Stream git status updates over WebSocket

- Add server-side status broadcaster and cache invalidation
- Refresh git status after git actions and checkout
- Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marminge committed 2026-04-05 10:37:17 -07:00
1 parent 12347082ef
commit 00d879b45f
31 files changed
+782 -245

No files matched your search

+2 -1
View File
@@ -949,11 +949,12 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* (yield* GitCore).checkoutBranch({
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
cwd: source,
branch: `${remoteName}/${featureBranch}`,
});
expect(checkoutResult.branch).toBe("upstream/feature");
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
+7
View File
@@ -2078,6 +2078,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
const branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [
"branch",
"--show-current",
]).pipe(Effect.map((stdout) => stdout.trim() || null));
return { branch };
},
);
+26
View File
@@ -11,6 +11,7 @@ import {
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
@@ -723,9 +724,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
Effect.catch(() => Effect.succeed(null)),
)
: null;
const hostingProvider = details.isRepo
? yield* resolveHostingProvider(cwd, details.branch)
: null;
return {
isRepo: details.isRepo,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
@@ -748,6 +753,21 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
cwd: string,
branch: string | null,
) {
const preferredRemoteName =
branch === null
? "origin"
: ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin");
const remoteUrl =
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
cwd: string,
remoteName: string | null,
@@ -1314,6 +1334,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
return yield* Cache.get(statusResultCache, normalizeStatusCacheKey(input.cwd));
});
const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")(
function* (cwd) {
yield* invalidateStatusResultCache(cwd);
},
);
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
@@ -1708,6 +1733,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return {
status,
invalidateStatus,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
@@ -0,0 +1,94 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import type { GitStatusResult } from "@t3tools/contracts";
import { describe } from "vitest";
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
const baseStatus: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/status-broadcast",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
function makeTestLayer(state: {
currentStatus: GitStatusResult;
statusCalls: number;
invalidationCalls: number;
}) {
const gitManager: GitManagerShape = {
status: () =>
Effect.sync(() => {
state.statusCalls += 1;
return state.currentStatus;
}),
invalidateStatus: () =>
Effect.sync(() => {
state.invalidationCalls += 1;
}),
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
};
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
}
describe("GitStatusBroadcasterLive", () => {
it.effect("reuses the cached git status across repeated reads", () => {
const state = {
currentStatus: baseStatus,
statusCalls: 0,
invalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(first, baseStatus);
assert.deepStrictEqual(second, baseStatus);
assert.equal(state.statusCalls, 1);
assert.equal(state.invalidationCalls, 1);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
const state = {
currentStatus: baseStatus,
statusCalls: 0,
invalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentStatus = {
...baseStatus,
branch: "feature/updated-status",
aheadCount: 2,
};
const refreshed = yield* broadcaster.refreshStatus("/repo");
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshed, state.currentStatus);
assert.deepStrictEqual(cached, state.currentStatus);
assert.equal(state.statusCalls, 2);
assert.equal(state.invalidationCalls, 2);
}).pipe(Effect.provide(makeTestLayer(state)));
});
});
@@ -0,0 +1,148 @@
import { realpathSync } from "node:fs";
import { Duration, Effect, Exit, Layer, PubSub, Ref, Scope, Stream } from "effect";
import type { GitStatusInput, GitStatusResult } from "@t3tools/contracts";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../Services/GitStatusBroadcaster.ts";
import { GitManager } from "../Services/GitManager.ts";
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface GitStatusChange {
readonly cwd: string;
readonly status: GitStatusResult;
}
interface CachedGitStatus {
readonly fingerprint: string;
readonly status: GitStatusResult;
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
function fingerprintStatus(status: GitStatusResult): string {
return JSON.stringify(status);
}
export const GitStatusBroadcasterLive = Layer.effect(
GitStatusBroadcaster,
Effect.gen(function* () {
const gitManager = yield* GitManager;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<GitStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
const pollersRef = yield* Ref.make(new Set<string>());
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
yield* gitManager.invalidateStatus(normalizedCwd);
const nextStatus = yield* gitManager.status({ cwd: normalizedCwd });
const nextFingerprint = fingerprintStatus(nextStatus);
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(normalizedCwd);
const nextCache = new Map(cache);
nextCache.set(normalizedCwd, {
fingerprint: nextFingerprint,
status: nextStatus,
});
return [previous?.fingerprint !== nextFingerprint, nextCache] as const;
});
if (shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd: normalizedCwd,
status: nextStatus,
});
}
return nextStatus;
},
);
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
input: GitStatusInput,
) {
const normalizedCwd = normalizeCwd(input.cwd);
const cached = yield* Ref.get(cacheRef).pipe(
Effect.map((cache) => cache.get(normalizedCwd)?.status ?? null),
);
if (cached) {
return cached;
}
return yield* refreshStatus(normalizedCwd);
});
const ensurePoller = Effect.fn("ensurePoller")(function* (cwd: string) {
const normalizedCwd = normalizeCwd(cwd);
const shouldStart = yield* Ref.modify(pollersRef, (activePollers) => {
if (activePollers.has(normalizedCwd)) {
return [false, activePollers] as const;
}
const nextPollers = new Set(activePollers);
nextPollers.add(normalizedCwd);
return [true, nextPollers] as const;
});
if (!shouldStart) {
return;
}
const refreshLoop = Effect.forever(
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(
refreshStatus(normalizedCwd).pipe(
Effect.catch((error) =>
Effect.logWarning("git status refresh failed", {
cwd: normalizedCwd,
detail: error.message,
}),
),
),
),
),
);
yield* Effect.forkIn(refreshLoop, broadcasterScope);
});
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const normalizedCwd = normalizeCwd(input.cwd);
yield* ensurePoller(normalizedCwd);
const initialStatus = yield* getStatus({ cwd: normalizedCwd });
return Stream.concat(
Stream.make(initialStatus),
Stream.fromPubSub(changesPubSub).pipe(
Stream.filter((event) => event.cwd === normalizedCwd),
Stream.map((event) => event.status),
),
);
}),
);
return {
getStatus,
refreshStatus,
streamStatus,
} satisfies GitStatusBroadcasterShape;
}),
);
+2 -1
View File
@@ -10,6 +10,7 @@ import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
@@ -285,7 +286,7 @@ export interface GitCoreShape {
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
) => Effect.Effect<GitCheckoutResult, GitCommandError, Scope.Scope>;
/**
* Initialize a repository in the provided directory.
@@ -41,6 +41,11 @@ export interface GitManagerShape {
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Clear any cached status snapshot for a repository so the next read is fresh.
*/
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
@@ -0,0 +1,18 @@
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type { GitManagerServiceError, GitStatusInput, GitStatusResult } from "@t3tools/contracts";
export interface GitStatusBroadcasterShape {
readonly getStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: GitStatusInput,
) => Stream.Stream<GitStatusResult, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends ServiceMap.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
+9 -11
View File
@@ -44,6 +44,7 @@ import {
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
import { Open, type OpenShape } from "./open.ts";
import {
@@ -294,6 +295,10 @@ const buildAppUnderTest = (options?: {
...options?.config,
};
const layerConfig = Layer.succeed(ServerConfig, config);
const gitManagerLayer = Layer.mock(GitManager)({
...options?.layers?.gitManager,
});
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
const appLayer = HttpRouter.serve(makeRoutesLayer, {
disableListenLog: true,
@@ -333,11 +338,8 @@ const buildAppUnderTest = (options?: {
...options?.layers?.gitCore,
}),
),
Layer.provide(
Layer.mock(GitManager)({
...options?.layers?.gitManager,
}),
),
Layer.provide(gitManagerLayer),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provide(
Layer.mock(ProjectSetupScriptRunner)({
runForThread: () => Effect.succeed({ status: "no-script" as const }),
@@ -1260,6 +1262,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitManager: {
invalidateStatus: () => Effect.void,
status: () =>
Effect.succeed({
isRepo: true,
@@ -1374,7 +1377,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}),
removeWorktree: () => Effect.void,
createBranch: () => Effect.void,
checkoutBranch: () => Effect.void,
checkoutBranch: (input) => Effect.succeed({ branch: input.branch }),
initRepo: () => Effect.void,
},
},
@@ -1382,11 +1385,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const wsUrl = yield* getWsServerUrl("/ws");
const status = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitStatus]({ cwd: "/tmp/repo" })),
);
assert.equal(status.branch, "main");
const pull = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
);
+10 -8
View File
@@ -30,6 +30,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
import { GitCoreLive } from "./git/Layers/GitCore";
import { GitHubCliLive } from "./git/Layers/GitHubCli";
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster";
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
import { TerminalManagerLive } from "./terminal/Layers/Manager";
import { GitManagerLive } from "./git/Layers/GitManager";
@@ -161,15 +162,16 @@ const ProviderLayerLive = Layer.unwrap(
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
const GitManagerLayerLive = GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
);
const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(
GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
),
),
Layer.provideMerge(GitManagerLayerLive),
Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))),
Layer.provideMerge(GitCoreLive),
);
+48 -20
View File
@@ -27,6 +27,7 @@ import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuer
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore";
import { GitManager } from "./git/Services/GitManager";
import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster";
import { Keybindings } from "./keybindings";
import { Open, resolveAvailableEditors } from "./open";
import { normalizeDispatchCommand } from "./orchestration/Normalizer";
@@ -56,6 +57,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
const open = yield* Open;
const gitManager = yield* GitManager;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const terminalManager = yield* TerminalManager;
const providerRegistry = yield* ProviderRegistry;
const config = yield* ServerConfig;
@@ -348,6 +350,11 @@ const WsRpcLayer = WsRpcGroup.toLayer(
};
});
const refreshGitStatus = (cwd: string) =>
gitStatusBroadcaster
.refreshStatus(cwd)
.pipe(Effect.ignoreCause({ log: true }), Effect.asVoid);
return WsRpcGroup.of({
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
observeRpcEffect(
@@ -559,14 +566,16 @@ const WsRpcLayer = WsRpcGroup.toLayer(
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.gitStatus]: (input) =>
observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(input), {
[WS_METHODS.subscribeGitStatus]: (input) =>
observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitPull]: (input) =>
observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitPull,
git.pullCurrentBranch(input.cwd).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitRunStackedAction]: (input) =>
observeRpcStream(
WS_METHODS.gitRunStackedAction,
@@ -581,7 +590,10 @@ const WsRpcLayer = WsRpcGroup.toLayer(
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
onSuccess: () =>
refreshGitStatus(input.cwd).pipe(
Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
),
}),
),
),
@@ -594,7 +606,9 @@ const WsRpcLayer = WsRpcGroup.toLayer(
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
observeRpcEffect(
WS_METHODS.gitPreparePullRequestThread,
gitManager.preparePullRequestThread(input),
gitManager
.preparePullRequestThread(input)
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitListBranches]: (input) =>
@@ -602,23 +616,37 @@ const WsRpcLayer = WsRpcGroup.toLayer(
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateWorktree]: (input) =>
observeRpcEffect(WS_METHODS.gitCreateWorktree, git.createWorktree(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitCreateWorktree,
git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitRemoveWorktree]: (input) =>
observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitRemoveWorktree,
git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitCreateBranch]: (input) =>
observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitCreateBranch,
git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitCheckout]: (input) =>
observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitCheckout,
Effect.scoped(git.checkoutBranch(input)).pipe(
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitInit]: (input) =>
observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "rpc.aggregate": "git" }),
observeRpcEffect(
WS_METHODS.gitInit,
git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",
@@ -1,5 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
@@ -17,9 +17,9 @@ import {
import {
gitBranchSearchInfiniteQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
} from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
@@ -89,7 +89,7 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const branchStatusQuery = useGitStatus(branchCwd);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
@@ -228,27 +228,23 @@ export function BranchToolbarBranchSelector({
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
const checkoutResult = await api.git.checkout({
cwd: selectionTarget.checkoutCwd,
branch: branch.name,
});
await invalidateGitQueries(queryClient);
const nextBranchName = branch.isRemote
? (checkoutResult.branch ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: selectionTarget.checkoutCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
});
};
@@ -651,24 +651,6 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}
if (tag === WS_METHODS.projectsSearchEntries) {
return {
entries: [],
+2 -2
View File
@@ -27,7 +27,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { useQuery } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { useGitStatus } from "~/lib/gitStatusState";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -1399,7 +1399,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const gitStatusQuery = useQuery(gitStatusQueryOptions(gitCwd));
const gitStatusQuery = useGitStatus(gitCwd);
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
+2 -2
View File
@@ -19,7 +19,7 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { useGitStatus } from "~/lib/gitStatusState";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
@@ -189,7 +189,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitStatusQuery = useQuery(gitStatusQueryOptions(activeCwd ?? null));
const gitStatusQuery = useGitStatus(activeCwd ?? null);
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -10,7 +10,7 @@ const BRANCH_NAME = "feature/toast-scope";
const {
invalidateGitQueriesSpy,
invalidateGitStatusQuerySpy,
refreshGitStatusSpy,
runStackedActionMutateAsyncSpy,
setThreadBranchSpy,
toastAddSpy,
@@ -19,7 +19,7 @@ const {
toastUpdateSpy,
} = vi.hoisted(() => ({
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
invalidateGitStatusQuerySpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
@@ -57,21 +57,6 @@ vi.mock("@tanstack/react-query", async () => {
};
}),
useQuery: vi.fn((options: { queryKey?: string[] }) => {
if (options.queryKey?.[0] === "git-status") {
return {
data: {
branch: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
error: null,
};
}
if (options.queryKey?.[0] === "git-branches") {
return {
data: {
@@ -110,7 +95,6 @@ vi.mock("~/editorPreferences", () => ({
}));
vi.mock("~/lib/gitReactQuery", () => ({
gitBranchesQueryOptions: vi.fn(() => ({ queryKey: ["git-branches"] })),
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
pull: vi.fn(() => ["pull"]),
@@ -118,9 +102,24 @@ vi.mock("~/lib/gitReactQuery", () => ({
},
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
gitStatusQueryOptions: vi.fn(() => ({ queryKey: ["git-status"] })),
invalidateGitQueries: invalidateGitQueriesSpy,
invalidateGitStatusQuery: invalidateGitStatusQuerySpy,
}));
vi.mock("~/lib/gitStatusState", () => ({
refreshGitStatus: refreshGitStatusSpy,
useGitStatus: vi.fn(() => ({
data: {
branch: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
error: null,
isPending: false,
})),
}));
vi.mock("~/lib/utils", async () => {
@@ -5,7 +5,7 @@ import type {
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
@@ -45,9 +45,8 @@ import {
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitStatusQuery,
} from "~/lib/gitReactQuery";
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
@@ -275,7 +274,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: gitStatus = null, error: gitStatusError } = useGitStatus(gitCwd);
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
@@ -801,7 +800,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitStatusQuery(queryClient, gitCwd);
if (open) refreshGitStatus(gitCwd);
}}
>
<MenuTrigger
@@ -170,20 +170,6 @@ function resolveWsRpc(tag: string): unknown {
branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}
if (tag === WS_METHODS.projectsSearchEntries) {
return { entries: [], truncated: false };
}
+4 -21
View File
@@ -49,7 +49,6 @@ import {
ThreadId,
type GitStatusResult,
} from "@t3tools/contracts";
import { useQueries } from "@tanstack/react-query";
import { Link, useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
type SidebarProjectSortOrder,
@@ -70,7 +69,7 @@ import {
threadJumpIndexFromCommand,
threadTraversalDirectionFromCommand,
} from "../keybindings";
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
import { useGitStatuses } from "../lib/gitStatusState";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
@@ -782,33 +781,17 @@ export default function Sidebar() {
],
[threadGitTargets],
);
const threadGitStatusQueries = useQueries({
queries: threadGitStatusCwds.map((cwd) => ({
...gitStatusQueryOptions(cwd),
staleTime: 30_000,
refetchInterval: 60_000,
})),
});
const threadGitStatuses = useGitStatuses(threadGitStatusCwds);
const prByThreadId = useMemo(() => {
const statusByCwd = new Map<string, GitStatusResult>();
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
const cwd = threadGitStatusCwds[index];
if (!cwd) continue;
const status = threadGitStatusQueries[index]?.data;
if (status) {
statusByCwd.set(cwd, status);
}
}
const map = new Map<ThreadId, ThreadPr>();
for (const target of threadGitTargets) {
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
const status = target.cwd ? threadGitStatuses.get(target.cwd) : undefined;
const branchMatches =
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
}, [threadGitStatuses, threadGitTargets]);
const openPrLink = useCallback((event: MouseEvent<HTMLElement>, prUrl: string) => {
event.preventDefault();
-29
View File
@@ -15,12 +15,9 @@ import type { GitListBranchesResult } from "@t3tools/contracts";
import {
gitBranchSearchInfiniteQueryOptions,
gitMutationKeys,
gitQueryKeys,
gitPreparePullRequestThreadMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
invalidateGitStatusQuery,
gitStatusQueryOptions,
invalidateGitQueries,
} from "./gitReactQuery";
@@ -84,7 +81,6 @@ describe("invalidateGitQueries", () => {
it("can invalidate a single cwd without blasting other git query scopes", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(gitQueryKeys.status("/repo/a"), { ok: "a" });
queryClient.setQueryData(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/a",
@@ -92,7 +88,6 @@ describe("invalidateGitQueries", () => {
}).queryKey,
BRANCH_SEARCH_RESULT,
);
queryClient.setQueryData(gitQueryKeys.status("/repo/b"), { ok: "b" });
queryClient.setQueryData(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/b",
@@ -103,9 +98,6 @@ describe("invalidateGitQueries", () => {
await invalidateGitQueries(queryClient, { cwd: "/repo/a" });
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/a").queryKey)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
@@ -114,9 +106,6 @@ describe("invalidateGitQueries", () => {
}).queryKey,
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/b").queryKey)?.isInvalidated,
).toBe(false);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
@@ -127,21 +116,3 @@ describe("invalidateGitQueries", () => {
).toBe(false);
});
});
describe("invalidateGitStatusQuery", () => {
it("invalidates only status for the selected cwd", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(gitQueryKeys.status("/repo/a"), { ok: "a" });
queryClient.setQueryData(gitQueryKeys.status("/repo/b"), { ok: "b" });
await invalidateGitStatusQuery(queryClient, "/repo/a");
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/a").queryKey)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/b").queryKey)?.isInvalidated,
).toBe(false);
});
});
+44 -67
View File
@@ -12,15 +12,12 @@ import {
import { ensureNativeApi } from "../nativeApi";
import { getWsRpcClient } from "../wsRpcClient";
const GIT_STATUS_STALE_TIME_MS = 5_000;
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
const GIT_BRANCHES_PAGE_SIZE = 100;
export const gitQueryKeys = {
all: ["git"] as const,
status: (cwd: string | null) => ["git", "status", cwd] as const,
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
branchSearch: (cwd: string | null, query: string) =>
["git", "branches", cwd, "search", query] as const,
@@ -38,37 +35,18 @@ export const gitMutationKeys = {
export function invalidateGitQueries(queryClient: QueryClient, input?: { cwd?: string | null }) {
const cwd = input?.cwd ?? null;
if (cwd !== null) {
return Promise.all([
queryClient.invalidateQueries({ queryKey: gitQueryKeys.status(cwd) }),
queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) }),
]);
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) });
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
export function invalidateGitStatusQuery(queryClient: QueryClient, cwd: string | null) {
function invalidateGitBranchQueries(queryClient: QueryClient, cwd: string | null) {
if (cwd === null) {
return Promise.resolve();
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.status(cwd) });
}
export function gitStatusQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.status(cwd),
queryFn: async () => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git status is unavailable.");
return api.git.status({ cwd });
},
enabled: cwd !== null,
staleTime: GIT_STATUS_STALE_TIME_MS,
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
});
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) });
}
export function gitBranchSearchInfiniteQueryOptions(input: {
@@ -129,7 +107,7 @@ export function gitInitMutationOptions(input: { cwd: string | null; queryClient:
return api.git.init({ cwd: input.cwd });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
@@ -146,7 +124,7 @@ export function gitCheckoutMutationOptions(input: {
return api.git.checkout({ cwd: input.cwd, branch });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
@@ -175,18 +153,18 @@ export function gitRunStackedActionMutationOptions(input: {
if (!input.cwd) throw new Error("Git action is unavailable.");
return getWsRpcClient().git.runStackedAction(
{
action,
actionId,
cwd: input.cwd,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
...(featureBranch ? { featureBranch: true } : {}),
...(filePaths && filePaths.length > 0 ? { filePaths } : {}),
},
...(onProgress ? [{ onProgress }] : []),
);
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
@@ -199,31 +177,19 @@ export function gitPullMutationOptions(input: { cwd: string | null; queryClient:
if (!input.cwd) throw new Error("Git pull is unavailable.");
return api.git.pull({ cwd: input.cwd });
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async ({
cwd,
branch,
newBranch,
path,
}: {
cwd: string;
branch: string;
newBranch: string;
path?: string | null;
}) => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git worktree creation is unavailable.");
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
},
mutationKey: ["git", "mutation", "create-worktree"] as const,
onSettled: async () => {
mutationFn: (
args: Parameters<ReturnType<typeof ensureNativeApi>["git"]["createWorktree"]>[0],
) => ensureNativeApi().git.createWorktree(args),
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
@@ -231,28 +197,40 @@ export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClie
export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git worktree removal is unavailable.");
return api.git.removeWorktree({ cwd, path, force });
},
mutationKey: ["git", "mutation", "remove-worktree"] as const,
onSettled: async () => {
mutationFn: (
args: Parameters<ReturnType<typeof ensureNativeApi>["git"]["removeWorktree"]>[0],
) => ensureNativeApi().git.removeWorktree(args),
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
export function gitCreateBranchMutationOptions(input: {
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationKey: ["git", "mutation", "create-branch", input.cwd] as const,
mutationFn: async (branch: string) => {
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
return api.git.createBranch({ cwd: input.cwd, branch });
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
export function gitPreparePullRequestThreadMutationOptions(input: {
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationFn: async ({
reference,
mode,
threadId,
}: {
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
mutationFn: async (args: {
reference: string;
mode: "local" | "worktree";
threadId?: ThreadId;
@@ -261,14 +239,13 @@ export function gitPreparePullRequestThreadMutationOptions(input: {
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
return api.git.preparePullRequestThread({
cwd: input.cwd,
reference,
mode,
...(threadId ? { threadId } : {}),
reference: args.reference,
mode: args.mode,
...(args.threadId ? { threadId: args.threadId } : {}),
});
},
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
+61
View File
@@ -0,0 +1,61 @@
import { GitManagerError, type GitStatusResult } from "@t3tools/contracts";
import { Cause, Option } from "effect";
import { AsyncResult } from "effect/unstable/reactivity";
import { describe, expect, it } from "vitest";
import { deriveGitStatusState } from "./gitStatusState";
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
describe("deriveGitStatusState", () => {
it("uses the latest streamed snapshot as the current git status", () => {
const streamedStatuses: [GitStatusResult, ...GitStatusResult[]] = [
BASE_STATUS,
{ ...BASE_STATUS, branch: "feature/updated-status" },
];
const state = deriveGitStatusState(
AsyncResult.success({
done: false,
items: streamedStatuses,
}),
);
expect(state).toEqual({
data: { ...BASE_STATUS, branch: "feature/updated-status" },
error: null,
cause: null,
isPending: false,
});
});
it("preserves the previous snapshot when the stream fails after succeeding", () => {
const previousSuccess = AsyncResult.success({
done: false,
items: [BASE_STATUS] as [GitStatusResult],
});
const error = new GitManagerError({
operation: "subscribeGitStatus",
detail: "stream disconnected",
});
const state = deriveGitStatusState(
AsyncResult.failure(Cause.fail(error), {
previousSuccess: Option.some(previousSuccess),
}),
);
expect(state.data).toEqual(BASE_STATUS);
expect(state.error).toBe(error);
expect(state.isPending).toBe(false);
});
});
+125
View File
@@ -0,0 +1,125 @@
import { useAtomValue } from "@effect/atom-react";
import { type GitManagerServiceError, type GitStatusResult, WS_METHODS } from "@t3tools/contracts";
import { Cause, Option } from "effect";
import type { RpcClientError } from "effect/unstable/rpc/RpcClientError";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useEffect, useState } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { WsRpcAtomClient } from "../rpc/client";
export type GitStatusStreamError =
| GitManagerServiceError
| RpcClientError
| Cause.NoSuchElementError;
export interface GitStatusState {
readonly data: GitStatusResult | null;
readonly error: GitStatusStreamError | null;
readonly cause: Cause.Cause<GitStatusStreamError> | null;
readonly isPending: boolean;
}
const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const emptyGitStatusStateAtom = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status-empty"),
);
const gitStatusStreamAtom = Atom.family((cwd: string) =>
WsRpcAtomClient.query(WS_METHODS.subscribeGitStatus, { cwd }).pipe(
Atom.withLabel(`git-status-stream:${cwd}`),
),
);
const gitStatusStateAtom = Atom.family((cwd: string) =>
Atom.make((get) => deriveGitStatusState(get(gitStatusStreamAtom(cwd)))).pipe(
Atom.withLabel(`git-status-state:${cwd}`),
),
);
export function deriveGitStatusState(
result: Atom.PullResult<GitStatusResult, GitStatusStreamError>,
): GitStatusState {
if (AsyncResult.isSuccess(result)) {
return {
data: getLatestGitStatusResult(result.value),
error: null,
cause: null,
isPending: result.waiting,
};
}
if (AsyncResult.isFailure(result)) {
const previousSuccess = Option.getOrNull(result.previousSuccess);
return {
data: previousSuccess ? getLatestGitStatusResult(previousSuccess.value) : null,
error: Option.getOrNull(Cause.findErrorOption(result.cause)),
cause: result.cause,
isPending: result.waiting,
};
}
return {
...EMPTY_GIT_STATUS_STATE,
isPending: true,
};
}
export function refreshGitStatus(cwd: string | null): void {
if (cwd === null) {
return;
}
appAtomRegistry.refresh(gitStatusStreamAtom(cwd));
}
export function useGitStatus(cwd: string | null): GitStatusState {
return useAtomValue(cwd === null ? emptyGitStatusStateAtom : gitStatusStateAtom(cwd));
}
export function useGitStatuses(cwds: ReadonlyArray<string>): ReadonlyMap<string, GitStatusResult> {
const [statusByCwd, setStatusByCwd] = useState<ReadonlyMap<string, GitStatusResult>>(
() => new Map(),
);
useEffect(() => {
const cleanups = cwds.map((cwd) =>
appAtomRegistry.subscribe(
gitStatusStateAtom(cwd),
(state) => {
setStatusByCwd((current) => {
const next = new Map(current);
if (state.data) {
next.set(cwd, state.data);
} else {
next.delete(cwd);
}
return next;
});
},
{ immediate: true },
),
);
return () => {
for (const cleanup of cleanups) {
cleanup();
}
};
}, [cwds]);
return statusByCwd;
}
function getLatestGitStatusResult(value: {
readonly items: ReadonlyArray<GitStatusResult>;
}): GitStatusResult | null {
return value.items.at(-1) ?? null;
}
+31 -1
View File
@@ -3,6 +3,7 @@ import {
DEFAULT_SERVER_SETTINGS,
type DesktopBridge,
EventId,
type GitStatusResult,
ProjectId,
type OrchestrationEvent,
type ServerConfig,
@@ -31,6 +32,7 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
const orchestrationEventListeners = new Set<(event: OrchestrationEvent) => void>();
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const rpcClientMock = {
dispose: vi.fn(),
@@ -54,7 +56,9 @@ const rpcClientMock = {
},
git: {
pull: vi.fn(),
status: vi.fn(),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
runStackedAction: vi.fn(),
listBranches: vi.fn(),
createWorktree: vi.fn(),
@@ -243,6 +247,32 @@ describe("wsNativeApi", () => {
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
});
it("forwards git status stream events", async () => {
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
const onStatus = vi.fn();
api.git.onStatus({ cwd: "/repo" }, onStatus);
const gitStatus = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/streamed",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
} satisfies GitStatusResult;
emitEvent(gitStatusListeners, gitStatus);
expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
expect(onStatus).toHaveBeenCalledWith(gitStatus);
});
it("forwards orchestration stream subscription options to the RPC client", async () => {
const { createWsNativeApi } = await import("./wsNativeApi");
+1 -1
View File
@@ -65,7 +65,7 @@ export function createWsNativeApi(): NativeApi {
},
git: {
pull: rpcClient.git.pull,
status: rpcClient.git.status,
onStatus: (input, callback, options) => rpcClient.git.onStatus(input, callback, options),
listBranches: rpcClient.git.listBranches,
createWorktree: rpcClient.git.createWorktree,
removeWorktree: rpcClient.git.removeWorktree,
+12 -2
View File
@@ -2,6 +2,7 @@ import {
type GitActionProgressEvent,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusResult,
type NativeApi,
ORCHESTRATION_WS_METHODS,
type ServerSettingsPatch,
@@ -64,7 +65,11 @@ export interface WsRpcClient {
};
readonly git: {
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
readonly status: RpcUnaryMethod<typeof WS_METHODS.gitStatus>;
readonly onStatus: (
input: RpcInput<typeof WS_METHODS.subscribeGitStatus>,
listener: (status: GitStatusResult) => void,
options?: StreamSubscriptionOptions,
) => () => void;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
@@ -149,7 +154,12 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
},
git: {
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)),
onStatus: (input, listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeGitStatus](input),
listener,
options,
),
runStackedAction: async (input, options) => {
let result: GitRunStackedActionResult | null = null;
+1
View File
@@ -24,6 +24,7 @@ interface BrowserWsRpcHarnessOptions {
const STREAM_METHODS = new Set<string>([
WS_METHODS.gitRunStackedAction,
WS_METHODS.subscribeGitStatus,
WS_METHODS.subscribeOrchestrationDomainEvents,
WS_METHODS.subscribeTerminalEvents,
WS_METHODS.subscribeServerConfig,
+14
View File
@@ -44,6 +44,14 @@ const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
const GitPullRequestReference = TrimmedNonEmptyStringSchema;
const GitPullRequestState = Schema.Literals(["open", "closed", "merged"]);
const GitPreparePullRequestThreadMode = Schema.Literals(["local", "worktree"]);
export const GitHostingProviderKind = Schema.Literals(["github", "gitlab", "unknown"]);
export type GitHostingProviderKind = typeof GitHostingProviderKind.Type;
export const GitHostingProvider = Schema.Struct({
kind: GitHostingProviderKind,
name: TrimmedNonEmptyStringSchema,
baseUrl: Schema.String,
});
export type GitHostingProvider = typeof GitHostingProvider.Type;
export const GitRunStackedActionToastRunAction = Schema.Struct({
kind: GitStackedAction,
});
@@ -188,6 +196,7 @@ const GitStatusPr = Schema.Struct({
export const GitStatusResult = Schema.Struct({
isRepo: Schema.Boolean,
hostingProvider: Schema.optional(GitHostingProvider),
hasOriginRemote: Schema.Boolean,
isDefaultBranch: Schema.Boolean,
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
@@ -236,6 +245,11 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({
});
export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type;
export const GitCheckoutResult = Schema.Struct({
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
});
export type GitCheckoutResult = typeof GitCheckoutResult.Type;
export const GitRunStackedActionResult = Schema.Struct({
action: GitStackedAction,
branch: Schema.Struct({
+9 -2
View File
@@ -1,5 +1,6 @@
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
@@ -149,7 +150,7 @@ export interface NativeApi {
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<void>;
checkout: (input: GitCheckoutInput) => Promise<void>;
checkout: (input: GitCheckoutInput) => Promise<GitCheckoutResult>;
init: (input: GitInitInput) => Promise<void>;
resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;
preparePullRequestThread: (
@@ -157,7 +158,13 @@ export interface NativeApi {
) => Promise<GitPreparePullRequestThreadResult>;
// Stacked action API
pull: (input: GitPullInput) => Promise<GitPullResult>;
status: (input: GitStatusInput) => Promise<GitStatusResult>;
onStatus: (
input: GitStatusInput,
callback: (status: GitStatusResult) => void,
options?: {
onResubscribe?: () => void;
},
) => () => void;
};
contextMenu: {
show: <T extends string>(
+6 -3
View File
@@ -6,6 +6,7 @@ import { OpenError, OpenInEditorInput } from "./editor";
import {
GitActionProgressEvent,
GitCheckoutInput,
GitCheckoutResult,
GitCommandError,
GitCreateBranchInput,
GitCreateWorktreeInput,
@@ -83,7 +84,6 @@ export const WS_METHODS = {
// Git methods
gitPull: "git.pull",
gitStatus: "git.status",
gitRunStackedAction: "git.runStackedAction",
gitListBranches: "git.listBranches",
gitCreateWorktree: "git.createWorktree",
@@ -110,6 +110,7 @@ export const WS_METHODS = {
serverUpdateSettings: "server.updateSettings",
// Streaming subscriptions
subscribeGitStatus: "subscribeGitStatus",
subscribeOrchestrationDomainEvents: "subscribeOrchestrationDomainEvents",
subscribeTerminalEvents: "subscribeTerminalEvents",
subscribeServerConfig: "subscribeServerConfig",
@@ -162,10 +163,11 @@ export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
error: OpenError,
});
export const WsGitStatusRpc = Rpc.make(WS_METHODS.gitStatus, {
export const WsSubscribeGitStatusRpc = Rpc.make(WS_METHODS.subscribeGitStatus, {
payload: GitStatusInput,
success: GitStatusResult,
error: GitManagerServiceError,
stream: true,
});
export const WsGitPullRpc = Rpc.make(WS_METHODS.gitPull, {
@@ -217,6 +219,7 @@ export const WsGitCreateBranchRpc = Rpc.make(WS_METHODS.gitCreateBranch, {
export const WsGitCheckoutRpc = Rpc.make(WS_METHODS.gitCheckout, {
payload: GitCheckoutInput,
success: GitCheckoutResult,
error: GitCommandError,
});
@@ -330,7 +333,7 @@ export const WsRpcGroup = RpcGroup.make(
WsProjectsSearchEntriesRpc,
WsProjectsWriteFileRpc,
WsShellOpenInEditorRpc,
WsGitStatusRpc,
WsSubscribeGitStatusRpc,
WsGitPullRpc,
WsGitRunStackedActionRpc,
WsGitResolvePullRequestRpc,
+66 -1
View File
@@ -1,4 +1,4 @@
import type { GitBranch } from "@t3tools/contracts";
import type { GitBranch, GitHostingProvider } from "@t3tools/contracts";
/**
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
@@ -119,3 +119,68 @@ export function dedupeRemoteBranchesWithLocalMatches(
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
function parseGitRemoteHost(remoteUrl: string): string | null {
const trimmed = remoteUrl.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.startsWith("git@")) {
const hostWithPath = trimmed.slice("git@".length);
const separatorIndex = hostWithPath.search(/[:/]/);
if (separatorIndex <= 0) {
return null;
}
return hostWithPath.slice(0, separatorIndex).toLowerCase();
}
try {
return new URL(trimmed).hostname.toLowerCase();
} catch {
return null;
}
}
function toBaseUrl(host: string): string {
return `https://${host}`;
}
function isGitHubHost(host: string): boolean {
return host === "github.com" || host.includes("github");
}
function isGitLabHost(host: string): boolean {
return host === "gitlab.com" || host.includes("gitlab");
}
export function detectGitHostingProviderFromRemoteUrl(
remoteUrl: string,
): GitHostingProvider | null {
const host = parseGitRemoteHost(remoteUrl);
if (!host) {
return null;
}
if (isGitHubHost(host)) {
return {
kind: "github",
name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
if (isGitLabHost(host)) {
return {
kind: "gitlab",
name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
return {
kind: "unknown",
name: host,
baseUrl: toBaseUrl(host),
};
}