feat(cli): per-resource filter flags on list commands

Adds the filter flags users were reaching for via `--jq` post-filter:

- `kb list --pinned` — client-side filter to KBs with `IsPinned`.
- `doc list --status <pending|processing|completed|failed>` —
  server-side query-param filter; `failed` surfaces ingestion errors
  immediately for triage.
- `session list --since <duration>` — client-side filter to sessions
  updated within the past duration. Accepts time.ParseDuration forms
  (24h, 1h30m, 30m) plus a `<N>d` suffix for whole days (7d, 0.5d).

Server-side filters are forwarded as query params (where the API
supports them) to avoid pulling the full list into memory; client-side
filters apply after the fetch so they compose with `--limit`.
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent 1b20b06f5e
commit 3b67986863
7 changed files with 246 additions and 17 deletions
+27 -3
View File
@@ -3,7 +3,9 @@ package doc
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"text/tabwriter"
"time"
@@ -31,12 +33,19 @@ var docListFields = []string{
type ListOptions struct {
Page int
PageSize int
Status string // --status: filter by parse_status (server-side query param)
}
// docListStatusValues mirrors internal/types/knowledge.go ParseStatus*
// constants — these are the values the server accepts on the
// ?parse_status= query. Kept in sync manually since the SDK doesn't
// re-export the enum.
var docListStatusValues = []string{"pending", "processing", "completed", "failed"}
// ListService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it.
type ListService interface {
ListKnowledge(ctx context.Context, kbID string, page, pageSize int, tagID string) ([]sdk.Knowledge, int64, error)
ListKnowledgeWithFilter(ctx context.Context, kbID string, page, pageSize int, filter sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error)
}
// listResult is the typed payload emitted under data on success.
@@ -91,8 +100,9 @@ backend storage order is not guaranteed and varies between deployments.`,
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page (1..1000)")
cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
cmdutil.AddJSONFlags(cmd, docListFields)
agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb when not running inside a project.")
agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb when not running inside a project. --status (server-side filter) restricts to a parse-pipeline state — `failed` is the practical one for surfacing ingestion errors.")
return cmd
}
@@ -109,7 +119,15 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
Message: fmt.Sprintf("--page-size must be in 1..1000, got %d", opts.PageSize),
}
}
items, total, err := svc.ListKnowledge(ctx, kbID, opts.Page, opts.PageSize, "")
if opts.Status != "" && !validDocListStatus(opts.Status) {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--status must be one of: %s — got %q",
strings.Join(docListStatusValues, " | "), opts.Status),
}
}
items, total, err := svc.ListKnowledgeWithFilter(ctx, kbID, opts.Page, opts.PageSize,
sdk.KnowledgeListFilter{ParseStatus: opts.Status})
if err != nil {
return cmdutil.WrapHTTP(err, "list documents")
}
@@ -150,6 +168,12 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
return tw.Flush()
}
// validDocListStatus reports whether s matches one of the server-accepted
// parse_status enum values surfaced via --status.
func validDocListStatus(s string) bool {
return slices.Contains(docListStatusValues, s)
}
// formatSize renders a byte count as a short human string (KB / MB).
// Kept tiny on purpose — go-humanize would pull a transitive dep just for one
// column. A "-" placeholder hides zero-size entries (URL / text).
+39 -4
View File
@@ -26,12 +26,12 @@ type fakeListSvc struct {
kbID string
page int
pageSize int
tagID string
filter sdk.KnowledgeListFilter
}
}
func (f *fakeListSvc) ListKnowledge(_ context.Context, kbID string, page, pageSize int, tagID string) ([]sdk.Knowledge, int64, error) {
f.got.kbID, f.got.page, f.got.pageSize, f.got.tagID = kbID, page, pageSize, tagID
func (f *fakeListSvc) ListKnowledgeWithFilter(_ context.Context, kbID string, page, pageSize int, filter sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error) {
f.got.kbID, f.got.page, f.got.pageSize, f.got.filter = kbID, page, pageSize, filter
return f.items, f.total, f.err
}
@@ -61,7 +61,7 @@ func TestList_Success_Human(t *testing.T) {
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, 1, svc.got.page)
assert.Equal(t, 20, svc.got.pageSize)
assert.Equal(t, "", svc.got.tagID, "doc list does not filter by tag")
assert.Equal(t, sdk.KnowledgeListFilter{}, svc.got.filter, "no flags ⇒ empty filter")
got := out.String()
for _, want := range []string{"ID", "NAME", "STATUS", "SIZE", "UPDATED", "doc1", "alpha.pdf", "completed", "2.0KB", "doc2", "beta.md", "pending"} {
@@ -217,3 +217,38 @@ func TestFormatSize(t *testing.T) {
}
}
func TestList_StatusFilter_ForwardedToSDK(t *testing.T) {
chdirIsolated(t)
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{Page: 1, PageSize: 20, Status: "failed"}
require.NoError(t, runList(context.Background(), opts, nil, svc, "kb_xxx"))
assert.Equal(t, "failed", svc.got.filter.ParseStatus,
"--status must be forwarded as filter.ParseStatus for server-side filtering")
}
func TestList_StatusFilter_RejectsUnknownValue(t *testing.T) {
chdirIsolated(t)
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{Page: 1, PageSize: 20, Status: "bogus"}
err := runList(context.Background(), opts, nil, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
assert.Contains(t, typed.Message, "pending")
assert.Contains(t, typed.Message, "failed")
}
func TestList_StatusFilter_AcceptsAllEnumValues(t *testing.T) {
chdirIsolated(t)
for _, v := range docListStatusValues {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{Page: 1, PageSize: 20, Status: v}
require.NoError(t, runList(context.Background(), opts, nil, svc, "kb_xxx"),
"status=%q should be accepted", v)
}
}