From 9e8e9d7dde7932b1443d9989ab14d4ca2a63ce8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Sun, 3 May 2026 09:38:54 +0100 Subject: [PATCH] fix(web): retry session commits fetch when workspace not ready (#789) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(web): retry session commits fetch when workspace not ready The COMMITS section dropped commits to "+0 -0" when the initial session.git.commits fetch landed before agentctl was recovered: the backend returned ready:false with an empty list, the hook stored [], and never refetched — leaving mergeCommits to fall back to PR data (which has stats=null from /pulls/{n}/commits). * fix(web): address review feedback on commits retry - Keep loading:true while a retry is scheduled (Greptile/Claude): the finally block was unconditionally resetting loading to false, leaving consumers seeing { loading: false, commits: [] } during the retry window — exactly the misleading state this hook avoids. - Cancel the pending retry on disconnect (CodeRabbit): added connectionStatus to the cleanup effect deps so a queued retry doesn't fire against a disconnected WS client. - Added a regression test for the loading-stays-true behavior. --------- Co-authored-by: Kandev Agent --- .../session/use-session-commits.test.ts | 134 ++++++++++++++++++ .../domains/session/use-session-commits.ts | 55 ++++++- 2 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 apps/web/hooks/domains/session/use-session-commits.test.ts diff --git a/apps/web/hooks/domains/session/use-session-commits.test.ts b/apps/web/hooks/domains/session/use-session-commits.test.ts new file mode 100644 index 0000000000..02edd73bf2 --- /dev/null +++ b/apps/web/hooks/domains/session/use-session-commits.test.ts @@ -0,0 +1,134 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { cleanup, renderHook, waitFor } from "@testing-library/react"; + +const mockRequest = vi.fn(); +const mockSetSessionCommits = vi.fn(); +const mockSetSessionCommitsLoading = vi.fn(); + +vi.mock("@/lib/ws/connection", () => ({ + getWebSocketClient: () => ({ request: mockRequest }), +})); + +let storeState: Record = {}; + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: Record) => unknown) => selector(storeState), +})); + +import { useSessionCommits } from "./use-session-commits"; + +function setStore(connectionStatus: "connected" | "disconnected" = "connected") { + storeState = { + environmentIdBySessionId: {} as Record, + sessionCommits: { + byEnvironmentId: {} as Record, + loading: {} as Record, + }, + connection: { status: connectionStatus }, + setSessionCommits: mockSetSessionCommits, + setSessionCommitsLoading: mockSetSessionCommitsLoading, + }; +} + +describe("useSessionCommits", () => { + beforeEach(() => { + vi.clearAllMocks(); + setStore(); + }); + + afterEach(() => { + cleanup(); + }); + + it("stores commits when the backend returns a populated list", async () => { + mockRequest.mockResolvedValueOnce({ + commits: [{ commit_sha: "abc", insertions: 10, deletions: 2 }], + }); + + renderHook(() => useSessionCommits("sess-1")); + + await waitFor(() => { + expect(mockSetSessionCommits).toHaveBeenCalledWith("sess-1", [ + { commit_sha: "abc", insertions: 10, deletions: 2 }, + ]); + }); + }); + + it("retries when the backend signals ready:false instead of overwriting with []", async () => { + mockRequest.mockResolvedValueOnce({ commits: [], ready: false }).mockResolvedValueOnce({ + commits: [{ commit_sha: "abc", insertions: 5, deletions: 1 }], + }); + + renderHook(() => useSessionCommits("sess-1")); + + // First request fires immediately. + await waitFor(() => expect(mockRequest).toHaveBeenCalledTimes(1)); + // The store must NOT be filled with the empty list — that would mask the + // missing data and prevent any future load. + expect(mockSetSessionCommits).not.toHaveBeenCalled(); + + // The hook's setTimeout retry kicks in after ~2s; waitFor polls until it + // does. Bump the timeout above the retry delay. + await waitFor( + () => { + expect(mockRequest).toHaveBeenCalledTimes(2); + }, + { timeout: 4000 }, + ); + await waitFor(() => { + expect(mockSetSessionCommits).toHaveBeenCalledWith("sess-1", [ + { commit_sha: "abc", insertions: 5, deletions: 1 }, + ]); + }); + }); + + it("keeps loading:true while a retry is scheduled", async () => { + mockRequest.mockResolvedValueOnce({ commits: [], ready: false }).mockResolvedValueOnce({ + commits: [{ commit_sha: "abc" }], + }); + + renderHook(() => useSessionCommits("sess-1")); + + // First request resolves with ready:false — the hook should set loading + // to true at the start, then leave it as-is (no setLoading(false) call) + // until the retry path eventually succeeds. + await waitFor(() => expect(mockRequest).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(mockSetSessionCommitsLoading).toHaveBeenCalledWith("sess-1", true)); + // Critical: setLoading(false) must NOT have been called yet — flipping + // it during the retry window leaves consumers seeing { loading: false, + // commits: [] } which is the "loaded but empty" lie this hook avoids. + expect( + mockSetSessionCommitsLoading.mock.calls.filter(([, value]) => value === false), + ).toHaveLength(0); + + // Once the retry succeeds, loading flips to false on the success path. + await waitFor(() => expect(mockRequest).toHaveBeenCalledTimes(2), { timeout: 4000 }); + await waitFor(() => expect(mockSetSessionCommitsLoading).toHaveBeenCalledWith("sess-1", false)); + }); + + it("does not retry when ready is true (default success path)", async () => { + mockRequest.mockResolvedValueOnce({ + commits: [{ commit_sha: "abc" }], + ready: true, + }); + + renderHook(() => useSessionCommits("sess-1")); + + await waitFor(() => expect(mockSetSessionCommits).toHaveBeenCalledTimes(1)); + + // Wait past the retry window — no second request should fire. + await new Promise((resolve) => setTimeout(resolve, 2500)); + expect(mockRequest).toHaveBeenCalledTimes(1); + }); + + it("does not fetch when disconnected", () => { + setStore("disconnected"); + renderHook(() => useSessionCommits("sess-1")); + expect(mockRequest).not.toHaveBeenCalled(); + }); + + it("does not fetch when sessionId is null", () => { + renderHook(() => useSessionCommits(null)); + expect(mockRequest).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/hooks/domains/session/use-session-commits.ts b/apps/web/hooks/domains/session/use-session-commits.ts index 962d6a61d1..f72bd9b56c 100644 --- a/apps/web/hooks/domains/session/use-session-commits.ts +++ b/apps/web/hooks/domains/session/use-session-commits.ts @@ -3,6 +3,8 @@ import { useAppStore } from "@/components/state-provider"; import { getWebSocketClient } from "@/lib/ws/connection"; import type { SessionCommit } from "@/lib/state/slices/session-runtime/types"; +const NOT_READY_RETRY_MS = 2000; + /** * Hook to fetch and manage commits for a session. * Commits are keyed by environmentId so sessions sharing the same environment @@ -25,6 +27,13 @@ export function useSessionCommits(sessionId: string | null) { // Track whether we had commits before (to detect clears) const prevCommitsRef = useRef(undefined); + // Retry timer for the not-ready case — agentctl recovers asynchronously + // after a backend restart, so the first fetch may land before the workspace + // execution has been ensured. Without a retry the store would be stuck on + // an empty list and the COMMITS section would silently miss commits whose + // commit_created notifications were already fired (or pushed and so + // filtered out by the live watcher). + const retryTimerRef = useRef | null>(null); const fetchCommits = useCallback(async () => { if (!sessionId) return; @@ -32,11 +41,31 @@ export function useSessionCommits(sessionId: string | null) { const client = getWebSocketClient(); if (!client) return; + if (retryTimerRef.current) { + clearTimeout(retryTimerRef.current); + retryTimerRef.current = null; + } + setSessionCommitsLoading(sessionId, true); try { - const response = await client.request<{ commits?: SessionCommit[] }>("session.git.commits", { - session_id: sessionId, - }); + const response = await client.request<{ commits?: SessionCommit[]; ready?: boolean }>( + "session.git.commits", + { session_id: sessionId }, + ); + + // Backend signals ready:false with an empty commits array when the + // workspace execution isn't available yet (e.g. agentctl still being + // recovered after a backend restart, or a session in WAITING_FOR_INPUT + // whose execution was never spawned). Don't overwrite the store with + // [] — that would leave commits looking "loaded but empty" forever. + // Schedule a retry so we eventually pick up the real list. + if (response?.ready === false) { + retryTimerRef.current = setTimeout(() => { + retryTimerRef.current = null; + fetchCommits(); + }, NOT_READY_RETRY_MS); + return; + } if (response?.commits) { setSessionCommits(sessionId, response.commits); @@ -44,7 +73,13 @@ export function useSessionCommits(sessionId: string | null) { } catch (error) { console.error("Failed to fetch session commits:", error); } finally { - setSessionCommitsLoading(sessionId, false); + // Keep loading:true while a retry is scheduled — the operation isn't + // really finished, and flipping the flag here would let consumers see + // `{ loading: false, commits: [] }` for the whole retry window, which is + // the same misleading state this hook is designed to avoid. + if (!retryTimerRef.current) { + setSessionCommitsLoading(sessionId, false); + } } }, [sessionId, setSessionCommits, setSessionCommitsLoading]); @@ -66,6 +101,18 @@ export function useSessionCommits(sessionId: string | null) { prevCommitsRef.current = commits; }, [sessionId, commits, fetchCommits, connectionStatus]); + // Cancel any in-flight retry on unmount, when the session changes, or when + // the WS disconnects — a retry firing against a disconnected client would + // either throw inside fetchCommits or hit getWebSocketClient()===null. + useEffect(() => { + return () => { + if (retryTimerRef.current) { + clearTimeout(retryTimerRef.current); + retryTimerRef.current = null; + } + }; + }, [sessionId, connectionStatus]); + return { commits: commits ?? [], loading,