diff --git a/cli/README.md b/cli/README.md index 3f14b4cc..005e3a16 100644 --- a/cli/README.md +++ b/cli/README.md @@ -112,7 +112,7 @@ Every command supports `--json`, returning a stable envelope shape: { "ok": true, "data": { /* command-specific payload */ }, - "_meta": { "context": "prod", "kb_id": "kb_abc" } + "_meta": { "context": "prod", "kb_id": "a32a63ff-fb36-4874-bcaa-30f48570a694" } } ``` diff --git a/cli/acceptance/contract/envelope_test.go b/cli/acceptance/contract/envelope_test.go index e02a0d2c..c1876a9c 100644 --- a/cli/acceptance/contract/envelope_test.go +++ b/cli/acceptance/contract/envelope_test.go @@ -155,25 +155,25 @@ var envelopeCases = []envelopeCase{ // 11-13. search — top-level command, positional query, --kb required. // --kb accepts either kb_ (passed through) or a name (resolved via - // list); kb_ prefix detection happens client-side, mirroring gcloud + // list); UUID-format detection happens client-side, mirroring gcloud // --project's id-or-name auto-detection. { name: "search.success", - args: []string{"search", "query", "--kb=kb_1", "--top-k=3", "--json"}, + args: []string{"search", "query", "--kb=11111111-1111-4111-8111-111111111111", "--top-k=3", "--json"}, server: searchTwoResults, }, { name: "search.error_resource_not_found", - args: []string{"search", "query", "--kb=kb_missing", "--json"}, + args: []string{"search", "query", "--kb=eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "--json"}, server: always404, wantErr: true, }, { - // --no-vector + --no-keyword is the input.invalid case; --kb=kb_1 is - // just there to satisfy MarkFlagRequired so validation runs deep + // --no-vector + --no-keyword is the input.invalid case; the KB UUID + // is just there to satisfy MarkFlagRequired so validation runs deep // enough to hit the mutex-channel check. name: "search.error_input_invalid", - args: []string{"search", "query", "--kb=kb_1", "--no-vector", "--no-keyword", "--json"}, + args: []string{"search", "query", "--kb=11111111-1111-4111-8111-111111111111", "--no-vector", "--no-keyword", "--json"}, wantErr: true, }, } @@ -331,7 +331,7 @@ func kbGetOne(w http.ResponseWriter, r *http.Request) { } func searchTwoResults(w http.ResponseWriter, r *http.Request) { - if !strings.Contains(r.URL.Path, "/knowledge-bases/kb_1/hybrid-search") { + if !strings.Contains(r.URL.Path, "/knowledge-bases/11111111-1111-4111-8111-111111111111/hybrid-search") { w.WriteHeader(http.StatusNotFound) return } diff --git a/cli/acceptance/contract/helpers_test.go b/cli/acceptance/contract/helpers_test.go index 97dde0d3..72878802 100644 --- a/cli/acceptance/contract/helpers_test.go +++ b/cli/acceptance/contract/helpers_test.go @@ -11,11 +11,27 @@ import ( "testing" "github.com/Tencent/WeKnora/cli/cmd" + "github.com/Tencent/WeKnora/cli/cmd/doctor" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/iostreams" + "github.com/Tencent/WeKnora/cli/internal/secrets" sdk "github.com/Tencent/WeKnora/client" ) +// TestMain pins the doctor credential-storage outcome for the whole suite. +// Otherwise the check probes the real OS keyring, which differs between +// macOS dev machines (Keychain present → ok) and Linux CI runners without +// libsecret (file fallback → warn), making golden envelopes host-dependent. +// MemStore is neither *FileStore nor a real keyring, so the doctor's +// type-switch hits the StatusOK branch. +func TestMain(m *testing.M) { + restore := doctor.SetCredStoreFactoryForTest(func() (secrets.Store, error) { + return secrets.NewMemStore(), nil + }) + defer restore() + os.Exit(m.Run()) +} + // update is the standard Go test golden-update flag. // go test -update ./acceptance/contract/... // Mirrors gh / kubectl / golang-migrate convention. diff --git a/cli/acceptance/testdata/envelopes/search.success.json b/cli/acceptance/testdata/envelopes/search.success.json index a3dd63f2..298c89c9 100644 --- a/cli/acceptance/testdata/envelopes/search.success.json +++ b/cli/acceptance/testdata/envelopes/search.success.json @@ -1 +1 @@ -{"ok":true,"data":[{"id":"chunk-1","content":"first chunk content","knowledge_id":"doc-1","chunk_index":0,"knowledge_title":"Doc 1","start_at":0,"end_at":0,"seq":0,"score":0.92,"match_type":0,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""},{"id":"chunk-2","content":"second chunk content","knowledge_id":"doc-2","chunk_index":1,"knowledge_title":"Doc 2","start_at":0,"end_at":0,"seq":0,"score":0.81,"match_type":1,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""}],"_meta":{"kb_id":"kb_1"},"dry_run":false} +{"ok":true,"data":[{"id":"chunk-1","content":"first chunk content","knowledge_id":"doc-1","chunk_index":0,"knowledge_title":"Doc 1","start_at":0,"end_at":0,"seq":0,"score":0.92,"match_type":0,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""},{"id":"chunk-2","content":"second chunk content","knowledge_id":"doc-2","chunk_index":1,"knowledge_title":"Doc 2","start_at":0,"end_at":0,"seq":0,"score":0.81,"match_type":1,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""}],"_meta":{"kb_id":"11111111-1111-4111-8111-111111111111"},"dry_run":false} diff --git a/cli/cmd/chat/chat.go b/cli/cmd/chat/chat.go index 2010a620..056da3a2 100644 --- a/cli/cmd/chat/chat.go +++ b/cli/cmd/chat/chat.go @@ -77,7 +77,7 @@ answer back. By default a fresh session is created on first invocation; pass Modes: TTY (default): live token streaming + reference footer Pipe / --no-stream / --json: buffered, emitted once on completion`, - Example: ` weknora chat "What is RRF?" --kb kb_123 + Example: ` weknora chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694 weknora chat "Summarise this design doc" --kb my-kb --json weknora chat "Continue?" --session-id sess_abc`, Args: cobra.MinimumNArgs(1), @@ -98,7 +98,7 @@ Modes: return runChat(c.Context(), opts, cli) }, } - cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides project link / env)") + cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides project link / env)") cmd.Flags().StringVar(&opts.SessionID, "session-id", "", "Continue an existing chat session (skip auto-create)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)") diff --git a/cli/cmd/chat/chat_test.go b/cli/cmd/chat/chat_test.go index 4c4373f9..118bbf32 100644 --- a/cli/cmd/chat/chat_test.go +++ b/cli/cmd/chat/chat_test.go @@ -64,11 +64,12 @@ func TestChat_StreamMode(t *testing.T) { out, errBuf := iostreams.SetForTestWithTTY(t) svc := &fakeChatService{ streamEvents: []*sdk.StreamResponse{ - {Content: "Hello "}, - {Content: "world"}, - {Done: true, KnowledgeReferences: []*sdk.SearchResult{ + {ResponseType: sdk.ResponseTypeAnswer, Content: "Hello "}, + {ResponseType: sdk.ResponseTypeAnswer, Content: "world"}, + {ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{ {KnowledgeID: "k1", KnowledgeTitle: "Doc One", Score: 0.42}, }}, + {ResponseType: sdk.ResponseTypeComplete, Done: true}, }, } opts := &Options{Query: "hi", KBID: "kb_1"} @@ -106,7 +107,8 @@ func TestChat_JSONMode(t *testing.T) { streamEvents: []*sdk.StreamResponse{ {Content: "answer body"}, {AssistantMessageID: "msg_99"}, - {Done: true, KnowledgeReferences: []*sdk.SearchResult{{KnowledgeID: "k1"}}}, + {ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{{KnowledgeID: "k1"}}}, + {ResponseType: sdk.ResponseTypeComplete, Done: true}, }, } opts := &Options{Query: "q", KBID: "kb_42", JSONOut: true} @@ -166,9 +168,9 @@ func TestChat_NoStreamFlag(t *testing.T) { var written string svc := &fakeChatService{ streamEvents: []*sdk.StreamResponse{ - {Content: "buffered "}, - {Content: "answer"}, - {Done: true}, + {ResponseType: sdk.ResponseTypeAnswer, Content: "buffered "}, + {ResponseType: sdk.ResponseTypeAnswer, Content: "answer"}, + {ResponseType: sdk.ResponseTypeComplete, Done: true}, }, } opts := &Options{Query: "q", KBID: "kb", NoStream: true} @@ -186,8 +188,8 @@ func TestChat_NonTTY_AccumulateMode(t *testing.T) { out, _ := iostreams.SetForTest(t) svc := &fakeChatService{ streamEvents: []*sdk.StreamResponse{ - {Content: "piped"}, - {Done: true}, + {ResponseType: sdk.ResponseTypeAnswer, Content: "piped"}, + {ResponseType: sdk.ResponseTypeComplete, Done: true}, }, } opts := &Options{Query: "q", KBID: "kb"} @@ -202,7 +204,7 @@ func TestChat_NonTTY_AccumulateMode(t *testing.T) { func TestChat_SessionIDProvided(t *testing.T) { _, errBuf := iostreams.SetForTestWithTTY(t) svc := &fakeChatService{ - streamEvents: []*sdk.StreamResponse{{Done: true}}, + streamEvents: []*sdk.StreamResponse{{ResponseType: sdk.ResponseTypeComplete, Done: true}}, } opts := &Options{Query: "q", KBID: "kb", SessionID: "sess_existing"} if err := runChat(context.Background(), opts, svc); err != nil { diff --git a/cli/cmd/doc/list.go b/cli/cmd/doc/list.go index d62f3637..1f9ef3d1 100644 --- a/cli/cmd/doc/list.go +++ b/cli/cmd/doc/list.go @@ -52,14 +52,14 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { Long: `Lists documents (uploaded files / web pages / inline text) in the resolved knowledge base. KB resolution follows the standard 4-level chain: --kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error. The --kb -flag accepts either a kb_ or a name (resolved via list). +flag accepts either a KB UUID (passed through) or a name (resolved via list). Default sort is updated_at desc so the most recent uploads surface first; backend storage order is not guaranteed and varies between deployments.`, - Example: ` weknora doc list # uses project link / env - weknora doc list --kb kb_abc # explicit id - weknora doc list --kb my-kb # resolved by name - weknora doc list --page 2 --json # paginated envelope output`, + Example: ` weknora doc list # uses project link / env + weknora doc list --kb a32a63ff-fb36-4874-bcaa-30f48570a694 # explicit UUID + weknora doc list --kb my-kb # resolved by name + weknora doc list --page 2 --json # paginated envelope output`, Args: cobra.NoArgs, RunE: func(c *cobra.Command, _ []string) error { kbID, err := f.ResolveKB(c) @@ -75,7 +75,7 @@ backend storage order is not guaranteed and varies between deployments.`, } // --kb is read by Factory.ResolveKB; declare it here so cobra parses the // value into the command's flag set. - cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides env / project link)") + cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)") cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)") cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.go index 412b2169..1f056bf5 100644 --- a/cli/cmd/doc/upload.go +++ b/cli/cmd/doc/upload.go @@ -47,7 +47,7 @@ func NewCmdUpload(f *cmdutil.Factory) *cobra.Command { Long: `Uploads a file (PDF / DOCX / Markdown / TXT / etc.) to the resolved knowledge base. KB resolution follows the standard 4-level chain: --kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error. The --kb -flag accepts either a kb_ or a name (resolved via list). +flag accepts either a KB UUID (passed through) or a name (resolved via list). Pass --name to override the recorded file name (useful when the local file has a generic name like "report.pdf" but you want to surface it as e.g. @@ -56,7 +56,7 @@ has a generic name like "report.pdf" but you want to surface it as e.g. v0.2 ships single-file upload only; --recursive / --glob and progress UI are planned for v0.3.`, Example: ` weknora doc upload report.pdf - weknora doc upload notes.md --kb kb_abc + weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694 weknora doc upload notes.md --kb my-kb weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"`, Args: cobra.ExactArgs(1), @@ -80,7 +80,7 @@ planned for v0.3.`, return runUpload(c.Context(), opts, cli, kbID, path) }, } - cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides env / project link)") + cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)") cmd.Flags().StringVar(&opts.Name, "name", "", "Custom file name to record (defaults to base name)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") agent.SetAgentHelp(cmd, "Uploads one local file to the resolved KB. Refuses non-regular files (dir / symlink). Returns data: Knowledge object with id, parse_status. Pass --kb outside a linked project.") diff --git a/cli/cmd/doctor/doctor.go b/cli/cmd/doctor/doctor.go index 9c148dea..cfbb440d 100644 --- a/cli/cmd/doctor/doctor.go +++ b/cli/cmd/doctor/doctor.go @@ -240,6 +240,25 @@ func fillVersionCheck(c *Check, info *compat.Info, cliVer string, fromCache bool // at secrets.NewBestEffortStore. var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEffortStore() } +// SetCredStoreFactoryForTest overrides the credential-storage factory used by +// runChecks and returns a cleanup function that restores the previous value. +// Exported so out-of-package tests (notably cli/acceptance/contract) can +// pin the credential_storage outcome — otherwise the check probes the real +// OS keyring, which is present on macOS dev machines but not on Linux CI +// runners without libsecret, producing host-dependent test flakes. +// +// Usage: +// +// restore := doctor.SetCredStoreFactoryForTest(func() (secrets.Store, error) { +// return secrets.NewMemStore(), nil // not *FileStore → StatusOK +// }) +// defer restore() +func SetCredStoreFactoryForTest(fn func() (secrets.Store, error)) (restore func()) { + saved := credStoreFactory + credStoreFactory = fn + return func() { credStoreFactory = saved } +} + // fillCredentialStorageCheck distinguishes the three terminal states the // secrets layer can produce: // diff --git a/cli/cmd/doctor/doctor_test.go b/cli/cmd/doctor/doctor_test.go index c45d1cb7..455c428b 100644 --- a/cli/cmd/doctor/doctor_test.go +++ b/cli/cmd/doctor/doctor_test.go @@ -57,6 +57,12 @@ func goodUserResp() *sdk.CurrentUserResponse { func TestDoctor_AllOK(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) out, _ := iostreams.SetForTest(t) + // Pin credential_storage to ok so this test doesn't probe the host OS + // keyring — macOS dev machines have Keychain, Linux CI without libsecret + // would otherwise warn and break the AllPassed assertion. + withCredStoreFactory(t, func() (secrets.Store, error) { + return secrets.NewMemStore(), nil + }) svc := &fakeServices{ systemInfo: &sdk.SystemInfo{Version: "1.0.0"}, userResp: goodUserResp(), @@ -173,6 +179,11 @@ func TestDoctor_NoConfig_StillRunsCredentialStorage(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir()) _, _ = iostreams.SetForTest(t) + // Pin credential_storage to ok regardless of host keyring presence + // (Linux CI without libsecret would otherwise warn). + withCredStoreFactory(t, func() (secrets.Store, error) { + return secrets.NewMemStore(), nil + }) f := cmdutil.New() svc, err := buildServices(f) diff --git a/cli/cmd/link/link.go b/cli/cmd/link/link.go index 51d30f86..b4fe89d0 100644 --- a/cli/cmd/link/link.go +++ b/cli/cmd/link/link.go @@ -25,7 +25,7 @@ import ( // Options captures `weknora link` flags. type Options struct { Context string // --context: record a specific context instead of the active one - KB string // --kb: kb_ or name; empty triggers interactive prompt on TTY + KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY JSONOut bool // --json } @@ -54,16 +54,16 @@ any existing link — re-run to switch. AI agents: link writes to the user's working directory. Only run it when the user explicitly asked to bind this directory; don't run it as a side effect.`, - Example: ` weknora link --kb kb_abc # explicit id - weknora link --kb engineering # name → id - weknora link # interactive (TTY)`, + Example: ` weknora link --kb a32a63ff-fb36-4874-bcaa-30f48570a694 # explicit UUID + weknora link --kb engineering # name → id + weknora link # interactive (TTY)`, Args: cobra.NoArgs, RunE: func(c *cobra.Command, _ []string) error { return runLink(c.Context(), opts, f) }, } cmd.Flags().StringVar(&opts.Context, "context", "", "Context to record in the link (defaults to active context)") - cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base id (kb_…) or name; omit on a TTY for interactive prompt") + cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") agent.SetAgentHelp(cmd, "Writes .weknora/project.yaml binding cwd to a KB. Pass --kb (id or name) for non-interactive use. Always overwrites.") return cmd diff --git a/cli/cmd/link/link_test.go b/cli/cmd/link/link_test.go index 4bcbfb82..176c6a74 100644 --- a/cli/cmd/link/link_test.go +++ b/cli/cmd/link/link_test.go @@ -64,13 +64,13 @@ func TestLink_ByID(t *testing.T) { out, _ := iostreams.SetForTest(t) f := newFactory("default", nil) - opts := &Options{KB: "kb_xxx"} + opts := &Options{KB: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"} require.NoError(t, runLink(context.Background(), opts, f)) linkPath := filepath.Join(dir, ".weknora", "project.yaml") p, err := projectlink.Load(linkPath) require.NoError(t, err) - assert.Equal(t, "kb_xxx", p.KBID) + assert.Equal(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", p.KBID) assert.Equal(t, "default", p.Context) assert.Contains(t, out.String(), "✓") } @@ -118,16 +118,16 @@ 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: "kb_old", + Context: "default", KBID: "11111111-1111-4111-8111-111111111111", })) f := newFactory("default", nil) - opts := &Options{KB: "kb_new"} + opts := &Options{KB: "22222222-2222-4222-8222-222222222222"} require.NoError(t, runLink(context.Background(), opts, f)) p, err := projectlink.Load(linkPath) require.NoError(t, err) - assert.Equal(t, "kb_new", p.KBID, "link should overwrite silently") + assert.Equal(t, "22222222-2222-4222-8222-222222222222", p.KBID, "link should overwrite silently") } // TestLink_NonInteractive_NoKB exercises the non-TTY-without-flag error path. diff --git a/cli/cmd/search/search.go b/cli/cmd/search/search.go index 6e21f432..4131de55 100644 --- a/cli/cmd/search/search.go +++ b/cli/cmd/search/search.go @@ -18,7 +18,7 @@ import ( // Options is the runtime configuration of one search invocation. type Options struct { Query string - KB string // raw --kb flag value (kb_ or name) + KB string // raw --kb flag value (UUID or name) KBID string // resolved id, populated by RunE before HybridSearch TopK int VectorThreshold float64 @@ -36,7 +36,7 @@ type Service interface { // NewCmdSearch builds `weknora search "" --kb `. // -// The single `--kb` flag accepts either a `kb_…` id (passed through) or a +// The single `--kb` flag accepts either a KB UUID (passed through) or a // name (resolved via ListKnowledgeBases). Mirrors gcloud `--project`'s // id-or-name auto-detection — the only mainstream pattern that collapses // the two forms onto one flag. @@ -70,7 +70,7 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command { return runSearch(c.Context(), opts, cli) }, } - cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base id (kb_…) or name") + cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name") cmd.Flags().IntVar(&opts.TopK, "top-k", 8, "Maximum results to return") cmd.Flags().Float64Var(&opts.VectorThreshold, "vector-threshold", 0, "Vector retrieval similarity floor (per-channel, pre-fusion); 0 = no filter") cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter") diff --git a/cli/internal/cmdutil/factory_test.go b/cli/internal/cmdutil/factory_test.go index 31a0ebb3..6b447a39 100644 --- a/cli/internal/cmdutil/factory_test.go +++ b/cli/internal/cmdutil/factory_test.go @@ -306,7 +306,7 @@ func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server { // isolates cwd / env / closure from the others. func TestResolveKB_Chain(t *testing.T) { t.Run("flag_kb_id_wins", func(t *testing.T) { - // kb_ form → no SDK call, no env, no disk. + // UUID form on --kb → pass-through; no SDK call, no env, no disk. t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose") dir := t.TempDir() resolveKBChdir(t, dir) @@ -320,9 +320,9 @@ func TestResolveKB_Chain(t *testing.T) { return nil, errors.New("must not be called") }, } - got, err := f.ResolveKB(makeResolveKBCmd(t, "kb_explicit")) + got, err := f.ResolveKB(makeResolveKBCmd(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) require.NoError(t, err) - assert.Equal(t, "kb_explicit", got) + assert.Equal(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", got) assert.Equal(t, 0, clientCalls) }) diff --git a/cli/internal/cmdutil/kb.go b/cli/internal/cmdutil/kb.go index 37faa652..9e5f18d0 100644 --- a/cli/internal/cmdutil/kb.go +++ b/cli/internal/cmdutil/kb.go @@ -3,20 +3,20 @@ package cmdutil import ( "context" "fmt" - "strings" + "regexp" sdk "github.com/Tencent/WeKnora/client" ) -// kbIDPrefix is the server-emitted prefix that marks a string as a KB id -// (rather than a KB name). The single `--kb` flag uses it for client-side -// id-vs-name auto-detection — the same pattern gcloud uses for --project -// (numeric id vs project-id form). -const kbIDPrefix = "kb_" +// uuidPattern matches the canonical 8-4-4-4-12 UUID form. WeKnora's KB ids +// are uuid.New().String() output stored as varchar(36); names are arbitrary +// user-supplied strings, so format-detection is unambiguous. +var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) // IsKBID reports whether s looks like a KB id. Used by Factory.ResolveKB and -// any caller that accepts a single id-or-name selector value. -func IsKBID(s string) bool { return strings.HasPrefix(s, kbIDPrefix) } +// any caller that accepts a single id-or-name selector value — same pattern +// gcloud uses for --project (id vs name auto-detection). +func IsKBID(s string) bool { return uuidPattern.MatchString(s) } // KBLister is the narrow SDK surface ResolveKBNameToID depends on. The // production *sdk.Client satisfies it; tests inject fakes without standing diff --git a/cli/internal/sse/accumulator.go b/cli/internal/sse/accumulator.go index bcd849df..56c106fe 100644 --- a/cli/internal/sse/accumulator.go +++ b/cli/internal/sse/accumulator.go @@ -42,11 +42,18 @@ func (a *Accumulator) Append(r *sdk.StreamResponse) { if r.AssistantMessageID != "" && a.AssistantMessageID == "" { a.AssistantMessageID = r.AssistantMessageID } - if r.Done { - // Terminal events carry References; capture once. - if r.KnowledgeReferences != nil { - a.References = r.KnowledgeReferences - } + // Capture references whenever they arrive — they may land on a + // dedicated `references` event before the terminal `complete`. + if r.KnowledgeReferences != nil { + a.References = r.KnowledgeReferences + } + // Stream is only truly done on response_type=complete. Other events + // (notably the leading agent_query metadata frame) carry done=true to + // mark their own per-event completion, but the answer fragments arrive + // in subsequent response_type=answer events. Gating on response_type + // avoids the off-by-one termination that would discard the entire + // answer. + if r.ResponseType == sdk.ResponseTypeComplete { a.finished = true } } diff --git a/cli/internal/sse/accumulator_test.go b/cli/internal/sse/accumulator_test.go index 3327d13e..7547c851 100644 --- a/cli/internal/sse/accumulator_test.go +++ b/cli/internal/sse/accumulator_test.go @@ -7,10 +7,16 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) +// terminator is the canonical "stream is done" event the accumulator +// recognises. The server emits response_type=complete after the answer +// fragments and any references; per-event done=true on agent_query / +// answer frames is NOT terminal. +var terminator = &sdk.StreamResponse{ResponseType: sdk.ResponseTypeComplete, Done: true} + func TestAccumulator_AppendsContent(t *testing.T) { a := &sse.Accumulator{} - a.Append(&sdk.StreamResponse{Content: "Hello "}) - a.Append(&sdk.StreamResponse{Content: "world"}) + a.Append(&sdk.StreamResponse{ResponseType: sdk.ResponseTypeAnswer, Content: "Hello "}) + a.Append(&sdk.StreamResponse{ResponseType: sdk.ResponseTypeAnswer, Content: "world"}) if got := a.Result(); got != "Hello world" { t.Errorf("got %q, want %q", got, "Hello world") } @@ -19,15 +25,17 @@ func TestAccumulator_AppendsContent(t *testing.T) { } } -func TestAccumulator_FinalizesOnDone(t *testing.T) { +func TestAccumulator_FinalizesOnComplete(t *testing.T) { a := &sse.Accumulator{} - a.Append(&sdk.StreamResponse{Content: "answer"}) + a.Append(&sdk.StreamResponse{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"}) + // References may arrive on a dedicated event before the terminator. a.Append(&sdk.StreamResponse{ - Done: true, + ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{{KnowledgeID: "k1"}}, }) + a.Append(terminator) if !a.Done() { - t.Error("expected Done=true") + t.Error("expected Done=true after response_type=complete") } if len(a.References) != 1 { t.Errorf("expected 1 reference, got %d", len(a.References)) @@ -37,13 +45,37 @@ func TestAccumulator_FinalizesOnDone(t *testing.T) { } } -func TestAccumulator_IgnoresPostDone(t *testing.T) { +func TestAccumulator_IgnoresAgentQueryDone(t *testing.T) { + // Server emits a leading agent_query frame with done=true to deliver + // session metadata; the accumulator must NOT treat that as terminal — + // otherwise the answer fragments that follow would be discarded. a := &sse.Accumulator{} - a.Append(&sdk.StreamResponse{Content: "first"}) - a.Append(&sdk.StreamResponse{Done: true}) - a.Append(&sdk.StreamResponse{Content: "after"}) + a.Append(&sdk.StreamResponse{ + ResponseType: sdk.ResponseTypeAgentQuery, + Done: true, + SessionID: "sess_123", + AssistantMessageID: "msg_456", + }) + a.Append(&sdk.StreamResponse{ResponseType: sdk.ResponseTypeAnswer, Content: "real answer"}) + a.Append(terminator) + if !a.Done() { + t.Error("expected Done=true after response_type=complete") + } + if got := a.Result(); got != "real answer" { + t.Errorf("agent_query done=true should not terminate; got %q", got) + } + if a.SessionID != "sess_123" { + t.Errorf("session metadata from agent_query frame lost: got %q", a.SessionID) + } +} + +func TestAccumulator_IgnoresPostComplete(t *testing.T) { + a := &sse.Accumulator{} + a.Append(&sdk.StreamResponse{ResponseType: sdk.ResponseTypeAnswer, Content: "first"}) + a.Append(terminator) + a.Append(&sdk.StreamResponse{ResponseType: sdk.ResponseTypeAnswer, Content: "after"}) if got := a.Result(); got != "first" { - t.Errorf("post-Done append should be no-op, got %q", got) + t.Errorf("post-complete append should be no-op, got %q", got) } } @@ -61,11 +93,12 @@ func TestAccumulator_NilSafe(t *testing.T) { func TestAccumulator_CapturesSessionMetadata(t *testing.T) { a := &sse.Accumulator{} a.Append(&sdk.StreamResponse{ + ResponseType: sdk.ResponseTypeAnswer, SessionID: "sess_123", AssistantMessageID: "msg_456", Content: "hi", }) - a.Append(&sdk.StreamResponse{Done: true}) + a.Append(terminator) if a.SessionID != "sess_123" { t.Errorf("SessionID: got %q", a.SessionID) }