Skip to content
TypeScript

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

Julius Marminge52d593c1a1f3
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 14f40d8d9ee..28b81cdd860 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -365,7 +365,11 @@ import { vcsEnvironment } from "../state/vcs";
import { sourceControlEnvironment } from "../state/sourceControl";
import { useProjectClone } from "../state/projectClones";
import { projectCloneDisplayName, projectCloneProgressSummary } from "@t3tools/contracts";
-import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
+import {
+ type EnvironmentPresentation,
+ useEnvironments,
+ usePrimaryEnvironment,
+} from "../state/environments";
import {
resolveThreadDetailRef,
useEnvironmentSupportsServerBrowser,
@@ -564,6 +568,7 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
// broadcast to all shell subscribers.
const VISIT_DISPATCH_THROTTLE_MS = 10_000;
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
+const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];
function useDraftHeroLayoutTransition(
isDraftHeroState: boolean,
animationsActive: boolean,
@@ -2282,7 +2287,7 @@ export default function ChatView(props: ChatViewProps) {
const environment = environmentById.get(environmentId);
return environment ? [environment] : [];
})
- : [];
+ : EMPTY_AUTO_UPDATE_ENVIRONMENTS;
const autoBalanceUpdateBanner = useAutoBalanceUpdateBanner(autoUpdateEnvironments);
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
const versionMismatchDismissKey =
diff --git a/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx b/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx
index 6d2930874c1..c0e376497da 100644
--- a/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx
+++ b/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx
@@ -1,10 +1,10 @@
import { useAtomValue } from "@effect/atom-react";
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
-import { Atom } from "effect/reactivity";
import { useState } from "react";
+import { environmentIdsKey } from "~/state/environmentAtomList";
import type { EnvironmentPresentation } from "~/state/environments";
-import { serverEnvironment } from "~/state/server";
+import { environmentUpdateStatesAtom } from "~/state/server";
import {
buildVersionMismatchDismissalKey,
dismissServerUpdateFailure,
@@ -29,13 +29,15 @@ import { ComposerServerUpdateIcon } from "./ComposerServerUpdateStatus";
export function useAutoBalanceUpdateBanner(
environments: readonly EnvironmentPresentation[],
): ComposerBannerStackItem | null {
- const statesAtom = Atom.make((get) =>
- environments.map((environment) => ({
- environment,
- state: get(serverEnvironment.updateStateAtom(environment.environmentId)),
- })),
+ const updateStates = useAtomValue(
+ environmentUpdateStatesAtom(
+ environmentIdsKey(environments.map(({ environmentId }) => environmentId)),
+ ),
);
- const states = useAtomValue(statesAtom);
+ const states = environments.flatMap((environment, index) => {
+ const state = updateStates[index];
+ return state ? [{ environment, state }] : [];
+ });
const [dismissedNotices, setDismissedNotices] = useState<ReadonlySet<string | ServerUpdateState>>(
() => new Set(),
);
diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts
index c252ccb8b34..bec85ea0d7f 100644
--- a/apps/web/src/components/diffs/useReviewFilePatches.ts
+++ b/apps/web/src/components/diffs/useReviewFilePatches.ts
@@ -52,7 +52,9 @@ export function useReviewFilePatches({
scope,
requested,
});
- const queriedPatchesAtom = patchesAtom(queries, theme);
+ const queriedPatchesAtom = reviewPatchesAtom(
+ JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
+ );
const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
useEffect(() => {
const previous = previousPreview.current;
@@ -157,7 +159,7 @@ export function useReviewFilePatches({
};
}
-// The refresh effect and the patches atom key on the identity of these queries.
+// The refresh effect keys on the identity of these queries.
function reviewFileQueries({
environmentId,
cwd,
@@ -184,25 +186,23 @@ function reviewFileQueries({
.filter((index) => index < files.length)
.map((index) => {
const file = files[index]!;
- return {
- index,
- query: reviewEnvironment.diffFilePatch({
- environmentId,
- input: {
- cacheKey: scope,
- request: {
- cwd,
- ...(baseRef ? { baseRef } : {}),
- ignoreWhitespace,
- file: {
- path: file.path,
- previousPath: file.previousPath,
- sourceKind: source.kind,
- },
+ const target: ReviewPatchTarget = {
+ environmentId,
+ input: {
+ cacheKey: scope,
+ request: {
+ cwd,
+ ...(baseRef ? { baseRef } : {}),
+ ignoreWhitespace,
+ file: {
+ path: file.path,
+ previousPath: file.previousPath,
+ sourceKind: source.kind,
},
},
- }),
+ },
};
+ return { index, target, query: reviewEnvironment.diffFilePatch(target) };
});
return queries;
}
@@ -211,32 +211,36 @@ function sortedReviewFiles(source: ReviewDiffPreviewSource | null) {
return source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? [];
}
-function patchesAtom(
- queries: ReadonlyArray<{
- index: number;
- query: ReturnType<typeof reviewEnvironment.diffFilePatch>;
- }>,
- theme: "light" | "dark",
-) {
- // Derived atoms parse each query result once, even when another file finishes loading.
- const parsedQuery = Atom.family((query: ReturnType<typeof reviewEnvironment.diffFilePatch>) =>
- Atom.map(query, (result) =>
- AsyncResult.map(result, (source) => {
- let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, {
- compactPartialHunkOffsets: true,
- });
- if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) {
- const stat = source.files[0]!;
- const file = { ...patch.files[0]!, name: stat.path };
- if (stat.previousPath !== null) file.prevName = stat.previousPath;
- else delete file.prevName;
- patch = { ...patch, files: [file] };
- }
- return { source, patch };
- }),
- ),
+type ReviewPatchTarget = Parameters<typeof reviewEnvironment.diffFilePatch>[0];
+
+// Derived atoms parse each query result once, even when another file finishes loading.
+const parsedPatchAtom = Atom.family((key: string) => {
+ const [theme, target] = JSON.parse(key) as ["light" | "dark", ReviewPatchTarget];
+ return Atom.map(reviewEnvironment.diffFilePatch(target), (result) =>
+ AsyncResult.map(result, (source) => {
+ let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, {
+ compactPartialHunkOffsets: true,
+ });
+ if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) {
+ const stat = source.files[0]!;
+ const file = { ...patch.files[0]!, name: stat.path };
+ if (stat.previousPath !== null) file.prevName = stat.previousPath;
+ else delete file.prevName;
+ patch = { ...patch, files: [file] };
+ }
+ return { source, patch };
+ }),
);
- return Atom.make(
- (get) => new Map(queries.map(({ index, query }) => [index, get(parsedQuery(query))])),
+});
+
+// Keyed by theme and query targets so every render with the same files reads the same atom.
+const reviewPatchesAtom = Atom.family((key: string) => {
+ const [theme, entries] = JSON.parse(key) as [
+ "light" | "dark",
+ ReadonlyArray<readonly [number, ReviewPatchTarget]>,
+ ];
+ const parsed = entries.map(
+ ([index, target]) => [index, parsedPatchAtom(JSON.stringify([theme, target]))] as const,
);
-}
+ return Atom.make((get) => new Map(parsed.map(([index, atom]) => [index, get(atom)])));
+});
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index bb7fa4ada23..2e46f8be05e 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -10,7 +10,6 @@ import {
TerminalIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
-import { Atom } from "effect/reactivity";
import {
type KeyboardEvent,
type ReactNode,
@@ -185,7 +184,12 @@ import {
import { APP_VERSION } from "~/branding";
import { requestConfirmDialog } from "~/confirmDialog";
import { useAtomCommand } from "../../state/use-atom-command";
-import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
+import { environmentIdsKey } from "~/state/environmentAtomList";
+import {
+ environmentUpdateStatesAtom,
+ primaryServerKeybindingsAtom,
+ serverEnvironment,
+} from "~/state/server";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import {
OutdatedServerUpdateAction,
@@ -2025,13 +2029,15 @@ export function ConnectionsSettings() {
const listedEnvironments = savedEnvironments.filter(
(environment) => !isDesktopLocalConnectionTarget(environment.entry.target),
);
- const savedServerUpdateStatesAtom = Atom.make((get) =>
- savedEnvironments.map((environment) => ({
- environment,
- updateStatus: get(serverEnvironment.updateStateAtom(environment.environmentId)).status,
- })),
+ const savedUpdateStates = useAtomValue(
+ environmentUpdateStatesAtom(
+ environmentIdsKey(savedEnvironments.map(({ environmentId }) => environmentId)),
+ ),
);
- const savedServerUpdateStates = useAtomValue(savedServerUpdateStatesAtom);
+ const savedServerUpdateStates = savedEnvironments.map((environment, index) => ({
+ environment,
+ updateStatus: savedUpdateStates[index]!.status,
+ }));
const savedServerUpdateTargets = savedServerUpdateStates.flatMap(
({ environment, updateStatus }): ServerUpdateTarget[] => {
const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
diff --git a/apps/web/src/components/settings/DeviceHostsSettings.tsx b/apps/web/src/components/settings/DeviceHostsSettings.tsx
index 5a337785e55..5b154634c95 100644
--- a/apps/web/src/components/settings/DeviceHostsSettings.tsx
+++ b/apps/web/src/components/settings/DeviceHostsSettings.tsx
@@ -2,7 +2,7 @@ import { DeviceToolVersions } from "../device/DeviceToolVersions";
import { DeviceHostAvailability } from "../device/DeviceHostAvailability";
import { useAtomValue } from "@effect/atom-react";
import * as Option from "effect/Option";
-import { AsyncResult, Atom } from "effect/reactivity";
+import { AsyncResult } from "effect/reactivity";
import { AuthSettingsWriteScope } from "@t3tools/contracts";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
@@ -12,6 +12,7 @@ import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";
import { randomUUID } from "../../lib/utils";
import { useState } from "react";
import { deviceEnvironment } from "../../state/device";
+import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { Button, InlineButton } from "../ui/button";
@@ -212,6 +213,10 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null
);
}
+const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
+ deviceEnvironment.state({ environmentId, input: {} }),
+);
+
function DeviceHostList({
environments,
groups,
@@ -238,15 +243,12 @@ function DeviceHostList({
settingsScopeEnvironmentLabels(environment, scopeEnvironments),
]),
);
- const states = useAtomValue(
- Atom.make(
- (get) =>
- new Map(
- environments.map(({ environmentId }) => {
- const result = get(deviceEnvironment.state({ environmentId, input: {} }));
- return [environmentId, Option.getOrUndefined(AsyncResult.value(result))] as const;
- }),
- ),
+ const environmentIds = environments.map(({ environmentId }) => environmentId);
+ const results = useAtomValue(deviceHostStatesAtom(environmentIdsKey(environmentIds)));
+ const states = new Map(
+ environmentIds.map(
+ (environmentId, index) =>
+ [environmentId, Option.getOrUndefined(AsyncResult.value(results[index]!))] as const,
),
);
const retry = useAtomCommand(deviceEnvironment.list);
diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
index 5fbc89ac8be..307b1879ff0 100644
--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx
+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
@@ -1,7 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
import * as Option from "effect/Option";
-import { AsyncResult, Atom } from "effect/reactivity";
+import { AsyncResult } from "effect/reactivity";
import {
Clock3Icon,
CopyIcon,
@@ -57,6 +57,7 @@ import {
type EnvironmentPresentation,
} from "../../state/environments";
import { useProjects } from "../../state/entities";
+import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -329,6 +330,10 @@ export function ScheduledTasksSettings(target: {
);
}
+const scheduledTasksListAtom = environmentAtomList("web-scheduled-tasks-list", (environmentId) =>
+ serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
+);
+
function ScheduledTaskEnvironmentList({
environmentId,
taskId,
@@ -339,31 +344,25 @@ function ScheduledTaskEnvironmentList({
readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void;
}) {
const { scope, environments } = useSettingsScope();
- const states = useAtomValue(
- Atom.make((get) =>
- environments.map((environment) => {
- const connected =
- environment.connection.phase === "connected" && environment.serverConfig !== null;
- const query = connected
- ? get(
- serverEnvironment.scheduledTasksLive({
- environmentId: environment.environmentId,
- input: {},
- }),
- )
- : null;
- const data = query === null ? null : Option.getOrNull(AsyncResult.value(query));
- return {
- environment,
- connected,
- tasks: data?.tasks.filter((task) =>
- matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
- ),
- error: query?._tag === "Failure" ? formatEnvironmentQueryError(query.cause) : null,
- };
- }),
- ),
+ const connectedIds = environments.flatMap((environment) =>
+ environment.connection.phase === "connected" && environment.serverConfig !== null
+ ? [environment.environmentId]
+ : [],
);
+ const queries = useAtomValue(scheduledTasksListAtom(environmentIdsKey(connectedIds)));
+ const states = environments.map((environment) => {
+ const index = connectedIds.indexOf(environment.environmentId);
+ const query = index < 0 ? null : queries[index]!;
+ const data = query === null ? null : Option.getOrNull(AsyncResult.value(query));
+ return {
+ environment,
+ connected: index >= 0,
+ tasks: data?.tasks.filter((task) =>
+ matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
+ ),
+ error: query?._tag === "Failure" ? formatEnvironmentQueryError(query.cause) : null,
+ };
+ });
const linkedState = states.find((state) => state.environment.environmentId === environmentId);
const linkedTask = linkedState?.tasks?.find((task) => task.id === taskId);
const openedLink = useRef(false);
diff --git a/apps/web/src/components/settings/SettingsScopeContext.tsx b/apps/web/src/components/settings/SettingsScopeContext.tsx
index af186f93b7b..d3200a34a39 100644
--- a/apps/web/src/components/settings/SettingsScopeContext.tsx
+++ b/apps/web/src/components/settings/SettingsScopeContext.tsx
@@ -1,4 +1,4 @@
-import { T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
+import { type EnvironmentId, T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import { useAtomValue } from "@effect/atom-react";
import * as Option from "effect/Option";
@@ -12,26 +12,46 @@ import { resolveScopedSettingsTargets, selectScopedSettingsEnvironments } from "
import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
import { selectSingleEnvironmentScope } from "./settingsScopeAxis";
+type ProjectFileMember = readonly [
+ environmentId: EnvironmentId,
+ workspaceRoot: string,
+ physicalProjectKey: string,
+];
+
+// Keyed by the members' identifying fields so each render reads the same atom.
+const memberProjectFilesAtom = Atom.family((membersKey: string) => {
+ const members = JSON.parse(membersKey) as ReadonlyArray<ProjectFileMember>;
+ return Atom.make((get) => {
+ const files = new Map<string, T3ProjectFile | null>();
+ for (const [environmentId, workspaceRoot, physicalProjectKey] of members) {
+ const result = get(
+ getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME),
+ );
+ if (result.waiting) continue;
+ const data =
+ get(optimisticFileAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME))?.data ??
+ Option.getOrNull(AsyncResult.value(result));
+ files.set(
+ physicalProjectKey,
+ data === null || data.truncated ? null : parseT3ProjectFile(data.contents),
+ );
+ }
+ return files;
+ }).pipe(Atom.withLabel(`web-settings-member-project-files:${membersKey}`));
+});
+
function useMemberProjectFiles(scope: ReturnType<typeof resolveSettingsScope>) {
const members = scope.kind === "project" || scope.kind === "checkout" ? scope.members : [];
return useAtomValue(
- Atom.make((get) => {
- const files = new Map<string, T3ProjectFile | null>();
- for (const member of members) {
- const result = get(
- getProjectFileQueryAtom(member.environmentId, member.workspaceRoot, T3_PROJECT_FILE_NAME),
- );
- if (result.waiting) continue;
- const data =
- get(optimisticFileAtom(member.environmentId, member.workspaceRoot, T3_PROJECT_FILE_NAME))
- ?.data ?? Option.getOrNull(AsyncResult.value(result));
- files.set(
+ memberProjectFilesAtom(
+ JSON.stringify(
+ members.map((member): ProjectFileMember => [
+ member.environmentId,
+ member.workspaceRoot,
member.physicalProjectKey,
- data === null || data.truncated ? null : parseT3ProjectFile(data.contents),
- );
- }
- return files;
- }),
+ ]),
+ ),
+ ),
);
}
diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsx
index fa1783a56c5..69dc98c1f4d 100644
--- a/apps/web/src/components/settings/StorageSettings.tsx
+++ b/apps/web/src/components/settings/StorageSettings.tsx
@@ -6,12 +6,12 @@ import type {
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
import { useRef, useState } from "react";
import { useAtomValue } from "@effect/atom-react";
-import { Atom } from "effect/reactivity";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { formatBytes } from "../../lib/formatBytes";
+import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -250,6 +250,15 @@ function CleanupResults({
);
}
+const storageCleanupReportsAtom = environmentAtomList(
+ "web-storage-cleanup-reports",
+ (environmentId) => serverEnvironment.storageCleanupReport({ environmentId, input: {} }),
+);
+const storageCleanupPermissionsAtom = environmentAtomList(
+ "web-storage-cleanup-permissions",
+ serverEnvironment.runStorageCleanup.permissionAtom,
+);
+
function CleanupSection() {
useRelativeTimeTick(60_000);
const { connectedEnvironments } = useSettingsScope();
@@ -258,31 +267,19 @@ function CleanupSection() {
const supported = connectedEnvironments.filter(
(environment) => environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
);
- const state = useAtomValue(
- Atom.make((get) =>
- connectedEnvironments.flatMap((environment) => {
- if (environment.serverConfig?.environment.capabilities.storageCleanupRun !== true)
- return [];
- const query = get(
- serverEnvironment.storageCleanupReport({
- environmentId: environment.environmentId,
- input: {},
- }),
- );
- return [
- {
- environmentId: environment.environmentId,
- allowed: get(
- serverEnvironment.runStorageCleanup.permissionAtom(environment.environmentId),
- ),
- report: query._tag === "Success" ? query.value : null,
- loading: query.waiting,
- failed: query._tag === "Failure",
- },
- ];
- }),
- ),
- );
+ const supportedIds = supported.map(({ environmentId }) => environmentId);
+ const reports = useAtomValue(storageCleanupReportsAtom(environmentIdsKey(supportedIds)));
+ const permissions = useAtomValue(storageCleanupPermissionsAtom(environmentIdsKey(supportedIds)));
+ const state = supportedIds.map((environmentId, index) => {
+ const query = reports[index]!;
+ return {
+ environmentId,
+ allowed: permissions[index]!,
+ report: query._tag === "Success" ? query.value : null,
+ loading: query.waiting,
+ failed: query._tag === "Failure",
+ };
+ });
const hasRules = supported.some((environment) => {
const settings = environment.serverConfig?.settings;
if (!settings) return false;
diff --git a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx
index 0d83c8b3d73..57e649ba011 100644
--- a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx
+++ b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx
@@ -1,9 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
-import { Atom } from "effect/reactivity";
import { type ReactNode, useSyncExternalStore } from "react";
import { cn } from "~/lib/utils";
-import { serverEnvironment } from "~/state/server";
+import { environmentIdsKey } from "~/state/environmentAtomList";
+import { environmentUpdateStatesAtom } from "~/state/server";
import { useServerUpdate } from "../ServerUpdateAction";
import { Button } from "../ui/button";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
@@ -33,17 +33,15 @@ function useNow(intervalMs: number | null): number {
}
function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray<UpdateRunMachineView> {
- const viewsAtom = Atom.make((get) =>
- run.machines.map((machine) => ({
- machine,
- status: resolveUpdateRunMachineStatus(
- machine,
- run.phase,
- get(serverEnvironment.updateStateAtom(machine.environmentId)),
- ),
- })),
+ const updateStates = useAtomValue(
+ environmentUpdateStatesAtom(
+ environmentIdsKey(run.machines.map(({ environmentId }) => environmentId)),
+ ),
);
- return useAtomValue(viewsAtom);
+ return run.machines.map((machine, index) => ({
+ machine,
+ status: resolveUpdateRunMachineStatus(machine, run.phase, updateStates[index]!),
+ }));
}
function localStatusLabel(run: UpdateEverythingRun, local: UpdateRunLocalState, now: number) {
diff --git a/apps/web/src/components/sidebar/useUpdateEverything.ts b/apps/web/src/components/sidebar/useUpdateEverything.ts
index bac6e00270f..dc34e1ebdb2 100644
--- a/apps/web/src/components/sidebar/useUpdateEverything.ts
+++ b/apps/web/src/components/sidebar/useUpdateEverything.ts
@@ -1,14 +1,14 @@
import { useAtomValue } from "@effect/atom-react";
import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
-import { Atom } from "effect/reactivity";
import { APP_VERSION } from "~/branding";
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { isElectron } from "~/env";
import { useEnvironments } from "~/state/environments";
import { useNpmReleasePublished } from "~/state/npmRelease";
-import { serverEnvironment } from "~/state/server";
-import { environmentSession } from "~/state/session";
+import { environmentIdsKey } from "~/state/environmentAtomList";
+import { environmentUpdateStatesAtom } from "~/state/server";
+import { environmentSessionStatesAtom } from "~/state/session";
import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
import { useProviderUpdates } from "../ProviderUpdatesAction";
import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
@@ -39,23 +39,21 @@ export type ReportLocalUpdateError = (title: string, description: string) => voi
export function useUpdateEverything(localUpdateVersion: string | null) {
const targetVersion = localUpdateVersion ?? APP_VERSION;
const { environments } = useEnvironments();
- const machinesAtom = Atom.make((get) =>
- environments.map((environment) => ({
- environmentId: environment.environmentId,
- label: environment.label,
- serverConfig: environment.serverConfig,
- connected: environment.connection.phase === "connected",
- hostedByThisApp:
- isElectron &&
- (environment.entry.target._tag === "PrimaryConnectionTarget" ||
- isDesktopLocalConnectionTarget(environment.entry.target)),
- canMaintain: canUpdateServer(
- get(environmentSession.sessionStateAtom(environment.environmentId)),
- ),
- updateState: get(serverEnvironment.updateStateAtom(environment.environmentId)),
- })),
- );
- const machines = useAtomValue(machinesAtom);
+ const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
+ const sessionStates = useAtomValue(environmentSessionStatesAtom(environmentIds));
+ const updateStates = useAtomValue(environmentUpdateStatesAtom(environmentIds));
+ const machines = environments.map((environment, index) => ({
+ environmentId: environment.environmentId,
+ label: environment.label,
+ serverConfig: environment.serverConfig,
+ connected: environment.connection.phase === "connected",
+ hostedByThisApp:
+ isElectron &&
+ (environment.entry.target._tag === "PrimaryConnectionTarget" ||
+ isDesktopLocalConnectionTarget(environment.entry.target)),
+ canMaintain: canUpdateServer(sessionStates[index]!),
+ updateState: updateStates[index]!,
+ }));
const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
machines,
targetVersion,
diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts
index 1b760ce2d73..01291ca53da 100644
--- a/apps/web/src/hooks/useSettings.ts
+++ b/apps/web/src/hooks/useSettings.ts
@@ -49,7 +49,13 @@ import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { useTheme } from "./useTheme";
-import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
+import {
+ environmentSession,
+ environmentSessionStatesAtom,
+ readEnvironmentScope,
+ useEnvironmentScope,
+} from "~/state/session";
+import { environmentIdsKey } from "~/state/environmentAtomList";
import { appAtomRegistry } from "~/rpc/atomRegistry";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -542,22 +548,22 @@ export function usePrimarySettingsAvailable(): boolean {
function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
const { environments } = useEnvironments();
- const writableTargetsAtom = Atom.make((get) =>
- environments.filter(supportsSharedSettingsSync).flatMap((environment) => {
- const result = get(environmentSession.sessionStateAtom(environment.environmentId));
- // A cold grant must not drop a shared edit. The server authorizes the
- // write; mismatch suggestions still wait for a confirmed grant.
- if (includePending && result._tag === "Initial") {
- return [environment.environmentId];
- }
- const session =
- result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
- return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
- ? [environment.environmentId]
- : [];
- }),
- );
- return useAtomValue(writableTargetsAtom);
+ const targetIds = environments
+ .filter(supportsSharedSettingsSync)
+ .map(({ environmentId }) => environmentId);
+ const results = useAtomValue(environmentSessionStatesAtom(environmentIdsKey(targetIds)));
+ return targetIds.flatMap((environmentId, index) => {
+ const result = results[index]!;
+ // A cold grant must not drop a shared edit. The server authorizes the
+ // write; mismatch suggestions still wait for a confirmed grant.
+ if (includePending && result._tag === "Initial") {
+ return [environmentId];
+ }
+ const session = result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
+ return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
+ ? [environmentId]
+ : [];
+ });
}
function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
diff --git a/apps/web/src/onboarding/useProjectScans.ts b/apps/web/src/onboarding/useProjectScans.ts
index 912bacdc041..e345d77c117 100644
--- a/apps/web/src/onboarding/useProjectScans.ts
+++ b/apps/web/src/onboarding/useProjectScans.ts
@@ -1,26 +1,27 @@
import { RegistryContext, useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
-import { AsyncResult, Atom } from "effect/reactivity";
+import { AsyncResult } from "effect/reactivity";
import { useContext } from "react";
import { agentSessionScan } from "../state/agentSessions";
+import { environmentAtomList, environmentIdsKey } from "../state/environmentAtomList";
import { formatEnvironmentQueryError } from "../state/query";
+const scanAtom = (environmentId: EnvironmentId) => agentSessionScan({ environmentId, input: {} });
+const projectScansAtom = environmentAtomList("web-project-scans", scanAtom);
+
export function useProjectScans(environmentIds: readonly EnvironmentId[]) {
const registry = useContext(RegistryContext);
- const scansAtom = Atom.make((get) =>
- environmentIds.map((environmentId) => {
- const atom = agentSessionScan({ environmentId, input: {} });
- const result = get(atom);
- return {
- environmentId,
- data: Option.getOrNull(AsyncResult.value(result)),
- error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
- isPending: result.waiting || result._tag === "Initial",
- refresh: () => registry.refresh(atom),
- };
- }),
- );
- return useAtomValue(scansAtom);
+ const results = useAtomValue(projectScansAtom(environmentIdsKey(environmentIds)));
+ return environmentIds.map((environmentId, index) => {
+ const result = results[index]!;
+ return {
+ environmentId,
+ data: Option.getOrNull(AsyncResult.value(result)),
+ error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
+ isPending: result.waiting || result._tag === "Initial",
+ refresh: () => registry.refresh(scanAtom(environmentId)),
+ };
+ });
}
diff --git a/apps/web/src/state/environmentAtomList.test.ts b/apps/web/src/state/environmentAtomList.test.ts
new file mode 100644
index 00000000000..1fa50cdeb90
--- /dev/null
+++ b/apps/web/src/state/environmentAtomList.test.ts
@@ -0,0 +1,24 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it } from "vite-plus/test";
+
+import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
+
+const counts = Atom.family((environmentId: EnvironmentId) => Atom.make(environmentId.length));
+const countsList = environmentAtomList("test-counts", counts);
+
+describe("environmentAtomList", () => {
+ it("returns the same atom and snapshot for an equal id list", () => {
+ const registry = AtomRegistry.make();
+ const first = countsList(
+ environmentIdsKey([EnvironmentId.make("a"), EnvironmentId.make("bb")]),
+ );
+ const second = countsList(
+ environmentIdsKey([EnvironmentId.make("a"), EnvironmentId.make("bb")]),
+ );
+ expect(second).toBe(first);
+ expect(registry.get(first)).toEqual([1, 2]);
+ expect(registry.get(second)).toBe(registry.get(first));
+ expect(registry.get(countsList(environmentIdsKey([])))).toEqual([]);
+ });
+});
diff --git a/apps/web/src/state/environmentAtomList.ts b/apps/web/src/state/environmentAtomList.ts
new file mode 100644
index 00000000000..6dfefaded3d
--- /dev/null
+++ b/apps/web/src/state/environmentAtomList.ts
@@ -0,0 +1,21 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+
+export const environmentIdsKey = (environmentIds: ReadonlyArray<EnvironmentId>) =>
+ environmentIds.join("\n");
+
+/**
+ * Reads one per-environment atom for a list of environments. The list is keyed by its ids, so
+ * renders that rebuild an equal list read the same atom instead of a new one whose fresh
+ * snapshot would schedule another render.
+ */
+export function environmentAtomList<A>(
+ label: string,
+ atom: (environmentId: EnvironmentId) => Atom.Atom<A>,
+) {
+ return Atom.family((key: string) =>
+ Atom.make((get) =>
+ key === "" ? [] : (key.split("\n") as EnvironmentId[]).map((id) => get(atom(id))),
+ ).pipe(Atom.withLabel(`${label}:${key}`)),
+ );
+}
diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts
index d9aa59d1179..3e2b00d269d 100644
--- a/apps/web/src/state/queries.ts
+++ b/apps/web/src/state/queries.ts
@@ -97,6 +97,32 @@ export function useThreadSearch(
};
}
+function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
+ const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
+ return vcsEnvironment.listRefs({
+ environmentId,
+ input: {
+ cwd,
+ ...(query.length > 0 ? { query } : {}),
+ ...(cursor === undefined ? {} : { cursor }),
+ limit: VCS_REF_LIST_LIMIT,
+ },
+ });
+}
+
+const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
+ ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
+>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
+
+// Keyed by target and cursors so every render of the same pages reads the same atom.
+const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
+ const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
+ const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
+ return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
+ Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
+ );
+});
+
export function usePaginatedBranches(target: VcsRefTarget) {
// Starts unkeyed: a key mismatch already resolves to the initial cursors, and seeding
// the key here would make every derivation below straddle this hook call.
@@ -112,24 +138,10 @@ export function usePaginatedBranches(target: VcsRefTarget) {
const targetKey =
environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
- const pageAtoms =
- environmentId !== null && cwd !== null
- ? cursors.map((cursor) =>
- vcsEnvironment.listRefs({
- environmentId,
- input: {
- cwd,
- ...(query.length > 0 ? { query } : {}),
- ...(cursor === undefined ? {} : { cursor }),
- limit: VCS_REF_LIST_LIMIT,
- },
- }),
- )
- : [];
- const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
- Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`),
+ const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
+ const results = useAtomValue(
+ pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
);
- const results = useAtomValue(pagesAtom);
const values = results.flatMap((result) => {
const value = Option.getOrNull(AsyncResult.value(result));
return value === null ? [] : [value];
@@ -164,10 +176,9 @@ export function usePaginatedBranches(target: VcsRefTarget) {
})()
: null;
const refresh = () => {
- const firstPage = pageAtoms[0];
setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
- if (firstPage !== undefined) {
- appAtomRegistry.refresh(firstPage);
+ if (targetKey !== null) {
+ appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
}
};
const nextCursor = data?.nextCursor;
diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts
index 5d85157931b..8e38c4eea80 100644
--- a/apps/web/src/state/server.ts
+++ b/apps/web/src/state/server.ts
@@ -18,6 +18,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
+import { environmentAtomList } from "./environmentAtomList";
import { primaryEnvironmentIdAtom } from "./primaryEnvironment";
import { environmentSession } from "./session";
@@ -30,6 +31,10 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRunt
usageLimitSources: true,
usageLimitsCommand: true,
});
+export const environmentUpdateStatesAtom = environmentAtomList(
+ "web-environment-update-states",
+ serverEnvironment.updateStateAtom,
+);
export const updateOutdatedServer = createOutdatedServerUpdateCommand(connectionAtomRuntime);
export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
catalogValueAtom: environmentCatalog.catalogValueAtom,
diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.ts
index 9e7ab528646..e594e856883 100644
--- a/apps/web/src/state/session.ts
+++ b/apps/web/src/state/session.ts
@@ -11,8 +11,13 @@ import { AsyncResult, Atom } from "effect/reactivity";
import { connectionAtomRuntime } from "../connection/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
+import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRuntime);
+export const environmentSessionStatesAtom = environmentAtomList(
+ "web-environment-session-states",
+ environmentSession.sessionStateAtom,
+);
const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
@@ -36,21 +41,26 @@ function sessionHasScope(
return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
}
+// Keyed by scope and ids so callers get one Set per session change, not one per render.
+const environmentsWithScopeAtom = Atom.family((key: string) => {
+ const [scope, idsKey = ""] = key.split(/\n(.*)/s) as [AuthEnvironmentScope, string?];
+ const ids = idsKey === "" ? [] : (idsKey.split("\n") as EnvironmentId[]);
+ const statesAtom = environmentSessionStatesAtom(idsKey);
+ return Atom.make((get) => {
+ const states = get(statesAtom);
+ return new Set(ids.filter((_, index) => sessionHasScope(states[index]!, scope)));
+ }).pipe(Atom.withLabel(`web-environments-with-scope:${key}`));
+});
+
export function useEnvironmentsWithScope(
environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,
scope: AuthEnvironmentScope,
): ReadonlySet<EnvironmentId> {
- const permitted = Atom.make((get) => {
- const ids = new Set<EnvironmentId>();
- for (const { environmentId } of environments) {
- const result = get(environmentSession.sessionStateAtom(environmentId));
- if (sessionHasScope(result, scope)) {
- ids.add(environmentId);
- }
- }
- return ids;
- });
- return useAtomValue(permitted);
+ return useAtomValue(
+ environmentsWithScopeAtom(
+ `${scope}\n${environmentIdsKey(environments.map(({ environmentId }) => environmentId))}`,
+ ),
+ );
}
export function readEnvironmentScope(