refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
+27
-59
@@ -3,7 +3,7 @@ package sessioncmd
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// sessionDeleteFields enumerates the fields surfaced for `--format json`
|
||||
// discovery on `session delete`. Tracks the single-id result struct;
|
||||
// multi-id mode emits MultiDeleteResult (ok/failed).
|
||||
// multi-id mode emits batch envelope (§4.5).
|
||||
var sessionDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
@@ -32,20 +32,6 @@ type deleteResult struct {
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
// MultiDeleteResult is the payload for multi-id deletes.
|
||||
// ok: ids successfully deleted; failed: ids that could not be deleted.
|
||||
type MultiDeleteResult struct {
|
||||
OK []string `json:"ok"`
|
||||
Failed []FailedItem `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
// FailedItem records an id that failed to delete along with its error message.
|
||||
type FailedItem struct {
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// NewCmdDelete builds `weknora session delete`. Single-id keeps the simpler
|
||||
// code path; multi-id uses keep-going semantics (one -y confirms all,
|
||||
// failures collected, exit 1 if any fail).
|
||||
@@ -89,12 +75,20 @@ without the user's explicit go-ahead.`,
|
||||
if len(args) == 1 {
|
||||
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
|
||||
}
|
||||
res, runErr := runMultiDelete(c.Context(), opts, fopts, cli, f.Prompter(), args)
|
||||
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
|
||||
if err := cli.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// Only emit when the operation actually ran. Pre-flight errors
|
||||
// (e.g. confirmation_required) must leave stdout empty per the
|
||||
// wire contract in README.md.
|
||||
if len(res.OK) > 0 || len(res.Failed) > 0 {
|
||||
if emitErr := emitMultiDelete(res, fopts, iostreams.IO.Out); emitErr != nil {
|
||||
if len(outcomes) > 0 {
|
||||
if emitErr := cmdutil.EmitBatch(outcomes, fopts, iostreams.IO.Out, cmdutil.DeletedAtNow); emitErr != nil {
|
||||
return emitErr
|
||||
}
|
||||
}
|
||||
@@ -102,11 +96,23 @@ without the user's explicit go-ahead.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, sessionDeleteFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "permanently delete one or more chat sessions and their messages",
|
||||
RequiredFlags: []string{"<session-id>... (positional, at least one)"},
|
||||
Examples: []string{
|
||||
"weknora session delete s_abc -y",
|
||||
"weknora session delete s_a s_b s_c -y",
|
||||
"weknora session delete s_abc -y --format json",
|
||||
},
|
||||
Warnings: []string{
|
||||
"session delete drops chat history for that session permanently. Never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "session", id); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "session", id, "session.delete", "weknora session delete "+id+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -115,46 +121,8 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted session %s\n", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMultiDelete iterates ids sequentially, keep-going on error: a single
|
||||
// failure does not abort the run, so the caller sees the full outcome.
|
||||
func runMultiDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, ids []string) (*MultiDeleteResult, error) {
|
||||
if err := cmdutil.ConfirmDestructiveBatch(p, opts.Yes, fopts.WantsJSON(), "session", len(ids)); err != nil {
|
||||
return &MultiDeleteResult{}, err
|
||||
}
|
||||
res := &MultiDeleteResult{}
|
||||
for _, id := range ids {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
res.Failed = append(res.Failed, FailedItem{ID: id, Message: err.Error()})
|
||||
continue
|
||||
}
|
||||
res.OK = append(res.OK, id)
|
||||
}
|
||||
if len(res.Failed) > 0 {
|
||||
return res, cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d/%d delete(s) failed", len(res.Failed), len(ids)))
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// emitMultiDelete renders per --format. Mirrors doc delete emitMultiDelete.
|
||||
func emitMultiDelete(res *MultiDeleteResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
for _, id := range res.OK {
|
||||
fmt.Fprintf(w, "OK %s\n", id)
|
||||
}
|
||||
for _, f := range res.Failed {
|
||||
fmt.Fprintf(w, "FAIL %s: %s\n", f.ID, f.Message)
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for session delete", fopts.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package sessioncmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
@@ -30,7 +32,7 @@ func TestDelete_WithYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_abc"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_abc"))
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "s_abc", svc.gotID)
|
||||
assert.False(t, p.Asked, "-y must skip prompt")
|
||||
@@ -40,7 +42,7 @@ func TestDelete_WithYes(t *testing.T) {
|
||||
func TestDelete_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "s_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -50,7 +52,7 @@ func TestDelete_NotFound(t *testing.T) {
|
||||
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_x")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "s_x")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -63,7 +65,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_yes"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_yes"))
|
||||
assert.True(t, p.Asked)
|
||||
assert.True(t, svc.called)
|
||||
}
|
||||
@@ -72,7 +74,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_no")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_no")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -102,41 +104,107 @@ func (f *fakeMultiDeleteSvc) DeleteSession(_ context.Context, id string) error {
|
||||
func TestMultiDelete_AllSucceed(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"s_a", "s_b", "s_c"})
|
||||
outcomes, err := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"s_a", "s_b", "s_c"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"s_a", "s_b", "s_c"}, res.OK)
|
||||
assert.Empty(t, res.Failed)
|
||||
require.Len(t, outcomes, 3)
|
||||
for _, oc := range outcomes {
|
||||
assert.Nil(t, oc.Err, "expected no error for %s", oc.ID)
|
||||
}
|
||||
assert.Equal(t, []string{"s_a", "s_b", "s_c"}, svc.deleted)
|
||||
}
|
||||
|
||||
func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{failOn: map[string]error{"s_b": errors.New("HTTP error 404: not found")}}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"s_a", "s_b", "s_c"})
|
||||
outcomes, err := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"s_a", "s_b", "s_c"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.Error(t, err, "any-failed must surface CodeOperationFailed")
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeOperationFailed, typed.Code)
|
||||
assert.Equal(t, []string{"s_a", "s_c"}, res.OK, "keep-going: s_c was still attempted after s_b failed")
|
||||
assert.Len(t, res.Failed, 1)
|
||||
assert.Equal(t, "s_b", res.Failed[0].ID)
|
||||
require.Len(t, outcomes, 3, "all three ids must appear in outcomes (argv order preserved)")
|
||||
assert.Nil(t, outcomes[0].Err, "s_a should succeed")
|
||||
assert.NotNil(t, outcomes[1].Err, "s_b should fail")
|
||||
assert.Nil(t, outcomes[2].Err, "s_c should succeed (keep-going)")
|
||||
assert.Equal(t, "s_b", outcomes[1].ID)
|
||||
}
|
||||
|
||||
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"s_a", "s_b"})
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "session", 2, "session.delete", "")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
assert.Empty(t, res.OK)
|
||||
assert.Empty(t, svc.deleted, "non-TTY without -y must not call DeleteSession")
|
||||
}
|
||||
|
||||
// TestSessionDelete_MultiID_PartialFailure_BatchEnvelope verifies that the JSON
|
||||
// output for a multi-id partial failure uses the §4.5 batch envelope shape:
|
||||
// {ok:false, data:[{id,ok,result?|error?}...], meta:{count,successes,failures}}.
|
||||
func TestSessionDelete_MultiID_PartialFailure_BatchEnvelope(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{failOn: map[string]error{
|
||||
"s_b": errors.New("HTTP error 404: not found"),
|
||||
}}
|
||||
outcomes, runErr := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"s_a", "s_b", "s_c"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.Error(t, runErr)
|
||||
require.Len(t, outcomes, 3)
|
||||
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &buf, cmdutil.DeletedAtNow))
|
||||
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
OK bool `json:"ok"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
} `json:"data"`
|
||||
Meta struct {
|
||||
Count int `json:"count"`
|
||||
Successes int `json:"successes"`
|
||||
Failures int `json:"failures"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &env), "envelope must be valid JSON")
|
||||
|
||||
assert.False(t, env.OK, "top-level ok must be false when any item failed")
|
||||
assert.Equal(t, 3, env.Meta.Count)
|
||||
assert.Equal(t, 2, env.Meta.Successes)
|
||||
assert.Equal(t, 1, env.Meta.Failures)
|
||||
require.Len(t, env.Data, 3)
|
||||
assert.Equal(t, "s_a", env.Data[0].ID)
|
||||
assert.True(t, env.Data[0].OK)
|
||||
assert.Equal(t, "s_b", env.Data[1].ID)
|
||||
assert.False(t, env.Data[1].OK)
|
||||
assert.NotNil(t, env.Data[1].Error)
|
||||
assert.Equal(t, "s_c", env.Data[2].ID)
|
||||
assert.True(t, env.Data[2].OK)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
@@ -64,7 +65,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
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().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
|
||||
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.AddFormatFlag(cmd, sessionListFields...)
|
||||
@@ -78,10 +79,10 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
Message: fmt.Sprintf("--page-size must be in 1..%d, got %d", maxPageSize, opts.PageSize),
|
||||
}
|
||||
}
|
||||
if opts.Limit < 0 || opts.Limit > 10000 {
|
||||
if opts.Limit < 1 || 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),
|
||||
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
|
||||
}
|
||||
}
|
||||
var since time.Duration
|
||||
@@ -136,12 +137,15 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
items = filtered
|
||||
}
|
||||
// --limit applies after --since so the cap reflects what the user sees.
|
||||
truncated := false
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
truncated = true
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, items)
|
||||
meta := &output.Meta{Count: len(items), HasMore: truncated}
|
||||
return fopts.Emit(iostreams.IO.Out, items, meta)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -2,6 +2,7 @@ package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -34,7 +35,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{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "no sessions")
|
||||
}
|
||||
|
||||
@@ -47,7 +48,7 @@ func TestList_Table(t *testing.T) {
|
||||
},
|
||||
total: 2,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "s_1")
|
||||
assert.Contains(t, got, "Design review")
|
||||
@@ -64,25 +65,34 @@ func TestList_JSON_BareArray(t *testing.T) {
|
||||
},
|
||||
total: 47,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
|
||||
// CLI always asks for page 1 of size --page-size; pagination is server-internal.
|
||||
assert.Equal(t, 1, svc.gotPage)
|
||||
assert.Equal(t, 10, svc.gotPageSize)
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(body), `[`), "bare array expected; got %q", body)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Session `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &env), "expected valid JSON envelope; got %q", body)
|
||||
assert.True(t, env.OK, "envelope.ok must be true")
|
||||
assert.Contains(t, body, `"id":"s_1"`)
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
assert.NotContains(t, body, `"_meta":`)
|
||||
assert.NotContains(t, body, `"has_more":`)
|
||||
assert.NotContains(t, body, `"total":`)
|
||||
}
|
||||
|
||||
func TestList_NilItems_RendersAsBareEmptyArray(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{items: nil, total: 0}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "[]", strings.TrimSpace(out.String()))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Session `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope; got %q", out.String())
|
||||
assert.True(t, env.OK, "envelope.ok must be true")
|
||||
assert.Len(t, env.Data, 0, "expected empty data array")
|
||||
}
|
||||
|
||||
func TestList_BadPagination(t *testing.T) {
|
||||
@@ -96,7 +106,7 @@ func TestList_BadPagination(t *testing.T) {
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := runList(context.Background(), &ListOptions{PageSize: tc.size}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListService{})
|
||||
err := runList(context.Background(), &ListOptions{PageSize: tc.size, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -108,7 +118,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{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -119,7 +129,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{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "s_zh")
|
||||
}
|
||||
|
||||
@@ -132,7 +142,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{PageSize: 30, Since: "7d"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: "7d", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: items, total: 3}))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "recent")
|
||||
@@ -146,7 +156,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{PageSize: 30, Since: v}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0}),
|
||||
"--since=%q should parse", v)
|
||||
})
|
||||
@@ -156,7 +166,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
|
||||
func TestList_SinceFilter_RejectsInvalidDuration(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Since: "bogus"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: "bogus", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -168,7 +178,7 @@ func TestList_SinceFilter_RejectsNonPositive(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
for _, v := range []string{"0d", "0h", "-1h"} {
|
||||
err := runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Since: v}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err, "--since=%q should reject", v)
|
||||
var typed *cmdutil.Error
|
||||
@@ -234,7 +244,7 @@ func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -246,7 +256,7 @@ 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.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
&ListOptions{PageSize: 20, AllPages: true, Limit: 10000}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []int{1, 2, 3}, svc.calls)
|
||||
got := strings.Count(out.String(), `"id":"s_`)
|
||||
assert.Equal(t, 45, got)
|
||||
|
||||
@@ -117,7 +117,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
if !opts.Full {
|
||||
return fopts.Emit(iostreams.IO.Out, s)
|
||||
return fopts.Emit(iostreams.IO.Out, s, nil)
|
||||
}
|
||||
// Project session + messages into a single bare object. Use the
|
||||
// SDK json tags via an embedded *Session so existing keys stay
|
||||
@@ -126,7 +126,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
||||
*sdk.Session
|
||||
Messages []sdk.Message `json:"messages"`
|
||||
}{Session: s, Messages: msgs}
|
||||
return fopts.Emit(iostreams.IO.Out, payload)
|
||||
return fopts.Emit(iostreams.IO.Out, payload, nil)
|
||||
}
|
||||
|
||||
w := iostreams.IO.Out
|
||||
|
||||
@@ -2,6 +2,7 @@ package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -50,7 +51,7 @@ func TestView_Human(t *testing.T) {
|
||||
CreatedAt: "2026-05-10T09:00:00Z",
|
||||
UpdatedAt: "2026-05-12T14:00:00Z",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_abc"))
|
||||
got := out.String()
|
||||
for _, want := range []string{"s_abc", "Design review", "RAG chunking strategy review", "2026-05-12"} {
|
||||
assert.Contains(t, got, want)
|
||||
@@ -64,14 +65,19 @@ func TestView_JSON(t *testing.T) {
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "s_abc"))
|
||||
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(body), `{"id":"s_abc"`), "bare object expected; got %q", body)
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.Session `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &env), "expected valid JSON envelope; got %q", body)
|
||||
assert.True(t, env.OK, "envelope.ok must be true")
|
||||
assert.Equal(t, "s_abc", env.Data.ID, "envelope.data.id must be s_abc")
|
||||
}
|
||||
|
||||
func TestView_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_missing")
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -81,7 +87,7 @@ func TestView_NotFound(t *testing.T) {
|
||||
func TestView_OmitsEmptyDescription(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s_min", Title: "Bare"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_min"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_min"))
|
||||
// Empty Description should not produce an empty `DESC:` line.
|
||||
for line := range strings.SplitSeq(out.String(), "\n") {
|
||||
if strings.HasPrefix(line, "DESC:") {
|
||||
@@ -101,7 +107,7 @@ func TestView_Full_LoadsMessages(t *testing.T) {
|
||||
{ID: "m2", Role: "assistant", Content: "RAG stands for retrieval-augmented generation.", CreatedAt: time.Date(2026, 5, 15, 14, 32, 5, 0, time.UTC)},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_abc"))
|
||||
got := out.String()
|
||||
assert.True(t, svc.loadCall.called, "expected LoadMessages to be called")
|
||||
assert.Equal(t, "s_abc", svc.loadCall.sessionID)
|
||||
@@ -117,7 +123,7 @@ func TestView_Full_NoMessages(t *testing.T) {
|
||||
s: &sdk.Session{ID: "s_empty", Title: "Empty"},
|
||||
msgs: []sdk.Message{},
|
||||
}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_empty"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_empty"))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "Messages (0)")
|
||||
}
|
||||
@@ -125,7 +131,7 @@ func TestView_Full_NoMessages(t *testing.T) {
|
||||
func TestView_Full_LimitInvalid_Zero(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -133,7 +139,7 @@ func TestView_Full_LimitInvalid_Zero(t *testing.T) {
|
||||
func TestView_Full_LimitInvalid_TooLarge(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -143,7 +149,7 @@ func TestView_Full_LimitInvalid_TooLarge(t *testing.T) {
|
||||
func TestView_LimitWithoutFull(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
|
||||
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
assert.Contains(t, err.Error(), "--limit")
|
||||
|
||||
Reference in New Issue
Block a user