feat(cli): search --all-pages canon catch-up + AGENTS.md SOP / CRUD canon
Brings search docs and search sessions to v0.4 pagination canon (--limit / --page-size / --all-pages, matching session list / doc list). Both default --all-pages=true to preserve prior silent walk-all behavior; explicit knobs added for users who want one-page fetch. cli/AGENTS.md gains two new sections: - Command surface design SOP — a 5-step SDK-schema-first pre-design checklist for future contributors. Earlier spec drafts produced schema-error classes (missing/mismatched fields, missing pagination flags) when commands were designed from convention rather than from the SDK; the SOP makes the SDK the ground truth. - CRUD command flag canon — Mode A (hard-required + flag error, no interactive prompts), the established pattern for non-auth CRUD. Also fixes the agent invoke rationale source: the CLI-layer precedent for invoke being a separate verb (not a chat mode) is documented inline rather than referencing other vendor CLI behavior.
This commit is contained in:
@@ -186,3 +186,30 @@ The curated 10 tools (`cli/internal/mcp/tools.go`):
|
||||
|
||||
Adding a tool is a deliberate API expansion — the agent-callable surface is the reason this CLI ships an MCP server, not its CLI command list, so the registration list in `registerTools` is maintained by hand.
|
||||
|
||||
## Command surface design SOP
|
||||
|
||||
Before specifying any CLI command, do this in order:
|
||||
|
||||
1. `grep -A 50 "type Foo struct" client/foo.go` — dump SDK request/response schemas.
|
||||
2. List every field with type and source line.
|
||||
3. For each field, decide: hot-path flag / config-file only / hidden / never-expose.
|
||||
4. Cross-check pagination signatures: an SDK `(ctx, id, page, pageSize)` shape demands `--limit` + `--all-pages` + `--page-size` on the CLI side.
|
||||
5. ONLY THEN consult mainstream CLI conventions to choose flag names, positionals, mutex, and confirm semantics.
|
||||
|
||||
Rationale: earlier drafts produced three categories of schema errors — fields that didn't exist on the underlying SDK, wrong field counts in user-facing docs, and missing pagination flags — that all stemmed from "design from convention, not from SDK." The fix is canonical: the SDK schema is the ground truth; convention decides names and shapes around that ground truth.
|
||||
|
||||
## CRUD command flag canon
|
||||
|
||||
v0.5+ follows **Mode A: hard-required + immediate flag error** for CRUD commands, not Mode B: TTY-prompts-fill (used by `auth login` only). Mode A is the standard pattern for scripted / agent-friendly CLI usage.
|
||||
|
||||
- Positional required: `cobra.ExactArgs(N)` or `cobra.MinimumNArgs(1)`
|
||||
- Flag required: `cmd.MarkFlagRequired("flag")`
|
||||
- Custom required (e.g., `agent edit` needs at-least-one-edit-flag): RunE-level validation that returns `input.invalid_argument`
|
||||
- Mutex: `cmd.MarkFlagsMutuallyExclusive("a", "b")`
|
||||
|
||||
Reasons for Mode A:
|
||||
|
||||
- Admin/debug commands are not `auth login` — there is no human-interactive prompt to lean on.
|
||||
- Agent-friendly: MCP callers do not stall waiting for stdin prompts.
|
||||
- Consistent with every existing non-auth WeKnora command.
|
||||
|
||||
|
||||
@@ -12,6 +12,37 @@ CLI history before v0.3 is recorded in the project root
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### v0.5 — agent CRUD, chunk subtree, MCP chunk_list, audit-driven cleanup
|
||||
|
||||
#### Added
|
||||
- `weknora agent create <name> --model <id>` / `agent edit <id>` /
|
||||
`agent delete <id>` — hybrid surface (8 hot-path flags + `--config-file`
|
||||
YAML/JSON tail + `--generate-skeleton` template emit). `--from <agent-id>`
|
||||
copies from an existing agent.
|
||||
- `weknora chunk list --doc <doc-id>` / `chunk view <chunk-id>` /
|
||||
`chunk delete <chunk-id> --doc <doc-id>` — new subtree for RAG retrieval
|
||||
debug. Paginated with v0.4 `--limit` / `--page-size` / `--all-pages` canon.
|
||||
- `weknora mcp serve` adds `chunk_list` as the 10th curated tool.
|
||||
- `weknora agent view <id>` human output now renders all 34 AgentConfig
|
||||
fields (previously 7), grouped into 10 presentation sections.
|
||||
- `--all-pages` / `--page-size` on `search docs` and `search sessions`
|
||||
(catching up with `session list` / `doc list` canon from v0.3+v0.4).
|
||||
|
||||
#### Fixed
|
||||
- MCP `search_chunks` tool: `limit` arg now correctly threads into
|
||||
`SearchParams.MatchCount`. Previously the server's default cap won,
|
||||
silently capping below the requested limit.
|
||||
- `search sessions` human time format: now uses `fuzzyTime` like
|
||||
`session list` instead of raw RFC3339.
|
||||
|
||||
#### Changed
|
||||
- `cli/AGENTS.md` MCP curation rationale rewritten: curated read-only
|
||||
is a deliberate product call gated on server-side token scope, not
|
||||
MCP industry canon.
|
||||
- `cli/AGENTS.md` adds §"Command surface design SOP" and
|
||||
§"CRUD command flag canon" for v0.6+ contributors.
|
||||
- `cli/go.mod`: adds `gopkg.in/yaml.v3` for `agent create --config-file`.
|
||||
|
||||
### v0.4 — output contract hardening and mainstream alignment
|
||||
|
||||
#### Breaking changes
|
||||
|
||||
+37
-8
@@ -15,11 +15,15 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// docsPageSize is how many entries we pull per ListKnowledge round-trip
|
||||
// when paging through a KB to filter client-side. Server caps page_size at
|
||||
// 1000 (per the doc/list bound this branch already added).
|
||||
// docsPageSize is the default --page-size on `search docs`: how many
|
||||
// entries to pull per ListKnowledge round-trip when paging through a KB
|
||||
// to filter client-side. Server caps page_size at 1000 (per the doc/list
|
||||
// bound this branch already added). Tunable via --page-size in 1..1000.
|
||||
const docsPageSize = 200
|
||||
|
||||
// docsMaxPageSize bounds the --page-size flag, matching session/doc list canon.
|
||||
const docsMaxPageSize = 1000
|
||||
|
||||
// docsFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `search docs`. Mirrors sdk.Knowledge json tags.
|
||||
var docsFields = []string{
|
||||
@@ -35,6 +39,15 @@ type DocsSearchOptions struct {
|
||||
KB string // raw --kb (UUID or name)
|
||||
KBID string // resolved id; populated before listing
|
||||
Limit int
|
||||
// PageSize is the server batch size per ListKnowledge call (1..1000,
|
||||
// default 200). Tunable so a caller searching a small KB can fetch
|
||||
// everything in one round-trip, or a caller on flaky network can
|
||||
// shorten the batch.
|
||||
PageSize int
|
||||
// AllPages walks server pages internally until total exhausted or
|
||||
// --limit accumulated. Default true preserves v0.4 behavior; setting
|
||||
// false stops after the first page (useful for cheap previews).
|
||||
AllPages bool
|
||||
}
|
||||
|
||||
// DocsSearchService is the narrow SDK surface this command depends on.
|
||||
@@ -55,9 +68,14 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "Find documents in a knowledge base by name (client-side substring match)",
|
||||
Long: `Pages through the KB's documents and surfaces every entry whose title or
|
||||
filename contains the query (case-insensitive). Useful for finding a
|
||||
specific upload to download or delete by id.`,
|
||||
specific upload to download or delete by id.
|
||||
|
||||
By default, --all-pages=true walks every server page until --limit is
|
||||
reached or the KB is exhausted (matching v0.4 behavior). Pass
|
||||
--all-pages=false to stop after one page.`,
|
||||
Example: ` weknora search docs "Q3 forecast" --kb finance
|
||||
weknora search docs "spec" --kb engineering --limit 5`,
|
||||
weknora search docs "spec" --kb engineering --limit 5
|
||||
weknora search docs "spec" --kb engineering --all-pages=false`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.Query = strings.TrimSpace(args[0])
|
||||
@@ -85,19 +103,27 @@ specific upload to download or delete by id.`,
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (required)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", docsPageSize, "Items per server batch (1..1000)")
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit")
|
||||
cmdutil.AddJSONFlags(cmd, docsFields)
|
||||
_ = cmd.MarkFlagRequired("kb")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, jopts *cmdutil.JSONOptions, svc DocsSearchService) error {
|
||||
if opts.PageSize < 1 || opts.PageSize > docsMaxPageSize {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
|
||||
fmt.Sprintf("--page-size must be in 1..%d, got %d", docsMaxPageSize, opts.PageSize))
|
||||
}
|
||||
needle := strings.ToLower(opts.Query)
|
||||
var matches []sdk.Knowledge
|
||||
|
||||
// Page through the KB until limit matches found or pagination exhausted.
|
||||
// The server returns total; stop when (page-1)*pageSize >= total.
|
||||
// --all-pages=true (default) walks every server page; --all-pages=false
|
||||
// stops after the first page. The server returns total; stop when
|
||||
// page*pageSize >= total.
|
||||
for page := 1; ; page++ {
|
||||
items, total, err := svc.ListKnowledge(ctx, opts.KBID, page, docsPageSize, "")
|
||||
items, total, err := svc.ListKnowledge(ctx, opts.KBID, page, opts.PageSize, "")
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list documents")
|
||||
}
|
||||
@@ -109,7 +135,10 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, jopts *cmdutil.
|
||||
}
|
||||
}
|
||||
}
|
||||
if int64(page*docsPageSize) >= total || len(items) == 0 {
|
||||
if !opts.AllPages {
|
||||
break
|
||||
}
|
||||
if int64(page*opts.PageSize) >= total || len(items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestDocsSearch_Substring(t *testing.T) {
|
||||
},
|
||||
total: 3,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20}, nil, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "d1")
|
||||
assert.Contains(t, got, "d3")
|
||||
@@ -57,7 +57,7 @@ func TestDocsSearch_MatchesFileName(t *testing.T) {
|
||||
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "Untitled", FileName: "report.pdf"}}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20}, nil, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc))
|
||||
assert.Contains(t, out.String(), "d1")
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
|
||||
pages: map[int][]sdk.Knowledge{1: page1, 2: page2},
|
||||
total: int64(docsPageSize) + 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 20}, nil, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc))
|
||||
assert.Contains(t, out.String(), "found")
|
||||
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when no match on page 1")
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func TestDocsSearch_StopsAtLimit(t *testing.T) {
|
||||
page1[i] = sdk.Knowledge{ID: "match", Title: "needle"}
|
||||
}
|
||||
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3}, nil, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, nil, svc))
|
||||
// Must not request page 2 because limit was hit mid-page.
|
||||
assert.Equal(t, []int{1}, svc.calls)
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func TestDocsSearch_JSON(t *testing.T) {
|
||||
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "match"}}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20}, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.JSONOptions{}, svc))
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), "["), "expected bare JSON array, got: %q", got)
|
||||
assert.Contains(t, got, `"id":"d1"`)
|
||||
@@ -105,13 +105,59 @@ func TestDocsSearch_JSON(t *testing.T) {
|
||||
func TestDocsSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{err: errors.New("HTTP error 404: kb not found")}
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20}, nil, svc)
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
|
||||
}
|
||||
|
||||
// TestSearchDocs_AllPagesFlag_DefaultsTrue_WalksAllPages locks in that the
|
||||
// historic walk-all-pages behavior is preserved when the new --all-pages flag
|
||||
// is left at its default (true). Three pages of fake data, all match the
|
||||
// substring; the run must request every page.
|
||||
func TestSearchDocs_AllPagesFlag_DefaultsTrue_WalksAllPages(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{
|
||||
pages: map[int][]sdk.Knowledge{
|
||||
1: {{ID: "d1", Title: "needle"}, {ID: "d2", Title: "needle"}},
|
||||
2: {{ID: "d3", Title: "needle"}},
|
||||
3: {},
|
||||
},
|
||||
total: 3,
|
||||
}
|
||||
opts := &DocsSearchOptions{Query: "needle", KBID: "kb_abc", Limit: 100, PageSize: 2, AllPages: true}
|
||||
require.NoError(t, runDocsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
assert.GreaterOrEqual(t, len(svc.calls), 2, "must walk multi pages by default")
|
||||
}
|
||||
|
||||
// TestSearchDocs_AllPagesFalse_StopsAtFirstPage asserts that --all-pages=false
|
||||
// caps server round-trips at one, even when the server reports far more
|
||||
// items available. New v0.5 opt-out for the walk-all default.
|
||||
func TestSearchDocs_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{
|
||||
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "needle"}, {ID: "d2", Title: "needle"}}},
|
||||
total: 100,
|
||||
}
|
||||
opts := &DocsSearchOptions{Query: "needle", KBID: "kb_abc", Limit: 100, PageSize: 2, AllPages: false}
|
||||
require.NoError(t, runDocsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
assert.Len(t, svc.calls, 1, "must stop at first page when --all-pages=false")
|
||||
}
|
||||
|
||||
// TestSearchDocs_PageSizeBound asserts the 1..1000 range guard mirrors the
|
||||
// session/doc list canon. Out-of-range values must produce
|
||||
// input.invalid_argument and never reach the SDK.
|
||||
func TestSearchDocs_PageSizeBound(t *testing.T) {
|
||||
for _, ps := range []int{0, -1, 1001} {
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "t", KBID: "k", Limit: 50, PageSize: ps}, &cmdutil.JSONOptions{}, &fakeDocsSearchSvc{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code, "page_size=%d", ps)
|
||||
}
|
||||
}
|
||||
|
||||
func mustTime(t *testing.T, s string) time.Time {
|
||||
t.Helper()
|
||||
v, err := time.Parse(time.RFC3339, s)
|
||||
|
||||
@@ -16,8 +16,14 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// sessionsPageSize is the default --page-size on `search sessions`: how many
|
||||
// entries to pull per GetSessionsByTenant round-trip when paging through to
|
||||
// filter client-side. Tunable via --page-size in 1..1000.
|
||||
const sessionsPageSize = 200
|
||||
|
||||
// sessionsMaxPageSize bounds the --page-size flag, matching session/doc list canon.
|
||||
const sessionsMaxPageSize = 1000
|
||||
|
||||
// sessionsSearchFields enumerates the fields surfaced for `--json` discovery
|
||||
// on `search sessions`. Mirrors sdk.Session json tags.
|
||||
var sessionsSearchFields = []string{
|
||||
@@ -27,6 +33,14 @@ var sessionsSearchFields = []string{
|
||||
type SessionsSearchOptions struct {
|
||||
Query string
|
||||
Limit int
|
||||
// PageSize is the server batch size per GetSessionsByTenant call
|
||||
// (1..1000, default 200). Tunable so a caller searching a small set
|
||||
// can fetch everything in one round-trip.
|
||||
PageSize int
|
||||
// AllPages walks server pages internally until total exhausted or
|
||||
// --limit accumulated. Default true preserves v0.4 behavior; setting
|
||||
// false stops after the first page (useful for cheap previews).
|
||||
AllPages bool
|
||||
}
|
||||
|
||||
// SessionsSearchService is the narrow SDK surface this command depends on.
|
||||
@@ -43,8 +57,15 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: `sessions "<query>"`,
|
||||
Short: "Find chat sessions by title or description (client-side substring match)",
|
||||
Long: `Pages through the tenant's chat sessions and surfaces every entry whose
|
||||
title or description contains the query (case-insensitive).
|
||||
|
||||
By default, --all-pages=true walks every server page until --limit is
|
||||
reached or the tenant's sessions are exhausted (matching v0.4 behavior).
|
||||
Pass --all-pages=false to stop after one page.`,
|
||||
Example: ` weknora search sessions "onboarding"
|
||||
weknora search sessions "Q3 review" --limit 3 --json`,
|
||||
weknora search sessions "Q3 review" --limit 3 --json
|
||||
weknora search sessions "Q3 review" --all-pages=false`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.Query = strings.TrimSpace(args[0])
|
||||
@@ -66,16 +87,24 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", sessionsPageSize, "Items per server batch (1..1000)")
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit")
|
||||
cmdutil.AddJSONFlags(cmd, sessionsSearchFields)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, jopts *cmdutil.JSONOptions, svc SessionsSearchService) error {
|
||||
if opts.PageSize < 1 || opts.PageSize > sessionsMaxPageSize {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
|
||||
fmt.Sprintf("--page-size must be in 1..%d, got %d", sessionsMaxPageSize, opts.PageSize))
|
||||
}
|
||||
needle := strings.ToLower(opts.Query)
|
||||
var matches []sdk.Session
|
||||
|
||||
// --all-pages=true (default) walks every server page; --all-pages=false
|
||||
// stops after the first page.
|
||||
for page := 1; ; page++ {
|
||||
items, total, err := svc.GetSessionsByTenant(ctx, page, sessionsPageSize)
|
||||
items, total, err := svc.GetSessionsByTenant(ctx, page, opts.PageSize)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list sessions")
|
||||
}
|
||||
@@ -87,7 +116,10 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, jopts *
|
||||
}
|
||||
}
|
||||
}
|
||||
if page*sessionsPageSize >= total || len(items) == 0 {
|
||||
if !opts.AllPages {
|
||||
break
|
||||
}
|
||||
if page*opts.PageSize >= total || len(items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestSessionsSearch_TitleAndDescription(t *testing.T) {
|
||||
}},
|
||||
total: 3,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20}, nil, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "s1")
|
||||
assert.Contains(t, got, "s2")
|
||||
@@ -52,7 +52,7 @@ func TestSessionsSearch_NoMatches(t *testing.T) {
|
||||
pages: map[int][]sdk.Session{1: {{Title: "foo"}}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20}, nil, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
|
||||
assert.Contains(t, out.String(), "(no matches)")
|
||||
}
|
||||
|
||||
@@ -63,14 +63,14 @@ func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
|
||||
page1[i] = sdk.Session{ID: "m", Title: "needle"}
|
||||
}
|
||||
svc := &fakeSessionsSearchSvc{pages: map[int][]sdk.Session{1: page1}, total: 1000}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5}, nil, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
|
||||
assert.Equal(t, []int{1}, svc.calls, "stops paging when limit reached")
|
||||
}
|
||||
|
||||
func TestSessionsSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeSessionsSearchSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20}, nil, svc)
|
||||
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, nil, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -90,8 +90,54 @@ func TestSessionsSearch_RendersFuzzyTime(t *testing.T) {
|
||||
}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10}, nil, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, "hour", "must render relative time (e.g. 'about 2 hours ago'), not raw RFC3339")
|
||||
assert.NotContains(t, body, "T0", "raw RFC3339 has 'T' between date and time; fuzzyTime output should not")
|
||||
}
|
||||
|
||||
// TestSearchSessions_AllPagesFlag_DefaultsTrue_WalksAllPages locks in that
|
||||
// the historic walk-all-pages behavior is preserved when --all-pages is left
|
||||
// at its default (true). Three pages of fake data with matches on each;
|
||||
// the run must request more than one page.
|
||||
func TestSearchSessions_AllPagesFlag_DefaultsTrue_WalksAllPages(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeSessionsSearchSvc{
|
||||
pages: map[int][]sdk.Session{
|
||||
1: {{ID: "s1", Title: "needle"}, {ID: "s2", Title: "needle"}},
|
||||
2: {{ID: "s3", Title: "needle"}},
|
||||
3: {},
|
||||
},
|
||||
total: 3,
|
||||
}
|
||||
opts := &SessionsSearchOptions{Query: "needle", Limit: 100, PageSize: 2, AllPages: true}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
assert.GreaterOrEqual(t, len(svc.calls), 2, "must walk multi pages by default")
|
||||
}
|
||||
|
||||
// TestSearchSessions_AllPagesFalse_StopsAtFirstPage asserts that
|
||||
// --all-pages=false caps server round-trips at one even when the server
|
||||
// reports far more items available. New v0.5 opt-out for the walk-all default.
|
||||
func TestSearchSessions_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeSessionsSearchSvc{
|
||||
pages: map[int][]sdk.Session{1: {{ID: "s1", Title: "needle"}, {ID: "s2", Title: "needle"}}},
|
||||
total: 100,
|
||||
}
|
||||
opts := &SessionsSearchOptions{Query: "needle", Limit: 100, PageSize: 2, AllPages: false}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
assert.Len(t, svc.calls, 1, "must stop at first page when --all-pages=false")
|
||||
}
|
||||
|
||||
// TestSearchSessions_PageSizeBound asserts the 1..1000 range guard mirrors
|
||||
// the session/doc list canon. Out-of-range values must produce
|
||||
// input.invalid_argument and never reach the SDK.
|
||||
func TestSearchSessions_PageSizeBound(t *testing.T) {
|
||||
for _, ps := range []int{0, -1, 1001} {
|
||||
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "t", Limit: 50, PageSize: ps}, &cmdutil.JSONOptions{}, &fakeSessionsSearchSvc{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code, "page_size=%d", ps)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user