diff --git a/apps/mobile/src/state/preview.ts b/apps/mobile/src/state/preview.ts index 3d5b87b4e31b8..19b3385928e3c 100644 --- a/apps/mobile/src/state/preview.ts +++ b/apps/mobile/src/state/preview.ts @@ -65,6 +65,8 @@ function applyEvent(current: ThreadPreviewTabs, event: PreviewEvent): ThreadPrev return { ...current, serverEpoch: event.serverEpoch, revision: event.revision, sessions }; } +const PREVIEW_TABS_IDLE_TTL_MS = 5 * 60_000; + const threadPreviewTabsAtom = Atom.family((threadKey: string) => { const ref = parseScopedThreadKey(threadKey); if (ref === null) return emptyTabsAtom; @@ -74,7 +76,6 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => { }); const eventsAtom = previewEnvironment.events({ environmentId: ref.environmentId, input: {} }); return Atom.make((get) => { - let disposed = false; let state = EMPTY_TABS; // Lists can land after events they predate; replay newer events on each list. let list: PreviewListResult | null = null; @@ -92,9 +93,6 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => { ); return events.reduce(applyEvent, { ...result, listed: true }); }; - get.addFinalizer(() => { - disposed = true; - }); get.subscribe(listAtom, (result) => { if (!AsyncResult.isSuccess(result)) return; const next = applyList(result.value); @@ -116,11 +114,11 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => { get.mount(eventsAtom); const cached = get.once(listAtom); if (AsyncResult.isSuccess(cached)) state = applyList(cached.value) ?? state; - queueMicrotask(() => { - if (!disposed) get.refresh(listAtom); - }); return state; - }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`mobile-preview-tabs:${threadKey}`)); + }).pipe( + Atom.setIdleTTL(PREVIEW_TABS_IDLE_TTL_MS), + Atom.withLabel(`mobile-preview-tabs:${threadKey}`), + ); }); interface ServerBrowserTabs { @@ -142,7 +140,7 @@ const serverBrowserTabsAtom = Atom.family((threadKey: string) => tabs: tabs.sessions.filter((session) => session.runtime === "server"), loaded: tabs.listed, }; - }).pipe(Atom.withEquality(sameServerBrowserTabs), Atom.setIdleTTL(1_000)), + }).pipe(Atom.withEquality(sameServerBrowserTabs), Atom.setIdleTTL(PREVIEW_TABS_IDLE_TTL_MS)), ); const emptyServerBrowserTabsAtom = Atom.make({ tabs: [], loaded: false }); const serverBrowserTabCountAtom = Atom.family((threadKey: string) => diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 69748fb95ba3e..b63a166bd04e8 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -229,7 +229,6 @@ import { threadHandoffSendBlockReason, useThreadHandoffBannerItem, } from "./chat/ThreadHandoffBanner"; -import { useDeviceState } from "~/state/device"; import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar"; import { ComposerContextPermissions } from "./ComposerContextPermissions"; import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; @@ -2282,9 +2281,6 @@ export default function ChatView(props: ChatViewProps) { const linkedItemsSurfaceAvailable = pullRequestsSurfaceAvailable || (isServerThread && (activeThreadShell?.issues?.length ?? 0) > 0); - const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState( - activeThreadRef?.environmentId ?? null, - ); // The thread's own change request, placed against the project it belongs to. Without a // project there is nothing to resolve it against, so the caller falls back to the browser. const activeProjectRepository = sourceControlClients.repositorySelector( @@ -2710,8 +2706,7 @@ export default function ChatView(props: ChatViewProps) { activeProject, activeRightPanelSurface, activePreviewState, - deviceState, - deviceStateLoaded, + serverSettings: serverConfig?.settings ?? null, pullRequestPanelTarget, threadPanelPresentation, isServerThread, @@ -3719,11 +3714,7 @@ export default function ChatView(props: ChatViewProps) { className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background" > {embedded ? null : ( - + )} {rightPanelControlsAtRoot && !embedded ? panelLayoutControls : null}
{ + useRightPanelStore.getState().open(props.threadRef, "device"); + closeThreadOverlay(deviceSetupDialogAtom); + }} + /> + ); +} + export function DeviceSetupDialogHost(props: { readonly threadKey: string | null; readonly threadRef: ScopedThreadRef | null; - readonly state: DeviceServiceState; }) { const open = useThreadOverlay(deviceSetupDialogAtom, props.threadKey) !== null; const { threadRef } = props; @@ -123,16 +136,7 @@ export function DeviceSetupDialogHost(props: { }} > - {threadRef ? ( - { - useRightPanelStore.getState().open(threadRef, "device"); - closeThreadOverlay(deviceSetupDialogAtom); - }} - /> - ) : null} + {open && threadRef ? : null} ); diff --git a/apps/web/src/components/chat/ThreadDetailsMachineLoad.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsMachineLoad.browser.test.tsx index 3c074558ff627..df1ffd184aaa5 100644 --- a/apps/web/src/components/chat/ThreadDetailsMachineLoad.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsMachineLoad.browser.test.tsx @@ -1,13 +1,15 @@ import { EnvironmentId, type HostResourcesSnapshot } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { render } from "../../../test/render"; +import { act, render } from "../../../test/render"; +import { HiddenThreadContext } from "./backgroundThread"; import { ThreadDetailsMachineLoad } from "./ThreadDetailsMachineLoad"; const environmentId = EnvironmentId.make("studio"); const state = vi.hoisted(() => ({ phase: "connected", sample: null as unknown, + resourcesReads: 0, presentationsAtom: Symbol("presentationsAtom"), resourcesAtom: Symbol("resourcesAtom"), })); @@ -41,6 +43,7 @@ vi.mock("@effect/atom-react", async (importOriginal) => { ...actual, useAtomValue: (atom: unknown, select?: (value: unknown) => unknown) => { if (atom === state.resourcesAtom) { + state.resourcesReads += 1; return state.sample === null ? { _tag: "Initial", waiting: true } : { _tag: "Success", value: state.sample, waiting: false }; @@ -49,7 +52,7 @@ vi.mock("@effect/atom-react", async (importOriginal) => { const presentations = new Map([[environmentId, { connection: { phase: state.phase } }]]); return select ? select(presentations) : presentations; } - return (actual.useAtomValue as (...args: ReadonlyArray) => unknown)(atom, select); + return { _tag: "Initial", waiting: false }; }, }; }); @@ -84,4 +87,66 @@ describe("ThreadDetailsMachineLoad", () => { await screen.rerender(); expect(screen.container.textContent).toContain("17%"); }); + + it("stops reading liveHostResources while the thread is hidden and resumes when visible", async () => { + state.phase = "connected"; + state.sample = sample(0.42); + state.resourcesReads = 0; + await using screen = await render( + + + , + ); + expect(screen.container.textContent).toBe(""); + expect(state.resourcesReads).toBe(0); + + await screen.rerender( + + + , + ); + expect(screen.container.textContent).toContain("42%"); + const readsWhileVisible = state.resourcesReads; + expect(readsWhileVisible).toBeGreaterThan(0); + + await screen.rerender( + + + , + ); + expect(screen.container.textContent).toBe(""); + expect(state.resourcesReads).toBe(readsWhileVisible); + }); + + it("stops reading liveHostResources when the document is hidden and resumes on visibilitychange", async () => { + state.phase = "connected"; + state.sample = sample(0.35); + state.resourcesReads = 0; + let visibilityState: DocumentVisibilityState = "visible"; + const spy = vi + .spyOn(document, "visibilityState", "get") + .mockImplementation(() => visibilityState); + try { + await using screen = await render(); + expect(screen.container.textContent).toContain("35%"); + const readsWhileVisible = state.resourcesReads; + expect(readsWhileVisible).toBeGreaterThan(0); + + visibilityState = "hidden"; + await act(() => { + document.dispatchEvent(new Event("visibilitychange")); + }); + expect(screen.container.textContent).toBe(""); + expect(state.resourcesReads).toBe(readsWhileVisible); + + visibilityState = "visible"; + await act(() => { + document.dispatchEvent(new Event("visibilitychange")); + }); + expect(screen.container.textContent).toContain("35%"); + expect(state.resourcesReads).toBeGreaterThan(readsWhileVisible); + } finally { + spy.mockRestore(); + } + }); }); diff --git a/apps/web/src/components/chat/ThreadDetailsMachineLoad.tsx b/apps/web/src/components/chat/ThreadDetailsMachineLoad.tsx index 5d50f8cf113bc..c0ae2095d3197 100644 --- a/apps/web/src/components/chat/ThreadDetailsMachineLoad.tsx +++ b/apps/web/src/components/chat/ThreadDetailsMachineLoad.tsx @@ -2,18 +2,37 @@ import { useAtomValue } from "@effect/atom-react"; import { type EnvironmentId, type HostPressureLevel, + type HostResourcesSnapshot, worstHostPressureLevel, } from "@t3tools/contracts"; +import { AsyncResult, Atom } from "effect/reactivity"; import { useGT, plural, part } from "gt-react"; -import { useState } from "react"; +import { use, useState, useSyncExternalStore } from "react"; import { formatBytes } from "../../lib/formatBytes"; import { useServerConfigs } from "../../state/entities"; import { environmentPresentations } from "../../state/presentation"; import { serverEnvironment } from "../../state/server"; +import { HiddenThreadContext } from "./backgroundThread"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; import { UsageRow, type UsageTone } from "./ThreadDetailsUsage"; +const IDLE_HOST_RESOURCES_ATOM = Atom.make( + AsyncResult.initial(), +).pipe(Atom.withLabel("thread-details:machine-load:idle")); + +function subscribeDocumentVisibility(onStoreChange: () => void): () => void { + if (typeof document === "undefined") return () => {}; + document.addEventListener("visibilitychange", onStoreChange); + return () => document.removeEventListener("visibilitychange", onStoreChange); +} + +function readDocumentVisible(): boolean { + return typeof document === "undefined" || document.visibilityState !== "hidden"; +} + +const readServerDocumentVisible = () => true; + const toneOf = (level: HostPressureLevel | undefined): UsageTone => level === "severe" ? "error" : level === "elevated" ? "warning" : null; @@ -26,7 +45,18 @@ export function ThreadDetailsMachineLoad({ readonly environmentId: EnvironmentId; }) { const gt = useGT(); - const result = useAtomValue(serverEnvironment.liveHostResources({ environmentId, input: {} })); + const hiddenThread = use(HiddenThreadContext); + const documentVisible = useSyncExternalStore( + subscribeDocumentVisibility, + readDocumentVisible, + readServerDocumentVisible, + ); + const pollingActive = !hiddenThread && documentVisible; + const result = useAtomValue( + pollingActive + ? serverEnvironment.liveHostResources({ environmentId, input: {} }) + : IDLE_HOST_RESOURCES_ATOM, + ); const pressure = useServerConfigs().get(environmentId)?.hostPressure; const connected = useAtomValue( environmentPresentations.presentationsAtom, diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 95c38dc3cb8a0..2e1dc902f13f5 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -7,7 +7,12 @@ import type { ThreadPreviewState } from "../../previewStateStore"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { useStableCallback } from "../../hooks/useStableCallback"; -import { type ScopedThreadRef, type PreviewSessionSnapshot } from "@t3tools/contracts"; +import { + type DeviceServiceState, + type ScopedThreadRef, + type PreviewSessionSnapshot, + type ServerSettings, +} from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { sideThreadComposer, sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; import { readThreadShell } from "../../state/entities"; @@ -37,7 +42,7 @@ import { } from "../preview/agentOpenedPreviews"; import { getClientSettings } from "../../hooks/useSettings"; import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic"; -import type { useDeviceState } from "../../state/device"; +import { readLoadedDeviceState } from "../../state/device"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { openDeviceSetupDialog } from "./ChatOverlayHosts"; import { previewEnvironment } from "../../state/preview"; @@ -48,8 +53,7 @@ interface RightPanelActionsInput { readonly activeProject: EnvironmentProject | null; readonly activeRightPanelSurface: RightPanelSurface | null; readonly activePreviewState: ThreadPreviewState; - readonly deviceState: ReturnType["state"]; - readonly deviceStateLoaded: boolean; + readonly serverSettings: ServerSettings | null; readonly pullRequestPanelTarget: ReturnType | null; readonly threadPanelPresentation: ThreadPanelPresentation; readonly isServerThread: boolean; @@ -71,6 +75,15 @@ interface RightPanelActionsInput { readonly onDiffPanelOpen: (() => void) | undefined; } +export function needsDeviceSetup( + loadedState: Pick | null, + serverSettings: Pick | null, +): boolean { + return loadedState !== null + ? !loadedState.onboardingCompleted || loadedState.hostStatus === "disabled" + : !serverSettings?.enableDeviceSupport || !serverSettings.deviceOnboardingCompleted; +} + /** * Opening, closing, and arranging the right panel's surfaces: browser, diff, files, pull * requests, device, and terminal tabs. @@ -81,8 +94,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { activeProject, activeRightPanelSurface, activePreviewState, - deviceState, - deviceStateLoaded, + serverSettings, pullRequestPanelTarget, threadPanelPresentation, isServerThread, @@ -163,7 +175,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface); const addDeviceSurface = () => { if (!activeThreadRef) return; - if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") { + if (needsDeviceSetup(readLoadedDeviceState(activeThreadRef.environmentId), serverSettings)) { openDeviceSetupDialog(scopedThreadKey(activeThreadRef)); return; } @@ -182,7 +194,8 @@ export function useRightPanelActions(input: RightPanelActionsInput) { floatPanelSurfaceOnClose(activeThreadRef, source, { autoShowFloatingPreview: getClientSettings().browserAutoShowFloatingPreview, previewState: activePreviewState, - deviceState: deviceStateLoaded ? deviceState : null, + deviceState: + source.kind === "device" ? readLoadedDeviceState(activeThreadRef.environmentId) : null, }); } useRightPanelStore.getState().setMaximized(activeThreadRef, false); diff --git a/apps/web/src/components/desktop/RunningThreadKeepAlive.tsx b/apps/web/src/components/desktop/RunningThreadKeepAlive.tsx deleted file mode 100644 index 38063ddb88dc6..0000000000000 --- a/apps/web/src/components/desktop/RunningThreadKeepAlive.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { useAtomMount } from "@effect/atom-react"; - -import { runningThreadKeepAliveAtom } from "../../state/threads"; - -export function RunningThreadKeepAlive() { - useAtomMount(runningThreadKeepAliveAtom); - return null; -} diff --git a/apps/web/src/components/preview/agentOpenedPreviews.test.ts b/apps/web/src/components/preview/agentOpenedPreviews.test.ts index 57cfe676063e3..d317989c82c8d 100644 --- a/apps/web/src/components/preview/agentOpenedPreviews.test.ts +++ b/apps/web/src/components/preview/agentOpenedPreviews.test.ts @@ -3,8 +3,10 @@ import { type DeviceServiceState, type EnvironmentId, type PreviewSessionSnapshot, + type ServerConfig, ThreadId, } from "@t3tools/contracts"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore"; @@ -29,7 +31,9 @@ import { followPreviewSessions, resetDeviceSessionBaselinesForTests, revealServerTabs, + shouldWatchEnvironmentDevices, startAgentOpenedPreviews, + startEnvironmentDeviceWatches, } from "./agentOpenedPreviews"; vi.mock("../../state/entities", () => ({ @@ -511,3 +515,203 @@ describe("startAgentOpenedPreviews", () => { expect(floatingTabId()).toBeNull(); }); }); + +describe("startEnvironmentDeviceWatches", () => { + const configWithDeviceSettings = (input: { + readonly enableDeviceSupport: boolean; + readonly enableAgentDeviceAccess: boolean; + }) => + ({ + settings: input, + }) as unknown as ServerConfig; + + it("watches an environment only when agent device access is enabled or a device is floating", () => { + expect(shouldWatchEnvironmentDevices(undefined, false)).toBe(false); + expect( + shouldWatchEnvironmentDevices( + configWithDeviceSettings({ enableDeviceSupport: false, enableAgentDeviceAccess: true }), + false, + ), + ).toBe(false); + expect( + shouldWatchEnvironmentDevices( + configWithDeviceSettings({ enableDeviceSupport: true, enableAgentDeviceAccess: false }), + false, + ), + ).toBe(false); + expect( + shouldWatchEnvironmentDevices( + configWithDeviceSettings({ enableDeviceSupport: true, enableAgentDeviceAccess: true }), + false, + ), + ).toBe(true); + expect(shouldWatchEnvironmentDevices(undefined, true)).toBe(true); + }); + + it("stays quiet when device access is off and starts/stops dynamically with settings and floating devices", () => { + setup(); + const registry = AtomRegistry.make(); + const connectedEnvironmentIdsAtom = Atom.make>([ + ref.environmentId, + ]).pipe(Atom.keepAlive); + const serverConfigsAtom = Atom.make>( + new Map([ + [ + ref.environmentId, + configWithDeviceSettings({ + enableDeviceSupport: false, + enableAgentDeviceAccess: false, + }), + ], + ]), + ).pipe(Atom.keepAlive); + + const active = new Set(); + const watchEnvironment = vi.fn((environmentId: EnvironmentId) => { + active.add(environmentId); + return () => { + active.delete(environmentId); + }; + }); + + const stop = startEnvironmentDeviceWatches({ + registry, + connectedEnvironmentIdsAtom, + serverConfigsAtom, + watchEnvironment, + }); + + expect(watchEnvironment).not.toHaveBeenCalled(); + expect([...active]).toEqual([]); + + registry.set( + serverConfigsAtom, + new Map([ + [ + ref.environmentId, + configWithDeviceSettings({ + enableDeviceSupport: true, + enableAgentDeviceAccess: false, + }), + ], + ]), + ); + expect(watchEnvironment).not.toHaveBeenCalled(); + + usePreviewMiniPlayerStore.getState().open(ref, { + kind: "device", + hostId: "local", + deviceId: "pixel", + platform: "android", + name: "Pixel 8", + }); + expect(watchEnvironment).toHaveBeenCalledTimes(1); + expect([...active]).toEqual([ref.environmentId]); + + usePreviewMiniPlayerStore.getState().close(ref); + expect([...active]).toEqual([]); + + registry.set( + serverConfigsAtom, + new Map([ + [ + ref.environmentId, + configWithDeviceSettings({ + enableDeviceSupport: true, + enableAgentDeviceAccess: true, + }), + ], + ]), + ); + expect(watchEnvironment).toHaveBeenCalledTimes(2); + expect([...active]).toEqual([ref.environmentId]); + + registry.set(connectedEnvironmentIdsAtom, []); + expect([...active]).toEqual([]); + + stop(); + registry.dispose(); + }); + + it("clears the baseline when demand ends but preserves it across transient disconnects", () => { + setup(); + const otherRef = scopeThreadRef(ref.environmentId, ThreadId.make("thread-2")); + const otherSession = { ...session, threadId: otherRef.threadId }; + const registry = AtomRegistry.make(); + const connectedEnvironmentIdsAtom = Atom.make>([ + ref.environmentId, + ]).pipe(Atom.keepAlive); + const serverConfigsAtom = Atom.make>( + new Map([ + [ + ref.environmentId, + configWithDeviceSettings({ + enableDeviceSupport: true, + enableAgentDeviceAccess: false, + }), + ], + ]), + ).pipe(Atom.keepAlive); + const stop = startEnvironmentDeviceWatches({ + registry, + connectedEnvironmentIdsAtom, + serverConfigsAtom, + watchEnvironment: () => () => {}, + }); + + usePreviewMiniPlayerStore.getState().open(ref, { + kind: "device", + hostId: "local", + deviceId: "pixel", + platform: "android", + name: "Pixel 8", + }); + applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating); + + usePreviewMiniPlayerStore.getState().close(ref); + usePreviewMiniPlayerStore.getState().open(ref, { + kind: "device", + hostId: "local", + deviceId: "pixel", + platform: "android", + name: "Pixel 8", + }); + applyDeviceSnapshot( + ref.environmentId, + deviceState({ sessions: [session, otherSession] }), + floating, + ); + expect( + usePreviewMiniPlayerStore.getState().byThreadKey[scopedThreadKey(otherRef)], + ).toBeUndefined(); + + usePreviewMiniPlayerStore.getState().close(ref); + registry.set( + serverConfigsAtom, + new Map([ + [ + ref.environmentId, + configWithDeviceSettings({ + enableDeviceSupport: true, + enableAgentDeviceAccess: true, + }), + ], + ]), + ); + applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating); + + registry.set(connectedEnvironmentIdsAtom, []); + registry.set(connectedEnvironmentIdsAtom, [ref.environmentId]); + applyDeviceSnapshot( + ref.environmentId, + deviceState({ sessions: [session, otherSession] }), + floating, + ); + expect( + usePreviewMiniPlayerStore.getState().byThreadKey[scopedThreadKey(otherRef)]?.source, + ).toMatchObject({ kind: "device", deviceId: "pixel" }); + + stop(); + registry.dispose(); + }); +}); diff --git a/apps/web/src/components/preview/agentOpenedPreviews.ts b/apps/web/src/components/preview/agentOpenedPreviews.ts index 0aef7466062a0..e8351192d44f0 100644 --- a/apps/web/src/components/preview/agentOpenedPreviews.ts +++ b/apps/web/src/components/preview/agentOpenedPreviews.ts @@ -8,9 +8,10 @@ import type { EnvironmentId, PreviewSessionSnapshot, ScopedThreadRef, + ServerConfig, ThreadId, } from "@t3tools/contracts"; -import { AsyncResult } from "effect/reactivity"; +import { AsyncResult, type Atom, type AtomRegistry } from "effect/reactivity"; import { getClientSettings } from "../../hooks/useSettings"; import { @@ -35,6 +36,7 @@ import { appAtomRegistry } from "../../rpc/atomRegistry"; import { deviceEnvironment } from "../../state/device"; import { readEnvironmentSupportsServerBrowser } from "../../state/entities"; import { environmentSummaries } from "../../state/presentation"; +import { environmentServerConfigsAtom } from "../../state/server"; /** * Shows browsers an agent or another client revealed for a thread: floating @@ -276,6 +278,17 @@ export function resetDeviceSessionBaselinesForTests(): void { deviceSessionBaselines.clear(); } +export function shouldWatchEnvironmentDevices( + config: ServerConfig | undefined, + hasFloatingDevice: boolean, +): boolean { + return ( + hasFloatingDevice || + (config?.settings.enableDeviceSupport === true && + config.settings.enableAgentDeviceAccess === true) + ); +} + function watchEnvironmentDevices(environmentId: EnvironmentId): () => void { return appAtomRegistry.subscribe( deviceEnvironment.state({ environmentId, input: {} }), @@ -291,10 +304,75 @@ function watchEnvironmentDevices(environmentId: EnvironmentId): () => void { ); } +export function startEnvironmentDeviceWatches(deps: { + readonly registry: AtomRegistry.AtomRegistry; + readonly connectedEnvironmentIdsAtom: Atom.Atom>; + readonly serverConfigsAtom: Atom.Atom>; + readonly watchEnvironment: (environmentId: EnvironmentId) => () => void; +}): () => void { + const watchedEnvironments = new Map void>(); + const syncWatchedEnvironments = () => { + const connectedIds = deps.registry.get(deps.connectedEnvironmentIdsAtom); + const serverConfigs = deps.registry.get(deps.serverConfigsAtom); + const floatingEnvironments = new Set(); + for (const [threadKey, entry] of Object.entries( + usePreviewMiniPlayerStore.getState().byThreadKey, + )) { + if (entry.source.kind !== "device") continue; + const ref = parseScopedThreadKey(threadKey); + if (ref !== null) floatingEnvironments.add(ref.environmentId); + } + const desired = new Set(); + for (const environmentId of connectedIds) { + if ( + shouldWatchEnvironmentDevices( + serverConfigs.get(environmentId), + floatingEnvironments.has(environmentId), + ) + ) { + desired.add(environmentId); + } + } + for (const [environmentId, stop] of watchedEnvironments) { + if (desired.has(environmentId)) continue; + stop(); + watchedEnvironments.delete(environmentId); + // Keep the baseline across transient disconnects while watching stays enabled, + // but clear it when demand ends so a later restart does not diff against stale sessions. + if ( + !shouldWatchEnvironmentDevices( + serverConfigs.get(environmentId), + floatingEnvironments.has(environmentId), + ) + ) { + deviceSessionBaselines.delete(environmentId); + } + } + for (const environmentId of desired) { + if (!watchedEnvironments.has(environmentId)) { + watchedEnvironments.set(environmentId, deps.watchEnvironment(environmentId)); + } + } + }; + const stopEnvironments = deps.registry.subscribe( + deps.connectedEnvironmentIdsAtom, + syncWatchedEnvironments, + ); + const stopConfigs = deps.registry.subscribe(deps.serverConfigsAtom, syncWatchedEnvironments); + const stopMiniPlayers = usePreviewMiniPlayerStore.subscribe(syncWatchedEnvironments); + syncWatchedEnvironments(); + return () => { + stopEnvironments(); + stopConfigs(); + stopMiniPlayers(); + for (const stop of watchedEnvironments.values()) stop(); + }; +} + /** - * Follows every thread's browser previews and every connected environment's - * device sessions for the life of the page, not just the open thread's: an - * agent in a background thread can open either. + * Follows every thread's browser previews and connected environments whose + * agent device access is enabled (or that currently float a device): an agent + * in a background thread can open either. */ export function startAgentOpenedPreviews(): () => void { const followed = new Map void>(); @@ -306,28 +384,15 @@ export function startAgentOpenedPreviews(): () => void { const stopIndex = appAtomRegistry.subscribe(previewThreadRefsAtom, followNewThreads, { immediate: true, }); - const watchedEnvironments = new Map void>(); - const watchConnectedEnvironments = (environmentIds: ReadonlyArray) => { - for (const [environmentId, stop] of watchedEnvironments) { - if (environmentIds.includes(environmentId)) continue; - stop(); - watchedEnvironments.delete(environmentId); - } - for (const environmentId of environmentIds) { - if (!watchedEnvironments.has(environmentId)) { - watchedEnvironments.set(environmentId, watchEnvironmentDevices(environmentId)); - } - } - }; - const stopEnvironments = appAtomRegistry.subscribe( - environmentSummaries.connectedEnvironmentIdsAtom, - watchConnectedEnvironments, - { immediate: true }, - ); + const stopDeviceWatches = startEnvironmentDeviceWatches({ + registry: appAtomRegistry, + connectedEnvironmentIdsAtom: environmentSummaries.connectedEnvironmentIdsAtom, + serverConfigsAtom: environmentServerConfigsAtom, + watchEnvironment: watchEnvironmentDevices, + }); return () => { stopIndex(); - stopEnvironments(); + stopDeviceWatches(); for (const stop of followed.values()) stop(); - for (const stop of watchedEnvironments.values()) stop(); }; } diff --git a/apps/web/src/components/preview/usePreviewSession.test.ts b/apps/web/src/components/preview/usePreviewSession.test.ts new file mode 100644 index 0000000000000..7b22cf9cc6bc5 --- /dev/null +++ b/apps/web/src/components/preview/usePreviewSession.test.ts @@ -0,0 +1,164 @@ +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + EnvironmentId, + type PreviewEvent, + type PreviewListResult, + type PreviewSessionSnapshot, + ThreadId, +} from "@t3tools/contracts"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { readThreadPreviewState, resetPreviewStateForTests } from "~/previewStateStore"; +import { createPreviewSessionSyncAtom } from "./usePreviewSession"; + +const ENV = EnvironmentId.make("env-preview-sync"); +const THREAD_A = scopeThreadRef(ENV, ThreadId.make("thread-a")); +const THREAD_B = scopeThreadRef(ENV, ThreadId.make("thread-b")); + +function makeSnapshot(threadId: string, tabId: string): PreviewSessionSnapshot { + return { + threadId, + tabId, + navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" }, + canGoBack: false, + canGoForward: false, + updatedAt: "2026-01-01T00:00:00.000Z", + runtime: "server", + reveal: true, + }; +} + +function makeHarness(idleTtlMs = 5 * 60_000) { + const listCalls = new Map(); + const listResults = new Map(); + const eventsAtom = Atom.make>( + AsyncResult.initial(), + ).pipe(Atom.keepAlive); + + const listFamily = Atom.family((threadId: string) => + Atom.make((): AsyncResult.AsyncResult => { + listCalls.set(threadId, (listCalls.get(threadId) ?? 0) + 1); + return AsyncResult.success( + listResults.get(threadId) ?? { + sessions: [], + serverEpoch: "epoch-1", + revision: 1, + }, + ); + }).pipe(Atom.setIdleTTL(0)), + ); + + const syncAtom = createPreviewSessionSyncAtom({ + list: ({ input }) => listFamily(input.threadId), + events: () => eventsAtom, + idleTtlMs, + }); + + const registry = AtomRegistry.make(); + return { + registry, + syncAtom, + eventsAtom, + listCalls, + listResults, + listCount: (threadId: ThreadId) => listCalls.get(threadId) ?? 0, + }; +} + +afterEach(() => { + resetPreviewStateForTests(); + vi.useRealTimers(); +}); + +describe("createPreviewSessionSyncAtom", () => { + it("avoids redundant preview.list refreshes across thread switches while still applying live events", async () => { + vi.useFakeTimers(); + const h = makeHarness(); + + const unmountA = h.registry.mount(h.syncAtom(scopedThreadKey(THREAD_A))); + await Promise.resolve(); + expect(h.listCount(THREAD_A.threadId)).toBe(1); + expect(readThreadPreviewState(THREAD_A).listLoaded).toBe(true); + + unmountA(); + const unmountB = h.registry.mount(h.syncAtom(scopedThreadKey(THREAD_B))); + await Promise.resolve(); + expect(h.listCount(THREAD_B.threadId)).toBe(1); + + await vi.advanceTimersByTimeAsync(30_000); + + const agentTab = makeSnapshot(THREAD_A.threadId, "tab_agent"); + h.registry.set( + h.eventsAtom, + AsyncResult.success({ + type: "opened", + threadId: THREAD_A.threadId, + tabId: agentTab.tabId, + createdAt: agentTab.updatedAt, + snapshot: agentTab, + serverEpoch: "epoch-1", + revision: 2, + }), + ); + expect(readThreadPreviewState(THREAD_A).sessions.tab_agent).toEqual(agentTab); + + unmountB(); + const remountA = h.registry.mount(h.syncAtom(scopedThreadKey(THREAD_A))); + await Promise.resolve(); + expect(h.listCount(THREAD_A.threadId)).toBe(1); + expect(h.listCount(THREAD_B.threadId)).toBe(1); + + h.listResults.set(THREAD_A.threadId, { + sessions: [makeSnapshot(THREAD_A.threadId, "tab_after_restart")], + serverEpoch: "epoch-2", + revision: 1, + }); + h.registry.set( + h.eventsAtom, + AsyncResult.success({ + type: "opened", + threadId: THREAD_A.threadId, + tabId: "tab_after_restart", + createdAt: "2026-01-01T00:01:00.000Z", + snapshot: makeSnapshot(THREAD_A.threadId, "tab_after_restart"), + serverEpoch: "epoch-2", + revision: 1, + }), + ); + await Promise.resolve(); + expect(h.listCount(THREAD_A.threadId)).toBe(2); + expect(readThreadPreviewState(THREAD_A).serverEpoch).toBe("epoch-2"); + + remountA(); + h.registry.dispose(); + }); + + it("refetches once after the idle TTL expires and the thread is visited again", async () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const h = makeHarness(10_000); + + const unmountA = h.registry.mount(h.syncAtom(scopedThreadKey(THREAD_A))); + await Promise.resolve(); + expect(h.listCount(THREAD_A.threadId)).toBe(1); + + unmountA(); + await vi.advanceTimersByTimeAsync(60_000); + await Promise.resolve(); + + const tabAfterExpiry = makeSnapshot(THREAD_A.threadId, "tab_after_expiry"); + h.listResults.set(THREAD_A.threadId, { + sessions: [tabAfterExpiry], + serverEpoch: "epoch-1", + revision: 2, + }); + const remountA = h.registry.mount(h.syncAtom(scopedThreadKey(THREAD_A))); + await Promise.resolve(); + expect(h.listCount(THREAD_A.threadId)).toBe(2); + expect(readThreadPreviewState(THREAD_A).sessions.tab_after_expiry).toEqual(tabAfterExpiry); + + remountA(); + h.registry.dispose(); + }); +}); diff --git a/apps/web/src/components/preview/usePreviewSession.ts b/apps/web/src/components/preview/usePreviewSession.ts index cdd63493f9042..12739e062b318 100644 --- a/apps/web/src/components/preview/usePreviewSession.ts +++ b/apps/web/src/components/preview/usePreviewSession.ts @@ -4,7 +4,13 @@ import { scopeThreadRef, scopedThreadKey, } from "@t3tools/client-runtime/environment"; -import { type EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { + type EnvironmentId, + type PreviewEvent, + type PreviewListResult, + type ScopedThreadRef, + ThreadId, +} from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -26,71 +32,85 @@ class PreviewSessionThreadKeyParseError extends Schema.TaggedError { - const threadRef = parseScopedThreadKey(threadKey); - if (threadRef === null) { - throw new PreviewSessionThreadKeyParseError({ threadKey }); - } +const PREVIEW_SESSION_SYNC_IDLE_TTL_MS = 5 * 60_000; - const sessionsAtom = previewEnvironment.list({ - environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId }, - }); - const eventsAtom = previewEnvironment.events({ - environmentId: threadRef.environmentId, - input: {}, - }); +export function createPreviewSessionSyncAtom(deps: { + readonly list: (target: { + readonly environmentId: EnvironmentId; + readonly input: { readonly threadId: ThreadId }; + }) => Atom.Atom>; + readonly events: (target: { + readonly environmentId: EnvironmentId; + readonly input: Record; + }) => Atom.Atom>; + readonly idleTtlMs?: number; +}) { + const idleTtlMs = deps.idleTtlMs ?? PREVIEW_SESSION_SYNC_IDLE_TTL_MS; + return Atom.family((threadKey: string) => { + const threadRef = parseScopedThreadKey(threadKey); + if (threadRef === null) { + throw new PreviewSessionThreadKeyParseError({ threadKey }); + } - return Atom.make((get) => { - let disposed = false; - let eventsVersion = 0; + const sessionsAtom = deps.list({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }); + const eventsAtom = deps.events({ + environmentId: threadRef.environmentId, + input: {}, + }); - const reconcileSessions = (result: Atom.Type) => { - if (result.waiting || !AsyncResult.isSuccess(result)) return; - reconcilePreviewServerSessions(threadRef, result.value); - if (!readThreadPreviewState(threadRef).listLoaded) { - // An event overtook the initial list; retry before using the partial index for surface cleanup. - queueMicrotask(() => { - if (!disposed) get.refresh(sessionsAtom); - }); - } - }; + return Atom.make((get) => { + let disposed = false; + let reconciled = false; + let eventsVersion = 0; - const applyLatestEvent = (result: Atom.Type) => { - if (!AsyncResult.isSuccess(result) || result.value.threadId !== threadRef.threadId) return; - const currentEpoch = readThreadPreviewState(threadRef).serverEpoch; - if (currentEpoch !== null && currentEpoch !== result.value.serverEpoch) { - get.refresh(sessionsAtom); - return; - } - applyPreviewServerEvent(threadRef, result.value); - }; + const reconcileSessions = (result: Atom.Type) => { + if (result.waiting || !AsyncResult.isSuccess(result)) return; + reconcilePreviewServerSessions(threadRef, result.value); + if (!readThreadPreviewState(threadRef).listLoaded) { + // An event overtook the initial list; retry before using the partial index for surface cleanup. + queueMicrotask(() => { + if (!disposed) get.refresh(sessionsAtom); + }); + } + }; - get.addFinalizer(() => { - disposed = true; - }); - const initialEvent = get.once(eventsAtom); - // Evaluate the lazy list, then reconcile only new responses because cached results can be stale. - get.once(sessionsAtom); - get.subscribe(sessionsAtom, (result) => { - reconcileSessions(result); - }); - get.subscribe(eventsAtom, (result) => { - eventsVersion += 1; - applyLatestEvent(result); - }); - get.mount(sessionsAtom); - get.mount(eventsAtom); - queueMicrotask(() => { - if (disposed) return; - // Keep local tabs until authoritative refresh; stale cached emptiness could remove automation-created - // tabs. - const current = get.once(sessionsAtom); - if (!AsyncResult.isInitial(current) && !current.waiting) get.refresh(sessionsAtom); - if (eventsVersion === 0) applyLatestEvent(initialEvent); - }); - }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`)); -}); + const applyLatestEvent = (result: Atom.Type) => { + if (!AsyncResult.isSuccess(result) || result.value.threadId !== threadRef.threadId) return; + const currentEpoch = readThreadPreviewState(threadRef).serverEpoch; + if (currentEpoch !== null && currentEpoch !== result.value.serverEpoch) { + get.refresh(sessionsAtom); + return; + } + applyPreviewServerEvent(threadRef, result.value); + }; + + get.addFinalizer(() => { + disposed = true; + }); + const initialEvent = get.once(eventsAtom); + get.subscribe(sessionsAtom, (result) => { + reconciled = true; + reconcileSessions(result); + }); + get.subscribe(eventsAtom, (result) => { + eventsVersion += 1; + applyLatestEvent(result); + }); + get.mount(sessionsAtom); + get.mount(eventsAtom); + queueMicrotask(() => { + if (disposed) return; + if (!reconciled) reconcileSessions(get.once(sessionsAtom)); + if (eventsVersion === 0) applyLatestEvent(initialEvent); + }); + }).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`preview:session-sync:${threadKey}`)); + }); +} + +const previewSessionSyncAtom = createPreviewSessionSyncAtom(previewEnvironment); export function usePreviewSession(threadRef: ScopedThreadRef): void { useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef))); diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index e82312bbfaaa8..2f3993f2618de 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -33,7 +33,6 @@ import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPrompt import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator"; import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator"; import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator"; -import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive"; import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut"; import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator"; import { ConnectDeviceApprovalCoordinator } from "../components/ConnectDeviceApprovalCoordinator"; @@ -44,7 +43,6 @@ import { Button } from "../components/ui/button"; import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page"; import { SharedTooltipProvider } from "../components/ui/shared-tooltip"; import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast"; -import { isElectron } from "../env"; import { useClientSettings } from "../hooks/useSettings"; import { deriveLogicalProjectKeyFromSettings, @@ -200,7 +198,6 @@ function RootRouteBranch() { ) : null} - {isElectron ? : null} diff --git a/apps/web/src/state/device.browser.test.tsx b/apps/web/src/state/device.browser.test.tsx index 1188119271c79..1d54e39de8868 100644 --- a/apps/web/src/state/device.browser.test.tsx +++ b/apps/web/src/state/device.browser.test.tsx @@ -28,6 +28,22 @@ vi.mock(import("./presentation"), async (original) => ({ connectedEnvironmentIdsAtom: Atom.make([EnvironmentId.make("device-loading")]), }, })); +vi.mock(import("./server"), async (original) => ({ + ...(await original()), + environmentServerConfigsAtom: Atom.make( + new Map([ + [ + EnvironmentId.make("device-loading"), + { + settings: { + enableDeviceSupport: true, + enableAgentDeviceAccess: true, + }, + } as never, + ], + ]), + ), +})); vi.mock(import("../hooks/useSettings"), () => ({ getClientSettings: (() => ({ browserAutoShowFloatingPreview: true })) as never, useClientSettings: (( diff --git a/apps/web/src/state/device.test.ts b/apps/web/src/state/device.test.ts new file mode 100644 index 0000000000000..3803dffe3e980 --- /dev/null +++ b/apps/web/src/state/device.test.ts @@ -0,0 +1,51 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { needsDeviceSetup } from "../components/chat/useRightPanelActions"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { deviceEnvironment, readLoadedDeviceState } from "./device"; + +describe("device state demand gating", () => { + it("reads null without mounting device.subscribeState when unloaded", () => { + const environmentId = EnvironmentId.make("env-device-unloaded-test"); + const atom = deviceEnvironment.state({ environmentId, input: {} }); + + expect(appAtomRegistry.getNodes().has(atom)).toBe(false); + expect(readLoadedDeviceState(environmentId)).toBeNull(); + expect(appAtomRegistry.getNodes().has(atom)).toBe(false); + }); + + it("derives setup requirement from server settings when unloaded and prefers loaded state", () => { + expect(needsDeviceSetup(null, null)).toBe(true); + expect( + needsDeviceSetup(null, { + enableDeviceSupport: false, + deviceOnboardingCompleted: true, + }), + ).toBe(true); + expect( + needsDeviceSetup(null, { + enableDeviceSupport: true, + deviceOnboardingCompleted: false, + }), + ).toBe(true); + expect( + needsDeviceSetup(null, { + enableDeviceSupport: true, + deviceOnboardingCompleted: true, + }), + ).toBe(false); + expect( + needsDeviceSetup( + { onboardingCompleted: true, hostStatus: "disabled" }, + { enableDeviceSupport: true, deviceOnboardingCompleted: true }, + ), + ).toBe(true); + expect( + needsDeviceSetup( + { onboardingCompleted: true, hostStatus: "ready" }, + { enableDeviceSupport: false, deviceOnboardingCompleted: false }, + ), + ).toBe(false); + }); +}); diff --git a/apps/web/src/state/device.ts b/apps/web/src/state/device.ts index a386d8b5d3650..8d9c4451fdb81 100644 --- a/apps/web/src/state/device.ts +++ b/apps/web/src/state/device.ts @@ -35,6 +35,12 @@ const EMPTY_DEVICE_STATE: DeviceServiceState = { revision: 0, }; +export function readLoadedDeviceState(environmentId: EnvironmentId): DeviceServiceState | null { + const atom = deviceEnvironment.state({ environmentId, input: {} }); + if (!appAtomRegistry.getNodes().has(atom)) return null; + return AsyncResult.getOrElse(appAtomRegistry.get(atom), () => null); +} + export function useDeviceState(environmentId: EnvironmentId | null): { readonly state: DeviceServiceState; readonly loaded: boolean; diff --git a/apps/web/src/state/threads.test.ts b/apps/web/src/state/threads.test.ts deleted file mode 100644 index 9d488c2a5d934..0000000000000 --- a/apps/web/src/state/threads.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { - EMPTY_ENVIRONMENT_THREAD_STATE, - type EnvironmentThreadState, -} from "@t3tools/client-runtime/state/threads"; -import { - EnvironmentId, - MessageId, - RunId, - ThreadId, - type OrchestrationV2ThreadShell, -} from "@t3tools/contracts"; -import { makeThreadProjectionFixture } from "../test-fixtures"; -import * as Option from "effect/Option"; -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; -import { describe, expect, it } from "vite-plus/test"; - -import { createRunningThreadKeepAliveAtom } from "./threads"; - -const LOCAL = EnvironmentId.make("local"); -const REMOTE = EnvironmentId.make("remote"); - -type Status = "running" | "starting" | "preparing" | "queued" | "waiting" | "idle"; -function shell(id: string, status: Status | null) { - return { id: ThreadId.make(id), status: status ?? "idle" } satisfies Pick< - OrchestrationV2ThreadShell, - "id" | "status" - >; -} -function detail(id: string, status: Status, overrides: Partial = {}) { - const projection = makeThreadProjectionFixture(); - const threadId = ThreadId.make(id); - const thread = { - ...projection, - thread: { ...projection.thread, id: threadId }, - runs: - status === "idle" - ? [] - : [ - { - id: RunId.make(`run-${id}`), - threadId, - ordinal: 1, - providerInstanceId: projection.thread.providerInstanceId, - modelSelection: projection.thread.modelSelection, - providerThreadId: null, - userMessageId: MessageId.make(`message-${id}`), - rootNodeId: null, - activeAttemptId: null, - status, - requestedAt: projection.updatedAt, - startedAt: null, - completedAt: null, - checkpointId: null, - contextHandoffId: null, - }, - ], - }; - return AsyncResult.success({ - ...EMPTY_ENVIRONMENT_THREAD_STATE, - status: "live", - data: Option.some(thread), - ...overrides, - }); -} - -function makeHarness() { - const tasks: Array<() => void> = []; - const registry = AtomRegistry.make({ - scheduleTask: (task) => { - tasks.push(task); - return () => {}; - }, - }); - const flush = () => { - for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task(); - }; - const environmentIds = Atom.make>([LOCAL, REMOTE]).pipe( - Atom.keepAlive, - ); - const threads = Atom.family((_environmentId: EnvironmentId) => - Atom.make>>([]).pipe(Atom.keepAlive), - ); - const keys = new Set(); - const states = Atom.family((_key: string) => - Atom.make>( - AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE), - ), - ); - const stateAtom = (environmentId: EnvironmentId, threadId: string) => { - const key = `${environmentId}:${threadId}`; - keys.add(key); - return states(key); - }; - const keepAlive = createRunningThreadKeepAliveAtom({ - environmentIdsAtom: environmentIds, - threadsAtom: threads, - stateAtom, - }); - registry.mount(keepAlive); - return { - registry, - environmentIds, - threads, - stateAtom, - keepAlive, - openStreams: () => { - flush(); - return [...keys].filter((key) => registry.getNodes().has(states(key))).toSorted(); - }, - }; -} - -describe("createRunningThreadKeepAliveAtom", () => { - it("keeps running threads open across shell updates and thread view visits", () => { - const h = makeHarness(); - h.registry.set(h.threads(LOCAL), [shell("a", "running"), shell("b", "idle"), shell("c", null)]); - h.registry.set(h.threads(REMOTE), [shell("d", "starting")]); - expect(h.openStreams()).toEqual(["local:a", "remote:d"]); - - const live = detail("a", "running"); - h.registry.set(h.stateAtom(LOCAL, "a"), live); - h.registry.mount(h.stateAtom(LOCAL, "a"))(); - - const kept = h.registry.get(h.keepAlive); - h.registry.set(h.threads(LOCAL), [shell("a", "running"), shell("b", "idle")]); - expect(h.registry.get(h.keepAlive)).toBe(kept); - expect(h.openStreams()).toEqual(["local:a", "remote:d"]); - expect(h.registry.get(h.stateAtom(LOCAL, "a"))).toBe(live); - }); - - it("holds a stopped thread until its own stream is live and shows the stop", () => { - const h = makeHarness(); - h.registry.set(h.threads(LOCAL), [ - shell("a", "running"), - shell("b", "running"), - shell("c", "running"), - ]); - h.registry.set(h.stateAtom(LOCAL, "a"), detail("a", "running")); - h.registry.set( - h.stateAtom(LOCAL, "c"), - detail("c", "running", { status: "cached", error: Option.some("Could not sync.") }), - ); - - h.registry.set(h.threads(LOCAL), [shell("a", "idle"), shell("b", "idle"), shell("c", "idle")]); - expect(h.openStreams()).toEqual(["local:a", "local:b"]); - - h.registry.set(h.stateAtom(LOCAL, "a"), detail("a", "idle")); - h.registry.set(h.stateAtom(LOCAL, "b"), detail("b", "idle", { status: "synchronizing" })); - expect(h.openStreams()).toEqual(["local:b"]); - h.registry.set(h.stateAtom(LOCAL, "b"), detail("b", "idle")); - expect(h.openStreams()).toEqual([]); - }); - - it("follows environments that connect and go away", () => { - const h = makeHarness(); - h.registry.set(h.environmentIds, [LOCAL]); - h.registry.set(h.threads(REMOTE), [shell("d", "running")]); - expect(h.openStreams()).toEqual([]); - - h.registry.set(h.environmentIds, [LOCAL, REMOTE]); - expect(h.openStreams()).toEqual(["remote:d"]); - - h.registry.set(h.stateAtom(REMOTE, "d"), detail("d", "running")); - h.registry.set(h.threads(REMOTE), [shell("d", "idle")]); - expect(h.openStreams()).toEqual(["remote:d"]); - h.registry.set(h.environmentIds, [LOCAL]); - expect(h.openStreams()).toEqual([]); - }); -}); diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 40c90c928d1ae..0f42040a74193 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -1,7 +1,5 @@ import { createChildThreadApprovalsAtom } from "@t3tools/client-runtime/state/thread-requests"; import { useAtomValue } from "@effect/atom-react"; -import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections"; -import { arrayElementsEqual } from "@t3tools/client-runtime/state/entities"; import { createEnvironmentThreadDetailAtoms, createEnvironmentThreadShellAtoms, @@ -12,8 +10,7 @@ import { createThreadEnvironmentAtoms, createThreadFamilyAtoms, } from "@t3tools/client-runtime/state/threads"; -import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; -import * as Option from "effect/Option"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult, Atom } from "effect/reactivity"; import { environmentCatalog } from "../connection/catalog"; @@ -68,71 +65,3 @@ export function useEnvironmentThread( const state = AsyncResult.getOrElse(result, () => EMPTY_ENVIRONMENT_THREAD_STATE); return state; } - -const isRunning = (status: string) => - status === "preparing" || status === "queued" || status === "starting" || status === "running"; - -type KeptThreads = ReadonlyMap>; - -function isDetailDone(result: AsyncResult.AsyncResult): boolean { - if (!AsyncResult.isSuccess(result)) return true; - const { status, data, error } = result.value; - if (status === "deleted" || Option.isSome(error)) return true; - return ( - status === "live" && - !Option.exists(data, (thread) => thread.runs.some((run) => isRunning(run.status))) - ); -} - -/** Keeps stopped threads mounted until their independent detail stream is live and also reports stopped. */ -export function createRunningThreadKeepAliveAtom(input: { - readonly environmentIdsAtom: Atom.Atom>; - readonly threadsAtom: ( - environmentId: EnvironmentId, - ) => Atom.Atom>>; - readonly stateAtom: ( - environmentId: EnvironmentId, - threadId: ThreadId, - ) => Atom.Atom>; -}) { - const runningThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => { - let previous: ReadonlyArray = []; - return Atom.make((get) => { - const running = get(input.threadsAtom(environmentId)).flatMap((thread) => - isRunning(thread.status) ? [thread.id] : [], - ); - if (arrayElementsEqual(previous, running)) return previous; - previous = running; - return running; - }).pipe(Atom.withLabel(`web-running-thread-ids:${environmentId}`)); - }); - - return Atom.make((get): KeptThreads => { - const previous = Option.getOrUndefined(get.self()); - const kept = new Map>(); - for (const environmentId of get(input.environmentIdsAtom)) { - const threadIds = new Set(get(runningThreadIdsAtom(environmentId))); - for (const threadId of previous?.get(environmentId) ?? []) { - if (threadIds.has(threadId)) continue; - const stateAtom = input.stateAtom(environmentId, threadId); - // A get dependency would hold stopped streams open until another change rebuilds this atom. - if (isDetailDone(get.once(stateAtom))) continue; - threadIds.add(threadId); - get.subscribe(stateAtom, (state) => { - if (isDetailDone(state)) get.refreshSelf(); - }); - } - for (const threadId of threadIds) get.mount(input.stateAtom(environmentId, threadId)); - kept.set(environmentId, threadIds); - } - return kept; - }).pipe(Atom.withLabel("web-running-thread-keep-alive")); -} - -export const runningThreadKeepAliveAtom = createRunningThreadKeepAliveAtom({ - environmentIdsAtom: Atom.map(environmentCatalog.catalogValueAtom, (catalog) => [ - ...enabledEnvironmentIds(catalog), - ]), - threadsAtom: environmentThreadShells.environmentThreadsAtom, - stateAtom: environmentThreads.stateAtom, -}); diff --git a/packages/client-runtime/src/state/device.ts b/packages/client-runtime/src/state/device.ts index e01b335ced9cb..65d07504c72fa 100644 --- a/packages/client-runtime/src/state/device.ts +++ b/packages/client-runtime/src/state/device.ts @@ -41,6 +41,7 @@ export function createDeviceEnvironmentAtoms( state: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:device:state", tag: WS_METHODS.subscribeDeviceState, + idleTtlMs: 30_000, }), configure: createEnvironmentRpcCommand(runtime, { label: "environment-data:device:configure", diff --git a/packages/client-runtime/src/state/preview.ts b/packages/client-runtime/src/state/preview.ts index 68eb1e2a96df0..733a4a89b5814 100644 --- a/packages/client-runtime/src/state/preview.ts +++ b/packages/client-runtime/src/state/preview.ts @@ -49,7 +49,9 @@ export function createPreviewEnvironmentAtoms( list: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:preview:list", tag: WS_METHODS.previewList, - staleTimeMs: 5_000, + // `previewSessionSyncAtom` keeps this mounted while live preview events keep state current. + idleTtlMs: 0, + staleTimeMs: 5 * 60_000, }), events: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:preview:events", diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index d03482b19311c..f84b8f2f81970 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -10,6 +10,7 @@ import { UsageLimitSourceId, type ServerConfig, type ServerConfigStreamEvent, + type ServerLifecycleLegacyThreadMigrationPayload, type ServerLifecycleStreamEvent, type ServerLifecycleWelcomePayload, type ServerSelfUpdateOutcome, @@ -2044,3 +2045,291 @@ describe("resource telemetry history", () => { }), ); }); + +describe("shared server lifecycle stream", () => { + it.effect( + "opens one subscribeServerLifecycle stream per environment for welcome, updateOutcome, and legacyThreadMigration", + () => + Effect.gen(function* () { + let subscribeCalls = 0; + const firstEvents = yield* Queue.unbounded(); + const secondEvents = yield* Queue.unbounded(); + const firstSubscribed = yield* Deferred.make(); + const secondSubscribed = yield* Deferred.make(); + const firstClient = { + [WS_METHODS.subscribeServerLifecycle]: () => { + subscribeCalls += 1; + return Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(firstEvents)), + ); + }, + } as unknown as WsRpcProtocolClient; + const secondClient = { + [WS_METHODS.subscribeServerLifecycle]: () => { + subscribeCalls += 1; + return Stream.fromEffect(Deferred.succeed(secondSubscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(secondEvents)), + ); + }, + } as unknown as WsRpcProtocolClient; + const firstSession = session(firstClient); + const secondSession = session(secondClient); + const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession)); + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + phase: "connected", + }), + session: supervisorSession, + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); + const environments = EnvironmentRegistry.EnvironmentRegistry.of({ + run: (_id, effect) => + Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + followStream: (_id, stream) => + Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + } as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.merge( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments), + Layer.succeed(Persistence.EnvironmentCacheStore, { + loadServerConfig: () => Effect.succeedNone, + } as unknown as Persistence.EnvironmentCacheStore["Service"]), + ), + ); + const atoms = createServerEnvironmentAtoms(runtime, { + initialConfigValueAtom: () => Atom.make(CONFIG), + }); + + const firstWelcome = { + environment: {} as ServerLifecycleWelcomePayload["environment"], + cwd: "/first", + projectName: "first", + } as ServerLifecycleWelcomePayload; + const secondWelcome = { + environment: {} as ServerLifecycleWelcomePayload["environment"], + cwd: "/second", + projectName: "second", + } as ServerLifecycleWelcomePayload; + const outcome: ServerSelfUpdateOutcome = { + id: "update-1", + fromVersion: "0.0.30", + targetVersion: "0.0.31", + status: "rolled-back", + reason: "prepared-timeout", + }; + const migration: ServerLifecycleLegacyThreadMigrationPayload = { + status: "running", + totalThreadCount: 4, + }; + + yield* Effect.scoped( + Effect.gen(function* () { + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) => + Effect.sync(() => value.dispose()), + ); + const target = { environmentId: TARGET.environmentId, input: {} }; + const welcomeAtom = atoms.welcome(target); + const outcomeAtom = atoms.updateOutcome(target); + const migrationAtom = atoms.legacyThreadMigration(target); + + yield* AtomRegistry.mount(registry, welcomeAtom); + yield* AtomRegistry.mount(registry, outcomeAtom); + yield* AtomRegistry.mount(registry, migrationAtom); + yield* Deferred.await(firstSubscribed); + expect(subscribeCalls).toBe(1); + + let welcomeNotifications = 0; + const unwatchWelcome = registry.subscribe(welcomeAtom, () => { + welcomeNotifications += 1; + }); + yield* Effect.addFinalizer(() => Effect.sync(unwatchWelcome)); + + const awaitMatch = ( + atom: Atom.Atom>, + predicate: (result: AsyncResult.AsyncResult) => boolean, + ) => + AtomRegistry.toStream(registry, atom).pipe( + Stream.filter(predicate), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + + const welcomeReceived = yield* awaitMatch( + welcomeAtom, + (result) => AsyncResult.isSuccess(result) && result.value === firstWelcome, + ).pipe(Effect.forkChild); + const outcomeReceived = yield* awaitMatch( + outcomeAtom, + (result) => AsyncResult.isSuccess(result) && result.value === outcome, + ).pipe(Effect.forkChild); + const migrationReceived = yield* awaitMatch( + migrationAtom, + (result) => AsyncResult.isSuccess(result) && result.value === migration, + ).pipe(Effect.forkChild); + + yield* Queue.offer(firstEvents, { + version: 1, + sequence: 1, + type: "welcome", + payload: firstWelcome, + }); + expect(AsyncResult.getOrElse(yield* Fiber.join(welcomeReceived), () => null)).toBe( + firstWelcome, + ); + const welcomeNotificationsAfterWelcome = welcomeNotifications; + + yield* Queue.offer(firstEvents, { + version: 1, + sequence: 2, + type: "ready", + payload: { + at: "2026-08-01T00:00:00.000Z", + environment: {} as ServerLifecycleWelcomePayload["environment"], + updateOutcome: outcome, + }, + }); + yield* Queue.offer(firstEvents, { + version: 1, + sequence: 3, + type: "legacyThreadMigration", + payload: migration, + }); + + expect(AsyncResult.getOrElse(yield* Fiber.join(outcomeReceived), () => null)).toBe( + outcome, + ); + expect(AsyncResult.getOrElse(yield* Fiber.join(migrationReceived), () => null)).toBe( + migration, + ); + expect(welcomeNotifications).toBe(welcomeNotificationsAfterWelcome); + expect(subscribeCalls).toBe(1); + + const cleared = yield* awaitMatch(welcomeAtom, AsyncResult.isInitial).pipe( + Effect.forkChild, + ); + yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession)); + yield* Deferred.await(secondSubscribed); + yield* Fiber.join(cleared); + expect(subscribeCalls).toBe(2); + + const reconnectedWelcome = yield* awaitMatch( + welcomeAtom, + (result) => AsyncResult.isSuccess(result) && result.value === secondWelcome, + ).pipe(Effect.forkChild); + yield* Queue.offer(firstEvents, { + version: 1, + sequence: 4, + type: "welcome", + payload: { ...firstWelcome, cwd: "/stale" }, + }); + yield* Queue.offer(secondEvents, { + version: 1, + sequence: 1, + type: "welcome", + payload: secondWelcome, + }); + expect(AsyncResult.getOrElse(yield* Fiber.join(reconnectedWelcome), () => null)).toBe( + secondWelcome, + ); + }), + ); + }), + ); +}); + +describe("live host resources", () => { + it.effect("polls every 15s while mounted and stops immediately on unmount", () => + Effect.gen(function* () { + vi.useFakeTimers(); + try { + yield* Effect.scoped( + Effect.gen(function* () { + let reads = 0; + const client = { + [WS_METHODS.serverGetHostResources]: () => + Effect.sync(() => ({ + sampledAt: reads++, + cpuUtilization: 0.25, + cpuCount: 8, + availableMemoryBytes: 8_000, + totalMemoryBytes: 16_000, + })), + } as unknown as WsRpcProtocolClient; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + phase: "connected", + }), + session: yield* SubscriptionRef.make(Option.some(session(client))), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); + const environments = EnvironmentRegistry.EnvironmentRegistry.of({ + run: (_id, effect) => + Effect.provideService( + effect, + EnvironmentSupervisor.EnvironmentSupervisor, + supervisor, + ), + followStream: (_id, stream) => + Stream.provideService( + stream, + EnvironmentSupervisor.EnvironmentSupervisor, + supervisor, + ), + } as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.merge( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments), + Layer.succeed(Persistence.EnvironmentCacheStore, { + loadServerConfig: () => Effect.succeedNone, + } as unknown as Persistence.EnvironmentCacheStore["Service"]), + ), + ); + const atoms = createServerEnvironmentAtoms(runtime, { + initialConfigValueAtom: () => Atom.make(CONFIG), + }); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) => + Effect.sync(() => value.dispose()), + ); + const live = atoms.liveHostResources({ + environmentId: TARGET.environmentId, + input: {}, + }); + const unmount = registry.mount(live); + const initial = yield* AtomRegistry.getResult(registry, live, { + suspendOnWaiting: true, + }); + expect(initial.sampledAt).toBe(0); + expect(reads).toBe(1); + + yield* Effect.promise(() => vi.advanceTimersByTimeAsync(5_000)); + expect(reads).toBe(1); + + yield* Effect.promise(() => vi.advanceTimersByTimeAsync(9_999)); + expect(reads).toBe(1); + + yield* Effect.promise(() => vi.advanceTimersByTimeAsync(1)); + expect(reads).toBe(2); + + unmount(); + yield* Effect.promise(() => vi.advanceTimersByTimeAsync(30_000)); + expect(reads).toBe(2); + }), + ); + } finally { + vi.useRealTimers(); + } + }), + ); +}); diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 15a0d4b5746b8..2f5fbcb315cd1 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -13,10 +13,13 @@ import { type ServerConfig, type ServerConfigStreamEvent, type ServerFeatureFlags, + type ServerLifecycleLegacyThreadMigrationPayload, + type ServerLifecycleReadyPayload, type ServerLifecycleWelcomePayload, type ServerLifecycleStreamReadyEvent, type ServerProviderWorkspaceSnapshot, ServerSelfUpdateError, + type ServerSelfUpdateOutcome, applyWorkflowRunsUpdate, type ServerSelfUpdateProgressEvent, type ServerSelfUpdateResult, @@ -773,6 +776,25 @@ function serverConfigStateChanges( ); } +export interface EnvironmentServerWelcomeState { + readonly currentSession: RpcSession | null; + readonly welcomeSession: RpcSession | null; + readonly welcome: ServerLifecycleWelcomePayload | null; +} + +interface EnvironmentServerLifecycleState extends EnvironmentServerWelcomeState { + readonly updateOutcome: Option.Option; + readonly legacyThreadMigration: Option.Option; +} + +const EMPTY_SERVER_LIFECYCLE_STATE: EnvironmentServerLifecycleState = { + currentSession: null, + welcomeSession: null, + welcome: null, + updateOutcome: Option.none(), + legacyThreadMigration: Option.none(), +}; + export function applyServerWelcomeEvent( current: EnvironmentServerWelcomeState, session: RpcSession, @@ -790,10 +812,39 @@ export function applyServerWelcomeEvent( : current; } -export interface EnvironmentServerWelcomeState { - readonly currentSession: RpcSession | null; - readonly welcomeSession: RpcSession | null; - readonly welcome: ServerLifecycleWelcomePayload | null; +function applyServerLifecycleEvent( + current: EnvironmentServerLifecycleState, + session: RpcSession, + event: { + readonly type: "welcome" | "ready" | "legacyThreadMigration"; + readonly payload: unknown; + }, +): EnvironmentServerLifecycleState { + if (current.currentSession !== session) return current; + switch (event.type) { + case "welcome": + return { + ...current, + welcomeSession: session, + welcome: event.payload as ServerLifecycleWelcomePayload, + }; + case "ready": { + const updateOutcome = (event.payload as ServerLifecycleReadyPayload).updateOutcome; + return updateOutcome === undefined + ? current + : { + ...current, + updateOutcome: Option.some(updateOutcome), + }; + } + case "legacyThreadMigration": + return { + ...current, + legacyThreadMigration: Option.some( + event.payload as ServerLifecycleLegacyThreadMigrationPayload, + ), + }; + } } export function resolveServerWelcomeState( @@ -802,23 +853,22 @@ export function resolveServerWelcomeState( return state.currentSession === state.welcomeSession ? state.welcome : null; } -export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWelcomeState.make")( +export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerLifecycleState.make")( function* () { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; const initialSession = Option.getOrNull(yield* SubscriptionRef.get(supervisor.session)); - const state = yield* SubscriptionRef.make({ + const state = yield* SubscriptionRef.make({ + ...EMPTY_SERVER_LIFECYCLE_STATE, currentSession: initialSession, - welcomeSession: null, - welcome: null, }); const updateWithCurrentSession = Effect.fn( - "EnvironmentServerWelcomeState.updateWithCurrentSession", + "EnvironmentServerLifecycleState.updateWithCurrentSession", )(function* ( update: ( - current: EnvironmentServerWelcomeState, + current: EnvironmentServerLifecycleState, currentSession: RpcSession | null, - ) => EnvironmentServerWelcomeState, + ) => EnvironmentServerLifecycleState, ) { return yield* SubscriptionRef.modifyEffect(state, (current) => SubscriptionRef.get(supervisor.session).pipe( @@ -832,17 +882,16 @@ export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWel yield* SubscriptionRef.changes(supervisor.session).pipe( Stream.runForEach(() => - updateWithCurrentSession((current, currentSession) => ({ - ...current, - currentSession, - })), + updateWithCurrentSession((current, currentSession) => + current.currentSession === currentSession ? current : { ...current, currentSession }, + ), ), Effect.forkScoped, ); yield* subscribeDynamicWithSession( WS_METHODS.subscribeServerLifecycle, - Effect.fn("EnvironmentServerWelcomeState.makeSubscribeInput")(function* (session) { + Effect.fn("EnvironmentServerLifecycleState.makeSubscribeInput")(function* (session) { yield* updateWithCurrentSession((current, currentSession) => currentSession === session ? { @@ -851,18 +900,17 @@ export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWel welcomeSession: session, welcome: null, } - : { ...current, currentSession }, + : current.currentSession === currentSession + ? current + : { ...current, currentSession }, ); return {}; }), ).pipe( Stream.runForEach(([session, event]) => updateWithCurrentSession((current, currentSession) => - applyServerWelcomeEvent( - { - ...current, - currentSession, - }, + applyServerLifecycleEvent( + current.currentSession === currentSession ? current : { ...current, currentSession }, session, event, ), @@ -875,19 +923,32 @@ export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWel }, ); -function serverWelcomeStateChanges(environmentId: EnvironmentId) { +function serverLifecycleStateChanges(environmentId: EnvironmentId) { return followStreamInEnvironment( environmentId, Stream.unwrap( makeEnvironmentServerWelcomeState().pipe( Effect.map((state) => - SubscriptionRef.changes(state).pipe(Stream.map(resolveServerWelcomeState)), + SubscriptionRef.changes(state).pipe(Stream.changesWith((a, b) => a === b)), ), ), ), ); } +function mapLifecycleResult( + result: AsyncResult.AsyncResult, + select: (state: EnvironmentServerLifecycleState) => A | null, +): AsyncResult.AsyncResult { + return AsyncResult.flatMap(result, (state): AsyncResult.AsyncResult => { + const value = select(state); + if (value === null) return AsyncResult.initial(result.waiting); + return result._tag === "Success" + ? AsyncResult.success(value, result) + : AsyncResult.success(value, { waiting: result.waiting }); + }); +} + /** Whether an environment's server turned on a feature flag; unset flags and unloaded configs are off. */ export function hasFeatureFlag( config: Pick | null | undefined, @@ -1492,22 +1553,43 @@ export function createServerEnvironmentAtoms( get(providersValueAtom(environmentId)), ]), ); - const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) => + const lifecycleStateFamily = Atom.family((environmentId: EnvironmentId) => runtime - .atom(serverWelcomeStateChanges(environmentId), { initialValue: null }) + .atom(serverLifecycleStateChanges(environmentId), { + initialValue: EMPTY_SERVER_LIFECYCLE_STATE, + }) .pipe( Atom.setIdleTTL(5 * 60_000), - Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`), + Atom.withLabel(`environment-data:server:lifecycle-state:${environmentId}`), ), ); const welcomeFamily = Atom.family((environmentId: EnvironmentId) => - Atom.make((get) => { - const result = get(welcomeStateFamily(environmentId)); - if (result._tag !== "Success") return result; - return result.value === null - ? AsyncResult.initial(result.waiting) - : AsyncResult.success(result.value, result); - }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)), + Atom.make((get) => + mapLifecycleResult(get(lifecycleStateFamily(environmentId)), resolveServerWelcomeState), + ).pipe( + Atom.withEquality(Equal.equals), + Atom.withLabel(`environment-data:server:welcome:${environmentId}`), + ), + ); + const updateOutcomeFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => + mapLifecycleResult(get(lifecycleStateFamily(environmentId)), (state) => + Option.getOrNull(state.updateOutcome), + ), + ).pipe( + Atom.withEquality(Equal.equals), + Atom.withLabel(`environment-data:server:update-outcome:${environmentId}`), + ), + ); + const legacyThreadMigrationFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => + mapLifecycleResult(get(lifecycleStateFamily(environmentId)), (state) => + Option.getOrNull(state.legacyThreadMigration), + ), + ).pipe( + Atom.withEquality(Equal.equals), + Atom.withLabel(`environment-data:server:legacy-thread-migration:${environmentId}`), + ), ); const databaseStorage = createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:server:database-storage", @@ -1581,6 +1663,14 @@ export function createServerEnvironmentAtoms( readonly environmentId: EnvironmentId; readonly input: EnvironmentRpcInput; }) => welcomeFamily(target.environmentId); + const updateOutcome = (target: { + readonly environmentId: EnvironmentId; + readonly input: EnvironmentRpcInput; + }) => updateOutcomeFamily(target.environmentId); + const legacyThreadMigration = (target: { + readonly environmentId: EnvironmentId; + readonly input: EnvironmentRpcInput; + }) => legacyThreadMigrationFamily(target.environmentId); const updateSettings = createEnvironmentRpcCommand(runtime, { label: "environment-data:server:update-settings", tag: WS_METHODS.serverUpdateSettings, @@ -1724,8 +1814,8 @@ export function createServerEnvironmentAtoms( liveHostResources: createEnvironmentQueryAtomFamily(runtime, { label: "environment-data:server:live-host-resources", idleTtlMs: 0, - staleTimeMs: 5_000, - refreshIntervalMs: 5_000, + staleTimeMs: 15_000, + refreshIntervalMs: 15_000, execute: (input: EnvironmentRpcInput) => request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")), }), @@ -1832,30 +1922,8 @@ export function createServerEnvironmentAtoms( }), configProjection, welcome, - updateOutcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, { - label: "environment-data:server:update-outcome", - tag: WS_METHODS.subscribeServerLifecycle, - transform: (stream) => - stream.pipe( - Stream.filterMap((event) => - event.type === "ready" && event.payload.updateOutcome !== undefined - ? Result.succeed(event.payload.updateOutcome) - : Result.failVoid, - ), - ), - }), - legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, { - label: "environment-data:server:legacy-thread-migration", - tag: WS_METHODS.subscribeServerLifecycle, - transform: (stream) => - stream.pipe( - Stream.filterMap((event) => - event.type === "legacyThreadMigration" - ? Result.succeed(event.payload) - : Result.failVoid, - ), - ), - }), + updateOutcome, + legacyThreadMigration, consumeResetCredit: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:consume-reset-credit", tag: WS_METHODS.providerConsumeResetCredit,