feat(cli): session subtree + kb edit / pin / empty

Roadmap items 3-5 (session) and 3-6/7/8 (kb manage).

cli/cmd/session/ (new package; sessioncmd to avoid shadowing stdlib):
- session list: paginated table (ID/TITLE/UPDATED). --page / --page-size
  with 1..1000 validation. _meta.has_more from page*size < total.
- session view <id>: prints metadata; non-empty fields only. Server
  timestamps arrive as strings; parsed best-effort as RFC3339.
- session delete <id>: high-risk-write; exit-10 confirmation in non-
  TTY/--json paths; --dry-run emits envelope.risk + dry_run:true.

cli/cmd/kb (extended):
- kb edit <id> [--name N] [--description D]: at least one flag required;
  *string options so unset fields stay unset in the PUT body. SDK
  UpdateKnowledgeBaseRequest has no embedding_model field, so the
  roadmap's --embedding-model dropped.
- kb pin <id> / kb unpin <id>: direct parity with gh issue pin /
  gh issue unpin (verified against gh manual). Idempotent: GetKnowledgeBase
  reads IsPinned, TogglePinKnowledgeBase fires only on state change.
  SDK KnowledgeBase struct gained the IsPinned field (server already
  returned it; SDK just hadn't modeled it — non-breaking additive).
- kb empty <id>: high-risk-write; exit-10 confirmation;
  --dry-run. Returns deleted_count from the async clear response.
  weknora-specific operation; no mainstream parallel.

Golden envelopes for kb_list and kb_view updated to include the new
is_pinned field — strict-additive change.

Cleanups surfaced by the post-commit reviewer round:
- ConfirmPrompter promoted to cli/internal/testutil/ (4-copy threshold
  reached: context/remove, kb/delete, kb/empty, session/delete).
  kb/delete_test.go's pre-existing local copy left untouched per the
  upstream-respect convention.
- kb pin/unpin idempotent no-op path no longer emits a write-class
  envelope. Added _meta.warnings "already {un}pinned — no server
  call made" and dropped the risk classification on the no-op branch.
- doc list --page-size was unbounded while session list enforces
  1..1000. Same validation added to doc list.

18 + 18 unit tests; e2e exit codes verified.

Roadmap: 3-5, 3-6, 3-7, 3-8.
This commit is contained in:
nullkey
2026-05-12 23:34:33 +08:00
committed by lyingbug
parent 4c26bc9ecc
commit 2f8681b48e
21 changed files with 1338 additions and 30 deletions
+96
View File
@@ -0,0 +1,96 @@
package sessioncmd
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
)
// DeleteOptions captures `weknora session delete` flag state. Yes is
// sourced from the global -y/--yes persistent flag (gh-style).
type DeleteOptions struct {
Yes bool
JSONOut bool
DryRun bool
}
// DeleteService is the narrow SDK surface this command depends on.
type DeleteService interface {
DeleteSession(ctx context.Context, id string) error
}
// deleteResult is the typed payload emitted under data on success.
type deleteResult struct {
ID string `json:"id"`
Deleted bool `json:"deleted"`
}
// NewCmdDelete builds `weknora session delete`. Mirrors `gh issue delete`:
// destructive write gated by -y/--yes (exit-10 protocol in scripted /
// --json invocations).
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.
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).
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10 and
returns an envelope describing the missing confirmation. 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),
RunE: func(c *cobra.Command, args []string) error {
opts.Yes, _ = c.Flags().GetBool("yes")
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runDelete(c.Context(), opts, nil, f.Prompter(), args[0])
}
cli, err := f.Client()
if err != nil {
return err
}
return runDelete(c.Context(), opts, cli, f.Prompter(), args[0])
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Destructively deletes a chat session by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
return cmd
}
func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p prompt.Prompter, id string) error {
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete session %s", id)}
if opts.DryRun {
return cmdutil.EmitDryRun(opts.JSONOut,
deleteResult{ID: id, Deleted: false}, nil, risk)
}
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "session", id); err != nil {
return err
}
if err := svc.DeleteSession(ctx, id); err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete session %s", id)
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
deleteResult{ID: id, Deleted: true}, nil, risk,
))
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted session %s\n", id)
return nil
}
+94
View File
@@ -0,0 +1,94 @@
package sessioncmd
import (
"context"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/testutil"
)
// fakeDeleteSvc records what id was deleted.
type fakeDeleteSvc struct {
err error
gotID string
called bool
}
func (f *fakeDeleteSvc) DeleteSession(_ context.Context, id string) error {
f.called = true
f.gotID = id
return f.err
}
func TestDelete_WithYes(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, 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")
assert.Contains(t, out.String(), "Deleted")
}
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}, svc, &testutil.ConfirmPrompter{}, "s_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
}
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{}, svc, &testutil.ConfirmPrompter{}, "s_x")
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.False(t, svc.called, "non-TTY without -y must not call DeleteSession")
}
func TestDelete_TTY_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, svc, p, "s_yes"))
assert.True(t, p.Asked)
assert.True(t, svc.called)
}
func TestDelete_TTY_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "s_no")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)
assert.False(t, svc.called)
assert.Contains(t, errBuf.String(), "Aborted")
}
func TestDelete_DryRun_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{DryRun: true, JSONOut: true}, svc, &testutil.ConfirmPrompter{}, "s_dry"))
body := out.String()
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
assert.Contains(t, body, `"dry_run":true`)
assert.Contains(t, body, `"high-risk-write"`)
assert.False(t, svc.called, "dry-run must not call SDK")
}
+122
View File
@@ -0,0 +1,122 @@
package sessioncmd
import (
"context"
"fmt"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
)
const (
defaultPage = 1
defaultPageSize = 30
maxPageSize = 1000
)
// ListOptions captures `weknora session list` flags.
type ListOptions struct {
Page int
PageSize int
JSONOut bool
}
// ListService is the narrow SDK surface this command depends on.
type ListService interface {
GetSessionsByTenant(ctx context.Context, page, pageSize int) ([]sdk.Session, int, error)
}
// listResult is the typed payload emitted under data.
type listResult struct {
Items []sdk.Session `json:"items"`
}
// NewCmdList builds `weknora session list`. Paginated; defaults to page=1
// page_size=30. Mirrors `gh issue list` shape (no cursor — server is
// page-based today).
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{Page: defaultPage, PageSize: defaultPageSize}
cmd := &cobra.Command{
Use: "list",
Short: "List chat sessions for the active context",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
cli, err := f.Client()
if err != nil {
return err
}
return runList(c.Context(), opts, cli)
},
}
cmd.Flags().IntVar(&opts.Page, "page", defaultPage, "Page number (1-indexed)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", defaultPageSize, "Items per page (1..1000)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Lists chat sessions. _meta.has_more is set when more pages exist; bump --page and retry to walk them.")
return cmd
}
func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
if opts.Page < 1 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--page must be >= 1, got %d", opts.Page),
}
}
if opts.PageSize < 1 || opts.PageSize > maxPageSize {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--page-size must be in 1..%d, got %d", maxPageSize, opts.PageSize),
}
}
items, total, err := svc.GetSessionsByTenant(ctx, opts.Page, opts.PageSize)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list sessions")
}
if items == nil {
items = []sdk.Session{} // JSON [] not null
}
if opts.JSONOut {
meta := &format.Meta{HasMore: opts.Page*opts.PageSize < total}
return format.WriteEnvelope(iostreams.IO.Out, format.Success(listResult{Items: items}, meta))
}
if len(items) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no sessions)")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tTITLE\tUPDATED")
now := time.Now()
for _, s := range items {
title := text.Truncate(50, s.Title)
if title == "" {
title = "-"
}
fmt.Fprintf(tw, "%s\t%s\t%s\n", s.ID, title, fuzzyTime(now, s.UpdatedAt))
}
return tw.Flush()
}
// fuzzyTime renders a server-provided timestamp string in `gh`-style "2d
// ago" form. Returns the raw input if parsing fails — better to surface
// the unknown format than to silently render "-".
func fuzzyTime(now time.Time, ts string) string {
if ts == "" {
return "-"
}
t, err := time.Parse(time.RFC3339, ts)
if err != nil {
return ts
}
return text.FuzzyAgo(now, t)
}
+140
View File
@@ -0,0 +1,140 @@
package sessioncmd
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeListService scripts a GetSessionsByTenant response.
type fakeListService struct {
items []sdk.Session
total int
err error
gotPage int
gotPageSize int
}
func (f *fakeListService) GetSessionsByTenant(_ context.Context, page, pageSize int) ([]sdk.Session, int, error) {
f.gotPage = page
f.gotPageSize = pageSize
return f.items, f.total, f.err
}
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc))
assert.Contains(t, out.String(), "no sessions")
}
func TestList_Table(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{
items: []sdk.Session{
{ID: "s_1", Title: "Design review", CreatedAt: "2026-05-10T09:00:00Z", UpdatedAt: "2026-05-12T14:00:00Z"},
{ID: "s_2", Title: "RAG bug repro", CreatedAt: "2026-05-09T08:00:00Z", UpdatedAt: "2026-05-11T11:00:00Z"},
},
total: 2,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc))
got := out.String()
assert.Contains(t, got, "s_1")
assert.Contains(t, got, "Design review")
assert.Contains(t, got, "s_2")
assert.Equal(t, 1, svc.gotPage)
assert.Equal(t, 30, svc.gotPageSize)
}
func TestList_JSON_WithMeta(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{
items: []sdk.Session{
{ID: "s_1", Title: "T1", UpdatedAt: "2026-05-12T14:00:00Z"},
},
total: 47,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10, JSONOut: true}, svc))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
require.True(t, env.OK)
// Pagination flags are forwarded.
assert.Equal(t, 2, svc.gotPage)
assert.Equal(t, 10, svc.gotPageSize)
// envelope.data.items shaped + paging metadata in _meta
body := out.String()
assert.Contains(t, body, `"id":"s_1"`)
assert.Contains(t, body, `"items":`)
// has_more inferred from page*pageSize < total (2*10=20 < 47).
assert.Contains(t, body, `"has_more":true`)
}
func TestList_JSON_LastPage_NoHasMore(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{
items: []sdk.Session{{ID: "s_1"}},
total: 11,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10, JSONOut: true}, svc))
// page*size = 20 ≥ total 11 → has_more must be false (omitempty drops the key)
body := out.String()
assert.NotContains(t, body, `"has_more":true`)
}
func TestList_NilItems_RendersAsEmptyArray(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30, JSONOut: true}, svc))
assert.Contains(t, out.String(), `"items":[]`)
}
func TestList_BadPagination(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cases := []struct {
page, size int
name string
}{
{0, 30, "page < 1"},
{-1, 30, "page negative"},
{1, 0, "size < 1"},
{1, 1001, "size > max"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := runList(context.Background(), &ListOptions{Page: tc.page, PageSize: tc.size}, &fakeListService{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
})
}
}
func TestList_NetworkError_TypedCode(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListService{err: errors.New("HTTP error 401: unauthenticated")}
err := runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
}
// Sanity: title with multi-rune content (CJK) should not crash truncation.
func TestList_NonASCIITitle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: []sdk.Session{{ID: "s_zh", Title: strings.Repeat("中文", 50)}}, total: 1}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc))
assert.Contains(t, out.String(), "s_zh")
}
+27
View File
@@ -0,0 +1,27 @@
// Package sessioncmd holds `weknora session` command tree (list / view /
// delete). Mirrors `gh issue list/view/delete` for chat history.
//
// Package name `sessioncmd` (not `session`) so callers can `import sdk
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
// shadowing — same hygiene as `contextcmd`.
package sessioncmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// NewCmd builds the `weknora session` parent command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "session",
Short: "Manage chat sessions",
Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
}
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdView(f))
cmd.AddCommand(NewCmdDelete(f))
return cmd
}
+88
View File
@@ -0,0 +1,88 @@
package sessioncmd
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// ViewOptions captures `weknora session view` flags.
type ViewOptions struct {
JSONOut bool
}
// ViewService is the narrow SDK surface this command depends on.
type ViewService interface {
GetSession(ctx context.Context, id string) (*sdk.Session, error)
}
// NewCmdView builds `weknora session view <id>`. Mirrors `gh issue view`.
// The server endpoint returns metadata only (title/description/timestamps);
// message content lives under a separate session_messages endpoint that the
// SDK doesn't currently wrap, which is why there's no --full flag.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{}
cmd := &cobra.Command{
Use: "view <id>",
Short: "Show a chat session by ID",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
cli, err := f.Client()
if err != nil {
return err
}
return runView(c.Context(), opts, cli, args[0])
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Shows a chat session's metadata (title, description, timestamps). Errors with resource.not_found if id is unknown.")
return cmd
}
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
s, err := svc.GetSession(ctx, id)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get session %q", id)
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(s, nil))
}
w := iostreams.IO.Out
fmt.Fprintf(w, "ID: %s\n", s.ID)
if s.Title != "" {
fmt.Fprintf(w, "TITLE: %s\n", s.Title)
}
if s.Description != "" {
fmt.Fprintf(w, "DESC: %s\n", s.Description)
}
if t, ok := parseTS(s.CreatedAt); ok {
fmt.Fprintf(w, "CREATED: %s\n", t.Format("2006-01-02 15:04:05"))
} else if s.CreatedAt != "" {
fmt.Fprintf(w, "CREATED: %s\n", s.CreatedAt)
}
if t, ok := parseTS(s.UpdatedAt); ok {
fmt.Fprintf(w, "UPDATED: %s\n", t.Format("2006-01-02 15:04:05"))
} else if s.UpdatedAt != "" {
fmt.Fprintf(w, "UPDATED: %s\n", s.UpdatedAt)
}
return nil
}
func parseTS(s string) (time.Time, bool) {
if s == "" {
return time.Time{}, false
}
t, err := time.Parse(time.RFC3339, s)
if err != nil {
return time.Time{}, false
}
return t, true
}
+80
View File
@@ -0,0 +1,80 @@
package sessioncmd
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeViewService scripts a GetSession response.
type fakeViewService struct {
s *sdk.Session
err error
gotID string
}
func (f *fakeViewService) GetSession(_ context.Context, id string) (*sdk.Session, error) {
f.gotID = id
return f.s, f.err
}
func TestView_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{
ID: "s_abc",
Title: "Design review",
Description: "RAG chunking strategy review",
CreatedAt: "2026-05-10T09:00:00Z",
UpdatedAt: "2026-05-12T14:00:00Z",
}}
require.NoError(t, runView(context.Background(), &ViewOptions{}, 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)
}
assert.Equal(t, "s_abc", svc.gotID)
}
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{JSONOut: true}, svc, "s_abc"))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
require.True(t, env.OK)
body := out.String()
assert.Contains(t, body, `"id":"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{}, svc, "s_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
}
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{}, 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:") {
t.Errorf("empty description should be omitted, found %q", line)
}
}
}