@devries-cameron20 / t3code Mirror · read-only / commits / 4a5dade3b4
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

perf(client): provider status pushes no longer re-render environment presentation consumers (#20821)

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

Julius Marminge committed Oct 17, 2026 at 05:12 UTC 4a5dade3b4915cdfd25729d2c24d5751a282ef7e
30 files changed +399 -106
apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx
+5 -2
@@ -5,12 +5,14 @@ import {
5 type AtomCommandResult,
6 } from "@t3tools/client-runtime/state/runtime";
7 import type { ProviderAuthResponse, ServerProvider } from "@t3tools/contracts";
8 +import { useAtomValue } from "@effect/atom-react";
9 import { useRef, useState } from "react";
10 import { Linking, Pressable, ScrollView, TextInput, View } from "react-native";
11 import { useSafeAreaInsets } from "react-native-safe-area-context";
12
13 import { AppText as Text } from "../../components/ui/AppText";
14 import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
15 +import { environmentPresentations } from "../../state/presentation";
16 import { useEnvironmentQuery } from "../../state/query";
17 import { serverEnvironment } from "../../state/server";
18 import { useAtomCommand } from "../../state/use-atom-command";
@@ -25,6 +27,7 @@ import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-en
27
28 export function SettingsProviderAccountsRouteScreen() {
29 const { selectedTargets } = useSettingsEnvironmentFilter();
30 + const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
31 const insets = useSafeAreaInsets();
32 return (
33 <>
@@ -41,7 +44,7 @@ export function SettingsProviderAccountsRouteScreen() {
44 ) : (
45 selectedTargets.map((environment) => (
46 <SettingsSection key={environment.environmentId} title={environment.label}>
44 - {environment.serverConfig.providers
47 + {(providersByEnvironment.get(environment.environmentId) ?? [])
48 .filter(
49 (provider) =>
50 provider.setup?.canAuthenticate ||
@@ -54,7 +57,7 @@ export function SettingsProviderAccountsRouteScreen() {
57 provider={provider}
58 />
59 ))}
57 - {!environment.serverConfig.providers.some(
60 + {!(providersByEnvironment.get(environment.environmentId) ?? []).some(
61 (provider) =>
62 provider.setup?.canAuthenticate ||
63 (provider.driver === "acpRegistry" && provider.installed),
apps/mobile/src/features/usage/ChatGptUsageSummary.tsx
+1 -1
@@ -11,7 +11,7 @@ export function ChatGptUsageSummary({
11 }: {
12 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
13 }) {
14 - const presentations = useAtomValue(environmentPresentations.presentationsAtom);
14 + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
15 const selected =
16 selectedEnvironmentIds === null
17 ? presentations
apps/mobile/src/features/usage/UsageLimitsPooled.tsx
+2 -2
@@ -222,7 +222,7 @@ export function UsageLimitsSection({
222 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
223 readonly cursorPrompt?: ReactNode;
224 }) {
225 - const presentations = useAtomValue(environmentPresentations.presentationsAtom);
225 + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
226 const selected =
227 selectedEnvironmentIds === null
228 ? presentations
@@ -345,7 +345,7 @@ type AccountScreenProps = StaticScreenProps<{
345
346 export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
347 const insets = useSafeAreaInsets();
348 - const presentations = useAtomValue(environmentPresentations.presentationsAtom);
348 + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
349 const { accountKey, windowId, windowKind, environmentIds, now } = route.params;
350 const selectedIds =
351 environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id)));
apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx
+1 -1
@@ -12,7 +12,7 @@ import { buildSubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
12 // Isolate quota changes from the much busier thread/config presentation stream.
13 const snapshotAtom = Atom.make((get) =>
14 buildSubscriptionUsageSnapshot(
15 - get(environmentPresentations.presentationsAtom),
15 + get(environmentPresentations.presentationsWithProvidersAtom),
16 Linking.createURL("settings/usage", { queryParams: { tab: "limits" } }),
17 Platform.OS === "android" ? Infinity : 6,
18 ),
apps/web/src/components/ChatView.tsx
+27 -18
@@ -364,6 +364,7 @@ import { useProjectClone } from "../state/projectClones";
364 import { projectCloneDisplayName, projectCloneProgressSummary } from "@t3tools/contracts";
365 import {
366 type EnvironmentPresentation,
367 + useEnvironmentProviders,
368 useEnvironments,
369 usePrimaryEnvironment,
370 } from "../state/environments";
@@ -1092,6 +1093,7 @@ export default function ChatView(props: ChatViewProps) {
1093 });
1094 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
1095 const { environments } = useEnvironments();
1096 + const providersByEnvironment = useEnvironmentProviders();
1097 const primaryEnvironment = usePrimaryEnvironment();
1098 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
1099 const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
@@ -2221,7 +2223,12 @@ export default function ChatView(props: ChatViewProps) {
2223 const serverConfig = activeThread
2224 ? (activeEnvironment?.serverConfig ?? null)
2225 : (primaryEnvironment?.serverConfig ?? null);
2224 - const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
2226 + const providerEnvironmentId = (activeThread ? activeEnvironment : primaryEnvironment)
2227 + ?.environmentId;
2228 + const providerStatuses =
2229 + (providerEnvironmentId === undefined
2230 + ? undefined
2231 + : providersByEnvironment.get(providerEnvironmentId)) ?? EMPTY_PROVIDERS;
2232 const selectedProviderByThreadId = composerActiveProvider ?? null;
2233 const threadProvider =
2234 activeThread?.modelSelection.instanceId ??
@@ -3185,23 +3192,25 @@ export default function ChatView(props: ChatViewProps) {
3192 return (
3193 environment?.connection.phase === "connected" &&
3194 (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
3188 - environment.serverConfig?.providers.some(
3189 - (provider) =>
3190 - (activeProviderInstanceId === null ||
3191 - provider.instanceId === activeProviderInstanceId) &&
3192 - provider.driver === selectedProvider &&
3193 - (environment.serverConfig?.settings
3194 - ? resolveProjectProviderInstanceEnabled(
3195 - environment.serverConfig.settings,
3196 - candidate.projectId,
3197 - provider.instanceId,
3198 - )
3199 - : provider.enabled) &&
3200 - provider.installed &&
3201 - provider.status !== "error" &&
3202 - provider.auth.status !== "unauthenticated" &&
3203 - provider.availability !== "unavailable",
3204 - )
3195 + providersByEnvironment
3196 + .get(candidate.environmentId)
3197 + ?.some(
3198 + (provider) =>
3199 + (activeProviderInstanceId === null ||
3200 + provider.instanceId === activeProviderInstanceId) &&
3201 + provider.driver === selectedProvider &&
3202 + (environment.serverConfig?.settings
3203 + ? resolveProjectProviderInstanceEnabled(
3204 + environment.serverConfig.settings,
3205 + candidate.projectId,
3206 + provider.instanceId,
3207 + )
3208 + : provider.enabled) &&
3209 + provider.installed &&
3210 + provider.status !== "error" &&
3211 + provider.auth.status !== "unauthenticated" &&
3212 + provider.availability !== "unavailable",
3213 + )
3214 );
3215 })
3216 .map((candidate) => candidate.environmentId)
apps/web/src/components/CommandPalette.tsx
+10 -5
@@ -129,7 +129,11 @@ import { useAtomQueryRunner } from "../state/use-atom-query-runner";
129 import { useScratchProject } from "../hooks/useScratchProject";
130 import { useNewProject } from "../hooks/useNewProject";
131 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
132 -import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
132 +import {
133 + useEnvironmentProviders,
134 + useEnvironments,
135 + usePrimaryEnvironmentId,
136 +} from "../state/environments";
137 import { useProjects, useServerConfigs, useThreadShells, waitForProject } from "../state/entities";
138 import { useThreadSearch } from "../state/queries";
139 import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
@@ -818,11 +822,12 @@ function OpenCommandPaletteDialog(props: {
822 const environmentThemes = useEnvironmentThemeDefinitions();
823 const themeCards = useThemeCards(customThemes, environmentThemes);
824 const providers = useAtomValue(primaryServerProvidersAtom);
825 + const providersByEnvironment = useEnvironmentProviders();
826 const providerEntryByEnvironmentAndInstanceId = new Map<string, ProviderInstanceEntry>(
827 environments.flatMap((environment) => {
828 const serverConfig = environment.serverConfig;
829 const derived = deriveProviderInstanceEntries(
825 - serverConfig?.providers ??
830 + providersByEnvironment.get(environment.environmentId) ??
831 (environment.environmentId === primaryEnvironmentId ? providers : []),
832 );
833 const entries = serverConfig
@@ -1680,9 +1685,9 @@ function OpenCommandPaletteDialog(props: {
1685 project.id === promptLinkProjectRef.projectId,
1686 ),
1687 providers:
1683 - environments.find(
1684 - (environment) => environment.environmentId === promptLinkProjectRef?.environmentId,
1685 - )?.serverConfig?.providers ?? [],
1688 + (promptLinkProjectRef
1689 + ? providersByEnvironment.get(promptLinkProjectRef.environmentId)
1690 + : undefined) ?? [],
1691 threadModelSelection: activeThread?.modelSelection ?? null,
1692 };
1693 const plainPromptLink = promptLinkInput
apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts
+8 -4
@@ -1,7 +1,10 @@
1 import type { ConnectionCatalogEntry } from "@t3tools/client-runtime/connection";
2 -import type { ServerConfig } from "@t3tools/contracts";
2
4 -import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
3 +import {
4 + useEnvironmentProviders,
5 + useEnvironments,
6 + usePrimaryEnvironmentId,
7 +} from "~/state/environments";
8 import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
9 import {
10 buildLocalEnvironmentUpdateGroups,
@@ -37,6 +40,7 @@ export function useLocalEnvironmentUpdateGroups(): {
40 readonly isAnySettling: boolean;
41 } {
42 const { environments } = useEnvironments();
43 + const providersByEnvironment = useEnvironmentProviders();
44 const primaryEnvironmentId = usePrimaryEnvironmentId();
45
46 const inputs: LocalEnvironmentProvidersInput[] = [];
@@ -47,7 +51,7 @@ export function useLocalEnvironmentUpdateGroups(): {
51 }
52
53 const isPrimary = environment.environmentId === primaryEnvironmentId;
50 - const serverConfig: ServerConfig | null = environment.serverConfig;
54 + const serverConfig = environment.serverConfig;
55
56 inputs.push({
57 environmentId: environment.environmentId,
@@ -61,7 +65,7 @@ export function useLocalEnvironmentUpdateGroups(): {
65 : environment.label,
66 isPrimary,
67 connectionState: isPrimary ? "ready" : normalizeConnectionState(environment.connection.phase),
64 - providers: serverConfig?.providers ?? [],
68 + providers: providersByEnvironment.get(environment.environmentId) ?? [],
69 });
70 }
71
apps/web/src/components/ProviderUpdatesAction.tsx
+3 -2
@@ -2,7 +2,7 @@ import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
2 import { settlePromise } from "@t3tools/client-runtime/state/runtime";
3 import { useRef, useState } from "react";
4
5 -import { useEnvironments } from "~/state/environments";
5 +import { useEnvironmentProviders, useEnvironments } from "~/state/environments";
6 import { serverEnvironment } from "~/state/server";
7 import { useAtomCommand } from "~/state/use-atom-command";
8 import {
@@ -17,11 +17,12 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
17
18 export function useProviderUpdates() {
19 const { environments } = useEnvironments();
20 + const providersByEnvironment = useEnvironmentProviders();
21 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
22 reportFailure: false,
23 });
24 const machines = environments.flatMap((environment) => {
24 - const providers = environment.serverConfig?.providers ?? [];
25 + const providers = providersByEnvironment.get(environment.environmentId) ?? [];
26 if (environment.connection.phase !== "connected") {
27 return [];
28 }
apps/web/src/components/Sidebar.tsx
+81 -19
@@ -1,4 +1,5 @@
1 -import { type EnvironmentId, type ScopedProjectRef, type ServerConfig } from "@t3tools/contracts";
1 +import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts";
2 +import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
3 import { ThreadHoverCard, ThreadHoverCardPopup } from "./ThreadHoverCard";
4 import { CollapsibleSectionHeader } from "./ui/collapsible-section-header";
5 import { ThreadTerminalStatusButton } from "./ThreadStatusIndicators";
@@ -13,6 +14,8 @@ import { requestCustomSnooze } from "./CustomSnoozeDialog";
14 import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
15 import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
16 import { useAtomValue } from "@effect/atom-react";
17 +import * as Option from "effect/Option";
18 +import { Atom } from "effect/reactivity";
19 import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
20 import * as Schema from "effect/Schema";
21 import {
@@ -156,9 +159,11 @@ import {
159 readThreadShell,
160 useAllEnvironmentProjectSnapshotsReady,
161 useProjects,
162 + useServerConfigs,
163 useThreadShells,
164 } from "../state/entities";
161 -import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
165 +import { environmentPresentations } from "../state/presentation";
166 +import { primaryServerKeybindingsAtom } from "../state/server";
167 import { environmentProjects } from "../state/projects";
168 import { vcsEnvironment } from "../state/vcs";
169 import { threadEnvironment } from "../state/threads";
@@ -284,7 +289,71 @@ import {
289 } from "../composerDraftStore";
290 import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
291
287 -const EMPTY_PROVIDER_ENTRIES: ReadonlyMap<string, ProviderInstanceEntry> = new Map();
292 +// The fields thread rows show. Provider status pushes refresh `checkedAt`,
293 +// status and auth on every provider; leaving those out keeps each
294 +// environment's map, and every memoized row, stable across them.
295 +type SidebarProviderEntry = Pick<
296 + ProviderInstanceEntry,
297 + | "instanceId"
298 + | "driverKind"
299 + | "displayName"
300 + | "accentColor"
301 + | "acpRegistryAgentId"
302 + | "acpRegistryIconUrl"
303 + | "models"
304 +>;
305 +
306 +function sameSidebarProviderEntries(
307 + left: ReadonlyMap<string, SidebarProviderEntry>,
308 + right: ReadonlyMap<string, SidebarProviderEntry>,
309 +): boolean {
310 + if (left.size !== right.size) return false;
311 + for (const [instanceId, entry] of right) {
312 + const other = left.get(instanceId);
313 + if (
314 + other === undefined ||
315 + other.driverKind !== entry.driverKind ||
316 + other.displayName !== entry.displayName ||
317 + other.accentColor !== entry.accentColor ||
318 + other.acpRegistryAgentId !== entry.acpRegistryAgentId ||
319 + other.acpRegistryIconUrl !== entry.acpRegistryIconUrl ||
320 + other.models !== entry.models
321 + ) {
322 + return false;
323 + }
324 + }
325 + return true;
326 +}
327 +
328 +// Threads on non-primary environments (T3 Connect, hosted) resolve their
329 +// provider entry from their own environment's config: default instance ids
330 +// are driver slugs, so a flat map would collide across environments.
331 +const sidebarProviderEntriesAtom = Atom.make((get) => {
332 + const providersByEnvironment = get(environmentPresentations.providersByEnvironmentAtom);
333 + const derived = deriveProviderEntriesByEnvironment(
334 + [...get(environmentPresentations.serverConfigsAtom)].map(
335 + ([environmentId, config]) =>
336 + [environmentId, providersByEnvironment.get(environmentId) ?? [], config.settings] as const,
337 + ),
338 + );
339 + const previous = Option.getOrNull(
340 + get.self<ReadonlyMap<string, ReadonlyMap<string, SidebarProviderEntry>>>(),
341 + );
342 + const next = new Map<string, ReadonlyMap<string, SidebarProviderEntry>>();
343 + let changed = previous === null || previous.size !== derived.size;
344 + for (const [environmentId, entries] of derived) {
345 + const prior = previous?.get(environmentId);
346 + if (prior !== undefined && sameSidebarProviderEntries(prior, entries)) {
347 + next.set(environmentId, prior);
348 + } else {
349 + next.set(environmentId, entries);
350 + changed = true;
351 + }
352 + }
353 + return !changed && previous !== null ? previous : next;
354 +}).pipe(Atom.withLabel("sidebar-provider-entries"));
355 +
356 +const EMPTY_PROVIDER_ENTRIES: ReadonlyMap<string, SidebarProviderEntry> = new Map();
357 // Collapsed shelves share one empty list so a route change alone does not
358 // give the sidebar list a new identity.
359 const EMPTY_THREADS: readonly EnvironmentThreadShell[] = [];
@@ -311,7 +380,7 @@ type SidebarOptimisticDrop = {
380 interface SidebarThreadPartitionInput {
381 readonly threads: readonly EnvironmentThreadShell[];
382 readonly scopedProjectKeys: ReadonlySet<string> | null;
314 - readonly serverConfigs: ReadonlyMap<EnvironmentId, ServerConfig>;
383 + readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
384 readonly optimisticDrop: SidebarOptimisticDrop | null;
385 readonly workingShelfEnabled: boolean;
386 // Snooze wakes and the queued-turn grace depend on the clock, so the minute
@@ -373,7 +442,7 @@ function routeThreadOnly(
442 function useSidebarThreads(input: {
443 readonly projectScopeKey: string | null;
444 readonly scopedProjectKeys: ReadonlySet<string> | null;
376 - readonly serverConfigs: ReadonlyMap<EnvironmentId, ServerConfig>;
445 + readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
446 readonly optimisticDrop: SidebarOptimisticDrop | null;
447 readonly routeThreadKey: string | null;
448 }) {
@@ -679,19 +748,12 @@ function isOptimisticDropReleased(input: {
748 function useSidebarLookups() {
749 const projects = useProjects();
750 const environments = useEnvironmentIdentities();
682 - const serverConfigs = useAtomValue(environmentServerConfigsAtom);
751 + const serverConfigs = useServerConfigs();
752 + const providerEntriesByEnvironment = useAtomValue(sidebarProviderEntriesAtom);
753 const projectGroups = useSidebarProjectGroups();
754 const environmentLabelById = new Map(
755 environments.map((environment) => [environment.environmentId, environment.label] as const),
756 );
687 - // Threads on non-primary environments (T3 Connect, hosted) resolve their
688 - // provider entry from their own environment's config: default instance ids
689 - // are driver slugs, so a flat map would collide across environments.
690 - const providerEntriesByEnvironment = deriveProviderEntriesByEnvironment(
691 - [...serverConfigs].map(
692 - ([environmentId, config]) => [environmentId, config.providers, config.settings] as const,
693 - ),
694 - );
757 const projectByKey = new Map(
758 projects.map((project) => [`${project.environmentId}:${project.id}`, project] as const),
759 );
@@ -804,7 +866,7 @@ function terminalProcessLabel(count: number): string {
866
867 function SidebarProviderStack(props: {
868 thread: SidebarThreadSummary;
807 - providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
869 + providerEntryByInstanceId: ReadonlyMap<string, SidebarProviderEntry>;
870 }) {
871 const stack = resolveThreadProviderStack(props.thread);
872 const currentInstanceId = stack[stack.length - 1]!;
@@ -870,8 +932,8 @@ function SidebarThreadTooltip({
932 projectDisplayName: string | null;
933 environmentLabel: string | null;
934 environmentMachine: EnvironmentMachineKind;
873 - providerEntry: ProviderInstanceEntry | null;
874 - providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
935 + providerEntry: SidebarProviderEntry | null;
936 + providerEntryByInstanceId: ReadonlyMap<string, SidebarProviderEntry>;
937 showInstanceBadge: boolean;
938 modelInstanceId: string;
939 modelLabel: string;
@@ -1482,7 +1544,7 @@ type SidebarThreadRowProps = {
1544 scratchMachineLabel: string | null;
1545 project: EnvironmentProject | null;
1546 projectDisplayName: string | null;
1485 - providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
1547 + providerEntryByInstanceId: ReadonlyMap<string, SidebarProviderEntry>;
1548 timestampFormat: TimestampFormat;
1549 onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void;
1550 onThreadActivate: (threadRef: ScopedThreadRef) => void;
@@ -2428,7 +2490,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
2490 projectDisplayName: string | null;
2491 environmentLabel: string | null;
2492 environmentMachine: EnvironmentMachineKind;
2431 - providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
2493 + providerEntryByInstanceId: ReadonlyMap<string, SidebarProviderEntry>;
2494 isHighlighted: boolean;
2495 isRouteActive: boolean;
2496 resultId: string;
apps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsx
+6 -1
@@ -30,7 +30,12 @@ vi.mock("../../state/entities", () => ({
30 .filter((shell) => shell.environmentId === ref.environmentId)
31 .map((shell) => shell.source),
32 useProjects: () => state.projects,
33 - useServerConfigs: () => state.configs,
33 +}));
34 +vi.mock("../../state/environments", () => ({
35 + useEnvironmentProviders: () =>
36 + new Map(
37 + [...state.configs].map(([id, config]) => [id, (config as { providers: unknown }).providers]),
38 + ),
39 }));
40 vi.mock("../../lib/archivedThreadsState", () => ({
41 useArchivedThreadSnapshots: () => ({ snapshots: [] }),
apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+3 -3
@@ -54,10 +54,10 @@ import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
54 import { buildThreadRouteParams } from "../../threadRoutes";
55 import {
56 useProjects,
57 - useServerConfigs,
57 useThreadProjection,
58 useThreadRelationshipShells,
59 } from "../../state/entities";
60 +import { useEnvironmentProviders } from "../../state/environments";
61 import { threadEnvironment } from "../../state/threads";
62 import { orchestrationEnvironment } from "../../state/orchestration";
63 import { useAtomCommand } from "../../state/use-atom-command";
@@ -210,7 +210,7 @@ export function ThreadRelationshipsPanel(props: {
210 }) {
211 const ref = scopeThreadRef(props.environmentId, props.threadId);
212 const projection = useThreadProjection(ref)?.projection ?? null;
213 - const serverConfigs = useServerConfigs();
213 + const providersByEnvironment = useEnvironmentProviders();
214 const relationshipShells = useThreadRelationshipShells(ref);
215 const allProjects = useProjects();
216 const archived = useArchivedThreadSnapshots([props.environmentId]);
@@ -226,7 +226,7 @@ export function ThreadRelationshipsPanel(props: {
226 const [stoppingId, setStoppingId] = useState<string | null>(null);
227 // These lookups and the graph walk every subagent and thread, so they sit below
228 // the panel's hooks where the compiler can cache them.
229 - const providers = serverConfigs.get(props.environmentId)?.providers;
229 + const providers = providersByEnvironment.get(props.environmentId);
230 const projects = allProjects.filter((project) => project.environmentId === props.environmentId);
231 const archivedShells = archived.snapshots.find(
232 (entry) => entry.environmentId === props.environmentId,
apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx
+1 -1
@@ -51,7 +51,7 @@ export interface SavedCloudEnvironmentConnection {
51 readonly environmentId: EnvironmentId;
52 readonly connection: EnvironmentConnectionPresentation;
53 readonly relayManaged: boolean;
54 - readonly serverConfig?: ServerConfig | null;
54 + readonly serverConfig?: Pick<ServerConfig, "environment"> | null;
55 }
56
57 function RemoteEnvironmentRowsSkeleton() {
apps/web/src/components/promptLinks/NewThreadLinkView.tsx
+5 -2
@@ -25,7 +25,9 @@ import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
25 import { useScratchProject } from "~/hooks/useScratchProject";
26 import { newProjectId } from "~/lib/utils";
27 import { useProjects, useThreadShells, waitForProject } from "~/state/entities";
28 +import { appAtomRegistry } from "~/rpc/atomRegistry";
29 import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
30 +import { environmentPresentations } from "~/state/presentation";
31 import { allReachableShellsLiveAtom } from "~/state/shell";
32 import { sourceControlEnvironment } from "~/state/sourceControl";
33 import { useAtomCommand } from "~/state/use-atom-command";
@@ -104,8 +106,9 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
106 const notes: Array<string> = [];
107 if (link.kind === "new" && link.provider !== null) {
108 const providers =
107 - environments.find((environment) => environment.environmentId === project.environmentId)
108 - ?.serverConfig?.providers ?? [];
109 + appAtomRegistry
110 + .get(environmentPresentations.providersByEnvironmentAtom)
111 + .get(project.environmentId) ?? [];
112 const resolved = resolvePromptLinkModelSelection(providers, {
113 provider: link.provider,
114 model: link.model,
apps/web/src/components/settings/ChatGptWelcomeCoordinator.tsx
+12 -9
@@ -28,19 +28,22 @@ function readAcknowledgedProfiles(): string[] {
28
29 export function ChatGptWelcomeCoordinator() {
30 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
31 + const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
32 const [acknowledged, setAcknowledged] = useState(readAcknowledgedProfiles);
33 const profiles = [...presentations].flatMap(([environmentId, presentation]) =>
34 presentation.connection.phase !== "connected"
35 ? []
35 - : (presentation.serverConfig?.providers ?? []).filter(usesChatGptSharing).map((provider) => ({
36 - key: JSON.stringify([
37 - environmentId,
38 - provider.instanceId,
39 - provider.auth.profileId ?? provider.auth.email ?? "default",
40 - ]),
41 - environmentLabel: presentation.entry.target.label,
42 - providerName: provider.displayName ?? "Codex",
43 - })),
36 + : (providersByEnvironment.get(environmentId) ?? [])
37 + .filter(usesChatGptSharing)
38 + .map((provider) => ({
39 + key: JSON.stringify([
40 + environmentId,
41 + provider.instanceId,
42 + provider.auth.profileId ?? provider.auth.email ?? "default",
43 + ]),
44 + environmentLabel: presentation.entry.target.label,
45 + providerName: provider.displayName ?? "Codex",
46 + })),
47 );
48 const next = profiles.find((profile) => !acknowledged.includes(profile.key));
49 const dismiss = () => {
apps/web/src/components/settings/EnvironmentIconPicker.tsx
+2 -2
@@ -21,7 +21,7 @@ import {
21 } from "../ui/menu";
22
23 export function resolveEnvironmentIconPickerLock(input: {
24 - readonly serverConfig: ServerConfig | null;
24 + readonly serverConfig: Pick<ServerConfig, "environment"> | null;
25 readonly operateAccess: "granted" | "denied" | "pending";
26 }): string | null {
27 if (input.serverConfig === null) {
@@ -41,7 +41,7 @@ export function EnvironmentIconMenu({
41 serverConfig,
42 }: {
43 readonly environmentId: EnvironmentId;
44 - readonly serverConfig: ServerConfig | null;
44 + readonly serverConfig: Pick<ServerConfig, "environment"> | null;
45 }) {
46 const updateSettings = useUpdateEnvironmentSettings(environmentId);
47 const operateAccess = useEnvironmentScope(environmentId, AuthSettingsWriteScope)
apps/web/src/components/settings/ProjectDefaultsSettings.tsx
+10 -6
@@ -16,7 +16,7 @@ import {
16 resolveDefaultProviderModelSelection,
17 sortProviderInstanceEntries,
18 } from "../../providerInstances";
19 -import { useEnvironments } from "../../state/environments";
19 +import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
20 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
21 import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic";
22 import { ProviderModelPicker } from "../chat/ProviderModelPicker";
@@ -53,10 +53,14 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
53 const updateSettings = useUpdateScopedSettings();
54 const navigate = useNavigate();
55 const { environments } = useEnvironments();
56 + const providersByEnvironment = useEnvironmentProviders();
57 const representative = target
58 ? environments.find((environment) => environment.environmentId === target.environmentId)
59 : undefined;
59 - const providers = representative?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
60 + const providers =
61 + (representative?.serverConfig
62 + ? providersByEnvironment.get(representative.environmentId)
63 + : undefined) ?? EMPTY_SERVER_PROVIDERS;
64 const selection = resolveDefaultProviderModelSelection(providers, settings.defaultModelSelection);
65 const entries = sortProviderInstanceEntries(
66 applyProviderInstanceSettings(
@@ -94,16 +98,16 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
98 const environment = environments.find(
99 (entry) => entry.environmentId === candidate.environmentId,
100 );
97 - const config = environment?.serverConfig;
98 - if (!config) continue;
101 + const providers = providersByEnvironment.get(candidate.environmentId);
102 + if (!environment?.serverConfig || !providers) continue;
103 const entry = applyProviderInstanceSettings(
100 - deriveProviderInstanceEntries(config.providers),
104 + deriveProviderInstanceEntries(providers),
105 candidate.settings,
106 candidate.projectId,
107 ).find((option) => option.instanceId === instanceId);
108 const options = getCustomModelOptionsByInstance(
109 mergeEnvironmentSettings(candidate.settings, settings),
106 - config.providers,
110 + providers,
111 ).get(instanceId);
112 if (
113 !entry?.enabled ||
apps/web/src/components/settings/SettingsPanels.tsx
+6 -1
@@ -102,6 +102,7 @@ import {
102 } from "../../providerInstances";
103 import { ensureLocalApi, readLocalApi } from "../../localApi";
104 import { isMacPlatform } from "../../lib/utils";
105 +import { useEnvironmentProviders } from "../../state/environments";
106 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
107 import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
108 import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -2055,7 +2056,11 @@ export function GeneralSettingsPanel() {
2056 const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
2057 readLastEnabledProjectGroupingMode(),
2058 );
2058 - const serverProviders = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
2059 + const providersByEnvironment = useEnvironmentProviders();
2060 + const serverProviders =
2061 + (environment?.serverConfig
2062 + ? providersByEnvironment.get(environment.environmentId)
2063 + : undefined) ?? EMPTY_SERVER_PROVIDERS;
2064 const supportsAutoSettlement =
2065 connectedEnvironments.length > 0 &&
2066 connectedEnvironments.every(
apps/web/src/components/settings/SourceControlWritingSettings.test.tsx
+1
@@ -37,6 +37,7 @@ vi.mock("./useScopedModelAvailability", () => ({
37 }));
38 vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
39 vi.mock("../../state/server", () => ({ EMPTY_SERVER_PROVIDERS: [] }));
40 +vi.mock("../../state/environments", () => ({ useEnvironmentProviders: () => new Map() }));
41 vi.mock("../chat/ProviderModelPicker", () => ({ ProviderModelPicker: () => null }));
42 vi.mock("./settingsSearch", () => ({ searchableSetting: (id: string) => ({ id, title: id }) }));
43 vi.mock("./settingsLayout", () => ({
apps/web/src/components/settings/SourceControlWritingSettings.tsx
+6 -1
@@ -29,6 +29,7 @@ import {
29 resolveAppModelSelectionState,
30 selectsPlanAgent,
31 } from "../../modelSelection";
32 +import { useEnvironmentProviders } from "../../state/environments";
33 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
34 import { ProviderModelPicker } from "../chat/ProviderModelPicker";
35 import { TraitsPicker } from "../chat/TraitsPicker";
@@ -71,7 +72,11 @@ export function SourceControlWritingSettingsSection() {
72 const { environment, connectedEnvironments, targets, target } = useSettingsScope();
73 const environmentId = environment?.environmentId ?? null;
74 const hasServerTargets = connectedEnvironments.length > 0;
74 - const serverProviders = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
75 + const providersByEnvironment = useEnvironmentProviders();
76 + const serverProviders =
77 + (environment?.serverConfig
78 + ? providersByEnvironment.get(environment.environmentId)
79 + : undefined) ?? EMPTY_SERVER_PROVIDERS;
80 const styleFieldMixed = (field: keyof ServerSettings["sourceControlWritingStyle"]) => {
81 const first = targets[0];
82 return (
apps/web/src/components/settings/useScopedModelAvailability.ts
+6 -5
@@ -7,7 +7,7 @@ import {
7 deriveProviderInstanceEntries,
8 type ProviderInstanceEntry,
9 } from "../../providerInstances";
10 -import { useEnvironments } from "../../state/environments";
10 +import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
11 import { useSettingsScope } from "./SettingsScopeContext";
12
13 export function useScopedModelDisabledReason(
@@ -16,22 +16,23 @@ export function useScopedModelDisabledReason(
16 ) {
17 const { targets } = useSettingsScope();
18 const { environments } = useEnvironments();
19 + const providersByEnvironment = useEnvironmentProviders();
20 return (instanceId: ProviderInstanceId, model: string): string | null => {
21 const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
22 for (const candidate of targets) {
23 const environment = environments.find(
24 (entry) => entry.environmentId === candidate.environmentId,
25 );
25 - const config = environment?.serverConfig;
26 - if (!config) continue;
26 + const providers = providersByEnvironment.get(candidate.environmentId);
27 + if (!environment?.serverConfig || !providers) continue;
28 const entry = applyProviderInstanceSettings(
28 - deriveProviderInstanceEntries(config.providers),
29 + deriveProviderInstanceEntries(providers),
30 candidate.settings,
31 candidate.projectId,
32 ).find((option) => option.instanceId === instanceId);
33 const options = getCustomModelOptionsByInstance(
34 mergeEnvironmentSettings(candidate.settings, settings),
34 - config.providers,
35 + providers,
36 ).get(instanceId);
37 if (
38 !entry?.enabled ||
apps/web/src/components/usage/UsageLimits.tsx
+1 -1
@@ -337,7 +337,7 @@ export function UsageLimitsSection({
337 readonly now: number;
338 readonly cursorPrompt?: ReactNode;
339 }) {
340 - const presentations = useAtomValue(environmentPresentations.presentationsAtom);
340 + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
341 const hiddenDrivers = new Set<ServerProvider["driver"]>(
342 [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind),
343 );
apps/web/src/components/usage/UsagePage.refresh.test.tsx
+15 -2
@@ -12,14 +12,27 @@ const state = vi.hoisted(() => ({
12 }));
13 vi.mock("@effect/atom-react", () => ({
14 useAtomValue: (atom: unknown) =>
15 - atom === "keybindings" ? DEFAULT_RESOLVED_KEYBINDINGS : state.presentations,
15 + atom === "keybindings"
16 + ? DEFAULT_RESOLVED_KEYBINDINGS
17 + : atom === "providers"
18 + ? new Map(
19 + [...state.presentations].map(([id, presentation]) => [
20 + id,
21 + presentation.serverConfig.providers,
22 + ]),
23 + )
24 + : state.presentations,
25 }));
26 vi.mock("@tanstack/react-router", () => ({
27 useNavigate: () => vi.fn(),
28 useCanGoBack: () => false,
29 }));
30 vi.mock("../../state/presentation", () => ({
22 - environmentPresentations: { presentationsAtom: null },
31 + environmentPresentations: {
32 + presentationsAtom: null,
33 + presentationsWithProvidersAtom: null,
34 + providersByEnvironmentAtom: "providers",
35 + },
36 }));
37 vi.mock("../../state/server", () => ({
38 serverEnvironment: { refreshProviders: null },
apps/web/src/components/usage/UsagePage.tsx
+4 -3
@@ -221,6 +221,7 @@ export function UsagePage() {
221 const refreshingUsage = isRefreshing && !showingLimits;
222 const showingKept = shown !== null && shown.window !== window;
223 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
224 + const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
225 const cursorAccessEnvironments = hiddenProviders.has("cursor")
226 ? []
227 : cursorKeychainAccessEnvironments(selectedEnvironments);
@@ -347,10 +348,10 @@ export function UsagePage() {
348 : enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime);
349 const showChatGptSharing =
350 !hiddenProviders.has("codex") &&
350 - [...presentations].some(
351 - ([id, presentation]) =>
351 + [...providersByEnvironment].some(
352 + ([id, providers]) =>
353 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) &&
353 - presentation.serverConfig?.providers.some(usesChatGptSharing),
354 + providers.some(usesChatGptSharing),
355 );
356
357 const windowLabel =
apps/web/src/state/entities.ts
+5 -3
@@ -14,7 +14,7 @@ import {
14 parseThreadKey,
15 threadKey,
16 } from "@t3tools/client-runtime/state/entities";
17 -import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";
17 +import type { ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
18 import type {
19 EnvironmentId,
20 OrchestrationV2ProjectedTurnItem,
@@ -26,6 +26,7 @@ import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thre
26 import { Atom } from "effect/reactivity";
27 import { appAtomRegistry } from "../rpc/atomRegistry";
28 import { environmentProjects } from "./projects";
29 +import { environmentPresentations } from "./presentation";
30 import { environmentServerConfigsAtom } from "./server";
31 import {
32 allEnvironmentProjectSnapshotsReadyAtom,
@@ -96,8 +97,9 @@ export function useProjects(): ReadonlyArray<EnvironmentProject> {
97 return useAtomValue(environmentProjects.projectsAtom);
98 }
99
99 -export function useServerConfigs(): ReadonlyMap<EnvironmentId, ServerConfig> {
100 - return useAtomValue(environmentServerConfigsAtom);
100 +/** Providers are left out; read them with `useEnvironmentProviders()`. */
101 +export function useServerConfigs() {
102 + return useAtomValue(environmentPresentations.serverConfigsAtom);
103 }
104
105 export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
apps/web/src/state/environments.ts
+5
@@ -55,6 +55,11 @@ export function useEnvironments() {
55 };
56 }
57
58 +/** Provider statuses change on every push, so they live apart from the presentations. */
59 +export function useEnvironmentProviders() {
60 + return useAtomValue(environmentPresentations.providersByEnvironmentAtom);
61 +}
62 +
63 export function usePrimaryEnvironmentId(): EnvironmentId | null {
64 return useAtomValue(primaryEnvironmentIdAtom);
65 }
packages/client-runtime/src/connection/presentation.ts
+8 -1
@@ -20,10 +20,17 @@ export interface EnvironmentConnectionPresentation {
20 readonly traceId: string | null;
21 }
22
23 +/**
24 + * Provider statuses are pushed every few minutes with fresh `checkedAt` stamps, and every root
25 + * coordinator reads environment presentations. Leaving them out keeps a presentation stable
26 + * across those pushes; provider readers subscribe to the server's providers atom instead.
27 + */
28 +export type EnvironmentServerConfig = Omit<ServerConfig, "providers">;
29 +
30 export interface EnvironmentPresentation {
31 readonly entry: ConnectionCatalogEntry;
32 readonly connection: EnvironmentConnectionPresentation;
26 - readonly serverConfig: ServerConfig | null;
33 + readonly serverConfig: EnvironmentServerConfig | null;
34 }
35
36 export function presentConnectionState(
packages/client-runtime/src/state/presentation.test.ts
+40 -1
@@ -76,7 +76,9 @@ describe("environment summary subscriptions", () => {
76 for (let i = 0; i < 20; i++) {
77 const next = config(false, `/workspace-${i}`);
78 h.registry.set(h.configs(FIRST), next);
79 - expect(h.registry.get(h.full.presentationsAtom).get(FIRST)?.serverConfig).toBe(next);
79 + expect(h.registry.get(h.full.presentationsAtom).get(FIRST)?.serverConfig?.cwd).toBe(
80 + next.cwd,
81 + );
82 expect(h.registry.get(h.environmentIdsAtom)).toBe(initialIds);
83 expect(h.registry.get(h.identitiesAtom)).toBe(initialLabels);
84 h.registry.get(h.environmentsAtom);
@@ -109,6 +111,43 @@ describe("environment summary subscriptions", () => {
111 }
112 });
113
114 + it("keeps presentations identical when only provider statuses change", () => {
115 + const h = harness();
116 + const pushes = { presentations: 0, providers: 0, configs: 0 };
117 + const stops = [
118 + h.registry.subscribe(h.full.presentationsAtom, () => pushes.presentations++),
119 + h.registry.subscribe(h.full.providersByEnvironmentAtom, () => pushes.providers++),
120 + h.registry.subscribe(h.full.serverConfigsAtom, () => pushes.configs++),
121 + ];
122 + try {
123 + const base = config();
124 + h.registry.set(h.configs(FIRST), { ...base, providers: [] } as ServerConfig);
125 + const presentations = h.registry.get(h.full.presentationsAtom);
126 + const configs = h.registry.get(h.full.serverConfigsAtom);
127 + const before = { ...pushes };
128 + const providers = [{ instanceId: "codex" }] as unknown as ServerConfig["providers"];
129 + h.registry.set(h.configs(FIRST), { ...base, providers } as ServerConfig);
130 +
131 + expect(h.registry.get(h.full.presentationsAtom)).toBe(presentations);
132 + expect(h.registry.get(h.full.providersByEnvironmentAtom).get(FIRST)).toBe(providers);
133 + expect(
134 + h.registry.get(h.full.presentationsWithProvidersAtom).get(FIRST)?.serverConfig,
135 + ).toEqual({ ...base, providers });
136 + expect(h.registry.get(h.full.serverConfigsAtom)).toBe(configs);
137 + expect(pushes.presentations).toBe(before.presentations);
138 + expect(pushes.configs).toBe(before.configs);
139 + expect(pushes.providers).toBe(before.providers + 1);
140 +
141 + h.registry.set(h.configs(FIRST), { ...base, cwd: "/moved", providers } as ServerConfig);
142 + expect(h.registry.get(h.full.presentationsAtom).get(FIRST)?.serverConfig?.cwd).toBe("/moved");
143 + expect(h.registry.get(h.full.serverConfigsAtom).get(FIRST)?.cwd).toBe("/moved");
144 + expect(h.registry.get(h.full.providersByEnvironmentAtom).get(FIRST)).toBe(providers);
145 + } finally {
146 + stops.forEach((stop) => stop());
147 + h.registry.dispose();
148 + }
149 + });
150 +
151 it("keeps connected search targets stable through config refreshes and updates them on disconnect", () => {
152 const h = harness();
153 let changes = 0;
packages/client-runtime/src/state/presentation.ts
+110 -6
@@ -3,6 +3,7 @@ import {
3 type EnvironmentMachineKind,
4 type EnvironmentId,
5 type ServerConfig,
6 + type ServerProvider,
7 } from "@t3tools/contracts";
8 import * as Option from "effect/Option";
9 import { AsyncResult, Atom } from "effect/reactivity";
@@ -12,9 +13,11 @@ import {
13 connectionCatalogDisplayUrl,
14 presentEnvironmentConnection,
15 type EnvironmentConnectionPhase,
16 + type EnvironmentConnectionPresentation,
17 type EnvironmentPresentation,
18 + type EnvironmentServerConfig,
19 } from "../connection/presentation.ts";
17 -import type { EnvironmentCatalogState } from "./connections.ts";
20 +import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
21 import { hasRelayRoute } from "../connection/routes.ts";
22
23 function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
@@ -29,6 +32,38 @@ function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boo
32 return true;
33 }
34
35 +function sameConnection(
36 + left: EnvironmentConnectionPresentation,
37 + right: EnvironmentConnectionPresentation,
38 +): boolean {
39 + return left.phase === right.phase && left.error === right.error && left.traceId === right.traceId;
40 +}
41 +
42 +function withoutProviders(
43 + config: ServerConfig | null,
44 + previous: EnvironmentServerConfig | null,
45 +): EnvironmentServerConfig | null {
46 + if (config === null) {
47 + return null;
48 + }
49 + const { providers: _providers, ...next } = config;
50 + if (previous === null) {
51 + return next;
52 + }
53 + const keys = Object.keys(next) as Array<keyof EnvironmentServerConfig>;
54 + return keys.length === Object.keys(previous).length &&
55 + keys.every((key) => key in previous && previous[key] === next[key])
56 + ? previous
57 + : next;
58 +}
59 +
60 +export interface EnvironmentPresentationWithProviders extends Omit<
61 + EnvironmentPresentation,
62 + "serverConfig"
63 +> {
64 + readonly serverConfig: ServerConfig | null;
65 +}
66 +
67 export function createEnvironmentPresentationAtoms<E>(input: {
68 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
69 readonly stateAtom: (
@@ -46,14 +81,28 @@ export function createEnvironmentPresentationAtoms<E>(input: {
81 AsyncResult.value(get(input.stateAtom(environmentId))),
82 () => AVAILABLE_CONNECTION_STATE,
83 );
49 - return {
84 + const previous = Option.getOrNull(get.self<EnvironmentPresentation | null>());
85 + const connection: EnvironmentConnectionPresentation =
86 + entry.unsupportedReason === undefined
87 + ? presentEnvironmentConnection(state)
88 + : { phase: "unsupported", error: entry.unsupportedReason, traceId: null };
89 + const next = {
90 entry,
91 connection:
52 - entry.unsupportedReason === undefined
53 - ? presentEnvironmentConnection(state)
54 - : { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
55 - serverConfig: get(input.serverConfigValueAtom(environmentId)),
92 + previous !== null && sameConnection(previous.connection, connection)
93 + ? previous.connection
94 + : connection,
95 + serverConfig: withoutProviders(
96 + get(input.serverConfigValueAtom(environmentId)),
97 + previous?.serverConfig ?? null,
98 + ),
99 } satisfies EnvironmentPresentation;
100 + return previous !== null &&
101 + previous.entry === next.entry &&
102 + previous.connection === next.connection &&
103 + previous.serverConfig === next.serverConfig
104 + ? previous
105 + : next;
106 }).pipe(Atom.withLabel(`environment-presentation:${environmentId}`)),
107 );
108
@@ -73,9 +122,64 @@ export function createEnvironmentPresentationAtoms<E>(input: {
122 return previous;
123 }).pipe(Atom.withLabel("environment-presentations"));
124
125 + // Enabled environments only, like the full server-configs map, but without providers, so
126 + // capability checks on every sidebar row and markdown link skip provider status pushes.
127 + const serverConfigsAtom = Atom.make((get) => {
128 + const next = new Map<EnvironmentId, EnvironmentServerConfig>();
129 + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
130 + const serverConfig = get(presentationAtom(environmentId))?.serverConfig;
131 + if (serverConfig != null) {
132 + next.set(environmentId, serverConfig);
133 + }
134 + }
135 + const previous = Option.getOrNull(
136 + get.self<ReadonlyMap<EnvironmentId, EnvironmentServerConfig>>(),
137 + );
138 + return previous !== null && mapsEqual(previous, next) ? previous : next;
139 + }).pipe(Atom.withLabel("environment-server-configs-without-providers"));
140 +
141 + const providersByEnvironmentAtom = Atom.make((get) => {
142 + const next = new Map<EnvironmentId, ReadonlyArray<ServerProvider>>();
143 + for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
144 + const providers = get(input.serverConfigValueAtom(environmentId))?.providers;
145 + if (providers !== undefined) {
146 + next.set(environmentId, providers);
147 + }
148 + }
149 + const previous = Option.getOrNull(
150 + get.self<ReadonlyMap<EnvironmentId, ReadonlyArray<ServerProvider>>>(),
151 + );
152 + return previous !== null && mapsEqual(previous, next) ? previous : next;
153 + }).pipe(Atom.withLabel("environment-providers"));
154 +
155 + // Usage limits ride on provider statuses, so these surfaces rebuild on every push by design.
156 + const presentationsWithProvidersAtom = Atom.make((get) => {
157 + const previous = Option.getOrNull(
158 + get.self<ReadonlyMap<EnvironmentId, EnvironmentPresentationWithProviders>>(),
159 + );
160 + const next = new Map<EnvironmentId, EnvironmentPresentationWithProviders>();
161 + for (const [environmentId, presentation] of get(presentationsAtom)) {
162 + const serverConfig = get(input.serverConfigValueAtom(environmentId));
163 + const prior = previous?.get(environmentId);
164 + next.set(
165 + environmentId,
166 + prior !== undefined &&
167 + prior.entry === presentation.entry &&
168 + prior.connection === presentation.connection &&
169 + prior.serverConfig === serverConfig
170 + ? prior
171 + : { ...presentation, serverConfig },
172 + );
173 + }
174 + return previous !== null && mapsEqual(previous, next) ? previous : next;
175 + }).pipe(Atom.withLabel("environment-presentations-with-providers"));
176 +
177 return {
178 presentationAtom,
179 presentationsAtom,
180 + serverConfigsAtom,
181 + providersByEnvironmentAtom,
182 + presentationsWithProvidersAtom,
183 };
184 }
185
packages/shared/src/usageLimits.test.ts
+14 -3
@@ -558,6 +558,7 @@ describe("pools", () => {
558 {
559 ...laptop,
560 serverConfig: {
561 + providers: [],
562 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-1")] }],
563 },
564 },
@@ -567,6 +568,7 @@ describe("pools", () => {
568 {
569 ...laptop,
570 serverConfig: {
571 + providers: [],
572 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-2")] }],
573 },
574 },
@@ -652,10 +654,16 @@ describe("pools", () => {
654 };
655 const hub = { ...source, accounts: [seat] };
656 const input = new Map([
655 - [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { usageLimitSources: [hub] } }],
657 + [
658 + EnvironmentId.make("env-a"),
659 + { ...laptop, serverConfig: { providers: [], usageLimitSources: [hub] } },
660 + ],
661 [
662 EnvironmentId.make("env-b"),
658 - { entry: { target: { label: "Desktop" } }, serverConfig: { usageLimitSources: [hub] } },
663 + {
664 + entry: { target: { label: "Desktop" } },
665 + serverConfig: { providers: [], usageLimitSources: [hub] },
666 + },
667 ],
668 ]);
669 const accounts = collectLimitAccounts(input);
@@ -678,7 +686,10 @@ describe("pools", () => {
686 new Map([
687 [
688 EnvironmentId.make("env-a"),
681 - { ...laptop, serverConfig: { usageLimitSources: [{ ...source, accounts }] } },
689 + {
690 + ...laptop,
691 + serverConfig: { providers: [], usageLimitSources: [{ ...source, accounts }] },
692 + },
693 ],
694 ]),
695 ),
packages/shared/src/usageLimits.ts
+1 -1
@@ -67,7 +67,7 @@ export type LimitPresentations = ReadonlyMap<
67 {
68 readonly entry: { readonly target: { readonly label: string } };
69 readonly serverConfig: {
70 - readonly providers?: readonly ServerProvider[] | undefined;
70 + readonly providers: readonly ServerProvider[];
71 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
72 } | null;
73 }