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
+60 -1
View File
@@ -3,6 +3,8 @@ package sessioncmd
import (
"context"
"fmt"
"strconv"
"strings"
"text/tabwriter"
"time"
@@ -31,6 +33,7 @@ var sessionListFields = []string{
type ListOptions struct {
Page int
PageSize int
Since string // --since: filter to sessions updated within the past duration
}
// ListService is the narrow SDK surface this command depends on.
@@ -65,8 +68,9 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
}
cmd.Flags().IntVar(&opts.Page, "page", defaultPage, "Page number (1-indexed)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", defaultPageSize, "Items per page (1..1000)")
cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)")
cmdutil.AddJSONFlags(cmd, sessionListFields)
agent.SetAgentHelp(cmd, "Lists chat sessions. _meta.has_more is set when more pages exist; bump --page and retry to walk them.")
agent.SetAgentHelp(cmd, "Lists chat sessions. _meta.has_more is set when more pages exist; bump --page and retry to walk them. --since filters *within the returned page* (client-side); widen --page-size when looking far back.")
return cmd
}
@@ -83,6 +87,14 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
Message: fmt.Sprintf("--page-size must be in 1..%d, got %d", maxPageSize, opts.PageSize),
}
}
var since time.Duration
if opts.Since != "" {
d, err := parseSinceDuration(opts.Since)
if err != nil {
return err
}
since = d
}
items, total, err := svc.GetSessionsByTenant(ctx, opts.Page, opts.PageSize)
if err != nil {
@@ -91,6 +103,20 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
if items == nil {
items = []sdk.Session{} // JSON [] not null
}
if since > 0 {
threshold := time.Now().Add(-since)
filtered := items[:0]
for _, s := range items {
t, err := time.Parse(time.RFC3339, s.UpdatedAt)
if err != nil {
continue // skip unparseable timestamps rather than guess
}
if t.After(threshold) {
filtered = append(filtered, s)
}
}
items = filtered
}
if jopts.Enabled() {
meta := &format.Meta{HasMore: opts.Page*opts.PageSize < total}
@@ -118,6 +144,39 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
return tw.Flush()
}
// parseSinceDuration accepts `time.ParseDuration` forms (1h30m, 24h, 30m)
// plus a `<N>d` suffix for whole days (e.g. 7d). Returns an
// input.invalid_argument *cmdutil.Error for unparseable inputs or
// non-positive durations.
func parseSinceDuration(s string) (time.Duration, error) {
raw := strings.TrimSpace(s)
var d time.Duration
var err error
if rest, ok := strings.CutSuffix(raw, "d"); ok {
num, perr := strconv.ParseFloat(rest, 64)
if perr != nil {
err = perr
} else {
d = time.Duration(num * float64(24*time.Hour))
}
} else {
d, err = time.ParseDuration(raw)
}
if err != nil {
return 0, &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--since %q is not a valid duration: %v (try 7d, 24h, 30m, 1h30m)", s, err),
}
}
if d <= 0 {
return 0, &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--since must be positive, got %q", s),
}
}
return d, nil
}
// fuzzyTime renders a server-provided timestamp string in "2d ago" form.
// Returns the raw input if parsing fails — better to surface the unknown
// format than to silently render "-".
+55
View File
@@ -6,6 +6,7 @@ import (
"errors"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -138,3 +139,57 @@ func TestList_NonASCIITitle(t *testing.T) {
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
assert.Contains(t, out.String(), "s_zh")
}
func TestList_SinceFilter_DropsOldSessions(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Session{
{ID: "recent", Title: "today", UpdatedAt: now.Add(-1 * time.Hour).Format(time.RFC3339)},
{ID: "old", Title: "last month", UpdatedAt: now.Add(-30 * 24 * time.Hour).Format(time.RFC3339)},
{ID: "yesterday", Title: "yday", UpdatedAt: now.Add(-23 * time.Hour).Format(time.RFC3339)},
}
require.NoError(t, runList(context.Background(),
&ListOptions{Page: 1, PageSize: 30, Since: "7d"}, nil,
&fakeListService{items: items, total: 3}))
got := out.String()
assert.Contains(t, got, "recent")
assert.Contains(t, got, "yesterday")
assert.NotContains(t, got, "old", "30-day-old session should be filtered out by --since 7d")
}
func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
cases := []string{"24h", "1h30m", "30m", "7d", "0.5d", "168h"}
for _, v := range cases {
t.Run(v, func(t *testing.T) {
_, _ = iostreams.SetForTest(t)
require.NoError(t, runList(context.Background(),
&ListOptions{Page: 1, PageSize: 30, Since: v}, nil,
&fakeListService{items: []sdk.Session{}, total: 0}),
"--since=%q should parse", v)
})
}
}
func TestList_SinceFilter_RejectsInvalidDuration(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(),
&ListOptions{Page: 1, PageSize: 30, Since: "bogus"}, nil,
&fakeListService{items: []sdk.Session{}, total: 0})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
func TestList_SinceFilter_RejectsNonPositive(t *testing.T) {
_, _ = iostreams.SetForTest(t)
for _, v := range []string{"0d", "0h", "-1h"} {
err := runList(context.Background(),
&ListOptions{Page: 1, PageSize: 30, Since: v}, nil,
&fakeListService{items: []sdk.Session{}, total: 0})
require.Error(t, err, "--since=%q should reject", v)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
}