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.
This commit is contained in:
20 files changed
+186
-164
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
+31
-15
@@ -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
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Capture | null>(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<void> {
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { Section } from "@/components/ui/section";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { api, describeError } from "@/lib/api";
|
||||
import { usePoll, useRead } from "@/lib/use-read";
|
||||
import { useRead } from "@/lib/use-read";
|
||||
import { answerApproval } from "@/runs/answer";
|
||||
import { coversSequence } from "@/runs/sequence";
|
||||
import { stateLabel } from "./state";
|
||||
@@ -22,8 +22,7 @@ const emit = defineEmits<{ answered: [] }>();
|
||||
|
||||
const { data, error, reload } = useRead(() => api.approvals());
|
||||
onMounted(reload);
|
||||
useLiveResource(null, () => void reload());
|
||||
usePoll(reload);
|
||||
useLiveResource("work", () => void reload());
|
||||
|
||||
const waiting = computed(() =>
|
||||
(data.value ?? []).filter((a) => a.state === "pending" && (!props.run || a.run_id === props.run)),
|
||||
|
||||
@@ -13,7 +13,7 @@ export const useAttentionStore = defineStore("attention", () => {
|
||||
async function load(): Promise<void> {
|
||||
// A failed read keeps the last count: the badge is a hint, and a blink to
|
||||
// zero would read as nothing waiting.
|
||||
const [approvals, runs] = await Promise.all([api.approvals().catch(() => undefined), api.runs().catch(() => undefined)]);
|
||||
const [approvals, runs] = await Promise.all([api.approvals().catch(() => undefined), api.runs(50).catch(() => undefined)]);
|
||||
if (approvals === undefined && runs === undefined) return;
|
||||
count.value = needsAttention(approvals ?? [], runs ?? []);
|
||||
}
|
||||
|
||||
@@ -1,54 +1,15 @@
|
||||
export type LiveResource =
|
||||
"tasks" | "captures" | "curators" | "skills" | "updates" | "chat";
|
||||
/** What a mounted view can re-read when the stream says it moved. A note says
|
||||
* what changed, never what it now says: one "work" frame covers a run and an
|
||||
* approval request both, because either moving is a reason to read both. */
|
||||
export type LiveResource = "work" | "chat";
|
||||
|
||||
export interface LiveEvent {
|
||||
id?: number;
|
||||
kind?: string;
|
||||
type?: string;
|
||||
task_id?: number | string;
|
||||
repo?: string;
|
||||
issue?: number | string;
|
||||
at?: string | number;
|
||||
detail?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const taskKinds = new Set([
|
||||
"stage_start",
|
||||
"stage_finish",
|
||||
"agent_finish",
|
||||
"tool_call",
|
||||
"parked",
|
||||
"outcome",
|
||||
"pr_merged",
|
||||
"pr_rejected",
|
||||
"pr_closed",
|
||||
"binding_started",
|
||||
"step_retried",
|
||||
"review_approved",
|
||||
"remediation_round",
|
||||
"operator_approved",
|
||||
"operator_rejected",
|
||||
"operator_rereviewed",
|
||||
"agent_approved",
|
||||
"agent_rejected",
|
||||
"agent_rereviewed",
|
||||
"changes_captured",
|
||||
"config_captured",
|
||||
"work_request_submitted",
|
||||
]);
|
||||
|
||||
/** Map a durable backend event to the read projections it invalidates. */
|
||||
export function resourcesForEvent(raw: unknown): LiveResource[] {
|
||||
const event = raw as LiveEvent | null;
|
||||
const kind = event?.kind ?? "";
|
||||
const resources = new Set<LiveResource>();
|
||||
if (event?.task_id || kind.startsWith("task_") || taskKinds.has(kind))
|
||||
resources.add("tasks");
|
||||
if (kind === "capture") resources.add("captures");
|
||||
if (kind.startsWith("curator_")) resources.add("curators");
|
||||
if (kind === "curator_action") resources.add("skills");
|
||||
if (kind === "update_report") resources.add("updates");
|
||||
if (kind === "chat_outcome") resources.add("chat");
|
||||
return [...resources];
|
||||
/** Map a stream frame's topic to the read it invalidates. */
|
||||
export function resourcesForTopic(topic: string): LiveResource[] {
|
||||
switch (topic) {
|
||||
case "work":
|
||||
case "chat":
|
||||
return [topic];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,7 @@ import {
|
||||
import { api, setAuthenticationStateHandler, subscribeEvents, type StreamFrame } from "../lib/api.ts";
|
||||
import type { CapabilitySections } from "../lib/capabilities.ts";
|
||||
import { reconnectDelay, type StreamState } from "../lib/stream-state.ts";
|
||||
import {
|
||||
resourcesForEvent,
|
||||
type LiveEvent,
|
||||
type LiveResource,
|
||||
} from "./live-events.ts";
|
||||
import { resourcesForTopic, type LiveResource } from "./live-events.ts";
|
||||
|
||||
/** The browser's session with the server: the live event stream, and which
|
||||
* sections this composition can back. */
|
||||
@@ -48,13 +44,8 @@ export const useSessionStore = defineStore("session", () => {
|
||||
|
||||
const streamState = ref<StreamState | "connecting">("connecting");
|
||||
const connectionRevision = ref(0);
|
||||
const activity = ref<LiveEvent[]>([]);
|
||||
const revisions = reactive<Record<LiveResource, number>>({
|
||||
tasks: 0,
|
||||
captures: 0,
|
||||
curators: 0,
|
||||
skills: 0,
|
||||
updates: 0,
|
||||
work: 0,
|
||||
chat: 0,
|
||||
});
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
@@ -62,15 +53,9 @@ export const useSessionStore = defineStore("session", () => {
|
||||
let logsReaders = 0;
|
||||
const listeners = new Map<string, Set<(data: unknown) => void>>();
|
||||
|
||||
function receive(raw: unknown): void {
|
||||
const event = raw as LiveEvent;
|
||||
activity.value = [event, ...activity.value].slice(0, 50);
|
||||
for (const resource of resourcesForEvent(event)) revisions[resource] += 1;
|
||||
}
|
||||
|
||||
function handleFrame(frame: StreamFrame, lastEventId: string): void {
|
||||
if (lastEventId) cursor = lastEventId;
|
||||
if (frame.topic === "tasks") receive(frame.data);
|
||||
for (const resource of resourcesForTopic(frame.topic)) revisions[resource] += 1;
|
||||
for (const listener of listeners.get(frame.topic) ?? []) listener(frame.data);
|
||||
}
|
||||
|
||||
@@ -126,12 +111,10 @@ export const useSessionStore = defineStore("session", () => {
|
||||
return {
|
||||
sections,
|
||||
loadCapabilities,
|
||||
activity,
|
||||
connectionRevision,
|
||||
revisions,
|
||||
streamState,
|
||||
initialize,
|
||||
receive,
|
||||
subscribe,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { resourcesForEvent } = await import("../src/stores/live-events.ts");
|
||||
|
||||
test("backend events invalidate only their owning projections", () => {
|
||||
assert.deepEqual(resourcesForEvent({ kind: "stage_finish", task_id: 42 }), [
|
||||
"tasks",
|
||||
]);
|
||||
assert.deepEqual(resourcesForEvent({ kind: "task_queued" }), ["tasks"]);
|
||||
assert.deepEqual(resourcesForEvent({ kind: "capture" }), ["captures"]);
|
||||
assert.deepEqual(resourcesForEvent({ kind: "curator_action" }), [
|
||||
"curators",
|
||||
"skills",
|
||||
]);
|
||||
assert.deepEqual(resourcesForEvent({ kind: "update_report" }), ["updates"]);
|
||||
assert.deepEqual(resourcesForEvent({ kind: "log" }), []);
|
||||
test("a frame no view reads invalidates nothing", async () => {
|
||||
const { resourcesForTopic } = await import("../src/stores/live-events.ts");
|
||||
assert.deepEqual(resourcesForTopic("work"), ["work"]);
|
||||
assert.deepEqual(resourcesForTopic("log"), []);
|
||||
});
|
||||
|
||||
test("a closed stream is retried with doubling delay, capped at 30s", async () => {
|
||||
|
||||
Reference in new issue
Block a user