From 7a285d11722fab1e010d6e58765ebbee24782710 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 3 May 2026 20:00:33 -0700 Subject: [PATCH] Add mobile source control discovery runtime state - Share source control discovery state across mobile environment lifecycles - Resolve discovery clients through centralized mobile environment sessions - Ignore stale in-flight discovery refreshes after invalidation or reset - Mark pending web shell/thread-detail runtime migration points Co-authored-by: codex --- .../src/features/review/ReviewSheet.tsx | 2 +- .../features/terminal/ThreadTerminalPanel.tsx | 2 +- .../terminal/ThreadTerminalRouteScreen.tsx | 6 +- .../src/features/threads/ThreadComposer.tsx | 4 +- .../features/threads/use-project-actions.ts | 2 +- .../src/state/environment-session-registry.ts | 48 ++++++++++++ .../state/source-control-discovery-manager.ts | 46 +++++++++++ apps/mobile/src/state/use-git-action-state.ts | 2 +- apps/mobile/src/state/use-git-branches.ts | 2 +- apps/mobile/src/state/use-git-status.ts | 2 +- .../state/use-remote-environment-registry.ts | 43 ++++------- .../src/state/use-selected-thread-commands.ts | 3 +- .../state/use-selected-thread-git-actions.ts | 3 +- .../state/use-selected-thread-git-state.ts | 3 + .../src/state/use-source-control-discovery.ts | 50 ++++++++++++ .../src/state/use-thread-composer-state.ts | 2 +- apps/mobile/src/state/use-thread-detail.ts | 2 +- apps/web/src/environments/runtime/service.ts | 12 +++ apps/web/src/store.ts | 12 +++ .../src/sourceControlDiscoveryState.test.ts | 76 +++++++++++++++++++ .../src/sourceControlDiscoveryState.ts | 52 +++++++++++-- 21 files changed, 326 insertions(+), 48 deletions(-) create mode 100644 apps/mobile/src/state/environment-session-registry.ts create mode 100644 apps/mobile/src/state/source-control-discovery-manager.ts create mode 100644 apps/mobile/src/state/use-source-control-discovery.ts diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index e148a8da23..4476249395 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -35,7 +35,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; import { cn } from "../../lib/cn"; import { useThemeColor } from "../../lib/useThemeColor"; -import { getEnvironmentClient } from "../../state/use-remote-environment-registry"; +import { getEnvironmentClient } from "../../state/environment-session-registry"; import { useSelectedThreadDetail } from "../../state/use-thread-detail"; import { useThreadDraftForThread } from "../../state/use-thread-composer-state"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; diff --git a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx index 04c240a13d..cbad8b2ba5 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx @@ -4,7 +4,7 @@ import { memo, useCallback, useEffect, useState } from "react"; import { Pressable, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; -import { getEnvironmentClient } from "../../state/use-remote-environment-registry"; +import { getEnvironmentClient } from "../../state/environment-session-registry"; import { attachTerminalSession, useTerminalSession, diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 26c91f7ca1..72061c90ef 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -14,10 +14,8 @@ import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-re import { EmptyState } from "../../components/EmptyState"; import { LoadingScreen } from "../../components/LoadingScreen"; import { buildThreadTerminalNavigation } from "../../lib/routes"; -import { - getEnvironmentClient, - useRemoteEnvironmentState, -} from "../../state/use-remote-environment-registry"; +import { getEnvironmentClient } from "../../state/environment-session-registry"; +import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry"; import { attachTerminalSession, useKnownTerminalSessions, diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 011422ff9e..d09ae40204 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -42,8 +42,8 @@ import { normalizeSearchQuery, scoreQueryMatch, } from "@t3tools/shared/searchRanking"; -import { getEnvironmentClient } from "../../state/use-remote-environment-registry"; -import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions"; +import { getEnvironmentClient } from "../../state/environment-session-registry"; +import { CLAUDE_AGENT_EFFORT_OPTIONS, type ClaudeAgentEffort } from "./claudeEffortOptions"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; /** diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index 717ab594f1..c5d8a66a28 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -17,11 +17,11 @@ import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3 import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { uuidv4 } from "../../lib/uuid"; +import { getEnvironmentClient } from "../../state/environment-session-registry"; import { environmentRuntimeManager } from "../../state/use-environment-runtime"; import { gitBranchManager } from "../../state/use-git-branches"; import { useRemoteCatalog } from "../../state/use-remote-catalog"; import { - getEnvironmentClient, setPendingConnectionError, useRemoteEnvironmentState, } from "../../state/use-remote-environment-registry"; diff --git a/apps/mobile/src/state/environment-session-registry.ts b/apps/mobile/src/state/environment-session-registry.ts new file mode 100644 index 0000000000..3eb94b32c0 --- /dev/null +++ b/apps/mobile/src/state/environment-session-registry.ts @@ -0,0 +1,48 @@ +import type { EnvironmentId } from "@t3tools/contracts"; + +import type { EnvironmentSession } from "./remote-runtime-types"; + +const environmentSessions = new Map(); +const environmentConnectionListeners = new Set<() => void>(); + +export function getEnvironmentSession(environmentId: EnvironmentId): EnvironmentSession | null { + return environmentSessions.get(environmentId) ?? null; +} + +export function getEnvironmentClient(environmentId: EnvironmentId) { + return getEnvironmentSession(environmentId)?.client ?? null; +} + +export function setEnvironmentSession( + environmentId: EnvironmentId, + session: EnvironmentSession, +): void { + environmentSessions.set(environmentId, session); +} + +export function removeEnvironmentSession(environmentId: EnvironmentId): EnvironmentSession | null { + const session = getEnvironmentSession(environmentId); + environmentSessions.delete(environmentId); + return session; +} + +export function drainEnvironmentSessions(): ReadonlyArray { + const sessions = [...environmentSessions.values()]; + environmentSessions.clear(); + return sessions; +} + +export function notifyEnvironmentConnectionListeners() { + for (const listener of environmentConnectionListeners) listener(); +} + +/** + * Subscribe to environment-connection changes (connect / disconnect / reconnect). + * Returns an unsubscribe function. + */ +export function subscribeEnvironmentConnections(listener: () => void): () => void { + environmentConnectionListeners.add(listener); + return () => { + environmentConnectionListeners.delete(listener); + }; +} diff --git a/apps/mobile/src/state/source-control-discovery-manager.ts b/apps/mobile/src/state/source-control-discovery-manager.ts new file mode 100644 index 0000000000..e3ba5d31df --- /dev/null +++ b/apps/mobile/src/state/source-control-discovery-manager.ts @@ -0,0 +1,46 @@ +import { + type SourceControlDiscoveryClient, + type SourceControlDiscoveryTarget, + createSourceControlDiscoveryManager, +} from "@t3tools/client-runtime"; +import { EnvironmentId, type SourceControlDiscoveryResult } from "@t3tools/contracts"; + +import { appAtomRegistry } from "./atom-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; + +export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({ + getRegistry: () => appAtomRegistry, + getClient: (key) => getEnvironmentClient(EnvironmentId.make(key))?.server ?? null, +}); + +export function sourceControlDiscoveryTargetForEnvironment( + environmentId: EnvironmentId | null, +): SourceControlDiscoveryTarget { + return { key: environmentId ?? null }; +} + +export function refreshSourceControlDiscoveryForEnvironment( + environmentId: EnvironmentId | null, + client?: SourceControlDiscoveryClient | null, +): Promise { + return sourceControlDiscoveryManager.refresh( + sourceControlDiscoveryTargetForEnvironment(environmentId), + client ?? undefined, + ); +} + +export function invalidateSourceControlDiscoveryForEnvironment( + environmentId: EnvironmentId | null, +): void { + sourceControlDiscoveryManager.invalidate( + sourceControlDiscoveryTargetForEnvironment(environmentId), + ); +} + +export function resetSourceControlDiscoveryState(): void { + sourceControlDiscoveryManager.reset(); +} + +export function resetSourceControlDiscoveryStateForTests(): void { + resetSourceControlDiscoveryState(); +} diff --git a/apps/mobile/src/state/use-git-action-state.ts b/apps/mobile/src/state/use-git-action-state.ts index 479d396320..77e13d1634 100644 --- a/apps/mobile/src/state/use-git-action-state.ts +++ b/apps/mobile/src/state/use-git-action-state.ts @@ -12,7 +12,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { uuidv4 } from "../lib/uuid"; import { appAtomRegistry } from "./atom-registry"; -import { getEnvironmentClient } from "./use-remote-environment-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; export const gitActionManager = createGitActionManager({ getRegistry: () => appAtomRegistry, diff --git a/apps/mobile/src/state/use-git-branches.ts b/apps/mobile/src/state/use-git-branches.ts index 20ac081221..b516906147 100644 --- a/apps/mobile/src/state/use-git-branches.ts +++ b/apps/mobile/src/state/use-git-branches.ts @@ -10,7 +10,7 @@ import { } from "@t3tools/client-runtime"; import { appAtomRegistry } from "./atom-registry"; -import { getEnvironmentClient } from "./use-remote-environment-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; export const gitBranchManager = createGitBranchManager({ getRegistry: () => appAtomRegistry, diff --git a/apps/mobile/src/state/use-git-status.ts b/apps/mobile/src/state/use-git-status.ts index 41ecdd47b7..5374b9b666 100644 --- a/apps/mobile/src/state/use-git-status.ts +++ b/apps/mobile/src/state/use-git-status.ts @@ -14,7 +14,7 @@ import { appAtomRegistry } from "./atom-registry"; import { getEnvironmentClient, subscribeEnvironmentConnections, -} from "./use-remote-environment-registry"; +} from "./environment-session-registry"; /** * Singleton git status manager for the mobile app. diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index 159bd49077..a7fb6339be 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -21,13 +21,21 @@ import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/co import { terminalDebugLog } from "../features/terminal/terminalDebugLog"; import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage"; import { appAtomRegistry } from "./atom-registry"; -import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types"; +import { + drainEnvironmentSessions, + notifyEnvironmentConnectionListeners, + removeEnvironmentSession, + setEnvironmentSession, +} from "./environment-session-registry"; +import { type ConnectedEnvironmentSummary } from "./remote-runtime-types"; +import { + invalidateSourceControlDiscoveryForEnvironment, + resetSourceControlDiscoveryState, +} from "./source-control-discovery-manager"; import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime"; import { shellSnapshotManager } from "./use-shell-snapshot"; import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session"; -const environmentSessions = new Map(); -const environmentConnectionListeners = new Set<() => void>(); const terminalMetadataUnsubscribers = new Map void>(); interface RemoteEnvironmentLocalState { @@ -57,10 +65,6 @@ const savedConnectionsByIdAtom = Atom.make { return appAtomRegistry.get(savedConnectionsByIdAtom); } @@ -121,17 +125,6 @@ function useRemoteEnvironmentLocalState(): RemoteEnvironmentLocalState { ); } -/** - * Subscribe to environment-connection changes (connect / disconnect / reconnect). - * Returns an unsubscribe function. - */ -export function subscribeEnvironmentConnections(listener: () => void): () => void { - environmentConnectionListeners.add(listener); - return () => { - environmentConnectionListeners.delete(listener); - }; -} - function setEnvironmentConnectionStatus( environmentId: EnvironmentId, state: ConnectedEnvironmentSummary["connectionState"], @@ -144,21 +137,17 @@ function setEnvironmentConnectionStatus( })); } -export function getEnvironmentClient(environmentId: EnvironmentId) { - return environmentSessions.get(environmentId)?.client ?? null; -} - export async function disconnectEnvironment( environmentId: EnvironmentId, options?: { readonly removeSaved?: boolean }, ) { - const session = environmentSessions.get(environmentId); - environmentSessions.delete(environmentId); + const session = removeEnvironmentSession(environmentId); notifyEnvironmentConnectionListeners(); await session?.connection.dispose(); terminalMetadataUnsubscribers.get(environmentId)?.(); terminalMetadataUnsubscribers.delete(environmentId); shellSnapshotManager.invalidate({ environmentId }); + invalidateSourceControlDiscoveryForEnvironment(environmentId); terminalSessionManager.invalidateEnvironment(environmentId); environmentRuntimeManager.invalidate({ environmentId }); @@ -258,7 +247,7 @@ export async function connectSavedEnvironment( }, }); - environmentSessions.set(connection.environmentId, { + setEnvironmentSession(connection.environmentId, { client, connection: environmentConnection, }); @@ -342,16 +331,16 @@ export function useRemoteEnvironmentBootstrap() { return () => { cancelled = true; - for (const session of environmentSessions.values()) { + for (const session of drainEnvironmentSessions()) { void session.connection.dispose(); } - environmentSessions.clear(); for (const unsubscribe of terminalMetadataUnsubscribers.values()) { unsubscribe(); } terminalMetadataUnsubscribers.clear(); environmentRuntimeManager.invalidate(); shellSnapshotManager.invalidate(); + resetSourceControlDiscoveryState(); terminalSessionManager.invalidate(); notifyEnvironmentConnectionListeners(); }; diff --git a/apps/mobile/src/state/use-selected-thread-commands.ts b/apps/mobile/src/state/use-selected-thread-commands.ts index 0db608b665..636c8fa6b1 100644 --- a/apps/mobile/src/state/use-selected-thread-commands.ts +++ b/apps/mobile/src/state/use-selected-thread-commands.ts @@ -11,7 +11,8 @@ import { import { uuidv4 } from "../lib/uuid"; import { environmentRuntimeManager } from "./use-environment-runtime"; -import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; +import { useRemoteEnvironmentState } from "./use-remote-environment-registry"; import { useThreadSelection } from "./use-thread-selection"; export function useSelectedThreadCommands(input: { diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index ac08c1e872..d4fa93bb5b 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -17,7 +17,8 @@ import { } from "@t3tools/shared/git"; import { uuidv4 } from "../lib/uuid"; -import { getEnvironmentClient, setPendingConnectionError } from "./use-remote-environment-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; +import { setPendingConnectionError } from "./use-remote-environment-registry"; import { gitActionManager, showGitActionResult } from "./use-git-action-state"; import { gitBranchManager } from "./use-git-branches"; import { gitStatusManager } from "./use-git-status"; diff --git a/apps/mobile/src/state/use-selected-thread-git-state.ts b/apps/mobile/src/state/use-selected-thread-git-state.ts index a055e7fed1..ea7bec44af 100644 --- a/apps/mobile/src/state/use-selected-thread-git-state.ts +++ b/apps/mobile/src/state/use-selected-thread-git-state.ts @@ -4,6 +4,7 @@ import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; import { useGitActionState } from "./use-git-action-state"; import { useGitBranches } from "./use-git-branches"; +import { useSourceControlDiscovery } from "./use-source-control-discovery"; import { useThreadSelection } from "./use-thread-selection"; import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; @@ -19,6 +20,7 @@ export function useSelectedThreadGitState() { [selectedThread?.environmentId, selectedThreadCwd], ); const gitActionState = useGitActionState(selectedThreadGitTarget); + const sourceControlDiscovery = useSourceControlDiscovery(selectedThread?.environmentId ?? null); const selectedThreadBranchTarget = useMemo( () => ({ @@ -39,6 +41,7 @@ export function useSelectedThreadGitState() { return { gitOperationLabel: gitActionState.currentLabel, + sourceControlDiscovery, selectedThreadBranches, selectedThreadBranchesLoading: selectedThreadBranchState.isPending, }; diff --git a/apps/mobile/src/state/use-source-control-discovery.ts b/apps/mobile/src/state/use-source-control-discovery.ts new file mode 100644 index 0000000000..45fba416a9 --- /dev/null +++ b/apps/mobile/src/state/use-source-control-discovery.ts @@ -0,0 +1,50 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM, + EMPTY_SOURCE_CONTROL_DISCOVERY_STATE, + type SourceControlDiscoveryState, + getSourceControlDiscoveryTargetKey, + sourceControlDiscoveryStateAtom, +} from "@t3tools/client-runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useEffect } from "react"; + +import { + getEnvironmentClient, + subscribeEnvironmentConnections, +} from "./environment-session-registry"; +import { + refreshSourceControlDiscoveryForEnvironment, + sourceControlDiscoveryTargetForEnvironment, +} from "./source-control-discovery-manager"; + +export function useSourceControlDiscovery( + environmentId: EnvironmentId | null, +): SourceControlDiscoveryState { + useEffect(() => { + if (!environmentId) { + return; + } + + const refresh = () => { + const client = getEnvironmentClient(environmentId); + if (!client) { + return; + } + + void refreshSourceControlDiscoveryForEnvironment(environmentId, client.server); + }; + + refresh(); + return subscribeEnvironmentConnections(refresh); + }, [environmentId]); + + const target = sourceControlDiscoveryTargetForEnvironment(environmentId); + const targetKey = getSourceControlDiscoveryTargetKey(target); + const state = useAtomValue( + targetKey !== null + ? sourceControlDiscoveryStateAtom(targetKey) + : EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM, + ); + return targetKey === null ? EMPTY_SOURCE_CONTROL_DISCOVERY_STATE : state; +} diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 391bc1dc36..cff627edb4 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -30,9 +30,9 @@ import { } from "../lib/threadActivity"; import { uuidv4 } from "../lib/uuid"; import { appAtomRegistry } from "../state/atom-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; import type { ConnectedEnvironmentSummary } from "../state/remote-runtime-types"; import { - getEnvironmentClient, setPendingConnectionError, useRemoteConnectionStatus, } from "../state/use-remote-environment-registry"; diff --git a/apps/mobile/src/state/use-thread-detail.ts b/apps/mobile/src/state/use-thread-detail.ts index 82b29d9da7..9d1285130a 100644 --- a/apps/mobile/src/state/use-thread-detail.ts +++ b/apps/mobile/src/state/use-thread-detail.ts @@ -15,7 +15,7 @@ import { appAtomRegistry } from "./atom-registry"; import { getEnvironmentClient, subscribeEnvironmentConnections, -} from "./use-remote-environment-registry"; +} from "./environment-session-registry"; import { useThreadSelection } from "./use-thread-selection"; function shouldKeepThreadDetailWarm(state: ThreadDetailState): boolean { diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 1e484d8c5b..b36c572a74 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -131,6 +131,13 @@ let needsProviderInvalidation = false; let lastBrowserHiddenAt: number | null = null; let lastBrowserResumeReconnectAt = Number.NEGATIVE_INFINITY; +// TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY): +// This file still owns web's legacy thread-detail subscription cache. Mobile +// uses createThreadDetailManager from @t3tools/client-runtime for the same +// retain/reconnect/evict lifecycle. When touching this logic, prefer migrating +// web to the shared manager or extracting the missing adapter layer instead of +// adding more behavior here. +// // Thread detail subscription cache policy: // - Active consumers keep a subscription retained via refCount. // - Released subscriptions stay warm for a longer idle TTL to avoid churn @@ -1078,6 +1085,11 @@ function createEnvironmentConnectionHandlers() { return { applyShellEvent, syncShellSnapshot: (snapshot: OrchestrationShellSnapshot, environmentId: EnvironmentId) => { + // TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY): + // Shell snapshots already have createShellSnapshotManager in + // @t3tools/client-runtime. Web currently projects snapshots straight into + // its denormalized Zustand store; future shell changes should migrate or + // bridge to the shared manager instead of growing this handler. if ( !shouldApplyProjectionSnapshot({ current: readLastAppliedProjectionVersion(environmentId), diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index e9972f7c9a..7d995b5ea7 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -43,6 +43,12 @@ export interface EnvironmentState { projectIds: ProjectId[]; projectById: Record; + // TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY): + // Web still stores shell snapshots and thread details in this denormalized + // Zustand shape. Mobile uses createShellSnapshotManager and + // createThreadDetailManager from @t3tools/client-runtime. New shared behavior + // belongs in those managers/reducers, with a web adapter layered on top. + // // --------------------------------------------------------------------------- // Thread bookkeeping — written by BOTH shell stream and detail stream. // Both streams ensure the thread is registered here; the bookkeeping is @@ -1120,6 +1126,9 @@ export function syncServerShellSnapshot( snapshot: OrchestrationShellSnapshot, environmentId: EnvironmentId, ): AppState { + // TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY): + // Keep web-specific projection here only until the store can consume + // createShellSnapshotManager or a shared adapter over its reducer. return commitEnvironmentState( state, environmentId, @@ -1136,6 +1145,9 @@ export function syncServerThreadDetail( thread: OrchestrationThread, environmentId: EnvironmentId, ): AppState { + // TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY): + // Keep web-specific projection here only until the store can consume + // createThreadDetailManager or a shared adapter over its reducer. const environmentState = getStoredEnvironmentState(state, environmentId); const previousThread = getThreadFromEnvironmentState(environmentState, thread.id); return commitEnvironmentState( diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts index 9a988be00a..583dcfa551 100644 --- a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts +++ b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts @@ -1,5 +1,6 @@ import { assert, beforeEach, it } from "vitest"; import type { SourceControlDiscoveryResult } from "@t3tools/contracts"; +import * as Option from "effect/Option"; import { AtomRegistry } from "effect/unstable/reactivity"; import { @@ -12,6 +13,37 @@ const EMPTY_RESULT: SourceControlDiscoveryResult = { sourceControlProviders: [], }; +const GITHUB_RESULT: SourceControlDiscoveryResult = { + versionControlSystems: [ + { + kind: "git", + label: "Git", + implemented: true, + status: "available", + version: Option.some("2.51.0"), + installHint: "Install Git.", + detail: Option.none(), + }, + ], + sourceControlProviders: [ + { + kind: "github", + label: "GitHub", + implemented: true, + status: "available", + version: Option.some("2.85.0"), + installHint: "Install GitHub CLI.", + detail: Option.none(), + auth: { + status: "authenticated", + account: Option.some("octo"), + host: Option.some("github.com"), + detail: Option.none(), + }, + }, + ], +}; + function unresolvedDiscovery() { throw new Error("Discovery resolver was not initialized."); } @@ -105,3 +137,47 @@ it("keeps the previous snapshot when refresh fails", async () => { isPending: false, }); }); + +it("invalidates a discovery target back to the initial snapshot", async () => { + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => ({ + discoverSourceControl: async () => GITHUB_RESULT, + }), + }); + + await manager.refresh({ key: "primary" }); + manager.invalidate({ key: "primary" }); + + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: null, + error: null, + isPending: true, + }); +}); + +it("ignores an in-flight refresh after the target is invalidated", async () => { + let resolveDiscovery: (result: SourceControlDiscoveryResult) => void = unresolvedDiscovery; + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => ({ + discoverSourceControl: () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + }), + }); + + const refresh = manager.refresh({ key: "primary" }); + manager.invalidate({ key: "primary" }); + resolveDiscovery(GITHUB_RESULT); + + const result = await refresh; + + assert.strictEqual(result, GITHUB_RESULT); + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: null, + error: null, + isPending: true, + }); +}); diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.ts b/packages/client-runtime/src/sourceControlDiscoveryState.ts index b18d6103b8..99465beff0 100644 --- a/packages/client-runtime/src/sourceControlDiscoveryState.ts +++ b/packages/client-runtime/src/sourceControlDiscoveryState.ts @@ -75,6 +75,15 @@ export interface SourceControlDiscoveryManagerConfig { export function createSourceControlDiscoveryManager(config: SourceControlDiscoveryManagerConfig) { const refreshInFlight = new Map>(); + const refreshVersions = new Map(); + + function getRefreshVersion(targetKey: string): number { + return refreshVersions.get(targetKey) ?? 0; + } + + function bumpRefreshVersion(targetKey: string): void { + refreshVersions.set(targetKey, getRefreshVersion(targetKey) + 1); + } /* -- Atom helpers -------------------------------------------------- */ @@ -156,21 +165,52 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove } markPending(targetKey); + const refreshVersion = getRefreshVersion(targetKey); const promise = resolvedClient.discoverSourceControl().then( (result) => { - setData(targetKey, result); + if (getRefreshVersion(targetKey) === refreshVersion) { + setData(targetKey, result); + } return result; }, (error: unknown) => { - setError(targetKey, error); + if (getRefreshVersion(targetKey) === refreshVersion) { + setError(targetKey, error); + } return getSnapshot(target).data; }, ); - const tracked = promise.finally(() => refreshInFlight.delete(targetKey)); + let tracked: Promise; + tracked = promise.finally(() => { + if (refreshInFlight.get(targetKey) === tracked) { + refreshInFlight.delete(targetKey); + } + }); refreshInFlight.set(targetKey, tracked); return tracked; } + /** + * Reset discovery state for one target and ignore any currently in-flight + * refresh for that target. If no target is provided, every known target is + * invalidated. + */ + function invalidate(target?: SourceControlDiscoveryTarget): void { + if (!target) { + reset(); + return; + } + + const targetKey = getSourceControlDiscoveryTargetKey(target); + if (targetKey === null) { + return; + } + + bumpRefreshVersion(targetKey); + refreshInFlight.delete(targetKey); + setState(targetKey, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE); + } + /** * Read the current atom snapshot for `target`. * @@ -191,16 +231,18 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove * Primarily used by tests and runtime teardown. */ function reset(): void { + const keys = new Set([...knownSourceControlDiscoveryKeys, ...refreshInFlight.keys()]); refreshInFlight.clear(); - for (const key of knownSourceControlDiscoveryKeys) { + for (const key of keys) { + bumpRefreshVersion(key); setState(key, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE); } - knownSourceControlDiscoveryKeys.clear(); } return { refresh, getSnapshot, + invalidate, reset, }; }