swarm-ui: one polled-resource hook for the refreshing pages
Each polling page repeated its own fetch-and-set code on a fixed timer, so a slow answer could be overtaken by the next tick, an older response could overwrite a newer one, and nothing aborted a request when the page went away. usePolled skips a tick while a request is in flight, aborts on unmount or refresh, ignores answers from dropped requests, and keeps the last good data under an error. The alerts, hives, agents, schedules, builds, review runs and broadcast pages and the subagent list use it.
This commit is contained in:
parent
9338496e24
commit
8917ba27b6
1 changed files with 274 additions and 160 deletions
|
|
@ -1,10 +1,9 @@
|
|||
// An agent's subagents, refetched on a timer: `GET /api/agents/{name}/subagents`.
|
||||
// Subagents are spawned on demand, so a one-off fetch would go stale. `null`
|
||||
// until the first answer; a failed fetch sets `error` and keeps the last list.
|
||||
// Mount per agent name: the timer is armed once per mount.
|
||||
import { useState } from "preact/hooks";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { useRefreshInterval } from "../../ui/refresh-interval/RefreshInterval.js";
|
||||
// Mount per agent name: the poll belongs to one agent.
|
||||
import type { ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { fetchJson, usePolled } from "../../ui/polled/usePolled.js";
|
||||
import { byRecency, type Subagent } from "./subagent-list.js";
|
||||
|
||||
const REFRESH_MS = 10_000;
|
||||
|
|
@ -13,24 +12,13 @@ export function useSubagentList(agentName: string): {
|
|||
subagents: Subagent[] | null;
|
||||
error: ProblemDetails | null;
|
||||
} {
|
||||
const [subagents, setSubagents] = useState<Subagent[] | null>(null);
|
||||
const [error, setError] = useState<ProblemDetails | null>(null);
|
||||
|
||||
async function refresh() {
|
||||
const res = await fetch(
|
||||
`/api/agents/${encodeURIComponent(agentName)}/subagents`,
|
||||
);
|
||||
if (!res.ok) {
|
||||
setError(await readApiError(res));
|
||||
return;
|
||||
}
|
||||
setSubagents(((await res.json()) as Subagent[]).sort(byRecency));
|
||||
setError(null);
|
||||
}
|
||||
|
||||
useRefreshInterval(REFRESH_MS, () => {
|
||||
refresh().catch((e: unknown) => setError({ detail: String(e) }));
|
||||
});
|
||||
|
||||
return { subagents, error };
|
||||
const { data, error } = usePolled(REFRESH_MS, async (signal) =>
|
||||
(
|
||||
await fetchJson<Subagent[]>(
|
||||
`/api/agents/${encodeURIComponent(agentName)}/subagents`,
|
||||
signal,
|
||||
)
|
||||
).sort(byRecency),
|
||||
);
|
||||
return { subagents: data, error };
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue