diff --git a/apps/server/src/git/Layers/GitStatusBroadcaster.ts b/apps/server/src/git/Layers/GitStatusBroadcaster.ts index c75326dfbe..5f97954e97 100644 --- a/apps/server/src/git/Layers/GitStatusBroadcaster.ts +++ b/apps/server/src/git/Layers/GitStatusBroadcaster.ts @@ -127,11 +127,12 @@ export const GitStatusBroadcasterLive = Layer.effect( Effect.gen(function* () { const normalizedCwd = normalizeCwd(input.cwd); yield* ensurePoller(normalizedCwd); + const subscription = yield* PubSub.subscribe(changesPubSub); const initialStatus = yield* getStatus({ cwd: normalizedCwd }); return Stream.concat( Stream.make(initialStatus), - Stream.fromPubSub(changesPubSub).pipe( + Stream.fromEffectRepeat(PubSub.take(subscription)).pipe( Stream.filter((event) => event.cwd === normalizedCwd), Stream.map((event) => event.status), ), diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 060dddd5b9..a3cc754dfd 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -1390,6 +1390,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => { ); assert.equal(pull.status, "pulled"); + const refreshedStatus = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRefreshStatus]({ cwd: "/tmp/repo" }), + ), + ); + assert.equal(refreshedStatus.isRepo, true); + const stackedEvents = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitRunStackedAction]({ @@ -1492,11 +1499,35 @@ it.layer(NodeServices.layer)("server router seam", (it) => { cwd: "/tmp/repo", detail: "upstream missing", }); + let invalidationCalls = 0; + let statusCalls = 0; yield* buildAppUnderTest({ layers: { gitCore: { pullCurrentBranch: () => Effect.fail(gitError), }, + gitManager: { + invalidateStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + status: () => + Effect.sync(() => { + statusCalls += 1; + return { + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: true, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + }), + }, }, }); @@ -1508,6 +1539,63 @@ it.layer(NodeServices.layer)("server router seam", (it) => { ); assertFailure(result, gitError); + assert.equal(invalidationCalls, 1); + assert.equal(statusCalls, 1); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc git.runStackedAction errors after refreshing git status", () => + Effect.gen(function* () { + const gitError = new GitCommandError({ + operation: "commit", + command: "git commit", + cwd: "/tmp/repo", + detail: "nothing to commit", + }); + let invalidationCalls = 0; + let statusCalls = 0; + yield* buildAppUnderTest({ + layers: { + gitManager: { + invalidateStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + status: () => + Effect.sync(() => { + statusCalls += 1; + return { + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: false, + branch: "feature/demo", + hasWorkingTreeChanges: true, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + }), + runStackedAction: () => Effect.fail(gitError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/tmp/repo", + action: "commit", + }).pipe(Stream.runCollect, Effect.result), + ), + ); + + assertFailure(result, gitError); + assert.equal(invalidationCalls, 1); + assert.equal(statusCalls, 1); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8514469495..6697411062 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -570,10 +570,20 @@ const WsRpcLayer = WsRpcGroup.toLayer( observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), { "rpc.aggregate": "git", }), + [WS_METHODS.gitRefreshStatus]: (input) => + observeRpcEffect( + WS_METHODS.gitRefreshStatus, + gitStatusBroadcaster.refreshStatus(input.cwd), + { + "rpc.aggregate": "git", + }, + ), [WS_METHODS.gitPull]: (input) => observeRpcEffect( WS_METHODS.gitPull, - git.pullCurrentBranch(input.cwd).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + git + .pullCurrentBranch(input.cwd) + .pipe(Effect.ensuring(refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true })))), { "rpc.aggregate": "git" }, ), [WS_METHODS.gitRunStackedAction]: (input) => @@ -589,7 +599,11 @@ const WsRpcLayer = WsRpcGroup.toLayer( }) .pipe( Effect.matchCauseEffect({ - onFailure: (cause) => Queue.failCause(queue, cause), + onFailure: (cause) => + refreshGitStatus(input.cwd).pipe( + Effect.ignore({ log: true }), + Effect.andThen(Queue.failCause(queue, cause)), + ), onSuccess: () => refreshGitStatus(input.cwd).pipe( Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)), diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index bd931f517b..36d528b2da 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -46,7 +46,7 @@ import { gitPullMutationOptions, gitRunStackedActionMutationOptions, } from "~/lib/gitReactQuery"; -import { useGitStatus } from "~/lib/gitStatusState"; +import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState"; import { newCommandId, randomUUID } from "~/lib/utils"; import { resolvePathLinkTarget } from "~/terminal-links"; import { readNativeApi } from "~/nativeApi"; @@ -358,6 +358,29 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }; }, [updateActiveProgressToast]); + useEffect(() => { + if (gitCwd === null) { + return; + } + + const refreshCurrentGitStatus = () => { + void refreshGitStatus(gitCwd).catch(() => undefined); + }; + const handleVisibilityChange = () => { + if (document.visibilityState === "visible") { + refreshCurrentGitStatus(); + } + }; + + window.addEventListener("focus", refreshCurrentGitStatus); + document.addEventListener("visibilitychange", handleVisibilityChange); + + return () => { + window.removeEventListener("focus", refreshCurrentGitStatus); + document.removeEventListener("visibilitychange", handleVisibilityChange); + }; + }, [gitCwd]); + const openExistingPr = useCallback(async () => { const api = readNativeApi(); if (!api) { @@ -798,7 +821,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions )} - + { + if (open) { + void refreshGitStatus(gitCwd).catch(() => undefined); + } + }} + > } disabled={isGitActionRunning} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 78b8326af5..d227e3a803 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -298,7 +298,7 @@ function SidebarThreadRow(props: SidebarThreadRowProps) { selectThreadTerminalState(state.terminalStateByThreadId, props.threadId).runningTerminalIds, ); const gitCwd = thread?.worktreePath ?? props.projectCwd; - const gitStatus = useGitStatus(thread?.branch !== null ? gitCwd : null); + const gitStatus = useGitStatus(thread?.branch != null ? gitCwd : null); if (!thread) { return null; diff --git a/apps/web/src/lib/gitReactQuery.ts b/apps/web/src/lib/gitReactQuery.ts index ff2d7b2591..a2611ebe25 100644 --- a/apps/web/src/lib/gitReactQuery.ts +++ b/apps/web/src/lib/gitReactQuery.ts @@ -106,7 +106,7 @@ export function gitInitMutationOptions(input: { cwd: string | null; queryClient: if (!input.cwd) throw new Error("Git init is unavailable."); return api.git.init({ cwd: input.cwd }); }, - onSuccess: async () => { + onSettled: async () => { await invalidateGitBranchQueries(input.queryClient, input.cwd); }, }); @@ -123,7 +123,7 @@ export function gitCheckoutMutationOptions(input: { if (!input.cwd) throw new Error("Git checkout is unavailable."); return api.git.checkout({ cwd: input.cwd, branch }); }, - onSuccess: async () => { + onSettled: async () => { await invalidateGitBranchQueries(input.queryClient, input.cwd); }, }); diff --git a/apps/web/src/lib/gitStatusState.test.ts b/apps/web/src/lib/gitStatusState.test.ts index 9ea94acd90..14f1f355d4 100644 --- a/apps/web/src/lib/gitStatusState.test.ts +++ b/apps/web/src/lib/gitStatusState.test.ts @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { getGitStatusSnapshot, resetGitStatusStateForTests, + refreshGitStatus, watchGitStatus, } from "./gitStatusState"; @@ -30,6 +31,10 @@ const BASE_STATUS: GitStatusResult = { }; const gitClient = { + refreshStatus: vi.fn(async (input: { cwd: string }) => ({ + ...BASE_STATUS, + branch: `${input.cwd}-refreshed`, + })), onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) => registerListener(gitStatusListeners, listener), ), @@ -44,6 +49,7 @@ function emitGitStatus(event: GitStatusResult) { afterEach(() => { gitStatusListeners.clear(); gitClient.onStatus.mockClear(); + gitClient.refreshStatus.mockClear(); resetGitStatusStateForTests(); }); @@ -75,4 +81,23 @@ describe("gitStatusState", () => { releaseB(); expect(gitStatusListeners.size).toBe(0); }); + + it("refreshes git status through the unary RPC without restarting the stream", async () => { + const release = watchGitStatus("/repo", gitClient); + + emitGitStatus(BASE_STATUS); + const refreshed = await refreshGitStatus("/repo", gitClient); + + expect(gitClient.onStatus).toHaveBeenCalledOnce(); + expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" }); + expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" }); + expect(getGitStatusSnapshot("/repo")).toEqual({ + data: BASE_STATUS, + error: null, + cause: null, + isPending: false, + }); + + release(); + }); }); diff --git a/apps/web/src/lib/gitStatusState.ts b/apps/web/src/lib/gitStatusState.ts index c8df1250ce..9d85205f2a 100644 --- a/apps/web/src/lib/gitStatusState.ts +++ b/apps/web/src/lib/gitStatusState.ts @@ -16,7 +16,7 @@ export interface GitStatusState { readonly isPending: boolean; } -type GitStatusClient = Pick; +type GitStatusClient = Pick; interface WatchedGitStatus { refCount: number; @@ -33,6 +33,10 @@ const EMPTY_GIT_STATUS_STATE = Object.freeze({ const NOOP: () => void = () => undefined; const watchedGitStatuses = new Map(); const knownGitStatusCwds = new Set(); +const gitStatusRefreshInFlight = new Map>(); +const gitStatusLastRefreshAtByCwd = new Map(); + +const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000; let sharedGitStatusClient: GitStatusClient | null = null; @@ -76,11 +80,41 @@ export function watchGitStatus( return () => unwatchGitStatus(cwd); } +export function refreshGitStatus( + cwd: string | null, + client: GitStatusClient = getWsRpcClient().git, +): Promise { + if (cwd === null) { + return Promise.resolve(null); + } + + ensureGitStatusClient(client); + + const currentInFlight = gitStatusRefreshInFlight.get(cwd); + if (currentInFlight) { + return currentInFlight; + } + + const lastRequestedAt = gitStatusLastRefreshAtByCwd.get(cwd) ?? 0; + if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) { + return Promise.resolve(getGitStatusSnapshot(cwd).data); + } + + gitStatusLastRefreshAtByCwd.set(cwd, Date.now()); + const refreshPromise = client.refreshStatus({ cwd }).finally(() => { + gitStatusRefreshInFlight.delete(cwd); + }); + gitStatusRefreshInFlight.set(cwd, refreshPromise); + return refreshPromise; +} + export function resetGitStatusStateForTests(): void { for (const watched of watchedGitStatuses.values()) { watched.unsubscribe(); } watchedGitStatuses.clear(); + gitStatusRefreshInFlight.clear(); + gitStatusLastRefreshAtByCwd.clear(); sharedGitStatusClient = null; for (const cwd of knownGitStatusCwds) { @@ -92,7 +126,8 @@ export function resetGitStatusStateForTests(): void { export function useGitStatus(cwd: string | null): GitStatusState { useEffect(() => watchGitStatus(cwd), [cwd]); - return cwd === null ? EMPTY_GIT_STATUS_STATE : useAtomValue(gitStatusStateAtom(cwd)); + const state = useAtomValue(gitStatusStateAtom(cwd ?? "")); + return cwd === null ? EMPTY_GIT_STATUS_STATE : state; } function ensureGitStatusClient(client: GitStatusClient): void { diff --git a/apps/web/src/wsNativeApi.test.ts b/apps/web/src/wsNativeApi.test.ts index 38712e8eed..ae56f85991 100644 --- a/apps/web/src/wsNativeApi.test.ts +++ b/apps/web/src/wsNativeApi.test.ts @@ -56,6 +56,7 @@ const rpcClientMock = { }, git: { pull: vi.fn(), + refreshStatus: vi.fn(), onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) => registerListener(gitStatusListeners, listener), ), @@ -172,6 +173,19 @@ const baseServerConfig: ServerConfig = { settings: DEFAULT_SERVER_SETTINGS, }; +const baseGitStatus: GitStatusResult = { + 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, +}; + beforeEach(() => { vi.resetModules(); vi.clearAllMocks(); @@ -256,24 +270,24 @@ describe("wsNativeApi", () => { 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; + const gitStatus = baseGitStatus; emitEvent(gitStatusListeners, gitStatus); expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined); expect(onStatus).toHaveBeenCalledWith(gitStatus); }); + it("forwards git status refreshes directly to the RPC client", async () => { + rpcClientMock.git.refreshStatus.mockResolvedValue(baseGitStatus); + const { createWsNativeApi } = await import("./wsNativeApi"); + + const api = createWsNativeApi(); + + await api.git.refreshStatus({ cwd: "/repo" }); + + expect(rpcClientMock.git.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" }); + }); + it("forwards orchestration stream subscription options to the RPC client", async () => { const { createWsNativeApi } = await import("./wsNativeApi"); diff --git a/apps/web/src/wsNativeApi.ts b/apps/web/src/wsNativeApi.ts index 045f6bc9f0..3cfb976e09 100644 --- a/apps/web/src/wsNativeApi.ts +++ b/apps/web/src/wsNativeApi.ts @@ -69,6 +69,7 @@ export function createWsNativeApi(): NativeApi { }, git: { pull: rpcClient.git.pull, + refreshStatus: rpcClient.git.refreshStatus, onStatus: (input, callback, options) => rpcClient.git.onStatus(input, callback, options), listBranches: rpcClient.git.listBranches, createWorktree: rpcClient.git.createWorktree, diff --git a/apps/web/src/wsRpcClient.ts b/apps/web/src/wsRpcClient.ts index 3e099507b5..e8d9486a74 100644 --- a/apps/web/src/wsRpcClient.ts +++ b/apps/web/src/wsRpcClient.ts @@ -65,6 +65,7 @@ export interface WsRpcClient { }; readonly git: { readonly pull: RpcUnaryMethod; + readonly refreshStatus: RpcUnaryMethod; readonly onStatus: ( input: RpcInput, listener: (status: GitStatusResult) => void, @@ -154,6 +155,8 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient { }, git: { pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)), + refreshStatus: (input) => + transport.request((client) => client[WS_METHODS.gitRefreshStatus](input)), onStatus: (input, listener, options) => transport.subscribe( (client) => client[WS_METHODS.subscribeGitStatus](input), diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 01b6d53f21..93886c746d 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -158,6 +158,7 @@ export interface NativeApi { ) => Promise; // Stacked action API pull: (input: GitPullInput) => Promise; + refreshStatus: (input: GitStatusInput) => Promise; onStatus: ( input: GitStatusInput, callback: (status: GitStatusResult) => void, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index f86a4c0457..5a48ef7241 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -84,6 +84,7 @@ export const WS_METHODS = { // Git methods gitPull: "git.pull", + gitRefreshStatus: "git.refreshStatus", gitRunStackedAction: "git.runStackedAction", gitListBranches: "git.listBranches", gitCreateWorktree: "git.createWorktree", @@ -176,6 +177,12 @@ export const WsGitPullRpc = Rpc.make(WS_METHODS.gitPull, { error: GitCommandError, }); +export const WsGitRefreshStatusRpc = Rpc.make(WS_METHODS.gitRefreshStatus, { + payload: GitStatusInput, + success: GitStatusResult, + error: GitManagerServiceError, +}); + export const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, { payload: GitRunStackedActionInput, success: GitActionProgressEvent, @@ -335,6 +342,7 @@ export const WsRpcGroup = RpcGroup.make( WsShellOpenInEditorRpc, WsSubscribeGitStatusRpc, WsGitPullRpc, + WsGitRefreshStatusRpc, WsGitRunStackedActionRpc, WsGitResolvePullRequestRpc, WsGitPreparePullRequestThreadRpc,