feat(cli): doc delete multi-id + api --paginate + paginate fixes + batch deletes
Batch-write surface and pagination consistency:
* weknora doc delete <doc-id> [<doc-id>...] — positional multi-id, default
keep-going on failure. Single -y confirms entire batch.
* weknora session delete <session-id> [<session-id>...] — same shape.
* weknora chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id> — multi-id
with shared --doc parent.
* Multi-id partial-failure rolls up as operation.failed (exit 1), not
server.error (exit 7) — failures are operation outcomes, not transient
transport issues, and the retry-with-backoff hint for server.* would
mislead callers.
* weknora api <path> --paginate — auto-walks offset pagination and merges
pages into a single {data, total} JSON response.
* Paginate truncation fix across 6 list/follower call sites.
* All doc / search / chunk / session / kb list commands migrated to
FormatOptions API.
Multi-id RunE only emits the {ok, failed} envelope when the operation
actually ran — pre-flight failures (e.g. confirmation_required) leave
stdout empty per the wire contract.
doc upload's missing-positional-or-flag check is wrapped as FlagError so
the exit code (2) matches the convention used by other commands that
require a positional argument directly.
This commit is contained in:
+98
-21
@@ -3,6 +3,7 @@ package sessioncmd
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
@@ -11,8 +12,9 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
)
|
||||
|
||||
// sessionDeleteFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `session delete`. Tracks the small result struct.
|
||||
// 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).
|
||||
var sessionDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
@@ -24,50 +26,87 @@ type DeleteService interface {
|
||||
DeleteSession(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// deleteResult is the typed payload emitted under data on success.
|
||||
// deleteResult is the typed payload emitted under data on single-id success.
|
||||
type deleteResult struct {
|
||||
ID string `json:"id"`
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
// NewCmdDelete builds `weknora session delete`. Destructive write gated
|
||||
// by -y/--yes (exit-10 protocol in scripted / --json invocations).
|
||||
// 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).
|
||||
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &DeleteOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "delete <id>",
|
||||
Short: "Delete a chat session",
|
||||
Long: `Permanently delete a chat session and its messages.
|
||||
Use: "delete <session-id> [<session-id>...]",
|
||||
Short: "Delete one or more chat sessions",
|
||||
Long: `Permanently delete one or more chat sessions and their messages.
|
||||
|
||||
Prompts for confirmation by default when stdout is a TTY and --json is not set.
|
||||
Pass -y/--yes (global flag) to skip the prompt (required in agent / CI / piped contexts).
|
||||
Prompts for confirmation by default when stdout is a TTY and JSON output is
|
||||
not set. Pass -y/--yes (global flag) to skip the prompt (required in agent
|
||||
/ CI / piped contexts).
|
||||
|
||||
Single-id: one confirm prompt, exit 0/1.
|
||||
Multi-id:
|
||||
• Default keep-going: failed deletes do NOT stop the run; failures collected.
|
||||
• One -y/--yes confirms all sessions.
|
||||
• Exit 0 if all succeed; exit 1 if any failed.
|
||||
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
and writes input.confirmation_required to stderr. NEVER auto-pass -y
|
||||
without the user's explicit go-ahead.`,
|
||||
Example: ` weknora session delete s_abc # interactive confirm
|
||||
weknora session delete s_abc -y # no prompt
|
||||
weknora session delete s_abc -y --json`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: ` weknora session delete s_abc # interactive confirm
|
||||
weknora session delete s_abc -y # no prompt
|
||||
weknora session delete s_abc -y --format json # bare {id, deleted:true} JSON
|
||||
weknora session delete s_a s_b s_c -y # delete 3, keep-going`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runDelete(c.Context(), opts, jopts, cli, f.Prompter(), args[0])
|
||||
// Single-id uses the simpler code path (bare {id, deleted}).
|
||||
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)
|
||||
// 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 {
|
||||
return emitErr
|
||||
}
|
||||
}
|
||||
return runErr
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, sessionDeleteFields)
|
||||
cmdutil.AddFormatFlag(cmd, sessionDeleteFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "session", id); err != nil {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -75,9 +114,47 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,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}, nil, svc, p, "s_abc"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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 +40,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}, nil, svc, &testutil.ConfirmPrompter{}, "s_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -50,7 +50,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{}, nil, svc, &testutil.ConfirmPrompter{}, "s_x")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_x")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -63,7 +63,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{}, nil, svc, p, "s_yes"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_yes"))
|
||||
assert.True(t, p.Asked)
|
||||
assert.True(t, svc.called)
|
||||
}
|
||||
@@ -72,7 +72,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "s_no")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_no")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -80,3 +80,63 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
assert.False(t, svc.called)
|
||||
assert.Contains(t, errBuf.String(), "Aborted")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Multi-id (keep-going semantics)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// fakeMultiDeleteSvc records every id deleted and can fail-on selected ids.
|
||||
type fakeMultiDeleteSvc struct {
|
||||
deleted []string
|
||||
failOn map[string]error
|
||||
}
|
||||
|
||||
func (f *fakeMultiDeleteSvc) DeleteSession(_ context.Context, id string) error {
|
||||
if e, ok := f.failOn[id]; ok {
|
||||
return e
|
||||
}
|
||||
f.deleted = append(f.deleted, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
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"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"s_a", "s_b", "s_c"}, res.OK)
|
||||
assert.Empty(t, res.Failed)
|
||||
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"})
|
||||
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)
|
||||
}
|
||||
|
||||
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"})
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ const (
|
||||
maxPageSize = 1000
|
||||
)
|
||||
|
||||
// sessionListFields enumerates the fields surfaced for `--json` discovery on
|
||||
// sessionListFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `session list`. Mirrors sdk.Session json tags.
|
||||
var sessionListFields = []string{
|
||||
"id", "tenant_id", "title", "description", "created_at", "updated_at",
|
||||
@@ -51,26 +51,27 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "List chat sessions for the active context",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runList(c.Context(), opts, jopts, cli)
|
||||
return runList(c.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
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)
|
||||
cmdutil.AddFormatFlag(cmd, sessionListFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, svc ListService) error {
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
|
||||
if opts.PageSize < 1 || opts.PageSize > maxPageSize {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
@@ -105,7 +106,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
accum = accum[:opts.Limit]
|
||||
break
|
||||
}
|
||||
if page*opts.PageSize >= total || len(chunk) == 0 {
|
||||
if len(accum) >= total || len(chunk) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -139,8 +140,8 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, items)
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, items)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -34,7 +34,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}, nil, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "no sessions")
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestList_Table(t *testing.T) {
|
||||
},
|
||||
total: 2,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, nil, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "s_1")
|
||||
assert.Contains(t, got, "Design review")
|
||||
@@ -64,7 +64,7 @@ func TestList_JSON_BareArray(t *testing.T) {
|
||||
},
|
||||
total: 47,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10}, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10}, &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)
|
||||
@@ -81,7 +81,7 @@ func TestList_JSON_BareArray(t *testing.T) {
|
||||
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.JSONOptions{}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "[]", strings.TrimSpace(out.String()))
|
||||
}
|
||||
|
||||
@@ -96,7 +96,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}, nil, &fakeListService{})
|
||||
err := runList(context.Background(), &ListOptions{PageSize: tc.size}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -108,7 +108,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}, nil, svc)
|
||||
err := runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -119,7 +119,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}, nil, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "s_zh")
|
||||
}
|
||||
|
||||
@@ -132,7 +132,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"}, nil,
|
||||
&ListOptions{PageSize: 30, Since: "7d"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: items, total: 3}))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "recent")
|
||||
@@ -146,7 +146,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}, nil,
|
||||
&ListOptions{PageSize: 30, Since: v}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0}),
|
||||
"--since=%q should parse", v)
|
||||
})
|
||||
@@ -156,7 +156,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"}, nil,
|
||||
&ListOptions{PageSize: 30, Since: "bogus"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -168,7 +168,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}, nil,
|
||||
&ListOptions{PageSize: 30, Since: v}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err, "--since=%q should reject", v)
|
||||
var typed *cmdutil.Error
|
||||
@@ -217,7 +217,7 @@ 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))
|
||||
&ListOptions{PageSize: 20, Limit: 5}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
got := strings.Count(out.String(), `"id":"s_`)
|
||||
assert.Equal(t, 5, got, "--limit 5 must slice 20 items down to 5")
|
||||
}
|
||||
@@ -226,7 +226,7 @@ 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))
|
||||
&ListOptions{PageSize: 10, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
got := strings.Count(out.String(), `"id":"s_`)
|
||||
assert.Equal(t, 10, got)
|
||||
}
|
||||
@@ -234,7 +234,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}, nil,
|
||||
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -246,7 +246,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.JSONOptions{}, svc))
|
||||
&ListOptions{PageSize: 20, AllPages: true}, &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)
|
||||
@@ -256,7 +256,7 @@ 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))
|
||||
&ListOptions{PageSize: 20, AllPages: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, 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")
|
||||
|
||||
+10
-9
@@ -17,7 +17,7 @@ const (
|
||||
maxFullLimit = 1000
|
||||
)
|
||||
|
||||
// sessionViewFields enumerates the fields surfaced for `--json` discovery on
|
||||
// sessionViewFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `session view`. Mirrors sdk.Session json tags; adds the synthesized
|
||||
// `messages` projection surfaced by `--full`.
|
||||
var sessionViewFields = []string{
|
||||
@@ -53,7 +53,7 @@ type ViewService interface {
|
||||
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ViewOptions{Limit: defaultFullLimit}
|
||||
cmd := &cobra.Command{
|
||||
Use: "view <id>",
|
||||
Use: "view <session-id>",
|
||||
Short: "Show a chat session by ID",
|
||||
Long: `Show a chat session.
|
||||
|
||||
@@ -65,24 +65,25 @@ Pass --full to also load the chat history (LoadMessages SDK call). Use
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.LimitSet = c.Flags().Changed("limit")
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runView(c.Context(), opts, jopts, cli, args[0])
|
||||
return runView(c.Context(), opts, fopts, cli, args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.Full, "full", false, "Also load chat history via LoadMessages")
|
||||
cmd.Flags().IntVar(&opts.Limit, "limit", defaultFullLimit, "Max messages to load when --full is set (1..1000)")
|
||||
cmdutil.AddJSONFlags(cmd, sessionViewFields)
|
||||
cmdutil.AddFormatFlag(cmd, sessionViewFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions, svc ViewService, id string) error {
|
||||
func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOptions, svc ViewService, id string) error {
|
||||
if !opts.Full && opts.LimitSet {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
@@ -114,9 +115,9 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
}
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
if fopts.WantsJSON() {
|
||||
if !opts.Full {
|
||||
return jopts.Emit(iostreams.IO.Out, s)
|
||||
return fopts.Emit(iostreams.IO.Out, s)
|
||||
}
|
||||
// Project session + messages into a single bare object. Use the
|
||||
// SDK json tags via an embedded *Session so existing keys stay
|
||||
@@ -125,7 +126,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
*sdk.Session
|
||||
Messages []sdk.Message `json:"messages"`
|
||||
}{Session: s, Messages: msgs}
|
||||
return jopts.Emit(iostreams.IO.Out, payload)
|
||||
return fopts.Emit(iostreams.IO.Out, payload)
|
||||
}
|
||||
|
||||
w := iostreams.IO.Out
|
||||
|
||||
@@ -50,7 +50,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{}, nil, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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)
|
||||
@@ -61,7 +61,7 @@ func TestView_Human(t *testing.T) {
|
||||
func TestView_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s_abc", Title: "T", UpdatedAt: "2026-05-12T14:00:00Z"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.JSONOptions{}, svc, "s_abc"))
|
||||
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)
|
||||
@@ -71,7 +71,7 @@ func TestView_JSON(t *testing.T) {
|
||||
func TestView_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{}, nil, svc, "s_missing")
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -81,7 +81,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{}, nil, svc, "s_min"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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 +101,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}, nil, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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 +117,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}, nil, svc, "s_empty"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_empty"))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "Messages (0)")
|
||||
}
|
||||
@@ -125,7 +125,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}, nil, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -133,7 +133,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}, nil, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -143,7 +143,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}, nil, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
assert.Contains(t, err.Error(), "--limit")
|
||||
@@ -158,7 +158,7 @@ func TestView_Full_JSON_HasMessages(t *testing.T) {
|
||||
{ID: "m1", Role: "user", Content: "hi"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.JSONOptions{}, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "s_abc"))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"messages":`)
|
||||
assert.Contains(t, body, `"id":"m1"`)
|
||||
@@ -170,7 +170,7 @@ func TestView_Full_JSON_HasMessages(t *testing.T) {
|
||||
func TestView_NoFull_DoesNotCallLoadMessages(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s_abc"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.JSONOptions{}, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "s_abc"))
|
||||
assert.False(t, svc.loadCall.called, "LoadMessages must not be called without --full")
|
||||
assert.NotContains(t, out.String(), `"messages":`)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user