TypeScript
perf(web): another thread streaming no longer re-renders the app root and thread panels (#20823)
Julius Marmingeedb21555667d
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 7fe50080852..518ff9b9c40 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -382,7 +382,7 @@ import {useThreadCheckpointSummaries,waitForThreadShell,} from "../state/entities";-import { environmentShell } from "../state/shell";+import { useEnvironmentShellHasSnapshot } from "../state/shell";import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";import { createPageScrollController, type PageScrollKey } from "./chat/pageScrollController";import { isTimelineScrollTarget } from "./chat/timelineScrollTarget";@@ -1881,10 +1881,9 @@ export default function ChatView(props: ChatViewProps) {});};const handleOpenDraftProjectSettingsStable = useStableCallback(handleOpenDraftProjectSettings);- const activeEnvironmentShell = useEnvironmentQuery(- activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null,+ const activeEnvironmentBootstrapComplete = useEnvironmentShellHasSnapshot(+ activeThread?.environmentId ?? null,);- const activeEnvironmentBootstrapComplete = activeEnvironmentShell.data?.snapshot._tag === "Some";const activeProjectKey = activeProject? `${activeProject.environmentId}:${activeProject.workspaceRoot}`: null;diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsxindex 143cb2f6440..bd77da3816e 100644--- a/apps/web/src/components/ThreadRouteView.tsx+++ b/apps/web/src/components/ThreadRouteView.tsx@@ -15,8 +15,7 @@ import {} from "../composerDraftStore";import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";import { useEnvironmentThreadRefs, useThreadRefs, useThreadShell } from "../state/entities";-import { useEnvironmentQuery } from "../state/query";-import { environmentShell } from "../state/shell";+import { useEnvironmentShellStatus } from "../state/shell";import {buildThreadRouteParams,isThreadRouteSnapshotAuthoritative,@@ -58,12 +57,10 @@ export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {}): null;- const shell = useEnvironmentQuery(- serverThreadRef === null ? null : environmentShell.stateAtom(serverThreadRef.environmentId),- );+ const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);const serverThreadShell = serverThread;const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);- const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shell.data?.status);+ const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);const draftThread = useComposerDraftStore((store) =>serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,);diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsxindex 251d694753a..594b857a016 100644--- a/apps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsx+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsx@@ -25,7 +25,10 @@ const state = vi.hoisted(() => ({vi.mock("@tanstack/react-router", () => ({ useNavigate: () => state.navigate }));vi.mock("../../state/entities", () => ({useThreadProjection: () => ({ projection: state.projection }),- useThreadShells: () => state.shells,+ useThreadRelationshipShells: (ref: { readonly environmentId: string }) =>+ (state.shells as ReadonlyArray<{ readonly environmentId: string; readonly source: unknown }>)+ .filter((shell) => shell.environmentId === ref.environmentId)+ .map((shell) => shell.source),useProjects: () => state.projects,useServerConfigs: () => state.configs,}));diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsxindex 10665e273fc..dad593c8018 100644--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx@@ -56,7 +56,7 @@ import {useProjects,useServerConfigs,useThreadProjection,- useThreadShells,+ useThreadRelationshipShells,} from "../../state/entities";import { threadEnvironment } from "../../state/threads";import { orchestrationEnvironment } from "../../state/orchestration";@@ -211,7 +211,7 @@ export function ThreadRelationshipsPanel(props: {const ref = scopeThreadRef(props.environmentId, props.threadId);const projection = useThreadProjection(ref)?.projection ?? null;const serverConfigs = useServerConfigs();- const threadShells = useThreadShells();+ const relationshipShells = useThreadRelationshipShells(ref);const allProjects = useProjects();const archived = useArchivedThreadSnapshots([props.environmentId]);const navigate = useNavigate();@@ -257,9 +257,7 @@ export function ThreadRelationshipsPanel(props: {deriveWorkflowGroups(runtimeSubagents).map((group) => [group.workflow.id, group]),);const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [- ...threadShells- .filter((thread) => thread.environmentId === props.environmentId)- .map((thread) => thread.source),+ ...relationshipShells,...(archivedShells ?? []),];const graph = deriveThreadRelationshipGraph({ threads: shells, projection });diff --git a/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx b/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsxindex 3e941e69dd5..0b76660e7f3 100644--- a/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx+++ b/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx@@ -9,8 +9,7 @@ import { newProjectId } from "../../lib/utils";import { readProjects, waitForProject } from "../../state/entities";import { usePrimaryEnvironment } from "../../state/environments";import { projectEnvironment } from "../../state/projects";-import { useEnvironmentQuery } from "../../state/query";-import { environmentShell } from "../../state/shell";+import { useEnvironmentShellHasSnapshot } from "../../state/shell";import { useAtomCommand } from "../../state/use-atom-command";export function DesktopAppActivationCoordinator() {@@ -19,16 +18,14 @@ export function DesktopAppActivationCoordinator() {const openThread = useNewThreadHandler();const queueRef = useRef(Promise.resolve());const activation = window.desktopBridge?.appActivation;- const shell = useEnvironmentQuery(- primaryEnvironment === null- ? null- : environmentShell.stateAtom(primaryEnvironment.environmentId),+ const shellHasSnapshot = useEnvironmentShellHasSnapshot(+ primaryEnvironment?.environmentId ?? null,);const ready =activation !== undefined &&primaryEnvironment?.connection.phase === "connected" &&primaryEnvironment.serverConfig !== null &&- shell.data?.snapshot._tag === "Some";+ shellHasSnapshot;const processRequest = useEffectEvent(async (request: DesktopAppActivationRequest) =>handleDesktopAppActivationRequest(request, {diff --git a/apps/web/src/components/onboarding/FirstRunGate.tsx b/apps/web/src/components/onboarding/FirstRunGate.tsxindex c76b5b1f7f3..ec5f92e0f58 100644--- a/apps/web/src/components/onboarding/FirstRunGate.tsx+++ b/apps/web/src/components/onboarding/FirstRunGate.tsx@@ -19,11 +19,7 @@ import {transitionFirstRunGateState,type FirstRunGateState,} from "../../onboarding/firstRun.logic";-import {- useAllEnvironmentShellsBootstrapped,- useProjects,- useThreadShells,-} from "../../state/entities";+import { useAllEnvironmentShellsBootstrapped, useProjects } from "../../state/entities";import { useEnvironments } from "../../state/environments";import { environmentProjects } from "../../state/projects";import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../../state/server";@@ -61,6 +57,18 @@ const workspaceEvidenceLiveAtom = Atom.make((get) => {return true;}).pipe(Atom.withLabel("web-onboarding-workspace-evidence-live"));+// The gate only needs how many threads exist and, while there is at most one,+// that thread; a shell update of any thread in a populated workspace must not+// re-render the app root.+const threadCountAtom = Atom.make(+ (get) => get(environmentThreadShells.threadShellsAtom).length,+).pipe(Atom.withLabel("web-onboarding-thread-count"));++const soleThreadAtom = Atom.make((get) => {+ const threads = get(environmentThreadShells.threadShellsAtom);+ return threads.length === 1 ? threads[0]! : null;+}).pipe(Atom.withLabel("web-onboarding-sole-thread"));+export function FirstRunGate({enabled,hostedStatic,@@ -79,7 +87,8 @@ export function FirstRunGate({const bootstrapped = useAllEnvironmentShellsBootstrapped();const { environments, isReady: environmentCatalogReady } = useEnvironments();const projects = useProjects();- const threads = useThreadShells();+ const threadCount = useAtomValue(threadCountAtom);+ const soleThread = useAtomValue(soleThreadAtom);const serverConfig = useAtomValue(primaryServerConfigAtom);const serverWelcome = useAtomValue(primaryServerWelcomeAtom);const primaryShellLive = useAtomValue(primaryShellLiveAtom);@@ -99,16 +108,18 @@ export function FirstRunGate({// would mean `npx t3` users never see the wizard.const serverCwd = serverConfig?.cwd ?? null;const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;- const workspaceFresh = isFreshFirstRunWorkspace({- primaryEnvironmentId,- serverCwd,- bootstrapProjectId: serverWelcome?.bootstrapProjectId,- bootstrapThreadId: serverWelcome?.bootstrapThreadId,- bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,- bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,- projects,- threads,- });+ const workspaceFresh =+ threadCount <= 1 &&+ isFreshFirstRunWorkspace({+ primaryEnvironmentId,+ serverCwd,+ bootstrapProjectId: serverWelcome?.bootstrapProjectId,+ bootstrapThreadId: serverWelcome?.bootstrapThreadId,+ bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,+ bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,+ projects,+ threads: soleThread === null ? [] : [soleThread],+ });const { decision: nextDecision, persistCompletion } = hostedStatic? resolveHostedFirstRunDecision({@@ -133,7 +144,7 @@ export function FirstRunGate({serverConfigAvailable: serverConfig !== null,workspaceFresh,projectCount: projects.length,- threadCount: threads.length,+ threadCount,});if (decision !== "wizard" && hydrated) {diff --git a/apps/web/src/hooks/useThreadVisitedMigration.ts b/apps/web/src/hooks/useThreadVisitedMigration.tsindex 56430d1354f..8728eaf9292 100644--- a/apps/web/src/hooks/useThreadVisitedMigration.ts+++ b/apps/web/src/hooks/useThreadVisitedMigration.ts@@ -1,17 +1,20 @@+import { RegistryContext } from "@effect/atom-react";import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";-import { useEffect } from "react";+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";+import { useContext, useEffect, useEffectEvent } from "react";-import { useThreadShells } from "../state/entities";-import { threadEnvironment } from "../state/threads";+import { environmentThreadShells, threadEnvironment } from "../state/threads";import { useAtomCommand } from "../state/use-atom-command";import { useUiStateStore } from "../uiStateStore";const migratedThreadKeys = new Set<string>();+// Subscribes outside render: the migration only acts on threads it has not+// seen, so a shell update must not re-render the layout that mounts it.export function useThreadVisitedMigration(): void {- const threads = useThreadShells();+ const registry = useContext(RegistryContext);const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });- useEffect(() => {+ const migrate = useEffectEvent((threads: ReadonlyArray<EnvironmentThreadShell>) => {for (const thread of threads) {// Field absent → the environment's server has no visited tracking; keep// the local value in play and reconsider if the server upgrades.@@ -30,5 +33,10 @@ export function useThreadVisitedMigration(): void {input: { threadId: thread.id, visitedAt: local },});}- }, [threads, visitThreadMutation]);+ });+ useEffect(+ () =>+ registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, { immediate: true }),+ [registry],+ );}diff --git a/apps/web/src/state/entities.relationshipShells.test.ts b/apps/web/src/state/entities.relationshipShells.test.tsnew file mode 100644index 00000000000..0a39f4a7865--- /dev/null+++ b/apps/web/src/state/entities.relationshipShells.test.ts@@ -0,0 +1,67 @@+import type {+ OrchestrationV2ThreadProjection,+ OrchestrationV2ThreadShell,+} from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { selectThreadRelationshipShells } from "./entities";++type Projection = Parameters<typeof selectThreadRelationshipShells>[1];++const shell = (id: string, parentThreadId: string | null = null) =>+ ({+ id,+ forkedFrom: null,+ lineage: { parentThreadId, relationshipToParent: parentThreadId === null ? null : "fork" },+ }) as unknown as OrchestrationV2ThreadShell;++const threadId = "current" as OrchestrationV2ThreadShell["id"];++describe("selectThreadRelationshipShells", () => {+ it("keeps the thread, its parent, its children and the threads its projection names", () => {+ const threads = [+ shell("current", "parent"),+ shell("parent"),+ shell("child", "current"),+ shell("subagent-child"),+ shell("workflow-member"),+ shell("transfer-source"),+ shell("unrelated"),+ shell("grandchild", "child"),+ ];+ const projection = {+ thread: threads[0],+ subagents: [+ {+ childThreadId: "subagent-child",+ workflow: { agents: [{ childThreadId: "workflow-member" }, {}] },+ },+ { childThreadId: null },+ ],+ contextTransfers: [{ sourceThreadId: "transfer-source", targetThreadId: "current" }],+ } as unknown as Pick<+ OrchestrationV2ThreadProjection,+ "thread" | "subagents" | "contextTransfers"+ >;++ expect(+ selectThreadRelationshipShells(threadId, projection, threads).map((thread) => thread.id),+ ).toEqual([+ "current",+ "parent",+ "child",+ "subagent-child",+ "workflow-member",+ "transfer-source",+ ]);+ });++ it("finds the parent from the shell before the projection loads", () => {+ const threads = [shell("current", "parent"), shell("parent"), shell("unrelated")];+ expect(+ selectThreadRelationshipShells(threadId, null as Projection, threads).map(+ (thread) => thread.id,+ ),+ ).toEqual(["current", "parent"]);+ });+});diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex a6dec362552..6e36bfa3cd2 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -9,8 +9,19 @@ import {type EnvironmentThreadStatus,type ThreadHistoryMeta,} from "@t3tools/client-runtime/state/threads";+import {+ arrayElementsEqual,+ parseThreadKey,+ threadKey,+} from "@t3tools/client-runtime/state/entities";import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";-import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";+import type {+ EnvironmentId,+ OrchestrationV2ProjectedTurnItem,+ OrchestrationV2ThreadProjection,+ OrchestrationV2ThreadShell,+ ThreadId,+} from "@t3tools/contracts";import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";import { Atom } from "effect/reactivity";import { appAtomRegistry } from "../rpc/atomRegistry";@@ -312,3 +323,70 @@ export function readEnvironmentThreadRefs(export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);}++function shellParentThreadId(+ thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,+): ThreadId | null {+ return thread.forkedFrom?.type === "run"+ ? thread.forkedFrom.threadId+ : thread.lineage.parentThreadId;+}++/**+ * The live shells the panel's immediate relationships can reach: the thread,+ * its parent, its children, and the threads its subagents, workflow members and+ * context transfers name. Keeps its array while those shells are unchanged, so+ * another thread streaming in the same environment does not re-render the panel.+ */+/** Exported for tests. */+export function selectThreadRelationshipShells(+ threadId: ThreadId,+ projection: Pick<+ OrchestrationV2ThreadProjection,+ "thread" | "subagents" | "contextTransfers"+ > | null,+ threads: ReadonlyArray<OrchestrationV2ThreadShell>,+): ReadonlyArray<OrchestrationV2ThreadShell> {+ const named = new Set<string>([threadId]);+ if (projection !== null) {+ const parentThreadId = shellParentThreadId(projection.thread);+ if (parentThreadId !== null) named.add(parentThreadId);+ for (const subagent of projection.subagents) {+ if (subagent.childThreadId !== null) named.add(subagent.childThreadId);+ for (const agent of subagent.workflow?.agents ?? []) {+ if (agent.childThreadId !== undefined) named.add(agent.childThreadId);+ }+ }+ for (const transfer of projection.contextTransfers) {+ named.add(transfer.sourceThreadId);+ named.add(transfer.targetThreadId);+ }+ }+ const current = threads.find((thread) => thread.id === threadId);+ const currentParentId = current === undefined ? null : shellParentThreadId(current);+ if (currentParentId !== null) named.add(currentParentId);+ return threads.filter(+ (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,+ );+}++const relationshipShellsAtomFamily = Atom.family((key: string) => {+ const ref = parseThreadKey(key);+ let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];+ return Atom.make((get) => {+ const next = selectThreadRelationshipShells(+ ref.threadId,+ get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,+ get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),+ );+ if (arrayElementsEqual(previous, next)) return previous;+ previous = next;+ return next;+ }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));+});++export function useThreadRelationshipShells(+ ref: ScopedThreadRef,+): ReadonlyArray<OrchestrationV2ThreadShell> {+ return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));+}diff --git a/apps/web/src/state/shell.ts b/apps/web/src/state/shell.tsindex e378a34ffd3..38269987e75 100644--- a/apps/web/src/state/shell.ts+++ b/apps/web/src/state/shell.ts@@ -7,12 +7,14 @@ import {createEnvironmentSnapshotAtom,createShellEnvironmentAtoms,type EnvironmentShellState,+ type EnvironmentShellStatus,} from "@t3tools/client-runtime/state/shell";import {type EnvironmentCatalogState,enabledEnvironmentIds,} from "@t3tools/client-runtime/state/connections";import type { EnvironmentId } from "@t3tools/contracts";+import { useAtomValue } from "@effect/atom-react";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/reactivity";@@ -24,6 +26,29 @@ export const shellEnvironment = createShellEnvironmentAtoms(connectionAtomRuntimexport const environmentShell = createEnvironmentShellAtoms(connectionAtomRuntime);export const environmentSnapshotAtom = createEnvironmentSnapshotAtom(environmentShell.stateAtom);+const NO_SHELL_STATUS_ATOM = Atom.make<EnvironmentShellStatus | null>(null).pipe(+ Atom.withLabel("web-environment-shell-status:none"),+);+const NO_SHELL_SNAPSHOT_ATOM = Atom.make(false).pipe(+ Atom.withLabel("web-environment-shell-has-snapshot:none"),+);++export function useEnvironmentShellStatus(+ environmentId: EnvironmentId | null,+): EnvironmentShellStatus | null {+ return useAtomValue(+ environmentId === null ? NO_SHELL_STATUS_ATOM : environmentShell.statusAtom(environmentId),+ );+}++export function useEnvironmentShellHasSnapshot(environmentId: EnvironmentId | null): boolean {+ return useAtomValue(+ environmentId === null+ ? NO_SHELL_SNAPSHOT_ATOM+ : environmentShell.hasSnapshotAtom(environmentId),+ );+}+export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => {const catalog = AsyncResult.value(get(environmentCatalog.catalogAtom));if (Option.isNone(catalog)) {diff --git a/apps/web/src/state/usePullRequestStack.ts b/apps/web/src/state/usePullRequestStack.tsindex 9d8ebffb698..2abd12c4416 100644--- a/apps/web/src/state/usePullRequestStack.ts+++ b/apps/web/src/state/usePullRequestStack.ts@@ -1,28 +1,39 @@-import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";+import { useAtomValue } from "@effect/atom-react";+import { ThreadPullRequestLink, type EnvironmentId, type PullRequestRef } from "@t3tools/contracts";+import { Atom } from "effect/reactivity";+import * as Schema from "effect/Schema";import {savedPullRequestStack,pullRequestStackView,} from "../components/pullRequest/pullRequestStackSnapshot";-import { useThreadShells } from "./entities";import { pullRequestStackAtom } from "./pullRequests";import { useEnvironmentQuery } from "./query";+import { environmentThreadShells } from "./threads";++const sameLinks = Schema.toEquivalence(Schema.Array(ThreadPullRequestLink));++// A shell update re-sends a thread's links as a new array, so equal links keep+// the previous list and a streaming thread does not re-render the stack.+const environmentPullRequestLinksAtom = Atom.family((environmentId: EnvironmentId) => {+ let previous: ReadonlyArray<ThreadPullRequestLink> = [];+ return Atom.make((get) => {+ const next = get(environmentThreadShells.environmentThreadsAtom(environmentId)).flatMap(+ (thread) => thread.pullRequests ?? [],+ );+ if (sameLinks(previous, next)) return previous;+ previous = next;+ return next;+ }).pipe(Atom.withLabel(`web-environment-pull-request-links:${environmentId}`));+});export function usePullRequestStack(environmentId: EnvironmentId,reference: PullRequestRef | null,) {- const threads = useThreadShells();+ const links = useAtomValue(environmentPullRequestLinksAtom(environmentId));+ const saved = reference === null ? null : savedPullRequestStack(links, reference);const query = useEnvironmentQuery(reference === null ? null : pullRequestStackAtom({ environmentId, input: reference }),);- const saved =- reference === null- ? null- : savedPullRequestStack(- threads- .filter((thread) => thread.environmentId === environmentId)- .flatMap((thread) => thread.pullRequests ?? []),- reference,- );return { ...query, ...pullRequestStackView(query, saved) };}diff --git a/apps/web/src/threadRoutes.ts b/apps/web/src/threadRoutes.tsindex 3be390e19b1..74d5a834a19 100644--- a/apps/web/src/threadRoutes.ts+++ b/apps/web/src/threadRoutes.ts@@ -22,7 +22,7 @@ type DraftThreadRouteState = {export type ThreadRouteRenderState = "loading" | "ready" | "missing";export function isThreadRouteSnapshotAuthoritative(- status: EnvironmentShellStatus | undefined,+ status: EnvironmentShellStatus | null | undefined,): boolean {return status === "live";}diff --git a/packages/client-runtime/src/state/shell.test.ts b/packages/client-runtime/src/state/shell.test.tsindex 7b39512fd97..0d88466d885 100644--- a/packages/client-runtime/src/state/shell.test.ts+++ b/packages/client-runtime/src/state/shell.test.ts@@ -7,7 +7,11 @@ import { Atom, AtomRegistry } from "effect/reactivity";import { PrimaryConnectionTarget } from "../connection/model.ts";import type { EnvironmentShellState } from "./shell.ts";-import { createEnvironmentServerConfigsAtom, createEnvironmentShellSummaryAtom } from "./shell.ts";+import {+ createEnvironmentServerConfigsAtom,+ createEnvironmentShellProgressAtoms,+ createEnvironmentShellSummaryAtom,+} from "./shell.ts";import { v2ThreadShell } from "./orchestrationV2TestFixtures.ts";const ENVIRONMENT_ID = EnvironmentId.make("environment-1");@@ -231,4 +235,35 @@ describe("environment shell projections", () => {harness.registry.set(harness.configAtom(ENVIRONMENT_ID), config);expect(harness.registry.get(harness.serverConfigsAtom)).toBe(withConfig);});++ it("keeps load progress quiet while threads stream and reports real progress", () => {+ const stateAtom = Atom.make(+ shellState({ status: "cached", updatedAt: "2026-06-01T00:00:00.000Z" }),+ );+ const registry = AtomRegistry.make();+ const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(() => stateAtom);+ let changes = 0;+ const unsubscribeStatus = registry.subscribe(statusAtom(ENVIRONMENT_ID), () => changes++);+ const unsubscribeSnapshot = registry.subscribe(+ hasSnapshotAtom(ENVIRONMENT_ID),+ () => changes++,+ );++ registry.set(+ stateAtom,+ shellState({ status: "cached", updatedAt: "2026-06-01T00:00:01.000Z" }),+ );+ expect(changes).toBe(0);++ registry.set(stateAtom, shellState({ status: "live", updatedAt: "2026-06-01T00:00:02.000Z" }));+ expect(registry.get(statusAtom(ENVIRONMENT_ID))).toBe("live");+ expect(changes).toBe(1);++ registry.set(stateAtom, shellState({ status: "live" }));+ expect(registry.get(hasSnapshotAtom(ENVIRONMENT_ID))).toBe(false);+ expect(changes).toBe(2);++ unsubscribeStatus();+ unsubscribeSnapshot();+ });});diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.tsindex 53132f627c1..12e5f19e899 100644--- a/packages/client-runtime/src/state/shell.ts+++ b/packages/client-runtime/src/state/shell.ts@@ -522,6 +522,27 @@ export function createEnvironmentServerConfigsAtom(input: {}).pipe(Atom.withLabel("environment-server-configs"));}+/**+ * Every shell push replaces the state, so views that gate on load progress read these+ * primitives instead and stay put while threads stream.+ */+export function createEnvironmentShellProgressAtoms(+ stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,+) {+ return {+ statusAtom: Atom.family((environmentId: EnvironmentId) =>+ Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(+ Atom.withLabel(`environment-shell-status:${environmentId}`),+ ),+ ),+ hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>+ Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(+ Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),+ ),+ ),+ };+}+export function createEnvironmentShellAtoms<R, E>(runtime: Atom.AtomRuntime<| EnvironmentRegistry.EnvironmentRegistry@@ -543,9 +564,13 @@ export function createEnvironmentShellAtoms<R, E>().pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),);+ const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);+return {stateAtom,stateValueAtom,+ statusAtom,+ hasSnapshotAtom,};}