Rename git state to VCS and add diff preview caching

- Replace git-scoped client/runtime state with VCS-scoped APIs
- Add checkpoint diff preview state and reuse cached diffs
- Update mobile and web review flows to use the new shared state
This commit is contained in:
Julius Marminge committed 2026-05-08 20:41:39 -07:00
1 parent 01596f53ad
commit 4ec9647ce7
40 files changed
+1114 -749

No files matched your search

+4 -4
View File
@@ -1,7 +1,7 @@
import type {
EnvironmentScopedProjectShell,
EnvironmentScopedThreadShell,
GitStatusState,
VcsStatusState,
} from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react";
@@ -14,7 +14,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { useGitStatus } from "../../state/use-git-status";
import { useVcsStatus } from "../../state/use-vcs-status";
import { threadStatusTone } from "../threads/threadPresentation";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -97,7 +97,7 @@ function ProjectGroupLabel(props: {
/* ─── Git summary line ──────────────────────────────────────────────── */
function gitSummaryParts(gitStatus: GitStatusState): ReadonlyArray<string> {
function gitSummaryParts(gitStatus: VcsStatusState): ReadonlyArray<string> {
if (!gitStatus.data) return [];
const { data } = gitStatus;
const parts: string[] = [];
@@ -127,7 +127,7 @@ function ThreadRow(props: {
// Subscribe to live git status — only when thread has a branch set.
// Threads sharing the same cwd share one WS subscription via ref-counting.
const cwd = branch ? (props.thread.worktreePath ?? props.projectCwd) : null;
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: cwd ? props.thread.environmentId : null,
cwd,
});
@@ -0,0 +1,110 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId, ReviewDiffPreviewResult } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { getEnvironmentClient } from "../../state/environment-session-registry";
const REVIEW_DIFF_PREVIEW_STALE_TIME_MS = 5_000;
const REVIEW_DIFF_PREVIEW_IDLE_TTL_MS = 5 * 60_000;
const REVIEW_DIFF_PREVIEW_KEY_SEPARATOR = "\u001f";
export interface ReviewDiffPreviewState {
readonly data: ReviewDiffPreviewResult | null;
readonly error: string | null;
readonly isPending: boolean;
readonly refresh: () => void;
}
function makeReviewDiffPreviewKey(input: {
readonly environmentId: EnvironmentId;
readonly cwd: string;
}): string {
return `${input.environmentId}${REVIEW_DIFF_PREVIEW_KEY_SEPARATOR}${input.cwd}`;
}
function parseReviewDiffPreviewKey(key: string): {
readonly environmentId: EnvironmentId;
readonly cwd: string;
} {
const [environmentId, cwd = ""] = key.split(REVIEW_DIFF_PREVIEW_KEY_SEPARATOR);
return {
environmentId: environmentId as EnvironmentId,
cwd,
};
}
const reviewDiffPreviewAtom = Atom.family((key: string) =>
Atom.make(
Effect.promise(async (): Promise<ReviewDiffPreviewResult> => {
const target = parseReviewDiffPreviewKey(key);
const client = getEnvironmentClient(target.environmentId);
if (!client) {
throw new Error("Remote connection is not ready.");
}
return client.review.getDiffPreview({ cwd: target.cwd });
}),
).pipe(
Atom.swr({
staleTime: REVIEW_DIFF_PREVIEW_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(REVIEW_DIFF_PREVIEW_IDLE_TTL_MS),
Atom.withLabel(`mobile:review:diff-preview:${key}`),
),
);
const EMPTY_REVIEW_DIFF_PREVIEW_RESULT_ATOM = Atom.make(
AsyncResult.initial<ReviewDiffPreviewResult, never>(false),
).pipe(Atom.keepAlive, Atom.withLabel("mobile:review:diff-preview:null"));
function readReviewDiffPreviewError(
result: AsyncResult.AsyncResult<ReviewDiffPreviewResult, unknown>,
): string | null {
if (result._tag !== "Failure") {
return null;
}
const error = Cause.squash(result.cause);
return error instanceof Error ? error.message : "Failed to load review diffs.";
}
export function useReviewDiffPreview(input: {
readonly environmentId?: EnvironmentId;
readonly cwd: string | null;
}): ReviewDiffPreviewState {
const key = useMemo(() => {
if (!input.environmentId || !input.cwd) {
return null;
}
return makeReviewDiffPreviewKey({ environmentId: input.environmentId, cwd: input.cwd });
}, [input.cwd, input.environmentId]);
const atom = key ? reviewDiffPreviewAtom(key) : null;
const result = useAtomValue(atom ?? EMPTY_REVIEW_DIFF_PREVIEW_RESULT_ATOM);
const refresh = useCallback(() => {
if (atom) {
appAtomRegistry.refresh(atom);
}
}, [atom]);
if (!atom) {
return {
data: null,
error: null,
isPending: false,
refresh,
};
}
return {
data: Option.getOrNull(AsyncResult.value(result)),
error: readReviewDiffPreviewError(result),
isPending: result.waiting,
refresh,
};
}
@@ -3,29 +3,24 @@ import { assert, it } from "vitest";
import {
getReviewAsyncStateSnapshot,
setReviewAsyncError,
setReviewGitDiffsLoading,
setReviewTurnDiffLoading,
} from "./reviewState";
it("stores review async loading and error state in atoms", () => {
const threadKey = `env-local:thread-review-state-${Date.now()}`;
setReviewGitDiffsLoading(threadKey, true);
setReviewTurnDiffLoading(threadKey, "turn-1", true);
setReviewAsyncError(threadKey, "load failed");
assert.deepStrictEqual(getReviewAsyncStateSnapshot(threadKey), {
loadingGitDiffs: true,
loadingTurnIds: { "turn-1": true },
error: "load failed",
});
setReviewGitDiffsLoading(threadKey, false);
setReviewTurnDiffLoading(threadKey, "turn-1", false);
setReviewAsyncError(threadKey, null);
assert.deepStrictEqual(getReviewAsyncStateSnapshot(threadKey), {
loadingGitDiffs: false,
loadingTurnIds: {},
error: null,
});
@@ -11,7 +11,6 @@ const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewS
const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
const EMPTY_REVIEW_LOADING_TURN_IDS = Object.freeze<Readonly<Record<string, boolean>>>({});
const EMPTY_REVIEW_ASYNC_STATE = Object.freeze<ReviewAsyncState>({
loadingGitDiffs: false,
loadingTurnIds: EMPTY_REVIEW_LOADING_TURN_IDS,
error: null,
});
@@ -109,7 +108,6 @@ export interface ReviewCacheForThread {
}
export interface ReviewAsyncState {
readonly loadingGitDiffs: boolean;
readonly loadingTurnIds: Readonly<Record<string, boolean>>;
readonly error: string | null;
}
@@ -200,13 +198,6 @@ function updateReviewAsyncState(
appAtomRegistry.set(atom, update(appAtomRegistry.get(atom)));
}
export function setReviewGitDiffsLoading(threadKey: string, loadingGitDiffs: boolean): void {
updateReviewAsyncState(threadKey, (current) => ({
...current,
loadingGitDiffs,
}));
}
export function setReviewTurnDiffLoading(
threadKey: string,
sectionId: string,
@@ -3,8 +3,10 @@ import { useCallback, useEffect, useMemo, useRef } from "react";
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { checkpointDiffManager, loadCheckpointDiff } from "../../state/use-checkpoint-diff";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useReviewDiffPreview } from "./reviewDiffPreviewState";
import {
buildReviewSectionItems,
getDefaultReviewSectionId,
@@ -13,7 +15,6 @@ import {
} from "./reviewModel";
import {
setReviewAsyncError,
setReviewGitDiffsLoading,
setReviewGitSections,
setReviewSelectedSectionId,
setReviewTurnDiffLoading,
@@ -29,13 +30,23 @@ export function useReviewSections(input: {
const { environmentId, reviewCache, threadId } = input;
const selectedThread = useSelectedThreadDetail();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const { error, loadingGitDiffs, loadingTurnIds } = reviewCache.asyncState;
const diffPreview = useReviewDiffPreview({ environmentId, cwd: selectedThreadCwd });
const refreshDiffPreview = diffPreview.refresh;
const { loadingTurnIds } = reviewCache.asyncState;
const error = diffPreview.error ?? reviewCache.asyncState.error;
const loadingGitDiffs = diffPreview.isPending;
const turnDiffByIdRef = useRef(reviewCache.turnDiffById);
useEffect(() => {
turnDiffByIdRef.current = reviewCache.turnDiffById;
}, [reviewCache.turnDiffById]);
useEffect(() => {
if (reviewCache.threadKey && diffPreview.data) {
setReviewGitSections(reviewCache.threadKey, diffPreview.data.sources);
}
}, [diffPreview.data, reviewCache.threadKey]);
const readyCheckpoints = useMemo(
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
[selectedThread?.checkpoints],
@@ -78,42 +89,6 @@ export function useReviewSections(input: {
[reviewCache.selectedSectionId, reviewSections],
);
const loadGitDiffs = useCallback(async () => {
if (!environmentId || !selectedThreadCwd) {
return;
}
const client = getEnvironmentClient(environmentId);
if (!client) {
if (reviewCache.threadKey) {
setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready.");
}
return;
}
if (reviewCache.threadKey) {
setReviewGitDiffsLoading(reviewCache.threadKey, true);
setReviewAsyncError(reviewCache.threadKey, null);
}
try {
const result = await client.review.getDiffPreview({ cwd: selectedThreadCwd });
if (reviewCache.threadKey) {
setReviewGitSections(reviewCache.threadKey, result.sources);
}
} catch (cause) {
if (reviewCache.threadKey) {
setReviewAsyncError(
reviewCache.threadKey,
cause instanceof Error ? cause.message : "Failed to load review diffs.",
);
}
} finally {
if (reviewCache.threadKey) {
setReviewGitDiffsLoading(reviewCache.threadKey, false);
}
}
}, [environmentId, reviewCache.threadKey, selectedThreadCwd]);
const loadTurnDiff = useCallback(
async (checkpoint: OrchestrationCheckpointSummary, force = false) => {
if (!environmentId || !threadId) {
@@ -129,8 +104,23 @@ export function useReviewSections(input: {
return;
}
const client = getEnvironmentClient(environmentId);
if (!client) {
const target = {
environmentId,
threadId,
fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
toTurnCount: checkpoint.checkpointTurnCount,
ignoreWhitespace: false,
cacheScope: sectionId,
};
const cached = checkpointDiffManager.getSnapshot(target).data;
if (!force && cached) {
if (reviewCache.threadKey) {
setReviewTurnDiff(reviewCache.threadKey, sectionId, cached.diff);
}
return;
}
if (!getEnvironmentClient(environmentId)) {
if (reviewCache.threadKey) {
setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready.");
}
@@ -142,13 +132,11 @@ export function useReviewSections(input: {
setReviewAsyncError(reviewCache.threadKey, null);
}
try {
const result = await client.orchestration.getTurnDiff({
threadId,
fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
toTurnCount: checkpoint.checkpointTurnCount,
});
const result = await loadCheckpointDiff(target, { force });
if (reviewCache.threadKey) {
setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff);
if (result) {
setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff);
}
}
} catch (cause) {
if (reviewCache.threadKey) {
@@ -166,10 +154,6 @@ export function useReviewSections(input: {
[environmentId, reviewCache.threadKey, threadId],
);
useEffect(() => {
void loadGitDiffs();
}, [loadGitDiffs]);
useEffect(() => {
if (!hasReviewSections) {
return;
@@ -237,8 +221,8 @@ export function useReviewSections(input: {
return;
}
await loadGitDiffs();
}, [checkpointBySectionId, loadGitDiffs, loadTurnDiff, selectedSection]);
refreshDiffPreview();
}, [checkpointBySectionId, loadTurnDiff, refreshDiffPreview, selectedSection]);
const selectSection = useCallback(
(sectionId: string) => {
@@ -7,7 +7,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { GitActionProgress } from "../../state/use-git-action-state";
import type { GitActionProgress } from "../../state/use-vcs-action-state";
export function GitActionProgressOverlay(props: {
readonly progress: GitActionProgress;
@@ -7,8 +7,8 @@ import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
import { dismissGitActionResult, useGitActionProgress } from "../../state/use-git-action-state";
import { useVcsStatus, vcsStatusManager } from "../../state/use-vcs-status";
import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
@@ -94,7 +94,7 @@ export function ThreadRouteScreen() {
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
@@ -124,7 +124,7 @@ export function ThreadRouteScreen() {
const handleRefreshGitStatus = useCallback(async () => {
if (!selectedThread) return;
await gitStatusManager.refresh({
await vcsStatusManager.refresh({
environmentId: selectedThread.environmentId,
cwd: selectedThreadCwd,
});
@@ -6,7 +6,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
import { useVcsStatus } from "../../../state/use-vcs-status";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
@@ -27,7 +27,7 @@ export function GitBranchesSheet() {
const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
@@ -5,7 +5,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
import { useVcsStatus } from "../../../state/use-vcs-status";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
@@ -27,7 +27,7 @@ export function GitCommitSheet() {
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
@@ -14,7 +14,7 @@ import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { buildThreadReviewRoutePath } from "../../../lib/routes";
import { useGitStatus } from "../../../state/use-git-status";
import { useVcsStatus } from "../../../state/use-vcs-status";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
@@ -36,7 +36,7 @@ export function GitOverviewSheet() {
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
@@ -0,0 +1,16 @@
import { createCheckpointDiffManager, type CheckpointDiffTarget } from "@t3tools/client-runtime";
import { appAtomRegistry } from "./atom-registry";
import { getEnvironmentClient } from "./environment-session-registry";
export const checkpointDiffManager = createCheckpointDiffManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => getEnvironmentClient(environmentId)?.orchestration ?? null,
});
export function loadCheckpointDiff(
target: CheckpointDiffTarget,
options?: { readonly force?: boolean },
) {
return checkpointDiffManager.load(target, undefined, options);
}
@@ -15,9 +15,9 @@ import {
import { uuidv4 } from "../lib/uuid";
import { getEnvironmentClient } from "./environment-session-registry";
import { setPendingConnectionError } from "./use-remote-environment-registry";
import { gitActionManager, showGitActionResult } from "./use-git-action-state";
import { vcsActionManager, showGitActionResult } from "./use-vcs-action-state";
import { vcsRefManager } from "./use-vcs-refs";
import { gitStatusManager } from "./use-git-status";
import { vcsStatusManager } from "./use-vcs-status";
import { useThreadSelection } from "./use-thread-selection";
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
@@ -68,9 +68,9 @@ export function useSelectedThreadGitActions() {
return null;
}
const status = await gitActionManager.refreshStatus(
const status = await vcsActionManager.refreshStatus(
{ environmentId: selectedThread.environmentId, cwd },
{ ...client.vcs, runStackedAction: client.git.runStackedAction },
{ ...client.vcs, runChangeRequest: client.git.runStackedAction },
options,
);
setPendingConnectionError(null);
@@ -190,7 +190,7 @@ export function useSelectedThreadGitActions() {
const onCheckoutSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.switchRef(
const result = await vcsActionManager.switchRef(
{ environmentId: thread.environmentId, cwd },
{ refName: branch },
);
@@ -210,7 +210,7 @@ export function useSelectedThreadGitActions() {
const onCreateSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.createRef(
const result = await vcsActionManager.createRef(
{ environmentId: thread.environmentId, cwd },
{
refName: branch,
@@ -233,7 +233,7 @@ export function useSelectedThreadGitActions() {
const onCreateSelectedThreadWorktree = useCallback(
async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
await runSelectedThreadGitMutation(async ({ thread, project }) => {
const result = await gitActionManager.createWorktree(
const result = await vcsActionManager.createWorktree(
{ environmentId: thread.environmentId, cwd: project.workspaceRoot },
{
refName: nextWorktree.baseBranch,
@@ -261,7 +261,7 @@ export function useSelectedThreadGitActions() {
const onPullSelectedThreadBranch = useCallback(async () => {
await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.pull({ environmentId: thread.environmentId, cwd });
const result = await vcsActionManager.pull({ environmentId: thread.environmentId, cwd });
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
if (result) {
showGitActionResult({
@@ -278,7 +278,7 @@ export function useSelectedThreadGitActions() {
const onRunSelectedThreadGitAction = useCallback(
async (input: GitActionRequestInput): Promise<GitRunStackedActionResult | null> => {
return await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.runStackedAction(
const result = await vcsActionManager.runChangeRequest(
{ environmentId: thread.environmentId, cwd },
{
actionId: uuidv4(),
@@ -288,7 +288,7 @@ export function useSelectedThreadGitActions() {
...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
},
{
gitStatus: gitStatusManager.getSnapshot({
gitStatus: vcsStatusManager.getSnapshot({
environmentId: thread.environmentId,
cwd,
}).data,
@@ -2,7 +2,7 @@ import { useMemo } from "react";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { useGitActionState } from "./use-git-action-state";
import { useVcsActionState } from "./use-vcs-action-state";
import { useVcsRefs } from "./use-vcs-refs";
import { useSourceControlDiscovery } from "./use-source-control-discovery";
import { useThreadSelection } from "./use-thread-selection";
@@ -19,7 +19,7 @@ export function useSelectedThreadGitState() {
}),
[selectedThread?.environmentId, selectedThreadCwd],
);
const gitActionState = useGitActionState(selectedThreadGitTarget);
const gitActionState = useVcsActionState(selectedThreadGitTarget);
const sourceControlDiscovery = useSourceControlDiscovery(selectedThread?.environmentId ?? null);
const selectedThreadBranchTarget = useMemo(
@@ -1,12 +1,12 @@
import { useAtomValue } from "@effect/atom-react";
import {
type GitActionState,
type GitActionTarget,
EMPTY_GIT_ACTION_ATOM,
EMPTY_GIT_ACTION_STATE,
createGitActionManager,
getGitActionTargetKey,
gitActionStateAtom,
type VcsActionState,
type VcsActionTarget,
EMPTY_VCS_ACTION_ATOM,
EMPTY_VCS_ACTION_STATE,
createVcsActionManager,
getVcsActionTargetKey,
vcsActionStateAtom,
} from "@t3tools/client-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -14,21 +14,21 @@ import { uuidv4 } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
import { getEnvironmentClient } from "./environment-session-registry";
export const gitActionManager = createGitActionManager({
export const vcsActionManager = createVcsActionManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const client = getEnvironmentClient(environmentId);
return client ? { ...client.vcs, runStackedAction: client.git.runStackedAction } : null;
return client ? { ...client.vcs, runChangeRequest: client.git.runStackedAction } : null;
},
getActionId: uuidv4,
});
export function useGitActionState(target: GitActionTarget): GitActionState {
const targetKey = getGitActionTargetKey(target);
export function useVcsActionState(target: VcsActionTarget): VcsActionState {
const targetKey = getVcsActionTargetKey(target);
const state = useAtomValue(
targetKey !== null ? gitActionStateAtom(targetKey) : EMPTY_GIT_ACTION_ATOM,
targetKey !== null ? vcsActionStateAtom(targetKey) : EMPTY_VCS_ACTION_ATOM,
);
return targetKey === null ? EMPTY_GIT_ACTION_STATE : state;
return targetKey === null ? EMPTY_VCS_ACTION_STATE : state;
}
// ---------------------------------------------------------------------------
@@ -110,8 +110,8 @@ function formatElapsedSeconds(ms: number | null): string | null {
return `Running for ${elapsed}s`;
}
export function useGitActionProgress(target: GitActionTarget): GitActionProgress {
const actionState = useGitActionState(target);
export function useGitActionProgress(target: VcsActionTarget): GitActionProgress {
const actionState = useVcsActionState(target);
const { result } = useGitActionResultNotification();
const [, forceUpdate] = useState(0);
@@ -1,12 +1,12 @@
import { useAtomValue } from "@effect/atom-react";
import {
type GitStatusState,
type GitStatusTarget,
EMPTY_GIT_STATUS_ATOM,
EMPTY_GIT_STATUS_STATE,
createGitStatusManager,
getGitStatusTargetKey,
gitStatusStateAtom,
type VcsStatusState,
type VcsStatusTarget,
EMPTY_VCS_STATUS_ATOM,
EMPTY_VCS_STATUS_STATE,
createVcsStatusManager,
getVcsStatusTargetKey,
vcsStatusStateAtom,
} from "@t3tools/client-runtime";
import { useEffect } from "react";
@@ -17,7 +17,7 @@ import {
} from "./environment-session-registry";
/**
* Singleton git status manager for the mobile app.
* Singleton VCS status manager for the mobile app.
*
* Uses ref-counted `onStatus` subscriptions (one per unique cwd)
* rather than one-shot `refreshStatus` RPCs. Multiple threads
@@ -28,7 +28,7 @@ import {
* even when the WS connection isn't ready at mount time, and
* re-established on reconnection.
*/
export const gitStatusManager = createGitStatusManager({
export const vcsStatusManager = createVcsStatusManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const client = getEnvironmentClient(environmentId);
@@ -41,22 +41,22 @@ export const gitStatusManager = createGitStatusManager({
});
/**
* Subscribe to live git status for a target (environmentId + cwd).
* Subscribe to live VCS status for a target (environmentId + cwd).
*
* Mirrors the web's `useGitStatus` hook. Automatically subscribes
* Mirrors the web's `useVcsStatus` hook. Automatically subscribes
* on mount, ref-counts shared cwds, and unsubscribes on unmount.
* Returns reactive `GitStatusState` via Effect atoms.
* Returns reactive `VcsStatusState` via Effect atoms.
*/
export function useGitStatus(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
export function useVcsStatus(target: VcsStatusTarget): VcsStatusState {
const targetKey = getVcsStatusTargetKey(target);
useEffect(
() => gitStatusManager.watch({ environmentId: target.environmentId, cwd: target.cwd }),
() => vcsStatusManager.watch({ environmentId: target.environmentId, cwd: target.cwd }),
[target.environmentId, target.cwd],
);
const state = useAtomValue(
targetKey !== null ? gitStatusStateAtom(targetKey) : EMPTY_GIT_STATUS_ATOM,
targetKey !== null ? vcsStatusStateAtom(targetKey) : EMPTY_VCS_STATUS_ATOM,
);
return targetKey === null ? EMPTY_GIT_STATUS_STATE : state;
return targetKey === null ? EMPTY_VCS_STATUS_STATE : state;
}
@@ -15,7 +15,7 @@ import {
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { readEnvironmentApi } from "../environmentApi";
import { useGitStatus } from "../lib/gitStatusState";
import { useVcsStatus } from "../lib/vcsStatusState";
import { useVcsRefs, vcsRefManager } from "../lib/vcsRefState";
import { newCommandId } from "../lib/utils";
import { cn } from "../lib/utils";
@@ -201,7 +201,7 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
const branchStatusQuery = useVcsStatus({ environmentId, cwd: branchCwd });
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
const branchRefTarget = useMemo(
+5 -5
View File
@@ -65,11 +65,11 @@ import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
vi.mock("../lib/gitStatusState", () => ({
useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useGitStatuses: () => new Map(),
refreshGitStatus: () => Promise.resolve(null),
resetGitStatusStateForTests: () => undefined,
vi.mock("../lib/vcsStatusState", () => ({
useVcsStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useVcsStatuses: () => new Map(),
refreshVcsStatus: () => Promise.resolve(null),
resetVcsStatusStateForTests: () => undefined,
}));
const THREAD_ID = "thread-browser-test" as ThreadId;
+2 -2
View File
@@ -39,7 +39,7 @@ import { Debouncer } from "@tanstack/react-pacer";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import { useGitStatus } from "~/lib/gitStatusState";
import { useVcsStatus } from "~/lib/vcsStatusState";
import { usePrimaryEnvironmentId } from "../environments/primary";
import { readEnvironmentApi } from "../environmentApi";
import { isElectron } from "../env";
@@ -1830,7 +1830,7 @@ export default function ChatView(props: ChatViewProps) {
worktreePath: activeThread?.worktreePath ?? null,
})
: null;
const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });
const gitStatusQuery = useVcsStatus({ environmentId, cwd: gitCwd });
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
// Prefer an instance-id match so a custom Codex instance (e.g.
+11 -21
View File
@@ -1,5 +1,4 @@
import { FileDiff, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { scopeThreadRef } from "@t3tools/client-runtime";
import type { TurnId } from "@t3tools/contracts";
@@ -21,8 +20,8 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { useGitStatus } from "~/lib/gitStatusState";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { useCheckpointDiff } from "~/lib/checkpointDiffState";
import { useVcsStatus } from "~/lib/vcsStatusState";
import { cn } from "~/lib/utils";
import { readLocalApi } from "../localApi";
import { resolvePathLinkTarget } from "../terminal-links";
@@ -152,7 +151,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
: undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitStatusQuery = useGitStatus({
const gitStatusQuery = useVcsStatus({
environmentId: activeThread?.environmentId ?? null,
cwd: activeCwd ?? null,
});
@@ -226,30 +225,21 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
}
return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
}, [orderedTurnDiffSummaries, selectedTurn]);
const activeCheckpointDiffQuery = useQuery(
checkpointDiffQueryOptions({
const activeCheckpointDiff = useCheckpointDiff(
{
environmentId: activeThread?.environmentId ?? null,
threadId: activeThreadId,
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
ignoreWhitespace: diffIgnoreWhitespace,
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
enabled: isGitRepo,
}),
},
{ enabled: isGitRepo },
);
const selectedTurnCheckpointDiff = selectedTurn
? activeCheckpointDiffQuery.data?.diff
: undefined;
const conversationCheckpointDiff = selectedTurn
? undefined
: activeCheckpointDiffQuery.data?.diff;
const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
const checkpointDiffError =
activeCheckpointDiffQuery.error instanceof Error
? activeCheckpointDiffQuery.error.message
: activeCheckpointDiffQuery.error
? "Failed to load checkpoint diff."
: null;
const selectedTurnCheckpointDiff = selectedTurn ? activeCheckpointDiff.data?.diff : undefined;
const conversationCheckpointDiff = selectedTurn ? undefined : activeCheckpointDiff.data?.diff;
const isLoadingCheckpointDiff = activeCheckpointDiff.isPending;
const checkpointDiffError = activeCheckpointDiff.error;
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
const hasResolvedPatch = typeof selectedPatch === "string";
@@ -27,7 +27,7 @@ const {
activeDraftThreadRef,
hasServerThreadRef,
invalidateSourceControlStateSpy,
refreshGitStatusSpy,
refreshVcsStatusSpy,
runStackedActionSpy,
setDraftThreadContextSpy,
setThreadBranchSpy,
@@ -40,7 +40,7 @@ const {
activeDraftThreadRef: { current: null as unknown },
hasServerThreadRef: { current: true },
invalidateSourceControlStateSpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
refreshVcsStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
setDraftThreadContextSpy: vi.fn(),
setThreadBranchSpy: vi.fn(),
@@ -93,10 +93,10 @@ vi.mock("~/lib/sourceControlActions", () => ({
})),
}));
vi.mock("~/lib/gitStatusState", () => ({
refreshGitStatus: refreshGitStatusSpy,
resetGitStatusStateForTests: () => undefined,
useGitStatus: vi.fn(() => ({
vi.mock("~/lib/vcsStatusState", () => ({
refreshVcsStatus: refreshVcsStatusSpy,
resetVcsStatusStateForTests: () => undefined,
useVcsStatus: vi.fn(() => ({
data: {
isRepo: true,
sourceControlProvider: {
@@ -362,14 +362,14 @@ describe("GitActionsControl thread-scoped progress toast", () => {
visibilityState = "visible";
document.dispatchEvent(new Event("visibilitychange"));
expect(refreshGitStatusSpy).not.toHaveBeenCalled();
expect(refreshVcsStatusSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(249);
expect(refreshGitStatusSpy).not.toHaveBeenCalled();
expect(refreshVcsStatusSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
expect(refreshGitStatusSpy).toHaveBeenCalledWith({
expect(refreshVcsStatusSpy).toHaveBeenCalledTimes(1);
expect(refreshVcsStatusSpy).toHaveBeenCalledWith({
environmentId: ENVIRONMENT_A,
cwd: GIT_CWD,
});
@@ -71,7 +71,7 @@ import {
useVcsInitAction,
useVcsPullAction,
} from "~/lib/sourceControlActions";
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { refreshVcsStatus, useVcsStatus } from "~/lib/vcsStatusState";
import { useSourceControlDiscovery } from "~/lib/sourceControlDiscoveryState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
@@ -410,7 +410,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
setPublishResult(result);
setPublishWizardStep(2);
});
void refreshGitStatus({ environmentId: props.environmentId, cwd: props.gitCwd }).catch(
void refreshVcsStatus({ environmentId: props.environmentId, cwd: props.gitCwd }).catch(
() => undefined,
);
})
@@ -989,7 +989,7 @@ export default function GitActionsControl({
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useGitStatus({
const { data: gitStatus = null, error: gitStatusError } = useVcsStatus({
environmentId: activeEnvironmentId,
cwd: gitCwd,
});
@@ -1094,7 +1094,7 @@ export default function GitActionsControl({
}
refreshTimeout = window.setTimeout(() => {
refreshTimeout = null;
void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
void refreshVcsStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
() => undefined,
);
}, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
@@ -1590,7 +1590,7 @@ export default function GitActionsControl({
<Menu
onOpenChange={(open) => {
if (open) {
void refreshGitStatus({
void refreshVcsStatus({
environmentId: activeEnvironmentId,
cwd: gitCwd,
}).catch(() => undefined);
@@ -33,11 +33,11 @@ import { useStore } from "../store";
import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
vi.mock("../lib/gitStatusState", () => ({
useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useGitStatuses: () => new Map(),
refreshGitStatus: () => Promise.resolve(null),
resetGitStatusStateForTests: () => undefined,
vi.mock("../lib/vcsStatusState", () => ({
useVcsStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useVcsStatuses: () => new Map(),
refreshVcsStatus: () => Promise.resolve(null),
resetVcsStatusStateForTests: () => undefined,
}));
const THREAD_ID = "thread-kb-toast-test" as ThreadId;
@@ -7,7 +7,7 @@ import {
usePreparePullRequestThreadAction,
usePullRequestResolution,
} from "~/lib/sourceControlActions";
import { useGitStatus } from "~/lib/gitStatusState";
import { useVcsStatus } from "~/lib/vcsStatusState";
import { cn } from "~/lib/utils";
import { parsePullRequestReference } from "~/pullRequestReference";
import { getSourceControlPresentation } from "~/sourceControlPresentation";
@@ -52,7 +52,7 @@ export function PullRequestThreadDialog({
{ wait: 450 },
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const { data: gitStatus = null } = useGitStatus({ environmentId, cwd });
const { data: gitStatus = null } = useVcsStatus({ environmentId, cwd });
const sourceControlPresentation = useMemo(
() => getSourceControlPresentation(gitStatus?.sourceControlProvider),
[gitStatus?.sourceControlProvider],
+2 -2
View File
@@ -86,7 +86,7 @@ import {
} from "../keybindings";
import { useModelPickerOpen } from "../modelPickerOpenState";
import { useShortcutModifierState } from "../shortcutModifierState";
import { useGitStatus } from "../lib/gitStatusState";
import { useVcsStatus } from "../lib/vcsStatusState";
import { readLocalApi } from "../localApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
@@ -370,7 +370,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
),
);
const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: thread.environmentId,
cwd: thread.branch != null ? gitCwd : null,
});
@@ -7,7 +7,7 @@ import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import { useGitStatus } from "../lib/gitStatusState";
import { useVcsStatus } from "../lib/vcsStatusState";
import { type AppState, selectProjectByRef, useStore } from "../store";
import { useThreadRunningTerminalIds } from "../terminalSessionState";
import { useUiStateStore } from "../uiStateStore";
@@ -150,7 +150,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
),
);
const gitCwd = thread.worktreePath ?? threadProjectCwd;
const gitStatus = useGitStatus({
const gitStatus = useVcsStatus({
environmentId: thread.environmentId,
cwd: thread.branch != null ? gitCwd : null,
});
@@ -108,12 +108,6 @@ vi.mock("~/orchestrationEventEffects", () => ({
})),
}));
vi.mock("~/lib/providerReactQuery", () => ({
providerQueryKeys: {
all: ["providers"],
},
}));
vi.mock("~/store", () => ({
useStore: {
getState: () => ({
@@ -33,7 +33,6 @@ import {
import { ensureLocalApi } from "~/localApi";
import { collectActiveTerminalUiThreadKeys } from "~/lib/terminalUiStateCleanup";
import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
import { providerQueryKeys } from "~/lib/providerReactQuery";
import { getPrimaryKnownEnvironment } from "../primary";
import {
bootstrapRemoteBearerSession,
@@ -1782,7 +1781,6 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
return;
}
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
emitProviderInvalidation();
},
{
+63
View File
@@ -0,0 +1,63 @@
import { useAtomValue } from "@effect/atom-react";
import {
type CheckpointDiffState,
type CheckpointDiffTarget,
checkpointDiffStateAtom,
createCheckpointDiffManager,
EMPTY_CHECKPOINT_DIFF_ATOM,
EMPTY_CHECKPOINT_DIFF_STATE,
getCheckpointDiffTargetKey,
} from "@t3tools/client-runtime";
import { useEffect, useMemo } from "react";
import { readEnvironmentApi } from "../environmentApi";
import { subscribeProviderInvalidations } from "../environments/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
const checkpointDiffManager = createCheckpointDiffManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => readEnvironmentApi(environmentId)?.orchestration ?? null,
});
export function invalidateCheckpointDiffs(): void {
checkpointDiffManager.invalidate();
}
subscribeProviderInvalidations(invalidateCheckpointDiffs);
export function useCheckpointDiff(
target: CheckpointDiffTarget,
options?: { readonly enabled?: boolean },
): CheckpointDiffState {
const stableTarget = useMemo(
() => ({
environmentId: target.environmentId,
threadId: target.threadId,
fromTurnCount: target.fromTurnCount,
toTurnCount: target.toTurnCount,
ignoreWhitespace: target.ignoreWhitespace,
cacheScope: target.cacheScope ?? null,
}),
[
target.cacheScope,
target.environmentId,
target.fromTurnCount,
target.ignoreWhitespace,
target.threadId,
target.toTurnCount,
],
);
const targetKey = getCheckpointDiffTargetKey(stableTarget);
useEffect(() => {
if (targetKey === null || options?.enabled === false) {
return;
}
void checkpointDiffManager.load(stableTarget);
}, [options?.enabled, stableTarget, targetKey]);
const state = useAtomValue(
targetKey !== null ? checkpointDiffStateAtom(targetKey) : EMPTY_CHECKPOINT_DIFF_ATOM,
);
return targetKey === null || options?.enabled === false ? EMPTY_CHECKPOINT_DIFF_STATE : state;
}
-224
View File
@@ -1,224 +0,0 @@
import { EnvironmentId, ThreadId, type EnvironmentApi } from "@t3tools/contracts";
import { QueryClient } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { checkpointDiffQueryOptions, providerQueryKeys } from "./providerReactQuery";
import * as environmentApi from "../environmentApi";
const threadId = ThreadId.make("thread-id");
const environmentId = EnvironmentId.make("environment-local");
function mockNativeApi(input: {
getTurnDiff: ReturnType<typeof vi.fn>;
getFullThreadDiff: ReturnType<typeof vi.fn>;
}) {
vi.spyOn(environmentApi, "ensureEnvironmentApi").mockReturnValue({
orchestration: {
getTurnDiff: input.getTurnDiff,
getFullThreadDiff: input.getFullThreadDiff,
},
} as unknown as EnvironmentApi);
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("providerQueryKeys.checkpointDiff", () => {
it("includes cacheScope so reused turn counts do not collide", () => {
const baseInput = {
environmentId,
threadId,
fromTurnCount: 1,
toTurnCount: 2,
ignoreWhitespace: false,
} as const;
expect(
providerQueryKeys.checkpointDiff({
...baseInput,
cacheScope: "turn:old-turn",
}),
).not.toEqual(
providerQueryKeys.checkpointDiff({
...baseInput,
cacheScope: "turn:new-turn",
}),
);
});
it("includes ignoreWhitespace so normal and whitespace-hidden diffs do not collide", () => {
const baseInput = {
environmentId,
threadId,
fromTurnCount: 1,
toTurnCount: 2,
cacheScope: "turn:abc",
} as const;
expect(
providerQueryKeys.checkpointDiff({
...baseInput,
ignoreWhitespace: false,
}),
).not.toEqual(
providerQueryKeys.checkpointDiff({
...baseInput,
ignoreWhitespace: true,
}),
);
});
});
describe("checkpointDiffQueryOptions", () => {
it("forwards checkpoint range to the provider API by default", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions({
environmentId,
threadId,
fromTurnCount: 3,
toTurnCount: 4,
ignoreWhitespace: false,
cacheScope: "turn:abc",
});
const queryClient = new QueryClient();
await queryClient.fetchQuery(options);
expect(getTurnDiff).toHaveBeenCalledWith({
threadId,
fromTurnCount: 3,
toTurnCount: 4,
ignoreWhitespace: false,
});
expect(getFullThreadDiff).not.toHaveBeenCalled();
});
it("forwards whitespace-hidden checkpoint range to the provider API", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions({
environmentId,
threadId,
fromTurnCount: 3,
toTurnCount: 4,
ignoreWhitespace: true,
cacheScope: "turn:abc",
});
const queryClient = new QueryClient();
await queryClient.fetchQuery(options);
expect(getTurnDiff).toHaveBeenCalledWith({
threadId,
fromTurnCount: 3,
toTurnCount: 4,
ignoreWhitespace: true,
});
expect(getFullThreadDiff).not.toHaveBeenCalled();
});
it("uses explicit full thread diff API when range starts from zero", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions({
environmentId,
threadId,
fromTurnCount: 0,
toTurnCount: 2,
ignoreWhitespace: true,
cacheScope: "thread:all",
});
const queryClient = new QueryClient();
await queryClient.fetchQuery(options);
expect(getFullThreadDiff).toHaveBeenCalledWith({
threadId,
toTurnCount: 2,
ignoreWhitespace: true,
});
expect(getTurnDiff).not.toHaveBeenCalled();
});
it("fails fast on invalid range and does not call provider RPC", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions({
environmentId,
threadId,
fromTurnCount: 4,
toTurnCount: 3,
ignoreWhitespace: false,
cacheScope: "turn:invalid",
});
const queryClient = new QueryClient();
await expect(queryClient.fetchQuery(options)).rejects.toThrow(
"Checkpoint diff is unavailable.",
);
expect(getTurnDiff).not.toHaveBeenCalled();
expect(getFullThreadDiff).not.toHaveBeenCalled();
});
it("retries checkpoint-not-ready errors longer than generic failures", () => {
const options = checkpointDiffQueryOptions({
environmentId,
threadId,
fromTurnCount: 1,
toTurnCount: 2,
ignoreWhitespace: false,
cacheScope: "turn:abc",
});
const retry = options.retry;
expect(typeof retry).toBe("function");
if (typeof retry !== "function") {
throw new Error("Expected retry to be a function.");
}
expect(retry(1, new Error("Checkpoint turn count 2 exceeds current turn count 1."))).toBe(true);
expect(
retry(11, new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1.")),
).toBe(true);
expect(
retry(12, new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1.")),
).toBe(false);
expect(retry(2, new Error("Something else failed."))).toBe(true);
expect(retry(3, new Error("Something else failed."))).toBe(false);
});
it("backs off longer for checkpoint-not-ready errors", () => {
const options = checkpointDiffQueryOptions({
environmentId,
threadId,
fromTurnCount: 1,
toTurnCount: 2,
ignoreWhitespace: false,
cacheScope: "turn:abc",
});
const retryDelay = options.retryDelay;
expect(typeof retryDelay).toBe("function");
if (typeof retryDelay !== "function") {
throw new Error("Expected retryDelay to be a function.");
}
const checkpointDelay = retryDelay(
4,
new Error("Checkpoint turn count 2 exceeds current turn count 1."),
);
const genericDelay = retryDelay(4, new Error("Network failure"));
expect(typeof checkpointDelay).toBe("number");
expect(typeof genericDelay).toBe("number");
expect((checkpointDelay ?? 0) > (genericDelay ?? 0)).toBe(true);
});
});
-139
View File
@@ -1,139 +0,0 @@
import {
type EnvironmentId,
OrchestrationGetFullThreadDiffInput,
OrchestrationGetTurnDiffInput,
ThreadId,
} from "@t3tools/contracts";
import { queryOptions } from "@tanstack/react-query";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ensureEnvironmentApi } from "../environmentApi";
const decodeFullThreadDiffInput = Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput);
const decodeTurnDiffInput = Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput);
interface CheckpointDiffQueryInput {
environmentId: EnvironmentId | null;
threadId: ThreadId | null;
fromTurnCount: number | null;
toTurnCount: number | null;
ignoreWhitespace: boolean;
cacheScope?: string | null;
enabled?: boolean;
}
export const providerQueryKeys = {
all: ["providers"] as const,
checkpointDiff: (input: CheckpointDiffQueryInput) =>
[
"providers",
"checkpointDiff",
input.environmentId ?? null,
input.threadId,
input.fromTurnCount,
input.toTurnCount,
input.ignoreWhitespace,
input.cacheScope ?? null,
] as const,
};
function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
if (input.fromTurnCount === 0) {
return decodeFullThreadDiffInput({
threadId: input.threadId,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace,
}).pipe(Option.map((fields) => ({ kind: "fullThreadDiff" as const, input: fields })));
}
return decodeTurnDiffInput({
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace,
}).pipe(Option.map((fields) => ({ kind: "turnDiff" as const, input: fields })));
}
function asCheckpointErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return "";
}
function normalizeCheckpointErrorMessage(error: unknown): string {
const message = asCheckpointErrorMessage(error).trim();
if (message.length === 0) {
return "Failed to load checkpoint diff.";
}
const lower = message.toLowerCase();
if (lower.includes("not a git repository")) {
return "Turn diffs are unavailable because this project is not a git repository.";
}
if (
lower.includes("checkpoint unavailable for thread") ||
lower.includes("checkpoint invariant violation")
) {
const separatorIndex = message.indexOf(":");
if (separatorIndex >= 0) {
const detail = message.slice(separatorIndex + 1).trim();
if (detail.length > 0) {
return detail;
}
}
}
return message;
}
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
const message = asCheckpointErrorMessage(error).toLowerCase();
return (
message.includes("exceeds current turn count") ||
message.includes("checkpoint is unavailable for turn") ||
message.includes("filesystem checkpoint is unavailable")
);
}
export function checkpointDiffQueryOptions(input: CheckpointDiffQueryInput) {
const decodedRequest = decodeCheckpointDiffRequest(input);
return queryOptions({
queryKey: providerQueryKeys.checkpointDiff(input),
queryFn: async () => {
if (!input.environmentId || !input.threadId || decodedRequest._tag === "None") {
throw new Error("Checkpoint diff is unavailable.");
}
const api = ensureEnvironmentApi(input.environmentId);
try {
if (decodedRequest.value.kind === "fullThreadDiff") {
return await api.orchestration.getFullThreadDiff(decodedRequest.value.input);
}
return await api.orchestration.getTurnDiff(decodedRequest.value.input);
} catch (error) {
throw new Error(normalizeCheckpointErrorMessage(error), { cause: error });
}
},
enabled:
(input.enabled ?? true) &&
!!input.environmentId &&
!!input.threadId &&
decodedRequest._tag === "Some",
staleTime: Infinity,
retry: (failureCount, error) => {
if (isCheckpointTemporarilyUnavailable(error)) {
return failureCount < 12;
}
return failureCount < 3;
},
retryDelay: (attempt, error) =>
isCheckpointTemporarilyUnavailable(error)
? Math.min(5_000, 250 * 2 ** (attempt - 1))
: Math.min(1_000, 100 * 2 ** (attempt - 1)),
});
}
+114 -18
View File
@@ -1,3 +1,13 @@
import { useAtomValue } from "@effect/atom-react";
import {
type VcsActionOperation,
type VcsActionState,
EMPTY_VCS_ACTION_ATOM,
EMPTY_VCS_ACTION_STATE,
createVcsActionManager,
getVcsActionTargetKey,
vcsActionStateAtom,
} from "@t3tools/client-runtime";
import {
type EnvironmentId,
type GitActionProgressEvent,
@@ -20,8 +30,9 @@ import {
} from "react";
import { ensureEnvironmentApi } from "../environmentApi";
import { requireEnvironmentConnection } from "../environments/runtime";
import { refreshGitStatus } from "./gitStatusState";
import { readEnvironmentConnection } from "../environments/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { getVcsStatusSnapshot, refreshVcsStatus } from "./vcsStatusState";
import { vcsRefManager } from "./vcsRefState";
type SourceControlActionKind =
@@ -43,6 +54,15 @@ interface SourceControlActionState<TArgs extends ReadonlyArray<unknown>, TResult
readonly resetError: () => void;
}
export const vcsActionManager = createVcsActionManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const client = readEnvironmentConnection(environmentId)?.client;
return client ? { ...client.vcs, runChangeRequest: client.git.runStackedAction } : null;
},
onInvalidate: (target) => invalidateSourceControlState(target),
});
const actionListeners = new Set<() => void>();
const activeActionCounts = new Map<string, number>();
@@ -89,6 +109,28 @@ function isAnyActionRunning(
return kinds.some((kind) => (activeActionCounts.get(actionKey(kind, scope)) ?? 0) > 0);
}
function getVcsActionOperationForKind(kind: SourceControlActionKind): VcsActionOperation | null {
switch (kind) {
case "init":
return "init";
case "pull":
return "pull";
case "runStackedAction":
return "run_change_request";
case "publishRepository":
case "preparePullRequestThread":
return null;
}
}
function useVcsActionStateForScope(scope: SourceControlActionScope): VcsActionState {
const targetKey = getVcsActionTargetKey(scope);
const state = useAtomValue(
targetKey !== null ? vcsActionStateAtom(targetKey) : EMPTY_VCS_ACTION_ATOM,
);
return targetKey === null ? EMPTY_VCS_ACTION_STATE : state;
}
export function invalidateSourceControlState(scope?: {
readonly environmentId?: EnvironmentId | null;
readonly cwd?: string | null;
@@ -98,7 +140,7 @@ export function invalidateSourceControlState(scope?: {
if (cwd !== null) {
vcsRefManager.invalidateScope({ environmentId, cwd });
if (environmentId !== null) {
return refreshGitStatus({ environmentId, cwd }).then(
return refreshVcsStatus({ environmentId, cwd }).then(
() => undefined,
() => undefined,
);
@@ -163,22 +205,71 @@ export function useSourceControlActionRunning(
kinds: ReadonlyArray<SourceControlActionKind>,
): boolean {
const stableKinds = useMemo(() => [...kinds].sort(), [kinds]);
return useSyncExternalStore(
const appActionRunning = useSyncExternalStore(
subscribeActionState,
() => isAnyActionRunning(stableKinds, scope),
() => false,
);
const vcsActionState = useVcsActionStateForScope(scope);
const vcsActionRunning =
vcsActionState.isRunning &&
stableKinds.some((kind) => getVcsActionOperationForKind(kind) === vcsActionState.operation);
return appActionRunning || vcsActionRunning;
}
function useVcsManagerAction<TArgs extends ReadonlyArray<unknown>, TResult>(input: {
readonly operation: VcsActionOperation;
readonly scope: SourceControlActionScope;
readonly unavailableMessage: string;
readonly action: (...args: TArgs) => Promise<TResult | null>;
}): SourceControlActionState<TArgs, TResult> {
const { action, operation, scope, unavailableMessage } = input;
const vcsActionState = useVcsActionStateForScope(scope);
const [error, setError] = useState<unknown>(null);
const [isTransitionPending, startTransition] = useTransition();
const resetError = useCallback(() => {
vcsActionManager.reset(scope);
startTransition(() => setError(null));
}, [scope, startTransition]);
const run = useCallback(
async (...args: TArgs): Promise<TResult> => {
startTransition(() => setError(null));
try {
const result = await action(...args);
if (result === null) {
throw new Error(unavailableMessage);
}
return result;
} catch (nextError) {
startTransition(() => setError(nextError));
throw nextError;
}
},
[action, startTransition, unavailableMessage],
);
return {
error: error ?? vcsActionState.error,
isPending:
isTransitionPending || (vcsActionState.isRunning && vcsActionState.operation === operation),
resetError,
run,
};
}
export function useVcsInitAction(scope: SourceControlActionScope) {
const action = useCallback(async () => {
if (!scope.cwd || !scope.environmentId) throw new Error("Git init is unavailable.");
return ensureEnvironmentApi(scope.environmentId).vcs.init({ cwd: scope.cwd });
return vcsActionManager.init(scope);
}, [scope]);
return useSourceControlAction({
kind: "init",
return useVcsManagerAction({
operation: "init",
scope,
unavailableMessage: "Git init is unavailable.",
action,
});
}
@@ -199,39 +290,44 @@ export function useGitStackedAction(scope: SourceControlActionScope) {
featureBranch?: boolean;
filePaths?: string[];
onProgress?: (event: GitActionProgressEvent) => void;
}): Promise<GitRunStackedActionResult> => {
}): Promise<GitRunStackedActionResult | null> => {
if (!scope.cwd || !scope.environmentId) throw new Error("Git action is unavailable.");
return requireEnvironmentConnection(scope.environmentId).client.git.runStackedAction(
return vcsActionManager.runChangeRequest(
scope,
{
action,
actionId,
cwd: scope.cwd,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch: true } : {}),
...(filePaths && filePaths.length > 0 ? { filePaths } : {}),
},
...(onProgress ? [{ onProgress }] : []),
{
gitStatus: getVcsStatusSnapshot(scope).data,
...(onProgress ? { onProgress } : {}),
},
);
},
[scope],
);
return useSourceControlAction({
kind: "runStackedAction",
return useVcsManagerAction({
operation: "run_change_request",
scope,
unavailableMessage: "Git action is unavailable.",
action,
});
}
export function useVcsPullAction(scope: SourceControlActionScope) {
const action = useCallback(async (): Promise<VcsPullResult> => {
const action = useCallback(async (): Promise<VcsPullResult | null> => {
if (!scope.cwd || !scope.environmentId) throw new Error("Git pull is unavailable.");
return ensureEnvironmentApi(scope.environmentId).vcs.pull({ cwd: scope.cwd });
return vcsActionManager.pull(scope);
}, [scope]);
return useSourceControlAction({
kind: "pull",
return useVcsManagerAction({
operation: "pull",
scope,
unavailableMessage: "Git pull is unavailable.",
action,
});
}
@@ -1,13 +1,13 @@
import { useAtomValue } from "@effect/atom-react";
import {
type GitStatusClient,
type GitStatusState,
type GitStatusTarget,
EMPTY_GIT_STATUS_ATOM,
EMPTY_GIT_STATUS_STATE,
createGitStatusManager,
getGitStatusTargetKey,
gitStatusStateAtom,
type VcsStatusClient,
type VcsStatusState,
type VcsStatusTarget,
EMPTY_VCS_STATUS_ATOM,
EMPTY_VCS_STATUS_STATE,
createVcsStatusManager,
getVcsStatusTargetKey,
vcsStatusStateAtom,
} from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { useEffect } from "react";
@@ -18,9 +18,9 @@ import {
} from "../environments/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
export type { GitStatusState, GitStatusTarget };
export type { VcsStatusState, VcsStatusTarget };
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const connection = readEnvironmentConnection(environmentId as EnvironmentId);
@@ -33,31 +33,31 @@ const manager = createGitStatusManager({
subscribeClientChanges: subscribeEnvironmentConnections,
});
export function getGitStatusSnapshot(target: GitStatusTarget): GitStatusState {
export function getVcsStatusSnapshot(target: VcsStatusTarget): VcsStatusState {
return manager.getSnapshot(target);
}
export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient): () => void {
export function watchVcsStatus(target: VcsStatusTarget, client?: VcsStatusClient): () => void {
return manager.watch(target, client);
}
export function refreshGitStatus(target: GitStatusTarget, client?: GitStatusClient) {
export function refreshVcsStatus(target: VcsStatusTarget, client?: VcsStatusClient) {
return manager.refresh(target, client);
}
export function resetGitStatusStateForTests(): void {
export function resetVcsStatusStateForTests(): void {
manager.reset();
}
export function useGitStatus(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
export function useVcsStatus(target: VcsStatusTarget): VcsStatusState {
const targetKey = getVcsStatusTargetKey(target);
useEffect(
() => manager.watch({ environmentId: target.environmentId, cwd: target.cwd }),
[target.environmentId, target.cwd],
);
const state = useAtomValue(
targetKey !== null ? gitStatusStateAtom(targetKey) : EMPTY_GIT_STATUS_ATOM,
targetKey !== null ? vcsStatusStateAtom(targetKey) : EMPTY_VCS_STATUS_ATOM,
);
return targetKey === null ? EMPTY_GIT_STATUS_STATE : state;
return targetKey === null ? EMPTY_VCS_STATUS_STATE : state;
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { ContextMenuItem, LocalApi } from "@t3tools/contracts";
import type { WsRpcClient } from "@t3tools/client-runtime";
import { resetGitStatusStateForTests } from "./lib/gitStatusState";
import { resetVcsStatusStateForTests } from "./lib/vcsStatusState";
import { resetSourceControlDiscoveryStateForTests } from "./lib/sourceControlDiscoveryState";
import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
import { resetServerStateForTests } from "./rpc/serverState";
@@ -196,7 +196,7 @@ export async function __resetLocalApiForTests() {
const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");
__resetClientSettingsPersistenceForTests();
await resetEnvironmentServiceForTests();
resetGitStatusStateForTests();
resetVcsStatusStateForTests();
resetSourceControlDiscoveryStateForTests();
resetRequestLatencyStateForTests();
resetSavedEnvironmentRegistryStoreForTests();
@@ -0,0 +1,135 @@
import { EnvironmentId, ThreadId, type OrchestrationGetTurnDiffResult } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
type CheckpointDiffClient,
createCheckpointDiffManager,
EMPTY_CHECKPOINT_DIFF_STATE,
getCheckpointDiffTargetKey,
} from "./checkpointDiffState.ts";
let registry = AtomRegistry.make();
function resetAtomRegistry() {
registry.dispose();
registry = AtomRegistry.make();
}
const TARGET = {
environmentId: EnvironmentId.make("env-local"),
threadId: ThreadId.make("thread-1"),
fromTurnCount: 1,
toTurnCount: 2,
ignoreWhitespace: false,
};
const PATCH_RESULT: OrchestrationGetTurnDiffResult = {
threadId: TARGET.threadId,
diff: "patch",
fromTurnCount: 1,
toTurnCount: 2,
};
function createClient() {
return {
getTurnDiff: vi.fn(async () => PATCH_RESULT),
getFullThreadDiff: vi.fn(async () => PATCH_RESULT),
} satisfies CheckpointDiffClient;
}
describe("createCheckpointDiffManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("loads a turn checkpoint diff into atom state", async () => {
const client = createClient();
const manager = createCheckpointDiffManager({
getRegistry: () => registry,
getClient: () => client,
});
await expect(manager.load(TARGET)).resolves.toEqual(PATCH_RESULT);
expect(client.getTurnDiff).toHaveBeenCalledWith({
threadId: TARGET.threadId,
fromTurnCount: 1,
toTurnCount: 2,
ignoreWhitespace: false,
});
expect(client.getFullThreadDiff).not.toHaveBeenCalled();
expect(manager.getSnapshot(TARGET)).toEqual({
data: PATCH_RESULT,
error: null,
isPending: false,
});
});
it("loads a full thread diff when the range starts at zero", async () => {
const client = createClient();
const manager = createCheckpointDiffManager({
getRegistry: () => registry,
getClient: () => client,
});
await manager.load({ ...TARGET, fromTurnCount: 0 });
expect(client.getFullThreadDiff).toHaveBeenCalledWith({
threadId: TARGET.threadId,
toTurnCount: 2,
ignoreWhitespace: false,
});
expect(client.getTurnDiff).not.toHaveBeenCalled();
});
it("returns empty state for invalid targets", () => {
const manager = createCheckpointDiffManager({
getRegistry: () => registry,
getClient: () => createClient(),
});
expect(manager.getSnapshot({ ...TARGET, threadId: null })).toBe(EMPTY_CHECKPOINT_DIFF_STATE);
expect(getCheckpointDiffTargetKey({ ...TARGET, threadId: null })).toBeNull();
});
it("deduplicates in-flight requests and reuses successful cached data", async () => {
const client = createClient();
const manager = createCheckpointDiffManager({
getRegistry: () => registry,
getClient: () => client,
});
const first = manager.load(TARGET);
const second = manager.load(TARGET);
expect(first).toBe(second);
await first;
await manager.load(TARGET);
expect(client.getTurnDiff).toHaveBeenCalledTimes(1);
});
it("retries temporarily unavailable checkpoint diffs", async () => {
let attempts = 0;
const client = {
getFullThreadDiff: vi.fn(async () => PATCH_RESULT),
getTurnDiff: vi.fn(async () => {
attempts += 1;
if (attempts < 3) {
throw new Error("checkpoint is unavailable for turn");
}
return PATCH_RESULT;
}),
} satisfies CheckpointDiffClient;
const manager = createCheckpointDiffManager({
getRegistry: () => registry,
getClient: () => client,
retryDelay: async () => undefined,
});
await expect(manager.load(TARGET)).resolves.toEqual(PATCH_RESULT);
expect(client.getTurnDiff).toHaveBeenCalledTimes(3);
});
});
@@ -0,0 +1,313 @@
import {
type EnvironmentId,
OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
OrchestrationGetTurnDiffInput,
type OrchestrationGetTurnDiffResult,
type ThreadId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
export type CheckpointDiffResult =
| OrchestrationGetTurnDiffResult
| OrchestrationGetFullThreadDiffResult;
export interface CheckpointDiffState {
readonly data: CheckpointDiffResult | null;
readonly error: string | null;
readonly isPending: boolean;
}
export interface CheckpointDiffTarget {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
readonly fromTurnCount: number | null;
readonly toTurnCount: number | null;
readonly ignoreWhitespace: boolean;
readonly cacheScope?: string | null;
}
export interface CheckpointDiffClient {
readonly getTurnDiff: (
input: OrchestrationGetTurnDiffInput,
) => Promise<OrchestrationGetTurnDiffResult>;
readonly getFullThreadDiff: (
input: OrchestrationGetFullThreadDiffInput,
) => Promise<OrchestrationGetFullThreadDiffResult>;
}
export const EMPTY_CHECKPOINT_DIFF_STATE = Object.freeze<CheckpointDiffState>({
data: null,
error: null,
isPending: false,
});
const INITIAL_CHECKPOINT_DIFF_STATE = Object.freeze<CheckpointDiffState>({
data: null,
error: null,
isPending: true,
});
const knownCheckpointDiffKeys = new Set<string>();
export const checkpointDiffStateAtom = Atom.family((key: string) => {
knownCheckpointDiffKeys.add(key);
return Atom.make(INITIAL_CHECKPOINT_DIFF_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`checkpoint-diff:${key}`),
);
});
export const EMPTY_CHECKPOINT_DIFF_ATOM = Atom.make(EMPTY_CHECKPOINT_DIFF_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("checkpoint-diff:null"),
);
const decodeFullThreadDiffInput = Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput);
const decodeTurnDiffInput = Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput);
type CheckpointDiffRequest =
| {
readonly kind: "fullThreadDiff";
readonly input: OrchestrationGetFullThreadDiffInput;
}
| {
readonly kind: "turnDiff";
readonly input: OrchestrationGetTurnDiffInput;
};
export function getCheckpointDiffTargetKey(target: CheckpointDiffTarget): string | null {
const decoded = decodeCheckpointDiffRequest(target);
if (target.environmentId === null || decoded._tag === "None") {
return null;
}
return [
target.environmentId,
target.threadId,
target.fromTurnCount,
target.toTurnCount,
target.ignoreWhitespace,
target.cacheScope ?? null,
].join(":");
}
function decodeCheckpointDiffRequest(target: CheckpointDiffTarget) {
if (target.fromTurnCount === 0) {
return decodeFullThreadDiffInput({
threadId: target.threadId,
toTurnCount: target.toTurnCount,
ignoreWhitespace: target.ignoreWhitespace,
}).pipe(Option.map((input) => ({ kind: "fullThreadDiff" as const, input })));
}
return decodeTurnDiffInput({
threadId: target.threadId,
fromTurnCount: target.fromTurnCount,
toTurnCount: target.toTurnCount,
ignoreWhitespace: target.ignoreWhitespace,
}).pipe(Option.map((input) => ({ kind: "turnDiff" as const, input })));
}
function asCheckpointErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return "";
}
export function normalizeCheckpointDiffErrorMessage(error: unknown): string {
const message = asCheckpointErrorMessage(error).trim();
if (message.length === 0) {
return "Failed to load checkpoint diff.";
}
const lower = message.toLowerCase();
if (lower.includes("not a git repository")) {
return "Turn diffs are unavailable because this project is not a git repository.";
}
if (
lower.includes("checkpoint unavailable for thread") ||
lower.includes("checkpoint invariant violation")
) {
const separatorIndex = message.indexOf(":");
if (separatorIndex >= 0) {
const detail = message.slice(separatorIndex + 1).trim();
if (detail.length > 0) {
return detail;
}
}
}
return message;
}
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
const message = asCheckpointErrorMessage(error).toLowerCase();
return (
message.includes("exceeds current turn count") ||
message.includes("checkpoint is unavailable for turn") ||
message.includes("filesystem checkpoint is unavailable")
);
}
function defaultRetryDelay(attempt: number, error: unknown): Promise<void> {
const delayMs = isCheckpointTemporarilyUnavailable(error)
? Math.min(5_000, 250 * 2 ** (attempt - 1))
: Math.min(1_000, 100 * 2 ** (attempt - 1));
return Effect.runPromise(Effect.sleep(Duration.millis(delayMs)));
}
export function createCheckpointDiffManager(config: {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: EnvironmentId) => CheckpointDiffClient | null;
readonly retryDelay?: (attempt: number, error: unknown) => Promise<void>;
}) {
const inFlight = new Map<string, Promise<CheckpointDiffResult | null>>();
const versions = new Map<string, number>();
function getVersion(targetKey: string): number {
return versions.get(targetKey) ?? 0;
}
function bumpVersion(targetKey: string): void {
versions.set(targetKey, getVersion(targetKey) + 1);
}
function setState(targetKey: string, state: CheckpointDiffState): void {
config.getRegistry().set(checkpointDiffStateAtom(targetKey), state);
}
function markPending(targetKey: string): void {
const current = config.getRegistry().get(checkpointDiffStateAtom(targetKey));
setState(
targetKey,
current.data === null ? INITIAL_CHECKPOINT_DIFF_STATE : { ...current, isPending: true },
);
}
function setError(targetKey: string, error: unknown): void {
const current = config.getRegistry().get(checkpointDiffStateAtom(targetKey));
setState(targetKey, {
data: current.data,
error: normalizeCheckpointDiffErrorMessage(error),
isPending: false,
});
}
async function requestWithRetry(
client: CheckpointDiffClient,
request: CheckpointDiffRequest,
): Promise<CheckpointDiffResult> {
let attempt = 0;
while (true) {
attempt += 1;
try {
if (request.kind === "fullThreadDiff") {
return await client.getFullThreadDiff(request.input);
}
return await client.getTurnDiff(request.input);
} catch (error) {
const maxAttempts = isCheckpointTemporarilyUnavailable(error) ? 13 : 4;
if (attempt >= maxAttempts) {
throw error;
}
await (config.retryDelay ?? defaultRetryDelay)(attempt, error);
}
}
}
function load(
target: CheckpointDiffTarget,
client?: CheckpointDiffClient,
options?: { readonly force?: boolean },
): Promise<CheckpointDiffResult | null> {
const targetKey = getCheckpointDiffTargetKey(target);
const decoded = decodeCheckpointDiffRequest(target);
if (targetKey === null || target.environmentId === null || decoded._tag === "None") {
return Promise.resolve(null);
}
if (!options?.force) {
const current = config.getRegistry().get(checkpointDiffStateAtom(targetKey));
if (current.data !== null && current.error === null) {
return Promise.resolve(current.data);
}
}
const existing = inFlight.get(targetKey);
if (existing) {
return existing;
}
const resolved = client ?? config.getClient(target.environmentId);
if (!resolved) {
setError(targetKey, new Error("Remote connection is not ready."));
return Promise.resolve(config.getRegistry().get(checkpointDiffStateAtom(targetKey)).data);
}
markPending(targetKey);
const version = getVersion(targetKey);
const promise = requestWithRetry(resolved, decoded.value).then(
(result) => {
if (getVersion(targetKey) === version) {
setState(targetKey, { data: result, error: null, isPending: false });
}
return result;
},
(error: unknown) => {
if (getVersion(targetKey) === version) {
setError(targetKey, error);
}
return config.getRegistry().get(checkpointDiffStateAtom(targetKey)).data;
},
);
inFlight.set(targetKey, promise);
void promise.finally(() => {
if (inFlight.get(targetKey) === promise) {
inFlight.delete(targetKey);
}
});
return promise;
}
function getSnapshot(target: CheckpointDiffTarget): CheckpointDiffState {
const targetKey = getCheckpointDiffTargetKey(target);
return targetKey === null
? EMPTY_CHECKPOINT_DIFF_STATE
: config.getRegistry().get(checkpointDiffStateAtom(targetKey));
}
function invalidate(target?: CheckpointDiffTarget): void {
if (target) {
const targetKey = getCheckpointDiffTargetKey(target);
if (targetKey === null) {
return;
}
bumpVersion(targetKey);
inFlight.delete(targetKey);
setState(targetKey, INITIAL_CHECKPOINT_DIFF_STATE);
return;
}
for (const key of knownCheckpointDiffKeys) {
bumpVersion(key);
setState(key, INITIAL_CHECKPOINT_DIFF_STATE);
}
inFlight.clear();
}
return {
getSnapshot,
invalidate,
load,
};
}
+3 -2
View File
@@ -9,9 +9,9 @@ export * from "./shellSnapshotState.ts";
export * from "./threadDetailReducer.ts";
export * from "./threadDetailState.ts";
export * from "./gitActions.ts";
export * from "./gitActionState.ts";
export * from "./vcsActionState.ts";
export * from "./vcsRefState.ts";
export * from "./gitStatusState.ts";
export * from "./vcsStatusState.ts";
export * from "./terminalSessionState.ts";
export * from "./transportError.ts";
export * from "./wsRpcProtocol.ts";
@@ -21,3 +21,4 @@ export * from "./environmentConnection.ts";
export * from "./sourceControlDiscoveryState.ts";
export * from "./composerPathSearchState.ts";
export * from "./archivedThreadsState.ts";
export * from "./checkpointDiffState.ts";
@@ -12,10 +12,10 @@ import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
type GitActionClient,
createGitActionManager,
EMPTY_GIT_ACTION_STATE,
} from "./gitActionState.ts";
type VcsActionClient,
createVcsActionManager,
EMPTY_VCS_ACTION_STATE,
} from "./vcsActionState.ts";
let atomRegistry = AtomRegistry.make();
@@ -126,19 +126,19 @@ function createMockClient() {
const createRefDeferred = createDeferred<VcsCreateRefResult>();
const createWorktreeDeferred = createDeferred<VcsCreateWorktreeResult>();
const initDeferred = createDeferred<void>();
const runStackedActionDeferred = createDeferred<GitRunStackedActionResult>();
let runStackedActionProgressListener: ((event: GitActionProgressEvent) => void) | null = null;
const runChangeRequestDeferred = createDeferred<GitRunStackedActionResult>();
let runChangeRequestProgressListener: ((event: GitActionProgressEvent) => void) | null = null;
const client: GitActionClient = {
const client: VcsActionClient = {
refreshStatus: vi.fn(() => refreshDeferred.promise),
pull: vi.fn(() => pullDeferred.promise),
switchRef: vi.fn(() => switchRefDeferred.promise),
createRef: vi.fn(() => createRefDeferred.promise),
createWorktree: vi.fn(() => createWorktreeDeferred.promise),
init: vi.fn(() => initDeferred.promise),
runStackedAction: vi.fn((_, options) => {
runStackedActionProgressListener = options?.onProgress ?? null;
return runStackedActionDeferred.promise;
runChangeRequest: vi.fn((_, options) => {
runChangeRequestProgressListener = options?.onProgress ?? null;
return runChangeRequestDeferred.promise;
}),
};
@@ -150,21 +150,21 @@ function createMockClient() {
createRefDeferred,
createWorktreeDeferred,
initDeferred,
runStackedActionDeferred,
runChangeRequestDeferred,
emitProgress(event: GitActionProgressEvent) {
runStackedActionProgressListener?.(event);
runChangeRequestProgressListener?.(event);
},
};
}
describe("createGitActionManager", () => {
describe("createVcsActionManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("tracks refreshStatus progress and clears state on success", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
const manager = createVcsActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
@@ -174,33 +174,34 @@ describe("createGitActionManager", () => {
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: true,
operation: "refresh_status",
currentLabel: "Refreshing git status",
currentLabel: "Refreshing source control status",
error: null,
});
mock.refreshDeferred.resolve(BASE_STATUS);
await expect(promise).resolves.toEqual(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_ACTION_STATE);
});
it("tracks runStackedAction progress events", async () => {
it("tracks runChangeRequest progress events", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
const onProgress = vi.fn();
const manager = createVcsActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
getActionId: () => "action-123",
});
const promise = manager.runStackedAction(
const promise = manager.runChangeRequest(
TARGET,
{ action: "commit_push", commitMessage: "Test commit" },
{ client: mock.client, gitStatus: BASE_STATUS },
{ client: mock.client, gitStatus: BASE_STATUS, onProgress },
);
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: true,
operation: "run_stacked_action",
operation: "run_change_request",
actionId: "action-123",
currentLabel: "Committing...",
error: null,
@@ -208,6 +209,7 @@ describe("createGitActionManager", () => {
mock.emitProgress(createPhaseStartedEvent());
expect(manager.getSnapshot(TARGET).currentLabel).toBe("Committing...");
expect(onProgress).toHaveBeenLastCalledWith(createPhaseStartedEvent());
mock.emitProgress(createHookStartedEvent());
expect(manager.getSnapshot(TARGET)).toMatchObject({
@@ -227,15 +229,15 @@ describe("createGitActionManager", () => {
});
const result = createActionFinishedEvent().result;
mock.runStackedActionDeferred.resolve(result);
mock.runChangeRequestDeferred.resolve(result);
await expect(promise).resolves.toEqual(result);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_ACTION_STATE);
});
it("stores the error when an operation fails", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
const manager = createVcsActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
@@ -253,13 +255,38 @@ describe("createGitActionManager", () => {
});
});
it("invalidates after successful mutations but not refreshStatus", async () => {
const mock = createMockClient();
const onInvalidate = vi.fn();
const manager = createVcsActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
onInvalidate,
});
const refreshPromise = manager.refreshStatus(TARGET, mock.client);
mock.refreshDeferred.resolve(BASE_STATUS);
await expect(refreshPromise).resolves.toEqual(BASE_STATUS);
expect(onInvalidate).not.toHaveBeenCalled();
const pullPromise = manager.pull(TARGET, mock.client);
const pullResult: VcsPullResult = {
status: "skipped_up_to_date",
refName: "main",
upstreamRef: null,
};
mock.pullDeferred.resolve(pullResult);
await expect(pullPromise).resolves.toEqual(pullResult);
expect(onInvalidate).toHaveBeenCalledWith(TARGET);
});
it("returns null when no client is available", async () => {
const manager = createGitActionManager({
const manager = createVcsActionManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
await expect(manager.switchRef(TARGET, { refName: "main" })).resolves.toBeNull();
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_ACTION_STATE);
});
});
@@ -20,18 +20,18 @@ import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { buildGitActionProgressStages } from "./gitActions.ts";
import type { WsRpcClient } from "./wsRpcClient.ts";
export type GitActionOperation =
export type VcsActionOperation =
| "refresh_status"
| "run_stacked_action"
| "run_change_request"
| "pull"
| "switch_ref"
| "create_ref"
| "create_worktree"
| "init";
export interface GitActionState {
export interface VcsActionState {
readonly isRunning: boolean;
readonly operation: GitActionOperation | null;
readonly operation: VcsActionOperation | null;
readonly actionId: string | null;
readonly action: GitStackedAction | null;
readonly currentLabel: string | null;
@@ -43,18 +43,19 @@ export interface GitActionState {
readonly error: string | null;
}
export interface GitActionTarget {
export interface VcsActionTarget {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
}
export type GitActionClient = Pick<
export type VcsActionClient = Pick<
WsRpcClient["vcs"],
"refreshStatus" | "pull" | "switchRef" | "createRef" | "createWorktree" | "init"
> &
Pick<WsRpcClient["git"], "runStackedAction">;
> & {
readonly runChangeRequest: WsRpcClient["git"]["runStackedAction"];
};
export const EMPTY_GIT_ACTION_STATE = Object.freeze<GitActionState>({
export const EMPTY_VCS_ACTION_STATE = Object.freeze<VcsActionState>({
isRunning: false,
operation: null,
actionId: null,
@@ -68,34 +69,34 @@ export const EMPTY_GIT_ACTION_STATE = Object.freeze<GitActionState>({
error: null,
});
const knownGitActionKeys = new Set<string>();
const knownVcsActionKeys = new Set<string>();
let nextGeneratedActionId = 0;
const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
export const gitActionStateAtom = Atom.family((key: string) => {
knownGitActionKeys.add(key);
return Atom.make(EMPTY_GIT_ACTION_STATE).pipe(
export const vcsActionStateAtom = Atom.family((key: string) => {
knownVcsActionKeys.add(key);
return Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-action:${key}`),
Atom.withLabel(`vcs-action:${key}`),
);
});
export const EMPTY_GIT_ACTION_ATOM = Atom.make(EMPTY_GIT_ACTION_STATE).pipe(
export const EMPTY_VCS_ACTION_ATOM = Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-action:null"),
Atom.withLabel("vcs-action:null"),
);
export function getGitActionTargetKey(target: GitActionTarget): string | null {
export function getVcsActionTargetKey(target: VcsActionTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}`;
}
export function applyGitActionProgressEvent(
current: GitActionState,
export function applyVcsActionProgressEvent(
current: VcsActionState,
event: GitActionProgressEvent,
): GitActionState {
): VcsActionState {
const now = nowMs();
switch (event.kind) {
@@ -105,7 +106,7 @@ export function applyGitActionProgressEvent(
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
phaseStartedAtMs: now,
hookStartedAtMs: null,
hookName: null,
@@ -118,7 +119,7 @@ export function applyGitActionProgressEvent(
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
currentLabel: event.label,
currentPhaseLabel: event.label,
phaseStartedAtMs: now,
@@ -133,7 +134,7 @@ export function applyGitActionProgressEvent(
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
currentLabel: `Running ${event.hookName}...`,
hookName: event.hookName,
hookStartedAtMs: now,
@@ -146,7 +147,7 @@ export function applyGitActionProgressEvent(
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
lastOutputLine: event.text,
error: null,
};
@@ -156,7 +157,7 @@ export function applyGitActionProgressEvent(
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
currentLabel: current.currentPhaseLabel,
hookName: null,
hookStartedAtMs: null,
@@ -169,35 +170,36 @@ export function applyGitActionProgressEvent(
isRunning: false,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
error: null,
};
case "action_failed":
return {
...EMPTY_GIT_ACTION_STATE,
...EMPTY_VCS_ACTION_STATE,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
operation: "run_change_request",
error: event.message,
};
}
}
export interface GitActionManagerConfig {
export interface VcsActionManagerConfig {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: EnvironmentId) => GitActionClient | null;
readonly getClient: (environmentId: EnvironmentId) => VcsActionClient | null;
readonly getActionId?: () => string;
readonly onInvalidate?: (target: VcsActionTarget) => void | Promise<void>;
}
export function createGitActionManager(config: GitActionManagerConfig) {
function setState(targetKey: string, nextState: GitActionState): void {
config.getRegistry().set(gitActionStateAtom(targetKey), nextState);
export function createVcsActionManager(config: VcsActionManagerConfig) {
function setState(targetKey: string, nextState: VcsActionState): void {
config.getRegistry().set(vcsActionStateAtom(targetKey), nextState);
}
function startOperation(
targetKey: string,
input: {
readonly operation: GitActionOperation;
readonly operation: VcsActionOperation;
readonly actionId?: string;
readonly action?: GitStackedAction;
readonly label: string;
@@ -219,39 +221,40 @@ export function createGitActionManager(config: GitActionManagerConfig) {
}
function finishOperation(targetKey: string): void {
setState(targetKey, EMPTY_GIT_ACTION_STATE);
setState(targetKey, EMPTY_VCS_ACTION_STATE);
}
function failOperation(
targetKey: string,
error: unknown,
input: {
readonly operation: GitActionOperation;
readonly operation: VcsActionOperation;
readonly actionId?: string;
readonly action?: GitStackedAction;
},
): void {
setState(targetKey, {
...EMPTY_GIT_ACTION_STATE,
...EMPTY_VCS_ACTION_STATE,
operation: input.operation,
actionId: input.actionId ?? null,
action: input.action ?? null,
error: error instanceof Error ? error.message : "Git action failed.",
error: error instanceof Error ? error.message : "Source control action failed.",
});
}
async function runOperation<TResult>(
target: GitActionTarget,
target: VcsActionTarget,
input: {
readonly operation: GitActionOperation;
readonly operation: VcsActionOperation;
readonly label: string;
readonly actionId?: string;
readonly action?: GitStackedAction;
readonly client?: GitActionClient | undefined;
readonly execute: (client: GitActionClient) => Promise<TResult>;
readonly client?: VcsActionClient | undefined;
readonly invalidateOnSuccess?: boolean;
readonly execute: (client: VcsActionClient) => Promise<TResult>;
},
): Promise<TResult | null> {
const targetKey = getGitActionTargetKey(target);
const targetKey = getVcsActionTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return null;
}
@@ -265,6 +268,9 @@ export function createGitActionManager(config: GitActionManagerConfig) {
try {
const result = await input.execute(resolved);
finishOperation(targetKey);
if (input.invalidateOnSuccess ?? true) {
await config.onInvalidate?.(target);
}
return result;
} catch (error) {
failOperation(targetKey, error, input);
@@ -272,20 +278,20 @@ export function createGitActionManager(config: GitActionManagerConfig) {
}
}
function getSnapshot(target: GitActionTarget): GitActionState {
const targetKey = getGitActionTargetKey(target);
function getSnapshot(target: VcsActionTarget): VcsActionState {
const targetKey = getVcsActionTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_ACTION_STATE;
return EMPTY_VCS_ACTION_STATE;
}
return config.getRegistry().get(gitActionStateAtom(targetKey));
return config.getRegistry().get(vcsActionStateAtom(targetKey));
}
async function refreshStatus(
target: GitActionTarget,
client?: GitActionClient,
target: VcsActionTarget,
client?: VcsActionClient,
options?: { readonly quiet?: boolean },
): Promise<Awaited<ReturnType<GitActionClient["refreshStatus"]>> | null> {
): Promise<Awaited<ReturnType<VcsActionClient["refreshStatus"]>> | null> {
if (options?.quiet) {
if (target.environmentId === null || target.cwd === null) {
return null;
@@ -296,15 +302,16 @@ export function createGitActionManager(config: GitActionManagerConfig) {
return runOperation(target, {
operation: "refresh_status",
label: "Refreshing git status",
label: "Refreshing source control status",
client,
invalidateOnSuccess: false,
execute: (resolved) => resolved.refreshStatus({ cwd: target.cwd! }),
});
}
async function pull(
target: GitActionTarget,
client?: GitActionClient,
target: VcsActionTarget,
client?: VcsActionClient,
options?: { readonly label?: string },
): Promise<VcsPullResult | null> {
return runOperation(target, {
@@ -316,9 +323,9 @@ export function createGitActionManager(config: GitActionManagerConfig) {
}
async function switchRef(
target: GitActionTarget,
target: VcsActionTarget,
input: Omit<VcsSwitchRefInput, "cwd">,
client?: GitActionClient,
client?: VcsActionClient,
options?: { readonly label?: string },
): Promise<VcsSwitchRefResult | null> {
return runOperation(target, {
@@ -330,9 +337,9 @@ export function createGitActionManager(config: GitActionManagerConfig) {
}
async function createRef(
target: GitActionTarget,
target: VcsActionTarget,
input: Omit<VcsCreateRefInput, "cwd">,
client?: GitActionClient,
client?: VcsActionClient,
options?: { readonly label?: string },
): Promise<VcsCreateRefResult | null> {
return runOperation(target, {
@@ -344,9 +351,9 @@ export function createGitActionManager(config: GitActionManagerConfig) {
}
async function createWorktree(
target: GitActionTarget,
target: VcsActionTarget,
input: Omit<VcsCreateWorktreeInput, "cwd">,
client?: GitActionClient,
client?: VcsActionClient,
options?: { readonly label?: string },
): Promise<VcsCreateWorktreeResult | null> {
return runOperation(target, {
@@ -358,23 +365,23 @@ export function createGitActionManager(config: GitActionManagerConfig) {
}
async function init(
target: GitActionTarget,
client?: GitActionClient,
target: VcsActionTarget,
client?: VcsActionClient,
options?: { readonly label?: string },
): Promise<Awaited<ReturnType<GitActionClient["init"]>> | null> {
): Promise<Awaited<ReturnType<VcsActionClient["init"]>> | null> {
return runOperation(target, {
operation: "init",
label: options?.label ?? "Initializing git repository",
label: options?.label ?? "Initializing repository",
client,
execute: (resolved) => resolved.init({ cwd: target.cwd! }),
});
}
async function runStackedAction(
target: GitActionTarget,
async function runChangeRequest(
target: VcsActionTarget,
input: Omit<GitRunStackedActionInput, "cwd" | "actionId"> & { readonly actionId?: string },
options?: {
readonly client?: GitActionClient;
readonly client?: VcsActionClient;
readonly gitStatus?: VcsStatusResult | null;
readonly onProgress?: (event: GitActionProgressEvent) => void;
},
@@ -382,11 +389,11 @@ export function createGitActionManager(config: GitActionManagerConfig) {
const actionId =
input.actionId ??
config.getActionId?.() ??
`git-action-${nowMs()}-${++nextGeneratedActionId}`;
const targetKey = getGitActionTargetKey(target);
`vcs-action-${nowMs()}-${++nextGeneratedActionId}`;
const targetKey = getVcsActionTargetKey(target);
return runOperation(target, {
operation: "run_stacked_action",
operation: "run_change_request",
label:
buildGitActionProgressStages({
action: input.action,
@@ -397,12 +404,12 @@ export function createGitActionManager(config: GitActionManagerConfig) {
input.action === "create_pr" &&
(!(options?.gitStatus?.hasUpstream ?? false) ||
(options?.gitStatus?.aheadCount ?? 0) > 0),
})[0] ?? "Running git action",
})[0] ?? "Running source control action",
actionId,
action: input.action,
client: options?.client,
execute: async (resolved) => {
const result = await resolved.runStackedAction(
const result = await resolved.runChangeRequest(
{
cwd: target.cwd!,
actionId,
@@ -412,7 +419,7 @@ export function createGitActionManager(config: GitActionManagerConfig) {
onProgress: (event) => {
if (targetKey !== null) {
const current = getSnapshot(target);
setState(targetKey, applyGitActionProgressEvent(current, event));
setState(targetKey, applyVcsActionProgressEvent(current, event));
}
options?.onProgress?.(event);
},
@@ -423,9 +430,17 @@ export function createGitActionManager(config: GitActionManagerConfig) {
});
}
function reset(): void {
for (const key of knownGitActionKeys) {
setState(key, EMPTY_GIT_ACTION_STATE);
function reset(target?: VcsActionTarget): void {
if (target) {
const targetKey = getVcsActionTargetKey(target);
if (targetKey !== null) {
setState(targetKey, EMPTY_VCS_ACTION_STATE);
}
return;
}
for (const key of knownVcsActionKeys) {
setState(key, EMPTY_VCS_ACTION_STATE);
}
}
@@ -437,7 +452,7 @@ export function createGitActionManager(config: GitActionManagerConfig) {
createRef,
createWorktree,
init,
runStackedAction,
runChangeRequest,
reset,
};
}
@@ -2,7 +2,7 @@ import { EnvironmentId, type VcsStatusResult } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import { type GitStatusClient, createGitStatusManager } from "./gitStatusState.ts";
import { type VcsStatusClient, createVcsStatusManager } from "./vcsStatusState.ts";
/* ─── Test helpers ──────────────────────────────────────────────────── */
@@ -34,12 +34,12 @@ const BASE_STATUS: VcsStatusResult = {
};
function createMockClient(): {
client: GitStatusClient;
client: VcsStatusClient;
listeners: Set<(event: VcsStatusResult) => void>;
emit: (event: VcsStatusResult) => void;
} {
const listeners = new Set<(event: VcsStatusResult) => void>();
const client: GitStatusClient = {
const client: VcsStatusClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
refName: `${input.cwd}-refreshed`,
@@ -66,7 +66,7 @@ const OTHER_ENV_TARGET = { environmentId: EnvironmentId.make("env-remote"), cwd:
/* ─── Tests ─────────────────────────────────────────────────────────── */
describe("createGitStatusManager", () => {
describe("createVcsStatusManager", () => {
afterEach(() => {
resetAtomRegistry();
});
@@ -74,7 +74,7 @@ describe("createGitStatusManager", () => {
describe("with explicit client (no reconnection)", () => {
it("starts in a pending state when watching", () => {
const { client } = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -86,7 +86,7 @@ describe("createGitStatusManager", () => {
it("shares one subscription per cwd and updates the snapshot", () => {
const { client, listeners, emit } = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -114,7 +114,7 @@ describe("createGitStatusManager", () => {
it("refreshes via unary RPC without restarting the stream", async () => {
const { client, emit } = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -142,7 +142,7 @@ describe("createGitStatusManager", () => {
it("keeps subscriptions isolated by environment when cwds match", () => {
const local = createMockClient();
const remote = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -161,7 +161,7 @@ describe("createGitStatusManager", () => {
});
it("returns null from refresh when no client is available", async () => {
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -170,7 +170,7 @@ describe("createGitStatusManager", () => {
});
it("returns empty state for null targets", () => {
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -184,7 +184,7 @@ describe("createGitStatusManager", () => {
const connectionListeners = new Set<() => void>();
const clients = new Map<string, ReturnType<typeof createMockClient>>();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => clients.get(envId)?.client ?? null,
getClientIdentity: (envId) => (clients.has(envId) ? envId : null),
@@ -217,7 +217,7 @@ describe("createGitStatusManager", () => {
const connectionListeners = new Set<() => void>();
const clients = new Map<string, ReturnType<typeof createMockClient>>();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => clients.get(envId)?.client ?? null,
getClientIdentity: (envId) =>
@@ -262,7 +262,7 @@ describe("createGitStatusManager", () => {
const connectionListeners = new Set<() => void>();
const mock = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
getClientIdentity: () => "id",
@@ -284,7 +284,7 @@ describe("createGitStatusManager", () => {
describe("with getClient config (one-shot)", () => {
it("resolves client from config and subscribes", () => {
const mock = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => (envId === "env-local" ? mock.client : null),
});
@@ -300,7 +300,7 @@ describe("createGitStatusManager", () => {
});
it("returns noop when client is not available", () => {
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
@@ -314,7 +314,7 @@ describe("createGitStatusManager", () => {
describe("reset", () => {
it("tears down all active subscriptions", () => {
const mock = createMockClient();
const manager = createGitStatusManager({
const manager = createVcsStatusManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
@@ -6,19 +6,19 @@ import type { WsRpcClient } from "./wsRpcClient.ts";
/* ─── Types ─────────────────────────────────────────────────────────── */
export interface GitStatusState {
export interface VcsStatusState {
readonly data: VcsStatusResult | null;
readonly error: GitManagerServiceError | null;
readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
export interface GitStatusTarget {
export interface VcsStatusTarget {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
}
export type GitStatusClient = Pick<WsRpcClient["vcs"], "onStatus" | "refreshStatus">;
export type VcsStatusClient = Pick<WsRpcClient["vcs"], "onStatus" | "refreshStatus">;
interface WatchedEntry {
refCount: number;
@@ -29,14 +29,14 @@ interface WatchedEntry {
const NOOP: () => void = () => undefined;
export const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
export const EMPTY_VCS_STATUS_STATE = Object.freeze<VcsStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
const INITIAL_VCS_STATUS_STATE = Object.freeze<VcsStatusState>({
data: null,
error: null,
cause: null,
@@ -45,24 +45,24 @@ const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
/* ─── Atoms ─────────────────────────────────────────────────────────── */
const knownGitStatusKeys = new Set<string>();
const knownVcsStatusKeys = new Set<string>();
export const gitStatusStateAtom = Atom.family((key: string) => {
knownGitStatusKeys.add(key);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
export const vcsStatusStateAtom = Atom.family((key: string) => {
knownVcsStatusKeys.add(key);
return Atom.make(INITIAL_VCS_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${key}`),
Atom.withLabel(`vcs-status:${key}`),
);
});
export const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
export const EMPTY_VCS_STATUS_ATOM = Atom.make(EMPTY_VCS_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
Atom.withLabel("vcs-status:null"),
);
/* ─── Helpers ───────────────────────────────────────────────────────── */
export function getGitStatusTargetKey(target: GitStatusTarget): string | null {
export function getVcsStatusTargetKey(target: VcsStatusTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
@@ -71,13 +71,13 @@ export function getGitStatusTargetKey(target: GitStatusTarget): string | null {
/* ─── Subscription manager ──────────────────────────────────────────── */
export interface GitStatusManagerConfig {
export interface VcsStatusManagerConfig {
/**
* Get the atom registry to read/write git status atoms.
* Get the atom registry to read/write VCS status atoms.
*/
readonly getRegistry: () => AtomRegistry.AtomRegistry;
/** Resolve a git client for an environment. */
readonly getClient: (environmentId: EnvironmentId) => GitStatusClient | null;
/** Resolve a VCS client for an environment. */
readonly getClient: (environmentId: EnvironmentId) => VcsStatusClient | null;
/**
* Optional: get a stable identity for the current client.
* Used to detect reconnections — when the identity changes the
@@ -92,10 +92,10 @@ export interface GitStatusManagerConfig {
readonly subscribeClientChanges?: (listener: () => void) => () => void;
}
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
const VCS_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
export function createGitStatusManager(config: GitStatusManagerConfig) {
export function createVcsStatusManager(config: VcsStatusManagerConfig) {
const watched = new Map<string, WatchedEntry>();
const refreshInFlight = new Map<string, Promise<VcsStatusResult>>();
const lastRefreshAt = new Map<string, number>();
@@ -103,11 +103,11 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
/* ── Atom helpers ───────────────────────────────────────────────── */
function markPending(targetKey: string): void {
const atom = gitStatusStateAtom(targetKey);
const atom = vcsStatusStateAtom(targetKey);
const current = config.getRegistry().get(atom);
const next: GitStatusState =
const next: VcsStatusState =
current.data === null
? INITIAL_GIT_STATUS_STATE
? INITIAL_VCS_STATUS_STATE
: { ...current, error: null, cause: null, isPending: true };
if (
current.data === next.data &&
@@ -121,7 +121,7 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
}
function setData(targetKey: string, status: VcsStatusResult): void {
config.getRegistry().set(gitStatusStateAtom(targetKey), {
config.getRegistry().set(vcsStatusStateAtom(targetKey), {
data: status,
error: null,
cause: null,
@@ -131,7 +131,7 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
/* ── Core subscription ──────────────────────────────────────────── */
function subscribeStream(targetKey: string, cwd: string, client: GitStatusClient): () => void {
function subscribeStream(targetKey: string, cwd: string, client: VcsStatusClient): () => void {
markPending(targetKey);
return client.onStatus({ cwd }, (status) => setData(targetKey, status), {
onResubscribe: () => markPending(targetKey),
@@ -140,7 +140,7 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
/* ── Dynamic subscription (handles reconnection) ────────────────── */
function createDynamicSubscription(targetKey: string, target: GitStatusTarget): () => void {
function createDynamicSubscription(targetKey: string, target: VcsStatusTarget): () => void {
const environmentId = target.environmentId!;
const cwd = target.cwd!;
let currentIdentity: string | null = null;
@@ -179,7 +179,7 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
/* ── Public API ─────────────────────────────────────────────────── */
/**
* Begin watching git status for `target`.
* Begin watching VCS status for `target`.
*
* Multiple watchers sharing the same `environmentId:cwd` key share
* one `onStatus` WS subscription (ref-counted).
@@ -189,8 +189,8 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
* lookup and reconnection handling. Useful in tests.
* @returns An unwatch function.
*/
function watch(target: GitStatusTarget, client?: GitStatusClient): () => void {
const targetKey = getGitStatusTargetKey(target);
function watch(target: VcsStatusTarget, client?: VcsStatusClient): () => void {
const targetKey = getVcsStatusTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return NOOP;
}
@@ -238,10 +238,10 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
* `onStatus` stream, so the subscription picks it up automatically.
*/
function refresh(
target: GitStatusTarget,
client?: GitStatusClient,
target: VcsStatusTarget,
client?: VcsStatusClient,
): Promise<VcsStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
const targetKey = getVcsStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
}
@@ -257,7 +257,7 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
const requestedAt = nowMs();
const last = lastRefreshAt.get(targetKey) ?? 0;
if (requestedAt - last < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
if (requestedAt - last < VCS_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getSnapshot(target).data);
}
@@ -269,10 +269,10 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
return promise;
}
function getSnapshot(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null) return EMPTY_GIT_STATUS_STATE;
return config.getRegistry().get(gitStatusStateAtom(targetKey));
function getSnapshot(target: VcsStatusTarget): VcsStatusState {
const targetKey = getVcsStatusTargetKey(target);
if (targetKey === null) return EMPTY_VCS_STATUS_STATE;
return config.getRegistry().get(vcsStatusStateAtom(targetKey));
}
function reset(): void {
@@ -282,10 +282,10 @@ export function createGitStatusManager(config: GitStatusManagerConfig) {
watched.clear();
refreshInFlight.clear();
lastRefreshAt.clear();
for (const key of knownGitStatusKeys) {
config.getRegistry().set(gitStatusStateAtom(key), INITIAL_GIT_STATUS_STATE);
for (const key of knownVcsStatusKeys) {
config.getRegistry().set(vcsStatusStateAtom(key), INITIAL_VCS_STATUS_STATE);
}
knownGitStatusKeys.clear();
knownVcsStatusKeys.clear();
}
return { watch, refresh, getSnapshot, reset };