Files
kandev/apps/web/hooks/domains/session/use-session-commits.ts
T
João Salavisa 9e8e9d7dde fix(web): retry session commits fetch when workspace not ready (#789)
* 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 <agent@kandev.dev>
2026-05-03 09:38:54 +01:00

122 lines
4.7 KiB
TypeScript

import { useEffect, useCallback, useRef } from "react";
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
* share the same commit list and don't duplicate fetches.
*/
export function useSessionCommits(sessionId: string | null) {
const commits = useAppStore((state) => {
if (!sessionId) return undefined;
const envKey = state.environmentIdBySessionId[sessionId] ?? sessionId;
return state.sessionCommits.byEnvironmentId[envKey];
});
const loading = useAppStore((state) => {
if (!sessionId) return false;
const envKey = state.environmentIdBySessionId[sessionId] ?? sessionId;
return state.sessionCommits.loading[envKey] ?? false;
});
const setSessionCommits = useAppStore((state) => state.setSessionCommits);
const setSessionCommitsLoading = useAppStore((state) => state.setSessionCommitsLoading);
const connectionStatus = useAppStore((state) => state.connection.status);
// Track whether we had commits before (to detect clears)
const prevCommitsRef = useRef<SessionCommit[] | undefined>(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<ReturnType<typeof setTimeout> | null>(null);
const fetchCommits = useCallback(async () => {
if (!sessionId) return;
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[]; 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);
}
} catch (error) {
console.error("Failed to fetch session commits:", error);
} finally {
// 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]);
// Fetch commits on mount or when commits are cleared (e.g., after reset)
useEffect(() => {
if (connectionStatus !== "connected") return;
if (!sessionId) return;
// Fetch if:
// 1. commits is undefined (initial load or after clear)
// 2. commits was previously set but is now undefined (reset scenario)
const wasCleared = prevCommitsRef.current !== undefined && commits === undefined;
const needsInitialFetch = commits === undefined;
if (needsInitialFetch || wasCleared) {
fetchCommits();
}
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,
refetch: fetchCommits,
};
}