feat: publish outbound answer images to private OSS
This commit is contained in:
@@ -79,6 +79,10 @@ type UserDirectory interface {
|
||||
ResolveUser(ctx context.Context, tenantKey, staffID, fallbackName string) (directory.Profile, error)
|
||||
}
|
||||
|
||||
type OutboundContentRewriter interface {
|
||||
Rewrite(ctx context.Context, content string) string
|
||||
}
|
||||
|
||||
// FinalCardSender sends an AI card as the final reply. Implementations must
|
||||
// not log err, outTrackID, or content at any level.
|
||||
type FinalCardSender interface {
|
||||
@@ -93,9 +97,10 @@ type StreamingCardSender interface {
|
||||
}
|
||||
|
||||
type HandlerOptions struct {
|
||||
ImageDownloader ImageDownloader
|
||||
CardSender FinalCardSender
|
||||
Directory UserDirectory
|
||||
ImageDownloader ImageDownloader
|
||||
CardSender FinalCardSender
|
||||
Directory UserDirectory
|
||||
OutboundRewriter OutboundContentRewriter
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
@@ -105,6 +110,7 @@ type Handler struct {
|
||||
downloader ImageDownloader
|
||||
card FinalCardSender
|
||||
directory UserDirectory
|
||||
outboundRewriter OutboundContentRewriter
|
||||
now func() time.Time
|
||||
cardUpdateInterval time.Duration
|
||||
finalDeliveryTimeout time.Duration
|
||||
@@ -146,6 +152,7 @@ func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, o
|
||||
downloader: opts.ImageDownloader,
|
||||
card: opts.CardSender,
|
||||
directory: opts.Directory,
|
||||
outboundRewriter: opts.OutboundRewriter,
|
||||
now: time.Now,
|
||||
cardUpdateInterval: 500 * time.Millisecond,
|
||||
finalDeliveryTimeout: defaultHTTPTimeout,
|
||||
@@ -290,6 +297,7 @@ func (h *Handler) streamingCapable() (StreamingCardSender, StreamingQAAsker) {
|
||||
func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req core.QARequest) error {
|
||||
result, err := h.qa.Ask(ctx, req)
|
||||
if err != nil {
|
||||
logQAFailure("non_streaming", err)
|
||||
if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil {
|
||||
return replyErr
|
||||
}
|
||||
@@ -298,13 +306,14 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req
|
||||
if result.Replayed && result.DeliveryStatus == core.DeliverySent {
|
||||
return nil
|
||||
}
|
||||
content := h.rewriteOutboundContent(ctx, result.Answer)
|
||||
|
||||
if h.card != nil {
|
||||
cardReq := CardRequest{
|
||||
ConversationType: req.ConversationType,
|
||||
ExternalUserID: req.ExternalUserID,
|
||||
ExternalChatID: req.ExternalChatID,
|
||||
Content: result.Answer,
|
||||
Content: content,
|
||||
}
|
||||
if outTrackID, cardErr := h.card.SendFinalCard(ctx, cardReq); cardErr == nil {
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodCard, outTrackID, "")
|
||||
@@ -312,7 +321,7 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req
|
||||
}
|
||||
log.Printf("DingTalk card delivery failed, falling back to markdown")
|
||||
}
|
||||
if err := h.sendReply(ctx, webhookURL, result.Answer); err != nil {
|
||||
if err := h.sendReply(ctx, webhookURL, content); err != nil {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
return err
|
||||
}
|
||||
@@ -333,6 +342,7 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co
|
||||
// Fallback: Ask → Markdown only (no SendFinalCard, no AskStream)
|
||||
result, askErr := h.qa.Ask(ctx, req)
|
||||
if askErr != nil {
|
||||
logQAFailure("streaming_fallback", askErr)
|
||||
if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil {
|
||||
return replyErr
|
||||
}
|
||||
@@ -341,7 +351,8 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co
|
||||
if result.Replayed && result.DeliveryStatus == core.DeliverySent {
|
||||
return nil
|
||||
}
|
||||
if replyErr := h.sendReply(ctx, webhookURL, result.Answer); replyErr != nil {
|
||||
content := h.rewriteOutboundContent(ctx, result.Answer)
|
||||
if replyErr := h.sendReply(ctx, webhookURL, content); replyErr != nil {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
return replyErr
|
||||
}
|
||||
@@ -369,6 +380,7 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co
|
||||
|
||||
result, err := streamingQA.AskStream(ctx, req, observer)
|
||||
if err != nil || strings.TrimSpace(result.Answer) == "" {
|
||||
logQAFailure("streaming", errOrEmptyAnswer(err, result.Answer))
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, core.QAResult{}, qaErrorReply, true)
|
||||
}
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result, result.Answer, false)
|
||||
@@ -386,12 +398,14 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r
|
||||
log.Printf("DingTalk event card start failed, falling back to markdown")
|
||||
result, askErr := h.qa.Ask(ctx, req)
|
||||
if askErr != nil {
|
||||
logQAFailure("event_fallback", askErr)
|
||||
return h.sendReply(ctx, webhookURL, qaErrorReply)
|
||||
}
|
||||
if result.Replayed && result.DeliveryStatus == core.DeliverySent {
|
||||
return nil
|
||||
}
|
||||
if replyErr := h.sendReply(ctx, webhookURL, result.Answer); replyErr != nil {
|
||||
content := h.rewriteOutboundContent(ctx, result.Answer)
|
||||
if replyErr := h.sendReply(ctx, webhookURL, content); replyErr != nil {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
return replyErr
|
||||
}
|
||||
@@ -421,6 +435,7 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r
|
||||
pump.Stop()
|
||||
|
||||
if err != nil || strings.TrimSpace(result.Answer) == "" {
|
||||
logQAFailure("event_streaming", errOrEmptyAnswer(err, result.Answer))
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, core.QAResult{}, qaErrorReply, true)
|
||||
}
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result, result.Answer, false)
|
||||
@@ -432,6 +447,10 @@ func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string,
|
||||
timeout = defaultHTTPTimeout
|
||||
}
|
||||
|
||||
if !isError {
|
||||
content = h.rewriteOutboundContent(ctx, content)
|
||||
}
|
||||
|
||||
// Final card convergence must still be attempted when the QA context was
|
||||
// canceled or timed out; otherwise the card can remain "processing".
|
||||
finalCtx, cancelFinal := context.WithTimeout(context.WithoutCancel(ctx), timeout)
|
||||
@@ -460,6 +479,19 @@ func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) rewriteOutboundContent(ctx context.Context, content string) string {
|
||||
if h.outboundRewriter == nil {
|
||||
return content
|
||||
}
|
||||
timeout := h.finalDeliveryTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultHTTPTimeout
|
||||
}
|
||||
rewriteCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)
|
||||
defer cancel()
|
||||
return h.outboundRewriter.Rewrite(rewriteCtx, content)
|
||||
}
|
||||
|
||||
func (h *Handler) recordDelivery(ctx context.Context, result core.QAResult, status, method, providerMessageID, failureCode string) {
|
||||
if strings.TrimSpace(result.TurnID) == "" || strings.TrimSpace(result.AnswerMessageID) == "" {
|
||||
return
|
||||
@@ -511,6 +543,50 @@ func renderProgressEvent(event weknora.StreamEvent) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func errOrEmptyAnswer(err error, answer string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(answer) == "" {
|
||||
return weknora.ErrEmptyAnswer
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func logQAFailure(mode string, err error) {
|
||||
log.Printf("DingTalk QA failed: mode=%s stage=%s", mode, qaFailureStage(err))
|
||||
}
|
||||
|
||||
func qaFailureStage(err error) string {
|
||||
switch {
|
||||
case err == nil:
|
||||
return "unknown"
|
||||
case errors.Is(err, context.Canceled):
|
||||
return "context_canceled"
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return "context_deadline"
|
||||
case errors.Is(err, core.ErrTurnInProgress):
|
||||
return "duplicate_or_in_progress"
|
||||
case errors.Is(err, weknora.ErrEmptyAnswer):
|
||||
return "empty_answer"
|
||||
}
|
||||
message := strings.ToLower(err.Error())
|
||||
switch {
|
||||
case strings.Contains(message, "begin turn"):
|
||||
return "begin_turn"
|
||||
case strings.Contains(message, "agent") && strings.Contains(message, "binding"):
|
||||
return "agent_binding"
|
||||
case strings.Contains(message, "session"):
|
||||
return "session"
|
||||
case strings.Contains(message, "weknora agent chat"):
|
||||
return "agent_chat"
|
||||
case strings.Contains(message, "required") || strings.Contains(message, "unsupported"):
|
||||
return "validation"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func imageFailureStage(err error) string {
|
||||
message := strings.ToLower(err.Error())
|
||||
switch {
|
||||
|
||||
@@ -726,6 +726,46 @@ func TestHandleCardSuccessDirectFieldsCorrectNoMarkdown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleNonStreamingRewritesFinalCardAndMarkdownFallback(t *testing.T) {
|
||||
resource := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
signed := "https://img.example/signed.jpg"
|
||||
answer := "说明\n"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cardErr error
|
||||
wantReply bool
|
||||
}{
|
||||
{name: "card"},
|
||||
{name: "markdown fallback", cardErr: errors.New("card failed"), wantReply: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
qa := &fakeQA{result: core.QAResult{Answer: answer}}
|
||||
reply := &fakeReply{}
|
||||
card := &fakeCard{returnID: "track", err: tc.cardErr}
|
||||
h := newTestHandlerWithCard(t, qa, reply, card)
|
||||
rewriter := &fakeOutboundRewriter{from: resource, to: signed}
|
||||
h.outboundRewriter = rewriter
|
||||
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !card.called || reply.called != tc.wantReply {
|
||||
t.Fatalf("card=%t reply=%t", card.called, reply.called)
|
||||
}
|
||||
content := card.lastReq.Content
|
||||
if tc.wantReply {
|
||||
content = reply.lastText
|
||||
}
|
||||
if strings.Contains(content, resource) || !strings.Contains(content, signed) {
|
||||
t.Fatalf("outbound content=%q", content)
|
||||
}
|
||||
if rewriter.calls != 1 {
|
||||
t.Fatalf("rewrite calls=%d, want 1", rewriter.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCardSuccessGroupChatIDCorrect(t *testing.T) {
|
||||
qa := &fakeQA{result: core.QAResult{Answer: "group card answer"}}
|
||||
reply := &fakeReply{}
|
||||
@@ -940,6 +980,17 @@ type cardUpdate struct {
|
||||
isError bool
|
||||
}
|
||||
|
||||
type fakeOutboundRewriter struct {
|
||||
calls int
|
||||
from string
|
||||
to string
|
||||
}
|
||||
|
||||
func (f *fakeOutboundRewriter) Rewrite(_ context.Context, content string) string {
|
||||
f.calls++
|
||||
return strings.ReplaceAll(content, f.from, f.to)
|
||||
}
|
||||
|
||||
func (f *fakeStreamingCard) SendFinalCard(_ context.Context, req CardRequest) (string, error) {
|
||||
f.finalCalled = true
|
||||
f.finalReq = req
|
||||
@@ -1123,11 +1174,14 @@ func TestHandleStreamingThrottleClockAdvances(t *testing.T) {
|
||||
|
||||
func TestHandleStreamingStartFailsFallbackAskMarkdown(t *testing.T) {
|
||||
card := &fakeStreamingCard{startErr: errors.New("card API unavailable")}
|
||||
resource := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
qa := &fakeStreamingQA{
|
||||
result: core.QAResult{Answer: "**fallback markdown**"},
|
||||
result: core.QAResult{Answer: "**fallback markdown**\n"},
|
||||
}
|
||||
reply := &fakeReply{}
|
||||
h := newTestHandlerWithStreaming(t, qa, reply, card)
|
||||
rewriter := &fakeOutboundRewriter{from: resource, to: "https://img.example/signed.jpg"}
|
||||
h.outboundRewriter = rewriter
|
||||
|
||||
err := h.Handle(context.Background(), directTextCallback())
|
||||
if err != nil {
|
||||
@@ -1156,8 +1210,11 @@ func TestHandleStreamingStartFailsFallbackAskMarkdown(t *testing.T) {
|
||||
if !reply.called {
|
||||
t.Fatal("SendMarkdown must be called on Start failure")
|
||||
}
|
||||
if reply.lastText != "**fallback markdown**" {
|
||||
t.Fatalf("markdown text = %q, want fallback markdown", reply.lastText)
|
||||
if strings.Contains(reply.lastText, resource) || !strings.Contains(reply.lastText, "https://img.example/signed.jpg") {
|
||||
t.Fatalf("markdown text = %q, want rewritten fallback markdown", reply.lastText)
|
||||
}
|
||||
if rewriter.calls != 1 {
|
||||
t.Fatalf("rewrite calls=%d, want 1", rewriter.calls)
|
||||
}
|
||||
|
||||
// No card updates
|
||||
@@ -2005,5 +2062,32 @@ func TestTriggerPersonSnapshotRegression(t *testing.T) {
|
||||
t.Fatalf("SenderName = %q, want 张三", qa.lastReq.SenderName)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestHandleStreamingRewritesOnlyFinalOutboundImageContent(t *testing.T) {
|
||||
card := &fakeStreamingCard{startID: "track-image-final"}
|
||||
resource := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
answer := "操作说明\n"
|
||||
qa := &fakeStreamingQA{chunks: []string{answer}, result: core.QAResult{Answer: answer}}
|
||||
reply := &fakeReply{}
|
||||
rewriter := &fakeOutboundRewriter{from: resource, to: "https://img.example/signed.jpg"}
|
||||
h := newTestHandlerWithStreaming(t, qa, reply, card)
|
||||
h.outboundRewriter = rewriter
|
||||
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(card.updates) < 2 {
|
||||
t.Fatalf("updates=%d", len(card.updates))
|
||||
}
|
||||
if !strings.Contains(card.updates[0].content, resource) {
|
||||
t.Fatalf("streaming intermediate content should remain untouched: %q", card.updates[0].content)
|
||||
}
|
||||
final := card.updates[len(card.updates)-1]
|
||||
if !final.isFinalize || strings.Contains(final.content, resource) || !strings.Contains(final.content, "https://img.example/signed.jpg") {
|
||||
t.Fatalf("final content=%q finalize=%t", final.content, final.isFinalize)
|
||||
}
|
||||
if rewriter.calls != 1 {
|
||||
t.Fatalf("rewrite calls=%d, want 1", rewriter.calls)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user