Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

perf: deduplicate git fetches and tab loaders (#4563)

[._.]/ Adam Eivyf784621e49bf
diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsx
index 17ba310153..bee050986e 100644
--- a/client/src/components/apps/tabs/GitTab.jsx
+++ b/client/src/components/apps/tabs/GitTab.jsx
@@ -108,23 +108,43 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
const [cleaningUp, setCleaningUp] = useState(false);
const [cleanupConfirm, setCleanupConfirm] = useState(false);
- const loadGitInfo = useCallback(async () => {
+ const loadGitData = useCallback(async (opts = {}) => {
if (!repoPath) return;
+ const { includeRemote = true } = opts;
setLoading(true);
- const [info, branchesResult] = await Promise.all([
+ if (includeRemote) setLoadingRemote(true);
+
+ const promises = [
api.getGitInfo(repoPath).catch(() => null),
api.getBranches(repoPath).catch(() => ({ branches: [] }))
- ]);
+ ];
+ if (includeRemote) {
+ promises.push(api.getRemoteBranches(repoPath).catch(() => null));
+ }
+
+ const [info, branchesResult, remoteResult] = await Promise.all(promises);
+
let comparison = null;
if (info?.baseBranch && info?.devBranch) {
comparison = await api.getBranchComparison(repoPath, info.baseBranch, info.devBranch).catch(() => null);
}
+
setGitInfo(info);
- setBranches(branchesResult.branches || []);
+ setBranches(branchesResult?.branches || []);
setBranchComparison(comparison);
setLoading(false);
+
+ if (includeRemote) {
+ if (remoteResult) {
+ setRemoteBranches(remoteResult.branches || []);
+ setDefaultBranch(remoteResult.defaultBranch || 'main');
+ }
+ setLoadingRemote(false);
+ }
}, [repoPath]);
+ const loadGitInfo = useCallback(() => loadGitData({ includeRemote: false }), [loadGitData]);
+
const loadRemoteBranches = useCallback(async () => {
if (!repoPath) return;
setLoadingRemote(true);
@@ -137,9 +157,8 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
}, [repoPath]);
useEffect(() => {
- loadGitInfo();
- loadRemoteBranches();
- }, [loadGitInfo, loadRemoteBranches]);
+ loadGitData({ includeRemote: true });
+ }, [loadGitData]);
const loadDiff = async () => {
if (!repoPath) return;
@@ -181,7 +200,7 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
}
toast.success(`Branches updated — ${parts.join(', ')}`);
}
- await loadGitInfo();
+ await loadGitData({ includeRemote: true });
};
const handleReleasePR = async () => {
diff --git a/server/services/git.fetchOrigin.test.js b/server/services/git.fetchOrigin.test.js
index 43aa8b1a66..94fe33175a 100644
--- a/server/services/git.fetchOrigin.test.js
+++ b/server/services/git.fetchOrigin.test.js
@@ -6,12 +6,13 @@ vi.mock('../lib/execGit.js', () => ({
execGit: execGitMock
}));
-import { fetchOrigin } from './git.js';
+import { getRemoteBranches, fetchOrigin, clearFetchCache, isFetchFresh } from './git.js';
describe('fetchOrigin', () => {
beforeEach(() => {
vi.useFakeTimers();
execGitMock.mockReset();
+ clearFetchCache();
});
afterEach(() => {
@@ -63,3 +64,61 @@ describe('fetchOrigin', () => {
expect(execGitMock).toHaveBeenCalledTimes(4);
});
});
+
+describe('getRemoteBranches fetch freshness window & deduplication', () => {
+ beforeEach(() => {
+ execGitMock.mockReset();
+ clearFetchCache();
+ });
+
+ it('skips fetch when getRemoteBranches is called again inside freshness window', async () => {
+ // Return success for fetch and standard mock outputs for git branch commands
+ execGitMock.mockResolvedValue({ stdout: 'origin/main|2026-08-19|author\n', stderr: '', exitCode: 0 });
+
+ await getRemoteBranches('/repo-fresh');
+ const callsFirst = execGitMock.mock.calls.filter(c => c[0][0] === 'fetch');
+ expect(callsFirst).toHaveLength(1);
+ expect(isFetchFresh('/repo-fresh')).toBe(true);
+
+ // Second call immediately within window
+ await getRemoteBranches('/repo-fresh');
+ const callsSecond = execGitMock.mock.calls.filter(c => c[0][0] === 'fetch');
+ expect(callsSecond).toHaveLength(1); // No new fetch calls
+ });
+
+ it('deduplicates concurrent calls to getRemoteBranches for the same repo', async () => {
+ let resolveFetch;
+ const fetchPromise = new Promise(r => { resolveFetch = r; });
+
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'fetch') {
+ return fetchPromise.then(() => ({ stdout: '', stderr: '', exitCode: 0 }));
+ }
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ });
+
+ // Launch two calls concurrently
+ const p1 = getRemoteBranches('/repo-concurrent');
+ const p2 = getRemoteBranches('/repo-concurrent');
+
+ resolveFetch();
+ await Promise.all([p1, p2]);
+
+ const fetchCalls = execGitMock.mock.calls.filter(c => c[0][0] === 'fetch');
+ expect(fetchCalls).toHaveLength(1);
+ });
+
+ it('fetchOrigin runs unconditionally and updates freshness for getRemoteBranches', async () => {
+ execGitMock.mockResolvedValue({ stdout: '', stderr: '', exitCode: 0 });
+
+ await fetchOrigin('/repo-update');
+ expect(isFetchFresh('/repo-update')).toBe(true);
+
+ // Subsequent getRemoteBranches call skips fetch because fetchOrigin refreshed it
+ await getRemoteBranches('/repo-update');
+ const fetchCalls = execGitMock.mock.calls.filter(c => c[0][0] === 'fetch');
+ // 1 from fetchOrigin, 0 from getRemoteBranches
+ expect(fetchCalls).toHaveLength(1);
+ expect(fetchCalls[0][0]).toEqual(['fetch', 'origin']);
+ });
+});
diff --git a/server/services/git.js b/server/services/git.js
index bb4383080e..007536c090 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -186,10 +186,33 @@ export async function getRemote(dir) {
*/
const FETCH_MAX_ATTEMPTS = 4;
const FETCH_RETRY_DELAY_MS = 250;
+const FETCH_FRESHNESS_MS = 15000;
+
+const lastFetchTimes = new Map();
+const activeFetches = new Map();
+
+export function recordFetchSuccess(dir) {
+ if (dir) lastFetchTimes.set(dir, Date.now());
+}
+
+export function isFetchFresh(dir, windowMs = FETCH_FRESHNESS_MS) {
+ if (!dir) return false;
+ const last = lastFetchTimes.get(dir);
+ if (!last) return false;
+ return (Date.now() - last) < windowMs;
+}
+
+export function clearFetchCache() {
+ lastFetchTimes.clear();
+ activeFetches.clear();
+}
function fetchOriginAttempt(dir, attempt) {
return execGit(['fetch', 'origin'], dir).then(
- () => true,
+ () => {
+ recordFetchSuccess(dir);
+ return true;
+ },
(err) => {
// A concurrent fetch that already wrote the exact refs this one wanted is
// a SUCCESS reported as a failure — git exits non-zero on the lost
@@ -197,7 +220,10 @@ function fetchOriginAttempt(dir, attempt) {
// right commits. Retrying re-runs a whole network fetch to learn there is
// nothing to do, and on a busy repo every attempt loses the same race, so
// the caller surfaced a red error for work that had actually completed.
- if (isBenignConcurrentFetchRefRace(err.message)) return true;
+ if (isBenignConcurrentFetchRefRace(err.message)) {
+ recordFetchSuccess(dir);
+ return true;
+ }
// Another PortOS surface or agent may advance the same remote ref mid-fetch.
if (attempt >= FETCH_MAX_ATTEMPTS || !isGitLockError(err.message)) throw err;
return sleep(FETCH_RETRY_DELAY_MS).then(() => fetchOriginAttempt(dir, attempt + 1));
@@ -838,6 +864,7 @@ export async function ensureLatest(dir) {
if (fetchResult.stderr?.includes('fatal')) {
return { success: false, branch: currentBranch, conflict: false, error: `fetch failed: ${fetchResult.stderr}` };
}
+ recordFetchSuccess(dir);
// Check if remote tracking branch exists
const remoteRef = await execGit(['rev-parse', `origin/${currentBranch}`], dir, { ignoreExitCode: true });
@@ -890,8 +917,25 @@ export async function ensureLatest(dir) {
* fully merged into the default branch and whether a local copy exists.
*/
export async function getRemoteBranches(dir) {
- // Fetch latest refs
- await execGit(['fetch', 'origin', '--prune'], dir, { ignoreExitCode: true });
+ // Fetch latest refs if not fresh within window
+ if (!isFetchFresh(dir)) {
+ if (activeFetches.has(dir)) {
+ await activeFetches.get(dir);
+ } else {
+ const fetchPromise = execGit(['fetch', 'origin', '--prune'], dir, { ignoreExitCode: true })
+ .then(res => {
+ if (res.exitCode === 0 || isBenignConcurrentFetchRefRace(res.stderr || res.stdout || '')) {
+ recordFetchSuccess(dir);
+ }
+ return res;
+ })
+ .finally(() => {
+ activeFetches.delete(dir);
+ });
+ activeFetches.set(dir, fetchPromise);
+ await fetchPromise;
+ }
+ }
// Detect default branch
const { baseBranch } = await getRepoBranches(dir);