@devries-cameron20 / t3code Mirror · read-only / commits / 52d593c1a1
Fork 0

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

fix(web): chat view no longer renders twice per update (#20847)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 17, 2026 at 03:35 UTC 52d593c1a1f33171f6d846e2cf9711fc8188272c
17 files changed +345 -236
apps/web/src/components/ChatView.tsx
+7 -2
@@ -365,7 +365,11 @@ import { vcsEnvironment } from "../state/vcs";
365 import { sourceControlEnvironment } from "../state/sourceControl";
366 import { useProjectClone } from "../state/projectClones";
367 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";
373 import {
374 resolveThreadDetailRef,
375 useEnvironmentSupportsServerBrowser,
@@ -564,6 +568,7 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
568 // broadcast to all shell subscribers.
569 const VISIT_DISPATCH_THROTTLE_MS = 10_000;
570 const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
571 +const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];
572 function useDraftHeroLayoutTransition(
573 isDraftHeroState: boolean,
574 animationsActive: boolean,
@@ -2282,7 +2287,7 @@ export default function ChatView(props: ChatViewProps) {
2287 const environment = environmentById.get(environmentId);
2288 return environment ? [environment] : [];
2289 })
2285 - : [];
2290 + : EMPTY_AUTO_UPDATE_ENVIRONMENTS;
2291 const autoBalanceUpdateBanner = useAutoBalanceUpdateBanner(autoUpdateEnvironments);
2292 const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
2293 const versionMismatchDismissKey =
apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx
+10 -8
@@ -1,10 +1,10 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
3 -import { Atom } from "effect/reactivity";
3 import { useState } from "react";
4
5 +import { environmentIdsKey } from "~/state/environmentAtomList";
6 import type { EnvironmentPresentation } from "~/state/environments";
7 -import { serverEnvironment } from "~/state/server";
7 +import { environmentUpdateStatesAtom } from "~/state/server";
8 import {
9 buildVersionMismatchDismissalKey,
10 dismissServerUpdateFailure,
@@ -29,13 +29,15 @@ import { ComposerServerUpdateIcon } from "./ComposerServerUpdateStatus";
29 export function useAutoBalanceUpdateBanner(
30 environments: readonly EnvironmentPresentation[],
31 ): 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 + ),
36 );
38 - const states = useAtomValue(statesAtom);
37 + const states = environments.flatMap((environment, index) => {
38 + const state = updateStates[index];
39 + return state ? [{ environment, state }] : [];
40 + });
41 const [dismissedNotices, setDismissedNotices] = useState<ReadonlySet<string | ServerUpdateState>>(
42 () => new Set(),
43 );
apps/web/src/components/diffs/useReviewFilePatches.ts
+49 -45
@@ -52,7 +52,9 @@ export function useReviewFilePatches({
52 scope,
53 requested,
54 });
55 - const queriedPatchesAtom = patchesAtom(queries, theme);
55 + const queriedPatchesAtom = reviewPatchesAtom(
56 + JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
57 + );
58 const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
59 useEffect(() => {
60 const previous = previousPreview.current;
@@ -157,7 +159,7 @@ export function useReviewFilePatches({
159 };
160 }
161
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.
163 function reviewFileQueries({
164 environmentId,
165 cwd,
@@ -184,25 +186,23 @@ function reviewFileQueries({
186 .filter((index) => index < files.length)
187 .map((index) => {
188 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,
201 },
202 },
204 - }),
203 + },
204 };
205 + return { index, target, query: reviewEnvironment.diffFilePatch(target) };
206 });
207 return queries;
208 }
@@ -211,32 +211,36 @@ function sortedReviewFiles(source: ReviewDiffPreviewSource | null) {
211 return source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? [];
212 }
213
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 + }),
233 );
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,
244 );
242 -}
245 + return Atom.make((get) => new Map(parsed.map(([index, atom]) => [index, get(atom)])));
246 +});
apps/web/src/components/settings/ConnectionsSettings.tsx
+14 -8
@@ -10,7 +10,6 @@ import {
10 TerminalIcon,
11 } from "lucide-react";
12 import { useAtomValue } from "@effect/atom-react";
13 -import { Atom } from "effect/reactivity";
13 import {
14 type KeyboardEvent,
15 type ReactNode,
@@ -185,7 +184,12 @@ import {
184 import { APP_VERSION } from "~/branding";
185 import { requestConfirmDialog } from "~/confirmDialog";
186 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";
193 import { ConnectionStatusDot } from "../ConnectionStatusDot";
194 import {
195 OutdatedServerUpdateAction,
@@ -2025,13 +2029,15 @@ export function ConnectionsSettings() {
2029 const listedEnvironments = savedEnvironments.filter(
2030 (environment) => !isDesktopLocalConnectionTarget(environment.entry.target),
2031 );
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 + ),
2036 );
2034 - const savedServerUpdateStates = useAtomValue(savedServerUpdateStatesAtom);
2037 + const savedServerUpdateStates = savedEnvironments.map((environment, index) => ({
2038 + environment,
2039 + updateStatus: savedUpdateStates[index]!.status,
2040 + }));
2041 const savedServerUpdateTargets = savedServerUpdateStates.flatMap(
2042 ({ environment, updateStatus }): ServerUpdateTarget[] => {
2043 const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
apps/web/src/components/settings/DeviceHostsSettings.tsx
+12 -10
@@ -2,7 +2,7 @@ import { DeviceToolVersions } from "../device/DeviceToolVersions";
2 import { DeviceHostAvailability } from "../device/DeviceHostAvailability";
3 import { useAtomValue } from "@effect/atom-react";
4 import * as Option from "effect/Option";
5 -import { AsyncResult, Atom } from "effect/reactivity";
5 +import { AsyncResult } from "effect/reactivity";
6 import { AuthSettingsWriteScope } from "@t3tools/contracts";
7 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
8 import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
@@ -12,6 +12,7 @@ import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";
12 import { randomUUID } from "../../lib/utils";
13 import { useState } from "react";
14 import { deviceEnvironment } from "../../state/device";
15 +import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
16 import { serverEnvironment } from "../../state/server";
17 import { useAtomCommand } from "../../state/use-atom-command";
18 import { Button, InlineButton } from "../ui/button";
@@ -212,6 +213,10 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null
213 );
214 }
215
216 +const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
217 + deviceEnvironment.state({ environmentId, input: {} }),
218 +);
219 +
220 function DeviceHostList({
221 environments,
222 groups,
@@ -238,15 +243,12 @@ function DeviceHostList({
243 settingsScopeEnvironmentLabels(environment, scopeEnvironments),
244 ]),
245 );
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,
252 ),
253 );
254 const retry = useAtomCommand(deviceEnvironment.list);
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+24 -25
@@ -1,7 +1,7 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
3 import * as Option from "effect/Option";
4 -import { AsyncResult, Atom } from "effect/reactivity";
4 +import { AsyncResult } from "effect/reactivity";
5 import {
6 Clock3Icon,
7 CopyIcon,
@@ -57,6 +57,7 @@ import {
57 type EnvironmentPresentation,
58 } from "../../state/environments";
59 import { useProjects } from "../../state/entities";
60 +import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
61 import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
62 import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
63 import { useAtomCommand } from "../../state/use-atom-command";
@@ -329,6 +330,10 @@ export function ScheduledTasksSettings(target: {
330 );
331 }
332
333 +const scheduledTasksListAtom = environmentAtomList("web-scheduled-tasks-list", (environmentId) =>
334 + serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
335 +);
336 +
337 function ScheduledTaskEnvironmentList({
338 environmentId,
339 taskId,
@@ -339,31 +344,25 @@ function ScheduledTaskEnvironmentList({
344 readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void;
345 }) {
346 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 + : [],
351 );
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 + });
366 const linkedState = states.find((state) => state.environment.environmentId === environmentId);
367 const linkedTask = linkedState?.tasks?.find((task) => task.id === taskId);
368 const openedLink = useRef(false);
apps/web/src/components/settings/SettingsScopeContext.tsx
+37 -17
@@ -1,4 +1,4 @@
1 -import { T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
1 +import { type EnvironmentId, T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
2 import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
3 import { useAtomValue } from "@effect/atom-react";
4 import * as Option from "effect/Option";
@@ -12,26 +12,46 @@ import { resolveScopedSettingsTargets, selectScopedSettingsEnvironments } from "
12 import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
13 import { selectSingleEnvironmentScope } from "./settingsScopeAxis";
14
15 +type ProjectFileMember = readonly [
16 + environmentId: EnvironmentId,
17 + workspaceRoot: string,
18 + physicalProjectKey: string,
19 +];
20 +
21 +// Keyed by the members' identifying fields so each render reads the same atom.
22 +const memberProjectFilesAtom = Atom.family((membersKey: string) => {
23 + const members = JSON.parse(membersKey) as ReadonlyArray<ProjectFileMember>;
24 + return Atom.make((get) => {
25 + const files = new Map<string, T3ProjectFile | null>();
26 + for (const [environmentId, workspaceRoot, physicalProjectKey] of members) {
27 + const result = get(
28 + getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME),
29 + );
30 + if (result.waiting) continue;
31 + const data =
32 + get(optimisticFileAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME))?.data ??
33 + Option.getOrNull(AsyncResult.value(result));
34 + files.set(
35 + physicalProjectKey,
36 + data === null || data.truncated ? null : parseT3ProjectFile(data.contents),
37 + );
38 + }
39 + return files;
40 + }).pipe(Atom.withLabel(`web-settings-member-project-files:${membersKey}`));
41 +});
42 +
43 function useMemberProjectFiles(scope: ReturnType<typeof resolveSettingsScope>) {
44 const members = scope.kind === "project" || scope.kind === "checkout" ? scope.members : [];
45 return useAtomValue(
18 - Atom.make((get) => {
19 - const files = new Map<string, T3ProjectFile | null>();
20 - for (const member of members) {
21 - const result = get(
22 - getProjectFileQueryAtom(member.environmentId, member.workspaceRoot, T3_PROJECT_FILE_NAME),
23 - );
24 - if (result.waiting) continue;
25 - const data =
26 - get(optimisticFileAtom(member.environmentId, member.workspaceRoot, T3_PROJECT_FILE_NAME))
27 - ?.data ?? Option.getOrNull(AsyncResult.value(result));
28 - files.set(
46 + memberProjectFilesAtom(
47 + JSON.stringify(
48 + members.map((member): ProjectFileMember => [
49 + member.environmentId,
50 + member.workspaceRoot,
51 member.physicalProjectKey,
30 - data === null || data.truncated ? null : parseT3ProjectFile(data.contents),
31 - );
32 - }
33 - return files;
34 - }),
52 + ]),
53 + ),
54 + ),
55 );
56 }
57
apps/web/src/components/settings/StorageSettings.tsx
+23 -26
@@ -6,12 +6,12 @@ import type {
6 import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
7 import { useRef, useState } from "react";
8 import { useAtomValue } from "@effect/atom-react";
9 -import { Atom } from "effect/reactivity";
9 import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12 } from "@t3tools/client-runtime/state/runtime";
13 import { formatBytes } from "../../lib/formatBytes";
14 +import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
15 import { serverEnvironment } from "../../state/server";
16 import { useAtomCommand } from "../../state/use-atom-command";
17 import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -250,6 +250,15 @@ function CleanupResults({
250 );
251 }
252
253 +const storageCleanupReportsAtom = environmentAtomList(
254 + "web-storage-cleanup-reports",
255 + (environmentId) => serverEnvironment.storageCleanupReport({ environmentId, input: {} }),
256 +);
257 +const storageCleanupPermissionsAtom = environmentAtomList(
258 + "web-storage-cleanup-permissions",
259 + serverEnvironment.runStorageCleanup.permissionAtom,
260 +);
261 +
262 function CleanupSection() {
263 useRelativeTimeTick(60_000);
264 const { connectedEnvironments } = useSettingsScope();
@@ -258,31 +267,19 @@ function CleanupSection() {
267 const supported = connectedEnvironments.filter(
268 (environment) => environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
269 );
261 - const state = useAtomValue(
262 - Atom.make((get) =>
263 - connectedEnvironments.flatMap((environment) => {
264 - if (environment.serverConfig?.environment.capabilities.storageCleanupRun !== true)
265 - return [];
266 - const query = get(
267 - serverEnvironment.storageCleanupReport({
268 - environmentId: environment.environmentId,
269 - input: {},
270 - }),
271 - );
272 - return [
273 - {
274 - environmentId: environment.environmentId,
275 - allowed: get(
276 - serverEnvironment.runStorageCleanup.permissionAtom(environment.environmentId),
277 - ),
278 - report: query._tag === "Success" ? query.value : null,
279 - loading: query.waiting,
280 - failed: query._tag === "Failure",
281 - },
282 - ];
283 - }),
284 - ),
285 - );
270 + const supportedIds = supported.map(({ environmentId }) => environmentId);
271 + const reports = useAtomValue(storageCleanupReportsAtom(environmentIdsKey(supportedIds)));
272 + const permissions = useAtomValue(storageCleanupPermissionsAtom(environmentIdsKey(supportedIds)));
273 + const state = supportedIds.map((environmentId, index) => {
274 + const query = reports[index]!;
275 + return {
276 + environmentId,
277 + allowed: permissions[index]!,
278 + report: query._tag === "Success" ? query.value : null,
279 + loading: query.waiting,
280 + failed: query._tag === "Failure",
281 + };
282 + });
283 const hasRules = supported.some((environment) => {
284 const settings = environment.serverConfig?.settings;
285 if (!settings) return false;
apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx
+10 -12
@@ -1,9 +1,9 @@
1 import { useAtomValue } from "@effect/atom-react";
2 -import { Atom } from "effect/reactivity";
2 import { type ReactNode, useSyncExternalStore } from "react";
3
4 import { cn } from "~/lib/utils";
6 -import { serverEnvironment } from "~/state/server";
5 +import { environmentIdsKey } from "~/state/environmentAtomList";
6 +import { environmentUpdateStatesAtom } from "~/state/server";
7 import { useServerUpdate } from "../ServerUpdateAction";
8 import { Button } from "../ui/button";
9 import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
@@ -33,17 +33,15 @@ function useNow(intervalMs: number | null): number {
33 }
34
35 function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray<UpdateRunMachineView> {
36 - const viewsAtom = Atom.make((get) =>
37 - run.machines.map((machine) => ({
38 - machine,
39 - status: resolveUpdateRunMachineStatus(
40 - machine,
41 - run.phase,
42 - get(serverEnvironment.updateStateAtom(machine.environmentId)),
43 - ),
44 - })),
36 + const updateStates = useAtomValue(
37 + environmentUpdateStatesAtom(
38 + environmentIdsKey(run.machines.map(({ environmentId }) => environmentId)),
39 + ),
40 );
46 - return useAtomValue(viewsAtom);
41 + return run.machines.map((machine, index) => ({
42 + machine,
43 + status: resolveUpdateRunMachineStatus(machine, run.phase, updateStates[index]!),
44 + }));
45 }
46
47 function localStatusLabel(run: UpdateEverythingRun, local: UpdateRunLocalState, now: number) {
apps/web/src/components/sidebar/useUpdateEverything.ts
+18 -20
@@ -1,14 +1,14 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
3 -import { Atom } from "effect/reactivity";
3
4 import { APP_VERSION } from "~/branding";
5 import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
6 import { isElectron } from "~/env";
7 import { useEnvironments } from "~/state/environments";
8 import { useNpmReleasePublished } from "~/state/npmRelease";
10 -import { serverEnvironment } from "~/state/server";
11 -import { environmentSession } from "~/state/session";
9 +import { environmentIdsKey } from "~/state/environmentAtomList";
10 +import { environmentUpdateStatesAtom } from "~/state/server";
11 +import { environmentSessionStatesAtom } from "~/state/session";
12 import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
13 import { useProviderUpdates } from "../ProviderUpdatesAction";
14 import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
@@ -39,23 +39,21 @@ export type ReportLocalUpdateError = (title: string, description: string) => voi
39 export function useUpdateEverything(localUpdateVersion: string | null) {
40 const targetVersion = localUpdateVersion ?? APP_VERSION;
41 const { environments } = useEnvironments();
42 - const machinesAtom = Atom.make((get) =>
43 - environments.map((environment) => ({
44 - environmentId: environment.environmentId,
45 - label: environment.label,
46 - serverConfig: environment.serverConfig,
47 - connected: environment.connection.phase === "connected",
48 - hostedByThisApp:
49 - isElectron &&
50 - (environment.entry.target._tag === "PrimaryConnectionTarget" ||
51 - isDesktopLocalConnectionTarget(environment.entry.target)),
52 - canMaintain: canUpdateServer(
53 - get(environmentSession.sessionStateAtom(environment.environmentId)),
54 - ),
55 - updateState: get(serverEnvironment.updateStateAtom(environment.environmentId)),
56 - })),
57 - );
58 - const machines = useAtomValue(machinesAtom);
42 + const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
43 + const sessionStates = useAtomValue(environmentSessionStatesAtom(environmentIds));
44 + const updateStates = useAtomValue(environmentUpdateStatesAtom(environmentIds));
45 + const machines = environments.map((environment, index) => ({
46 + environmentId: environment.environmentId,
47 + label: environment.label,
48 + serverConfig: environment.serverConfig,
49 + connected: environment.connection.phase === "connected",
50 + hostedByThisApp:
51 + isElectron &&
52 + (environment.entry.target._tag === "PrimaryConnectionTarget" ||
53 + isDesktopLocalConnectionTarget(environment.entry.target)),
54 + canMaintain: canUpdateServer(sessionStates[index]!),
55 + updateState: updateStates[index]!,
56 + }));
57 const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
58 machines,
59 targetVersion,
apps/web/src/hooks/useSettings.ts
+23 -17
@@ -49,7 +49,13 @@ import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
49 import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
50 import { useAtomCommand } from "~/state/use-atom-command";
51 import { useTheme } from "./useTheme";
52 -import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
52 +import {
53 + environmentSession,
54 + environmentSessionStatesAtom,
55 + readEnvironmentScope,
56 + useEnvironmentScope,
57 +} from "~/state/session";
58 +import { environmentIdsKey } from "~/state/environmentAtomList";
59 import { appAtomRegistry } from "~/rpc/atomRegistry";
60
61 const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -542,22 +548,22 @@ export function usePrimarySettingsAvailable(): boolean {
548
549 function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
550 const { environments } = useEnvironments();
545 - const writableTargetsAtom = Atom.make((get) =>
546 - environments.filter(supportsSharedSettingsSync).flatMap((environment) => {
547 - const result = get(environmentSession.sessionStateAtom(environment.environmentId));
548 - // A cold grant must not drop a shared edit. The server authorizes the
549 - // write; mismatch suggestions still wait for a confirmed grant.
550 - if (includePending && result._tag === "Initial") {
551 - return [environment.environmentId];
552 - }
553 - const session =
554 - result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
555 - return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
556 - ? [environment.environmentId]
557 - : [];
558 - }),
559 - );
560 - return useAtomValue(writableTargetsAtom);
551 + const targetIds = environments
552 + .filter(supportsSharedSettingsSync)
553 + .map(({ environmentId }) => environmentId);
554 + const results = useAtomValue(environmentSessionStatesAtom(environmentIdsKey(targetIds)));
555 + return targetIds.flatMap((environmentId, index) => {
556 + const result = results[index]!;
557 + // A cold grant must not drop a shared edit. The server authorizes the
558 + // write; mismatch suggestions still wait for a confirmed grant.
559 + if (includePending && result._tag === "Initial") {
560 + return [environmentId];
561 + }
562 + const session = result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
563 + return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
564 + ? [environmentId]
565 + : [];
566 + });
567 }
568
569 function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
apps/web/src/onboarding/useProjectScans.ts
+16 -15
@@ -1,26 +1,27 @@
1 import { RegistryContext, useAtomValue } from "@effect/atom-react";
2 import type { EnvironmentId } from "@t3tools/contracts";
3 import * as Option from "effect/Option";
4 -import { AsyncResult, Atom } from "effect/reactivity";
4 +import { AsyncResult } from "effect/reactivity";
5 import { useContext } from "react";
6
7 import { agentSessionScan } from "../state/agentSessions";
8 +import { environmentAtomList, environmentIdsKey } from "../state/environmentAtomList";
9 import { formatEnvironmentQueryError } from "../state/query";
10
11 +const scanAtom = (environmentId: EnvironmentId) => agentSessionScan({ environmentId, input: {} });
12 +const projectScansAtom = environmentAtomList("web-project-scans", scanAtom);
13 +
14 export function useProjectScans(environmentIds: readonly EnvironmentId[]) {
15 const registry = useContext(RegistryContext);
12 - const scansAtom = Atom.make((get) =>
13 - environmentIds.map((environmentId) => {
14 - const atom = agentSessionScan({ environmentId, input: {} });
15 - const result = get(atom);
16 - return {
17 - environmentId,
18 - data: Option.getOrNull(AsyncResult.value(result)),
19 - error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
20 - isPending: result.waiting || result._tag === "Initial",
21 - refresh: () => registry.refresh(atom),
22 - };
23 - }),
24 - );
25 - return useAtomValue(scansAtom);
16 + const results = useAtomValue(projectScansAtom(environmentIdsKey(environmentIds)));
17 + return environmentIds.map((environmentId, index) => {
18 + const result = results[index]!;
19 + return {
20 + environmentId,
21 + data: Option.getOrNull(AsyncResult.value(result)),
22 + error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
23 + isPending: result.waiting || result._tag === "Initial",
24 + refresh: () => registry.refresh(scanAtom(environmentId)),
25 + };
26 + });
27 }
apps/web/src/state/environmentAtomList.test.ts new
+24
@@ -0,0 +1,24 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { Atom, AtomRegistry } from "effect/reactivity";
3 +import { describe, expect, it } from "vite-plus/test";
4 +
5 +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
6 +
7 +const counts = Atom.family((environmentId: EnvironmentId) => Atom.make(environmentId.length));
8 +const countsList = environmentAtomList("test-counts", counts);
9 +
10 +describe("environmentAtomList", () => {
11 + it("returns the same atom and snapshot for an equal id list", () => {
12 + const registry = AtomRegistry.make();
13 + const first = countsList(
14 + environmentIdsKey([EnvironmentId.make("a"), EnvironmentId.make("bb")]),
15 + );
16 + const second = countsList(
17 + environmentIdsKey([EnvironmentId.make("a"), EnvironmentId.make("bb")]),
18 + );
19 + expect(second).toBe(first);
20 + expect(registry.get(first)).toEqual([1, 2]);
21 + expect(registry.get(second)).toBe(registry.get(first));
22 + expect(registry.get(countsList(environmentIdsKey([])))).toEqual([]);
23 + });
24 +});
apps/web/src/state/environmentAtomList.ts new
+21
@@ -0,0 +1,21 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import { Atom } from "effect/reactivity";
3 +
4 +export const environmentIdsKey = (environmentIds: ReadonlyArray<EnvironmentId>) =>
5 + environmentIds.join("\n");
6 +
7 +/**
8 + * Reads one per-environment atom for a list of environments. The list is keyed by its ids, so
9 + * renders that rebuild an equal list read the same atom instead of a new one whose fresh
10 + * snapshot would schedule another render.
11 + */
12 +export function environmentAtomList<A>(
13 + label: string,
14 + atom: (environmentId: EnvironmentId) => Atom.Atom<A>,
15 +) {
16 + return Atom.family((key: string) =>
17 + Atom.make((get) =>
18 + key === "" ? [] : (key.split("\n") as EnvironmentId[]).map((id) => get(atom(id))),
19 + ).pipe(Atom.withLabel(`${label}:${key}`)),
20 + );
21 +}
apps/web/src/state/queries.ts
+31 -20
@@ -97,6 +97,32 @@ export function useThreadSearch(
97 };
98 }
99
100 +function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
101 + const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
102 + return vcsEnvironment.listRefs({
103 + environmentId,
104 + input: {
105 + cwd,
106 + ...(query.length > 0 ? { query } : {}),
107 + ...(cursor === undefined ? {} : { cursor }),
108 + limit: VCS_REF_LIST_LIMIT,
109 + },
110 + });
111 +}
112 +
113 +const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
114 + ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
115 +>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
116 +
117 +// Keyed by target and cursors so every render of the same pages reads the same atom.
118 +const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
119 + const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
120 + const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
121 + return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
122 + Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
123 + );
124 +});
125 +
126 export function usePaginatedBranches(target: VcsRefTarget) {
127 // Starts unkeyed: a key mismatch already resolves to the initial cursors, and seeding
128 // the key here would make every derivation below straddle this hook call.
@@ -112,24 +138,10 @@ export function usePaginatedBranches(target: VcsRefTarget) {
138 const targetKey =
139 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
140 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
115 - const pageAtoms =
116 - environmentId !== null && cwd !== null
117 - ? cursors.map((cursor) =>
118 - vcsEnvironment.listRefs({
119 - environmentId,
120 - input: {
121 - cwd,
122 - ...(query.length > 0 ? { query } : {}),
123 - ...(cursor === undefined ? {} : { cursor }),
124 - limit: VCS_REF_LIST_LIMIT,
125 - },
126 - }),
127 - )
128 - : [];
129 - const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
130 - Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`),
141 + const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
142 + const results = useAtomValue(
143 + pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
144 );
132 - const results = useAtomValue(pagesAtom);
145 const values = results.flatMap((result) => {
146 const value = Option.getOrNull(AsyncResult.value(result));
147 return value === null ? [] : [value];
@@ -164,10 +176,9 @@ export function usePaginatedBranches(target: VcsRefTarget) {
176 })()
177 : null;
178 const refresh = () => {
167 - const firstPage = pageAtoms[0];
179 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
169 - if (firstPage !== undefined) {
170 - appAtomRegistry.refresh(firstPage);
180 + if (targetKey !== null) {
181 + appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
182 }
183 };
184 const nextCursor = data?.nextCursor;
apps/web/src/state/server.ts
+5
@@ -18,6 +18,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
18
19 import { environmentCatalog } from "../connection/catalog";
20 import { connectionAtomRuntime } from "../connection/runtime";
21 +import { environmentAtomList } from "./environmentAtomList";
22 import { primaryEnvironmentIdAtom } from "./primaryEnvironment";
23 import { environmentSession } from "./session";
24
@@ -30,6 +31,10 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRunt
31 usageLimitSources: true,
32 usageLimitsCommand: true,
33 });
34 +export const environmentUpdateStatesAtom = environmentAtomList(
35 + "web-environment-update-states",
36 + serverEnvironment.updateStateAtom,
37 +);
38 export const updateOutdatedServer = createOutdatedServerUpdateCommand(connectionAtomRuntime);
39 export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
40 catalogValueAtom: environmentCatalog.catalogValueAtom,
apps/web/src/state/session.ts
+21 -11
@@ -11,8 +11,13 @@ import { AsyncResult, Atom } from "effect/reactivity";
11
12 import { connectionAtomRuntime } from "../connection/runtime";
13 import { appAtomRegistry } from "../rpc/atomRegistry";
14 +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
15
16 export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRuntime);
17 +export const environmentSessionStatesAtom = environmentAtomList(
18 + "web-environment-session-states",
19 + environmentSession.sessionStateAtom,
20 +);
21
22 const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
23
@@ -36,21 +41,26 @@ function sessionHasScope(
41 return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
42 }
43
44 +// Keyed by scope and ids so callers get one Set per session change, not one per render.
45 +const environmentsWithScopeAtom = Atom.family((key: string) => {
46 + const [scope, idsKey = ""] = key.split(/\n(.*)/s) as [AuthEnvironmentScope, string?];
47 + const ids = idsKey === "" ? [] : (idsKey.split("\n") as EnvironmentId[]);
48 + const statesAtom = environmentSessionStatesAtom(idsKey);
49 + return Atom.make((get) => {
50 + const states = get(statesAtom);
51 + return new Set(ids.filter((_, index) => sessionHasScope(states[index]!, scope)));
52 + }).pipe(Atom.withLabel(`web-environments-with-scope:${key}`));
53 +});
54 +
55 export function useEnvironmentsWithScope(
56 environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,
57 scope: AuthEnvironmentScope,
58 ): ReadonlySet<EnvironmentId> {
43 - const permitted = Atom.make((get) => {
44 - const ids = new Set<EnvironmentId>();
45 - for (const { environmentId } of environments) {
46 - const result = get(environmentSession.sessionStateAtom(environmentId));
47 - if (sessionHasScope(result, scope)) {
48 - ids.add(environmentId);
49 - }
50 - }
51 - return ids;
52 - });
53 - return useAtomValue(permitted);
59 + return useAtomValue(
60 + environmentsWithScopeAtom(
61 + `${scope}\n${environmentIdsKey(environments.map(({ environmentId }) => environmentId))}`,
62 + ),
63 + );
64 }
65
66 export function readEnvironmentScope(