Refactor client runtime state refresh handling

- Move archived threads state into shared client-runtime
- Add stale-aware refresh/invalidation for path search, discovery, and VCS refs
- Wire provider invalidations through the web runtime
This commit is contained in:
Julius Marminge committed 2026-05-08 19:38:12 -07:00
1 parent 9ef8d75c54
commit 01596f53ad
15 files changed
+536 -129

No files matched your search

@@ -17,10 +17,13 @@ import {
subscribeEnvironmentConnections,
} from "./environment-session-registry";
const COMPOSER_PATH_SEARCH_STALE_TIME_MS = 15_000;
const composerPathSearchManager = createComposerPathSearchManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => getEnvironmentClient(environmentId)?.projects ?? null,
subscribeClientChanges: subscribeEnvironmentConnections,
staleTimeMs: COMPOSER_PATH_SEARCH_STALE_TIME_MS,
});
export function useComposerPathSearch(target: ComposerPathSearchTarget): ComposerPathSearchState {
@@ -27,4 +27,5 @@ export {
resetEnvironmentServiceForTests,
startEnvironmentConnectionService,
subscribeEnvironmentConnections,
subscribeProviderInvalidations,
} from "./service";
@@ -119,6 +119,7 @@ const pendingSavedEnvironmentConnections = new Map<
PendingSavedEnvironmentConnection
>();
const environmentConnectionListeners = new Set<() => void>();
const providerInvalidationListeners = new Set<() => void>();
const threadDetailSubscriptions = new Map<string, ThreadDetailSubscriptionEntry>();
const terminalMetadataSubscriptions = new Map<EnvironmentId, () => void>();
const lastAppliedProjectionVersionByEnvironment = new Map<
@@ -604,6 +605,12 @@ function emitEnvironmentConnectionRegistryChange() {
}
}
function emitProviderInvalidation() {
for (const listener of providerInvalidationListeners) {
listener();
}
}
function getRuntimeErrorFields(error: unknown) {
return {
lastError: error instanceof Error ? error.message : String(error),
@@ -1543,6 +1550,13 @@ export function subscribeEnvironmentConnections(listener: () => void): () => voi
};
}
export function subscribeProviderInvalidations(listener: () => void): () => void {
providerInvalidationListeners.add(listener);
return () => {
providerInvalidationListeners.delete(listener);
};
}
export function listEnvironmentConnections(): ReadonlyArray<EnvironmentConnection> {
return [...environmentConnections.values()];
}
@@ -1769,6 +1783,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
}
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
emitProviderInvalidation();
},
{
wait: 100,
+16 -79
View File
@@ -1,83 +1,23 @@
import { useAtomValue } from "@effect/atom-react";
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import {
type ArchivedSnapshotEntry,
createArchivedThreadsManager,
makeArchivedThreadsEnvironmentKey,
readArchivedThreadsSnapshotState,
} from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { readEnvironmentApi } from "../environmentApi";
import { appAtomRegistry } from "../rpc/atomRegistry";
const ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
const ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
export type ArchivedSnapshotEntry = {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
};
const knownArchivedThreadEnvironmentKeys = new Set<string>();
function makeArchivedThreadsEnvironmentKey(environmentIds: ReadonlyArray<EnvironmentId>): string {
return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR);
}
function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
if (key.length === 0) {
return [];
}
return key
.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR)
.map((environmentId) => EnvironmentId.make(environmentId));
}
const archivedThreadSnapshotsAtom = Atom.family((environmentKey: string) => {
knownArchivedThreadEnvironmentKeys.add(environmentKey);
return Atom.make(
Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
const environmentIds = parseArchivedThreadsEnvironmentKey(environmentKey);
const snapshots = await Promise.all(
environmentIds.map(async (environmentId) => {
const api = readEnvironmentApi(environmentId);
if (!api) {
return null;
}
return {
environmentId,
snapshot: await api.orchestration.getArchivedShellSnapshot(),
};
}),
);
return snapshots.filter((snapshot) => snapshot !== null);
}),
).pipe(
Atom.swr({
staleTime: ARCHIVED_THREADS_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(ARCHIVED_THREADS_IDLE_TTL_MS),
Atom.withLabel(`archived-thread-snapshots:${environmentKey}`),
);
const archivedThreadsManager = createArchivedThreadsManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => readEnvironmentApi(environmentId)?.orchestration ?? null,
});
function readArchivedThreadsError(
result: AsyncResult.AsyncResult<ReadonlyArray<ArchivedSnapshotEntry>, unknown>,
): string | null {
if (result._tag !== "Failure") {
return null;
}
const error = Cause.squash(result.cause);
return error instanceof Error ? error.message : "Failed to load archived threads.";
}
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
for (const key of knownArchivedThreadEnvironmentKeys) {
if (parseArchivedThreadsEnvironmentKey(key).includes(environmentId)) {
appAtomRegistry.refresh(archivedThreadSnapshotsAtom(key));
}
}
archivedThreadsManager.refreshForEnvironment(environmentId);
}
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
@@ -90,17 +30,14 @@ export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<Environ
() => makeArchivedThreadsEnvironmentKey(environmentIds),
[environmentIds],
);
const atom = archivedThreadSnapshotsAtom(environmentKey);
const atom = archivedThreadsManager.getAtom(environmentKey);
const result = useAtomValue(atom);
const snapshots = Option.getOrElse(AsyncResult.value(result), () => []);
const refresh = useCallback(() => {
appAtomRegistry.refresh(atom);
}, [atom]);
archivedThreadsManager.refresh(environmentIds);
}, [environmentIds]);
return {
snapshots,
error: readArchivedThreadsError(result),
isLoading: result.waiting,
...readArchivedThreadsSnapshotState(result),
refresh,
};
}
@@ -14,11 +14,13 @@ import { useEffect, useMemo } from "react";
import {
readEnvironmentConnection,
subscribeEnvironmentConnections,
subscribeProviderInvalidations,
} from "../environments/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
const COMPOSER_PATH_SEARCH_LIMIT = 80;
const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 120;
const COMPOSER_PATH_SEARCH_STALE_TIME_MS = 15_000;
const composerPathSearchManager = createComposerPathSearchManager({
getRegistry: () => appAtomRegistry,
@@ -26,8 +28,15 @@ const composerPathSearchManager = createComposerPathSearchManager({
subscribeClientChanges: subscribeEnvironmentConnections,
limit: COMPOSER_PATH_SEARCH_LIMIT,
debounceMs: COMPOSER_PATH_SEARCH_DEBOUNCE_MS,
staleTimeMs: COMPOSER_PATH_SEARCH_STALE_TIME_MS,
});
export function invalidateComposerPathSearches(): void {
composerPathSearchManager.invalidate();
}
subscribeProviderInvalidations(invalidateComposerPathSearches);
export function useComposerPathSearch(target: ComposerPathSearchTarget): ComposerPathSearchState {
const stableTarget = useMemo(
() => ({
@@ -7,11 +7,13 @@ import {
sourceControlDiscoveryStateAtom,
} from "@t3tools/client-runtime";
import { EnvironmentId, type SourceControlDiscoveryResult } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { Atom } from "effect/unstable/reactivity";
import { useEffect } from "react";
import { readPrimaryEnvironmentDescriptor } from "../environments/primary";
import { readEnvironmentConnection } from "../environments/runtime";
import {
readEnvironmentConnection,
subscribeEnvironmentConnections,
} from "../environments/runtime";
import { readLocalApi } from "../localApi";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -59,21 +61,11 @@ const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({
}
return null;
},
subscribeClientChanges: subscribeEnvironmentConnections,
staleTimeMs: SOURCE_CONTROL_DISCOVERY_STALE_TIME_MS,
idleTtlMs: SOURCE_CONTROL_DISCOVERY_IDLE_TTL_MS,
});
const sourceControlDiscoveryAutoRefreshAtom = Atom.family((targetKey: string) =>
Atom.make(() =>
Effect.promise(() => sourceControlDiscoveryManager.refresh({ key: targetKey })),
).pipe(
Atom.swr({
staleTime: SOURCE_CONTROL_DISCOVERY_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(SOURCE_CONTROL_DISCOVERY_IDLE_TTL_MS),
Atom.withLabel(`source-control-discovery:auto-refresh:${targetKey}`),
),
);
export function refreshSourceControlDiscovery(
input?: SourceControlDiscoveryTargetInput,
): Promise<SourceControlDiscoveryResult | null> {
@@ -97,7 +89,7 @@ export function useSourceControlDiscovery(
getSourceControlDiscoveryTargetKey(sourceControlDiscoveryTarget(input)) ??
SOURCE_CONTROL_DISCOVERY_TARGET.key;
useAtomValue(sourceControlDiscoveryAutoRefreshAtom(targetKey));
useEffect(() => sourceControlDiscoveryManager.watch({ key: targetKey }), [targetKey]);
return useAtomValue(sourceControlDiscoveryStateAtom(targetKey));
}
@@ -0,0 +1,96 @@
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
type ArchivedThreadsClient,
createArchivedThreadsManager,
makeArchivedThreadsEnvironmentKey,
parseArchivedThreadsEnvironmentKey,
readArchivedThreadsSnapshotState,
} from "./archivedThreadsState.ts";
let registry = AtomRegistry.make();
function resetAtomRegistry() {
registry.dispose();
registry = AtomRegistry.make();
}
function createSnapshot(id: string): OrchestrationShellSnapshot {
return {
snapshotSequence: 1,
projects: [],
threads: [],
updatedAt: `2026-05-08T00:00:00.000Z`,
id,
} as OrchestrationShellSnapshot;
}
describe("createArchivedThreadsManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("loads archived snapshots for configured environment clients", async () => {
const envA = EnvironmentId.make("env-a");
const envB = EnvironmentId.make("env-b");
const clients = new Map<EnvironmentId, ArchivedThreadsClient>([
[
envA,
{
getArchivedShellSnapshot: vi.fn(async () => createSnapshot("a")),
},
],
[
envB,
{
getArchivedShellSnapshot: vi.fn(async () => createSnapshot("b")),
},
],
]);
const manager = createArchivedThreadsManager({
getRegistry: () => registry,
getClient: (environmentId) => clients.get(environmentId) ?? null,
});
const result = registry.get(manager.getAtom(makeArchivedThreadsEnvironmentKey([envB, envA])));
await vi.waitFor(() => {
const state = readArchivedThreadsSnapshotState(
registry.get(manager.getAtom(makeArchivedThreadsEnvironmentKey([envA, envB]))),
);
expect(state.snapshots.map((snapshot) => snapshot.environmentId)).toEqual([envA, envB]);
});
expect(readArchivedThreadsSnapshotState(result).isLoading).toBe(true);
});
it("refreshes known snapshot groups that include an environment", async () => {
const envA = EnvironmentId.make("env-a");
const envB = EnvironmentId.make("env-b");
const getArchivedShellSnapshot = vi.fn(async () =>
createSnapshot(`a-${getArchivedShellSnapshot.mock.calls.length}`),
);
const manager = createArchivedThreadsManager({
getRegistry: () => registry,
getClient: (environmentId) => (environmentId === envA ? { getArchivedShellSnapshot } : null),
staleTimeMs: 60_000,
});
const atom = manager.getAtom(makeArchivedThreadsEnvironmentKey([envA, envB]));
registry.get(atom);
await vi.waitFor(() => expect(getArchivedShellSnapshot).toHaveBeenCalledTimes(1));
manager.refreshForEnvironment(envA);
await vi.waitFor(() => expect(getArchivedShellSnapshot).toHaveBeenCalledTimes(2));
});
it("round-trips environment keys in sorted order", () => {
const envA = EnvironmentId.make("env-a");
const envB = EnvironmentId.make("env-b");
const key = makeArchivedThreadsEnvironmentKey([envB, envA]);
expect(parseArchivedThreadsEnvironmentKey(key)).toEqual([envA, envB]);
});
});
@@ -0,0 +1,117 @@
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
export type ArchivedSnapshotEntry = {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
};
export interface ArchivedThreadsClient {
readonly getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;
}
export interface ArchivedThreadsSnapshotState {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly error: string | null;
readonly isLoading: boolean;
}
const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
const DEFAULT_ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
const DEFAULT_ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
export function makeArchivedThreadsEnvironmentKey(
environmentIds: ReadonlyArray<EnvironmentId>,
): string {
return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR);
}
export function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
if (key.length === 0) {
return [];
}
return key
.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR)
.map((environmentId) => EnvironmentId.make(environmentId));
}
export function readArchivedThreadsSnapshotState(
result: AsyncResult.AsyncResult<ReadonlyArray<ArchivedSnapshotEntry>, unknown>,
): ArchivedThreadsSnapshotState {
const snapshots = Option.getOrElse(AsyncResult.value(result), () => []);
let error: string | null = null;
if (result._tag === "Failure") {
const cause = Cause.squash(result.cause);
error = cause instanceof Error ? cause.message : "Failed to load archived threads.";
}
return {
snapshots,
error,
isLoading: result.waiting,
};
}
export function createArchivedThreadsManager(config: {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: EnvironmentId) => ArchivedThreadsClient | null;
readonly staleTimeMs?: number;
readonly idleTtlMs?: number;
}) {
const knownEnvironmentKeys = new Set<string>();
const staleTime = config.staleTimeMs ?? DEFAULT_ARCHIVED_THREADS_STALE_TIME_MS;
const idleTtl = config.idleTtlMs ?? DEFAULT_ARCHIVED_THREADS_IDLE_TTL_MS;
const snapshotsAtom = Atom.family((environmentKey: string) => {
knownEnvironmentKeys.add(environmentKey);
return Atom.make(
Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
const snapshots = await Promise.all(
parseArchivedThreadsEnvironmentKey(environmentKey).map(async (environmentId) => {
const client = config.getClient(environmentId);
if (!client) {
return null;
}
return {
environmentId,
snapshot: await client.getArchivedShellSnapshot(),
};
}),
);
return snapshots.filter((snapshot) => snapshot !== null);
}),
).pipe(
Atom.swr({
staleTime,
revalidateOnMount: true,
}),
Atom.setIdleTTL(idleTtl),
Atom.withLabel(`archived-thread-snapshots:${environmentKey}`),
);
});
function getAtom(environmentKey: string) {
return snapshotsAtom(environmentKey);
}
function refresh(environmentIds: ReadonlyArray<EnvironmentId>): void {
config.getRegistry().refresh(getAtom(makeArchivedThreadsEnvironmentKey(environmentIds)));
}
function refreshForEnvironment(environmentId: EnvironmentId): void {
for (const environmentKey of knownEnvironmentKeys) {
if (parseArchivedThreadsEnvironmentKey(environmentKey).includes(environmentId)) {
config.getRegistry().refresh(getAtom(environmentKey));
}
}
}
return {
getAtom,
refresh,
refreshForEnvironment,
};
}
@@ -1,4 +1,4 @@
import { assert, beforeEach, it } from "vitest";
import { assert, beforeEach, it, vi } from "vitest";
import type { EnvironmentId } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
@@ -62,6 +62,80 @@ it("stores path search results in atom state", async () => {
});
});
it("reuses fresh cached path search results", async () => {
const searchEntries = vi.fn(async () => ({
entries: [{ path: "src/index.ts", kind: "file" as const }],
truncated: false,
}));
const manager = createComposerPathSearchManager({
getRegistry: () => registry,
debounceMs: 0,
staleTimeMs: 15_000,
getClient: () => ({ searchEntries }),
});
manager.search(TARGET);
await flushAsyncWork();
manager.search(TARGET);
await flushAsyncWork();
assert.strictEqual(searchEntries.mock.calls.length, 1);
assert.deepStrictEqual(manager.getSnapshot(TARGET), {
entries: [{ path: "src/index.ts", kind: "file" }],
isPending: false,
error: null,
});
});
it("invalidates watched path searches and refreshes without clearing entries", async () => {
type SearchResult = Awaited<ReturnType<ComposerPathSearchClient["searchEntries"]>>;
let resolveSecond: (value: SearchResult) => void = noop;
let callCount = 0;
const searchEntries = vi.fn((() => {
callCount += 1;
if (callCount === 1) {
return Promise.resolve({
entries: [{ path: "src/old.ts", kind: "file" as const }],
truncated: false,
});
}
return new Promise((resolve) => {
resolveSecond = resolve;
});
}) satisfies ComposerPathSearchClient["searchEntries"]);
const manager = createComposerPathSearchManager({
getRegistry: () => registry,
debounceMs: 0,
staleTimeMs: 15_000,
getClient: () => ({ searchEntries }),
});
const unwatch = manager.watch(TARGET);
await flushAsyncWork();
manager.invalidate();
assert.deepStrictEqual(manager.getSnapshot(TARGET), {
entries: [{ path: "src/old.ts", kind: "file" }],
isPending: true,
error: null,
});
resolveSecond({
entries: [{ path: "src/new.ts", kind: "file" }],
truncated: false,
});
await flushAsyncWork();
assert.deepStrictEqual(manager.getSnapshot(TARGET), {
entries: [{ path: "src/new.ts", kind: "file" }],
isPending: false,
error: null,
});
assert.strictEqual(searchEntries.mock.calls.length, 2);
unwatch();
});
it("ignores stale path search results after a newer request starts", async () => {
let resolveFirst: (value: {
entries: ReadonlyArray<{ path: string; kind: "file" | "directory" }>;
@@ -1,4 +1,5 @@
import type { EnvironmentId, ProjectSearchEntriesResult } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -32,6 +33,10 @@ export interface ComposerPathSearchClient {
interface WatchedEntry {
refCount: number;
target: ComposerPathSearchTarget & {
readonly environmentId: EnvironmentId;
readonly cwd: string;
};
teardown: () => void;
}
@@ -92,10 +97,12 @@ export function createComposerPathSearchManager(config: {
readonly subscribeClientChanges?: (listener: () => void) => () => void;
readonly debounceMs?: number;
readonly limit?: number;
readonly staleTimeMs?: number;
}) {
const watched = new Map<string, WatchedEntry>();
const versions = new Map<string, number>();
const timers = new Map<string, Fiber.Fiber<void, never>>();
const lastLoadedAt = new Map<string, number>();
const debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS;
const limit = config.limit ?? DEFAULT_LIMIT;
@@ -148,20 +155,26 @@ export function createComposerPathSearchManager(config: {
isPending: false,
error: null,
});
lastLoadedAt.set(targetKey, Effect.runSync(Clock.currentTimeMillis));
})
.catch((error: unknown) => {
if (versions.get(targetKey) !== version) {
return;
}
const current = config.getRegistry().get(composerPathSearchStateAtom(targetKey));
setState(targetKey, {
entries: [],
entries: current.entries,
isPending: false,
error: error instanceof Error ? error.message : "Failed to search project files.",
});
});
}
function search(target: ComposerPathSearchTarget, client?: ComposerPathSearchClient): void {
function search(
target: ComposerPathSearchTarget,
client?: ComposerPathSearchClient,
options?: { readonly force?: boolean },
): void {
const targetKey = getComposerPathSearchTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return;
@@ -177,9 +190,25 @@ export function createComposerPathSearchManager(config: {
return;
}
const lastLoaded = lastLoadedAt.get(targetKey);
if (
!options?.force &&
lastLoaded !== undefined &&
config.staleTimeMs !== undefined &&
Effect.runSync(Clock.currentTimeMillis) - lastLoaded < config.staleTimeMs
) {
return;
}
const version = bumpVersion(targetKey);
clearTimer(targetKey);
setState(targetKey, PENDING_COMPOSER_PATH_SEARCH_STATE);
const current = config.getRegistry().get(composerPathSearchStateAtom(targetKey));
setState(
targetKey,
current.entries.length === 0
? PENDING_COMPOSER_PATH_SEARCH_STATE
: { ...current, isPending: true, error: null },
);
const readyTarget = {
...target,
@@ -211,6 +240,12 @@ export function createComposerPathSearchManager(config: {
return NOOP;
}
const readyTarget = {
...target,
environmentId: target.environmentId,
cwd: target.cwd,
};
const existing = watched.get(targetKey);
if (existing) {
existing.refCount += 1;
@@ -235,7 +270,7 @@ export function createComposerPathSearchManager(config: {
}
currentClient = client;
search(target, client);
search(readyTarget, client);
};
const unsubscribe = config.subscribeClientChanges?.(sync) ?? NOOP;
@@ -243,6 +278,7 @@ export function createComposerPathSearchManager(config: {
watched.set(targetKey, {
refCount: 1,
target: readyTarget,
teardown: () => {
unsubscribe();
clearTimer(targetKey);
@@ -277,9 +313,31 @@ export function createComposerPathSearchManager(config: {
for (const targetKey of timers.keys()) {
clearTimer(targetKey);
}
lastLoadedAt.clear();
}
function invalidate(target?: ComposerPathSearchTarget): void {
if (target) {
const targetKey = getComposerPathSearchTargetKey(target);
if (targetKey === null) {
return;
}
lastLoadedAt.delete(targetKey);
const watchedEntry = watched.get(targetKey);
if (watchedEntry) {
search(watchedEntry.target, undefined, { force: true });
}
return;
}
lastLoadedAt.clear();
for (const watchedEntry of watched.values()) {
search(watchedEntry.target, undefined, { force: true });
}
}
return {
invalidate,
getSnapshot,
search,
watch,
+1
View File
@@ -20,3 +20,4 @@ export * from "./wsRpcClient.ts";
export * from "./environmentConnection.ts";
export * from "./sourceControlDiscoveryState.ts";
export * from "./composerPathSearchState.ts";
export * from "./archivedThreadsState.ts";
@@ -233,6 +233,31 @@ it("watches a discovery target with ref-counted client-change subscriptions", as
assert.strictEqual(unsubscribeCalls, 1);
});
it("reuses fresh watched discovery results on remount", async () => {
let discoveryCalls = 0;
const client = {
discoverSourceControl: async () => {
discoveryCalls += 1;
return EMPTY_RESULT;
},
};
const manager = createSourceControlDiscoveryManager({
getRegistry: () => registry,
getClient: () => client,
staleTimeMs: 60_000,
});
const firstUnwatch = manager.watch({ key: "primary" });
await flushAsyncWork();
firstUnwatch();
const secondUnwatch = manager.watch({ key: "primary" });
await flushAsyncWork();
secondUnwatch();
assert.strictEqual(discoveryCalls, 1);
});
it("refreshes a watched discovery target when the resolved client is replaced", async () => {
let listener: () => void = noop;
let activeResult = EMPTY_RESULT;
@@ -1,4 +1,5 @@
import type { SourceControlDiscoveryResult } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
/* --- Types ---------------------------------------------------------- */
@@ -83,9 +84,13 @@ export interface SourceControlDiscoveryManagerConfig<TKey extends string = strin
* instead of relying on React hooks to manually kick discovery.
*/
readonly subscribeClientChanges?: (listener: () => void) => () => void;
readonly staleTimeMs?: number;
readonly idleTtlMs?: number;
}
const NOOP: () => void = () => undefined;
const DEFAULT_STALE_TIME_MS = 30_000;
const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
export function createSourceControlDiscoveryManager<TKey extends string = string>(
config: SourceControlDiscoveryManagerConfig<TKey>,
@@ -99,6 +104,25 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
>();
const refreshVersions = new Map<string, number>();
const watched = new Map<string, WatchedEntry>();
const refreshTargets = new Map<string, SourceControlDiscoveryTarget<TKey>>();
const staleTimeMs = config.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
const idleTtlMs = config.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
const watchedRefreshAtom = Atom.family((targetKey: string) =>
Atom.make(() =>
Effect.promise(() => {
const target = refreshTargets.get(targetKey);
return target ? refresh(target) : Promise.resolve(null);
}),
).pipe(
Atom.swr({
staleTime: staleTimeMs,
revalidateOnMount: true,
}),
Atom.setIdleTTL(idleTtlMs),
Atom.withLabel(`source-control-discovery:watched-refresh:${targetKey}`),
),
);
function getRefreshVersion(targetKey: string): number {
return refreshVersions.get(targetKey) ?? 0;
@@ -174,6 +198,7 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
if (targetKey === null) {
return Promise.resolve(null);
}
refreshTargets.set(targetKey, target);
const resolvedClient = client ?? config.getClient(targetKey);
if (!resolvedClient) {
@@ -271,6 +296,7 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
if (targetKey === null) {
return NOOP;
}
refreshTargets.set(targetKey, target);
const existing = watched.get(targetKey);
if (existing) {
@@ -298,19 +324,19 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
return;
}
const isClientReplacement = currentClient !== null;
currentClient = resolved;
void refresh(target, resolved);
refreshWatchedTarget(targetKey, target, isClientReplacement ? resolved : undefined);
};
const unsubChanges = config.subscribeClientChanges(sync);
sync();
teardown = unsubChanges;
} else {
const resolved = config.getClient(targetKey);
if (!resolved) {
if (!config.getClient(targetKey)) {
return NOOP;
}
void refresh(target, resolved);
refreshWatchedTarget(targetKey, target);
teardown = NOOP;
}
@@ -333,6 +359,20 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
watched.delete(targetKey);
}
function refreshWatchedTarget(
targetKey: string,
target: SourceControlDiscoveryTarget<TKey>,
client?: SourceControlDiscoveryClient,
): void {
refreshTargets.set(targetKey, target);
if (client) {
void refresh(target, client);
return;
}
config.getRegistry().get(watchedRefreshAtom(targetKey));
}
/**
* Clear in-flight refresh tracking and reset every known discovery atom.
* Primarily used by tests and runtime teardown.
@@ -343,6 +383,7 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
entry.teardown();
}
watched.clear();
refreshTargets.clear();
refreshInFlight.clear();
for (const key of keys) {
bumpRefreshVersion(key);
@@ -292,10 +292,14 @@ describe("createVcsRefManager", () => {
watchLimit: 100,
});
await manager.load(TARGET, mock.client, { limit: 100 });
const unwatch = manager.watch(TARGET);
await Promise.resolve();
const firstUnwatch = manager.watch(TARGET);
await vi.waitFor(() => {
expect(manager.getSnapshot(TARGET).data).toEqual(FIRST_PAGE);
});
firstUnwatch();
const secondUnwatch = manager.watch(TARGET);
await Promise.resolve();
expect(mock.listRefs).toHaveBeenCalledTimes(1);
expect(manager.getSnapshot(TARGET)).toEqual({
data: FIRST_PAGE,
@@ -303,7 +307,7 @@ describe("createVcsRefManager", () => {
error: null,
});
unwatch();
secondUnwatch();
});
it("swallows watched refresh failures after storing error state", async () => {
+54 -20
View File
@@ -6,7 +6,7 @@ import type {
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { Atom, type AtomRegistry, type AsyncResult } from "effect/unstable/reactivity";
import type { WsRpcClient } from "./wsRpcClient.ts";
@@ -111,11 +111,27 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
const loadVersions = new Map<string, number>();
const watched = new Map<string, WatchedEntry>();
const lastLoadedAt = new Map<string, number>();
const refreshTargets = new Map<string, VcsRefTarget>();
const watchLoadOptions =
config.watchLimit === undefined
? undefined
: { limit: config.watchLimit, preserveLoadedRefs: true };
const watchedRefreshAtom = Atom.family((targetKey: string) =>
Atom.make(() =>
Effect.promise(() => {
const target = refreshTargets.get(targetKey);
return target ? load(target, undefined, watchLoadOptions) : Promise.resolve(null);
}),
).pipe(
Atom.swr({
staleTime: config.staleTimeMs ?? 0,
revalidateOnMount: true,
}),
Atom.withLabel(`vcs-refs:watched-refresh:${targetKey}`),
),
);
function getLoadVersion(targetKey: string): number {
return loadVersions.get(targetKey) ?? 0;
}
@@ -178,6 +194,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return null;
}
refreshTargets.set(targetKey, target);
const resolved = client ?? config.getClient(target.environmentId);
if (!resolved) {
@@ -272,6 +289,37 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
});
}
function refreshWatchedTarget(targetKey: string, target: VcsRefTarget, client?: VcsRefClient) {
refreshTargets.set(targetKey, target);
if (client || config.staleTimeMs === undefined) {
const resolved =
client ?? (target.environmentId ? config.getClient(target.environmentId) : null);
if (resolved) {
loadInBackground(target, resolved, watchLoadOptions);
}
return;
}
const lastLoaded = lastLoadedAt.get(targetKey);
if (
lastLoaded !== undefined &&
Effect.runSync(Clock.currentTimeMillis) - lastLoaded < config.staleTimeMs
) {
return;
}
const result = config
.getRegistry()
.get(watchedRefreshAtom(targetKey)) as AsyncResult.AsyncResult<
VcsListRefsResult | null,
unknown
>;
if (result._tag === "Failure") {
config.onBackgroundError?.(result.cause);
}
}
function watch(target: VcsRefTarget, client?: VcsRefClient): () => void {
const targetKey = getVcsRefTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
@@ -285,21 +333,9 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
}
let teardown: () => void;
const shouldRefresh = () => {
if (config.staleTimeMs === undefined) {
return true;
}
const lastLoaded = lastLoadedAt.get(targetKey);
return (
lastLoaded === undefined ||
Effect.runSync(Clock.currentTimeMillis) - lastLoaded >= config.staleTimeMs
);
};
if (client) {
if (shouldRefresh()) {
loadInBackground(target, client, watchLoadOptions);
}
refreshWatchedTarget(targetKey, target, client);
teardown = NOOP;
} else if (config.subscribeClientChanges) {
let currentClient: VcsRefClient | null = null;
@@ -313,10 +349,9 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
return;
}
const hadClient = currentClient !== null;
currentClient = resolved;
if (shouldRefresh()) {
loadInBackground(target, resolved, watchLoadOptions);
}
refreshWatchedTarget(targetKey, target, hadClient ? resolved : undefined);
};
const unsubscribe = config.subscribeClientChanges(sync);
@@ -327,9 +362,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
if (!resolved) {
return NOOP;
}
if (shouldRefresh()) {
loadInBackground(target, resolved, watchLoadOptions);
}
refreshWatchedTarget(targetKey, target);
teardown = NOOP;
}
@@ -394,6 +427,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
inFlight.clear();
loadVersions.clear();
lastLoadedAt.clear();
refreshTargets.clear();
invalidate();
}