From 34482c8b0cb861a01d5397569839d59e9d48f633 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 27 Nov 2026 19:44:21 +1100 Subject: [PATCH] fix(dashboard): re-read on the live stream instead of polling Every view listing runs or approvals polled on a timer: the home page made four requests every five seconds per open tab, two of them the same run list, and the needs-attention card asked for 200 runs to render five. A run or an approval request moving is now published on the hub and framed on the dashboard stream, so those views re-read on the change. A reconnect still re-reads everything, and the hub drops a reader that falls behind, which ends its stream and reconnects it. --- internal/app/archie/run.go | 5 ++ internal/platform/hub/hub.go | 4 + modules/approvals/approvals.go | 10 +++ modules/approvals/internal/store/store.go | 16 ++++ modules/dashboard/stream.go | 46 ++++++++---- modules/dashboard/stream_test.go | 85 ++++++++++++++-------- modules/runs/internal/store/store.go | 20 +++++ modules/runs/runs.go | 10 +++ ui/src/components/topbar/SectionCrumb.vue | 2 +- ui/src/dashboard/NeedsAttentionCard.vue | 7 +- ui/src/dashboard/RecentRunsCard.vue | 5 +- ui/src/pages/events/inspector/index.vue | 3 +- ui/src/pages/events/inspector/lib/state.ts | 18 +---- ui/src/pages/runs/[id].vue | 2 +- ui/src/pages/runs/index.vue | 4 +- ui/src/runs/ApprovalsSection.vue | 5 +- ui/src/stores/attention.ts | 2 +- ui/src/stores/live-events.ts | 65 ++++------------- ui/src/stores/session.ts | 23 +----- ui/test/live-state.test.ts | 18 +---- 20 files changed, 186 insertions(+), 164 deletions(-) diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index b9d783f9b..e5d9693eb 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -181,6 +181,8 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary tell := deliveries.NewModule(db, log.With("module", "deliveries"), orgID, live, conns) engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()}) + // A run that starts, moves or ends tells every open dashboard to re-read. + engine.UseLive(live) // A model alias a saved workflow names can't be deleted out from under it. settings.UseWorkflowAliases(engine) talk := chat.NewModule(db, log.With("module", "chat"), orgID, live) @@ -192,6 +194,9 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, actionTypes, settings, settings) // Approving an action that can't be undone needs a fresh passkey assertion. allow.UseConfirmer(settings) + // A request that is raised, escalated or answered moves the same way a run + // does: the dashboard re-reads it. + allow.UseLive(live) policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID) // An answer a channel delivers is an event, and settles its request. sealer, err := seal.New(cfg.AgeIdentity, cfg.AgeBackupRecipients) diff --git a/internal/platform/hub/hub.go b/internal/platform/hub/hub.go index 3742ceeca..cf52aeefb 100644 --- a/internal/platform/hub/hub.go +++ b/internal/platform/hub/hub.go @@ -9,6 +9,10 @@ import "sync" // buffer is how many notes a subscriber may fall behind before it is cut off. const buffer = 32 +// WorkTopic carries a note whenever a run or an approval request moves, so a +// mounted view re-reads what is running or waiting on a person. +const WorkTopic = "work" + // Note says something on a topic changed. Seq is the stream position a // subscriber reads from to catch up. type Note struct { diff --git a/modules/approvals/approvals.go b/modules/approvals/approvals.go index 20329e384..73a9af901 100644 --- a/modules/approvals/approvals.go +++ b/modules/approvals/approvals.go @@ -20,6 +20,7 @@ import ( "github.com/google/uuid" "github.com/jmoiron/sqlx" + "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/modules/approvals/internal/store" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/deliveries" @@ -272,6 +273,15 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake } } +// UseLive publishes a note on the hub whenever a request moves, so a mounted +// view re-reads instead of polling. +func (m *Module) UseLive(h *hub.Hub) { + if h == nil { + return + } + m.store.UseChange(func() { h.Publish(hub.Note{Topic: hub.WorkTopic}) }) +} + // Ask reuses the request for the same run and key so retries do not create // duplicate requests. It covers every action in ds, which one person approves // in one act. It uses a change-request connector when judgement requires a diff --git a/modules/approvals/internal/store/store.go b/modules/approvals/internal/store/store.go index 307bb5dab..b8b635a49 100644 --- a/modules/approvals/internal/store/store.go +++ b/modules/approvals/internal/store/store.go @@ -95,11 +95,23 @@ type Request struct { // Store is the approvals module's Postgres store. type Store struct { db *sqlx.DB + // changed is told after every write that moves a request, so a mounted + // view re-reads instead of polling. + changed func() } // New returns a store on db. func New(db *sqlx.DB) *Store { return &Store{db: db} } +// UseChange sets the function told after every write that moves a request. +func (s *Store) UseChange(changed func()) { s.changed = changed } + +func (s *Store) change() { + if s.changed != nil { + s.changed() + } +} + const requestColumns = `id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind, target_id, level, actions, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via, step, step_deadline, change_request, counted, discarded_because` @@ -126,6 +138,7 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) { if err != nil { return Request{}, fmt.Errorf("put request: %w", err) } + s.change() return out, nil } @@ -158,6 +171,7 @@ func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, b if err != nil { return Request{}, fmt.Errorf("answer request: %w", err) } + s.change() return out, nil } @@ -177,6 +191,7 @@ func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step i if err != nil { return Request{}, false, fmt.Errorf("escalate request: %w", err) } + s.change() return out, true, nil } @@ -194,6 +209,7 @@ func (s *Store) Discard(ctx context.Context, orgID string, id uuid.UUID, because if err != nil { return Request{}, false, fmt.Errorf("discard approval: %w", err) } + s.change() return out, true, nil } diff --git a/modules/dashboard/stream.go b/modules/dashboard/stream.go index ea4da8d59..d9066fc97 100644 --- a/modules/dashboard/stream.go +++ b/modules/dashboard/stream.go @@ -18,14 +18,19 @@ import ( // the connection open and the browser notices one that died. const keepalive = 25 * time.Second -// chatOutcome is the frame the dashboard re-reads the open conversation on. -const chatOutcome = `data: {"topic":"tasks","data":{"kind":"chat_outcome"}}` + "\n\n" +// workFrame tells the dashboard that a run or an approval request moved, so +// every view listing either re-reads it. +const workFrame = `data: {"topic":"work","data":{}}` + "\n\n" + +// chatFrame is the frame the dashboard re-reads the open conversation on. +const chatFrame = `data: {"topic":"chat","data":{}}` + "\n\n" // Register adds the dashboard's live stream: the one EventSource the SPA -// keeps open, framing each update as `data: {"topic":…,"data":…}`. A settled -// chat action is the only update with a dashboard reader; a turn's own reply -// streams from the chat API. Keepalives tell the connection indicator the -// server is up, and a reconnect makes every mounted page re-read. +// keeps open, framing each update as `data: {"topic":…,"data":…}`. A run or +// an approval request moving is what most views re-read on, and a settled +// chat action is what the open conversation re-reads on. Keepalives tell the +// connection indicator the server is up, and a reconnect makes every mounted +// page re-read. func Register(api huma.API, h *hub.Hub) { httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindDashboard), huma.Operation{ OperationID: "stream-dashboard", Method: http.MethodGet, Path: "/api/stream", @@ -36,19 +41,25 @@ func Register(api huma.API, h *hub.Hub) { }}, }, func(ctx context.Context, _ *struct{}) (*huma.StreamResponse, error) { // A conversation is its owner's; nobody else hears that it changed. - var chat <-chan hub.Note - stop := func() {} - if p, ok := governance.PrincipalFromContext(ctx); ok && p.IdentityID != "" { - chat, stop = h.Subscribe(chatpkg.OwnerTopic(string(p.IdentityID))) + var owner string + if p, ok := governance.PrincipalFromContext(ctx); ok { + owner = string(p.IdentityID) } return &huma.StreamResponse{Body: func(hc huma.Context) { - defer stop() - serve(hc, chat) + work, stopWork := h.Subscribe(hub.WorkTopic) + defer stopWork() + var chat <-chan hub.Note + if owner != "" { + var stopChat func() + chat, stopChat = h.Subscribe(chatpkg.OwnerTopic(owner)) + defer stopChat() + } + serve(hc, work, chat) }}, nil }) } -func serve(hc huma.Context, chat <-chan hub.Note) { +func serve(hc huma.Context, work, chat <-chan hub.Note) { w := hc.BodyWriter() flusher, ok := w.(http.Flusher) if !ok { @@ -67,13 +78,18 @@ func serve(hc huma.Context, chat <-chan hub.Note) { case <-hc.Context().Done(): return case <-tick.C: - case _, ok := <-chat: + case _, ok := <-work: if !ok { // The hub dropped a reader that fell behind; it reconnects // and re-reads. return } - frame = chatOutcome + frame = workFrame + case _, ok := <-chat: + if !ok { + return + } + frame = chatFrame } if _, err := fmt.Fprint(w, frame); err != nil { return diff --git a/modules/dashboard/stream_test.go b/modules/dashboard/stream_test.go index a419313f4..da1ce69fe 100644 --- a/modules/dashboard/stream_test.go +++ b/modules/dashboard/stream_test.go @@ -28,41 +28,68 @@ func TestStreamTellsOnlyTheConversationsOwner(t *testing.T) { {string(governance.SystemID), false}, } { t.Run(tc.reader, func(t *testing.T) { - h := hub.New() - mux := http.NewServeMux() - Register(httpapi.New(mux, "test", headerAuth{}, allowAll{}), h) - srv := httptest.NewServer(mux) - defer srv.Close() - - ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) - defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/api/stream", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("X-As", tc.reader) - res, err := srv.Client().Do(req) - if err != nil { - t.Fatal(err) - } - defer func() { _ = res.Body.Close() }() - h.Publish(hub.Note{Topic: chat.OwnerTopic("alice")}) - - heard := false - lines := bufio.NewScanner(res.Body) - for lines.Scan() { - if strings.Contains(lines.Text(), "chat_outcome") { - heard = true - break - } - } - if heard != tc.hears { + s := openStream(t, tc.reader) + s.h.Publish(hub.Note{Topic: chat.OwnerTopic("alice")}) + if heard := s.hears(`"topic":"chat"`); heard != tc.hears { t.Fatalf("%s heard the update: %v, want %v", tc.reader, heard, tc.hears) } }) } } +// TestStreamTellsEveryReaderWhenWorkMoves guards what replaced the dashboard's +// polling: a run or an approval request moving reaches every open dashboard, +// so a view re-reads on the change instead of on a timer. +func TestStreamTellsEveryReaderWhenWorkMoves(t *testing.T) { + s := openStream(t, "bob") + s.h.Publish(hub.Note{Topic: hub.WorkTopic}) + if !s.hears(`"topic":"work"`) { + t.Fatal("a run or approval moving reached no reader") + } +} + +// streamReader is one open dashboard stream, reading as one person. +type streamReader struct { + h *hub.Hub + lines *bufio.Scanner +} + +// openStream starts a dashboard stream as reader, which ends when the test +// does. +func openStream(t *testing.T, reader string) *streamReader { + t.Helper() + h := hub.New() + mux := http.NewServeMux() + Register(httpapi.New(mux, "test", headerAuth{}, allowAll{}), h) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) + t.Cleanup(cancel) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/api/stream", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("X-As", reader) + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = res.Body.Close() }) + return &streamReader{h: h, lines: bufio.NewScanner(res.Body)} +} + +// hears reports whether a frame mentioning marker arrived before the stream +// ended. +func (s *streamReader) hears(marker string) bool { + for s.lines.Scan() { + if strings.Contains(s.lines.Text(), marker) { + return true + } + } + return false +} + // headerAuth signs in whoever the X-As header names; the system identity is // the instance administrator. type headerAuth struct{} diff --git a/modules/runs/internal/store/store.go b/modules/runs/internal/store/store.go index 21f9adc8f..8167fde28 100644 --- a/modules/runs/internal/store/store.go +++ b/modules/runs/internal/store/store.go @@ -95,6 +95,9 @@ type Step struct { // Store is the runs module's Postgres store. type Store struct { db *sqlx.DB + // changed is told after every write that moves a run, so a mounted view + // re-reads instead of polling. + changed func() } // New returns a store on db. @@ -102,6 +105,15 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} } +// UseChange sets the function told after every write that moves a run. +func (s *Store) UseChange(changed func()) { s.changed = changed } + +func (s *Store) change() { + if s.changed != nil { + s.changed() + } +} + // NewRun is a run to queue. type NewRun struct { OrgID string @@ -136,6 +148,7 @@ func (s *Store) Start(ctx context.Context, n NewRun) (uuid.UUID, error) { if err != nil { return uuid.Nil, fmt.Errorf("start run: %w", err) } + s.change() return id, nil } @@ -167,6 +180,7 @@ func (s *Store) StartFor(ctx context.Context, token, parent uuid.UUID, n NewRun) if err != nil { return uuid.Nil, fmt.Errorf("start run: %w", err) } + s.change() return id, nil } @@ -195,6 +209,7 @@ func (s *Store) Claim(ctx context.Context, owner string, token uuid.UUID, ttl ti if err != nil { return Run{}, false, fmt.Errorf("claim run: %w", err) } + s.change() return run, true, nil } @@ -254,6 +269,7 @@ func (s *Store) Suspend(ctx context.Context, id, token uuid.UUID, wakeAt *time.T if affected(res) == 0 { return ErrLeaseLost } + s.change() return nil } @@ -293,6 +309,7 @@ func (s *Store) Finish(ctx context.Context, id, token uuid.UUID, e Ended) error if err := tx.Commit(); err != nil { return fmt.Errorf("finish run: %w", err) } + s.change() return nil } @@ -397,6 +414,7 @@ func (s *Store) Retry(ctx context.Context, orgID string, id uuid.UUID, from stri if err := tx.Commit(); err != nil { return fmt.Errorf("retry run: %w", err) } + s.change() return nil } @@ -420,6 +438,7 @@ func (s *Store) Signal(ctx context.Context, id uuid.UUID, key string, payload js if err := tx.Commit(); err != nil { return fmt.Errorf("signal run: %w", err) } + s.change() return nil } @@ -476,6 +495,7 @@ func (s *Store) Cancel(ctx context.Context, orgID string, id uuid.UUID, by strin if err := tx.Commit(); err != nil { return fmt.Errorf("cancel run: %w", err) } + s.change() return nil } diff --git a/modules/runs/runs.go b/modules/runs/runs.go index fbba1c9f2..3d1a8edd4 100644 --- a/modules/runs/runs.go +++ b/modules/runs/runs.go @@ -18,6 +18,7 @@ import ( "github.com/google/uuid" "github.com/jmoiron/sqlx" + "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/runs/internal/store" ) @@ -98,6 +99,15 @@ func New(db *sqlx.DB, log *slog.Logger, opts Options) *Engine { return newEngine(s, s, log, opts) } +// UseLive publishes a note on the hub whenever a run moves, so a mounted view +// re-reads instead of polling. Call it before Work. +func (e *Engine) UseLive(h *hub.Hub) { + if h == nil { + return + } + e.db.UseChange(func() { h.Publish(hub.Note{Topic: hub.WorkTopic}) }) +} + func newEngine(db *store.Store, work runWork, log *slog.Logger, opts Options) *Engine { if opts.Workers <= 0 { opts.Workers = 4 diff --git a/ui/src/components/topbar/SectionCrumb.vue b/ui/src/components/topbar/SectionCrumb.vue index 070521111..454d8c893 100644 --- a/ui/src/components/topbar/SectionCrumb.vue +++ b/ui/src/components/topbar/SectionCrumb.vue @@ -23,7 +23,7 @@ const route = useRoute(); // The badge counts what waits on a person on every page, not only the dashboard. const attention = useAttentionStore(); void attention.load(); -useLiveResource(null, () => void attention.load(), 5000); +useLiveResource("work", () => void attention.load(), 5000); const links = computed(() => navTree(props.hidden).flatMap((node): NavEntry[] => (node.kind === "link" ? [node.entry] : node.items)), ); diff --git a/ui/src/dashboard/NeedsAttentionCard.vue b/ui/src/dashboard/NeedsAttentionCard.vue index 2599a2b1f..011eafe2f 100644 --- a/ui/src/dashboard/NeedsAttentionCard.vue +++ b/ui/src/dashboard/NeedsAttentionCard.vue @@ -9,21 +9,20 @@ import { ReadError } from "@/components/ui/read-error"; import { Section } from "@/components/ui/section"; import { Timestamp } from "@/components/ui/timestamp"; import { api } from "@/lib/api"; -import { usePoll, useRead } from "@/lib/use-read"; import { waitsOnPerson } from "@/lib/needs-attention"; +import { useRead } from "@/lib/use-read"; import { useLiveResource } from "@/stores/session"; /** What waits on a person: approval requests, and runs a step parked. Each * links to the run that needs the answer. */ const approvals = useRead(() => api.approvals()); -const runs = useRead(() => api.runs()); +const runs = useRead(() => api.runs(50)); function reload(): void { void approvals.reload(); void runs.reload(); } onMounted(reload); -useLiveResource(null, reload); -usePoll(reload); +useLiveResource("work", reload); interface Waiting { key: string; diff --git a/ui/src/dashboard/RecentRunsCard.vue b/ui/src/dashboard/RecentRunsCard.vue index c9616325e..8e602418a 100644 --- a/ui/src/dashboard/RecentRunsCard.vue +++ b/ui/src/dashboard/RecentRunsCard.vue @@ -11,7 +11,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { Timestamp } from "@/components/ui/timestamp"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { api } from "@/lib/api"; -import { usePoll, useRead } from "@/lib/use-read"; +import { useRead } from "@/lib/use-read"; import { ended, stateTone } from "@/runs/state"; import { useLiveResource } from "@/stores/session"; @@ -20,8 +20,7 @@ import { useLiveResource } from "@/stores/session"; const router = useRouter(); const { data, error, reload } = useRead(() => api.runs(50)); onMounted(reload); -useLiveResource(null, () => void reload()); -usePoll(reload); +useLiveResource("work", () => void reload()); const FILTERS = [ { value: "all", label: "All" }, diff --git a/ui/src/pages/events/inspector/index.vue b/ui/src/pages/events/inspector/index.vue index 3426ac95c..f76b8c4a7 100644 --- a/ui/src/pages/events/inspector/index.vue +++ b/ui/src/pages/events/inspector/index.vue @@ -17,7 +17,7 @@ import CaptureDetail from "@/pages/events/inspector/components/CaptureDetail.vue import CapturesCard from "@/pages/events/inspector/components/CapturesCard.vue"; import EventTypesCard from "@/pages/events/inspector/components/EventTypesCard.vue"; import { loadEventTypes } from "@/pages/events/inspector/lib/event-type-state"; -import { captures, load, selectById, selectNewest, selected, useCaptures } from "@/pages/events/inspector/lib/state"; +import { captures, load, selectById, selectNewest, selected } from "@/pages/events/inspector/lib/state"; /** * Event inspector: recent inbound events, newest first, with the selected @@ -36,7 +36,6 @@ import { captures, load, selectById, selectNewest, selected, useCaptures } from * back into it; the page therefore stays as tall as the list, however large the * payload. */ -useCaptures(); const route = useRoute(); const router = useRouter(); diff --git a/ui/src/pages/events/inspector/lib/state.ts b/ui/src/pages/events/inspector/lib/state.ts index 856022ff0..c1d15488a 100644 --- a/ui/src/pages/events/inspector/lib/state.ts +++ b/ui/src/pages/events/inspector/lib/state.ts @@ -3,8 +3,6 @@ import { ref } from "vue"; import { errors } from "@/copy/errors"; import { api, describeError } from "@/lib/api"; import { keepRows } from "@/lib/keep-unchanged"; -import { useLiveResource } from "@/stores/session"; -import { loadEventTypes } from "@/pages/events/inspector/lib/event-type-state"; /** * The event inspector's shared state. @@ -58,10 +56,8 @@ export const loading = ref(true); export const selected = ref(null); /** - * load re-reads the list. It runs once on mount and again on every capture - * event, so it deliberately never re-enters the loading state: the skeletons - * are for a page with nothing on it yet, and a live refresh that put them back - * would replace the rows an operator is reading several times a minute. + * load re-reads the list. It runs on mount, so it deliberately never re-enters + * the loading state: the skeletons are for a page with nothing on it yet. */ let generation = 0; export async function load(): Promise { @@ -97,13 +93,3 @@ export function selectById(id: string): boolean { export function selectNewest(): void { if (captures.value.length) selected.value = captures.value[0]; } - -/** Owns the live stream that invalidates the list, for the page's lifetime. - * The initial read belongs to the page, which has to await it before it can - * restore a selection from the address bar. */ -export function useCaptures(): void { - useLiveResource("captures", () => { - void load(); - void loadEventTypes(); - }); -} diff --git a/ui/src/pages/runs/[id].vue b/ui/src/pages/runs/[id].vue index 15950f9be..08bc14619 100644 --- a/ui/src/pages/runs/[id].vue +++ b/ui/src/pages/runs/[id].vue @@ -42,7 +42,7 @@ const id = computed(() => String(route.params.id)); const { data, error, reload } = useRead(() => api.run(id.value)); onMounted(reload); watch(id, () => void reload()); -useLiveResource(null, () => void reload()); +useLiveResource("work", () => void reload()); const finished = computed(() => !!data.value?.run.finished_at); const cancellable = computed(() => (data.value ? !ended(data.value.run.state) : false)); usePoll(() => { diff --git a/ui/src/pages/runs/index.vue b/ui/src/pages/runs/index.vue index 0e82f9eaa..18481e870 100644 --- a/ui/src/pages/runs/index.vue +++ b/ui/src/pages/runs/index.vue @@ -16,14 +16,12 @@ import { ReadError } from "@/components/ui/read-error"; import { Spinner } from "@/components/ui/spinner"; import { api } from "@/lib/api"; import { useFilteredList } from "@/lib/sys-query"; -import { usePoll } from "@/lib/use-read"; import { useLiveResource } from "@/stores/session"; import ApprovalsSection from "@/runs/ApprovalsSection.vue"; import RunTable from "@/runs/RunTable.vue"; const { data, error, reload, query, clear } = useFilteredList((sysQuery) => api.runs(200, undefined, sysQuery)); -useLiveResource(null, () => void reload()); -usePoll(reload); +useLiveResource("work", () => void reload());