feat(api): filter lists by sys_query

sys_query is conditions joined by ^, each field=value, field!=value or fieldLIKEtext. A bad condition or a field a list does not offer is a 400 naming the fields it accepts, so a typo never reads as an empty page. Runs, workflows, proposals, guards and action types take it, and the dashboard keeps the filter in the URL so a filtered list is a link.

The guard control API is list-guard-controls at /api/controls/guards: list-guards belongs to the connectors extension list, and the resource is a guard. JudgeStanding keeps its name, since it is the model judgement a guard recorded.
This commit is contained in:
sam committed 2026-11-27 17:06:30 +11:00
1 parent 6a3bf1e200
commit 6356aa5d52
19 files changed
+620 -173

No files matched your search

+72 -34
View File
@@ -3205,36 +3205,7 @@ components:
required:
- text
type: object
JudgementHistoryEntry:
additionalProperties: false
properties:
answered_by:
type: string
answered_by_id:
type: string
approval:
type: string
at:
format: date-time
type: string
decision_id:
type: string
level:
type: string
refused_by:
type: string
run_id:
type: string
target:
type: string
required:
- decision_id
- run_id
- target
- level
- at
type: object
JudgementJudgeControl:
JudgementGuardControl:
additionalProperties: false
properties:
advisory:
@@ -3278,6 +3249,35 @@ components:
- settings
- settings_schema
type: object
JudgementHistoryEntry:
additionalProperties: false
properties:
answered_by:
type: string
answered_by_id:
type: string
approval:
type: string
at:
format: date-time
type: string
decision_id:
type: string
level:
type: string
refused_by:
type: string
run_id:
type: string
target:
type: string
required:
- decision_id
- run_id
- target
- level
- at
type: object
JudgementJudgeRecord:
additionalProperties: false
properties:
@@ -5366,6 +5366,14 @@ paths:
/api/action-types:
get:
operationId: list-action-types
parameters:
- description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
explode: false
in: query
name: sys_query
schema:
description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
type: string
responses:
"200":
content:
@@ -6247,16 +6255,24 @@ paths:
summary: Accept a package and start it
tags:
- Connectors
/api/controls/judges:
/api/controls/guards:
get:
operationId: list-judges
operationId: list-guard-controls
parameters:
- description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
explode: false
in: query
name: sys_query
schema:
description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
type: string
responses:
"200":
content:
application/json:
schema:
items:
$ref: "#/components/schemas/JudgementJudgeControl"
$ref: "#/components/schemas/JudgementGuardControl"
type:
- array
- "null"
@@ -6267,7 +6283,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List each guard's judge, its standing and its eval date
summary: List each guard with its last recorded judgement
tags:
- Controls
/api/credential-kinds:
@@ -8291,6 +8307,13 @@ paths:
- superseded
- withdrawn
type: string
- description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
explode: false
in: query
name: sys_query
schema:
description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
type: string
responses:
"200":
content:
@@ -8533,6 +8556,13 @@ paths:
description: Only this workflow's runs
format: uuid
type: string
- description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
explode: false
in: query
name: sys_query
schema:
description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
type: string
responses:
"200":
content:
@@ -9822,6 +9852,14 @@ paths:
/api/workflows:
get:
operationId: list-workflows
parameters:
- description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
explode: false
in: query
name: sys_query
schema:
description: "Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"
type: string
responses:
"200":
content:
+138
View File
@@ -0,0 +1,138 @@
package httpapi
import (
"fmt"
"sort"
"strings"
)
// sys_query is the filter a list operation takes: conditions joined by ^, all
// of which a row must meet. A condition names a field the operation offers and
// compares the row's value for it as text: field=value keeps the rows that
// equal it, field!=value the rows that differ, and fieldLIKEtext the rows whose
// value contains text. Every comparison ignores case.
// Fields names what a list's filter may compare: each field a condition can
// name, reading one row's value as text.
type Fields[T any] map[string]func(T) string
// op is how a condition compares a row's value.
type op int
const (
opEqual op = iota
opNotEqual
opLike
)
type condition struct {
field string
op op
value string
}
// Filter keeps the rows whose values meet every condition in raw, a list's
// sys_query. An empty raw keeps every row. A malformed condition, or a field
// the list does not offer, is an error for the caller: it names what the list
// accepts, so a list answers a bad filter with a 400 rather than an empty page.
// Conditions apply to the rows the operation already read.
func Filter[T any](raw string, fields Fields[T], rows []T) ([]T, error) {
terms := strings.Split(strings.TrimSpace(raw), "^")
if len(terms) == 1 && terms[0] == "" {
return rows, nil
}
conds := make([]condition, 0, len(terms))
for _, term := range terms {
c, err := parseCondition(strings.TrimSpace(term), fields)
if err != nil {
return nil, err
}
conds = append(conds, c)
}
out := make([]T, 0, len(rows))
for _, row := range rows {
if meets(conds, fields, row) {
out = append(out, row)
}
}
return out, nil
}
func parseCondition[T any](term string, fields Fields[T]) (condition, error) {
field, value, o, ok := splitOperator(term)
if !ok {
if term == "" {
return condition{}, fmt.Errorf("sys_query: an empty condition; join conditions with ^")
}
return condition{}, fmt.Errorf("sys_query: %q has no operator; write field=value, field!=value or fieldLIKEtext", term)
}
if _, offered := fields[field]; !offered {
return condition{}, fmt.Errorf("sys_query: %q is not a field here; filter on %s", field, strings.Join(fieldNames(fields), ", "))
}
return condition{field: field, op: o, value: value}, nil
}
// splitOperator splits a condition at the first operator it contains, so a
// value may itself contain the characters of another one.
func splitOperator(term string) (field, value string, o op, ok bool) {
at, width := -1, 0
o = opEqual
consider := func(index, size int, which op) {
if index <= 0 || (at >= 0 && index >= at) {
return
}
at, width, o = index, size, which
}
consider(strings.Index(term, "!="), 2, opNotEqual)
consider(strings.Index(term, "="), 1, opEqual)
consider(indexFold(term, "LIKE"), 4, opLike)
if at < 0 {
return "", "", opEqual, false
}
return strings.TrimSpace(term[:at]), strings.TrimSpace(term[at+width:]), o, true
}
func meets[T any](conds []condition, fields Fields[T], row T) bool {
for _, c := range conds {
have := strings.ToLower(fields[c.field](row))
want := strings.ToLower(c.value)
switch c.op {
case opEqual:
if have != want {
return false
}
case opNotEqual:
if have == want {
return false
}
case opLike:
if !strings.Contains(have, want) {
return false
}
}
}
return true
}
// indexFold finds where ASCII needle appears in s, ignoring case. It compares
// windows of the original string so an offset stays a byte offset into s, which
// upper-casing would not guarantee for a field name outside ASCII.
func indexFold(s, needle string) int {
for i := 0; i+len(needle) <= len(s); i++ {
if strings.EqualFold(s[i:i+len(needle)], needle) {
return i
}
}
return -1
}
// fieldNames lists a list's filterable fields in a stable order, for the error
// a bad filter gets.
func fieldNames[T any](fields Fields[T]) []string {
names := make([]string, 0, len(fields))
for name := range fields {
names = append(names, name)
}
sort.Strings(names)
return names
}
+60
View File
@@ -0,0 +1,60 @@
package httpapi
import (
"strings"
"testing"
)
// TestFilter guards the sys_query grammar list pages depend on: conditions
// joined by ^ all apply, = and != compare the whole value, LIKE matches part of
// it, case is ignored, and a bad condition or an unknown field is refused with
// the fields the list offers rather than silently returning nothing.
func TestFilter(t *testing.T) {
type row struct{ name, state string }
rows := []row{{"reversibility", "running"}, {"precedent", "failed"}, {"freeze", "disabled"}}
fields := Fields[row]{
"name": func(r row) string { return r.name },
"state": func(r row) string { return r.state },
}
tests := []struct {
name string
query string
want []string
wantErr string
}{
{name: "no filter keeps every row", query: "", want: []string{"reversibility", "precedent", "freeze"}},
{name: "equals keeps the matching row", query: "state=failed", want: []string{"precedent"}},
{name: "equals ignores case", query: "state=FAILED", want: []string{"precedent"}},
{name: "not equals drops the matching row", query: "state!=running", want: []string{"precedent", "freeze"}},
{name: "LIKE matches part of the value", query: "nameLIKEeced", want: []string{"precedent"}},
{name: "LIKE ignores case", query: "nameLIKEECE", want: []string{"precedent"}},
{name: "conditions joined by ^ all apply", query: "nameLIKEe^state=disabled", want: []string{"freeze"}},
{name: "spaces around a condition are ignored", query: " state = disabled ", want: []string{"freeze"}},
{name: "a value may contain an equals sign", query: "name=precedent=x", want: nil},
{name: "unknown field is refused with the fields on offer", query: "stat=running", wantErr: `"stat" is not a field here; filter on name, state`},
{name: "a field name outside ASCII keeps its offset", query: "ıxLIKEa", wantErr: `"ıx" is not a field here`},
{name: "no operator is refused", query: "running", wantErr: `"running" has no operator`},
{name: "an empty condition is refused", query: "state=running^", wantErr: "an empty condition"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Filter(tt.query, fields, rows)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Filter(%q) error = %v, want %q", tt.query, err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("Filter(%q) error = %v", tt.query, err)
}
names := make([]string, 0, len(got))
for _, r := range got {
names = append(names, r.name)
}
if strings.Join(names, ",") != strings.Join(tt.want, ",") {
t.Fatalf("Filter(%q) = %v, want %v", tt.query, names, tt.want)
}
})
}
}
+23 -2
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"log/slog"
"net/http"
"strconv"
"time"
"github.com/danielgtaylor/huma/v2"
@@ -342,13 +343,33 @@ func (c *ActionTypes) Register(api huma.API, outcomes Outcomes) {
}, c.reset)
}
func (c *ActionTypes) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ActionTypeView], error) {
type listActionTypesInput struct {
SysQuery string `query:"sys_query" doc:"Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"`
}
// actionTypeFilterFields are what an action type list's filter may compare.
var actionTypeFilterFields = httpapi.Fields[ActionTypeView]{
"connector": func(v ActionTypeView) string { return v.Connector },
"action": func(v ActionTypeView) string { return v.Action },
"target_kind": func(v ActionTypeView) string { return v.TargetKind },
"environment": func(v ActionTypeView) string { return v.Environment },
"level": func(v ActionTypeView) string { return v.Level.String() },
"default": func(v ActionTypeView) string { return v.Default.String() },
"decisions": func(v ActionTypeView) string { return strconv.Itoa(v.Decisions) },
"count": func(v ActionTypeView) string { return strconv.Itoa(v.Count) },
}
func (c *ActionTypes) list(ctx context.Context, in *listActionTypesInput) (*httpapi.Reply[[]ActionTypeView], error) {
out, err := c.List(ctx)
if err != nil {
c.log.ErrorContext(ctx, "list action types", "error", err)
return nil, huma.Error500InternalServerError("couldn't list action types")
}
return httpapi.OK(out), nil
filtered, err := httpapi.Filter(in.SysQuery, actionTypeFilterFields, out)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
return httpapi.OK(filtered), nil
}
func (c *ActionTypes) detail(outcomes Outcomes) func(context.Context, *actionTypeInput) (*httpapi.Reply[ActionTypeDetail], error) {
@@ -4,6 +4,7 @@ import (
"context"
json "encoding/json/v2"
"net/http"
"strconv"
"time"
"github.com/danielgtaylor/huma/v2"
@@ -13,14 +14,14 @@ import (
"github.com/samcharles93/archie-core/modules/governance"
)
// judgeScanLimit bounds the decisions the control page reads to find a
// guardScanLimit bounds the decisions the control page reads to find a
// guard's last recorded standing.
const judgeScanLimit = 200
const guardScanLimit = 200
// JudgeControl is one guard as the Controls page shows it: built-in guards and
// GuardControl is one guard as the Controls page shows it: built-in guards and
// every guard extension installation (running, disabled, or failed), with its
// configuration and the last model judgement recorded for it.
type JudgeControl struct {
type GuardControl struct {
Name string `json:"name"`
InstallationID string `json:"installation_id,omitempty"`
Package string `json:"package,omitempty"`
@@ -52,16 +53,16 @@ type JudgeStanding struct {
At time.Time `json:"at"`
}
// Judges returns each built-in guard and every guard extension installation with
// Guards returns each built-in guard and every guard extension installation with
// its configuration and the last model judgement recorded for it.
func (m *Module) Judges(ctx context.Context) ([]JudgeControl, error) {
out := make([]JudgeControl, 0, len(m.guards))
func (m *Module) Guards(ctx context.Context) ([]GuardControl, error) {
out := make([]GuardControl, 0, len(m.guards))
for _, g := range m.guards {
latest, err := m.latestJudge(ctx, g.Name())
if err != nil {
return nil, err
}
out = append(out, JudgeControl{
out = append(out, GuardControl{
Name: g.Name(),
BuiltIn: true,
Advisory: g.Advisory(),
@@ -74,14 +75,14 @@ func (m *Module) Judges(ctx context.Context) ([]JudgeControl, error) {
if m.extensions == nil {
return out, nil
}
ext, err := m.extensionJudges(ctx)
ext, err := m.extensionGuards(ctx)
if err != nil {
return nil, err
}
return append(out, ext...), nil
}
func (m *Module) extensionJudges(ctx context.Context) ([]JudgeControl, error) {
func (m *Module) extensionGuards(ctx context.Context) ([]GuardControl, error) {
running := map[string]*connectors.Guard{}
for _, g := range m.extensions.Guards(ctx) {
running[g.Name()] = g
@@ -89,16 +90,16 @@ func (m *Module) extensionJudges(ctx context.Context) ([]JudgeControl, error) {
if lister, ok := m.extensions.(guardInstallationLister); ok {
views, err := lister.GuardInstallations(ctx)
if err == nil && views != nil {
return m.viewsToJudges(ctx, views, running)
return m.viewsToGuards(ctx, views, running)
}
}
out := make([]JudgeControl, 0, len(running))
out := make([]GuardControl, 0, len(running))
for _, g := range running {
latest, err := m.latestJudge(ctx, g.Name())
if err != nil {
return nil, err
}
out = append(out, JudgeControl{
out = append(out, GuardControl{
Name: g.Name(),
Version: g.Version(),
Digest: g.Digest(),
@@ -113,8 +114,8 @@ func (m *Module) extensionJudges(ctx context.Context) ([]JudgeControl, error) {
return out, nil
}
func (m *Module) viewsToJudges(ctx context.Context, views []connectors.ExtensionView, running map[string]*connectors.Guard) ([]JudgeControl, error) {
out := make([]JudgeControl, 0, len(views))
func (m *Module) viewsToGuards(ctx context.Context, views []connectors.ExtensionView, running map[string]*connectors.Guard) ([]GuardControl, error) {
out := make([]GuardControl, 0, len(views))
for _, v := range views {
advisory := false
if g := running[v.Name]; g != nil {
@@ -124,7 +125,7 @@ func (m *Module) viewsToJudges(ctx context.Context, views []connectors.Extension
if err != nil {
return nil, err
}
out = append(out, JudgeControl{
out = append(out, GuardControl{
Name: v.Name,
InstallationID: v.ID.String(),
Package: v.Package,
@@ -145,7 +146,7 @@ func (m *Module) viewsToJudges(ctx context.Context, views []connectors.Extension
// latestJudge finds the newest verdict a guard recorded with a model judge.
func (m *Module) latestJudge(ctx context.Context, guard string) (*JudgeStanding, error) {
recent, err := m.queries.RecentBodies(ctx, m.orgID, judgeScanLimit)
recent, err := m.queries.RecentBodies(ctx, m.orgID, guardScanLimit)
if err != nil {
return nil, err
}
@@ -168,19 +169,38 @@ func (m *Module) latestJudge(ctx context.Context, guard string) (*JudgeStanding,
return nil, nil
}
// Register adds the judgement controls API.
// Register adds the guards API.
func (m *Module) Register(api huma.API) {
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindGuard), huma.Operation{
OperationID: "list-judges", Method: http.MethodGet, Path: "/api/controls/judges",
Summary: "List each guard's judge, its standing and its eval date", Tags: []string{"Controls"},
}, m.listJudges)
OperationID: "list-guard-controls", Method: http.MethodGet, Path: "/api/controls/guards",
Summary: "List each guard with its last recorded judgement", Tags: []string{"Controls"},
}, m.listGuards)
}
func (m *Module) listJudges(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]JudgeControl], error) {
out, err := m.Judges(ctx)
type listGuardsInput struct {
SysQuery string `query:"sys_query" doc:"Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"`
}
// guardFilterFields are what a guard list's filter may compare.
var guardFilterFields = httpapi.Fields[GuardControl]{
"name": func(v GuardControl) string { return v.Name },
"package": func(v GuardControl) string { return v.Package },
"scope": func(v GuardControl) string { return v.Scope },
"version": func(v GuardControl) string { return v.Version },
"advisory": func(v GuardControl) string { return strconv.FormatBool(v.Advisory) },
"enabled": func(v GuardControl) string { return strconv.FormatBool(v.Enabled) },
"state": func(v GuardControl) string { return v.State },
}
func (m *Module) listGuards(ctx context.Context, in *listGuardsInput) (*httpapi.Reply[[]GuardControl], error) {
out, err := m.Guards(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list judges", "error", err)
return nil, huma.Error500InternalServerError("couldn't read the judges")
m.log.ErrorContext(ctx, "list guards", "error", err)
return nil, huma.Error500InternalServerError("couldn't read the guards")
}
return httpapi.OK(out), nil
filtered, err := httpapi.Filter(in.SysQuery, guardFilterFields, out)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
return httpapi.OK(filtered), nil
}
+20 -2
View File
@@ -219,7 +219,21 @@ type idInput struct {
}
type listInput struct {
State string `query:"state" enum:"pending,approved,rejected,published,superseded,withdrawn" doc:"Only proposals in this state"`
State string `query:"state" enum:"pending,approved,rejected,published,superseded,withdrawn" doc:"Only proposals in this state"`
SysQuery string `query:"sys_query" doc:"Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"`
}
// proposalFilterFields are what a proposal list's filter may compare. The
// store applies a state from its own parameter, so a state condition here
// narrows that answer rather than replacing it.
var proposalFilterFields = httpapi.Fields[View]{
"id": func(v View) string { return v.ID.String() },
"kind": func(v View) string { return v.Kind },
"state": func(v View) string { return v.State },
"needs": func(v View) string { return v.Needs },
"title": func(v View) string { return v.Title },
"target_kind": func(v View) string { return v.TargetKind },
"target_id": func(v View) string { return v.TargetID },
}
func (m *Module) list(ctx context.Context, in *listInput) (*httpapi.Reply[[]View], error) {
@@ -239,7 +253,11 @@ func (m *Module) list(ctx context.Context, in *listInput) (*httpapi.Reply[[]View
}
out = append(out, v)
}
return httpapi.OK(out), nil
filtered, err := httpapi.Filter(in.SysQuery, proposalFilterFields, out)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
return httpapi.OK(filtered), nil
}
type proposeInput struct {
+15 -1
View File
@@ -236,6 +236,16 @@ func (a *runAPI) cancel(ctx context.Context, in *cancelRunInput) (*httpapi.Reply
type recentRunsInput struct {
Limit int `query:"limit" minimum:"1" maximum:"200" default:"50"`
WorkflowID string `query:"workflow_id" format:"uuid" doc:"Only this workflow's runs"`
SysQuery string `query:"sys_query" doc:"Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"`
}
// runFilterFields are what a run list's filter may compare. The filter applies
// to the runs the limit returns.
var runFilterFields = httpapi.Fields[RunView]{
"id": func(v RunView) string { return v.ID.String() },
"workflow": func(v RunView) string { return v.Workflow },
"state": func(v RunView) string { return v.State },
"error": func(v RunView) string { return v.Error },
}
type runInput struct {
@@ -268,7 +278,11 @@ func (a *runAPI) recent(ctx context.Context, in *recentRunsInput) (*httpapi.Repl
for _, s := range runs {
views = append(views, view(s, nil))
}
return httpapi.OK(views), nil
filtered, err := httpapi.Filter(in.SysQuery, runFilterFields, views)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
return httpapi.OK(filtered), nil
}
func (a *runAPI) trail(ctx context.Context, in *runInput) (*httpapi.Reply[Trail], error) {
+20 -2
View File
@@ -6,6 +6,7 @@ import (
json "encoding/json/v2"
"errors"
"net/http"
"strconv"
"time"
"github.com/danielgtaylor/huma/v2"
@@ -172,7 +173,20 @@ func (a *workflowAPI) fail(ctx context.Context, what string, err error) error {
return huma.Error500InternalServerError("couldn't " + what)
}
func (a *workflowAPI) list(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[]WorkflowView], error) {
type listWorkflowsInput struct {
SysQuery string `query:"sys_query" doc:"Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"`
}
// workflowFilterFields are what a workflow list's filter may compare.
var workflowFilterFields = httpapi.Fields[WorkflowView]{
"id": func(v WorkflowView) string { return v.ID.String() },
"name": func(v WorkflowView) string { return v.Name },
"created_by": func(v WorkflowView) string { return v.CreatedBy },
"enabled": func(v WorkflowView) string { return strconv.FormatBool(v.Enabled) },
"version": func(v WorkflowView) string { return strconv.Itoa(v.Version) },
}
func (a *workflowAPI) list(ctx context.Context, in *listWorkflowsInput) (*httpapi.Reply[[]WorkflowView], error) {
stored, err := a.e.db.Workflows(ctx, a.orgID)
if err != nil {
return nil, a.fail(ctx, "list the workflows", err)
@@ -181,7 +195,11 @@ func (a *workflowAPI) list(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[
for _, w := range stored {
out = append(out, workflowView(w))
}
return httpapi.OK(out), nil
filtered, err := httpapi.Filter(in.SysQuery, workflowFilterFields, out)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
return httpapi.OK(filtered), nil
}
// idInput is a workflow's id in the path.
+11 -1
View File
@@ -27,7 +27,7 @@
{
"path": "/controls/guards",
"label": "Guards",
"description": "Judges that inspect actions before they run."
"description": "Guards that inspect actions before they run."
},
{
"path": "/events",
@@ -219,6 +219,16 @@
"label": "Extensions",
"description": "Installed extensions, grants and the marketplace."
},
{
"path": "/settings/extensions/marketplace",
"label": "Extension marketplace",
"description": "Available extensions from the configured catalogue."
},
{
"path": "/settings/extensions/packages",
"label": "Extension packages",
"description": "Accepted extension packages by kind."
},
{
"path": "/settings/memory",
"label": "Shared memory",
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
import { Search, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { useSysQuery } from "@/lib/sys-query";
const props = defineProps<{
/** The control's accessible name, like "Filter guards". */
label: string;
/** What the list accepts, comma separated, for the title. */
fields: string;
/** A condition in the list's own vocabulary, shown until something is typed. */
example: string;
}>();
const { query, draft, commit, clear } = useSysQuery();
</script>
<template>
<form class="w-56 max-sm:w-full" @submit.prevent="commit">
<InputGroup>
<InputGroupAddon><Search /></InputGroupAddon>
<InputGroupInput
v-model="draft"
:aria-label="label"
:placeholder="example"
:title="`Filter on ${fields}`"
/>
<InputGroupAddon v-if="query" align="inline-end">
<Button type="button" variant="ghost" size="icon-xs" aria-label="Clear filter" title="Clear filter" @click="clear"><X /></Button>
</InputGroupAddon>
</InputGroup>
</form>
</template>
+8 -6
View File
@@ -185,14 +185,16 @@ async function request<T = unknown>(
export const api = {
// The archie binary's module API; the wire types are below the object.
runs: (limit = 200, workflowId?: string) => request<Run[]>("/api/runs" + qs({ limit, workflow_id: workflowId })),
runs: (limit = 200, workflowId?: string, sysQuery?: string) =>
request<Run[]>("/api/runs" + qs({ limit, workflow_id: workflowId, sys_query: sysQuery })),
run: (id: string) => request<RunTrail>(`/api/runs/${encodeURIComponent(id)}`),
/** Queues a parked run again from the step that parked it, or from `from`. */
retryRun: (id: string, from?: string) =>
request<Run>(`/api/runs/${encodeURIComponent(id)}/retry`, { method: "POST", body: from ? { from } : {} }),
/** Asks a run that has not ended to stop, along with the runs it called. */
cancelRun: (id: string) => request<Run>(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }),
proposals: (state?: ProposalState) => request<Proposal[]>("/api/proposals" + qs({ state })),
proposals: (state?: ProposalState, sysQuery?: string) =>
request<Proposal[]>("/api/proposals" + qs({ state, sys_query: sysQuery })),
proposal: (id: string) => request<Proposal>(`/api/proposals/${encodeURIComponent(id)}`),
/** Approves a proposal and the actions it lists; the server applies it. */
approveProposal: (id: string, assertion?: ApprovalAssertion) =>
@@ -246,7 +248,7 @@ export const api = {
createTrigger: (trigger: TriggerInput) => request<Trigger>("/api/triggers", { method: "POST", body: trigger }),
putTrigger: (id: string, trigger: TriggerInput) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(id)}`, { method: "PUT", body: trigger }),
workflowList: () => request<WorkflowVersion[]>("/api/workflows"),
workflowList: (sysQuery?: string) => request<WorkflowVersion[]>("/api/workflows" + qs({ sys_query: sysQuery })),
/** Creates a workflow, publishing body as its first version when given. */
createWorkflow: (name: string, body?: string) =>
request<WorkflowIdentity>("/api/workflows", { method: "POST", body: body === undefined ? { name } : { name, body } }),
@@ -347,8 +349,8 @@ export const api = {
request<PolicyText>(`/api/policies/${kind}` + qs({ version })),
putPolicyText: (kind: PolicyKind, body: string) =>
request<PolicyText>(`/api/policies/${kind}`, { method: "PUT", body: { body } }),
judges: () => request<Judge[]>("/api/controls/judges"),
actionTypes: () => request<ActionType[]>("/api/action-types"),
guards: (sysQuery?: string) => request<Guard[]>("/api/controls/guards" + qs({ sys_query: sysQuery })),
actionTypes: (sysQuery?: string) => request<ActionType[]>("/api/action-types" + qs({ sys_query: sysQuery })),
actionType: (id: string) => request<ActionTypeDetail>(`/api/action-types/${encodeURIComponent(id)}`),
resetActionType: (id: string) =>
request<ActionType>(`/api/action-types/${encodeURIComponent(id)}/reset`, { method: "POST" }),
@@ -1534,7 +1536,7 @@ export interface PolicyText {
versions?: { version: number; created_at: string; created_by?: string }[];
}
export interface Judge {
export interface Guard {
name: string;
installation_id?: string;
package?: string;
+72
View File
@@ -0,0 +1,72 @@
import { computed, onMounted, ref, watch, type ComputedRef, type Ref } from "vue";
import { useRoute, useRouter, type LocationQuery, type LocationQueryValue } from "vue-router";
import { useRead, type Read } from "./use-read.ts";
/** The filter parameter lists carry: conditions joined by ^, each field=value,
* field!=value or fieldLIKEtext, compared ignoring case by the server. */
const SYS_QUERY = "sys_query";
/** sysQueryOf reads the filter out of a route query, which is an array when the
* name repeats, and drops the surrounding space an operator's paste brings. */
function sysQueryOf(value: LocationQueryValue | LocationQueryValue[] | undefined): string {
const first = (Array.isArray(value) ? value.find((item) => item) : value) ?? "";
return typeof first === "string" ? first.trim() : "";
}
/** queryWithSysQuery puts `sysQuery` into `query` beside every other parameter,
* and removes the parameter when the filter is empty so the URL says what it
* filters by. */
function queryWithSysQuery(query: LocationQuery, sysQuery: string): LocationQuery {
const next: LocationQuery = { ...query };
delete next[SYS_QUERY];
const trimmed = sysQuery.trim();
if (trimmed) next[SYS_QUERY] = trimmed;
return next;
}
export interface SysQuery {
/** What the URL carries, so back, forward and a deep link all move it. */
query: ComputedRef<string>;
/** The text a field shows until it is committed; Enter commits it. */
draft: Ref<string>;
commit: () => void;
clear: () => void;
}
/** useSysQuery keeps one list's filter in the URL. Each control owns an
* instance: the URL is the state, so they cannot disagree. */
export function useSysQuery(): SysQuery {
const route = useRoute();
const router = useRouter();
const query = computed(() => sysQueryOf(route.query[SYS_QUERY]));
const draft = ref(query.value);
watch(query, (value) => {
draft.value = value;
});
function replace(sysQuery: string): void {
void router.replace({ query: queryWithSysQuery(route.query, sysQuery) });
}
return {
query,
draft,
commit: () => replace(draft.value),
clear: () => {
draft.value = "";
replace("");
},
};
}
/** useFilteredList reads a list through the URL's filter and re-reads when it
* changes. `query` tells a page with no rows apart from one whose filter
* matched none. */
export function useFilteredList<T>(read: (sysQuery: string) => Promise<T>): Read<T> & { query: ComputedRef<string>; clear: () => void } {
const { query, clear } = useSysQuery();
// useRead drops a response that settles after a newer read started, so a
// slow unfiltered answer cannot land over a filtered one.
const list = useRead(() => read(query.value));
watch(query, () => void list.reload());
onMounted(() => void list.reload());
return { ...list, query, clear };
}
+19 -10
View File
@@ -1,17 +1,19 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ref } from "vue";
import ListFilter from "@/base/ListFilter.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { MoreMenu } from "@/components/ui/more-menu";
import { ReadError } from "@/components/ui/read-error";
import { Skeleton } from "@/components/ui/skeleton";
import { Timestamp } from "@/components/ui/timestamp";
import { errors } from "@/copy/errors";
import { api, describeError, type ActionType } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { useFilteredList } from "@/lib/sys-query";
import { stateLabel } from "@/runs/state";
definePage({
@@ -24,8 +26,7 @@ definePage({
},
});
const actionTypes = useRead(() => api.actionTypes());
onMounted(() => void actionTypes.reload());
const { data, error, reload, query, clear } = useFilteredList((sysQuery) => api.actionTypes(sysQuery));
const actionTypePath = (c: ActionType) => `/controls/action-types/${encodeURIComponent(c.id)}`;
@@ -46,19 +47,22 @@ async function reset(c: ActionType): Promise<void> {
} catch (cause) {
resetError.value = describeError(cause, errors.common.unknown);
}
await actionTypes.reload();
await reload();
}
</script>
<template>
<div>
<div class="mb-3 flex justify-end">
<ListFilter label="Filter action types" fields="connector, action, target_kind, environment, level, default, decisions, count" example="connector=mistral" />
</div>
<p v-if="resetError" role="alert" class="mb-2 text-caption text-danger">{{ resetError }}</p>
<ReadError v-if="actionTypes.error.value" :message="actionTypes.error.value" retry-label="Retry" @retry="actionTypes.reload" />
<Skeleton v-else-if="!actionTypes.data.value" class="h-16 w-full" />
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<Skeleton v-else-if="!data" class="h-16 w-full" />
<DataTable
v-else
:columns="actionTypeColumns"
:rows="actionTypes.data.value"
:rows="data"
:row-key="(c) => c.id"
:row-link="actionTypePath"
:row-label="(c) => `${c.connector}.${c.action}`"
@@ -82,7 +86,12 @@ async function reset(c: ActionType): Promise<void> {
</MoreMenu>
</div>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No action types</EmptyTitle></EmptyHeader></Empty></template>
<template #empty>
<Empty>
<EmptyHeader><EmptyTitle>{{ query ? "No action type matches the filter" : "No action types" }}</EmptyTitle></EmptyHeader>
<EmptyContent v-if="query"><Button variant="outline" size="sm" @click="clear">Clear filter</Button></EmptyContent>
</Empty>
</template>
</DataTable>
</div>
</template>
+1 -1
View File
@@ -28,7 +28,7 @@ definePage({
const route = useRoute("controls-guard");
const id = computed(() => String(route.params.id));
const { data, error, reload } = useRead(() => api.judges());
const { data, error, reload } = useRead(() => api.guards());
onMounted(() => void reload());
const guard = computed(() => {
+24 -17
View File
@@ -1,34 +1,33 @@
<script setup lang="ts">
import { onMounted } from "vue";
import { RouterLink } from "vue-router";
import ListFilter from "@/base/ListFilter.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { ReadError } from "@/components/ui/read-error";
import { Skeleton } from "@/components/ui/skeleton";
import { Timestamp } from "@/components/ui/timestamp";
import { api, type Judge } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { api, type Guard } from "@/lib/api";
import { useFilteredList } from "@/lib/sys-query";
definePage({
name: "controls-guards",
meta: {
label: "Guards",
description: "Judges that inspect actions before they run.",
description: "Guards that inspect actions before they run.",
navPath: "/controls/guards",
section: "controls",
},
});
const judges = useRead(() => api.judges());
onMounted(() => void judges.reload());
const { data, error, reload, query, clear } = useFilteredList((sysQuery) => api.guards(sysQuery));
const judgeKey = (j: Judge) => j.installation_id || j.name;
const guardPath = (j: Judge) => `/controls/guards/${encodeURIComponent(judgeKey(j))}`;
const guardKey = (g: Guard) => g.installation_id || g.name;
const guardPath = (g: Guard) => `/controls/guards/${encodeURIComponent(guardKey(g))}`;
const judgeColumns: DataTableColumn<Judge>[] = [
const guardColumns: DataTableColumn<Guard>[] = [
{ id: "name", label: "Guard", fixed: true, width: "auto", sort: (j) => j.name },
{ id: "mode", label: "Mode", fixed: true, width: "8rem" },
{ id: "status", label: "Status", hide: "sm", width: "8rem" },
@@ -38,16 +37,19 @@ const judgeColumns: DataTableColumn<Judge>[] = [
<template>
<div>
<ReadError v-if="judges.error.value" :message="judges.error.value" retry-label="Retry" @retry="judges.reload" />
<Skeleton v-else-if="!judges.data.value" class="h-16 w-full" />
<div class="mb-3 flex justify-end">
<ListFilter label="Filter guards" fields="name, package, scope, version, advisory, enabled, state" example="state=running" />
</div>
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<Skeleton v-else-if="!data" class="h-16 w-full" />
<DataTable
v-else
:columns="judgeColumns"
:rows="judges.data.value"
:row-key="judgeKey"
:columns="guardColumns"
:rows="data"
:row-key="guardKey"
:row-link="guardPath"
:row-label="(j) => j.name"
storage-key="judges"
storage-key="guards"
>
<template #cell-name="{ row }">
<span class="font-medium">{{ row.name }}</span>
@@ -80,7 +82,12 @@ const judgeColumns: DataTableColumn<Judge>[] = [
@click.stop
><RouterLink :to="{ path: '/settings/extensions', query: { tab: 'installations', configure: row.installation_id } }">Configure</RouterLink></Button>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No guards</EmptyTitle></EmptyHeader></Empty></template>
<template #empty>
<Empty>
<EmptyHeader><EmptyTitle>{{ query ? "No guard matches the filter" : "No guards" }}</EmptyTitle></EmptyHeader>
<EmptyContent v-if="query"><Button variant="outline" size="sm" @click="clear">Clear filter</Button></EmptyContent>
</Empty>
</template>
</DataTable>
<div class="mt-3 flex flex-wrap gap-4 text-caption text-fg-muted">
<RouterLink class="underline" :to="{ path: '/settings/extensions', query: { tab: 'packages', kind: 'guards' } }">Manage guards</RouterLink>
+13 -6
View File
@@ -8,24 +8,27 @@ definePage({
},
});
import { onMounted, ref, watch } from "vue";
import { ref, watch } from "vue";
import ListFilter from "@/base/ListFilter.vue";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { ReadError } from "@/components/ui/read-error";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Timestamp } from "@/components/ui/timestamp";
import { api, type Proposal, type ProposalState } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { useFilteredList } from "@/lib/sys-query";
import { usePoll } from "@/lib/use-read";
import { useLiveResource } from "@/stores/session";
import { kindLabel, proposalTone, STATES } from "@/proposals/state";
// The tab picks the state in SQL; the filter narrows what comes back.
const state = ref<ProposalState>("pending");
const { data, error, loading, reload } = useRead(() => api.proposals(state.value));
onMounted(reload);
const { data, error, loading, reload, query, clear } = useFilteredList((sysQuery) => api.proposals(state.value, sysQuery));
watch(state, () => {
data.value = undefined;
error.value = "";
@@ -55,10 +58,14 @@ const columns: DataTableColumn<Proposal>[] = [
<TabsTrigger v-for="s in STATES" :key="s.value" :value="s.value">{{ s.label }}</TabsTrigger>
</TabsList>
</Tabs>
<ListFilter label="Filter proposals" fields="id, kind, state, needs, title, target_kind, target_id" example="titleLIKEdeploy" />
</PageHeader>
<ReadError v-if="error" :class="data && 'mb-2'" :message="error" retry-label="Retry" @retry="reload" />
<div v-if="!data && !error" role="status" aria-label="Loading proposals" class="space-y-2"><Skeleton class="h-10 w-full" /><Skeleton class="h-10 w-full" /></div>
<Empty v-else-if="data && !data.length"><EmptyHeader><EmptyTitle>No proposals</EmptyTitle></EmptyHeader></Empty>
<Empty v-else-if="data && !data.length">
<EmptyHeader><EmptyTitle>{{ query ? "No proposal matches the filter" : "No proposals" }}</EmptyTitle></EmptyHeader>
<EmptyContent v-if="query"><Button size="sm" variant="outline" @click="clear">Clear filter</Button></EmptyContent>
</Empty>
<DataTable
v-else-if="data"
:columns="columns"
+13 -31
View File
@@ -8,54 +8,36 @@ definePage({
},
});
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { Search } from "@lucide/vue";
import ListFilter from "@/base/ListFilter.vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { ReadError } from "@/components/ui/read-error";
import { Spinner } from "@/components/ui/spinner";
import { api } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
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 route = useRoute();
const { data, error, reload } = useRead(() => api.runs());
onMounted(reload);
const { data, error, reload, query, clear } = useFilteredList((sysQuery) => api.runs(200, undefined, sysQuery));
useLiveResource(null, () => void reload());
usePoll(reload);
// A workflow links here with ?workflow=, which starts the filter on its name.
const query = ref(String(route.query.workflow ?? ""));
// A filter earns its place once the list outgrows a glance.
const FILTER_FROM = 8;
const filterable = computed(() => (data.value?.length ?? 0) > FILTER_FROM || !!query.value);
const shown = computed(() => {
const needle = query.value.trim().toLowerCase();
return (data.value ?? []).filter((r) => !needle || r.workflow.toLowerCase().includes(needle) || r.state.includes(needle));
});
</script>
<template>
<div>
<PageHeader title="Runs">
<InputGroup v-if="filterable" class="w-56 max-sm:w-full">
<InputGroupAddon><Search /></InputGroupAddon>
<InputGroupInput v-model="query" type="search" aria-label="Filter runs" placeholder="Filter" />
</InputGroup>
<ListFilter label="Filter runs" fields="id, workflow, state, error" example="state=running" />
</PageHeader>
<ApprovalsSection @answered="reload" />
<div v-if="error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error }}</p>
<Button variant="outline" size="sm" @click="reload">Retry</Button>
</div>
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<p v-else-if="!data" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading runs…</p>
<Empty v-else-if="!data.length"><EmptyHeader><EmptyTitle>No runs</EmptyTitle></EmptyHeader></Empty>
<p v-else-if="!shown.length" class="text-label text-fg-muted">No run matches.</p>
<RunTable v-else :rows="shown" storage-key="runs" with-workflow />
<Empty v-else-if="!data.length">
<EmptyHeader><EmptyTitle>{{ query ? "No run matches the filter" : "No runs" }}</EmptyTitle></EmptyHeader>
<EmptyContent v-if="query"><Button size="sm" variant="outline" @click="clear">Clear filter</Button></EmptyContent>
</Empty>
<RunTable v-else :rows="data" storage-key="runs" with-workflow />
</div>
</template>
+20 -29
View File
@@ -17,28 +17,30 @@ definePage({
});
import UserReference from "@/org/UserReference.vue";
import { computed, ref } from "vue";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useMediaQuery } from "@vueuse/core";
import { Copy, ListChecks, Plus, Search, Trash2 } from "@lucide/vue";
import { Copy, ListChecks, Plus, Trash2 } from "@lucide/vue";
import { toast } from "vue-sonner";
import ListFilter from "@/base/ListFilter.vue";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { ReadError } from "@/components/ui/read-error";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Timestamp } from "@/components/ui/timestamp";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { useSysQuery } from "@/lib/sys-query";
import { stateTone } from "@/runs/state";
import { useWorkflowList, type WorkflowRow } from "@/workflows/use-workflow-list";
import WorkflowDelivery from "@/workflows/WorkflowDelivery.vue";
@@ -46,19 +48,12 @@ import WorkflowLastRun from "@/workflows/WorkflowLastRun.vue";
import WorkflowRowActions from "@/workflows/WorkflowRowActions.vue";
const router = useRouter();
const { rows, error, partial, loading, reload, triggersKnown, runsKnown } = useWorkflowList();
const { query, clear } = useSysQuery();
const { rows, error, partial, loading, reload, triggersKnown, runsKnown } = useWorkflowList(query);
const wide = useMediaQuery("(min-width: 1024px)");
// A filter earns its place once the list outgrows a glance.
const FILTER_FROM = 8;
const query = ref("");
const shown = computed(() => {
const needle = query.value.trim().toLowerCase();
return needle ? rows.value.filter((row) => row.name.toLowerCase().includes(needle) || row.starts.some((s) => s.toLowerCase().includes(needle))) : rows.value;
});
const open = (id: string) => void router.push({ path: `/workflows/${id}` });
const openRuns = (name: string) => void router.push({ path: "/runs", query: { workflow: name } });
const openRuns = (name: string) => void router.push({ path: "/runs", query: { sys_query: `workflowLIKE${name}` } });
const startsText = (row: WorkflowRow) => row.starts[0] ?? "";
const startsMore = (row: WorkflowRow) => row.starts.slice(1);
const lastTo = (row: WorkflowRow) => (row.last ? `/runs/${row.last.id}` : undefined);
@@ -124,29 +119,25 @@ async function create(): Promise<void> {
<template>
<div>
<PageHeader title="Workflows">
<InputGroup v-if="rows.length > FILTER_FROM" class="w-56 max-sm:w-full">
<InputGroupAddon><Search /></InputGroupAddon>
<InputGroupInput v-model="query" type="search" aria-label="Filter workflows" placeholder="Filter" />
</InputGroup>
<ListFilter label="Filter workflows" fields="id, name, created_by, enabled, version" example="nameLIKEdeploy" />
<Button size="icon-sm" variant="ghost" aria-label="New workflow" title="New workflow" @click="creating = true"><Plus /></Button>
</PageHeader>
<div v-if="error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error }}</p>
<Button variant="outline" size="sm" @click="reload">Retry</Button>
</div>
<ReadError v-if="error" class="mb-4" :message="error" retry-label="Retry" @retry="reload" />
<p v-if="partial" class="mb-2 text-caption text-danger" role="alert">{{ partial }}</p>
<p v-if="loading" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading workflows…</p>
<Empty v-else-if="!rows.length && !error">
<EmptyHeader>
<EmptyTitle>No workflows</EmptyTitle>
<EmptyTitle>{{ query ? "No workflow matches the filter" : "No workflows" }}</EmptyTitle>
</EmptyHeader>
<Button size="sm" variant="outline" @click="creating = true"><Plus data-icon="inline-start" />New workflow</Button>
<EmptyContent>
<Button v-if="query" size="sm" variant="outline" @click="clear">Clear filter</Button>
<Button v-else size="sm" variant="outline" @click="creating = true"><Plus data-icon="inline-start" />New workflow</Button>
</EmptyContent>
</Empty>
<p v-else-if="rows.length && !shown.length" class="text-label text-fg-muted">No workflow matches.</p>
<Table v-else-if="wide && shown.length" class="table-fixed" aria-label="Workflows">
<Table v-else-if="wide && rows.length" class="table-fixed" aria-label="Workflows">
<TableHeader>
<TableRow>
<TableHead class="w-[22%]">Workflow</TableHead>
@@ -160,7 +151,7 @@ async function create(): Promise<void> {
</TableRow>
</TableHeader>
<TableBody>
<ContextMenu v-for="row in shown" :key="row.id">
<ContextMenu v-for="row in rows" :key="row.id">
<ContextMenuTrigger as-child>
<TableRow class="cursor-pointer align-middle" @click="open(row.id)">
<TableCell class="whitespace-normal">
@@ -200,8 +191,8 @@ async function create(): Promise<void> {
</TableBody>
</Table>
<ul v-else-if="shown.length" class="flex flex-col gap-2" aria-label="Workflows">
<li v-for="row in shown" :key="row.id">
<ul v-else-if="rows.length" class="flex flex-col gap-2" aria-label="Workflows">
<li v-for="row in rows" :key="row.id">
<ContextMenu>
<ContextMenuTrigger as-child>
<Card class="cursor-pointer gap-2.5 px-4 py-3 transition-colors hover:bg-secondary/60" @click="open(row.id)">
+10 -5
View File
@@ -1,4 +1,4 @@
import { computed, onMounted } from "vue";
import { computed, onMounted, watch, type Ref } from "vue";
import { api, type Trigger } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
@@ -45,9 +45,12 @@ export function byActivity(a: WorkflowRow, b: WorkflowRow): number {
}
/** The workflows, published or only drafted, with what starts each and how its
* runs went. The counts come from the server, which counts every run. */
export function useWorkflowList() {
const workflows = useRead(() => api.workflowList());
* runs went. The counts come from the server, which counts every run. The
* server filters the published list, so a filter narrows that. */
export function useWorkflowList(sysQuery: Ref<string> | string = "") {
const filter = computed(() => (typeof sysQuery === "string" ? sysQuery : sysQuery.value));
const workflows = useRead(() => api.workflowList(filter.value));
watch(filter, () => void workflows.reload());
const drafts = useRead(() => api.workflowDrafts());
const triggers = useRead(() => api.triggers());
const stats = useRead(() => api.workflowStats());
@@ -82,8 +85,10 @@ export function useWorkflowList() {
row(w.id, w.name, { version: w.version, body: w.body, steps: w.steps?.length ?? 0, published: w.created_at, by: w.created_by, enabled: w.enabled }),
);
const known = new Set(published.map((r) => r.id));
// The server filters published workflows only, so a draft with no version
// is left out of a filtered list rather than shown unfiltered.
const drafted = (drafts.data.value ?? [])
.filter((d) => !known.has(d.workflow_id))
.filter((d) => !known.has(d.workflow_id) && !filter.value)
.map((d) => row(d.workflow_id, d.name, { body: d.body, published: d.updated_at, by: d.updated_by }));
return [...published, ...drafted].sort(byActivity);
});