feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING)
D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
This commit is contained in:
@@ -102,7 +102,7 @@ func emitAgentCheck(res *AgentCheckResult, fopts *cmdutil.FormatOptions, w io.Wr
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
case cmdutil.FormatText, "":
|
||||
return writeAgentCheckText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent check", fopts.Mode)
|
||||
|
||||
@@ -138,11 +138,11 @@ func TestEmitAgentCheck_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitAgentCheck_TextHuman(t *testing.T) {
|
||||
func TestEmitAgentCheck_Text(t *testing.T) {
|
||||
trueP := true
|
||||
var buf bytes.Buffer
|
||||
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
@@ -292,7 +292,7 @@ func openConfigFile(path string) (io.Reader, string, error) {
|
||||
}
|
||||
|
||||
// emitAgent writes the Agent to stdout (bare SDK shape for --format json,
|
||||
// human KV otherwise). Shared by create and edit; defined here for proximity
|
||||
// text KV otherwise). Shared by create and edit; defined here for proximity
|
||||
// to the create flow.
|
||||
func emitAgent(fopts *cmdutil.FormatOptions, ag *sdk.Agent) error {
|
||||
if fopts.WantsJSON() {
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestDelete_NonTTY_WithYes_Direct(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc", Yes: true},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
))
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
assert.Contains(t, out.String(), "ag_abc")
|
||||
@@ -56,7 +56,7 @@ func TestDelete_404_PropagatesNotFound(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_missing", Yes: true},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -71,7 +71,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
@@ -84,7 +84,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
||||
@@ -257,7 +257,7 @@ func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
pf := root.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "")
|
||||
pf.String("format", "", "Output format: human | json | ndjson")
|
||||
pf.String("format", "", "Output format: text | json | ndjson")
|
||||
pf.StringP("jq", "q", "", "")
|
||||
ag := &cobra.Command{Use: "agent"}
|
||||
ag.AddCommand(edit)
|
||||
|
||||
@@ -23,9 +23,9 @@ func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
|
||||
return f.items, f.err
|
||||
}
|
||||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
func TestList_Empty_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no agents)") {
|
||||
@@ -53,14 +53,14 @@ func TestList_Empty_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_NonEmpty_Human_RendersColumns(t *testing.T) {
|
||||
func TestList_NonEmpty_Text_RendersColumns(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
now := time.Now()
|
||||
items := []sdk.Agent{
|
||||
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -162,7 +162,7 @@ func TestList_Limit_Zero_Rejected(t *testing.T) {
|
||||
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeAgents(2)})
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeAgents(2)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative --limit")
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ func emitAgentStatus(res *AgentStatusResult, fopts *cmdutil.FormatOptions, w io.
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
case cmdutil.FormatText, "":
|
||||
return writeAgentStatusText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent status", fopts.Mode)
|
||||
|
||||
@@ -93,10 +93,10 @@ func TestEmitAgentStatus_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitAgentStatus_TextHuman(t *testing.T) {
|
||||
func TestEmitAgentStatus_Text(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func (f *fakeViewSvc) GetAgent(_ context.Context, _ string) (*sdk.Agent, error)
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
|
||||
func TestView_Text_RendersMetadataAndConfig(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{resp: &sdk.Agent{
|
||||
ID: "ag_abc",
|
||||
@@ -41,7 +41,7 @@ func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
|
||||
WebSearchEnabled: true,
|
||||
},
|
||||
}}
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_abc"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -69,7 +69,7 @@ func TestAgentViewFields_TopLevelOnly(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestRenderAgent_RendersAllGroupsWithOmitEmpty validates the grouped
|
||||
// human rendering: present groups print, zero-value fields omit, and an
|
||||
// text rendering: present groups print, zero-value fields omit, and an
|
||||
// entire section is suppressed when all of its fields are zero.
|
||||
func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
@@ -84,7 +84,7 @@ func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"kb_a"},
|
||||
FAQPriorityEnabled: true,
|
||||
WebSearchEnabled: false, // zero — omitted in human
|
||||
WebSearchEnabled: false, // zero — omitted in text
|
||||
FallbackStrategy: "fixed",
|
||||
FallbackResponse: "I don't know.",
|
||||
},
|
||||
@@ -118,7 +118,7 @@ func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
func TestView_Text_OmitsEmptyFields(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{resp: &sdk.Agent{
|
||||
ID: "ag_min",
|
||||
@@ -126,7 +126,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}}
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_min"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_min"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -169,7 +169,7 @@ func TestView_JSON_BareObject(t *testing.T) {
|
||||
func TestView_404_MapsToResourceNotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_missing")
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestAPI_GetSuccess(t *testing.T) {
|
||||
})
|
||||
defer stop()
|
||||
|
||||
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/foo", false); err != nil {
|
||||
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -119,7 +119,7 @@ func TestAPI_PostWithStdinInput(t *testing.T) {
|
||||
defer stop()
|
||||
|
||||
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/things", false); err != nil {
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/things", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
if seenMethod != http.MethodPost || seenPath != "/api/v1/things" {
|
||||
@@ -146,7 +146,7 @@ func TestAPI_InputFile(t *testing.T) {
|
||||
defer stop()
|
||||
|
||||
opts := &Options{Input: tmp}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
if string(seenBody) != payload {
|
||||
@@ -167,7 +167,7 @@ func TestAPI_InputDash_Stdin(t *testing.T) {
|
||||
|
||||
payload := `{"k":"from-stdin"}`
|
||||
opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
if string(seenBody) != payload {
|
||||
@@ -183,7 +183,7 @@ func TestAPI_NotFound(t *testing.T) {
|
||||
})
|
||||
defer stop()
|
||||
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/missing", false)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for 404")
|
||||
}
|
||||
@@ -203,7 +203,7 @@ func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
|
||||
for _, m := range []string{"OPTIONS", "PATCH", "TRACE", "CUSTOM"} {
|
||||
t.Run(m, func(t *testing.T) {
|
||||
seenMethod = ""
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, m, "/api/v1/things", false)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, m, "/api/v1/things", false)
|
||||
if err != nil {
|
||||
t.Fatalf("expected method %q to be accepted, got %v", m, err)
|
||||
}
|
||||
@@ -216,7 +216,7 @@ func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
|
||||
|
||||
func TestAPI_EmptyMethodRejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "", "/api/v1/things", false)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "", "/api/v1/things", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty method")
|
||||
}
|
||||
@@ -228,7 +228,7 @@ func TestAPI_EmptyMethodRejected(t *testing.T) {
|
||||
|
||||
func TestAPI_PathWithoutSlash(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "GET", "api/v1/things", false)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "GET", "api/v1/things", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing leading slash")
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
|
||||
Context: "ci",
|
||||
APIKey: "sk-zzz",
|
||||
}
|
||||
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
|
||||
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
v, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-zzz", v)
|
||||
cfg, _ := f.Config()
|
||||
|
||||
@@ -19,7 +19,7 @@ func newListFactory(cfg *config.Config) *cmdutil.Factory {
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_HumanRender(t *testing.T) {
|
||||
func TestList_TextRender(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "prod",
|
||||
@@ -28,7 +28,7 @@ func TestList_HumanRender(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(cfg)))
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(cfg)))
|
||||
|
||||
got := out.String()
|
||||
// One row per context, current marked with `*`.
|
||||
@@ -44,7 +44,7 @@ func TestList_HumanRender(t *testing.T) {
|
||||
|
||||
func TestList_Empty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(&config.Config{})))
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(&config.Config{})))
|
||||
assert.Contains(t, out.String(), "No profiles configured")
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestRunLogin_PasswordMode(t *testing.T) {
|
||||
Host: "https://kb.example.com",
|
||||
Context: "prod",
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
|
||||
|
||||
assert.Equal(t, "a@b.c", svc.got.email)
|
||||
assert.Equal(t, "secret", svc.got.password)
|
||||
@@ -84,7 +84,7 @@ func TestRunLogin_WithToken(t *testing.T) {
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(" sk-1234 \n"),
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
got, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-1234", got)
|
||||
cfg, _ := f.Config()
|
||||
@@ -107,7 +107,7 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader("sk-bad"),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -139,7 +139,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(""),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.missing_flag")
|
||||
}
|
||||
@@ -147,7 +147,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
func TestRunLogin_BadHost(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func TestRunLogin_LoginRefused(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "x"})
|
||||
svc := &fakeLoginService{resp: &sdk.LoginResponse{Success: false, Message: "bad password"}}
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc)
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "auth.bad_credential")
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestLogout_CurrentContext(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Empty(t, cfg.CurrentContext, "current_context should clear when removed")
|
||||
assert.NotContains(t, cfg.Contexts, "prod")
|
||||
@@ -75,7 +75,7 @@ func TestLogout_NamedContext(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Equal(t, "prod", cfg.CurrentContext, "current_context untouched when removing other")
|
||||
assert.NotContains(t, cfg.Contexts, "staging")
|
||||
@@ -93,7 +93,7 @@ func TestLogout_All(t *testing.T) {
|
||||
"staging": {Host: "https://staging"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Empty(t, cfg.Contexts)
|
||||
assert.Empty(t, cfg.CurrentContext)
|
||||
@@ -103,7 +103,7 @@ func TestLogout_NoContexts(t *testing.T) {
|
||||
isolateConfig(t)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cfg := &config.Config{}
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -117,7 +117,7 @@ func TestLogout_UnknownName(t *testing.T) {
|
||||
CurrentContext: "prod",
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -130,7 +130,7 @@ func TestLogout_NoCurrentNoFlag(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestRefresh_Happy(t *testing.T) {
|
||||
AccessToken: "new-access",
|
||||
RefreshToken: "new-refresh",
|
||||
}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
|
||||
gotAccess, _ := store.Get("prod", "access")
|
||||
@@ -97,7 +97,7 @@ func TestRefresh_NamedContext(t *testing.T) {
|
||||
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
|
||||
Success: true, AccessToken: "new-stg-access", RefreshToken: "new-stg-refresh",
|
||||
}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging context, not current")
|
||||
// current is untouched
|
||||
@@ -109,7 +109,7 @@ func TestRefresh_NamedContext(t *testing.T) {
|
||||
func TestRefresh_NoCurrentContext(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f := newRefreshFactory(t, &config.Config{}, secrets.NewMemStore())
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -125,7 +125,7 @@ func TestRefresh_APIKeyContext(t *testing.T) {
|
||||
Contexts: map[string]config.Context{"ci": {Host: "https://kb", APIKeyRef: "mem://ci/api_key"}},
|
||||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -143,7 +143,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
|
||||
}
|
||||
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
|
||||
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -161,7 +161,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
|
||||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: false, Message: "refresh token expired"}}
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -184,7 +184,7 @@ func TestRefresh_TransportError(t *testing.T) {
|
||||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
svc := &fakeRefreshService{err: errors.New("connection reset")}
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
@@ -33,7 +33,7 @@ func newCurrentUserResponse(user *sdk.AuthUser, tenant *sdk.AuthTenant) *sdk.Cur
|
||||
return r
|
||||
}
|
||||
|
||||
func TestRunStatus_HumanOutput(t *testing.T) {
|
||||
func TestRunStatus_TextOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{
|
||||
@@ -52,7 +52,7 @@ func TestRunStatus_HumanOutput(t *testing.T) {
|
||||
&sdk.AuthTenant{ID: 7, Name: "Acme"},
|
||||
),
|
||||
}
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "profile: prod")
|
||||
assert.Contains(t, got, "host: https://kb.example.com")
|
||||
@@ -83,7 +83,7 @@ func TestRunStatus_JSONOutput(t *testing.T) {
|
||||
|
||||
func TestRunStatus_NoSDKClient(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &cmdutil.Factory{}, nil)
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &cmdutil.Factory{}, nil)
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
|
||||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
|
||||
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: assert.AnError})
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: assert.AnError})
|
||||
require.Error(t, err)
|
||||
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
|
||||
// classify network.error so retry logic / exit code 7 / IsTransient apply.
|
||||
@@ -105,7 +105,7 @@ func TestRunStatus_SDKError_HTTP401(t *testing.T) {
|
||||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
|
||||
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
|
||||
_ = store.Set("prod", "access", "jwt-token-xyz")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func TestAuthToken_APIKeyMode_PlainOutput(t *testing.T) {
|
||||
_ = store.Set("ci", "api_key", "sk_test_apikey_42")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "sk_test_apikey_42" {
|
||||
@@ -129,7 +129,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
store := secrets.NewMemStore()
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
@@ -154,7 +154,7 @@ func TestAuthToken_ProfileOverride(t *testing.T) {
|
||||
f.ProfileOverride = "staging"
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "staging-key" {
|
||||
@@ -172,7 +172,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
|
||||
store := secrets.NewMemStore()
|
||||
// no Set - keyring is empty
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected auth.unauthenticated, got nil")
|
||||
}
|
||||
@@ -190,7 +190,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
|
||||
}
|
||||
store := secrets.NewMemStore()
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected auth.unauthenticated, got nil")
|
||||
}
|
||||
@@ -234,7 +234,7 @@ func makeAPIKeyCfg() (*config.Config, *secrets.MemStore) {
|
||||
func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
|
||||
cfg, store := makeBearerCfg()
|
||||
out, errBuf := iostreams.SetForTest(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "jwt-xyz" {
|
||||
@@ -248,7 +248,7 @@ func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
|
||||
func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
|
||||
cfg, store := makeBearerCfg()
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "jwt-xyz" {
|
||||
@@ -265,7 +265,7 @@ func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
|
||||
func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
|
||||
cfg, store := makeAPIKeyCfg()
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "sk_42" {
|
||||
|
||||
+82
-98
@@ -3,15 +3,16 @@
|
||||
//
|
||||
// Two output modes share a single SDK call:
|
||||
//
|
||||
// - Stream mode (TTY + text format): write each StreamResponse.Content
|
||||
// - Stream mode (TTY + --format text): write each StreamResponse.Content
|
||||
// fragment directly to iostreams.IO.Out as it arrives, then print a
|
||||
// footer with knowledge references. This is the "feels alive" UX a
|
||||
// human typing in a terminal expects.
|
||||
//
|
||||
// - Accumulate mode (--format json / pipe): buffer every fragment via
|
||||
// sse.Accumulator and emit a single JSON object (or a single plain-text
|
||||
// answer + references block) once Done. Agents and pipes get a
|
||||
// deterministic single record to parse.
|
||||
// - NDJSON mode (--format json / --format ndjson / pipe): inject a CLI
|
||||
// "init" event at stream head, then pass through every SDK event verbatim
|
||||
// as NDJSON lines. Agents and pipes get a live event stream they can
|
||||
// parse incrementally. --format json routes here too — buffered JSON
|
||||
// envelope makes no sense for a streaming command (§5).
|
||||
//
|
||||
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
|
||||
// one goroutine, so neither mode needs locking. The runChat core takes a
|
||||
@@ -21,8 +22,6 @@ package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -31,15 +30,18 @@ import (
|
||||
"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/output"
|
||||
"github.com/Tencent/WeKnora/cli/internal/sse"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// chatFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `chat`. Mirrors the chatData struct json tags.
|
||||
// chatFields enumerates the NDJSON init-event fields surfaced for
|
||||
// `--format json` / `--format ndjson` discovery on `chat`. Reflects the
|
||||
// InitEvent head line + the raw SDK event vocabulary (§5).
|
||||
var chatFields = []string{
|
||||
"answer", "references", "thinking",
|
||||
"session_id", "assistant_message_id", "kb_id", "query",
|
||||
"session_id", "kb_id",
|
||||
// SDK event fields (pass-through): response_type, content, done,
|
||||
// knowledge_references, assistant_message_id, session_id
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
@@ -56,23 +58,6 @@ type ChatService interface {
|
||||
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error) error
|
||||
}
|
||||
|
||||
// chatData is the JSON payload emitted on the JSON path. Mirrors what an
|
||||
// agent needs to continue a conversation: the answer text, retrieval
|
||||
// references, and the session pointer to thread follow-ups.
|
||||
type chatData struct {
|
||||
Answer string `json:"answer"`
|
||||
References []*sdk.SearchResult `json:"references"`
|
||||
// Thinking holds the reasoning / reflection text emitted by reasoning
|
||||
// models via response_type=thinking frames. Omitted when empty
|
||||
// (non-reasoning model or model didn't surface reasoning for this
|
||||
// query).
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
AssistantMessageID string `json:"assistant_message_id,omitempty"`
|
||||
KBID string `json:"kb_id"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
|
||||
// NewCmd builds `weknora chat <text>`.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &Options{}
|
||||
@@ -84,8 +69,12 @@ answer back. By default a fresh session is created on first invocation; pass
|
||||
--session to continue an existing conversation.
|
||||
|
||||
Modes:
|
||||
TTY (text format, default): live token streaming + reference footer
|
||||
--format json / pipe: buffered, emitted once on completion`,
|
||||
--format text: live token streaming + reference footer
|
||||
--format json / --format ndjson / pipe (default): NDJSON event stream —
|
||||
one init line at head (session_id, kb_id),
|
||||
then raw SDK events verbatim. Both json
|
||||
and ndjson flags produce the same NDJSON
|
||||
stream (§5).`,
|
||||
Example: ` weknora chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694
|
||||
weknora chat "Summarise this design doc" --kb my-kb --format json
|
||||
weknora chat "Continue?" --session sess_abc`,
|
||||
@@ -116,10 +105,10 @@ Modes:
|
||||
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
|
||||
cmdutil.AddFormatFlag(cmd, chatFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Ask a streaming RAG question against a knowledge base and get a single answer + cited chunks. Agents should use --format json for parseable output.",
|
||||
UsedFor: "Ask a streaming RAG question against a knowledge base. Produces an NDJSON event stream: init line (session_id, kb_id) then raw SDK events. Use --format json or --format ndjson.",
|
||||
RequiredFlags: []string{"--kb"},
|
||||
Examples: []string{`weknora chat "What is RRF?" --kb kb_abc --format json`},
|
||||
Output: "answer / references / session_id / thinking — see chatData struct (chat.go)",
|
||||
Output: "NDJSON stream: {type:init, session_id, kb_id} then SDK events (response_type, content, done, knowledge_references, ...)",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
@@ -139,7 +128,10 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
return cmdutil.NewError(cmdutil.CodeServerError, "chat: no SDK client available")
|
||||
}
|
||||
|
||||
jsonOut := fopts != nil && fopts.Mode == cmdutil.FormatJSON
|
||||
// Streaming commands route --format json AND --format ndjson to the
|
||||
// NDJSON event-stream path. A buffered envelope makes no sense for a
|
||||
// streaming command (§5). Only --format text uses the live renderer.
|
||||
ndjsonMode := fopts != nil && (fopts.Mode == cmdutil.FormatJSON || fopts.Mode == cmdutil.FormatNDJSON)
|
||||
|
||||
sessionID := opts.SessionID
|
||||
autoCreated := false
|
||||
@@ -149,7 +141,7 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
// Ctrl-C during session creation: classify as cancelled so the
|
||||
// hint nudges the user toward retry-with-signal-clean, not
|
||||
// "pass --session" as session_create_failed would.
|
||||
if isCancelled(ctx, err) {
|
||||
if cmdutil.IsCancelled(ctx, err) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
|
||||
}
|
||||
// Map HTTP-shaped failures, but tag generic transport / unknown
|
||||
@@ -164,21 +156,40 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
autoCreated = true
|
||||
}
|
||||
|
||||
// Decide output mode. Stream mode requires:
|
||||
// 1. an interactive stdout (tty)
|
||||
// 2. no --format json (JSON output is single-record by definition)
|
||||
// 3. no --format ndjson (handled by the early-return branch below)
|
||||
streamMode := iostreams.IO.IsStdoutTTY() && !jsonOut &&
|
||||
(fopts == nil || fopts.Mode != cmdutil.FormatNDJSON)
|
||||
if ndjsonMode {
|
||||
return runChatNDJSON(ctx, opts, sessionID, svc)
|
||||
}
|
||||
|
||||
// Surface the auto-created session ID up-front so a user who hits ^C
|
||||
// mid-stream still has the pointer to resume - no need to scroll back
|
||||
// past tokens. Skipped in JSON mode (it ends up in the data object) and
|
||||
// when the caller already supplied --session.
|
||||
if autoCreated && !jsonOut {
|
||||
// past tokens. Skipped in NDJSON mode (it appears in the init event).
|
||||
if autoCreated {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
|
||||
}
|
||||
|
||||
return runChatText(ctx, opts, sessionID, autoCreated, svc)
|
||||
}
|
||||
|
||||
// runChatNDJSON handles --format json and --format ndjson paths.
|
||||
// Emits a CLI init event at stream head, then passes every SDK event through
|
||||
// verbatim as NDJSON lines. No buffering — callers parse the stream
|
||||
// incrementally (§5).
|
||||
func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc ChatService) error {
|
||||
w := iostreams.IO.Out
|
||||
|
||||
// 1. Inject the CLI-managed init event at the head of the stream (§5.3).
|
||||
// Carries the session pointer + retrieval context callers need for
|
||||
// follow-up threading.
|
||||
initEv := output.InitEvent{
|
||||
SessionID: sessionID,
|
||||
KBID: opts.KBID,
|
||||
Profile: cmdutil.GetProfile(),
|
||||
}
|
||||
if err := output.EmitInit(w, initEv); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. Open SDK stream and pass each event through as a bare NDJSON line.
|
||||
req := &sdk.KnowledgeQARequest{
|
||||
Query: opts.Query,
|
||||
KnowledgeBaseIDs: []string{opts.KBID},
|
||||
@@ -186,22 +197,30 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
WebSearchEnabled: false,
|
||||
Channel: "api",
|
||||
}
|
||||
cb := func(r *sdk.StreamResponse) error {
|
||||
return output.EmitSDKEvent(w, r)
|
||||
}
|
||||
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
|
||||
if cmdutil.IsCancelled(ctx, err) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
|
||||
}
|
||||
return cmdutil.WrapHTTP(err, "knowledge qa stream")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --format ndjson: stream raw SDK events as NDJSON. Encoder hoisted out
|
||||
// of callback to avoid per-event allocation.
|
||||
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
|
||||
enc := json.NewEncoder(iostreams.IO.Out)
|
||||
enc.SetEscapeHTML(false)
|
||||
cb := func(r *sdk.StreamResponse) error {
|
||||
return enc.Encode(r)
|
||||
}
|
||||
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
|
||||
if isCancelled(ctx, err) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
|
||||
}
|
||||
return cmdutil.WrapHTTP(err, "knowledge qa stream")
|
||||
}
|
||||
return nil
|
||||
// runChatText handles the --format text path. Streams content fragments
|
||||
// live on TTY; accumulates then renders on non-TTY pipes.
|
||||
func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreated bool, svc ChatService) error {
|
||||
// Stream mode requires an interactive stdout.
|
||||
streamMode := iostreams.IO.IsStdoutTTY()
|
||||
|
||||
req := &sdk.KnowledgeQARequest{
|
||||
Query: opts.Query,
|
||||
KnowledgeBaseIDs: []string{opts.KBID},
|
||||
AgentEnabled: false,
|
||||
WebSearchEnabled: false,
|
||||
Channel: "api",
|
||||
}
|
||||
|
||||
acc := &sse.Accumulator{}
|
||||
@@ -221,12 +240,11 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
// Re-surface the auto-created session id on failure so a user who
|
||||
// missed the start-of-stream notice (it scrolls past mid-stream
|
||||
// tokens, especially on ^C) can still recover with --session.
|
||||
// Skipped in JSON mode - the data object carries it in .session_id.
|
||||
if autoCreated && !jsonOut {
|
||||
if autoCreated {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
|
||||
}
|
||||
// Context cancelled (Ctrl-C) → user-aborted, exit 130 lineage.
|
||||
if isCancelled(ctx, streamErr) {
|
||||
if cmdutil.IsCancelled(ctx, streamErr) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "chat cancelled")
|
||||
}
|
||||
// Stream began (we observed at least one event) but never reached a
|
||||
@@ -253,29 +271,9 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
answer := acc.Result()
|
||||
references := acc.References
|
||||
|
||||
if jsonOut {
|
||||
// Prefer the SDK-echoed session id (acc.SessionID) but fall back to
|
||||
// our local sessionID - agents must always see a usable pointer.
|
||||
sid := acc.SessionID
|
||||
if sid == "" {
|
||||
sid = sessionID
|
||||
}
|
||||
data := chatData{
|
||||
Answer: answer,
|
||||
References: references,
|
||||
Thinking: acc.Thinking(),
|
||||
SessionID: sid,
|
||||
AssistantMessageID: acc.AssistantMessageID,
|
||||
KBID: opts.KBID,
|
||||
Query: opts.Query,
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, data)
|
||||
}
|
||||
|
||||
// Human / non-JSON paths: streaming mode already wrote the answer body
|
||||
// via the callback, so we only need to render the trailing references
|
||||
// (and a closing newline). Accumulate + non-JSON writes the answer here
|
||||
// for the first time.
|
||||
// Streaming mode already wrote the answer body via the callback, so we
|
||||
// only need to render the trailing references (and a closing newline).
|
||||
// Non-TTY accumulate path writes the answer here for the first time.
|
||||
out := iostreams.IO.Out
|
||||
if streamMode {
|
||||
// Ensure the answer line ends cleanly before the references footer.
|
||||
@@ -292,19 +290,5 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
|
||||
return nil
|
||||
}
|
||||
|
||||
// isCancelled reports whether err or ctx represents a context-cancelled
|
||||
// state — true on Ctrl-C / SIGTERM after main.go's signal.NotifyContext
|
||||
// fires. Wrapping URL/transport layers may rewrite context.Canceled into
|
||||
// something errors.Is no longer recognises, so we fall back to ctx.Err().
|
||||
func isCancelled(ctx context.Context, err error) bool {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return true
|
||||
}
|
||||
if ctx.Err() == context.Canceled {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// compile-time check: the production SDK client implements ChatService.
|
||||
var _ ChatService = (*sdk.Client)(nil)
|
||||
|
||||
+147
-60
@@ -1,11 +1,9 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -62,8 +60,8 @@ func (f *fakeChatService) KnowledgeQAStream(ctx context.Context, sessionID strin
|
||||
// var _ ChatService = (*sdk.Client)(nil) check at the bottom of chat.go.
|
||||
var _ ChatService = (*fakeChatService)(nil)
|
||||
|
||||
// textOpts returns a FormatOptions configured for the text (human) render
|
||||
// path — the most common shape under test.
|
||||
// textOpts returns a FormatOptions configured for the text render path —
|
||||
// the most common shape under test.
|
||||
func textOpts() *cmdutil.FormatOptions {
|
||||
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
}
|
||||
@@ -109,57 +107,105 @@ func TestChat_StreamMode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChat_JSONMode(t *testing.T) {
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
// TestChat_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format json)
|
||||
// always injects an "init" line first carrying session_id and kb_id.
|
||||
func TestChat_NDJSON_FirstLineIsInit(t *testing.T) {
|
||||
out, errBuf := iostreams.SetForTest(t)
|
||||
|
||||
svc := &fakeChatService{
|
||||
streamEvents: []*sdk.StreamResponse{
|
||||
{Content: "answer body"},
|
||||
{AssistantMessageID: "msg_99"},
|
||||
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{{KnowledgeID: "k1"}}},
|
||||
{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"},
|
||||
{ResponseType: sdk.ResponseTypeComplete, Done: true},
|
||||
},
|
||||
}
|
||||
opts := &Options{Query: "q", KBID: "kb_42"}
|
||||
if err := runChat(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc); err != nil {
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
|
||||
t.Fatalf("runChat: %v", err)
|
||||
}
|
||||
|
||||
// JSON mode must NOT print the human session-hint on stderr; the session
|
||||
// id is carried inside the JSON object instead.
|
||||
// NDJSON mode must NOT print the session hint to stderr.
|
||||
if errBuf.Len() != 0 {
|
||||
t.Errorf("expected empty stderr in JSON mode, got %q", errBuf.String())
|
||||
t.Errorf("expected empty stderr in NDJSON mode, got %q", errBuf.String())
|
||||
}
|
||||
|
||||
var got struct {
|
||||
Answer string `json:"answer"`
|
||||
SessionID string `json:"session_id"`
|
||||
AssistantMessageID string `json:"assistant_message_id"`
|
||||
KBID string `json:"kb_id"`
|
||||
Query string `json:"query"`
|
||||
References []struct {
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
} `json:"references"`
|
||||
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
|
||||
if len(lines) == 0 {
|
||||
t.Fatal("no output")
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode JSON: %v\n%s", err, out.String())
|
||||
var first struct {
|
||||
Type string `json:"type"`
|
||||
SessionID string `json:"session_id"`
|
||||
KBID string `json:"kb_id"`
|
||||
}
|
||||
if got.Answer != "answer body" {
|
||||
t.Errorf("answer: got %q", got.Answer)
|
||||
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
|
||||
t.Fatalf("first line not JSON: %v\n %s", err, lines[0])
|
||||
}
|
||||
if got.SessionID != "sess_auto" {
|
||||
t.Errorf("session_id: got %q", got.SessionID)
|
||||
if first.Type != "init" {
|
||||
t.Errorf("first line type: got %q, want init", first.Type)
|
||||
}
|
||||
if got.AssistantMessageID != "msg_99" {
|
||||
t.Errorf("assistant_message_id: got %q", got.AssistantMessageID)
|
||||
if first.SessionID != "sess_auto" {
|
||||
t.Errorf("init.session_id: got %q, want sess_auto", first.SessionID)
|
||||
}
|
||||
if got.KBID != "kb_42" {
|
||||
t.Errorf("kb_id: got %q", got.KBID)
|
||||
if first.KBID != "kb_42" {
|
||||
t.Errorf("init.kb_id: got %q, want kb_42", first.KBID)
|
||||
}
|
||||
if got.Query != "q" {
|
||||
t.Errorf("query: got %q", got.Query)
|
||||
}
|
||||
|
||||
// TestChat_NDJSON_PassthroughEvents verifies that the NDJSON path emits
|
||||
// init + N SDK events = N+1 total lines (no buffering, no extra wrapping).
|
||||
func TestChat_NDJSON_PassthroughEvents(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
svc := &fakeChatService{
|
||||
streamEvents: []*sdk.StreamResponse{
|
||||
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
|
||||
{ResponseType: sdk.ResponseTypeComplete, Done: true},
|
||||
},
|
||||
}
|
||||
if len(got.References) != 1 || got.References[0].KnowledgeID != "k1" {
|
||||
t.Errorf("references payload missing: %+v", got.References)
|
||||
opts := &Options{Query: "q", KBID: "kb_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
|
||||
t.Fatalf("runChat: %v", err)
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
|
||||
// 1 init + 2 SDK events = 3 lines.
|
||||
if len(lines) != 3 {
|
||||
t.Fatalf("got %d lines, want 3:\n%s", len(lines), out.String())
|
||||
}
|
||||
// Each must be valid JSON.
|
||||
for i, line := range lines {
|
||||
var obj map[string]any
|
||||
if err := json.Unmarshal([]byte(line), &obj); err != nil {
|
||||
t.Errorf("line %d not valid JSON: %v\n %s", i+1, err, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChat_NDJSON_JSONEqualsNDJSON verifies that --format json and --format ndjson
|
||||
// produce identical byte output on a streaming command.
|
||||
func TestChat_NDJSON_JSONEqualsNDJSON(t *testing.T) {
|
||||
events := []*sdk.StreamResponse{
|
||||
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
|
||||
{ResponseType: sdk.ResponseTypeComplete, Done: true},
|
||||
}
|
||||
|
||||
runWith := func(mode cmdutil.FormatMode) string {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChatService{streamEvents: events}
|
||||
opts := &Options{Query: "q", KBID: "kb_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: mode}
|
||||
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
|
||||
t.Fatalf("runChat(%s): %v", mode, err)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
jsonOut := runWith(cmdutil.FormatJSON)
|
||||
ndjsonOut := runWith(cmdutil.FormatNDJSON)
|
||||
if jsonOut != ndjsonOut {
|
||||
t.Errorf("--format json and --format ndjson differ:\n json: %q\n ndjson: %q", jsonOut, ndjsonOut)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,8 +392,46 @@ func TestChat_SessionCreate404SurfacesNotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChat_NDJSON_InitIncludesProfile verifies that when a profile is set,
|
||||
// the NDJSON init event carries the profile field.
|
||||
func TestChat_NDJSON_InitIncludesProfile(t *testing.T) {
|
||||
cmdutil.SetProfile("prod")
|
||||
t.Cleanup(func() { cmdutil.SetProfile("") })
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChatService{
|
||||
streamEvents: []*sdk.StreamResponse{
|
||||
{ResponseType: sdk.ResponseTypeComplete, Done: true},
|
||||
},
|
||||
}
|
||||
opts := &Options{Query: "q", KBID: "kb_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
|
||||
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
|
||||
t.Fatalf("runChat: %v", err)
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
|
||||
if len(lines) == 0 {
|
||||
t.Fatal("no output")
|
||||
}
|
||||
var initLine struct {
|
||||
Type string `json:"type"`
|
||||
Profile string `json:"profile"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
|
||||
t.Fatalf("first line not JSON: %v\n %s", err, lines[0])
|
||||
}
|
||||
if initLine.Type != "init" {
|
||||
t.Errorf("type: got %q, want init", initLine.Type)
|
||||
}
|
||||
if initLine.Profile != "prod" {
|
||||
t.Errorf("profile: got %q, want prod", initLine.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
|
||||
// Fake stream emits 3 events: thinking, answer, complete.
|
||||
// With the init injection, total output is 4 lines (1 init + 3 SDK events).
|
||||
svc := &fakeChatService{
|
||||
streamEvents: []*sdk.StreamResponse{
|
||||
{ResponseType: sdk.ResponseTypeThinking, Content: "search KB"},
|
||||
@@ -355,47 +439,50 @@ func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
|
||||
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
|
||||
},
|
||||
}
|
||||
var stdout bytes.Buffer
|
||||
prev := iostreams.IO.Out
|
||||
iostreams.IO.Out = &stdout
|
||||
defer func() { iostreams.IO.Out = prev }()
|
||||
// Also redirect stderr so the auto-created session hint doesn't write to
|
||||
// real stderr during tests.
|
||||
prevErr := iostreams.IO.Err
|
||||
iostreams.IO.Err = os.Stderr
|
||||
defer func() { iostreams.IO.Err = prevErr }()
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
opts := &Options{Query: "hi", KBID: "kb_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
|
||||
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
|
||||
t.Fatalf("runChat: %v", err)
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(stdout.String(), "\n"), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatalf("got %d lines, want 3:\n%s", len(lines), stdout.String())
|
||||
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
|
||||
// 1 init + 3 SDK events = 4 lines.
|
||||
if len(lines) != 4 {
|
||||
t.Fatalf("got %d lines, want 4:\n%s", len(lines), out.String())
|
||||
}
|
||||
// Each line must be valid JSON with the right response_type.
|
||||
var first map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
|
||||
t.Fatalf("line 1 not JSON: %v", err)
|
||||
|
||||
// First line: CLI-injected init event.
|
||||
var initLine map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
|
||||
t.Fatalf("line 1 (init) not JSON: %v", err)
|
||||
}
|
||||
if first["response_type"] != "thinking" {
|
||||
t.Errorf("first event response_type=%v, want thinking", first["response_type"])
|
||||
if initLine["type"] != "init" {
|
||||
t.Errorf("first line type=%v, want init", initLine["type"])
|
||||
}
|
||||
// Second line: answer.
|
||||
|
||||
// Second line: thinking event (SDK passthrough).
|
||||
var second map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
|
||||
t.Fatalf("line 2 not JSON: %v", err)
|
||||
}
|
||||
if second["response_type"] != "answer" {
|
||||
t.Errorf("second event response_type=%v, want answer", second["response_type"])
|
||||
if second["response_type"] != "thinking" {
|
||||
t.Errorf("second event response_type=%v, want thinking", second["response_type"])
|
||||
}
|
||||
// Third line: complete with done=true.
|
||||
// Third line: answer.
|
||||
var third map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[2]), &third); err != nil {
|
||||
t.Fatalf("line 3 not JSON: %v", err)
|
||||
}
|
||||
if third["done"] != true {
|
||||
t.Errorf("third event done=%v, want true", third["done"])
|
||||
if third["response_type"] != "answer" {
|
||||
t.Errorf("third event response_type=%v, want answer", third["response_type"])
|
||||
}
|
||||
// Fourth line: complete with done=true.
|
||||
var fourth map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[3]), &fourth); err != nil {
|
||||
t.Fatalf("line 4 not JSON: %v", err)
|
||||
}
|
||||
if fourth["done"] != true {
|
||||
t.Errorf("fourth event done=%v, want true", fourth["done"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ func TestDelete_TTY_ConfirmYes_Calls(t *testing.T) {
|
||||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runDelete(context.Background(),
|
||||
&DeleteOptions{ChunkID: "c1", DocID: "doc_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p))
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "c1", svc.gotChunkID)
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func TestDelete_TTY_ConfirmNo_Aborts(t *testing.T) {
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(),
|
||||
&DeleteOptions{ChunkID: "c1", DocID: "doc_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p)
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -177,7 +177,7 @@ func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
|
||||
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiChunkDeleteSvc{}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "chunk", 2, "chunk.delete", "")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
||||
@@ -154,7 +154,7 @@ func TestList_MissingDoc_FlagError(t *testing.T) {
|
||||
require.Error(t, cmd.Execute(), "expect required-flag error for missing --doc")
|
||||
}
|
||||
|
||||
func TestList_Human_TableHeader(t *testing.T) {
|
||||
func TestList_Text_TableHeader(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{
|
||||
pages: [][]sdk.Chunk{{
|
||||
@@ -162,21 +162,21 @@ func TestList_Human_TableHeader(t *testing.T) {
|
||||
}},
|
||||
totals: []int64{1}, errs: []error{nil},
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
body := out.String()
|
||||
for _, want := range []string{"CHUNK_ID", "INDEX", "TYPE", "ENABLED", "PREVIEW", "UPDATED", "c1", "text"} {
|
||||
assert.Contains(t, body, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_Human_PreviewTruncatedTo80(t *testing.T) {
|
||||
func TestList_Text_PreviewTruncatedTo80(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
long := strings.Repeat("a", 200)
|
||||
svc := &fakeListSvc{
|
||||
pages: [][]sdk.Chunk{{{ID: "c1", Content: long, ChunkType: "text", IsEnabled: true}}},
|
||||
totals: []int64{1}, errs: []error{nil},
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
body := out.String()
|
||||
// 80-col preview means we never see the 100th `a` from the content (only column truncation kicks in).
|
||||
assert.NotContains(t, body, strings.Repeat("a", 100), "preview must be truncated to ~80 chars")
|
||||
|
||||
@@ -35,7 +35,7 @@ type ViewOptions struct {
|
||||
|
||||
const chunkViewLong = `Show a single chunk with all SDK fields.
|
||||
|
||||
Human output is a key-value block; pass --format json for the bare 23-field SDK
|
||||
Text output is a key-value block; pass --format json for the bare 23-field SDK
|
||||
Chunk object. Content renders verbatim regardless of size — pipe to
|
||||
less or use --format json for large chunks. WeKnora chunks are typically bounded
|
||||
by the ingest pipeline (~1000 tokens / a few KB), so unconditional full
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestView_Happy_RendersAllFields(t *testing.T) {
|
||||
CreatedAt: "2026-05-15T11:00:00Z",
|
||||
UpdatedAt: "2026-05-15T12:00:00Z",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, "c1")
|
||||
assert.Contains(t, body, "doc_abc")
|
||||
@@ -51,9 +51,9 @@ func TestView_HumanLabels_DocAndKB(t *testing.T) {
|
||||
svc := &fakeViewSvc{resp: &sdk.Chunk{
|
||||
ID: "c1", KnowledgeID: "doc_abc", KnowledgeBaseID: "kb_abc",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
body := out.String()
|
||||
// Human KV uses friendlier DOC_ID / KB_ID labels (the SDK's
|
||||
// Text KV uses friendlier DOC_ID / KB_ID labels (the SDK's
|
||||
// knowledge_id / knowledge_base_id are kept only in --format json output).
|
||||
assert.Contains(t, body, "doc_id")
|
||||
assert.Contains(t, body, "kb_id")
|
||||
@@ -64,7 +64,7 @@ func TestView_HumanLabels_DocAndKB(t *testing.T) {
|
||||
func TestView_OmitsZeroOrEmpty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{resp: &sdk.Chunk{ID: "c_min", Content: "x"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_min"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_min"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
body := out.String()
|
||||
// status / start_at / end_at all zero → must be omitted from the human KV.
|
||||
assert.NotContains(t, body, "status:")
|
||||
@@ -89,7 +89,7 @@ func TestView_JSON_BareSDKShape(t *testing.T) {
|
||||
got := env.Data
|
||||
assert.Equal(t, "c_json", got.ID)
|
||||
assert.Equal(t, "doc_abc", got.KnowledgeID)
|
||||
// JSON uses SDK snake_case keys (knowledge_id), not human relabel doc_id.
|
||||
// JSON uses SDK snake_case keys (knowledge_id), not text relabel doc_id.
|
||||
assert.Contains(t, out.String(), `"knowledge_id":"doc_abc"`)
|
||||
assert.Contains(t, out.String(), `"knowledge_base_id":"kb_abc"`)
|
||||
assert.NotContains(t, out.String(), `"doc_id"`)
|
||||
@@ -99,7 +99,7 @@ func TestView_JSON_BareSDKShape(t *testing.T) {
|
||||
func TestView_404(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{ChunkID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runView(context.Background(), &ViewOptions{ChunkID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "resource.not_found")
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
// Package contextcmd holds the `weknora context` command tree
|
||||
// (list / add / remove / use).
|
||||
//
|
||||
// Package name `contextcmd` (not `context`) to avoid shadowing stdlib context.
|
||||
// The cobra Use: string is "context" - this is what users type.
|
||||
package contextcmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// NewCmd builds the `weknora context` parent command.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "context",
|
||||
Short: "Manage CLI contexts (named connection targets)",
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
}
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdAdd(f))
|
||||
cmd.AddCommand(NewCmdRemove(f))
|
||||
cmd.AddCommand(NewCmdUse(f))
|
||||
return cmd
|
||||
}
|
||||
+10
-10
@@ -34,11 +34,11 @@ func (f *fakeCreateSvc) CreateManualKnowledge(
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func TestCreate_Success_Human(t *testing.T) {
|
||||
func TestCreate_Success_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_1", Title: "Sprint Notes"}}
|
||||
opts := &CreateOptions{Text: "# Sprint Notes\n\nAction items: ...", Name: "Sprint Notes"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
|
||||
assert.Equal(t, "kb_xxx", svc.got.kbID)
|
||||
assert.Equal(t, "# Sprint Notes\n\nAction items: ...", svc.got.req.Content)
|
||||
@@ -51,7 +51,7 @@ func TestCreate_Success_NoName_FallsBackToTitle(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_2", Title: "Server Title"}}
|
||||
opts := &CreateOptions{Text: "Some content"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
// When --name is omitted the display falls back to k.Title from the server response.
|
||||
assert.Contains(t, out.String(), "Server Title")
|
||||
}
|
||||
@@ -60,7 +60,7 @@ func TestCreate_Success_NoName_NoTitle_FallsBackToID(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_3"}}
|
||||
opts := &CreateOptions{Text: "Some content"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Contains(t, out.String(), "doc_manual_3")
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestCreate_TagID_Forwarded(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_t"}}
|
||||
opts := &CreateOptions{Text: "content", TagID: "tag_42"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "tag_42", svc.got.req.TagID)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ func TestCreate_Channel_Override(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_ch"}}
|
||||
opts := &CreateOptions{Text: "content", Channel: "browser_extension"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "browser_extension", svc.got.req.Channel)
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ func TestCreate_Channel_DefaultIsAPI(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_ch"}}
|
||||
opts := &CreateOptions{Text: "content"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, uploadChannel, svc.got.req.Channel)
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ func TestCreate_ServerError_Wraps(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal server error")}
|
||||
err := runCreate(context.Background(),
|
||||
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -120,7 +120,7 @@ func TestCreate_HTTPError_400_Wraps(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 400: bad request")}
|
||||
err := runCreate(context.Background(),
|
||||
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -133,7 +133,7 @@ func TestCreate_EmptyText_RejectsBeforeSDK(t *testing.T) {
|
||||
// defensive guard; cobra's MarkFlagRequired catches it earlier in RunE).
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "should-not-reach"}}
|
||||
err := runCreate(context.Background(),
|
||||
&CreateOptions{Text: ""}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
&CreateOptions{Text: ""}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
// Verify the SDK was NOT called.
|
||||
assert.Nil(t, svc.got.req, "SDK must not be called when --text is empty")
|
||||
|
||||
+14
-14
@@ -76,7 +76,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
// Force=true short-circuits the confirm path; the prompter must not be
|
||||
// consulted, so any value works.
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
|
||||
|
||||
assert.Equal(t, "doc_abc", svc.got)
|
||||
assert.Equal(t, 1, svc.calls)
|
||||
@@ -104,7 +104,7 @@ func TestDelete_Success_JSON(t *testing.T) {
|
||||
func TestDelete_NotFound_404(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.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "doc_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "doc_missing")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -115,7 +115,7 @@ func TestDelete_NotFound_404(t *testing.T) {
|
||||
func TestDelete_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "doc_x")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "doc_x")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -129,7 +129,7 @@ func TestDelete_HTTPError_500(t *testing.T) {
|
||||
func TestDelete_ConfirmYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, svc.calls, "user said yes ⇒ delete proceeds")
|
||||
assert.Contains(t, out.String(), "✓")
|
||||
@@ -138,7 +138,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
|
||||
func TestDelete_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 0, svc.calls, "user said no ⇒ SDK must NOT be called")
|
||||
|
||||
@@ -154,7 +154,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
|
||||
func TestDelete_AgentPrompterErrors(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 0, svc.calls)
|
||||
|
||||
@@ -170,7 +170,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
|
||||
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -269,7 +269,7 @@ func TestRunMultiDelete_ConfirmBatch_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||
func TestRunMultiDelete_ConfirmBatch_TTY_UserAborts(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "document", 3, "doc.delete", "")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -341,7 +341,7 @@ func TestEmitMultiDelete_Text(t *testing.T) {
|
||||
{ID: "a", Err: nil},
|
||||
{ID: "b", Err: errors.New("boom")},
|
||||
}
|
||||
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &buf, nil)
|
||||
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &buf, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
out := buf.String()
|
||||
@@ -356,7 +356,7 @@ func TestEmitMultiDelete_TextEmpty(t *testing.T) {
|
||||
{ID: "x", Err: nil},
|
||||
{ID: "y", Err: nil},
|
||||
}
|
||||
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &buf, nil)
|
||||
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &buf, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
out := buf.String()
|
||||
@@ -367,7 +367,7 @@ func TestEmitMultiDelete_TextEmpty(t *testing.T) {
|
||||
|
||||
func TestEmitMultiDelete_UnsupportedFormat(t *testing.T) {
|
||||
// EmitBatch defers unsupported format handling to WriteBatchEnvelope; for
|
||||
// non-JSON formats it falls through to human text. Verify it does not error.
|
||||
// non-JSON formats it falls through to text. Verify it does not error.
|
||||
var buf bytes.Buffer
|
||||
outcomes := []cmdutil.BatchOutcome{}
|
||||
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: "yaml"}, &buf, nil)
|
||||
@@ -494,7 +494,7 @@ func TestDocDelete_All_WithYes_TextMode(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeAllSvc{resp: &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 5}}
|
||||
opts := &DeleteOptions{All: true, KB: "kb_y", Yes: true}
|
||||
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{})
|
||||
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, svc.called)
|
||||
body := out.String()
|
||||
@@ -507,7 +507,7 @@ func TestDocDelete_All_TTY_UserAborts(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeAllSvc{}
|
||||
opts := &DeleteOptions{All: true, KB: "kb_z", Yes: false}
|
||||
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false})
|
||||
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -521,7 +521,7 @@ func TestDocDelete_All_ServiceError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeAllSvc{err: errors.New("HTTP error 404: not found")}
|
||||
opts := &DeleteOptions{All: true, KB: "kb_missing", Yes: true}
|
||||
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{})
|
||||
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
+12
-12
@@ -34,11 +34,11 @@ func (f *fakeFetchSvc) CreateKnowledgeFromURL(
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func TestFetch_Success_Human(t *testing.T) {
|
||||
func TestFetch_Success_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_1", FileName: "whitepaper.pdf"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/whitepaper.pdf"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
|
||||
assert.Equal(t, "kb_xxx", svc.got.kbID)
|
||||
assert.Equal(t, "https://example.com/whitepaper.pdf", svc.got.req.URL)
|
||||
@@ -51,7 +51,7 @@ func TestFetch_WithName_PassesAsFileName(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_2"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/article.html", Name: "Q3 Article"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "Q3 Article", svc.got.req.FileName,
|
||||
"--name must be forwarded as FileName (server uses it for file-vs-crawl mode hint)")
|
||||
}
|
||||
@@ -60,7 +60,7 @@ func TestFetch_Title(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/a.pdf", Title: "My Title"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "My Title", svc.got.req.Title)
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestFetch_FileType(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/no-ext", FileType: "pdf"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "pdf", svc.got.req.FileType)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ func TestFetch_TagID(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/a.pdf", TagID: "tag_99"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "tag_99", svc.got.req.TagID)
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func TestFetch_EnableMultimodel_Forwarded(t *testing.T) {
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
|
||||
mm := true
|
||||
opts := &FetchOptions{URL: "https://example.com/a.pdf", EnableMultimodel: &mm}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
require.NotNil(t, svc.got.req.EnableMultimodel)
|
||||
assert.True(t, *svc.got.req.EnableMultimodel)
|
||||
}
|
||||
@@ -94,7 +94,7 @@ func TestFetch_Channel_Override(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/a.pdf", Channel: "web"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "web", svc.got.req.Channel)
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ func TestFetch_Channel_DefaultIsAPI(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
|
||||
opts := &FetchOptions{URL: "https://example.com/a.pdf"}
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, uploadChannel, svc.got.req.Channel)
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ func TestFetch_DuplicateURL_Maps_resource_already_exists(t *testing.T) {
|
||||
err: sdk.ErrDuplicateURL,
|
||||
}
|
||||
err := runFetch(context.Background(),
|
||||
&FetchOptions{URL: "https://example.com/dup.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
&FetchOptions{URL: "https://example.com/dup.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -141,7 +141,7 @@ func TestFetch_ServerError_Wraps(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{err: errors.New("HTTP error 500: internal server error")}
|
||||
err := runFetch(context.Background(),
|
||||
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -156,6 +156,6 @@ func TestFetch_KBResolutionFailure_Propagates(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeFetchSvc{err: errors.New("HTTP error 404: knowledge base not found")}
|
||||
err := runFetch(context.Background(),
|
||||
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "")
|
||||
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
+19
-19
@@ -49,7 +49,7 @@ func chdirIsolated(t *testing.T) {
|
||||
t.Setenv("WEKNORA_KB_ID", "")
|
||||
}
|
||||
|
||||
func TestList_Success_Human(t *testing.T) {
|
||||
func TestList_Success_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
now := time.Now()
|
||||
items := []sdk.Knowledge{
|
||||
@@ -58,7 +58,7 @@ func TestList_Success_Human(t *testing.T) {
|
||||
}
|
||||
svc := &fakeListSvc{items: items, total: 2}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
|
||||
assert.Equal(t, "kb_xxx", svc.got.kbID)
|
||||
assert.Equal(t, 1, svc.got.page)
|
||||
@@ -90,11 +90,11 @@ func TestList_Success_JSON(t *testing.T) {
|
||||
assert.NotContains(t, got, `"_meta":`)
|
||||
}
|
||||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
func TestList_Empty_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{items: nil, total: 0}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Contains(t, out.String(), "(no documents)")
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func TestList_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{err: errors.New("HTTP error 500: internal")}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30}
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -197,7 +197,7 @@ func TestList_SortByUpdatedDesc(t *testing.T) {
|
||||
{ID: "new", FileName: "new.pdf", UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
}
|
||||
svc := &fakeListSvc{items: items, total: 2}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 20, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 20, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
|
||||
got := out.String()
|
||||
newIdx := strings.Index(got, "new.pdf")
|
||||
@@ -231,7 +231,7 @@ func TestList_StatusFilter_ForwardedToSDK(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, Status: "failed"}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "failed", svc.got.filter.ParseStatus,
|
||||
"--status must be forwarded as filter.ParseStatus for server-side filtering")
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func TestList_StatusFilter_RejectsUnknownValue(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, Status: "bogus"}
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -256,7 +256,7 @@ func TestList_StatusFilter_AcceptsAllEnumValues(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, Status: v}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"),
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"),
|
||||
"status=%q should be accepted", v)
|
||||
}
|
||||
}
|
||||
@@ -321,7 +321,7 @@ func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
opts := &ListOptions{PageSize: 20, Limit: -1}
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -356,7 +356,7 @@ func TestList_Keyword_PassedToFilter(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, Keyword: "spec"}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "spec", svc.got.filter.Keyword)
|
||||
}
|
||||
|
||||
@@ -364,7 +364,7 @@ func TestList_FileType_PassedToFilter(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, FileType: "pdf"}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "pdf", svc.got.filter.FileType)
|
||||
}
|
||||
|
||||
@@ -372,7 +372,7 @@ func TestList_Source_PassedToFilter(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, Source: "api"}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "api", svc.got.filter.Source)
|
||||
}
|
||||
|
||||
@@ -380,7 +380,7 @@ func TestList_TagID_PassedToFilter(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, TagID: "tag_42"}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
assert.Equal(t, "tag_42", svc.got.filter.TagID)
|
||||
}
|
||||
|
||||
@@ -389,7 +389,7 @@ func TestList_StartTime_RFC3339Parses(t *testing.T) {
|
||||
svc := &fakeListSvc{}
|
||||
want := "2026-05-01T00:00:00Z"
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, StartTime: want}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
parsed, err := time.Parse(time.RFC3339, want)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, svc.got.filter.StartTime.Equal(parsed),
|
||||
@@ -402,7 +402,7 @@ func TestList_EndTime_RFC3339Parses(t *testing.T) {
|
||||
svc := &fakeListSvc{}
|
||||
want := "2026-06-30T23:59:59Z"
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, EndTime: want}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
parsed, err := time.Parse(time.RFC3339, want)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, svc.got.filter.EndTime.Equal(parsed))
|
||||
@@ -411,7 +411,7 @@ func TestList_EndTime_RFC3339Parses(t *testing.T) {
|
||||
func TestList_StartTime_InvalidFormat_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, StartTime: "tomorrow"}
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -423,7 +423,7 @@ func TestList_StartTime_InvalidFormat_Rejected(t *testing.T) {
|
||||
func TestList_EndTime_InvalidFormat_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30, EndTime: "2026-05-01"} // date-only, not RFC3339
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
|
||||
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -447,7 +447,7 @@ func TestList_AllFiltersCombined(t *testing.T) {
|
||||
StartTime: "2026-01-01T00:00:00Z",
|
||||
EndTime: "2026-12-31T23:59:59Z",
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
|
||||
f := svc.got.filter
|
||||
assert.Equal(t, "completed", f.ParseStatus)
|
||||
assert.Equal(t, "spec", f.Keyword)
|
||||
|
||||
@@ -207,11 +207,11 @@ func validateUploadFlags(opts *UploadOptions, args []string) error {
|
||||
}
|
||||
|
||||
// renderUploadSuccess emits the post-upload result. JSON path is the bare
|
||||
// Knowledge object; human path prints a checkmark line. Shared by single-
|
||||
// file upload and URL ingest; humanVerb varies (uploaded/ingested) and
|
||||
// Knowledge object; text path prints a checkmark line. Shared by single-
|
||||
// file upload and URL ingest; verb varies (uploaded/ingested) and
|
||||
// fallbackDisplay covers the case when the server-recorded file_name is
|
||||
// blank (URL ingest pre-redirect).
|
||||
func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, humanVerb, customName, fallbackDisplay string) error {
|
||||
func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, verb, customName, fallbackDisplay string) error {
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, k, nil)
|
||||
}
|
||||
@@ -222,7 +222,7 @@ func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, humanVe
|
||||
if displayed == "" {
|
||||
displayed = fallbackDisplay
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s %q (id: %s)\n", humanVerb, displayed, k.ID)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s %q (id: %s)\n", verb, displayed, k.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestUploadRecursive_WalksAllFiles(t *testing.T) {
|
||||
|
||||
svc := &scriptedUploadSvc{}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*"}
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
|
||||
|
||||
sort.Strings(svc.called)
|
||||
assert.Equal(t, []string{"a.pdf", "b.pdf", "c.pdf"}, svc.called)
|
||||
@@ -85,7 +85,7 @@ func TestUploadRecursive_GlobFilter(t *testing.T) {
|
||||
|
||||
svc := &scriptedUploadSvc{}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*.pdf"}
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
|
||||
|
||||
sort.Strings(svc.called)
|
||||
assert.Equal(t, []string{"doc.pdf", "keep.pdf"}, svc.called)
|
||||
@@ -103,7 +103,7 @@ func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) {
|
||||
"bad.pdf": {err: errors.New("HTTP error 500: internal")},
|
||||
}}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*"}
|
||||
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
|
||||
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -126,7 +126,7 @@ func TestUploadRecursive_NoMatches(t *testing.T) {
|
||||
|
||||
svc := &scriptedUploadSvc{}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*.pdf"}
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
|
||||
assert.Len(t, svc.called, 0)
|
||||
assert.Contains(t, strings.ToLower(out.String()), "no files matched")
|
||||
}
|
||||
@@ -135,7 +135,7 @@ func TestUploadRecursive_NotADirectory(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
path := writeTempFile(t, "single.pdf")
|
||||
svc := &scriptedUploadSvc{}
|
||||
err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
|
||||
err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -149,7 +149,7 @@ func TestUploadRecursive_RejectsNameFlag(t *testing.T) {
|
||||
mkTree(t, dir, "a.pdf")
|
||||
svc := &scriptedUploadSvc{}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*", Name: "single-name.pdf"}
|
||||
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
|
||||
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -171,7 +171,7 @@ func TestUploadRecursive_PropagatesMultimodelAndMetadata(t *testing.T) {
|
||||
Metadata: []string{"team=alpha"},
|
||||
Channel: "browser_extension",
|
||||
}
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
|
||||
|
||||
require.NotNil(t, svc.lastEnableMultimodel)
|
||||
assert.True(t, *svc.lastEnableMultimodel)
|
||||
@@ -186,7 +186,7 @@ func TestUploadRecursive_MetadataInvalid_NoCalls(t *testing.T) {
|
||||
|
||||
svc := &scriptedUploadSvc{}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*", Metadata: []string{"badformat"}}
|
||||
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
|
||||
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
+15
-15
@@ -52,12 +52,12 @@ func writeTempFile(t *testing.T, name string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
func TestUpload_Success_Human(t *testing.T) {
|
||||
func TestUpload_Success_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
path := writeTempFile(t, "report.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_99", FileName: "report.pdf"}}
|
||||
opts := &UploadOptions{}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
|
||||
assert.Equal(t, "kb_xxx", svc.got.kbID)
|
||||
assert.Equal(t, path, svc.got.filePath)
|
||||
@@ -79,7 +79,7 @@ func TestUpload_Success_CustomName(t *testing.T) {
|
||||
path := writeTempFile(t, "q3.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_88", FileName: "q3.pdf"}}
|
||||
opts := &UploadOptions{Name: "Q3 Marketing Report.pdf"}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
assert.Equal(t, "Q3 Marketing Report.pdf", svc.got.customName)
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ func TestUpload_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
path := writeTempFile(t, "x.txt")
|
||||
svc := &fakeUploadSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
|
||||
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -117,7 +117,7 @@ func TestUpload_HTTPError_409Conflict(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
path := writeTempFile(t, "dup.pdf")
|
||||
svc := &fakeUploadSvc{err: errors.New("HTTP error 409: file exists")}
|
||||
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
|
||||
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -133,7 +133,7 @@ func TestUpload_DuplicateFileMaps_resource_already_exists(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
path := writeTempFile(t, "dup.md")
|
||||
svc := &fakeUploadSvc{err: sdk.ErrDuplicateFile}
|
||||
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
|
||||
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -199,7 +199,7 @@ func TestUpload_EnableMultimodel_Set_True(t *testing.T) {
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_mm", FileName: "mm.pdf"}}
|
||||
mm := true
|
||||
opts := &UploadOptions{EnableMultimodel: &mm}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
require.NotNil(t, svc.got.enableMultimodel, "expected non-nil *bool when flag set")
|
||||
assert.True(t, *svc.got.enableMultimodel)
|
||||
}
|
||||
@@ -210,7 +210,7 @@ func TestUpload_EnableMultimodel_Set_False(t *testing.T) {
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_mm", FileName: "mm.pdf"}}
|
||||
mm := false
|
||||
opts := &UploadOptions{EnableMultimodel: &mm}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
require.NotNil(t, svc.got.enableMultimodel, "explicit false must still surface as non-nil *bool")
|
||||
assert.False(t, *svc.got.enableMultimodel)
|
||||
}
|
||||
@@ -254,7 +254,7 @@ func TestUpload_Metadata_ParseKV(t *testing.T) {
|
||||
path := writeTempFile(t, "m.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
|
||||
opts := &UploadOptions{Metadata: []string{"foo=bar", "baz=qux"}}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
assert.Equal(t, map[string]string{"foo": "bar", "baz": "qux"}, svc.got.metadata)
|
||||
}
|
||||
|
||||
@@ -263,7 +263,7 @@ func TestUpload_Metadata_EmptyValueAllowed(t *testing.T) {
|
||||
path := writeTempFile(t, "m.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
|
||||
opts := &UploadOptions{Metadata: []string{"foo="}}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
assert.Equal(t, map[string]string{"foo": ""}, svc.got.metadata)
|
||||
}
|
||||
|
||||
@@ -272,7 +272,7 @@ func TestUpload_Metadata_LastWins(t *testing.T) {
|
||||
path := writeTempFile(t, "m.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
|
||||
opts := &UploadOptions{Metadata: []string{"k=v1", "k=v2"}}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
assert.Equal(t, map[string]string{"k": "v2"}, svc.got.metadata)
|
||||
}
|
||||
|
||||
@@ -281,7 +281,7 @@ func TestUpload_Metadata_InvalidFormat_NoEquals(t *testing.T) {
|
||||
path := writeTempFile(t, "m.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
|
||||
opts := &UploadOptions{Metadata: []string{"foo"}}
|
||||
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
|
||||
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -293,7 +293,7 @@ func TestUpload_Metadata_InvalidFormat_EmptyKey(t *testing.T) {
|
||||
path := writeTempFile(t, "m.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
|
||||
opts := &UploadOptions{Metadata: []string{"=bar"}}
|
||||
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
|
||||
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -305,7 +305,7 @@ func TestUpload_Channel_Override(t *testing.T) {
|
||||
path := writeTempFile(t, "c.pdf")
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_c", FileName: "c.pdf"}}
|
||||
opts := &UploadOptions{Channel: "browser_extension"}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
assert.Equal(t, "browser_extension", svc.got.channel)
|
||||
}
|
||||
|
||||
@@ -315,6 +315,6 @@ func TestUpload_Channel_DefaultStillAPI(t *testing.T) {
|
||||
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_c", FileName: "c.pdf"}}
|
||||
// Empty Channel is the runUpload contract for "use default".
|
||||
opts := &UploadOptions{}
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
|
||||
assert.Equal(t, uploadChannel, svc.got.channel)
|
||||
}
|
||||
|
||||
+18
-18
@@ -24,7 +24,7 @@ func (f *fakeViewSvc) GetKnowledge(_ context.Context, _ string) (*sdk.Knowledge,
|
||||
return f.doc, f.err
|
||||
}
|
||||
|
||||
func TestView_Human_RendersExpectedFields(t *testing.T) {
|
||||
func TestView_Text_RendersExpectedFields(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
processed := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{
|
||||
@@ -40,7 +40,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
|
||||
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
|
||||
ProcessedAt: &processed,
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_abc"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -57,10 +57,10 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
|
||||
|
||||
// A doc with no FileName falls back to Title for the NAME line - same
|
||||
// ordering as `doc list` (KnowledgeDisplayName precedence).
|
||||
func TestView_Human_TitleFallback(t *testing.T) {
|
||||
func TestView_Text_TitleFallback(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_url", Title: "Pasted article", FileName: ""}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_url"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_url"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -72,13 +72,13 @@ func TestView_Human_TitleFallback(t *testing.T) {
|
||||
// Optional fields (ProcessedAt nil, ErrorMessage empty, EmbeddingModelID
|
||||
// empty) must not produce empty KEY: lines - the formatter omits them
|
||||
// rather than printing "PROCESSED: -".
|
||||
func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
func TestView_Text_OmitsEmptyFields(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{
|
||||
ID: "doc_abc",
|
||||
FileName: "x.txt",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_abc"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
// Line-prefix match (not substring): "ERROR:" as a substring could
|
||||
@@ -122,7 +122,7 @@ func TestView_JSON_BareObject(t *testing.T) {
|
||||
func TestView_NotFound_ClassifiedAs404(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "missing")
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
@@ -131,14 +131,14 @@ func TestView_NotFound_ClassifiedAs404(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- expanded human render: title/desc/source/channel/etc. ---
|
||||
// --- expanded text render: title/desc/source/channel/etc. ---
|
||||
|
||||
func TestView_Title_RendersWhenDifferentFromFileName(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{
|
||||
ID: "doc_t", FileName: "raw.pdf", Title: "Quarterly Plan",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -154,7 +154,7 @@ func TestView_Title_OmittedWhenSameAsFileName(t *testing.T) {
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{
|
||||
ID: "doc_t", FileName: "policy.pdf", Title: "policy.pdf",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
for _, l := range strings.Split(out.String(), "\n") {
|
||||
@@ -167,7 +167,7 @@ func TestView_Title_OmittedWhenSameAsFileName(t *testing.T) {
|
||||
func TestView_Description(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_d", FileName: "x.pdf", Description: "Annual review"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_d"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_d"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "Annual review") {
|
||||
@@ -180,7 +180,7 @@ func TestView_SourceAndChannel(t *testing.T) {
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{
|
||||
ID: "doc_s", FileName: "x.pdf", Source: "https://example.com/x", Channel: "web",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_s"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_s"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -198,7 +198,7 @@ func TestView_SummaryAndEnableStatus(t *testing.T) {
|
||||
SummaryStatus: "completed",
|
||||
EnableStatus: "disabled",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_st"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_st"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -212,7 +212,7 @@ func TestView_SummaryAndEnableStatus(t *testing.T) {
|
||||
func TestView_TagID(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_t", FileName: "x.pdf", TagID: "tag_abc"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -221,10 +221,10 @@ func TestView_TagID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestView_StorageSize_Human(t *testing.T) {
|
||||
func TestView_StorageSize_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_sz", FileName: "x.pdf", StorageSize: 2 * 1024 * 1024}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_sz"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_sz"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -240,7 +240,7 @@ func TestView_FileHash_Prefix12(t *testing.T) {
|
||||
FileName: "x.pdf",
|
||||
FileHash: "abcdef1234567890fedcba0987654321",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_h"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_h"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -257,7 +257,7 @@ func TestView_ErrorMessage_WarnPrefix(t *testing.T) {
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{
|
||||
ID: "doc_e", FileName: "x.pdf", ErrorMessage: "parser failed at offset 4096",
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_e"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_e"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
||||
+1
-1
@@ -265,7 +265,7 @@ func emitWaitResult(r *WaitResult, fopts *cmdutil.FormatOptions, w io.Writer) er
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, r, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
case cmdutil.FormatText, "":
|
||||
return writeWaitText(w, r)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for doc wait", fopts.Mode)
|
||||
|
||||
@@ -189,9 +189,9 @@ func TestWaitForDocs_MultiID_WaitAllOnPartialFailure(t *testing.T) {
|
||||
// B5: emitWaitResult rendering tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestEmitWaitResult_TextHumanSummary(t *testing.T) {
|
||||
func TestEmitWaitResult_TextSummary(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
res := &WaitResult{
|
||||
Completed: []string{"a", "b"},
|
||||
Failed: []FailedDoc{{ID: "c", Message: "parse boom"}},
|
||||
|
||||
@@ -354,7 +354,7 @@ func emit(fopts *cmdutil.FormatOptions, r Result) {
|
||||
r.Summary.Passed, r.Summary.Warned, r.Summary.Failed, r.Summary.Skipped)
|
||||
}
|
||||
|
||||
// marker returns the human-mode prefix glyph for a check status.
|
||||
// marker returns the text-mode prefix glyph for a check status.
|
||||
//
|
||||
// Agent / JSON consumers read the stable status string from
|
||||
// data.checks[].status; the glyphs are presentation-only and never appear
|
||||
|
||||
@@ -417,10 +417,10 @@ func TestDoctor_BareJSON_FailRaisesSummary(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_HumanMarker_Warn confirms the human-mode glyph appears for warn
|
||||
// TestDoctor_TextMarker_Warn confirms the human-mode glyph appears for warn
|
||||
// rows. Glyph choice is presentation-only; we pin via substring (no width
|
||||
// alignment assertion since terminal-width handling is environmental).
|
||||
func TestDoctor_HumanMarker_Warn(t *testing.T) {
|
||||
func TestDoctor_TextMarker_Warn(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
r := Result{
|
||||
Summary: Summary{Warned: 1},
|
||||
@@ -428,13 +428,13 @@ func TestDoctor_HumanMarker_Warn(t *testing.T) {
|
||||
{Name: "server_version", Status: StatusWarn, Details: "older"},
|
||||
},
|
||||
}
|
||||
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, r)
|
||||
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, r)
|
||||
got := out.String()
|
||||
if !strings.Contains(got, "⚠") {
|
||||
t.Errorf("human output should contain ⚠ glyph for warn, got %q", got)
|
||||
t.Errorf("text output should contain ⚠ glyph for warn, got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "warn") {
|
||||
t.Errorf("human output should still contain status word `warn`, got %q", got)
|
||||
t.Errorf("text output should still contain status word `warn`, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -125,7 +125,7 @@ func emitCheck(res *CheckResult, fopts *cmdutil.FormatOptions, w io.Writer) erro
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
case cmdutil.FormatText, "":
|
||||
return writeCheckText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for kb check", fopts.Mode)
|
||||
|
||||
@@ -108,7 +108,7 @@ func TestEmitCheck_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitCheck_TextHuman(t *testing.T) {
|
||||
func TestEmitCheck_Text(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &CheckResult{
|
||||
ID: "kb_x", Reachable: true,
|
||||
@@ -116,7 +116,7 @@ func TestEmitCheck_TextHuman(t *testing.T) {
|
||||
IsProcessing: true, ProcessingCount: 1,
|
||||
FailedCount: 2,
|
||||
}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
if err := emitCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("emitCheck: %v", err)
|
||||
}
|
||||
|
||||
+10
-10
@@ -27,7 +27,7 @@ func (f *fakeCreateSvc) CreateKnowledgeBase(_ context.Context, kb *sdk.Knowledge
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func TestCreate_Success_Human(t *testing.T) {
|
||||
func TestCreate_Success_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{
|
||||
ID: "kb_new",
|
||||
@@ -40,7 +40,7 @@ func TestCreate_Success_Human(t *testing.T) {
|
||||
Description: "team docs",
|
||||
EmbeddingModel: "model_x",
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
|
||||
// Body sent to SDK matches flags.
|
||||
require.NotNil(t, svc.got)
|
||||
@@ -60,7 +60,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_x", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
|
||||
require.NotNil(t, svc.got)
|
||||
assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")
|
||||
@@ -69,7 +69,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
|
||||
func TestCreate_NameRequired(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -81,7 +81,7 @@ func TestCreate_NameRequired(t *testing.T) {
|
||||
func TestCreate_NameWhitespaceOnly(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -92,7 +92,7 @@ func TestCreate_NameWhitespaceOnly(t *testing.T) {
|
||||
func TestCreate_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -103,7 +103,7 @@ func TestCreate_HTTPError_500(t *testing.T) {
|
||||
func TestCreate_HTTPError_409Conflict(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 409: name exists")}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -132,7 +132,7 @@ func TestCreate_StorageProvider_InjectsRequest(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_s", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n", StorageProvider: "Local"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
|
||||
require.NotNil(t, svc.got.StorageProviderConfig)
|
||||
assert.Equal(t, "local", svc.got.StorageProviderConfig.Provider, "value should be lowercased + trimmed before send")
|
||||
@@ -142,7 +142,7 @@ func TestCreate_StorageProvider_InvalidValueReturnsFlagError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
opts := &CreateOptions{Name: "n", StorageProvider: "azure"}
|
||||
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
assert.Equal(t, 2, cmdutil.ExitCode(err), "invalid --storage-provider must exit 2 (flag validation)")
|
||||
@@ -154,7 +154,7 @@ func TestCreate_StorageProvider_OmittedWhenEmpty(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_n", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n"} // no --storage-provider
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
|
||||
assert.Nil(t, svc.got.StorageProviderConfig, "empty flag must omit StorageProviderConfig (let server pick default)")
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_force"))
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_force"))
|
||||
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "kb_force", svc.gotID)
|
||||
@@ -46,7 +46,7 @@ func TestDelete_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_missing")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -61,7 +61,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_nontty")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_nontty")
|
||||
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -97,7 +97,7 @@ func TestDelete_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.FormatHuman}, svc, p, "kb_yes"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_yes"))
|
||||
|
||||
assert.True(t, p.Asked, "confirm prompt should fire on TTY without --force")
|
||||
assert.True(t, svc.called, "answer=yes ⇒ delete proceeds")
|
||||
@@ -108,7 +108,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_no")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_no")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -123,7 +123,7 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Err: prompt.ErrAgentNoPrompt}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_err")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_err")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
||||
@@ -45,7 +45,7 @@ func (f *fakeEditSvc) UpdateKnowledgeBase(_ context.Context, id string, req *sdk
|
||||
func TestEdit_RequiresAtLeastOneFlag(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{}
|
||||
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc")
|
||||
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -66,7 +66,7 @@ func TestEdit_OnlyName_PreservesCurrentDescription(t *testing.T) {
|
||||
}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("new")
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
|
||||
|
||||
assert.Equal(t, "kb_abc", svc.gotID)
|
||||
require.NotNil(t, svc.gotReq)
|
||||
@@ -85,7 +85,7 @@ func TestEdit_OnlyDescription_PreservesCurrentName(t *testing.T) {
|
||||
}
|
||||
opts := &EditOptions{}
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
|
||||
|
||||
require.NotNil(t, svc.gotReq)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
@@ -98,7 +98,7 @@ func TestEdit_BothFlags(t *testing.T) {
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("renamed")
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
|
||||
assert.Equal(t, "renamed", svc.gotReq.Name)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func TestEdit_NotFound(t *testing.T) {
|
||||
svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("x")
|
||||
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing")
|
||||
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -127,7 +127,7 @@ func withRootHarnessKB(edit *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
pf := root.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "")
|
||||
pf.String("format", "", "Output format: human | json | ndjson")
|
||||
pf.String("format", "", "Output format: text | json | ndjson")
|
||||
pf.StringP("jq", "q", "", "")
|
||||
kb := &cobra.Command{Use: "kb"}
|
||||
kb.AddCommand(edit)
|
||||
|
||||
@@ -23,9 +23,9 @@ func (f *fakeListSvc) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBa
|
||||
return f.items, f.err
|
||||
}
|
||||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
func TestList_Empty_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no knowledge bases)") {
|
||||
@@ -54,14 +54,14 @@ func TestList_Empty_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_NonEmpty_Human_RenderColumns(t *testing.T) {
|
||||
func TestList_NonEmpty_Text_RenderColumns(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
now := time.Now()
|
||||
items := []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Marketing", KnowledgeCount: 5, UpdatedAt: now.Add(-3 * time.Hour)},
|
||||
{ID: "kb2", Name: "Engineering", KnowledgeCount: 1, UpdatedAt: now.Add(-2 * 24 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -120,7 +120,7 @@ func TestList_PinnedFilter(t *testing.T) {
|
||||
{ID: "kb2", Name: "Engineering", IsPinned: false, UpdatedAt: now.Add(-time.Hour)},
|
||||
{ID: "kb3", Name: "Finance", IsPinned: true, UpdatedAt: now.Add(-2 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -132,12 +132,12 @@ func TestList_PinnedFilter(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_PinnedFilter_NoPinned_HumanMessage(t *testing.T) {
|
||||
func TestList_PinnedFilter_NoPinned_TextMessage(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
items := []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Marketing", IsPinned: false, UpdatedAt: time.Now()},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no pinned knowledge bases)") {
|
||||
@@ -191,7 +191,7 @@ func TestList_Limit_Zero_Rejected(t *testing.T) {
|
||||
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeKBs(3)})
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeKBs(3)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative --limit")
|
||||
}
|
||||
|
||||
+1
-1
@@ -76,7 +76,7 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
|
||||
}
|
||||
// No-op path: the resource is already in the requested state. We
|
||||
// emit the current resource so callers see the canonical shape on
|
||||
// both fresh-toggle and no-op paths. Human path prints a confirming
|
||||
// both fresh-toggle and no-op paths. Text path prints a confirming
|
||||
// line; agents observe via the unchanged is_pinned field.
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, current, nil)
|
||||
|
||||
@@ -44,7 +44,7 @@ func (f *fakePinSvc) TogglePinKnowledgeBase(_ context.Context, id string) (*sdk.
|
||||
func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
|
||||
assert.True(t, svc.toggleCalled, "must call toggle when current state differs")
|
||||
assert.Contains(t, out.String(), "kb_abc")
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
||||
func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
|
||||
assert.False(t, svc.toggleCalled, "already pinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already pinned")
|
||||
}
|
||||
@@ -60,14 +60,14 @@ func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
||||
func TestUnpin_PinnedToUnpinned_CallsToggle(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", false))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
|
||||
assert.True(t, svc.toggleCalled)
|
||||
}
|
||||
|
||||
func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", false))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
|
||||
assert.False(t, svc.toggleCalled, "already unpinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already unpinned")
|
||||
}
|
||||
@@ -75,7 +75,7 @@ func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
||||
func TestPin_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{getErr: errors.New("HTTP error 404: not found")}
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing", true)
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -89,7 +89,7 @@ func TestPin_ToggleError(t *testing.T) {
|
||||
current: sdk.KnowledgeBase{IsPinned: false},
|
||||
toggleErr: errors.New("HTTP error 500: internal"),
|
||||
}
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true)
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
@@ -96,7 +96,7 @@ func emitStatus(res *StatusResult, fopts *cmdutil.FormatOptions, w io.Writer) er
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
case cmdutil.FormatText, "":
|
||||
return writeStatusText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for kb status", fopts.Mode)
|
||||
|
||||
@@ -78,10 +78,10 @@ func TestEmitStatus_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitStatus_TextHuman(t *testing.T) {
|
||||
func TestEmitStatus_Text(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &StatusResult{ID: "kb_x", Reachable: true, KnowledgeCount: 5, ChunkCount: 20, IsProcessing: true, ProcessingCount: 1}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
if err := emitStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("emitStatus: %v", err)
|
||||
}
|
||||
|
||||
+3
-3
@@ -64,9 +64,9 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, kb, nil)
|
||||
}
|
||||
// Human: KEY: VALUE. Nested config structs (chunking_config, vlm_config,
|
||||
// etc.) are intentionally omitted from the human render — those are for
|
||||
// `--format json | jq '.chunking_config'` workflows.
|
||||
// Text mode: KEY: VALUE. Nested config structs (chunking_config,
|
||||
// vlm_config, etc.) are intentionally omitted from the text render —
|
||||
// those are for `--format json | jq '.chunking_config'` workflows.
|
||||
w := iostreams.IO.Out
|
||||
fmt.Fprintf(w, "ID: %s\n", kb.ID)
|
||||
fmt.Fprintf(w, "NAME: %s\n", kb.Name)
|
||||
|
||||
+12
-12
@@ -22,12 +22,12 @@ func (f *fakeGetSvc) GetKnowledgeBase(ctx context.Context, id string) (*sdk.Know
|
||||
return f.kb, f.err
|
||||
}
|
||||
|
||||
func TestGet_OK_Human(t *testing.T) {
|
||||
func TestGet_OK_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{
|
||||
ID: "kb1", Name: "Marketing", KnowledgeCount: 12, ChunkCount: 245,
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runGet: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -63,7 +63,7 @@ func TestGet_OK_JSON(t *testing.T) {
|
||||
func TestGet_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "missing")
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
@@ -72,12 +72,12 @@ func TestGet_NotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- expanded human render: badges + extra KV lines ---
|
||||
// --- expanded text render: badges + extra KV lines ---
|
||||
|
||||
func TestView_Pinned_RendersPinnedLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Pinned", IsPinned: true}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "PINNED:") {
|
||||
@@ -88,7 +88,7 @@ func TestView_Pinned_RendersPinnedLine(t *testing.T) {
|
||||
func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Plain", IsPinned: false}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
for _, l := range strings.Split(out.String(), "\n") {
|
||||
@@ -101,7 +101,7 @@ func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
|
||||
func TestView_Temporary_RendersTempLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_t", Name: "Tmp", IsTemporary: true}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_t"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_t"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "TEMPORARY:") {
|
||||
@@ -112,7 +112,7 @@ func TestView_Temporary_RendersTempLine(t *testing.T) {
|
||||
func TestView_SummaryModel(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", SummaryModelID: "summary-model-x"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -124,7 +124,7 @@ func TestView_SummaryModel(t *testing.T) {
|
||||
func TestView_TypeAndSource(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", Type: "general", Description: "d"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -136,7 +136,7 @@ func TestView_TypeAndSource(t *testing.T) {
|
||||
func TestView_Processing(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_p", Name: "Busy", IsProcessing: true, ProcessingCount: 3}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_p"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_p"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -148,7 +148,7 @@ func TestView_Processing(t *testing.T) {
|
||||
func TestView_NotProcessing_OmitsProcessingLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_idle", Name: "Idle", IsProcessing: false}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_idle"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_idle"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
for _, l := range strings.Split(out.String(), "\n") {
|
||||
@@ -165,7 +165,7 @@ func TestView_CreatedAt_AlwaysRendered(t *testing.T) {
|
||||
CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
||||
+14
-14
@@ -21,7 +21,7 @@ import (
|
||||
|
||||
// linkFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `link`. Tracks the small linkResult struct.
|
||||
var linkFields = []string{"context", "kb_id", "kb_name", "project_link_path"}
|
||||
var linkFields = []string{"profile", "kb_id", "kb_name", "project_link_path"}
|
||||
|
||||
type Options struct {
|
||||
KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY
|
||||
@@ -29,7 +29,7 @@ type Options struct {
|
||||
|
||||
// linkResult is the typed payload emitted under data.
|
||||
type linkResult struct {
|
||||
Context string `json:"context"`
|
||||
Profile string `json:"profile"`
|
||||
KBID string `json:"kb_id"`
|
||||
KBName string `json:"kb_name,omitempty"`
|
||||
ProjectLinkPath string `json:"project_link_path"`
|
||||
@@ -77,7 +77,7 @@ func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f
|
||||
}
|
||||
linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName)
|
||||
|
||||
ctxName, err := resolveContext(f)
|
||||
profileName, err := resolveProfile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f
|
||||
}
|
||||
|
||||
link := &projectlink.Project{
|
||||
Context: ctxName,
|
||||
Profile: profileName,
|
||||
KBID: kbID,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
@@ -97,34 +97,34 @@ func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f
|
||||
}
|
||||
|
||||
r := linkResult{
|
||||
Context: ctxName,
|
||||
Profile: profileName,
|
||||
KBID: kbID,
|
||||
KBName: kbName,
|
||||
ProjectLinkPath: linkPath,
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, r)
|
||||
return fopts.Emit(iostreams.IO.Out, r, nil)
|
||||
}
|
||||
if kbName != "" {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, ctxName, kbName, kbID)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, profileName, kbName, kbID)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, ctxName, kbID)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, profileName, kbID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveContext picks the auth context to record in the link. There is no
|
||||
// resolveProfile picks the active profile to record in the link. There is no
|
||||
// per-invocation override flag on `weknora link` itself - to record under a
|
||||
// different context, use the global persistent flag (`weknora --context
|
||||
// staging link --kb my-kb`); the active context at link time is what gets
|
||||
// different profile, use the global persistent flag (`weknora --profile
|
||||
// staging link --kb my-kb`); the active profile at link time is what gets
|
||||
// written.
|
||||
func resolveContext(f *cmdutil.Factory) (string, error) {
|
||||
func resolveProfile(f *cmdutil.Factory) (string, error) {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if cfg.CurrentContext == "" {
|
||||
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active context; run `weknora auth login` first")
|
||||
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active profile; run `weknora auth login` first")
|
||||
}
|
||||
return cfg.CurrentContext, nil
|
||||
}
|
||||
@@ -166,7 +166,7 @@ func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory)
|
||||
return "", "", cmdutil.WrapHTTP(err, "list knowledge bases")
|
||||
}
|
||||
if len(kbs) == 0 {
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first")
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active profile; create one first")
|
||||
}
|
||||
fmt.Fprintln(iostreams.IO.Err, "Available knowledge bases:")
|
||||
for _, kb := range kbs {
|
||||
|
||||
@@ -71,7 +71,7 @@ func TestLink_ByID(t *testing.T) {
|
||||
p, err := projectlink.Load(linkPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", p.KBID)
|
||||
assert.Equal(t, "default", p.Context)
|
||||
assert.Equal(t, "default", p.Profile)
|
||||
assert.Contains(t, out.String(), "✓")
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestLink_OverwritesExisting(t *testing.T) {
|
||||
// Pre-existing link.
|
||||
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
|
||||
require.NoError(t, projectlink.Save(linkPath, &projectlink.Project{
|
||||
Context: "default", KBID: "11111111-1111-4111-8111-111111111111",
|
||||
Profile: "default", KBID: "11111111-1111-4111-8111-111111111111",
|
||||
}))
|
||||
|
||||
f := newFactory("default", nil)
|
||||
|
||||
@@ -72,7 +72,7 @@ func runUnlink(opts *UnlinkOptions, fopts *cmdutil.FormatOptions) error {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "remove %s", linkPath)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, unlinkResult{ProjectLinkPath: linkPath})
|
||||
return fopts.Emit(iostreams.IO.Out, unlinkResult{ProjectLinkPath: linkPath}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Unlinked %s\n", linkPath)
|
||||
return nil
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package linkcmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -20,7 +21,7 @@ func mkLinkFile(t *testing.T, dir string) string {
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
if err := projectlink.Save(full, &projectlink.Project{Context: "default", KBID: "kb_abc"}); err != nil {
|
||||
if err := projectlink.Save(full, &projectlink.Project{Profile: "default", KBID: "kb_abc"}); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
return full
|
||||
@@ -89,12 +90,19 @@ func TestUnlink_JSON_BareObject(t *testing.T) {
|
||||
t.Fatalf("runUnlink: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(got), &env); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, got)
|
||||
}
|
||||
if !env.OK {
|
||||
t.Errorf("envelope.ok must be true, got %q", got)
|
||||
}
|
||||
for _, want := range []string{`"project_link_path"`, projectlink.DirName} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in output:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, `"ok":`) {
|
||||
t.Errorf("bare output must not carry envelope keys, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -16,9 +16,9 @@ type AddOptions struct {
|
||||
User string
|
||||
}
|
||||
|
||||
// contextAddFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `context add`. The result describes the newly-registered context.
|
||||
var contextAddFields = []string{
|
||||
// profileAddFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `profile add`. The result describes the newly-registered profile.
|
||||
var profileAddFields = []string{
|
||||
"name", "host", "user", "current",
|
||||
}
|
||||
|
||||
@@ -30,9 +30,9 @@ type addResult struct {
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
// NewCmdAdd builds `weknora context add`. Registers a *credentialless*
|
||||
// NewCmdAdd builds `weknora profile add`. Registers a *credentialless*
|
||||
// connection target - host + optional user only. Credentials for the new
|
||||
// context are attached separately with `weknora auth login --name <n>`,
|
||||
// profile are attached separately with `weknora auth login --name <n>`,
|
||||
// separating "where" the CLI talks to (the host) and "how" it authenticates
|
||||
// (the credential). If you want one command for both, run
|
||||
// `weknora auth login --name <n> --host <h>` instead.
|
||||
@@ -40,16 +40,16 @@ func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &AddOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "add <name>",
|
||||
Short: "Register a new context (host without credentials)",
|
||||
Long: `Add a new context entry to config.yaml. Stores host (and optionally
|
||||
Short: "Register a new profile (host without credentials)",
|
||||
Long: `Add a new profile entry to config.yaml. Stores host (and optionally
|
||||
user) but does NOT prompt for credentials. Use ` + "`weknora auth login --name <n>`" + ` to
|
||||
attach credentials in a single step instead, or run ` + "`weknora auth login --name <n>`" + ` after
|
||||
` + "`weknora context add`" + ` to fill them in.
|
||||
` + "`weknora profile add`" + ` to fill them in.
|
||||
|
||||
The first context added is auto-selected as the current context. Subsequent
|
||||
adds leave the current context untouched.`,
|
||||
Example: ` weknora context add staging --host https://staging.example.com
|
||||
weknora context add prod --host https://prod.example.com --user alice@example.com`,
|
||||
The first profile added is auto-selected as the current profile. Subsequent
|
||||
adds leave the current profile untouched.`,
|
||||
Example: ` weknora profile add staging --host https://staging.example.com
|
||||
weknora profile add prod --host https://prod.example.com --user alice@example.com`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -61,8 +61,8 @@ adds leave the current context untouched.`,
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
|
||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
|
||||
cmdutil.AddFormatFlag(cmd, contextAddFields...)
|
||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'profile list' (optional, cosmetic only)")
|
||||
cmdutil.AddFormatFlag(cmd, profileAddFields...)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
return cmd
|
||||
}
|
||||
@@ -83,8 +83,8 @@ func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
|
||||
if _, exists := cfg.Contexts[name]; exists {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeResourceAlreadyExists,
|
||||
Message: fmt.Sprintf("context %q already exists", name),
|
||||
Hint: fmt.Sprintf("use a different name, or run `weknora context remove %s` first", name),
|
||||
Message: fmt.Sprintf("profile %q already exists", name),
|
||||
Hint: fmt.Sprintf("use a different name, or run `weknora profile remove %s` first", name),
|
||||
}
|
||||
}
|
||||
if cfg.Contexts == nil {
|
||||
@@ -100,12 +100,12 @@ func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst})
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst}, nil)
|
||||
}
|
||||
if wasFirst {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -114,18 +114,18 @@ func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
|
||||
// digits, dash, underscore, dot. The `.` exception lets emails / DNS-like
|
||||
// names through; the path-traversal `..` is structurally rejected by a
|
||||
// separate guard because it would let a hand-edited config.yaml claim a
|
||||
// context whose name walks out of the keyring namespace.
|
||||
// profile whose name walks out of the keyring namespace.
|
||||
func validateName(name string) error {
|
||||
if name == "" {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: "context name must not be empty",
|
||||
Message: "profile name must not be empty",
|
||||
}
|
||||
}
|
||||
if name == "." || name == ".." || strings.Contains(name, "/") || strings.Contains(name, "\\") {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("context name %q is reserved or path-like", name),
|
||||
Message: fmt.Sprintf("profile name %q is reserved or path-like", name),
|
||||
Hint: "use letters, digits, dashes, underscores, or dots",
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func validateName(name string) error {
|
||||
default:
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("context name %q contains invalid character %q", name, r),
|
||||
Message: fmt.Sprintf("profile name %q contains invalid character %q", name, r),
|
||||
Hint: "use letters, digits, dashes, underscores, or dots",
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -24,7 +24,7 @@ func TestAdd_HappyPath(t *testing.T) {
|
||||
}
|
||||
c, ok := cfg.Contexts["staging"]
|
||||
if !ok {
|
||||
t.Fatalf("staging not in Contexts; got keys=%v", contextKeys(cfg.Contexts))
|
||||
t.Fatalf("staging not in Contexts; got keys=%v", profileKeys(cfg.Contexts))
|
||||
}
|
||||
if c.Host != "https://my.example.com" {
|
||||
t.Errorf("Host=%q, want https://my.example.com", c.Host)
|
||||
@@ -32,9 +32,9 @@ func TestAdd_HappyPath(t *testing.T) {
|
||||
if c.User != "alice@example.com" {
|
||||
t.Errorf("User=%q, want alice@example.com", c.User)
|
||||
}
|
||||
// First context auto-becomes current.
|
||||
// First profile auto-becomes current.
|
||||
if cfg.CurrentContext != "staging" {
|
||||
t.Errorf("first context should auto-become current, got CurrentContext=%q", cfg.CurrentContext)
|
||||
t.Errorf("first profile should auto-become current, got CurrentContext=%q", cfg.CurrentContext)
|
||||
}
|
||||
if !strings.Contains(out.String(), "staging") {
|
||||
t.Errorf("output should mention added name, got %q", out.String())
|
||||
@@ -67,7 +67,7 @@ func TestAdd_DuplicateName(t *testing.T) {
|
||||
// Existing entry must NOT be overwritten.
|
||||
got, _ := config.Load()
|
||||
if got.Contexts["staging"].Host != "https://old.example.com" {
|
||||
t.Errorf("existing context overwritten; Host=%q", got.Contexts["staging"].Host)
|
||||
t.Errorf("existing profile overwritten; Host=%q", got.Contexts["staging"].Host)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestAdd_BadHost(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
|
||||
func TestAdd_SecondProfileDoesNotChangeCurrent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
@@ -115,7 +115,7 @@ func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
|
||||
}
|
||||
got, _ := config.Load()
|
||||
if got.CurrentContext != "production" {
|
||||
t.Errorf("adding a second context must not switch current; got %q", got.CurrentContext)
|
||||
t.Errorf("adding a second profile must not switch current; got %q", got.CurrentContext)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,10 +126,14 @@ func TestAdd_JSON(t *testing.T) {
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
got := env.Data
|
||||
if got["name"] != "staging" {
|
||||
t.Errorf("name should be staging, got %v", got)
|
||||
}
|
||||
@@ -137,6 +141,6 @@ func TestAdd_JSON(t *testing.T) {
|
||||
t.Errorf("host wrong: %v", got)
|
||||
}
|
||||
if got["current"] != true {
|
||||
t.Errorf("first added context must be current=true, got %v", got)
|
||||
t.Errorf("first added profile must be current=true, got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -11,13 +11,14 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
type ListOptions struct{}
|
||||
|
||||
// contextListFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `context list`. Each entry is a per-context summary row.
|
||||
var contextListFields = []string{
|
||||
// profileListFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `profile list`. Each entry is a per-profile summary row.
|
||||
var profileListFields = []string{
|
||||
"name", "host", "user", "current",
|
||||
}
|
||||
|
||||
@@ -28,18 +29,18 @@ type listEntry struct {
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
// NewCmdList builds `weknora context list`. Per-host enumeration with an
|
||||
// NewCmdList builds `weknora profile list`. Per-host enumeration with an
|
||||
// active marker. Reads only config.yaml - no network, no keyring touch.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List configured contexts",
|
||||
Long: `Show every context registered in ~/.config/weknora/config.yaml. The
|
||||
active context (used by subsequent commands when --context is unset) is
|
||||
Short: "List configured profiles",
|
||||
Long: `Show every profile registered in ~/.config/weknora/config.yaml. The
|
||||
active profile (used by subsequent commands when --profile is unset) is
|
||||
marked with a leading "*". No network requests are issued.
|
||||
|
||||
The credential mode (api-key vs password) is intentionally not shown here -
|
||||
run "weknora auth list" for that. "context list" is the catalog of *where*
|
||||
run "weknora auth list" for that. "profile list" is the catalog of *where*
|
||||
the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
@@ -51,7 +52,7 @@ the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
return runList(fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, contextListFields...)
|
||||
cmdutil.AddFormatFlag(cmd, profileListFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -72,10 +73,11 @@ func runList(fopts *cmdutil.FormatOptions) error {
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, entries)
|
||||
meta := &output.Meta{Count: len(entries)}
|
||||
return fopts.Emit(iostreams.IO.Out, entries, meta)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` (or `weknora context add`) to create one.")
|
||||
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` (or `weknora profile add`) to create one.")
|
||||
return nil
|
||||
}
|
||||
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -17,8 +17,8 @@ func TestList_Empty(t *testing.T) {
|
||||
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "No contexts") {
|
||||
t.Errorf("empty output should mention `No contexts`, got %q", out.String())
|
||||
if !strings.Contains(out.String(), "No profiles") {
|
||||
t.Errorf("empty output should mention `No profiles`, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ func TestList_MultipleSorted(t *testing.T) {
|
||||
// active marker on staging row
|
||||
stgLine := lineContaining(got, "staging")
|
||||
if !strings.HasPrefix(stgLine, "*") {
|
||||
t.Errorf("active context row must start with `*`, got %q", stgLine)
|
||||
t.Errorf("active profile row must start with `*`, got %q", stgLine)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,10 +79,14 @@ func TestList_JSON(t *testing.T) {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
|
||||
var rows []map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &rows); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
rows := env.Data
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("expected 2 entries, got %d", len(rows))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Package profilecmd holds the `weknora profile` command tree
|
||||
// (list / add / remove / use).
|
||||
//
|
||||
// Package name `profilecmd` (not `profile`) to keep the pattern consistent
|
||||
// with other cmd subpackages.
|
||||
// The cobra Use: string is "profile" - this is what users type.
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// NewCmd builds the `weknora profile` parent command.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "profile",
|
||||
Short: "Manage CLI profiles (named connection targets)",
|
||||
}
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdAdd(f))
|
||||
cmd.AddCommand(NewCmdRemove(f))
|
||||
cmd.AddCommand(NewCmdUse(f))
|
||||
return cmd
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -16,9 +16,9 @@ type RemoveOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||
}
|
||||
|
||||
// contextRemoveFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `context remove`. The result reports the disposition of the removed entry.
|
||||
var contextRemoveFields = []string{
|
||||
// profileRemoveFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `profile remove`. The result reports the disposition of the removed entry.
|
||||
var profileRemoveFields = []string{
|
||||
"name", "removed", "was_current",
|
||||
}
|
||||
|
||||
@@ -29,26 +29,26 @@ type removeResult struct {
|
||||
WasCurrent bool `json:"was_current"`
|
||||
}
|
||||
|
||||
// NewCmdRemove builds `weknora context remove`. Drops the entry from
|
||||
// NewCmdRemove builds `weknora profile remove`. Drops the entry from
|
||||
// config.yaml and best-effort clears keyring references. Removing a
|
||||
// non-current context is low-friction (no prompt). Removing the *current*
|
||||
// context triggers the destructive-write confirmation protocol (exit 10),
|
||||
// non-current profile is low-friction (no prompt). Removing the *current*
|
||||
// profile triggers the destructive-write confirmation protocol (exit 10),
|
||||
// because subsequent commands will have no default connection target.
|
||||
func NewCmdRemove(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &RemoveOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "remove <name>",
|
||||
Short: "Remove a context (drops entry, clears keyring refs)",
|
||||
Long: `Deletes the named context from config.yaml and best-effort clears any
|
||||
Short: "Remove a profile (drops entry, clears keyring refs)",
|
||||
Long: `Deletes the named profile from config.yaml and best-effort clears any
|
||||
keyring references it owned (matches ` + "`weknora auth logout`" + `).
|
||||
|
||||
Removing the current context also clears CurrentContext - subsequent commands
|
||||
will error until you select another with ` + "`weknora context use <name>`" + ` or pick
|
||||
one up via the global ` + "`--context`" + ` flag. Because that change is observable in
|
||||
every later command, removing the current context requires explicit -y/--yes
|
||||
Removing the current profile also clears CurrentContext - subsequent commands
|
||||
will error until you select another with ` + "`weknora profile use <name>`" + ` or pick
|
||||
one up via the global ` + "`--profile`" + ` flag. Because that change is observable in
|
||||
every later command, removing the current profile requires explicit -y/--yes
|
||||
in scripted / --format json invocations (exit code 10; see cli/README.md).`,
|
||||
Example: ` weknora context remove staging # remove non-current → no prompt
|
||||
weknora context remove production -y # remove current → confirm`,
|
||||
Example: ` weknora profile remove staging # remove non-current → no prompt
|
||||
weknora profile remove production -y # remove current → confirm`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -64,7 +64,18 @@ in scripted / --format json invocations (exit code 10; see cli/README.md).`,
|
||||
return runRemove(opts, fopts, args[0], store, f.Prompter())
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, contextRemoveFields...)
|
||||
cmdutil.AddFormatFlag(cmd, profileRemoveFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "remove a named profile and its stored credentials",
|
||||
RequiredFlags: []string{"<name> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora profile remove staging",
|
||||
"weknora profile remove production -y",
|
||||
},
|
||||
Warnings: []string{
|
||||
"profile remove drops the named profile and its stored credentials. Never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -80,10 +91,10 @@ func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, s
|
||||
wasCurrent := name == cfg.CurrentContext
|
||||
|
||||
jsonOut := fopts.WantsJSON()
|
||||
// Confirmation only fires for removing the current context - non-current
|
||||
// Confirmation only fires for removing the current profile - non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current context", name); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -97,24 +108,24 @@ func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, s
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
clearContextSecrets(store, ctx, name)
|
||||
clearProfileSecrets(store, ctx, name)
|
||||
|
||||
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
|
||||
if jsonOut {
|
||||
return fopts.Emit(iostreams.IO.Out, result)
|
||||
return fopts.Emit(iostreams.IO.Out, result, nil)
|
||||
}
|
||||
if wasCurrent {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared - run `weknora context use <name>` to pick another)\n", name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed profile %s (current profile cleared - run `weknora profile use <name>` to pick another)\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s\n", name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed profile %s\n", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
|
||||
// slot the context references. Errors are swallowed so a missing keyring
|
||||
// clearProfileSecrets mirrors auth/logout.go: best-effort delete every secret
|
||||
// slot the profile references. Errors are swallowed so a missing keyring
|
||||
// entry doesn't block remove (same policy as `auth logout`).
|
||||
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
|
||||
func clearProfileSecrets(store secrets.Store, c config.Context, name string) {
|
||||
if c.TokenRef != "" {
|
||||
_ = store.Delete(name, "access")
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
// seedStore returns a MemStore pre-loaded with sentinel values for every
|
||||
// secret slot a context might reference. Tests assert deletion by checking
|
||||
// secret slot a profile might reference. Tests assert deletion by checking
|
||||
// `secrets.ErrNotFound` post-runRemove.
|
||||
func seedStore(t *testing.T, name string, slots ...string) *secrets.MemStore {
|
||||
t.Helper()
|
||||
@@ -66,7 +66,7 @@ func TestRemove_NonCurrent_NoPromptNeeded(t *testing.T) {
|
||||
}
|
||||
assertDeleted(t, store, "staging", "api_key")
|
||||
if !strings.Contains(out.String(), "staging") {
|
||||
t.Errorf("output should mention removed context, got %q", out.String())
|
||||
t.Errorf("output should mention removed profile, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,8 +90,8 @@ func TestRemove_NotFound_WithDidYouMean(t *testing.T) {
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeLocalContextNotFound {
|
||||
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound)
|
||||
if cm.Code != cmdutil.CodeLocalProfileNotFound {
|
||||
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeLocalProfileNotFound)
|
||||
}
|
||||
if !strings.Contains(cm.Hint, "production") {
|
||||
t.Errorf("hint should suggest 'production', got %q", cm.Hint)
|
||||
@@ -164,7 +164,7 @@ func TestRemove_Current_WithYes_ClearsCurrent(t *testing.T) {
|
||||
t.Errorf("removing current must clear CurrentContext, got %q", got.CurrentContext)
|
||||
}
|
||||
assertDeleted(t, store, "production", "access")
|
||||
if !strings.Contains(out.String(), "current context cleared") {
|
||||
if !strings.Contains(out.String(), "current profile cleared") {
|
||||
t.Errorf("output should warn about cleared current, got %q", out.String())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -11,27 +11,27 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// contextUseFields enumerates fields surfaced for `--format json` discovery on
|
||||
// `context use`.
|
||||
var contextUseFields = []string{"current_context", "previous_context"}
|
||||
// profileUseFields enumerates fields surfaced for `--format json` discovery on
|
||||
// `profile use`.
|
||||
var profileUseFields = []string{"current_profile", "previous_profile"}
|
||||
|
||||
// NewCmdUse builds the `weknora context use <name>` command.
|
||||
// NewCmdUse builds the `weknora profile use <name>` command.
|
||||
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "use <name>",
|
||||
Short: "Switch the default context for subsequent commands",
|
||||
Long: `Switches the default context written in config.yaml. Names are case-sensitive.
|
||||
Short: "Switch the default profile for subsequent commands",
|
||||
Long: `Switches the default profile written in config.yaml. Names are case-sensitive.
|
||||
|
||||
The active context is what every subsequent command uses for auth + host. The
|
||||
global --context flag (e.g. weknora --context staging kb list) overrides for
|
||||
The active profile is what every subsequent command uses for auth + host. The
|
||||
global --profile flag (e.g. weknora --profile staging kb list) overrides for
|
||||
one command without writing to disk.
|
||||
|
||||
AI agents: Do NOT switch the active context unless the user explicitly asked
|
||||
you to. Context selection is a user preference; one-shot overrides should use
|
||||
the global --context flag instead, which writes nothing to disk.`,
|
||||
Example: ` weknora context use staging # persist switch
|
||||
weknora --context staging kb list # one-shot override (no disk write)
|
||||
weknora context use staging --format json # {current_context, previous_context}`,
|
||||
AI agents: Do NOT switch the active profile unless the user explicitly asked
|
||||
you to. Profile selection is a user preference; one-shot overrides should use
|
||||
the global --profile flag instead, which writes nothing to disk.`,
|
||||
Example: ` weknora profile use staging # persist switch
|
||||
weknora --profile staging kb list # one-shot override (no disk write)
|
||||
weknora profile use staging --format json # {current_profile, previous_profile}`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -42,13 +42,13 @@ the global --context flag instead, which writes nothing to disk.`,
|
||||
return runUse(args[0], fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, contextUseFields...)
|
||||
cmdutil.AddFormatFlag(cmd, profileUseFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
type useResult struct {
|
||||
CurrentContext string `json:"current_context"`
|
||||
PreviousContext string `json:"previous_context,omitempty"`
|
||||
CurrentProfile string `json:"current_profile"`
|
||||
PreviousProfile string `json:"previous_profile,omitempty"`
|
||||
}
|
||||
|
||||
func runUse(name string, fopts *cmdutil.FormatOptions) error {
|
||||
@@ -64,14 +64,14 @@ func runUse(name string, fopts *cmdutil.FormatOptions) error {
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
result := useResult{CurrentContext: name, PreviousContext: prev}
|
||||
result := useResult{CurrentProfile: name, PreviousProfile: prev}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, result)
|
||||
return fopts.Emit(iostreams.IO.Out, result, nil)
|
||||
}
|
||||
if prev != "" && prev != name {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Switched context to %s (was %s)\n", name, prev)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Switched profile to %s (was %s)\n", name, prev)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Active context: %s\n", name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Active profile: %s\n", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -79,27 +79,27 @@ func runUse(name string, fopts *cmdutil.FormatOptions) error {
|
||||
func notFoundError(name string, cfg *config.Config) error {
|
||||
if len(cfg.Contexts) == 0 {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalContextNotFound,
|
||||
Message: fmt.Sprintf("context not found: %s", name),
|
||||
Hint: "no contexts registered - run `weknora auth login` first",
|
||||
Code: cmdutil.CodeLocalProfileNotFound,
|
||||
Message: fmt.Sprintf("profile not found: %s", name),
|
||||
Hint: "no profiles registered - run `weknora auth login` first",
|
||||
}
|
||||
}
|
||||
keys := contextKeys(cfg.Contexts)
|
||||
keys := profileKeys(cfg.Contexts)
|
||||
candidate := closestMatch(name, keys)
|
||||
var hint string
|
||||
if candidate != "" && candidate != name {
|
||||
hint = fmt.Sprintf("did you mean: %q?", candidate)
|
||||
} else {
|
||||
hint = fmt.Sprintf("available contexts: %v", keys)
|
||||
hint = fmt.Sprintf("available profiles: %v", keys)
|
||||
}
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalContextNotFound,
|
||||
Message: fmt.Sprintf("context not found: %s", name),
|
||||
Code: cmdutil.CodeLocalProfileNotFound,
|
||||
Message: fmt.Sprintf("profile not found: %s", name),
|
||||
Hint: hint,
|
||||
}
|
||||
}
|
||||
|
||||
func contextKeys(m map[string]config.Context) []string {
|
||||
func profileKeys(m map[string]config.Context) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
@@ -1,4 +1,4 @@
|
||||
package contextcmd
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
@@ -36,7 +36,7 @@ func TestUse_OK(t *testing.T) {
|
||||
t.Errorf("CurrentContext = %q, want production", got.CurrentContext)
|
||||
}
|
||||
if !strings.Contains(out.String(), "production") {
|
||||
t.Errorf("output should mention switched-to context, got %q", out.String())
|
||||
t.Errorf("output should mention switched-to profile, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ func TestUse_NotFound_WithDidYouMean(t *testing.T) {
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeLocalContextNotFound {
|
||||
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound)
|
||||
if cm.Code != cmdutil.CodeLocalProfileNotFound {
|
||||
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalProfileNotFound)
|
||||
}
|
||||
if cm.Hint != `did you mean: "production"?` {
|
||||
t.Errorf("hint should be exact `did you mean: \"production\"?`, got %q", cm.Hint)
|
||||
@@ -95,7 +95,7 @@ func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUse_NotFound_EmptyContexts(t *testing.T) {
|
||||
func TestUse_NotFound_EmptyProfiles(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
@@ -105,7 +105,7 @@ func TestUse_NotFound_EmptyContexts(t *testing.T) {
|
||||
}
|
||||
cm := err.(*cmdutil.Error)
|
||||
if !strings.Contains(cm.Hint, "auth login") {
|
||||
t.Errorf("hint should mention `auth login` for empty Contexts, got %q", cm.Hint)
|
||||
t.Errorf("hint should mention `auth login` for empty profiles, got %q", cm.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -53,7 +53,7 @@ func resolveFormatEarly(args []string) {
|
||||
}
|
||||
}
|
||||
switch mode {
|
||||
case "json", "ndjson", "human":
|
||||
case "json", "ndjson", "text":
|
||||
cmdutil.SetFormatMode(mode)
|
||||
case "":
|
||||
// nothing to set; leave globalFormatMode at its zero value
|
||||
@@ -219,7 +219,7 @@ func addGlobalFlags(cmd *cobra.Command) {
|
||||
// instead of being rejected as "unknown flag" exit 2 by cobra. Commands
|
||||
// that don't produce JSON output (e.g. `completion bash`) ignore the flag
|
||||
// rather than error — the unified agent contract is worth the trade.
|
||||
pf.String("format", "", "Output format: human | json | ndjson (default: json)")
|
||||
pf.String("format", "", "Output format: text | json | ndjson (default: json)")
|
||||
pf.StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
|
||||
}
|
||||
|
||||
|
||||
@@ -27,14 +27,14 @@ func (f *fakeChunksSvc) HybridSearch(_ context.Context, kbID string, p *sdk.Sear
|
||||
return f.results, f.err
|
||||
}
|
||||
|
||||
func TestRunSearch_HumanOutput(t *testing.T) {
|
||||
func TestRunSearch_TextOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
||||
{Score: 0.92, Content: "first chunk", KnowledgeID: "doc-1", MatchType: sdk.MatchTypeVector},
|
||||
{Score: 0.81, Content: "second chunk", KnowledgeID: "doc-2", MatchType: sdk.MatchTypeKeyword},
|
||||
}}
|
||||
opts := &ChunksOptions{Query: "hello", KBID: "kb_abc", Limit: 5}
|
||||
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
|
||||
assert.Equal(t, "kb_abc", svc.gotKB)
|
||||
assert.Equal(t, "hello", svc.gotQ)
|
||||
@@ -46,7 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
|
||||
|
||||
// JSON output must surface match_type so machine consumers / agents can
|
||||
// reason about retrieval channels without re-implementing the wire format.
|
||||
// (Human renderer keeps default minimal - diagnostic info opt-in via --format json.)
|
||||
// (Text renderer keeps default minimal - diagnostic info opt-in via --format json.)
|
||||
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
||||
@@ -74,7 +74,7 @@ func TestRunSearch_JSONOutput(t *testing.T) {
|
||||
func TestRunSearch_EmptyResults(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{results: nil}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "(no results)")
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
|
||||
{Score: 0, Content: "enrichment parent"}, // server-padded
|
||||
{Score: 0, Content: "enrichment nearby"}, // server-padded
|
||||
}}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "3 result(s)")
|
||||
assert.NotContains(t, got, "enrichment parent")
|
||||
@@ -99,7 +99,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
|
||||
|
||||
func TestRunSearch_BothChannelsDisabled(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeChunksSvc{})
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeChunksSvc{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -107,7 +107,7 @@ func TestRunSearch_BothChannelsDisabled(t *testing.T) {
|
||||
func TestRunSearch_ServiceError_Transport(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{err: assert.AnError}
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -118,7 +118,7 @@ func TestRunSearch_ServiceError_Transport(t *testing.T) {
|
||||
func TestRunSearch_ServiceError_HTTPNotFound(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{err: errors.New("HTTP error 404: knowledge base not found")}
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -132,7 +132,7 @@ func TestIndent(t *testing.T) {
|
||||
|
||||
func TestRunSearch_NilService(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "server.error")
|
||||
}
|
||||
@@ -168,7 +168,7 @@ func TestRunSearch_NoVectorPassedThrough(t *testing.T) {
|
||||
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
|
||||
Query: "q", KBID: "kb1", NoVector: true,
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NotNil(t, got)
|
||||
assert.True(t, got.DisableVectorMatch)
|
||||
assert.False(t, got.DisableKeywordsMatch)
|
||||
@@ -180,7 +180,7 @@ func TestRunSearch_NoKeywordPassedThrough(t *testing.T) {
|
||||
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
|
||||
Query: "q", KBID: "kb1", NoKeyword: true,
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NotNil(t, got)
|
||||
assert.True(t, got.DisableKeywordsMatch)
|
||||
assert.False(t, got.DisableVectorMatch)
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestDocsSearch_Substring(t *testing.T) {
|
||||
},
|
||||
total: 2,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Equal(t, "q3", svc.lastFilter.Keyword, "query must be threaded as filter.Keyword")
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "d1")
|
||||
@@ -62,7 +62,7 @@ func TestDocsSearch_MatchesFileName(t *testing.T) {
|
||||
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "Untitled", FileName: "report.pdf"}}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "d1")
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
|
||||
pages: map[int][]sdk.Knowledge{1: page1, 2: page2},
|
||||
total: int64(docsPageSize) + 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "found")
|
||||
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when more items reported")
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func TestDocsSearch_StopsAtLimit(t *testing.T) {
|
||||
page1[i] = sdk.Knowledge{ID: "match", Title: "needle"}
|
||||
}
|
||||
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
// Must not request page 2 because limit was hit mid-page.
|
||||
assert.Equal(t, []int{1}, svc.calls)
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func TestDocsSearch_JSON(t *testing.T) {
|
||||
func TestDocsSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{err: errors.New("HTTP error 404: kb not found")}
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -165,7 +165,7 @@ func TestSearchDocs_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
|
||||
func TestSearchDocs_KeywordPassedToFilter(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: {{ID: "d1"}}}, total: 1}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Equal(t, "my-query", svc.lastFilter.Keyword, "Query must be threaded as filter.Keyword on ListKnowledgeWithFilter")
|
||||
// Other filter fields must be empty - search docs only forwards the keyword.
|
||||
assert.Empty(t, svc.lastFilter.ParseStatus)
|
||||
|
||||
@@ -31,7 +31,7 @@ func TestKBSearch_Substring(t *testing.T) {
|
||||
{ID: "kb2", Name: "Engineering Docs", KnowledgeCount: 50},
|
||||
{ID: "kb3", Name: "Marketing Q4 Plan", KnowledgeCount: 5},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "kb1")
|
||||
assert.Contains(t, got, "kb3")
|
||||
@@ -43,7 +43,7 @@ func TestKBSearch_CaseInsensitive(t *testing.T) {
|
||||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "ENGINEERING"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "kb1")
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestKBSearch_MatchesDescription(t *testing.T) {
|
||||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Engineering", Description: "all marketing docs are here"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "kb1")
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
|
||||
{ID: "kb_short", Name: "marketing"},
|
||||
{ID: "kb_mid", Name: "marketing 2024"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
// Order: shortest name first.
|
||||
iShort := strings.Index(got, "kb_short")
|
||||
@@ -79,7 +79,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
|
||||
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
|
||||
{ID: "c", Name: "match-c"}, {ID: "d", Name: "match-d"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
count := 0
|
||||
for _, id := range []string{"a", "b", "c", "d"} {
|
||||
@@ -93,7 +93,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
|
||||
func TestKBSearch_NoMatches(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{Name: "foo"}}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "(no matches)")
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ func TestKBSearch_JSON(t *testing.T) {
|
||||
func TestKBSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeKBSearchSvc{err: errors.New("HTTP error 401: unauthenticated")}
|
||||
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestSessionsSearch_TitleAndDescription(t *testing.T) {
|
||||
}},
|
||||
total: 3,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "s1")
|
||||
assert.Contains(t, got, "s2")
|
||||
@@ -52,7 +52,7 @@ func TestSessionsSearch_NoMatches(t *testing.T) {
|
||||
pages: map[int][]sdk.Session{1: {{Title: "foo"}}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "(no matches)")
|
||||
}
|
||||
|
||||
@@ -63,14 +63,14 @@ func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
|
||||
page1[i] = sdk.Session{ID: "m", Title: "needle"}
|
||||
}
|
||||
svc := &fakeSessionsSearchSvc{pages: map[int][]sdk.Session{1: page1}, total: 1000}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Equal(t, []int{1}, svc.calls, "stops paging when limit reached")
|
||||
}
|
||||
|
||||
func TestSessionsSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeSessionsSearchSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -90,7 +90,7 @@ func TestSessionsSearch_RendersFuzzyTime(t *testing.T) {
|
||||
}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, "hour", "must render relative time (e.g. 'about 2 hours ago'), not raw RFC3339")
|
||||
assert.NotContains(t, body, "T0", "raw RFC3339 has 'T' between date and time; fuzzyTime output should not")
|
||||
|
||||
+14
-14
@@ -60,11 +60,12 @@ The 'weknora agent' subtree handles CRUD only (list / view / create /
|
||||
edit / delete / status / check).
|
||||
|
||||
Modes:
|
||||
TTY (human format, default): live answer streaming + tool-trace footer
|
||||
--format json / --format ndjson / pipe: NDJSON event stream — one init line
|
||||
at head (session_id, agent_id), then raw SDK
|
||||
agent events verbatim. Both json and ndjson
|
||||
flags produce the same NDJSON stream (§5).`,
|
||||
--format text: live answer streaming + tool-trace footer
|
||||
--format json / --format ndjson / pipe (default): NDJSON event stream —
|
||||
one init line at head (session_id, agent_id),
|
||||
then raw SDK agent events verbatim. Both
|
||||
json and ndjson flags produce the same
|
||||
NDJSON stream (§5).`,
|
||||
Example: ` weknora session ask --agent ag_x "Summarize Q3 sales"
|
||||
weknora session ask --session sess_x --agent ag_x "Follow-up question"
|
||||
weknora session ask --agent ag_x "Multi-step task" --format ndjson`,
|
||||
@@ -112,8 +113,7 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
|
||||
|
||||
// Streaming commands route --format json AND --format ndjson to the
|
||||
// NDJSON event-stream path. A buffered envelope makes no sense for a
|
||||
// streaming command (§5). Only --format human (or TTY default) uses the
|
||||
// live renderer.
|
||||
// streaming command (§5). Only --format text uses the live renderer.
|
||||
ndjsonMode := fopts != nil && (fopts.Mode == cmdutil.FormatJSON || fopts.Mode == cmdutil.FormatNDJSON)
|
||||
|
||||
sessionID := opts.SessionID
|
||||
@@ -145,7 +145,7 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
|
||||
}
|
||||
|
||||
return runAskHuman(ctx, opts, sessionID, autoCreated, svc)
|
||||
return runAskText(ctx, opts, sessionID, autoCreated, svc)
|
||||
}
|
||||
|
||||
// runAskNDJSON handles --format json and --format ndjson paths.
|
||||
@@ -184,9 +184,9 @@ func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc A
|
||||
return nil
|
||||
}
|
||||
|
||||
// runAskHuman handles the TTY / human-text path. Streams answer fragments
|
||||
// runAskText handles the --format text path. Streams answer fragments
|
||||
// live on TTY; accumulates then renders on non-TTY pipes.
|
||||
func runAskHuman(ctx context.Context, opts *AskOptions, sessionID string, autoCreated bool, svc AskService) error {
|
||||
func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCreated bool, svc AskService) error {
|
||||
// Stream mode requires an interactive stdout.
|
||||
streamMode := iostreams.IO.IsStdoutTTY()
|
||||
|
||||
@@ -243,9 +243,9 @@ func runAskHuman(ctx context.Context, opts *AskOptions, sessionID string, autoCr
|
||||
return nil
|
||||
}
|
||||
|
||||
// renderAskToolTrace prints a compact tool-event footer in human mode.
|
||||
// Skipped when the agent emitted no tool events — silent beats an empty
|
||||
// banner.
|
||||
// renderAskToolTrace prints a compact tool-event footer in --format text
|
||||
// mode. Skipped when the agent emitted no tool events — silent beats an
|
||||
// empty banner.
|
||||
func renderAskToolTrace(w io.Writer, events []sse.AgentToolEvent) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
@@ -262,7 +262,7 @@ func renderAskToolTrace(w io.Writer, events []sse.AgentToolEvent) {
|
||||
}
|
||||
|
||||
// truncateAskInline shrinks a multi-line result to a single line + ellipsis
|
||||
// for the human tool-trace footer.
|
||||
// for the text tool-trace footer.
|
||||
func truncateAskInline(s string, maxLen int) string {
|
||||
s = strings.ReplaceAll(s, "\n", " ")
|
||||
if len(s) <= maxLen {
|
||||
|
||||
@@ -63,10 +63,10 @@ func referencesEvent(refs []*sdk.SearchResult) *sdk.AgentStreamResponse {
|
||||
}
|
||||
}
|
||||
|
||||
// textOpts returns a FormatOptions configured for the text (human) render
|
||||
// path — the most common shape under test.
|
||||
// textOpts returns a FormatOptions configured for the text render path —
|
||||
// the most common shape under test.
|
||||
func textOpts() *cmdutil.FormatOptions {
|
||||
return &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
}
|
||||
|
||||
// ndjsonOpts returns a FormatOptions for the NDJSON event-stream path.
|
||||
@@ -253,7 +253,7 @@ func TestSessionAsk_StreamAbortBeforeDone_MapsToSSEStreamAborted(t *testing.T) {
|
||||
streamErr: errors.New("connection reset"),
|
||||
}
|
||||
opts := &AskOptions{AgentID: "ag", Query: "x"}
|
||||
// Human path (textOpts) validates Done; NDJSON path does not buffer.
|
||||
// Text path (textOpts) validates Done; NDJSON path does not buffer.
|
||||
err := runAsk(context.Background(), opts, textOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected stream-aborted error")
|
||||
@@ -311,8 +311,8 @@ func TestSessionAsk_Cancellation_MapsToOperationCancelled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: human-mode output writes the answer body and a tool-trace footer.
|
||||
func TestSessionAsk_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
|
||||
// Sanity: text-mode output writes the answer body and a tool-trace footer.
|
||||
func TestSessionAsk_Text_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
|
||||
answerEvent("hello"),
|
||||
|
||||
@@ -32,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.FormatHuman}, 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")
|
||||
@@ -42,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.FormatHuman}, 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)
|
||||
@@ -52,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.FormatHuman}, 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)
|
||||
@@ -65,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.FormatHuman}, 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)
|
||||
}
|
||||
@@ -74,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.FormatHuman}, 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)
|
||||
@@ -145,7 +145,7 @@ func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
|
||||
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "session", 2, "session.delete", "")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
||||
@@ -35,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, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "no sessions")
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestList_Table(t *testing.T) {
|
||||
},
|
||||
total: 2,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "s_1")
|
||||
assert.Contains(t, got, "Design review")
|
||||
@@ -106,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, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListService{})
|
||||
err := runList(context.Background(), &ListOptions{PageSize: tc.size, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -118,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, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
err := runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -129,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, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
assert.Contains(t, out.String(), "s_zh")
|
||||
}
|
||||
|
||||
@@ -142,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", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&ListOptions{PageSize: 30, Since: "7d", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: items, total: 3}))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "recent")
|
||||
@@ -156,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, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0}),
|
||||
"--since=%q should parse", v)
|
||||
})
|
||||
@@ -166,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", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&ListOptions{PageSize: 30, Since: "bogus", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -178,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, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err, "--since=%q should reject", v)
|
||||
var typed *cmdutil.Error
|
||||
@@ -244,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.FormatHuman},
|
||||
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
||||
@@ -42,7 +42,7 @@ func (f *fakeViewService) LoadMessages(_ context.Context, sessionID string, limi
|
||||
return f.msgs, f.msgsErr
|
||||
}
|
||||
|
||||
func TestView_Human(t *testing.T) {
|
||||
func TestView_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{
|
||||
ID: "s_abc",
|
||||
@@ -51,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.FormatHuman}, 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)
|
||||
@@ -77,7 +77,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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)
|
||||
@@ -87,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.FormatHuman}, 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:") {
|
||||
@@ -107,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.FormatHuman}, 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)
|
||||
@@ -123,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.FormatHuman}, 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)")
|
||||
}
|
||||
@@ -131,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.FormatHuman}, 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")
|
||||
}
|
||||
@@ -139,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.FormatHuman}, 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")
|
||||
}
|
||||
@@ -149,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.FormatHuman}, 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")
|
||||
|
||||
Reference in New Issue
Block a user