Skip to content

Commit a514a2e

Browse files
fix(web): chat view no longer renders twice per update
useAutoBalanceUpdateBanner built a new Atom.make on every render, and ChatView passed a fresh [] when the draft was not auto-balanced. Each ChatView render handed useAtomValue a new store with a new snapshot, so React scheduled a second ChatView render. Per-environment list atoms are now Atom.family instances keyed by the joined environment ids (state/environmentAtomList.ts), and ChatView passes a module-level empty list. The same in-render atom construction is removed from the other hooks and settings sections that had it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent efdaa4b commit a514a2e

17 files changed

Lines changed: 345 additions & 236 deletions

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,11 @@ import { vcsEnvironment } from "../state/vcs";
365365
import { sourceControlEnvironment } from "../state/sourceControl";
366366
import { useProjectClone } from "../state/projectClones";
367367
import { projectCloneDisplayName, projectCloneProgressSummary } from "@t3tools/contracts";
368-
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
368+
import {
369+
type EnvironmentPresentation,
370+
useEnvironments,
371+
usePrimaryEnvironment,
372+
} from "../state/environments";
369373
import {
370374
resolveThreadDetailRef,
371375
useEnvironmentSupportsServerBrowser,
@@ -564,6 +568,7 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
564568
// broadcast to all shell subscribers.
565569
const VISIT_DISPATCH_THROTTLE_MS = 10_000;
566570
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
571+
const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];
567572
function useDraftHeroLayoutTransition(
568573
isDraftHeroState: boolean,
569574
animationsActive: boolean,
@@ -2282,7 +2287,7 @@ export default function ChatView(props: ChatViewProps) {
22822287
const environment = environmentById.get(environmentId);
22832288
return environment ? [environment] : [];
22842289
})
2285-
: [];
2290+
: EMPTY_AUTO_UPDATE_ENVIRONMENTS;
22862291
const autoBalanceUpdateBanner = useAutoBalanceUpdateBanner(autoUpdateEnvironments);
22872292
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
22882293
const versionMismatchDismissKey =

‎apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
3-
import { Atom } from "effect/reactivity";
43
import { useState } from "react";
54

5+
import { environmentIdsKey } from "~/state/environmentAtomList";
66
import type { EnvironmentPresentation } from "~/state/environments";
7-
import { serverEnvironment } from "~/state/server";
7+
import { environmentUpdateStatesAtom } from "~/state/server";
88
import {
99
buildVersionMismatchDismissalKey,
1010
dismissServerUpdateFailure,
@@ -29,13 +29,15 @@ import { ComposerServerUpdateIcon } from "./ComposerServerUpdateStatus";
2929
export function useAutoBalanceUpdateBanner(
3030
environments: readonly EnvironmentPresentation[],
3131
): ComposerBannerStackItem | null {
32-
const statesAtom = Atom.make((get) =>
33-
environments.map((environment) => ({
34-
environment,
35-
state: get(serverEnvironment.updateStateAtom(environment.environmentId)),
36-
})),
32+
const updateStates = useAtomValue(
33+
environmentUpdateStatesAtom(
34+
environmentIdsKey(environments.map(({ environmentId }) => environmentId)),
35+
),
3736
);
38-
const states = useAtomValue(statesAtom);
37+
const states = environments.flatMap((environment, index) => {
38+
const state = updateStates[index];
39+
return state ? [{ environment, state }] : [];
40+
});
3941
const [dismissedNotices, setDismissedNotices] = useState<ReadonlySet<string | ServerUpdateState>>(
4042
() => new Set(),
4143
);

‎apps/web/src/components/diffs/useReviewFilePatches.ts‎

Lines changed: 49 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ export function useReviewFilePatches({
5252
scope,
5353
requested,
5454
});
55-
const queriedPatchesAtom = patchesAtom(queries, theme);
55+
const queriedPatchesAtom = reviewPatchesAtom(
56+
JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
57+
);
5658
const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
5759
useEffect(() => {
5860
const previous = previousPreview.current;
@@ -157,7 +159,7 @@ export function useReviewFilePatches({
157159
};
158160
}
159161

160-
// The refresh effect and the patches atom key on the identity of these queries.
162+
// The refresh effect keys on the identity of these queries.
161163
function reviewFileQueries({
162164
environmentId,
163165
cwd,
@@ -184,25 +186,23 @@ function reviewFileQueries({
184186
.filter((index) => index < files.length)
185187
.map((index) => {
186188
const file = files[index]!;
187-
return {
188-
index,
189-
query: reviewEnvironment.diffFilePatch({
190-
environmentId,
191-
input: {
192-
cacheKey: scope,
193-
request: {
194-
cwd,
195-
...(baseRef ? { baseRef } : {}),
196-
ignoreWhitespace,
197-
file: {
198-
path: file.path,
199-
previousPath: file.previousPath,
200-
sourceKind: source.kind,
201-
},
189+
const target: ReviewPatchTarget = {
190+
environmentId,
191+
input: {
192+
cacheKey: scope,
193+
request: {
194+
cwd,
195+
...(baseRef ? { baseRef } : {}),
196+
ignoreWhitespace,
197+
file: {
198+
path: file.path,
199+
previousPath: file.previousPath,
200+
sourceKind: source.kind,
202201
},
203202
},
204-
}),
203+
},
205204
};
205+
return { index, target, query: reviewEnvironment.diffFilePatch(target) };
206206
});
207207
return queries;
208208
}
@@ -211,32 +211,36 @@ function sortedReviewFiles(source: ReviewDiffPreviewSource | null) {
211211
return source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? [];
212212
}
213213

214-
function patchesAtom(
215-
queries: ReadonlyArray<{
216-
index: number;
217-
query: ReturnType<typeof reviewEnvironment.diffFilePatch>;
218-
}>,
219-
theme: "light" | "dark",
220-
) {
221-
// Derived atoms parse each query result once, even when another file finishes loading.
222-
const parsedQuery = Atom.family((query: ReturnType<typeof reviewEnvironment.diffFilePatch>) =>
223-
Atom.map(query, (result) =>
224-
AsyncResult.map(result, (source) => {
225-
let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, {
226-
compactPartialHunkOffsets: true,
227-
});
228-
if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) {
229-
const stat = source.files[0]!;
230-
const file = { ...patch.files[0]!, name: stat.path };
231-
if (stat.previousPath !== null) file.prevName = stat.previousPath;
232-
else delete file.prevName;
233-
patch = { ...patch, files: [file] };
234-
}
235-
return { source, patch };
236-
}),
237-
),
214+
type ReviewPatchTarget = Parameters<typeof reviewEnvironment.diffFilePatch>[0];
215+
216+
// Derived atoms parse each query result once, even when another file finishes loading.
217+
const parsedPatchAtom = Atom.family((key: string) => {
218+
const [theme, target] = JSON.parse(key) as ["light" | "dark", ReviewPatchTarget];
219+
return Atom.map(reviewEnvironment.diffFilePatch(target), (result) =>
220+
AsyncResult.map(result, (source) => {
221+
let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, {
222+
compactPartialHunkOffsets: true,
223+
});
224+
if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) {
225+
const stat = source.files[0]!;
226+
const file = { ...patch.files[0]!, name: stat.path };
227+
if (stat.previousPath !== null) file.prevName = stat.previousPath;
228+
else delete file.prevName;
229+
patch = { ...patch, files: [file] };
230+
}
231+
return { source, patch };
232+
}),
238233
);
239-
return Atom.make(
240-
(get) => new Map(queries.map(({ index, query }) => [index, get(parsedQuery(query))])),
234+
});
235+
236+
// Keyed by theme and query targets so every render with the same files reads the same atom.
237+
const reviewPatchesAtom = Atom.family((key: string) => {
238+
const [theme, entries] = JSON.parse(key) as [
239+
"light" | "dark",
240+
ReadonlyArray<readonly [number, ReviewPatchTarget]>,
241+
];
242+
const parsed = entries.map(
243+
([index, target]) => [index, parsedPatchAtom(JSON.stringify([theme, target]))] as const,
241244
);
242-
}
245+
return Atom.make((get) => new Map(parsed.map(([index, atom]) => [index, get(atom)])));
246+
});

‎apps/web/src/components/settings/ConnectionsSettings.tsx‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
TerminalIcon,
1111
} from "lucide-react";
1212
import { useAtomValue } from "@effect/atom-react";
13-
import { Atom } from "effect/reactivity";
1413
import {
1514
type KeyboardEvent,
1615
type ReactNode,
@@ -185,7 +184,12 @@ import {
185184
import { APP_VERSION } from "~/branding";
186185
import { requestConfirmDialog } from "~/confirmDialog";
187186
import { useAtomCommand } from "../../state/use-atom-command";
188-
import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
187+
import { environmentIdsKey } from "~/state/environmentAtomList";
188+
import {
189+
environmentUpdateStatesAtom,
190+
primaryServerKeybindingsAtom,
191+
serverEnvironment,
192+
} from "~/state/server";
189193
import { ConnectionStatusDot } from "../ConnectionStatusDot";
190194
import {
191195
OutdatedServerUpdateAction,
@@ -2025,13 +2029,15 @@ export function ConnectionsSettings() {
20252029
const listedEnvironments = savedEnvironments.filter(
20262030
(environment) => !isDesktopLocalConnectionTarget(environment.entry.target),
20272031
);
2028-
const savedServerUpdateStatesAtom = Atom.make((get) =>
2029-
savedEnvironments.map((environment) => ({
2030-
environment,
2031-
updateStatus: get(serverEnvironment.updateStateAtom(environment.environmentId)).status,
2032-
})),
2032+
const savedUpdateStates = useAtomValue(
2033+
environmentUpdateStatesAtom(
2034+
environmentIdsKey(savedEnvironments.map(({ environmentId }) => environmentId)),
2035+
),
20332036
);
2034-
const savedServerUpdateStates = useAtomValue(savedServerUpdateStatesAtom);
2037+
const savedServerUpdateStates = savedEnvironments.map((environment, index) => ({
2038+
environment,
2039+
updateStatus: savedUpdateStates[index]!.status,
2040+
}));
20352041
const savedServerUpdateTargets = savedServerUpdateStates.flatMap(
20362042
({ environment, updateStatus }): ServerUpdateTarget[] => {
20372043
const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig);

‎apps/web/src/components/settings/DeviceHostsSettings.tsx‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { DeviceToolVersions } from "../device/DeviceToolVersions";
22
import { DeviceHostAvailability } from "../device/DeviceHostAvailability";
33
import { useAtomValue } from "@effect/atom-react";
44
import * as Option from "effect/Option";
5-
import { AsyncResult, Atom } from "effect/reactivity";
5+
import { AsyncResult } from "effect/reactivity";
66
import { AuthSettingsWriteScope } from "@t3tools/contracts";
77
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
88
import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
@@ -12,6 +12,7 @@ import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";
1212
import { randomUUID } from "../../lib/utils";
1313
import { useState } from "react";
1414
import { deviceEnvironment } from "../../state/device";
15+
import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
1516
import { serverEnvironment } from "../../state/server";
1617
import { useAtomCommand } from "../../state/use-atom-command";
1718
import { Button, InlineButton } from "../ui/button";
@@ -212,6 +213,10 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null
212213
);
213214
}
214215

216+
const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
217+
deviceEnvironment.state({ environmentId, input: {} }),
218+
);
219+
215220
function DeviceHostList({
216221
environments,
217222
groups,
@@ -238,15 +243,12 @@ function DeviceHostList({
238243
settingsScopeEnvironmentLabels(environment, scopeEnvironments),
239244
]),
240245
);
241-
const states = useAtomValue(
242-
Atom.make(
243-
(get) =>
244-
new Map(
245-
environments.map(({ environmentId }) => {
246-
const result = get(deviceEnvironment.state({ environmentId, input: {} }));
247-
return [environmentId, Option.getOrUndefined(AsyncResult.value(result))] as const;
248-
}),
249-
),
246+
const environmentIds = environments.map(({ environmentId }) => environmentId);
247+
const results = useAtomValue(deviceHostStatesAtom(environmentIdsKey(environmentIds)));
248+
const states = new Map(
249+
environmentIds.map(
250+
(environmentId, index) =>
251+
[environmentId, Option.getOrUndefined(AsyncResult.value(results[index]!))] as const,
250252
),
251253
);
252254
const retry = useAtomCommand(deviceEnvironment.list);

‎apps/web/src/components/settings/ScheduledTasksSettings.tsx‎

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
33
import * as Option from "effect/Option";
4-
import { AsyncResult, Atom } from "effect/reactivity";
4+
import { AsyncResult } from "effect/reactivity";
55
import {
66
Clock3Icon,
77
CopyIcon,
@@ -57,6 +57,7 @@ import {
5757
type EnvironmentPresentation,
5858
} from "../../state/environments";
5959
import { useProjects } from "../../state/entities";
60+
import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
6061
import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
6162
import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
6263
import { useAtomCommand } from "../../state/use-atom-command";
@@ -329,6 +330,10 @@ export function ScheduledTasksSettings(target: {
329330
);
330331
}
331332

333+
const scheduledTasksListAtom = environmentAtomList("web-scheduled-tasks-list", (environmentId) =>
334+
serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
335+
);
336+
332337
function ScheduledTaskEnvironmentList({
333338
environmentId,
334339
taskId,
@@ -339,31 +344,25 @@ function ScheduledTaskEnvironmentList({
339344
readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void;
340345
}) {
341346
const { scope, environments } = useSettingsScope();
342-
const states = useAtomValue(
343-
Atom.make((get) =>
344-
environments.map((environment) => {
345-
const connected =
346-
environment.connection.phase === "connected" && environment.serverConfig !== null;
347-
const query = connected
348-
? get(
349-
serverEnvironment.scheduledTasksLive({
350-
environmentId: environment.environmentId,
351-
input: {},
352-
}),
353-
)
354-
: null;
355-
const data = query === null ? null : Option.getOrNull(AsyncResult.value(query));
356-
return {
357-
environment,
358-
connected,
359-
tasks: data?.tasks.filter((task) =>
360-
matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
361-
),
362-
error: query?._tag === "Failure" ? formatEnvironmentQueryError(query.cause) : null,
363-
};
364-
}),
365-
),
347+
const connectedIds = environments.flatMap((environment) =>
348+
environment.connection.phase === "connected" && environment.serverConfig !== null
349+
? [environment.environmentId]
350+
: [],
366351
);
352+
const queries = useAtomValue(scheduledTasksListAtom(environmentIdsKey(connectedIds)));
353+
const states = environments.map((environment) => {
354+
const index = connectedIds.indexOf(environment.environmentId);
355+
const query = index < 0 ? null : queries[index]!;
356+
const data = query === null ? null : Option.getOrNull(AsyncResult.value(query));
357+
return {
358+
environment,
359+
connected: index >= 0,
360+
tasks: data?.tasks.filter((task) =>
361+
matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
362+
),
363+
error: query?._tag === "Failure" ? formatEnvironmentQueryError(query.cause) : null,
364+
};
365+
});
367366
const linkedState = states.find((state) => state.environment.environmentId === environmentId);
368367
const linkedTask = linkedState?.tasks?.find((task) => task.id === taskId);
369368
const openedLink = useRef(false);

0 commit comments

Comments
 (0)