test(api): cover resource_urls=public across the rewriter, handlers and SSE wire
Includes an end-to-end ContinueStream test that asserts the full SSE wire output. It caught a leak: the references event carries its results twice, and the copy in Data holds the typed []*SearchResult that CopyData did not traverse, so handles reached a caller that asked for public URLs. CopyData now handles the typed slice, []string and map[string]string forms. Co-authored-by: lyingbug <lyingbug@users.noreply.github.com>main
parent
877a6ebf9d
commit
96e28b2438
|
|
@ -0,0 +1,136 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// stubResourceFileService resolves any storage reference to one fixed public URL.
|
||||
type stubResourceFileService struct {
|
||||
interfaces.FileService
|
||||
url string
|
||||
}
|
||||
|
||||
func (s *stubResourceFileService) GetFileURL(context.Context, string) (string, error) {
|
||||
return s.url, nil
|
||||
}
|
||||
|
||||
func (s *stubResourceFileService) SaveFile(
|
||||
context.Context, *multipart.FileHeader, uint64, string,
|
||||
) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *stubResourceFileService) GetFile(context.Context, string) (io.ReadCloser, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
const testResourceHandle = "resource://xifDo7NTSL300Lp1goVutw"
|
||||
|
||||
func newResourceURLTestRouter(t *testing.T, messages []*types.Message) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
h := &MessageHandler{
|
||||
MessageService: &stubMessageService{
|
||||
getRecent: func(context.Context, string, int) ([]*types.Message, error) {
|
||||
return messages, nil
|
||||
},
|
||||
},
|
||||
FileService: &stubResourceFileService{url: "https://cdn.example.com/signed.png"},
|
||||
}
|
||||
r.GET("/messages/:session_id/load", h.LoadMessages)
|
||||
return r
|
||||
}
|
||||
|
||||
func loadMessageContent(t *testing.T, router *gin.Engine, query string) string {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/messages/sess1/load"+query, nil))
|
||||
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
|
||||
|
||||
var body struct {
|
||||
Data []struct {
|
||||
Content string `json:"content"`
|
||||
Images []struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"images"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
|
||||
require.Len(t, body.Data, 1)
|
||||
return body.Data[0].Content
|
||||
}
|
||||
|
||||
// Without the parameter, history must keep returning handles so existing clients
|
||||
// (including the WeKnora frontend, which proxies through /files) are unaffected.
|
||||
func TestLoadMessages_DefaultsToHandles(t *testing.T) {
|
||||
router := newResourceURLTestRouter(t, []*types.Message{
|
||||
{Content: "see "},
|
||||
})
|
||||
assert.Equal(t, "see ", loadMessageContent(t, router, ""))
|
||||
}
|
||||
|
||||
func TestLoadMessages_PublicModeReturnsLoadableURLs(t *testing.T) {
|
||||
router := newResourceURLTestRouter(t, []*types.Message{
|
||||
{
|
||||
Content: "see ",
|
||||
Images: types.MessageImages{{URL: testResourceHandle}},
|
||||
},
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest(
|
||||
http.MethodGet, "/messages/sess1/load?resource_urls=public", nil))
|
||||
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
|
||||
|
||||
body := w.Body.String()
|
||||
assert.Contains(t, body, "https://cdn.example.com/signed.png")
|
||||
assert.NotContains(t, body, "resource://")
|
||||
}
|
||||
|
||||
// A typo must be reported rather than silently falling back to handles, so an
|
||||
// integrator finds the mistake instead of debugging "broken images".
|
||||
func TestLoadMessages_RejectsInvalidResourceURLMode(t *testing.T) {
|
||||
router := newResourceURLTestRouter(t, nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest(
|
||||
http.MethodGet, "/messages/sess1/load?resource_urls=signed", nil))
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code, "body=%s", w.Body.String())
|
||||
assert.Contains(t, w.Body.String(), "resource_urls")
|
||||
}
|
||||
|
||||
// The deployment-wide default lets an operator switch every integration over
|
||||
// without changing client code.
|
||||
func TestLoadMessages_DeploymentDefaultAppliesWithoutParameter(t *testing.T) {
|
||||
t.Setenv("RESOURCE_URL_MODE", "public")
|
||||
router := newResourceURLTestRouter(t, []*types.Message{
|
||||
{Content: "see "},
|
||||
})
|
||||
assert.Equal(t, "see ",
|
||||
loadMessageContent(t, router, ""))
|
||||
}
|
||||
|
||||
// An explicit parameter must still win over the deployment default.
|
||||
func TestLoadMessages_ParameterOverridesDeploymentDefault(t *testing.T) {
|
||||
t.Setenv("RESOURCE_URL_MODE", "public")
|
||||
router := newResourceURLTestRouter(t, []*types.Message{
|
||||
{Content: "see "},
|
||||
})
|
||||
assert.Equal(t, "see ",
|
||||
loadMessageContent(t, router, "?resource_urls=handle"))
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// The stubs below implement only the methods ContinueStream reaches; embedding
|
||||
// each interface keeps everything else nil-panicky so an un-stubbed call fails
|
||||
// loudly rather than returning a zero value.
|
||||
|
||||
type stubSessionService struct {
|
||||
interfaces.SessionService
|
||||
}
|
||||
|
||||
func (s *stubSessionService) GetSession(_ context.Context, id string) (*types.Session, error) {
|
||||
return &types.Session{ID: id, TenantID: 1}, nil
|
||||
}
|
||||
|
||||
type stubMessageServiceForStream struct {
|
||||
interfaces.MessageService
|
||||
}
|
||||
|
||||
func (s *stubMessageServiceForStream) GetMessage(
|
||||
_ context.Context, sessionID, messageID string,
|
||||
) (*types.Message, error) {
|
||||
return &types.Message{ID: messageID, SessionID: sessionID, RequestID: "req-1"}, nil
|
||||
}
|
||||
|
||||
// stubStreamManager replays a fixed event list, mimicking a completed stream.
|
||||
type stubStreamManager struct {
|
||||
events []interfaces.StreamEvent
|
||||
}
|
||||
|
||||
func (s *stubStreamManager) AppendEvent(
|
||||
context.Context, string, string, interfaces.StreamEvent,
|
||||
) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubStreamManager) GetEvents(
|
||||
_ context.Context, _, _ string, fromOffset int,
|
||||
) ([]interfaces.StreamEvent, int, error) {
|
||||
if fromOffset >= len(s.events) {
|
||||
return nil, len(s.events), nil
|
||||
}
|
||||
return s.events[fromOffset:], len(s.events), nil
|
||||
}
|
||||
|
||||
// completedAnswerStream is one assistant turn whose answer embeds a knowledge-base
|
||||
// image, with the resource handle straddling two deltas as it does in production
|
||||
// when the model-context decoder flushes mid-reference.
|
||||
func completedAnswerStream() []interfaces.StreamEvent {
|
||||
return []interfaces.StreamEvent{
|
||||
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "The diagram  shows the flow."},
|
||||
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "", Done: true},
|
||||
{ID: "refs-1", Type: types.ResponseTypeReferences, Data: map[string]interface{}{
|
||||
"references": types.References{{
|
||||
ID: "chunk-1",
|
||||
Content: "figure ",
|
||||
ImageInfo: `[{"url":"` + testResourceHandle + `"}]`,
|
||||
}},
|
||||
}},
|
||||
{ID: "complete-1", Type: types.ResponseTypeComplete, Done: true},
|
||||
}
|
||||
}
|
||||
|
||||
func newContinueStreamRouter(t *testing.T) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
h := &Handler{
|
||||
sessionService: &stubSessionService{},
|
||||
messageService: &stubMessageServiceForStream{},
|
||||
streamManager: &stubStreamManager{events: completedAnswerStream()},
|
||||
fileService: &stubResourceFileService{},
|
||||
}
|
||||
r.GET("/sessions/continue-stream/:session_id", h.ContinueStream)
|
||||
return r
|
||||
}
|
||||
|
||||
func continueStream(t *testing.T, query string) (int, string) {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
newContinueStreamRouter(t).ServeHTTP(recorder, httptest.NewRequest(
|
||||
http.MethodGet, "/sessions/continue-stream/sess1?message_id=msg1"+query, nil))
|
||||
return recorder.Code, recorder.Body.String()
|
||||
}
|
||||
|
||||
// Default behaviour: the SSE stream keeps carrying internal handles, which the
|
||||
// WeKnora frontend resolves through the authenticated /files proxy.
|
||||
func TestContinueStream_DefaultEmitsHandles(t *testing.T) {
|
||||
code, body := continueStream(t, "")
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
|
||||
assert.Contains(t, body, testResourceHandle)
|
||||
assert.NotContains(t, body, "cdn.example.com")
|
||||
}
|
||||
|
||||
// With resource_urls=public the whole stream — answer text and the references
|
||||
// payload — carries URLs a third-party app can load directly.
|
||||
func TestContinueStream_PublicModeEmitsLoadableURLs(t *testing.T) {
|
||||
code, body := continueStream(t, "&resource_urls=public")
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
|
||||
assert.NotContains(t, body, "resource://",
|
||||
"no internal handle may reach a client that asked for public URLs")
|
||||
assert.Contains(t, body, "https://cdn.example.com/signed.png")
|
||||
|
||||
// The handle was split across two answer deltas; the reassembled Markdown
|
||||
// image must be intact rather than broken in half.
|
||||
assert.Contains(t, body, ` shows the flow.`)
|
||||
|
||||
// The references payload carries both the chunk text and image_info.
|
||||
assert.Contains(t, body, `figure `)
|
||||
assert.Contains(t, body, `[{\"url\":\"https://cdn.example.com/signed.png\"}]`)
|
||||
|
||||
// Every answer delta must precede the completion marker.
|
||||
assert.Less(t, strings.LastIndex(body, `"response_type":"answer"`),
|
||||
strings.Index(body, `"response_type":"complete"`))
|
||||
}
|
||||
|
||||
func TestContinueStream_RejectsInvalidResourceURLMode(t *testing.T) {
|
||||
code, body := continueStream(t, "&resource_urls=signed")
|
||||
assert.Equal(t, http.StatusBadRequest, code, body)
|
||||
assert.Contains(t, body, "resource_urls")
|
||||
}
|
||||
|
|
@ -0,0 +1,205 @@
|
|||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/storageurl"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const testResourceHandle = "resource://xifDo7NTSL300Lp1goVutw"
|
||||
|
||||
// stubResourceFileService resolves any storage reference to one fixed public URL.
|
||||
type stubResourceFileService struct {
|
||||
interfaces.FileService
|
||||
}
|
||||
|
||||
func (s *stubResourceFileService) GetFileURL(context.Context, string) (string, error) {
|
||||
return "https://cdn.example.com/signed.png", nil
|
||||
}
|
||||
|
||||
func (s *stubResourceFileService) SaveFile(
|
||||
context.Context, *multipart.FileHeader, uint64, string,
|
||||
) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *stubResourceFileService) GetFile(context.Context, string) (io.ReadCloser, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func publicStreamRewriter() *storageurl.StreamRewriter {
|
||||
return storageurl.NewStreamRewriter(storageurl.NewRequestRewriter(
|
||||
context.Background(), storageurl.ModePublic, &stubResourceFileService{}, nil))
|
||||
}
|
||||
|
||||
func newTestGinContext(t *testing.T, query string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/knowledge-chat/sess1"+query, nil)
|
||||
return c, recorder
|
||||
}
|
||||
|
||||
// The default mode must leave the stream byte-identical and unbuffered.
|
||||
func TestResolveStreamRewriter_DefaultIsDisabled(t *testing.T) {
|
||||
h := &Handler{fileService: &stubResourceFileService{}}
|
||||
c, _ := newTestGinContext(t, "")
|
||||
|
||||
rewriter, err := h.resolveStreamRewriter(c)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, rewriter.Enabled())
|
||||
}
|
||||
|
||||
func TestResolveStreamRewriter_RejectsInvalidValue(t *testing.T) {
|
||||
h := &Handler{fileService: &stubResourceFileService{}}
|
||||
c, _ := newTestGinContext(t, "?resource_urls=signed")
|
||||
|
||||
_, err := h.resolveStreamRewriter(c)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "resource_urls")
|
||||
}
|
||||
|
||||
// The default mode must not alter a payload at all.
|
||||
func TestBuildStreamResponseFor_DisabledPassesThrough(t *testing.T) {
|
||||
rewriter := storageurl.NewStreamRewriter(storageurl.NewRewriter(nil, "TEST"))
|
||||
evt := interfaces.StreamEvent{
|
||||
ID: "answer-1",
|
||||
Type: types.ResponseTypeAnswer,
|
||||
Content: "see ",
|
||||
}
|
||||
|
||||
response := buildStreamResponseFor(context.Background(), evt, "req-1", rewriter)
|
||||
assert.Equal(t, evt.Content, response.Content)
|
||||
}
|
||||
|
||||
// Answer deltas are chunks the client accumulates, so a handle split across two
|
||||
// events must be held back and rewritten once complete rather than emitted broken.
|
||||
func TestBuildStreamResponseFor_HoldsReferenceSplitAcrossDeltas(t *testing.T) {
|
||||
rewriter := publicStreamRewriter()
|
||||
ctx := context.Background()
|
||||
|
||||
first := buildStreamResponseFor(ctx, interfaces.StreamEvent{
|
||||
ID: "answer-1",
|
||||
Type: types.ResponseTypeAnswer,
|
||||
Content: "see 
|
||||
assert.Equal(t, "see ", first.Content, "the incomplete reference must be held back")
|
||||
|
||||
second := buildStreamResponseFor(ctx, interfaces.StreamEvent{
|
||||
ID: "answer-1",
|
||||
Type: types.ResponseTypeAnswer,
|
||||
Content: "NTSL300Lp1goVutw) done",
|
||||
}, "req-1", rewriter)
|
||||
assert.Equal(t, " done", second.Content)
|
||||
}
|
||||
|
||||
// Interleaved answer and thinking streams must not corrupt each other's buffers.
|
||||
func TestBuildStreamResponseFor_DeltaStreamsAreIndependent(t *testing.T) {
|
||||
rewriter := publicStreamRewriter()
|
||||
ctx := context.Background()
|
||||
|
||||
answer := buildStreamResponseFor(ctx, interfaces.StreamEvent{
|
||||
ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "
|
||||
assert.Empty(t, answer.Content)
|
||||
|
||||
thinking := buildStreamResponseFor(ctx, interfaces.StreamEvent{
|
||||
ID: "think-1", Type: types.ResponseTypeThinking, Content: "reasoning text",
|
||||
}, "req-1", rewriter)
|
||||
assert.Equal(t, "reasoning text", thinking.Content)
|
||||
|
||||
answer = buildStreamResponseFor(ctx, interfaces.StreamEvent{
|
||||
ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "300Lp1goVutw)",
|
||||
}, "req-1", rewriter)
|
||||
assert.Equal(t, "", answer.Content)
|
||||
}
|
||||
|
||||
// Non-delta events carry a complete value, so they must be rewritten immediately
|
||||
// rather than waiting for a chunk that will never arrive.
|
||||
func TestBuildStreamResponseFor_NonDeltaContentIsRewrittenImmediately(t *testing.T) {
|
||||
response := buildStreamResponseFor(context.Background(), interfaces.StreamEvent{
|
||||
ID: "tool-1",
|
||||
Type: types.ResponseTypeToolResult,
|
||||
Content: "chart ",
|
||||
}, "req-1", publicStreamRewriter())
|
||||
assert.Equal(t, "chart ", response.Content)
|
||||
}
|
||||
|
||||
// The references payload and tool metadata share pointers and maps with the
|
||||
// stream replay buffer, so rewriting must not mutate the source event.
|
||||
func TestBuildStreamResponseFor_DoesNotMutateSourceEvent(t *testing.T) {
|
||||
reference := &types.SearchResult{Content: "chunk "}
|
||||
evt := interfaces.StreamEvent{
|
||||
ID: "refs-1",
|
||||
Type: types.ResponseTypeReferences,
|
||||
Data: map[string]interface{}{
|
||||
"references": types.References{reference},
|
||||
"output": "chart ",
|
||||
},
|
||||
}
|
||||
|
||||
response := buildStreamResponseFor(context.Background(), evt, "req-1", publicStreamRewriter())
|
||||
|
||||
require.Len(t, response.KnowledgeReferences, 1)
|
||||
assert.Equal(t, "chunk ",
|
||||
response.KnowledgeReferences[0].Content)
|
||||
assert.Equal(t, "chunk ", reference.Content,
|
||||
"the replay buffer's SearchResult must be untouched")
|
||||
assert.Equal(t, "chart ", evt.Data["output"],
|
||||
"the replay buffer's metadata map must be untouched")
|
||||
assert.Equal(t, "chart ", response.Data["output"])
|
||||
}
|
||||
|
||||
// A trailing reference held back when the stream ends must still be delivered,
|
||||
// as the event type it came from, before the completion marker.
|
||||
func TestEmitStreamEvent_FlushesHeldContentBeforeCompletion(t *testing.T) {
|
||||
rewriter := publicStreamRewriter()
|
||||
ctx := context.Background()
|
||||
c, recorder := newTestGinContext(t, "?resource_urls=public")
|
||||
|
||||
held := buildStreamResponseFor(ctx, interfaces.StreamEvent{
|
||||
ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "tail 
|
||||
require.Equal(t, "tail ", held.Content)
|
||||
|
||||
emitStreamEvent(ctx, c, interfaces.StreamEvent{
|
||||
ID: "complete-1", Type: types.ResponseTypeComplete, Done: true,
|
||||
}, "req-1", rewriter)
|
||||
|
||||
body := recorder.Body.String()
|
||||
assert.Contains(t, body, `"response_type":"answer"`)
|
||||
assert.Contains(t, body, `
|
||||
assert.Less(t,
|
||||
indexOf(body, `"response_type":"answer"`),
|
||||
indexOf(body, `"response_type":"complete"`),
|
||||
"held content must precede the completion marker",
|
||||
)
|
||||
}
|
||||
|
||||
func TestHoldbackKeyRoundTrip(t *testing.T) {
|
||||
responseType, eventID := parseHoldbackKey(holdbackKey(types.ResponseTypeThinking, "think-1"))
|
||||
assert.Equal(t, types.ResponseTypeThinking, responseType)
|
||||
assert.Equal(t, "think-1", eventID)
|
||||
}
|
||||
|
||||
func indexOf(haystack, needle string) int {
|
||||
for i := 0; i+len(needle) <= len(haystack); i++ {
|
||||
if haystack[i:i+len(needle)] == needle {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
|
@ -109,6 +109,31 @@ func (w *Rewriter) copyValue(ctx context.Context, value interface{}, depth int)
|
|||
case string:
|
||||
out := w.String(ctx, typed)
|
||||
return out, out != typed
|
||||
// The references event carries its results twice: once in
|
||||
// StreamResponse.KnowledgeReferences and once in Data. With an in-memory
|
||||
// stream manager these arrive as the typed slice rather than the decoded
|
||||
// []interface{} a Redis round-trip produces, so both forms need a case or
|
||||
// the Data copy leaks handles the caller asked to have resolved.
|
||||
case types.References:
|
||||
return types.References(w.CopyReferences(ctx, typed)), true
|
||||
case []*types.SearchResult:
|
||||
return w.CopyReferences(ctx, typed), true
|
||||
case []string:
|
||||
out := make([]string, len(typed))
|
||||
changed := false
|
||||
for i, item := range typed {
|
||||
out[i] = w.String(ctx, item)
|
||||
changed = changed || out[i] != item
|
||||
}
|
||||
return out, changed
|
||||
case map[string]string:
|
||||
out := make(map[string]string, len(typed))
|
||||
changed := false
|
||||
for key, item := range typed {
|
||||
out[key] = w.String(ctx, item)
|
||||
changed = changed || out[key] != item
|
||||
}
|
||||
return out, changed
|
||||
case map[string]interface{}:
|
||||
out := make(map[string]interface{}, len(typed))
|
||||
changed := false
|
||||
|
|
|
|||
|
|
@ -0,0 +1,198 @@
|
|||
package storageurl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func publicRewriter(url string) *Rewriter {
|
||||
return NewRewriter(stubResolver(url), "TEST")
|
||||
}
|
||||
|
||||
func TestNewRequestRewriter_HandleModeIsDisabled(t *testing.T) {
|
||||
w := NewRequestRewriter(context.Background(), ModeHandle, &stubFileService{}, nil)
|
||||
assert.False(t, w.Enabled(), "the default mode must not resolve anything")
|
||||
}
|
||||
|
||||
func TestNewRequestRewriter_PublicModeIsEnabled(t *testing.T) {
|
||||
w := NewRequestRewriter(context.Background(), ModePublic, &stubFileService{}, nil)
|
||||
require.True(t, w.Enabled())
|
||||
assert.Equal(t, "https://cdn.example.com/resource://xifDo7NTSL300Lp1goVutw",
|
||||
w.Ref(context.Background(), "resource://xifDo7NTSL300Lp1goVutw"))
|
||||
}
|
||||
|
||||
func TestRewriteMessages(t *testing.T) {
|
||||
w := publicRewriter("https://cdn.example.com/x.png")
|
||||
ctx := context.Background()
|
||||
|
||||
messages := []*types.Message{
|
||||
nil,
|
||||
{
|
||||
Content: "answer ",
|
||||
Images: types.MessageImages{{
|
||||
URL: "resource://aaaabbbbccccddddeeeeff",
|
||||
Caption: "shows ",
|
||||
}},
|
||||
KnowledgeReferences: types.References{{
|
||||
Content: "chunk ",
|
||||
ImageInfo: `[{"url":"resource://xifDo7NTSL300Lp1goVutw"}]`,
|
||||
}},
|
||||
AgentSteps: types.AgentSteps{{
|
||||
Thought: "looking at ",
|
||||
ToolCalls: []types.ToolCall{{
|
||||
Reflection: "saw ",
|
||||
Result: &types.ToolResult{Output: "chart "},
|
||||
}},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
w.RewriteMessages(ctx, messages)
|
||||
|
||||
message := messages[1]
|
||||
assert.Equal(t, "answer ", message.Content)
|
||||
assert.Equal(t, "https://cdn.example.com/x.png", message.Images[0].URL)
|
||||
assert.Equal(t, "shows ", message.Images[0].Caption)
|
||||
assert.Equal(t, "chunk ", message.KnowledgeReferences[0].Content)
|
||||
assert.Equal(t, `[{"url":"https://cdn.example.com/x.png"}]`, message.KnowledgeReferences[0].ImageInfo)
|
||||
assert.Equal(t, "looking at ", message.AgentSteps[0].Thought)
|
||||
assert.Equal(t, "saw ", message.AgentSteps[0].ToolCalls[0].Reflection)
|
||||
assert.Equal(t, "chart ", message.AgentSteps[0].ToolCalls[0].Result.Output)
|
||||
}
|
||||
|
||||
func TestRewriteMessages_DisabledLeavesHandles(t *testing.T) {
|
||||
w := NewRewriter(nil, "TEST")
|
||||
messages := []*types.Message{{Content: ""}}
|
||||
w.RewriteMessages(context.Background(), messages)
|
||||
assert.Equal(t, "", messages[0].Content)
|
||||
}
|
||||
|
||||
// SSE references payloads share their *SearchResult pointers with the stream
|
||||
// replay buffer and the assistant message being persisted, so rewriting must not
|
||||
// mutate the originals.
|
||||
func TestCopyReferences_DoesNotMutateOriginals(t *testing.T) {
|
||||
w := publicRewriter("https://cdn.example.com/x.png")
|
||||
original := &types.SearchResult{
|
||||
Content: "chunk ",
|
||||
MatchedContent: "match ",
|
||||
ImageInfo: `[{"url":"resource://xifDo7NTSL300Lp1goVutw"}]`,
|
||||
}
|
||||
refs := []*types.SearchResult{original, nil}
|
||||
|
||||
out := w.CopyReferences(context.Background(), refs)
|
||||
|
||||
require.Len(t, out, 2)
|
||||
assert.NotSame(t, original, out[0])
|
||||
assert.Equal(t, "chunk ", original.Content,
|
||||
"the replay buffer's copy must be untouched")
|
||||
assert.Equal(t, "chunk ", out[0].Content)
|
||||
assert.Equal(t, "match ", out[0].MatchedContent)
|
||||
assert.Equal(t, `[{"url":"https://cdn.example.com/x.png"}]`, out[0].ImageInfo)
|
||||
assert.Nil(t, out[1])
|
||||
}
|
||||
|
||||
func TestCopyReferences_DisabledReturnsInput(t *testing.T) {
|
||||
w := NewRewriter(nil, "TEST")
|
||||
refs := []*types.SearchResult{{Content: ""}}
|
||||
assert.Equal(t, refs, w.CopyReferences(context.Background(), refs))
|
||||
}
|
||||
|
||||
// Agent tool metadata is tool-defined, so every string leaf is rewritten — and
|
||||
// the source map, which the replay buffer also holds, must not be mutated.
|
||||
func TestCopyData_RewritesNestedStringsWithoutMutating(t *testing.T) {
|
||||
w := publicRewriter("https://cdn.example.com/x.png")
|
||||
data := map[string]interface{}{
|
||||
"tool_name": "chart_export",
|
||||
"duration_ms": 42,
|
||||
"output": "",
|
||||
"nested": map[string]interface{}{
|
||||
"images": []interface{}{"resource://xifDo7NTSL300Lp1goVutw", "http://example.com/x.png"},
|
||||
},
|
||||
}
|
||||
|
||||
out := w.CopyData(context.Background(), data)
|
||||
|
||||
assert.Equal(t, "", data["output"],
|
||||
"the replay buffer's map must be untouched")
|
||||
assert.Equal(t, "", out["output"])
|
||||
assert.Equal(t, "chart_export", out["tool_name"])
|
||||
assert.Equal(t, 42, out["duration_ms"])
|
||||
|
||||
nested := out["nested"].(map[string]interface{})["images"].([]interface{})
|
||||
assert.Equal(t, "https://cdn.example.com/x.png", nested[0])
|
||||
assert.Equal(t, "http://example.com/x.png", nested[1])
|
||||
}
|
||||
|
||||
// The references SSE event carries its results twice: in
|
||||
// StreamResponse.KnowledgeReferences and again in Data. An in-memory stream
|
||||
// manager keeps the typed slice, so CopyData must traverse it or the Data copy
|
||||
// leaks the handles the caller asked to have resolved.
|
||||
func TestCopyData_RewritesTypedReferenceSlices(t *testing.T) {
|
||||
w := publicRewriter("https://cdn.example.com/x.png")
|
||||
original := &types.SearchResult{Content: "figure "}
|
||||
data := map[string]interface{}{
|
||||
"references": types.References{original},
|
||||
"tags": []string{"resource://xifDo7NTSL300Lp1goVutw", "plain"},
|
||||
"metadata": map[string]string{"thumb": "resource://xifDo7NTSL300Lp1goVutw"},
|
||||
}
|
||||
|
||||
out := w.CopyData(context.Background(), data)
|
||||
|
||||
refs := out["references"].(types.References)
|
||||
assert.Equal(t, "figure ", refs[0].Content)
|
||||
assert.Equal(t, "figure ", original.Content)
|
||||
assert.Equal(t,
|
||||
[]string{"https://cdn.example.com/x.png", "plain"},
|
||||
out["tags"].([]string),
|
||||
)
|
||||
assert.Equal(t,
|
||||
map[string]string{"thumb": "https://cdn.example.com/x.png"},
|
||||
out["metadata"].(map[string]string),
|
||||
)
|
||||
}
|
||||
|
||||
// Copying every metadata map on every SSE event would be pure garbage, so an
|
||||
// unchanged map must be returned as-is.
|
||||
func TestCopyData_ReturnsInputWhenNothingChanges(t *testing.T) {
|
||||
w := publicRewriter("https://cdn.example.com/x.png")
|
||||
data := map[string]interface{}{"tool_name": "chart_export", "duration_ms": 42}
|
||||
assert.Equal(t, data, w.CopyData(context.Background(), data))
|
||||
}
|
||||
|
||||
func TestCopyData_NilAndDisabled(t *testing.T) {
|
||||
assert.Nil(t, publicRewriter("https://x/y.png").CopyData(context.Background(), nil))
|
||||
data := map[string]interface{}{"output": ""}
|
||||
assert.Equal(t, data, NewRewriter(nil, "TEST").CopyData(context.Background(), data))
|
||||
}
|
||||
|
||||
func TestDefaultMode(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Setenv(EnvVar, "")
|
||||
assert.Equal(t, ModeHandle, DefaultMode(ctx))
|
||||
|
||||
t.Setenv(EnvVar, "public")
|
||||
assert.Equal(t, ModePublic, DefaultMode(ctx))
|
||||
|
||||
t.Setenv(EnvVar, "nonsense")
|
||||
assert.Equal(t, ModeHandle, DefaultMode(ctx), "a typo must degrade to the safe default")
|
||||
}
|
||||
|
||||
func TestResolveMode_QueryWinsOverDeployment(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Setenv(EnvVar, "public")
|
||||
|
||||
mode, err := ResolveMode(ctx, "handle")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ModeHandle, mode, "an explicit query value must win")
|
||||
|
||||
mode, err = ResolveMode(ctx, "")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ModePublic, mode)
|
||||
|
||||
_, err = ResolveMode(ctx, "yes-please")
|
||||
assert.Error(t, err, "an invalid query value is a client error")
|
||||
}
|
||||
Loading…
Reference in New Issue