refactor(cli): --limit/--all-pages, Go 1.26, internal/agent → aiclient

Cross-cutting cleanup that lands alongside the new feature surface:

- `--limit / -L` and `--all-pages` on every list command. Default
  --limit 30 (gh-parity); --all-pages drains every server page
  client-side, capped by --limit. Closes the audit finding that the
  old "1000 max per call" implicit cap was undiscoverable.
- `auth token` emits a TTY-only stderr advisory when stdout is a
  terminal (the credential just got displayed in scrollback) plus an
  api-key-mode rotation hint.
- Comment + doc discipline pass: drop external project name
  references from in-code comments (we reference them in design notes,
  not inline).
- Bump `go` directive to 1.26.0 and CI matrix to 1.26.x to align with
  the main module's go.mod.
- Rename `cli/internal/agent` → `cli/internal/aiclient` to
  disambiguate from the new `cli/cmd/agent` resource subtree. The
  package handles AI coding-agent env detection + per-command --help
  annotations; the new name reflects that more precisely.
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent 9bb83b47fd
commit bdc589e1c0
59 changed files with 837 additions and 275 deletions
+2 -2
View File
@@ -6,7 +6,7 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -70,7 +70,7 @@ without the user's explicit go-ahead.`,
},
}
cmdutil.AddJSONFlags(cmd, sessionDeleteFields)
agent.SetAgentHelp(cmd, "Destructively deletes a chat session by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
aiclient.SetAgentHelp(cmd, "Destructively deletes a chat session by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
return cmd
}
+64 -26
View File
@@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -31,9 +31,14 @@ var sessionListFields = []string{
}
type ListOptions struct {
Page int
PageSize int
PageSize int // Items per server batch (default 50).
Since string // --since: filter to sessions updated within the past duration
// Limit caps the returned items client-side (default 30; 0 = no cap).
// Applied after pagination / --all-pages accumulation and --since filter.
Limit int
// AllPages walks server pages internally, accumulating items until
// total exhausted or --limit hit.
AllPages bool
}
// ListService is the narrow SDK surface this command depends on.
@@ -46,10 +51,9 @@ type listResult struct {
Items []sdk.Session `json:"items"`
}
// NewCmdList builds `weknora session list`. Paginated; defaults to page=1
// page_size=30. No cursor — server is page-based today.
// NewCmdList builds `weknora session list`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{Page: defaultPage, PageSize: defaultPageSize}
opts := &ListOptions{PageSize: defaultPageSize}
cmd := &cobra.Command{
Use: "list",
Short: "List chat sessions for the active context",
@@ -66,27 +70,28 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
return runList(c.Context(), opts, jopts, cli)
},
}
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().IntVar(&opts.PageSize, "page-size", defaultPageSize, "Items per server batch (1..1000)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
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. --since filters *within the returned page* (client-side); widen --page-size when looking far back.")
aiclient.SetAgentHelp(cmd, "Lists chat sessions. data.{items}; pagination metadata in _meta.{page, page_size, total, has_more}. --all-pages drains every server page in one call (capped by --limit). --since filters client-side after fetch.")
return cmd
}
func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, svc ListService) error {
if opts.Page < 1 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--page must be >= 1, got %d", opts.Page),
}
}
if opts.PageSize < 1 || opts.PageSize > maxPageSize {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--page-size must be in 1..%d, got %d", maxPageSize, opts.PageSize),
}
}
if opts.Limit < 0 || opts.Limit > 10000 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--limit must be in 0..10000 (0 = no cap), got %d", opts.Limit),
}
}
var since time.Duration
if opts.Since != "" {
d, err := parseSinceDuration(opts.Since)
@@ -96,9 +101,37 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
since = d
}
items, total, err := svc.GetSessionsByTenant(ctx, opts.Page, opts.PageSize)
if err != nil {
return cmdutil.WrapHTTP(err, "list sessions")
var (
items []sdk.Session
total int
)
if opts.AllPages {
accum := make([]sdk.Session, 0)
page := 1
for {
chunk, t, err := svc.GetSessionsByTenant(ctx, page, opts.PageSize)
if err != nil {
return cmdutil.WrapHTTP(err, "list sessions")
}
total = t
accum = append(accum, chunk...)
if opts.Limit > 0 && len(accum) >= opts.Limit {
accum = accum[:opts.Limit]
break
}
if page*opts.PageSize >= total || len(chunk) == 0 {
break
}
page++
}
items = accum
} else {
chunk, t, err := svc.GetSessionsByTenant(ctx, 1, opts.PageSize)
if err != nil {
return cmdutil.WrapHTTP(err, "list sessions")
}
items = chunk
total = t
}
if items == nil {
items = []sdk.Session{} // JSON [] not null
@@ -117,16 +150,21 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
}
items = filtered
}
// --limit applies after --since so the cap reflects what the user sees.
if opts.Limit > 0 && len(items) > opts.Limit {
items = items[:opts.Limit]
}
if jopts.Enabled() {
// When --since is active, has_more is meaningless: the server's
// total counts all sessions but the page is now client-side
// filtered. An agent walking pages would see has_more=true even
// when no later page can contain matching items. Drop the flag
// rather than mislead. The agent_help string documents this.
meta := &format.Meta{}
if since == 0 {
meta.HasMore = opts.Page*opts.PageSize < total
// has_more is suppressed when --since filter is active (server
// total ≠ what we returned) or when --all-pages drained the server.
meta := &format.Meta{
Page: 1,
PageSize: opts.PageSize,
Total: int64(total),
}
if since == 0 && !opts.AllPages {
meta.HasMore = opts.PageSize < total
}
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
+117 -24
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
@@ -35,7 +36,7 @@ func (f *fakeListService) GetSessionsByTenant(_ context.Context, page, pageSize
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, nil, svc))
assert.Contains(t, out.String(), "no sessions")
}
@@ -48,7 +49,7 @@ func TestList_Table(t *testing.T) {
},
total: 2,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, nil, svc))
got := out.String()
assert.Contains(t, got, "s_1")
assert.Contains(t, got, "Design review")
@@ -65,30 +66,34 @@ func TestList_JSON_WithMeta(t *testing.T) {
},
total: 47,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10}, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10}, &cmdutil.JSONOptions{}, svc))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
require.True(t, env.OK)
// Pagination flags are forwarded.
assert.Equal(t, 2, svc.gotPage)
// Pagination is server-internal: CLI always asks for page 1 of size --page-size.
assert.Equal(t, 1, svc.gotPage)
assert.Equal(t, 10, svc.gotPageSize)
// envelope.data.items shaped + paging metadata in _meta
body := out.String()
assert.Contains(t, body, `"id":"s_1"`)
assert.Contains(t, body, `"items":`)
// has_more inferred from page*pageSize < total (2*10=20 < 47).
// has_more inferred from page_size < total (10 < 47).
assert.Contains(t, body, `"has_more":true`)
// pagination metadata lives in _meta now
assert.Contains(t, body, `"page":1`)
assert.Contains(t, body, `"page_size":10`)
assert.Contains(t, body, `"total":47`)
}
func TestList_JSON_LastPage_NoHasMore(t *testing.T) {
func TestList_JSON_PageSizeCoversAll_NoHasMore(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{
items: []sdk.Session{{ID: "s_1"}},
total: 11,
total: 1,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10}, &cmdutil.JSONOptions{}, svc))
// page*size = 20 ≥ total 11 → has_more must be false (omitempty drops the key)
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.JSONOptions{}, svc))
// page_size (30) ≥ total (1) → has_more must be false (omitempty drops the key)
body := out.String()
assert.NotContains(t, body, `"has_more":true`)
}
@@ -96,24 +101,22 @@ func TestList_JSON_LastPage_NoHasMore(t *testing.T) {
func TestList_NilItems_RendersAsEmptyArray(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.JSONOptions{}, svc))
assert.Contains(t, out.String(), `"items":[]`)
}
func TestList_BadPagination(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cases := []struct {
page, size int
name string
size int
name string
}{
{0, 30, "page < 1"},
{-1, 30, "page negative"},
{1, 0, "size < 1"},
{1, 1001, "size > max"},
{0, "size < 1"},
{1001, "size > max"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := runList(context.Background(), &ListOptions{Page: tc.page, PageSize: tc.size}, nil, &fakeListService{})
err := runList(context.Background(), &ListOptions{PageSize: tc.size}, nil, &fakeListService{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -125,7 +128,7 @@ func TestList_BadPagination(t *testing.T) {
func TestList_NetworkError_TypedCode(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListService{err: errors.New("HTTP error 401: unauthenticated")}
err := runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc)
err := runList(context.Background(), &ListOptions{PageSize: 30}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -136,7 +139,7 @@ func TestList_NetworkError_TypedCode(t *testing.T) {
func TestList_NonASCIITitle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: []sdk.Session{{ID: "s_zh", Title: strings.Repeat("中文", 50)}}, total: 1}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, nil, svc))
assert.Contains(t, out.String(), "s_zh")
}
@@ -149,7 +152,7 @@ func TestList_SinceFilter_DropsOldSessions(t *testing.T) {
{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,
&ListOptions{PageSize: 30, Since: "7d"}, nil,
&fakeListService{items: items, total: 3}))
got := out.String()
assert.Contains(t, got, "recent")
@@ -163,7 +166,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
t.Run(v, func(t *testing.T) {
_, _ = iostreams.SetForTest(t)
require.NoError(t, runList(context.Background(),
&ListOptions{Page: 1, PageSize: 30, Since: v}, nil,
&ListOptions{PageSize: 30, Since: v}, nil,
&fakeListService{items: []sdk.Session{}, total: 0}),
"--since=%q should parse", v)
})
@@ -173,7 +176,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
func TestList_SinceFilter_RejectsInvalidDuration(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(),
&ListOptions{Page: 1, PageSize: 30, Since: "bogus"}, nil,
&ListOptions{PageSize: 30, Since: "bogus"}, nil,
&fakeListService{items: []sdk.Session{}, total: 0})
require.Error(t, err)
var typed *cmdutil.Error
@@ -185,7 +188,7 @@ 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,
&ListOptions{PageSize: 30, Since: v}, nil,
&fakeListService{items: []sdk.Session{}, total: 0})
require.Error(t, err, "--since=%q should reject", v)
var typed *cmdutil.Error
@@ -193,3 +196,93 @@ func TestList_SinceFilter_RejectsNonPositive(t *testing.T) {
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
}
// makeSessions builds N sessions with distinct IDs and descending UpdatedAt.
func makeSessions(n int) []sdk.Session {
base := time.Now()
out := make([]sdk.Session, n)
for i := 0; i < n; i++ {
out[i] = sdk.Session{
ID: fmt.Sprintf("s_%03d", i),
Title: fmt.Sprintf("title-%03d", i),
UpdatedAt: base.Add(-time.Duration(i) * time.Minute).Format(time.RFC3339),
}
}
return out
}
// pagedSessionSvc returns server-paginated session results from a flat slice
// and records page numbers requested.
type pagedSessionSvc struct {
all []sdk.Session
calls []int
pageSize int
}
func (p *pagedSessionSvc) GetSessionsByTenant(_ context.Context, page, pageSize int) ([]sdk.Session, int, error) {
p.calls = append(p.calls, page)
p.pageSize = pageSize
start := (page - 1) * pageSize
if start >= len(p.all) {
return []sdk.Session{}, len(p.all), nil
}
end := start + pageSize
if end > len(p.all) {
end = len(p.all)
}
return p.all[start:end], len(p.all), nil
}
func TestList_Limit_LessThanPageSize_SlicesToLimit(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: makeSessions(20), total: 20}
require.NoError(t, runList(context.Background(),
&ListOptions{PageSize: 20, Limit: 5}, &cmdutil.JSONOptions{}, svc))
got := strings.Count(out.String(), `"id":"s_`)
assert.Equal(t, 5, got, "--limit 5 must slice 20 items down to 5")
}
func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: makeSessions(10), total: 10}
require.NoError(t, runList(context.Background(),
&ListOptions{PageSize: 10, Limit: 50}, &cmdutil.JSONOptions{}, svc))
got := strings.Count(out.String(), `"id":"s_`)
assert.Equal(t, 10, got)
}
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(),
&ListOptions{PageSize: 30, Limit: -1}, nil,
&fakeListService{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
func TestList_AllPages_WalksAllServerPages(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &pagedSessionSvc{all: makeSessions(45)}
require.NoError(t, runList(context.Background(),
&ListOptions{PageSize: 20, AllPages: true}, &cmdutil.JSONOptions{}, svc))
assert.Equal(t, []int{1, 2, 3}, svc.calls)
got := strings.Count(out.String(), `"id":"s_`)
assert.Equal(t, 45, got)
// --all-pages drained, so has_more should be absent.
assert.NotContains(t, out.String(), `"has_more":true`)
}
func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &pagedSessionSvc{all: makeSessions(200)}
require.NoError(t, runList(context.Background(),
&ListOptions{PageSize: 20, AllPages: true, Limit: 50}, &cmdutil.JSONOptions{}, svc))
got := strings.Count(out.String(), `"id":"s_`)
assert.Equal(t, 50, got)
assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit")
}
// (test removed: --page flag was dropped in v0.4 mainstream-alignment;
// --all-pages now walks unconditionally, no mutex case to test.)
+2 -2
View File
@@ -7,7 +7,7 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -50,7 +50,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
},
}
cmdutil.AddJSONFlags(cmd, sessionViewFields)
agent.SetAgentHelp(cmd, "Shows a chat session's metadata (title, description, timestamps). Errors with resource.not_found if id is unknown.")
aiclient.SetAgentHelp(cmd, "Shows a chat session's metadata (title, description, timestamps). Errors with resource.not_found if id is unknown.")
return cmd
}