Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(channel): deliver the final answer only to Slack and Lark (MUL-5378) (#6016)

Bohan Jiangba108978acba
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 4e97c694d5..1a891de00c 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -346,6 +346,12 @@ func buildChatPrompt(task Task) string {
// from the context the inbound enricher already injected, so it gets the
// awareness statement without the commands, and ChatInThread — which only ever
// picks between those two commands — does not apply to it (MUL-4899).
+ //
+ // The no-narration rule is a THIRD axis and belongs to neither half: it is a
+ // property of delivering to an IM channel at all, so it is emitted for every
+ // channel type. #4776 introduced it that way; the MUL-4899 split moved it into
+ // the Slack branch along with the read commands it happened to mention, which
+ // silently dropped it for Feishu/Lark (GH #6006).
if task.ChatChannelType != "" {
platform := channelDisplayName(task.ChatChannelType)
fmt.Fprintf(&b, "You are operating inside a %s conversation — not the Multica web app. This conversation and its history live in %s, NOT in Multica; never look in Multica issues or comments for it.\n", platform, platform)
@@ -361,10 +367,12 @@ func buildChatPrompt(task Task) string {
// These reads are the agent's private context-gathering; narrating them
// into a chat reply reads as noise (the user reported every reply being
// prefixed with "我先读取…"). Tell the agent to keep them out of its answer.
- b.WriteString("Do these reads SILENTLY as an internal step — they are how you gather context, not part of your answer. Do NOT narrate them: your reply must not begin with what you are about to read or just read (no \"我先读取…\" / \"let me read the history / open the thread\"). Reply to the user with your answer only.\n")
+ b.WriteString("Do these reads SILENTLY as an internal step — they are how you gather context, not part of your answer.\n")
} else {
fmt.Fprintf(&b, "Work from the context already provided to you below — Multica has no history reader for %s, so there is no command that can fetch more of this conversation. If you genuinely need earlier context that is not here, ask the user for it rather than guessing.\n", platform)
}
+ // Scoped to process, not results — a completion confirmation IS the deliverable.
+ fmt.Fprintf(&b, "Reply to %s with the final outcome only. Do NOT narrate planned or in-progress steps (\"我先读取…\"); completed actions are part of the outcome.\n", platform)
b.WriteString("\n")
}
if task.Agent != nil && len(task.Agent.Skills) > 0 {
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index b4393e17f7..67aaebcbc5 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -331,6 +331,59 @@ func TestBuildChatPromptChannelAwareness(t *testing.T) {
})
}
+// TestBuildChatPromptNoNarrationOnEveryChannel pins the THIRD axis of the chat
+// channel policy: the no-narration delivery rule keys off "is there a channel at
+// all", like the upload axis and unlike the Slack-only history axis.
+//
+// Regression guard for GH #6006. #4776 introduced the rule for every channel;
+// the MUL-4899 split moved it into the Slack branch along with the read commands
+// its wording happened to mention, so Feishu/Lark replies silently went back to
+// carrying interim narration. The two-layer matrix below could not catch that —
+// it only ever asserted the rule on the Slack case.
+//
+// The carve-out is pinned alongside the prohibition on purpose. A rule phrased
+// as "don't say what you just did" reads as forbidding "已创建 Issue X" — the
+// actual deliverable for a do-this request — so the two must move together: the
+// prohibition covers PROCESS, never the completed outcome.
+func TestBuildChatPromptNoNarrationOnEveryChannel(t *testing.T) {
+ const (
+ prohibition = "Do NOT narrate planned or in-progress steps"
+ carveOut = "completed actions are part of the outcome"
+ )
+
+ for _, tc := range []struct {
+ name string
+ channelType string
+ want bool
+ }{
+ {name: "slack", channelType: execenv.ChannelTypeSlack, want: true},
+ {name: "feishu", channelType: execenv.ChannelTypeFeishu, want: true},
+ {name: "direct chat has no channel to deliver into", channelType: "", want: false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ out := buildChatPrompt(Task{
+ ChatSessionID: "sess-1",
+ ChatChannelType: tc.channelType,
+ ChatMessage: "hi",
+ })
+ for _, phrase := range []string{prohibition, carveOut} {
+ if got := strings.Contains(out, phrase); got != tc.want {
+ t.Errorf("%q present=%v, want %v\n--- output ---\n%s", phrase, got, tc.want, out)
+ }
+ }
+ if !tc.want {
+ return
+ }
+ // The prohibition must not read as a blanket ban on past tense. If a
+ // future edit drops the carve-out, an agent asked to create an issue
+ // has no way left to report that it did.
+ if strings.Contains(out, "must not say what you are about to do or just did") {
+ t.Errorf("prohibition must scope to process, not completed outcomes\n--- output ---\n%s", out)
+ }
+ })
+ }
+}
+
// TestBuildChatPromptTwoLayerChannelPolicy pins the two INDEPENDENT axes of the
// chat channel policy (MUL-4899). Collapsing them into one condition is exactly
// the bug this matrix exists to catch:
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index af00e8ead3..a9f5a8af5a 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -953,7 +953,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
semanticActivityCh := make(chan string, 256)
var outputMu sync.Mutex
- var output strings.Builder
+ // Result.Output is "final user-facing output selected by the backend"
+ // (agent.go), so it holds the deliverable only. finalAnswer is the text the
+ // app-server labelled `phase: "final_answer"`; lastAgentMessage is the
+ // fallback for the legacy `agent_message` protocol, which carries no phase.
+ // Every agent message still flows to msgCh, so the transcript is unchanged —
+ // only what the daemon forwards to a chat/channel reply narrows (GH #6006).
+ var finalAnswer, lastAgentMessage string
var semanticObserved atomic.Bool
turnNotificationGate := &codexTurnNotificationGate{}
@@ -982,7 +988,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
logCodexAgentMessage(b.cfg.Logger, msg)
if msg.Type == MessageText {
outputMu.Lock()
- output.WriteString(msg.Content)
+ lastAgentMessage = msg.Content
outputMu.Unlock()
}
trySend(msgCh, msg)
@@ -991,6 +997,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
semanticObserved.Store(true)
}
},
+ onFinalAnswer: func(text string) {
+ outputMu.Lock()
+ finalAnswer = text
+ outputMu.Unlock()
+ },
onSemanticActivity: func(description string) {
semanticObserved.Store(true)
b.cfg.Logger.Debug("codex semantic activity observed", "activity", description)
@@ -1471,7 +1482,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
outputMu.Lock()
- finalOutput := output.String()
+ finalOutput := codexDeliverableOutput(finalAnswer, lastAgentMessage)
outputMu.Unlock()
// Build usage map from accumulated codex usage.
@@ -1809,6 +1820,19 @@ func trySendString(ch chan<- string, value string) {
}
}
+// codexDeliverableOutput picks Result.Output from what the turn produced: the
+// message the app-server itself labelled `phase: "final_answer"`, or — for the
+// legacy `agent_message` protocol, which carries no phase — the most recent
+// agent message. Never every message joined: the intermediate ones narrate the
+// work between tool calls, which belongs to the transcript and not to a chat or
+// IM reply (GH #6006).
+func codexDeliverableOutput(finalAnswer, lastAgentMessage string) string {
+ if finalAnswer != "" {
+ return finalAnswer
+ }
+ return lastAgentMessage
+}
+
func logCodexAgentMessage(logger *slog.Logger, msg Message) {
if logger == nil {
return
@@ -1862,6 +1886,12 @@ type codexClient struct {
onMessage func(Message)
onSemanticActivity func(description string)
onTurnDone func(aborted bool)
+ // onFinalAnswer fires only for an agent message the app-server itself
+ // labelled `phase: "final_answer"` — the turn's deliverable, as opposed to
+ // the intermediate agent messages that narrate work between tool calls.
+ // Both still reach onMessage: the transcript keeps the whole timeline, only
+ // Result.Output is narrowed to the deliverable (GH #6006).
+ onFinalAnswer func(text string)
// acceptNotification isolates the active turn from same-thread history
// replay emitted while thread/resume is restoring prior conversation.
// Unit-level protocol tests leave it nil and exercise dispatch directly.
@@ -2578,8 +2608,17 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
c.onMessage(Message{Type: MessageText, Content: text})
}
phase, _ := item["phase"].(string)
- if phase == "final_answer" && c.turnStarted {
- if c.onTurnDone != nil {
+ if phase == "final_answer" {
+ // Deliberately NOT gated on turnStarted, unlike onTurnDone below:
+ // the gate exists so a subagent or a replayed history turn cannot
+ // end OUR turn early, and the thread guard at the top of this
+ // function already keeps foreign threads out. A final answer that
+ // arrives before we observed turn/started is still this thread's
+ // deliverable, and dropping it would fall back to narration.
+ if text != "" && c.onFinalAnswer != nil {
+ c.onFinalAnswer(text)
+ }
+ if c.turnStarted && c.onTurnDone != nil {
c.onTurnDone(false)
}
}
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index d908ccea51..b64a991b00 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -1188,6 +1188,83 @@ func TestCodexRawItemAgentMessageFinalAnswer(t *testing.T) {
}
}
+// TestCodexDeliverableOutputExcludesNarration pins Result.Output to the turn's
+// deliverable. Codex used to concatenate every agent message, so a tool-using
+// run shipped its intermediate narration to Slack and Lark along with the answer
+// (GH #6006). The wiring mirrors executeOnce: onMessage tracks the last agent
+// message, onFinalAnswer captures the phase-labelled one, and
+// codexDeliverableOutput picks between them.
+func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
+ t.Parallel()
+
+ const (
+ rawNarration = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m1","text":"Let me check the logs."}}}`
+ rawFinal = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m2","text":"The retry loop is the cause.","phase":"final_answer"}}}`
+ legacyFirst = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"agent_message","message":"Let me check the logs."}}}`
+ legacySecond = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"agent_message","message":"The retry loop is the cause."}}}`
+ wantDeliverabl = "The retry loop is the cause."
+ )
+
+ cases := []struct {
+ name string
+ protocol string
+ lines []string
+ want string
+ }{
+ {
+ name: "raw protocol keeps only the labelled final answer",
+ protocol: "raw",
+ lines: []string{rawNarration, rawFinal},
+ want: wantDeliverabl,
+ },
+ {
+ name: "raw protocol without a final_answer falls back to the last message",
+ protocol: "raw",
+ lines: []string{rawNarration, `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m2","text":"The retry loop is the cause."}}}`},
+ want: wantDeliverabl,
+ },
+ {
+ name: "legacy protocol carries no phase and falls back to the last message",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacySecond},
+ want: wantDeliverabl,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = tc.protocol
+ c.turnStarted = true
+
+ var finalAnswer, lastAgentMessage string
+ var streamed []string
+ c.onMessage = func(msg Message) {
+ if msg.Type == MessageText {
+ lastAgentMessage = msg.Content
+ streamed = append(streamed, msg.Content)
+ }
+ }
+ c.onFinalAnswer = func(text string) { finalAnswer = text }
+
+ for _, line := range tc.lines {
+ c.handleLine(line)
+ }
+
+ if got := codexDeliverableOutput(finalAnswer, lastAgentMessage); got != tc.want {
+ t.Fatalf("Result.Output = %q, want %q", got, tc.want)
+ }
+ // Narrowing delivery must not narrow the transcript: both messages
+ // still stream to the timeline the Multica UI renders.
+ if len(streamed) != 2 || streamed[0] != "Let me check the logs." {
+ t.Fatalf("expected both agent messages streamed, got %q", streamed)
+ }
+ })
+ }
+}
+
func TestCodexRawThreadStatusIdle(t *testing.T) {
t.Parallel()
@@ -1299,12 +1376,16 @@ func TestCodexRawItemAgentMessageFinalAnswerFromSubagentIgnored(t *testing.T) {
var messages []Message
var doneCount int
+ var finalAnswer string
c.onMessage = func(msg Message) {
messages = append(messages, msg)
}
c.onTurnDone = func(aborted bool) {
doneCount++
}
+ c.onFinalAnswer = func(text string) {
+ finalAnswer = text
+ }
c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr_subagent","item":{"type":"agentMessage","id":"sub-1","text":"subagent leakage","phase":"final_answer"}}}`)
@@ -1314,6 +1395,12 @@ func TestCodexRawItemAgentMessageFinalAnswerFromSubagentIgnored(t *testing.T) {
if doneCount != 0 {
t.Fatalf("subagent final_answer must not trigger onTurnDone, got %d calls", doneCount)
}
+ // onFinalAnswer selects Result.Output, so a subagent reaching it would ship
+ // another thread's answer as this run's reply. It rides the same
+ // isNotificationFromOtherThread guard; pin that it stays behind it.
+ if finalAnswer != "" {
+ t.Fatalf("subagent final_answer must not become the deliverable, got %q", finalAnswer)
+ }
}
func TestCodexCloseAllPending(t *testing.T) {
diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.go
index 23715fa098..74dff6e6ac 100644
--- a/server/pkg/agent/copilot.go
+++ b/server/pkg/agent/copilot.go
@@ -26,12 +26,31 @@ type copilotBackend struct {
// event stream. It is shared between production (Execute) and tests via
// handleCopilotEvent, so the parsing logic is never duplicated.
type copilotEventState struct {
- output strings.Builder
- sessionID string
- activeModel string
- finalStatus string
- finalError string
- usage map[string]TokenUsage
+ // output holds the latest COMPLETE assistant turn, not every turn joined:
+ // Result.Output is "final user-facing output selected by the backend"
+ // (agent.go), and a tool-using run's earlier turns are narration around the
+ // work, not the deliverable (GH #6006). Every turn still reaches the
+ // transcript through the emitted MessageText.
+ output strings.Builder
+ // pendingDelta buffers the turn currently streaming. It is cleared when that
+ // turn's authoritative assistant.message lands, so it is non-empty only when
+ // the process died mid-turn — the one case where a partial beats the
+ // previous turn's complete text.
+ pendingDelta strings.Builder
+ sessionID string
+ activeModel string
+ finalStatus string
+ finalError string
+ usage map[string]TokenUsage
+}
+
+// finalOutput is the deliverable for Result.Output: the last complete assistant
+// turn, or the partial turn that was still streaming when the process died.
+func (st *copilotEventState) finalOutput() string {
+ if st.pendingDelta.Len() > 0 {
+ return st.pendingDelta.String()
+ }
+ return st.output.String()
}
func newCopilotEventState(seedModel string) *copilotEventState {
@@ -68,9 +87,9 @@ func handleCopilotEvent(evt copilotEvent, st *copilotEventState) []Message {
case "assistant.message_delta":
var delta copilotMessageDelta
if err := json.Unmarshal(evt.Data, &delta); err == nil && delta.DeltaContent != "" {
- // Write to output as defense-in-depth: if the process is killed
- // before the final assistant.message arrives, we still have text.
- st.output.WriteString(delta.DeltaContent)
+ // Buffer deltas as defense-in-depth: if the process is killed before
+ // this turn's assistant.message arrives, we still have its text.
+ st.pendingDelta.WriteString(delta.DeltaContent)
msgs = append(msgs, Message{Type: MessageText, Content: delta.DeltaContent})
}
@@ -79,19 +98,19 @@ func handleCopilotEvent(evt copilotEvent, st *copilotEventState) []Message {
if err := json.Unmarshal(evt.Data, &msg); err != nil {
return nil
}
- // assistant.message carries the full turn content. Since deltas
- // already wrote to output incrementally, we reset and write the
- // authoritative content once to avoid double-counting.
+ // assistant.message carries the full turn content and supersedes both the
+ // deltas that streamed it and whatever earlier turn output held: a run
+ // that narrates, calls a tool, then answers must deliver the answer, not
+ // the pair joined together.
if msg.Content != "" {
- // Separator between turns.
- trimmed := strings.TrimSuffix(st.output.String(), msg.Content)
st.output.Reset()
- st.output.WriteString(trimmed)
- if st.output.Len() > 0 && !strings.HasSuffix(st.output.String(), "\n\n") {
- st.output.WriteString("\n\n")
- }
st.output.WriteString(msg.Content)
}
+ // Clear unconditionally — this event IS the turn boundary. A tool-only
+ // turn reports content:"" (the toolRequests below are the whole turn), and
+ // leaving its deltas buffered would let them be stitched onto the NEXT
+ // turn's partial text if the process then died mid-stream.
+ st.pendingDelta.Reset()
if msg.ReasoningText != "" {
msgs = append(msgs, Message{Type: MessageThinking, Content: msg.ReasoningText})
}
@@ -296,7 +315,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOp
resCh <- Result{
Status: st.finalStatus,
- Output: st.output.String(),
+ Output: st.finalOutput(),
Error: st.finalError,
DurationMs: duration.Milliseconds(),
SessionID: st.sessionID,
diff --git a/server/pkg/agent/copilot_test.go b/server/pkg/agent/copilot_test.go
index 78156def05..64e0beadb7 100644
--- a/server/pkg/agent/copilot_test.go
+++ b/server/pkg/agent/copilot_test.go
@@ -649,8 +649,76 @@ func TestCopilotEventLoopDeltaFallbackOutput(t *testing.T) {
handleCopilotEvent(evt, st)
}
- if st.output.String() != "hello world" {
- t.Fatalf("expected output 'hello world', got %q", st.output.String())
+ if st.finalOutput() != "hello world" {
+ t.Fatalf("expected output 'hello world', got %q", st.finalOutput())
+ }
+}
+
+// TestCopilotEventLoopDeliversFinalTurnOnly pins Result.Output to the LAST
+// assistant turn. Copilot used to join every turn with "\n\n", so a run that
+// narrated, called a tool, then answered shipped narration + answer to Slack and
+// Lark as one reply (GH #6006). The narration still reaches the transcript as
+// MessageText; only the deliverable narrows.
+func TestCopilotEventLoopDeliversFinalTurnOnly(t *testing.T) {
+ t.Parallel()
+ lines := []string{
+ `{"type":"assistant.message_delta","data":{"messageId":"m1","deltaContent":"Let me check the logs."},"id":"d1","timestamp":"2026-04-16T08:43:38.000Z","parentId":"p1","ephemeral":true}`,
+ `{"type":"assistant.message","data":{"messageId":"m1","content":"Let me check the logs.","toolRequests":[{"toolCallId":"t1","name":"shell","arguments":{}}]},"id":"a1","timestamp":"2026-04-16T08:43:38.100Z","parentId":"p1"}`,
+ `{"type":"tool.execution_complete","data":{"toolCallId":"t1","success":true,"result":{"content":"nothing there"}},"id":"tc1","timestamp":"2026-04-16T08:43:39.000Z","parentId":"p1"}`,
+ `{"type":"assistant.message_delta","data":{"messageId":"m2","deltaContent":"The retry loop is the cause."},"id":"d2","timestamp":"2026-04-16T08:43:40.000Z","parentId":"p1","ephemeral":true}`,
+ `{"type":"assistant.message","data":{"messageId":"m2","content":"The retry loop is the cause."},"id":"a2","timestamp":"2026-04-16T08:43:40.100Z","parentId":"p1"}`,
+ }
+
+ st := newCopilotEventState("copilot")
+ var streamed []string
+ for _, line := range lines {
+ var evt copilotEvent
+ if err := json.Unmarshal([]byte(line), &evt); err != nil {
+ t.Fatal(err)
+ }
+ for _, m := range handleCopilotEvent(evt, st) {
+ if m.Type == MessageText {
+ streamed = append(streamed, m.Content)
+ }
+ }
+ }
+
+ if got := st.finalOutput(); got != "The retry loop is the cause." {
+ t.Fatalf("Result.Output should be the final turn only, got %q", got)
+ }
+ // The transcript must still see the narration — this fix narrows delivery,
+ // not the timeline the Multica UI renders.
+ if len(streamed) != 2 || streamed[0] != "Let me check the logs." {
+ t.Fatalf("expected both turns streamed as MessageText, got %q", streamed)
+ }
+}
+
+// TestCopilotEventLoopToolOnlyTurnClearsPendingDelta covers the turn shape the
+// delta fallback can get wrong: a turn whose authoritative assistant.message
+// reports content:"" because the tool requests ARE the turn. Its deltas must not
+// stay buffered, or a later turn that dies mid-stream would deliver the two
+// stitched together.
+func TestCopilotEventLoopToolOnlyTurnClearsPendingDelta(t *testing.T) {
+ t.Parallel()
+ lines := []string{
+ `{"type":"assistant.message_delta","data":{"messageId":"m1","deltaContent":"Checking the logs now."},"id":"d1","timestamp":"2026-04-16T08:43:38.000Z","parentId":"p1","ephemeral":true}`,
+ `{"type":"assistant.message","data":{"messageId":"m1","content":"","toolRequests":[{"toolCallId":"t1","name":"shell","arguments":{}}]},"id":"a1","timestamp":"2026-04-16T08:43:38.100Z","parentId":"p1"}`,
+ // Next turn starts streaming, then the process dies before its
+ // assistant.message lands.
+ `{"type":"assistant.message_delta","data":{"messageId":"m2","deltaContent":"The retry loop"},"id":"d2","timestamp":"2026-04-16T08:43:40.000Z","parentId":"p1","ephemeral":true}`,
+ }
+
+ st := newCopilotEventState("copilot")
+ for _, line := range lines {
+ var evt copilotEvent
+ if err := json.Unmarshal([]byte(line), &evt); err != nil {
+ t.Fatal(err)
+ }
+ handleCopilotEvent(evt, st)
+ }
+
+ if got := st.finalOutput(); got != "The retry loop" {
+ t.Fatalf("killed mid-turn should deliver that turn's partial only, got %q", got)
}
}