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 <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-05-20 10:53:18 +02:00
1 parent 37908166ed
commit 7a285d1172
21 files changed
+326 -48

No files matched your search

@@ -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";
@@ -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,
@@ -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,
@@ -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";
/**
@@ -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";
@@ -0,0 +1,48 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentSession } from "./remote-runtime-types";
const environmentSessions = new Map<EnvironmentId, EnvironmentSession>();
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<EnvironmentSession> {
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);
};
}
@@ -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<SourceControlDiscoveryResult | null> {
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();
}
@@ -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,
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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.
@@ -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<EnvironmentId, EnvironmentSession>();
const environmentConnectionListeners = new Set<() => void>();
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
interface RemoteEnvironmentLocalState {
@@ -57,10 +65,6 @@ const savedConnectionsByIdAtom = Atom.make<Record<EnvironmentId, SavedRemoteConn
Atom.withLabel("mobile:saved-connections"),
);
function notifyEnvironmentConnectionListeners() {
for (const listener of environmentConnectionListeners) listener();
}
function getSavedConnectionsById(): Record<EnvironmentId, SavedRemoteConnection> {
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();
};
@@ -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: {
@@ -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";
@@ -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,
};
@@ -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;
}
@@ -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";
+1 -1
View File
@@ -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 {
@@ -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),
+12
View File
@@ -43,6 +43,12 @@ export interface EnvironmentState {
projectIds: ProjectId[];
projectById: Record<ProjectId, Project>;
// 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(
@@ -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<SourceControlDiscoveryResult>((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,
});
});
@@ -75,6 +75,15 @@ export interface SourceControlDiscoveryManagerConfig {
export function createSourceControlDiscoveryManager(config: SourceControlDiscoveryManagerConfig) {
const refreshInFlight = new Map<string, Promise<SourceControlDiscoveryResult | null>>();
const refreshVersions = new Map<string, number>();
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<SourceControlDiscoveryResult | null>;
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,
};
}