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:
+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"])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user