Files
buzz/desktop/src/features/agents/useManagedAgentRuntimeReconciliation.ts
Tyler 61cc738ee8 feat(desktop+acp): spawn a harness per (agent, community) pair at GUI startup — warm sockets, lazy LLM pool (#2122)
Signed-off-by: Tyler Longwell <tlongwell@block.xyz>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
Signed-off-by: Tyler <109685178+tlongwell-block@users.noreply.github.com>
Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Tyler Longwell <tlongwell@block.xyz>
Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Dawn <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Matt Toohey <contact@matttoohey.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: npub1hwqy0rnujtl25dzmlhn8qwux4kr8sjhas3ugltx9j5dm5dwkp2dsqjhytw <bb80478e7c92feaa345bfde6703b86ad86784afd84788facc5951bba35d60a9b@buzz.block.builderlab.xyz>
2026-07-22 13:24:46 -07:00

136 lines
5.0 KiB
TypeScript

import { useQueryClient } from "@tanstack/react-query";
import * as React from "react";
import {
canonicalCommunityRelays,
classifyReconcileResult,
pendingReconcileRelays,
reconcileRetryDelayMs,
} from "@/features/agents/managedAgentReconciliationPlan";
import {
cacheReconciledManagedAgentRuntimes,
managedAgentRuntimesQueryKey,
} from "@/features/agents/managedAgentRuntimeHooks";
import { canonicalRelayUrl } from "@/features/agents/managedAgentRuntimeStatus";
import type { ManagedAgentRuntimeStatus } from "@/shared/api/types";
import { reconcileManagedAgentRuntimes } from "@/shared/api/tauriManagedAgents";
/**
* Bootstrap a lazy harness pair for every auto-start local agent in every
* configured community, incrementally and with retry.
*
* Reconciliation is keyed by canonical relay URL: each configured relay is
* reconciled once it appears (so adding a community mid-session spawns pairs
* there without needing the add flow to also switch communities), and a relay
* whose reconcile fails is retried with a capped backoff (5s / 30s / 2m) rather
* than left un-spawned until the next switch or relaunch. Relays that reconcile
* cleanly are never re-hit; once nothing is outstanding, no timer is left
* running.
*/
export function useManagedAgentRuntimeReconciliation(
communities: readonly { relayUrl: string }[],
): void {
const queryClient = useQueryClient();
// Canonical relay URLs that have reconciled cleanly — never re-hit.
const reconciledRef = React.useRef<Set<string>>(new Set());
// Canonical relay URLs with a reconcile call in flight — not re-dispatched.
const inFlightRef = React.useRef<Set<string>>(new Set());
// Consecutive failures per canonical relay URL, driving the retry backoff.
const failuresRef = React.useRef<Map<string, number>>(new Map());
const retryTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(
null,
);
React.useEffect(() => {
let cancelled = false;
const clearRetryTimer = () => {
if (retryTimerRef.current !== null) {
clearTimeout(retryTimerRef.current);
retryTimerRef.current = null;
}
};
const scheduleRetry = (failed: readonly string[]) => {
// One shared timer fires at the soonest per-relay backoff; every failing
// relay is retried together (reconcile is idempotent), so re-hitting a
// longer-backoff relay early is harmless.
let soonest: number | null = null;
for (const relay of failed) {
const nextCount = (failuresRef.current.get(relay) ?? 0) + 1;
failuresRef.current.set(relay, nextCount);
const delay = reconcileRetryDelayMs(nextCount);
if (delay !== null && (soonest === null || delay < soonest)) {
soonest = delay;
}
}
clearRetryTimer();
if (soonest === null) return; // all failing relays hit the retry cap
retryTimerRef.current = setTimeout(() => {
retryTimerRef.current = null;
if (!cancelled) runReconcile();
}, soonest);
};
const runReconcile = () => {
const canonicalToRequested = canonicalCommunityRelays(
communities,
canonicalRelayUrl,
);
// Forget bookkeeping for relays that are no longer configured so the sets
// stay bounded and re-adding a removed community reconciles it afresh.
for (const done of [...reconciledRef.current]) {
if (!canonicalToRequested.has(done)) reconciledRef.current.delete(done);
}
for (const failing of [...failuresRef.current.keys()]) {
if (!canonicalToRequested.has(failing)) {
failuresRef.current.delete(failing);
}
}
const pending = pendingReconcileRelays(
canonicalToRequested,
reconciledRef.current,
inFlightRef.current,
);
if (pending.length === 0) {
clearRetryTimer();
return;
}
for (const relay of pending) inFlightRef.current.add(relay);
const targets = pending.map((relay) => ({
relayUrl: canonicalToRequested.get(relay) as string,
}));
const baseline = queryClient.getQueryData<ManagedAgentRuntimeStatus[]>(
managedAgentRuntimesQueryKey,
);
void reconcileManagedAgentRuntimes(targets)
.then((runtimes) => {
cacheReconciledManagedAgentRuntimes(queryClient, baseline, runtimes);
return classifyReconcileResult(pending, runtimes, canonicalRelayUrl);
})
.catch((error) => {
console.warn("[managed-agent-runtimes] reconcile failed:", error);
return classifyReconcileResult(pending, null, canonicalRelayUrl);
})
.then(({ succeeded, failed }) => {
for (const relay of pending) inFlightRef.current.delete(relay);
for (const relay of succeeded) {
reconciledRef.current.add(relay);
failuresRef.current.delete(relay);
}
if (!cancelled && failed.length > 0) scheduleRetry(failed);
});
};
runReconcile();
return () => {
cancelled = true;
clearRetryTimer();
};
}, [communities, queryClient]);
}