fix: poll compact task approval summaries instead of full history

This commit is contained in:
renaesop
2026-12-02 07:22:15 +00:00
parent 8f91643b78
commit e605578e3e
10 changed files with 246 additions and 35 deletions
+38
View File
@@ -0,0 +1,38 @@
package db
import "context"
// InterceptPendingSummary is the small snapshot needed by task and session badges.
// It deliberately excludes request bodies, audit context and settled history.
type InterceptPendingSummary struct {
Total int64 `json:"total"`
Agents []InterceptPendingAgent `json:"agents"`
}
type InterceptPendingAgent struct {
AgentName string `json:"agent_name"`
Count int64 `json:"count"`
}
func (d *DB) TaskInterceptPendingSummary(ctx context.Context, taskID string) (InterceptPendingSummary, error) {
result := InterceptPendingSummary{Agents: []InterceptPendingAgent{}}
rows, err := d.QueryContext(ctx, `
SELECT agent_name, COUNT(*)
FROM intercept_pending
WHERE task_id=$1 AND status='pending'
GROUP BY agent_name
ORDER BY agent_name`, taskID)
if err != nil {
return result, err
}
defer rows.Close()
for rows.Next() {
var agent InterceptPendingAgent
if err := rows.Scan(&agent.AgentName, &agent.Count); err != nil {
return result, err
}
result.Total += agent.Count
result.Agents = append(result.Agents, agent)
}
return result, rows.Err()
}
+71
View File
@@ -0,0 +1,71 @@
package db
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
)
func TestTaskInterceptPendingSummary(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.Close() })
task := "pending-summary-" + t.Name()
t.Cleanup(func() { _, _ = d.Exec("DELETE FROM intercept_pending WHERE task_id IN ($1,$2)", task, task+"-other") })
for _, fixture := range []struct {
task, agent, status string
count int
}{
{task, "mainagent", "pending", 3},
{task, "planner", "pending", 1},
{task, "work#2 · #123", "pending", 120},
{task, "mainagent", "allowed", 1000},
{task, "planner", "denied", 2},
{task, "planner", "timeout", 2},
{task + "-other", "planner", "pending", 9},
} {
_, err := d.Exec(`INSERT INTO intercept_pending(task_id,agent_name,tool_name,tool_input,status,reason)
SELECT $1,$2,'Bash',jsonb_build_object('command',repeat('private-payload',300)),$3,'private reason'
FROM generate_series(1,$4::int)`, fixture.task, fixture.agent, fixture.status, fixture.count)
if err != nil {
t.Fatal(err)
}
}
got, err := d.TaskInterceptPendingSummary(context.Background(), task)
if err != nil || got.Total != 124 || len(got.Agents) != 3 {
t.Fatalf("summary = %+v, err = %v", got, err)
}
want := map[string]int64{"mainagent": 3, "planner": 1, "work#2 · #123": 120}
for _, agent := range got.Agents {
if want[agent.AgentName] != agent.Count {
t.Fatalf("wrong agent count: %+v", agent)
}
}
raw, err := json.Marshal(got)
if err != nil || len(raw) > 300 || strings.Contains(string(raw), "private") {
t.Fatalf("summary includes details: bytes=%d err=%v", len(raw), err)
}
if _, err := d.Exec("UPDATE intercept_pending SET status='allowed' WHERE task_id=$1 AND status='pending'", task); err != nil {
t.Fatal(err)
}
got, err = d.TaskInterceptPendingSummary(context.Background(), task)
if err != nil || got.Total != 0 || got.Agents == nil || len(got.Agents) != 0 {
t.Fatalf("settled summary = %+v, err = %v", got, err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := d.TaskInterceptPendingSummary(ctx, task); !errors.Is(err, context.Canceled) {
t.Fatalf("canceled query: %v", err)
}
var index string
if err := d.QueryRow("SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND indexname='idx_intercept_pending_task_agent'").Scan(&index); err != nil {
t.Fatal(err)
}
if !strings.Contains(index, "(task_id, agent_name)") || !strings.Contains(index, "WHERE (status = 'pending'") {
t.Fatalf("missing covering partial index: %s", index)
}
}
@@ -0,0 +1,4 @@
-- Task/session badges aggregate only unresolved approvals, without loading history.
-- Covers both the task filter and agent grouping; settled rows never enter this index.
CREATE INDEX IF NOT EXISTS idx_intercept_pending_task_agent
ON intercept_pending (task_id, agent_name) WHERE status = 'pending';
+16
View File
@@ -0,0 +1,16 @@
package server
import "net/http"
func (s *Server) interceptTaskPendingSummary(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
summary, err := pg.TaskInterceptPendingSummary(r.Context(), r.PathValue("taskID"))
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, summary)
}
+72
View File
@@ -0,0 +1,72 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
)
func TestInterceptTaskPendingSummaryHTTP(t *testing.T) {
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
d, err := db.Open(dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.Close() })
task := "pending-summary-http"
t.Cleanup(func() { _, _ = d.Exec("DELETE FROM intercept_pending WHERE task_id IN ($1,$2)", task, task+"-other") })
s := &Server{m: &Manager{pg: d, interceptor: intercept.New(d)}, jwtKey: []byte("summary-test-signing-key")}
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
for _, fixture := range []struct{ task, status string }{{task, "pending"}, {task, "allowed"}, {task + "-other", "pending"}} {
if _, err := d.CreateDecidedIntercept(0, 0, fixture.task, "mainagent", "Bash", []byte(`{"command":"private fixture"}`), fixture.status, "private reason"); err != nil {
t.Fatal(err)
}
}
do := func(task string, auth bool) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodGet, "/api/intercept/task/"+task+"/pending-summary", nil)
if auth {
r.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
return rec
}
if rec := do(task, false); rec.Code != http.StatusUnauthorized {
t.Fatalf("unprotected summary: %d", rec.Code)
}
for _, tc := range []struct {
task string
total int64
}{{task, 1}, {task + "-empty", 0}} {
rec := do(tc.task, true)
var summary db.InterceptPendingSummary
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &summary) != nil || summary.Total != tc.total || summary.Agents == nil {
t.Fatalf("summary: %d %s", rec.Code, rec.Body.String())
}
if rec.Body.Len() > 150 {
t.Fatalf("summary unexpectedly includes request data: %d bytes", rec.Body.Len())
}
}
// The existing history API still includes settled rows; it is not repurposed.
req := httptest.NewRequest(http.MethodGet, "/api/intercept/task/"+task, nil)
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
var history struct {
Total int `json:"total"`
}
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &history) != nil || history.Total != 2 {
t.Fatalf("history contract changed: %d %s", rec.Code, rec.Body.String())
}
}
+1
View File
@@ -1124,6 +1124,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/intercept/history/{id}", s.interceptDetail)
mux.HandleFunc("GET /api/intercept/history/{id}/execution", s.interceptExecution)
mux.HandleFunc("GET /api/intercept/task/{taskID}", s.interceptListTaskItems)
mux.HandleFunc("GET /api/intercept/task/{taskID}/pending-summary", s.interceptTaskPendingSummary)
mux.HandleFunc("GET /api/intercept/tool-config", s.interceptGetToolConfig)
mux.HandleFunc("PUT /api/intercept/tool-config", s.interceptSetToolConfig)
mux.HandleFunc("GET /api/target-gate/exemptions", s.targetGateGetExemptions)
@@ -62,7 +62,7 @@ import type {
Activity,
ChatAttachment,
IntentAsset,
InterceptApprovalRow,
InterceptPendingSummary,
Session,
SessionStatus,
SessionTokenUsage,
@@ -466,7 +466,15 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
);
}
export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; taskPaused?: boolean }) {
export function SessionsTab({
taskId,
taskPaused = false,
pendingIntercepts,
}: {
taskId: string;
taskPaused?: boolean;
pendingIntercepts: InterceptPendingSummary["agents"];
}) {
const approvalFocus = useApprovalFocus({ taskId });
const [selectedSessionId, setActiveId] = React.useState(MAIN_ID);
const focusSession = React.useMemo<Session | undefined>(() => {
@@ -636,8 +644,6 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
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=
@@ -841,25 +847,6 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
};
}, [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 stopPolling = setVisibleInterval(load, 5000);
return () => {
alive = false;
stopPolling();
};
}, [taskId]);
// Re-render on a timer so "streaming" liveness recomputes as activity goes stale.
const [, setTick] = React.useState(0);
React.useEffect(() => {
@@ -40,7 +40,7 @@ import { useQueryState } from "@/hooks/use-query-state";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { setVisibleInterval } from "@/lib/polling";
import type { LLMProfile, Task } from "@/lib/types";
import type { InterceptPendingSummary, LLMProfile, Task } from "@/lib/types";
import { AssetsTab } from "./_tabs/assets-tab";
import { BroadcastTab } from "./_tabs/broadcast-tab";
@@ -237,7 +237,8 @@ function TaskDetailInner() {
"sessions",
TABS.map((tab) => tab.value),
);
const [interceptPendingCount, setInterceptPendingCount] = React.useState(0);
const [pendingSummary, setPendingSummary] = React.useState<InterceptPendingSummary>({ total: 0, agents: [] });
const interceptPendingCount = pendingSummary.total;
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [archiving, setArchiving] = React.useState(false);
const [resumingPlanning, setResumingPlanning] = React.useState(false);
@@ -251,19 +252,27 @@ function TaskDetailInner() {
React.useEffect(() => {
let alive = true;
const load = () =>
api
.interceptTask(id)
.then((rows) => {
if (alive) setInterceptPendingCount(rows.filter((r) => r.status === "pending").length);
})
.catch(() => {
// Polling is best-effort; the next interval retries automatically.
});
let inFlight = false;
const controller = new AbortController();
setPendingSummary({ total: 0, agents: [] });
const load = async () => {
// The initial load and a visibility refresh must not overlap.
if (inFlight || !alive) return;
inFlight = true;
try {
const summary = await api.interceptTaskPendingSummary(id, controller.signal);
if (alive) setPendingSummary(summary);
} catch {
// Keep the last snapshot; the next visible poll retries.
} finally {
inFlight = false;
}
};
void load();
const stopPolling = setVisibleInterval(load, 5000);
return () => {
alive = false;
controller.abort();
stopPolling();
};
}, [id]);
@@ -514,7 +523,7 @@ function TaskDetailInner() {
{/* Tab content */}
<div className="flex-1 p-4 lg:p-6">
<TabsContent value="sessions" className="mt-0">
<SessionsTab taskId={id} taskPaused={task?.status === "paused"} />
<SessionsTab taskId={id} taskPaused={task?.status === "paused"} pendingIntercepts={pendingSummary.agents} />
</TabsContent>
<TabsContent value="overview" className="mt-0">
<OverviewTab taskId={id} />
+7
View File
@@ -1514,6 +1514,13 @@ export const api = {
items: arr(r.items),
total: r.total ?? r.items?.length ?? 0,
})),
interceptTaskPendingSummary: (taskId: string, signal?: AbortSignal) =>
MOCK
? Promise.resolve<import("@/lib/types").InterceptPendingSummary>({ total: 0, agents: [] })
: http<import("@/lib/types").InterceptPendingSummary>(
`/intercept/task/${encodeURIComponent(taskId)}/pending-summary`,
{ signal },
),
interceptTask: (taskId: string) =>
get<{ items: InterceptApprovalRow[] }>(`/intercept/task/${taskId}`).then((r) => arr(r.items)),
interceptTaskPage: (taskId: string, page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
+6
View File
@@ -1967,3 +1967,9 @@ export interface SharedBrowserInput {
text?: string;
keyCode?: number;
}
// Compact task/session badge data; full approval details are loaded on demand.
export interface InterceptPendingSummary {
total: number;
agents: { agent_name: string; count: number }[];
}