Merge pull request #193 from RuoJi6/RuoJi6/fix/issue-186-intercept-polling-count

fix(intercept): avoid full-history polling and full-table counts (#186)
This commit is contained in:
ji ruo committed 2026-11-27 15:55:28 +08:00
commit 10be95ac44
14 files changed
+676 -159

No files matched your search

@@ -161,21 +161,36 @@ function NavItem({ item, isItemActive, isSubItemActive, isSubmenuOpen }: NavItem
);
}
// InterceptPendingBadge polls /api/intercept/pending every 5 s and shows a red
// count badge when there are unresolved approval requests.
// InterceptPendingBadge polls /api/intercept/pending/summary every 5 s (while
// visible) and shows an amber count badge when there are unresolved requests.
function InterceptPendingBadge() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
let live = true;
let inFlight = false;
async function poll() {
if (inFlight || document.hidden) return;
inFlight = true;
try {
const list = await api.interceptPending();
if (live) setCount(list.length);
} catch { /* ignore */ }
const summary = await api.interceptPendingSummary();
if (live) setCount(summary.count);
} catch {
/* ignore */
} finally {
inFlight = false;
}
}
poll();
const t = setInterval(poll, 5000);
return () => { live = false; clearInterval(t); };
void poll();
const t = setInterval(() => void poll(), 5000);
const onVisible = () => {
if (!document.hidden) void poll();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
live = false;
clearInterval(t);
document.removeEventListener("visibilitychange", onVisible);
};
}, []);
if (count === 0) return null;
return (
@@ -59,7 +59,6 @@ import type {
Activity,
ChatAttachment,
IntentAsset,
InterceptApprovalRow,
Session,
SessionStatus,
SessionTokenUsage,
@@ -491,7 +490,17 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
);
}
export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string; requestedSession?: string }) {
const EMPTY_PENDING_AGENTS: string[] = [];
export function SessionsTab({
taskId,
requestedSession = "",
pendingAgentNames = EMPTY_PENDING_AGENTS,
}: {
taskId: string;
requestedSession?: string;
pendingAgentNames?: string[];
}) {
const { ui, liveUI } = useUITranslation();
const approvalFocus = useApprovalFocus({ taskId });
@@ -676,8 +685,6 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
const [taskTokens, setTaskTokens] = React.useState<TokenTotal | null>(null);
const [sessionTokens, setSessionTokens] = React.useState<Record<string, SessionTokenUsage>>({});
const [llmResolutions, setLLMResolutions] = React.useState<TaskLLMResolutions | null>(null);
// Pending intercept requests for this task — used to show warning icons on sessions.
const [pendingIntercepts, setPendingIntercepts] = React.useState<InterceptApprovalRow[]>([]);
// Refs backing SSE/loading without re-render churn.
const snapshotRef = React.useRef(0); // task-level snapshot cursor → SSE since=
@@ -885,25 +892,6 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
};
}, [taskId]);
React.useEffect(() => {
let alive = true;
const load = () =>
api
.interceptTask(taskId)
.then((rows) => {
if (alive) setPendingIntercepts(rows.filter((r) => r.status === "pending"));
})
.catch(() => {
// Polling is best-effort; the next interval retries automatically.
});
void load();
const t = setInterval(load, 5000);
return () => {
alive = false;
clearInterval(t);
};
}, [taskId]);
// Re-render on a timer so "streaming" liveness recomputes as activity goes stale.
const [, setTick] = React.useState(0);
React.useEffect(() => {
@@ -1225,16 +1213,16 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
const hasPendingForSession = React.useCallback(
(s: Session): boolean => {
if (s.inherited) return false;
if (!pendingIntercepts.length) return false;
if (s.role === "mainagent") return pendingIntercepts.some((r) => r.agent_name === "mainagent");
if (s.role === "planner") return pendingIntercepts.some((r) => r.agent_name === "planner");
if (!pendingAgentNames.length) return false;
if (s.role === "mainagent") return pendingAgentNames.includes("mainagent");
if (s.role === "planner") return pendingAgentNames.includes("planner");
// Worker: extract intent ID from "work#N · #<intentID>"
return pendingIntercepts.some((r) => {
const m = r.agent_name.match(/·\s*#(\d+)$/);
return pendingAgentNames.some((agentName) => {
const m = agentName.match(/·\s*#(\d+)$/);
return m ? m[1] === s.intent_id : false;
});
},
[pendingIntercepts],
[pendingAgentNames],
);
// Liveness from each session's last-seen activity time (kept fresh by the 1.5s tick).
@@ -314,6 +314,7 @@ function TaskDetailInner() {
if (TABS(liveUI).some((item) => item.value === normalizedRequestedTab)) setTab(normalizedRequestedTab);
}, [normalizedRequestedTab, liveUI]);
const [interceptPendingCount, setInterceptPendingCount] = React.useState(0);
const [pendingAgentNames, setPendingAgentNames] = React.useState<string[]>([]);
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [archiving, setArchiving] = React.useState(false);
@@ -326,20 +327,36 @@ function TaskDetailInner() {
React.useEffect(() => {
let alive = true;
const load = () =>
let inFlight = false;
setInterceptPendingCount(0);
setPendingAgentNames([]);
const loadSummary = () => {
if (inFlight || document.hidden) return;
inFlight = true;
api
.interceptTask(id)
.then((rows) => {
if (alive) setInterceptPendingCount(rows.filter((r) => r.status === "pending").length);
.interceptPendingSummary(id)
.then((summary) => {
if (!alive) return;
setInterceptPendingCount(summary.count);
setPendingAgentNames(summary.agent_names);
})
.catch(() => {
// Polling is best-effort; the next interval retries automatically.
})
.finally(() => {
inFlight = false;
});
void load();
const t = setInterval(load, 5000);
};
loadSummary();
const t = setInterval(loadSummary, 5000);
const onVisible = () => {
if (!document.hidden) loadSummary();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
alive = false;
clearInterval(t);
document.removeEventListener("visibilitychange", onVisible);
};
}, [id]);
@@ -598,7 +615,12 @@ function TaskDetailInner() {
{/* Tab content */}
<div className="flex-1 p-4 lg:p-6">
<TabsContent value="sessions" className="mt-0">
<SessionsTab key={id} taskId={id} requestedSession={searchParams.get("session") ?? ""} />
<SessionsTab
key={id}
taskId={id}
requestedSession={searchParams.get("session") ?? ""}
pendingAgentNames={pendingAgentNames}
/>
</TabsContent>
<TabsContent value="traffic" className="mt-0">
<TrafficHistory taskId={id} />
+94 -30
View File
@@ -34,6 +34,7 @@ import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
import { api } from "@/lib/api";
import type {
InterceptApprovalFilter,
InterceptApprovalPage,
InterceptApprovalRow,
InterceptAudit,
InterceptDetail,
@@ -902,6 +903,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
const [page, setPage] = React.useState(1);
const [pageSize, setPageSize] = React.useState(20);
const [total, setTotal] = React.useState(0);
const [totalApproximate, setTotalApproximate] = React.useState(false);
const [totalCapped, setTotalCapped] = React.useState(false);
const [hasMore, setHasMore] = React.useState(false);
const [filter, setFilter] = React.useState<InterceptApprovalFilter>({});
const [searchText, setSearchText] = React.useState("");
const [fromDate, setFromDate] = React.useState("");
@@ -913,6 +917,8 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
const [deciding, setDeciding] = React.useState(false);
const [revision, setRevision] = React.useState(0);
const request = React.useRef(0);
const inFlight = React.useRef<number | null>(null);
const pendingKeyRef = React.useRef<string | null>(null);
const decisionLock = React.useRef(false);
const filterID = React.useId();
const filtered = Boolean(filter.status || filter.decision_source || filter.q || filter.from || filter.to);
@@ -925,37 +931,77 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
}, [taskId]);
const load = React.useCallback(
async (manual = false) => {
async (mode: "full" | "manual" | "poll" = "full") => {
if (mode === "poll" && (document.hidden || inFlight.current !== null)) return;
const id = ++request.current;
if (manual) setRefreshing(true);
inFlight.current = id;
if (mode === "manual") setRefreshing(true);
const fetchHistory = () =>
taskId
? api.interceptTaskPage(taskId, page, pageSize, filter)
: api.interceptHistoryPage(page, pageSize, filter);
const applyHistory = (value: InterceptApprovalPage) => {
setRows(value.items);
setTotal(value.total);
setTotalApproximate(Boolean(value.total_approximate));
setTotalCapped(Boolean(value.total_capped));
setHasMore(Boolean(value.has_more));
setError("");
};
const pendingSignature = (list: InterceptPending[]) =>
list
.map((row) => row.id)
.sort((a, b) => a - b)
.join(",");
try {
// The approval queue is independent of the current history page and its
// filter. Older requests must remain actionable even when newer decisions
// fill the page or a filter would hide them.
const [history, pending] = await Promise.allSettled([
taskId
? api.interceptTaskPage(taskId, page, pageSize, filter)
: api.interceptHistoryPage(page, pageSize, filter),
api.interceptPending(),
]);
if (id !== request.current) return;
if (history.status === "fulfilled") {
setRows(history.value.items);
setTotal(history.value.total);
setError("");
// Keep the actionable pending queue fresh on every tick. Only auto-refresh
// history on page 1 without a free-text search (or when pending IDs change)
// so background polls neither re-run full-text scans nor shift deeper pages.
const pollHistory = mode !== "poll" || (page === 1 && !filter.q);
if (pollHistory) {
// The approval queue is independent of the current history page and its
// filter. Older requests must remain actionable even when newer decisions
// fill the page or a filter would hide them.
const [history, pending] = await Promise.allSettled([fetchHistory(), api.interceptPending(taskId)]);
if (id !== request.current) return;
if (history.status === "fulfilled") {
applyHistory(history.value);
} else {
setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef"));
}
if (pending.status === "fulfilled") {
pendingKeyRef.current = pendingSignature(pending.value);
setPendingRows(pending.value);
setPendingError("");
} else {
setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef"));
}
} else {
setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef"));
try {
const pending = await api.interceptPending(taskId);
if (id !== request.current) return;
const nextKey = pendingSignature(pending);
const changed = pendingKeyRef.current !== null && nextKey !== pendingKeyRef.current;
pendingKeyRef.current = nextKey;
setPendingRows(pending);
setPendingError("");
if (changed) {
try {
const history = await fetchHistory();
if (id === request.current) applyHistory(history);
} catch (e) {
if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef"));
}
}
} catch (e) {
if (id === request.current) setPendingError((e as Error).message || liveUI("screen.d1d044826a45ef"));
}
}
if (pending.status === "fulfilled") {
setPendingRows(pending.value);
setPendingError("");
} else {
setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef"));
}
if (manual) setRevision((v) => v + 1);
if (mode === "manual") setRevision((v) => v + 1);
} catch (e) {
if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef"));
} finally {
if (inFlight.current === id) inFlight.current = null;
if (id === request.current) {
setLoading(false);
setRefreshing(false);
@@ -968,11 +1014,17 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
latestLoad.current = load;
React.useEffect(() => {
void load();
const timer = setInterval(() => void load(), 5000);
void load("full");
const timer = setInterval(() => void load("poll"), 5000);
const onVisible = () => {
if (!document.hidden) void load("poll");
};
document.addEventListener("visibilitychange", onVisible);
return () => {
request.current++;
inFlight.current = null;
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [load]);
@@ -991,6 +1043,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setPage(1);
setRows([]);
setTotal(0);
setTotalApproximate(false);
setTotalCapped(false);
setHasMore(false);
setError("");
setLoading(true);
};
@@ -1013,6 +1068,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setPage(1);
setRows([]);
setTotal(0);
setTotalApproximate(false);
setTotalCapped(false);
setHasMore(false);
setError("");
setLoading(true);
}, 300);
@@ -1036,10 +1094,10 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setRevision((v) => v + 1);
toast.success(decision === "allowed" ? ui("screen.c90e80972b10bf") : ui("screen.846e5cf371bfdc"));
// Re-fetch counts and rows: a decided item may no longer match the filter.
await latestLoad.current(true);
await latestLoad.current("manual");
} catch (e) {
toast.error((e as Error).message);
await latestLoad.current(true);
await latestLoad.current("manual");
} finally {
decisionLock.current = false;
setDeciding(false);
@@ -1056,6 +1114,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
...historyById.get(row.id),
...row,
}));
let totalDisplay: string | number = total;
if (totalCapped) totalDisplay = `${total}+`;
else if (totalApproximate) totalDisplay = `~${total}`;
const title = taskId ? ui("screen.b4c245b6421a35") : ui("screen.b75d0f43cd1eb7");
return (
<div className="flex min-w-0 flex-col gap-5">
@@ -1069,7 +1130,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
</Badge>
) : null}
</div>
<Button variant="outline" size="sm" onClick={() => void load(true)} disabled={loading || refreshing}>
<Button variant="outline" size="sm" onClick={() => void load("manual")} disabled={loading || refreshing}>
<RefreshCwIcon data-icon="inline-start" className={cn(refreshing && "animate-spin")} />
{ui("screen.aee88743413144")}
</Button>
@@ -1217,7 +1278,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
<div className="border-b px-4 py-3 font-medium text-sm">
{filtered ? ui("screen.479424539ce56d") : ui("screen.e4257920848098")}
{ui("punctuation.da047c04c9")}
{total}
{totalDisplay}
{ui("punctuation.f2e44c6c95")}
{filter.q ? (
<span className="ml-2 break-all font-normal text-muted-foreground text-xs">
@@ -1260,6 +1321,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
page={page}
pageSize={pageSize}
total={total}
totalApproximate={totalApproximate}
totalCapped={totalCapped}
hasMore={hasMore}
onPageChange={setPage}
onPageSizeChange={changePageSize}
pageSizeOptions={[10, 20, 50]}
+15 -5
View File
@@ -13,6 +13,9 @@ interface TablePaginationProps {
page: number; // 1-based
pageSize: number;
total: number; // total (after filtering)
totalApproximate?: boolean;
totalCapped?: boolean;
hasMore?: boolean;
onPageChange: (p: number) => void;
onPageSizeChange: (s: number) => void;
pageSizeOptions?: number[];
@@ -35,15 +38,22 @@ export function TablePagination({
page,
pageSize,
total,
totalApproximate = false,
totalCapped = false,
hasMore = false,
onPageChange,
onPageSizeChange,
pageSizeOptions = [10, 20, 50],
}: TablePaginationProps) {
const { t } = useTranslation();
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const totalPages = Math.max(1, Math.ceil(total / pageSize), hasMore ? page + 1 : 0);
const safePage = Math.min(Math.max(1, page), totalPages);
const from = total === 0 ? 0 : (safePage - 1) * pageSize + 1;
const to = Math.min(safePage * pageSize, total);
const hasItems = total > 0 || hasMore;
const from = hasItems ? (safePage - 1) * pageSize + 1 : 0;
const to = hasMore ? safePage * pageSize : Math.min(safePage * pageSize, total);
let totalLabel: string | number = total;
if (totalCapped) totalLabel = `${total}+`;
else if (totalApproximate) totalLabel = `~${total}`;
const onPageChangeRef = useRef(onPageChange);
onPageChangeRef.current = onPageChange;
@@ -67,8 +77,8 @@ export function TablePagination({
</SelectContent>
</Select>
<span>{t("pagination.perPage")}</span>
{total > 0 ? (
<span className="tabular-nums">{t("pagination.range", { from, to, total, count: total })}</span>
{hasItems ? (
<span className="tabular-nums">{t("pagination.range", { from, to, total: totalLabel, count: total })}</span>
) : (
<span>{t("pagination.empty")}</span>
)}
+40 -11
View File
@@ -54,9 +54,11 @@ import type {
IntelligencePage,
IntentAsset,
InterceptApprovalFilter,
InterceptApprovalPage,
InterceptApprovalRow,
InterceptDetail,
InterceptPending,
InterceptPendingSummary,
InterceptRule,
JudgeConfig,
JudgeUsage,
@@ -1672,7 +1674,17 @@ export const api = {
post<{ ok: boolean; enabled: boolean }>(`/asset-intercept/rules/${id}/toggle`, { enabled }),
// ---- intercept pending (ask) ----
interceptPending: () => get<{ pending: InterceptPending[] }>("/intercept/pending").then((r) => arr(r.pending)),
interceptPending: (taskId?: string) =>
get<{ pending: InterceptPending[] }>(
taskId ? `/intercept/pending?task_id=${encodeURIComponent(taskId)}` : "/intercept/pending",
).then((r) => arr(r.pending)),
interceptPendingSummary: (taskId?: string): Promise<InterceptPendingSummary> =>
get<{ count?: number; agent_names?: string[] }>(
taskId ? `/intercept/pending/summary?task_id=${encodeURIComponent(taskId)}` : "/intercept/pending/summary",
).then((r) => ({
count: r.count ?? 0,
agent_names: arr(r.agent_names),
})),
interceptGetOne: (id: number) => get<InterceptPending>(`/intercept/pending/${id}`),
interceptDecide: (id: number, decision: "allowed" | "denied") =>
post<{ ok: boolean }>(`/intercept/pending/${id}/decide`, { decision }),
@@ -1682,21 +1694,38 @@ export const api = {
),
interceptDetail: (id: number) => get<InterceptDetail>(`/intercept/history/${id}`),
interceptHistory: () => get<{ items: InterceptApprovalRow[] }>("/intercept/history").then((r) => arr(r.items)),
interceptHistoryPage: (page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
get<{ items: InterceptApprovalRow[]; total?: number }>(
`/intercept/history?${interceptPageQuery(page, size, filter)}`,
).then((r) => ({
interceptHistoryPage: (page = 1, size = 20, filter: InterceptApprovalFilter = {}): Promise<InterceptApprovalPage> =>
get<{
items: InterceptApprovalRow[];
total?: number;
total_approximate?: boolean;
total_capped?: boolean;
has_more?: boolean;
}>(`/intercept/history?${interceptPageQuery(page, size, filter)}`).then((r) => ({
items: arr(r.items),
total: r.total ?? r.items?.length ?? 0,
total_approximate: Boolean(r.total_approximate),
total_capped: Boolean(r.total_capped),
has_more: Boolean(r.has_more),
})),
interceptTask: (taskId: string) =>
get<{ items: InterceptApprovalRow[] }>(`/intercept/task/${taskId}`).then((r) => arr(r.items)),
interceptTaskPage: (taskId: string, page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
get<{ items: InterceptApprovalRow[]; total?: number }>(
`/intercept/task/${encodeURIComponent(taskId)}?${interceptPageQuery(page, size, filter)}`,
).then((r) => ({
interceptTaskPage: (
taskId: string,
page = 1,
size = 20,
filter: InterceptApprovalFilter = {},
): Promise<InterceptApprovalPage> =>
get<{
items: InterceptApprovalRow[];
total?: number;
total_approximate?: boolean;
total_capped?: boolean;
has_more?: boolean;
}>(`/intercept/task/${encodeURIComponent(taskId)}?${interceptPageQuery(page, size, filter)}`).then((r) => ({
items: arr(r.items),
total: r.total ?? r.items?.length ?? 0,
total_approximate: Boolean(r.total_approximate),
total_capped: Boolean(r.total_capped),
has_more: Boolean(r.has_more),
})),
// ---- intercept tool-config (全局工具拦截范围) ----
+18 -4
View File
@@ -2774,8 +2774,19 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
if (path === "/intercept/rules" && m === "GET") return { rules: D.interceptRules };
if (seg[0] === "intercept" && seg[1] === "rules" && seg[3] === "toggle")
return { ok: true, enabled: b.enabled ?? true };
if (path === "/intercept/pending" && m === "GET")
return { pending: mockInterceptHistory.filter((r) => r.status === "pending") };
if (path === "/intercept/pending/summary" && m === "GET") {
const taskId = q.get("task_id")?.trim() || "";
const pending = mockInterceptHistory.filter((r) => r.status === "pending" && (!taskId || r.task_id === taskId));
if (!taskId) return { count: pending.length };
const agentNames = [...new Set(pending.map((r) => r.agent_name).filter(Boolean))].sort();
return { count: pending.length, agent_names: agentNames };
}
if (path === "/intercept/pending" && m === "GET") {
const taskId = q.get("task_id")?.trim() || "";
return {
pending: mockInterceptHistory.filter((r) => r.status === "pending" && (!taskId || r.task_id === taskId)),
};
}
if (seg[0] === "intercept" && seg[1] === "pending" && seg[3] === "decide") {
const id = Number(seg[2]);
const row = mockInterceptHistory.find((r) => r.id === id) ?? mockInterceptPending.find((r) => r.id === id);
@@ -2834,14 +2845,17 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
(search.startsWith("#") ? row.id === Number(search.slice(1)) : haystack.includes(search.toLowerCase())))
);
});
if (!q.has("page") && !q.has("size") && !status && !decisionSource && !search && !from && !to)
return { items: filtered, total: filtered.length };
if (!q.has("page") && !q.has("size") && !status && !decisionSource && !search && !from && !to) {
const capped = filtered.slice(0, 200);
return { items: capped, total: capped.length };
}
const page = Math.max(1, Number(q.get("page")) || 1);
const size = Math.min(100, Math.max(1, Number(q.get("size")) || 20));
const offset = (page - 1) * size;
return {
items: filtered.slice(offset, offset + size),
total: filtered.length,
has_more: offset + size < filtered.length,
page,
page_size: size,
};
+13
View File
@@ -1468,6 +1468,11 @@ export interface InterceptPending {
created_at: string;
}
export interface InterceptPendingSummary {
count: number;
agent_names: string[];
}
// JudgeConfig: 模型兜底审批(仅当没有任何拦截规则命中时由模型判断)的全局配置。
export interface JudgeConfig {
enabled: boolean;
@@ -1514,6 +1519,14 @@ export interface InterceptApprovalRow extends InterceptPending {
rule_name: string; // "" if rule was deleted
}
export interface InterceptApprovalPage {
items: InterceptApprovalRow[];
total: number;
total_approximate?: boolean;
total_capped?: boolean;
has_more?: boolean;
}
// ── 资产同步 (ScopeSentry 数据源) ──────────────────────────────────────────────
export interface SSProject {
id: string; // MongoDB ObjectID — used as filter.project