Skip to content

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

Go

MUL-7458 Fix incorrectly folded Copilot CLI replies (#8507)

Multica Eve985986e4fb07
diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsx
index 58fdb73d37..c1d0e20374 100644
--- a/packages/views/chat/components/chat-message-list.test.tsx
+++ b/packages/views/chat/components/chat-message-list.test.tsx
@@ -3,7 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import { chatKeys } from "@multica/core/chat/queries";
-import type { TaskMessagePayload } from "@multica/core/types";
+import type { Attachment, TaskMessagePayload } from "@multica/core/types";
import type { ReactElement } from "react";
import enChat from "../../locales/en/chat.json";
@@ -59,6 +59,26 @@ function taskMsg(
return { task_id: TASK_ID, seq, type, ...extra } as TaskMessagePayload;
}
+function pdfAttachment(id: string): Attachment {
+ return {
+ id,
+ workspace_id: "workspace-1",
+ issue_id: null,
+ comment_id: null,
+ chat_session_id: "session-1",
+ chat_message_id: null,
+ uploader_type: "member",
+ uploader_id: "member-1",
+ filename: "report.pdf",
+ url: "/uploads/report.pdf",
+ download_url: `/api/attachments/${id}/download`,
+ markdown_url: `/api/attachments/${id}/download`,
+ content_type: "application/pdf",
+ size_bytes: 1024,
+ created_at: "2026-09-17T00:00:00Z",
+ };
+}
+
// A streaming timeline whose middle (tool steps) is non-empty, so the live
// footer renders the "N steps" outer fold.
const INITIAL_MESSAGES: TaskMessagePayload[] = [
@@ -234,6 +254,147 @@ describe("ChatMessageList live timeline (MUL-3960 regression)", () => {
expect(await screen.findByText("Draft ready.")).toBeInTheDocument();
expect(screen.queryByText(/Hidden suggestion/)).not.toBeInTheDocument();
});
+
+ it("keeps attachments visible when a settled content transform removes their inline reference", async () => {
+ const attachmentId = "11111111-2222-3333-4444-555555555555";
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={new QueryClient()}>
+ <ChatMessageList
+ messages={[{
+ id: "transformed-attachment",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content:
+ `<agent_draft>!file[report.pdf](/api/attachments/${attachmentId}/download)</agent_draft>` +
+ "Visible answer",
+ task_id: null,
+ created_at: "2026-09-17T00:00:00Z",
+ attachments: [pdfAttachment(attachmentId)],
+ }]}
+ pendingTask={null}
+ availability="online"
+ transformContent={(content) =>
+ content.replace(/<agent_draft>[\s\S]*<\/agent_draft>/, "")
+ }
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByText("Visible answer")).toBeInTheDocument();
+ expect(screen.getByText("report.pdf")).toBeInTheDocument();
+ });
+
+ it("does not offer Copy for an attachment-only reply", async () => {
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={new QueryClient()}>
+ <ChatMessageList
+ messages={[{
+ id: "attachment-only",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "",
+ task_id: null,
+ created_at: "2026-09-17T00:00:00Z",
+ attachments: [
+ pdfAttachment("11111111-2222-3333-4444-555555555555"),
+ ],
+ }]}
+ pendingTask={null}
+ availability="online"
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByText("report.pdf")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Copy" })).not.toBeInTheDocument();
+ });
+
+ it("renders the canonical settled answer while retaining process narration", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
+ taskMsg(0, "text", { content: "first timeline fragment" }),
+ taskMsg(1, "thinking", { content: "checking" }),
+ taskMsg(2, "text", { content: "second timeline fragment" }),
+ ]);
+
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={[{
+ id: "settled-answer",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "Complete canonical answer",
+ task_id: TASK_ID,
+ created_at: "2026-09-17T00:00:00Z",
+ }]}
+ pendingTask={null}
+ availability="online"
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByText("Complete canonical answer")).toBeInTheDocument();
+ expect(screen.getAllByText("Complete canonical answer")).toHaveLength(1);
+ const foldTrigger = screen.getByText("1 step");
+ expect(screen.queryByText("first timeline fragment")).not.toBeInTheDocument();
+ expect(screen.queryByText("second timeline fragment")).not.toBeInTheDocument();
+
+ fireEvent.click(foldTrigger);
+ expect(screen.getByText("first timeline fragment")).toBeInTheDocument();
+ expect(screen.queryByText("second timeline fragment")).not.toBeInTheDocument();
+ expect(screen.getAllByText("Complete canonical answer")).toHaveLength(1);
+ });
+
+ it("keeps the answer node mounted across the live-to-settled handoff", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
+ taskMsg(0, "tool_use", { tool: "Read", input: { path: "/tmp/x" } }),
+ taskMsg(1, "text", { content: "Intermediate narration" }),
+ taskMsg(2, "thinking", { content: "Checking the result" }),
+ taskMsg(3, "text", { content: "Stable final answer" }),
+ ]);
+
+ const view = (
+ messages: Parameters<typeof ChatMessageList>[0]["messages"],
+ pendingTask: Parameters<typeof ChatMessageList>[0]["pendingTask"],
+ ) => (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={messages}
+ pendingTask={pendingTask}
+ availability="online"
+ />
+ </QueryClientProvider>
+ </I18nProvider>
+ );
+
+ const { rerender } = render(
+ view([], { task_id: TASK_ID, status: "running" }),
+ );
+ const answerBefore = await screen.findByText("Stable final answer");
+ expect(screen.getByText("3 steps")).toBeInTheDocument();
+
+ rerender(view([{
+ id: "persisted-answer",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "Stable final answer",
+ task_id: TASK_ID,
+ created_at: "2026-09-17T00:00:00Z",
+ }], null));
+
+ expect(await screen.findByText("Stable final answer")).toBe(answerBefore);
+ expect(screen.getByText("3 steps")).toBeInTheDocument();
+ expect(screen.queryByText("Intermediate narration")).not.toBeInTheDocument();
+ });
});
describe("ChatMessageList footer spacing", () => {
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 6af5b8c14b..31203576e3 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -51,7 +51,11 @@ import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";
import { LIVE_END_ROW_ATTR, useStickToBottom } from "./stick-to-bottom";
import { formatElapsedMs } from "../lib/format";
-import { splitTimeline, extractCopyText } from "../lib/copy-text";
+import {
+ canonicalAnswerText,
+ extractCopyText,
+ splitTimeline,
+} from "../lib/copy-text";
import { stripChatQuickActionsProtocol } from "../lib/quick-actions";
import { useT } from "../../i18n";
@@ -599,6 +603,14 @@ function AssistantMessage({
// without any text. Keep whatever tool/thinking timeline the run produced and
// show a localized "no text reply" notice instead of an empty markdown block.
const isNoResponse = message?.message_kind === "no_response";
+ const settledContent = message
+ ? canonicalAnswerText(message, transformContent)
+ : undefined;
+ // Empty persisted content is valid for attachment-only/no-response turns and
+ // for legacy rows whose transcript is the only remaining text source. Only
+ // a non-empty canonical answer replaces timeline text after settlement.
+ const canonicalAnswer =
+ !isNoResponse && settledContent?.trim() ? settledContent : undefined;
return (
<div className="w-full space-y-1.5">
@@ -608,13 +620,14 @@ function AssistantMessage({
attachments={message?.attachments}
phase={phase}
isStreaming={!message}
+ settledContent={canonicalAnswer}
/>
)}
{isNoResponse ? (
<NoResponseNotice />
) : message && timeline.length === 0 ? (
<RichContent
- content={message.content}
+ content={settledContent ?? message.content}
attachments={message.attachments}
density="compact"
phase="settled"
@@ -625,12 +638,13 @@ function AssistantMessage({
<>
<AttachmentList
attachments={message.attachments}
- content={message.content}
+ content={settledContent ?? message.content}
/>
<MessageFooter
message={message}
timeline={timeline}
isPending={isPending}
+ transformContent={transformContent}
/>
{onQuickAction && showStarterCards ? (
// The opening's starter cards own this turn's suggestion strip
@@ -853,15 +867,18 @@ function MessageFooter({
message,
timeline,
isPending,
+ transformContent,
}: {
message: ChatMessage;
timeline: ChatTimelineItem[];
isPending: boolean;
+ transformContent?: (content: string) => string;
}) {
// A no_response turn has nothing to copy, and its caption uses a neutral
// "Finished in Xs" instead of "Replied in Xs" (MUL-4351).
const isNoResponse = message.message_kind === "no_response";
- const showCopy = !isPending && !isNoResponse;
+ const copyContent = extractCopyText(message, timeline, transformContent);
+ const showCopy = !isPending && !isNoResponse && copyContent.trim().length > 0;
if (message.elapsed_ms == null && !showCopy) return null;
return (
<div className="flex items-center gap-1.5">
@@ -871,21 +888,21 @@ function MessageFooter({
elapsedMs={message.elapsed_ms}
/>
)}
- {showCopy && <MessageCopyButton message={message} timeline={timeline} />}
+ {showCopy && (
+ <MessageCopyButton content={copyContent} />
+ )}
</div>
);
}
function MessageCopyButton({
- message,
- timeline,
+ content,
}: {
- message: ChatMessage;
- timeline: ChatTimelineItem[];
+ content: string;
}) {
const { t } = useT("chat");
const handleCopy = async () => {
- if (await copyText(extractCopyText(message, timeline))) {
+ if (await copyText(content)) {
toast.success(t(($) => $.message_list.copied_toast));
} else {
toast.error(t(($) => $.message_list.copy_failed_toast));
@@ -1041,37 +1058,66 @@ function FailureBubble({
);
}
-// ─── Timeline: outer process fold + final text (Conductor-style) ─────────
+// ─── Timeline: outer process fold + answer (Conductor-style) ─────────────
//
-// splitTimeline (lib/copy-text.ts) carves the items into:
+// While streaming, splitTimeline (lib/copy-text.ts) carves the items into:
// preface — text before the first thinking/tool item
// middle — first → last non-text item (inclusive, may sandwich text)
// final — text after the last non-text item
//
-// We render preface + final outside an outer Collapsible ("X steps") that
-// wraps middle. The inner row Collapsibles (ThinkingRow / ToolCallRow /
-// ToolResultRow) are unchanged — clicking them toggles independently of
-// the outer fold. Copy mirrors what's visible when the outer fold is
-// closed: preface + final, never middle. See extractCopyText for the
-// authoritative copy logic.
+// Once settled, the persisted chat_message content is authoritative for the
+// answer. Preface + middle remain in the process fold so intermediate narration
+// is still inspectable; only trailing transcript text is replaced. Explicit
+// process/answer keys preserve the trailing RichContent subtree when a live row
+// becomes its persisted row (MUL-4922).
function TimelineView({
items,
isStreaming,
attachments,
phase = "settled",
+ settledContent,
}: {
items: ChatTimelineItem[];
isStreaming?: boolean;
attachments?: import("@multica/core/types").Attachment[];
phase?: "streaming" | "settled";
+ settledContent?: string;
}) {
+ if (phase === "settled" && settledContent !== undefined) {
+ const { preface, middle } = splitTimeline(items);
+ const processItems = [...preface, ...middle];
+ return (
+ <>
+ {processItems.length > 0 && (
+ <OuterProcessFold
+ key="process"
+ items={processItems}
+ isStreaming={false}
+ attachments={attachments}
+ phase="settled"
+ stepCount={middle.length}
+ />
+ )}
+ <RichContent
+ key="answer"
+ content={settledContent}
+ attachments={attachments}
+ density="compact"
+ phase="settled"
+ className="leading-relaxed"
+ />
+ </>
+ );
+ }
+
const { preface, middle, final } = splitTimeline(items);
return (
<>
{preface.length > 0 && (
<RichContent
+ key="preface"
content={preface.map((t) => t.content ?? "").join("")}
attachments={attachments}
density="compact"
@@ -1081,6 +1127,7 @@ function TimelineView({
)}
{middle.length > 0 && (
<OuterProcessFold
+ key="process"
items={middle}
isStreaming={!!isStreaming}
attachments={attachments}
@@ -1089,6 +1136,7 @@ function TimelineView({
)}
{final.length > 0 && (
<RichContent
+ key="answer"
content={final.map((t) => t.content ?? "").join("")}
attachments={attachments}
density="compact"
@@ -1105,11 +1153,13 @@ function OuterProcessFold({
isStreaming,
attachments,
phase = "settled",
+ stepCount,
}: {
items: ChatTimelineItem[];
isStreaming?: boolean;
attachments?: import("@multica/core/types").Attachment[];
phase?: "streaming" | "settled";
+ stepCount?: number;
}) {
const { t } = useT("chat");
// Open while the task streams (so the user watches progress), collapsed once
@@ -1123,13 +1173,13 @@ function OuterProcessFold({
if (wasStreaming.current && !isStreaming) setOpen(false);
wasStreaming.current = !!isStreaming;
}, [isStreaming]);
- const stepCount = items.length;
+ const displayedStepCount = stepCount ?? items.length;
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger className="flex items-center gap-1 text-caption text-muted-foreground hover:text-foreground transition-colors">
{open ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}
- <span>{t(($) => $.message_list.process_steps, { count: stepCount })}</span>
+ <span>{t(($) => $.message_list.process_steps, { count: displayedStepCount })}</span>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="mt-1 rounded-lg border bg-muted/20 p-2 space-y-0.5">
diff --git a/packages/views/chat/lib/copy-text.test.ts b/packages/views/chat/lib/copy-text.test.ts
index b6ba987ad2..61f4f4cc7b 100644
--- a/packages/views/chat/lib/copy-text.test.ts
+++ b/packages/views/chat/lib/copy-text.test.ts
@@ -2,7 +2,11 @@
import { describe, it, expect } from "vitest";
import type { ChatMessage } from "@multica/core/types";
import type { ChatTimelineItem } from "@multica/core/chat";
-import { splitTimeline, extractCopyText } from "./copy-text";
+import {
+ canonicalAnswerText,
+ extractCopyText,
+ splitTimeline,
+} from "./copy-text";
const text = (seq: number, content: string): ChatTimelineItem => ({
seq,
@@ -82,54 +86,38 @@ describe("splitTimeline", () => {
});
});
-describe("extractCopyText", () => {
- it("falls back to message.content when timeline is empty (legacy)", () => {
- expect(extractCopyText(message("legacy body"), [])).toBe("legacy body");
+describe("canonicalAnswerText", () => {
+ it("uses persisted message content", () => {
+ expect(canonicalAnswerText(message("legacy body"))).toBe("legacy body");
});
- it("returns concatenated text segments for an all-text timeline", () => {
+ it("applies a surface transform to hidden protocols", () => {
expect(
- extractCopyText(message(""), [text(1, "hello"), text(2, "world")]),
- ).toBe("hello\n\nworld");
+ canonicalAnswerText(
+ message("visible<agent_draft>hidden</agent_draft>"),
+ (content) => content.replace(/<agent_draft>[\s\S]*<\/agent_draft>/, ""),
+ ),
+ ).toBe("visible");
});
+});
- it("returns only the final text for the standard tool-using shape", () => {
+describe("extractCopyText", () => {
+ it("copies canonical message content without transcript inference", () => {
expect(
- extractCopyText(message(""), [
- thinking(1),
- tool(2),
- text(3, "intermediate — should be excluded"),
- tool(4),
- text(5, "final answer"),
+ extractCopyText(message("complete canonical answer"), [
+ text(1, "partial timeline answer"),
+ thinking(2),
]),
- ).toBe("final answer");
+ ).toBe("complete canonical answer");
});
- it("includes preface and final, excludes middle text", () => {
+ it("falls back to visible timeline text for legacy empty-content rows", () => {
expect(
- extractCopyText(message(""), [
- text(1, "preface"),
- tool(2),
- text(3, "middle — excluded"),
- tool(4),
- text(5, "final"),
- ]),
+ extractCopyText(message(""), [text(1, "preface"), tool(2), text(3, "final")]),
).toBe("preface\n\nfinal");
});
- it("falls back to message.content when timeline has no text items", () => {
- expect(
- extractCopyText(message("fallback body"), [thinking(1), tool(2)]),
- ).toBe("fallback body");
- });
-
- it("joins multiple trailing text segments with blank-line separators", () => {
- expect(
- extractCopyText(message(""), [
- tool(1),
- text(2, "para 1"),
- text(3, "para 2"),
- ]),
- ).toBe("para 1\n\npara 2");
+ it("returns empty text for an attachment-only row", () => {
+ expect(extractCopyText(message(""), [])).toBe("");
});
});
diff --git a/packages/views/chat/lib/copy-text.ts b/packages/views/chat/lib/copy-text.ts
index 98bc19e5ef..350e1ee3eb 100644
--- a/packages/views/chat/lib/copy-text.ts
+++ b/packages/views/chat/lib/copy-text.ts
@@ -1,5 +1,6 @@
import type { ChatMessage } from "@multica/core/types";
import type { ChatTimelineItem } from "@multica/core/chat";
+import { stripChatQuickActionsProtocol } from "./quick-actions";
/**
* Split an assistant timeline into three regions for the conductor-style fold:
@@ -8,10 +9,9 @@ import type { ChatTimelineItem } from "@multica/core/chat";
* including any text items sandwiched between them
* final — text items after the last non-text item
*
- * UI renders preface above the outer fold, middle inside the fold (with each
- * row keeping its existing inner Collapsible), and final below the fold.
- * Copy concatenates preface + final — the fold's contents are intentionally
- * omitted, mirroring what's visible when the fold is closed.
+ * While streaming, UI renders preface above the outer fold, middle inside the
+ * fold, and final below it. Once settled, preface + middle become process
+ * history and the canonical chat message replaces final.
*/
export function splitTimeline(items: ChatTimelineItem[]): {
preface: ChatTimelineItem[];
@@ -34,21 +34,34 @@ export function splitTimeline(items: ChatTimelineItem[]): {
}
/**
- * Markdown source the Copy action puts on the clipboard. By design this is
- * the user-visible answer only — anything inside the outer fold (thinking,
- * tool calls, sandwiched intermediate text) is dropped. Falls back to
- * `message.content` for legacy messages without a timeline and for the
- * pathological all-non-text shape so Copy never produces an empty string.
+ * Canonical completed answer from the persisted chat message. Surface-specific
+ * transforms still apply so hidden protocols stay out of the rendered and
+ * copied answer.
+ */
+export function canonicalAnswerText(
+ message: ChatMessage,
+ transformContent?: (content: string) => string,
+): string {
+ const content = stripChatQuickActionsProtocol(message.content ?? "");
+ return transformContent ? transformContent(content) : content;
+}
+
+/**
+ * Markdown source for Copy. Completed messages use canonical content instead
+ * of inferring an answer from transcript position. Legacy rows with empty
+ * content retain the previous visible-timeline fallback.
*/
export function extractCopyText(
message: ChatMessage,
timeline: ChatTimelineItem[],
+ transformContent?: (content: string) => string,
): string {
- if (timeline.length === 0) return message.content ?? "";
+ const canonical = canonicalAnswerText(message, transformContent);
+ if (canonical.trim()) return canonical;
+
const { preface, final } = splitTimeline(timeline);
- const pieces = [...preface, ...final]
- .map((i) => i.content ?? "")
- .filter((s) => s.length > 0);
- if (pieces.length === 0) return message.content ?? "";
- return pieces.join("\n\n");
+ return [...preface, ...final]
+ .map((item) => item.content ?? "")
+ .filter((content) => content.length > 0)
+ .join("\n\n");
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a831584502..b84f3f5f84 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9297,37 +9297,51 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
go func() {
defer close(drainFinished)
var mu sync.Mutex
- var pendingText strings.Builder
- var pendingThinking strings.Builder
- var pendingTextAt time.Time
- var pendingThinkingAt time.Time
+ var pendingContent strings.Builder
+ var pendingType string
+ var pendingAt time.Time
var batch []TaskMessageData
callIDToTool := map[string]string{}
- flush := func() {
+ // sealPendingLocked turns the current contiguous text/thinking frame
+ // into a sequenced row. Callers hold mu so a ticker flush cannot assign
+ // a later seq between sealing the frame and appending the event that
+ // followed it.
+ sealPendingLocked := func() {
+ if pendingContent.Len() == 0 {
+ return
+ }
+ s := msgSeq.Add(1)
+ batch = append(batch, TaskMessageData{
+ Seq: int(s),
+ Type: pendingType,
+ Content: pendingContent.String(),
+ CreatedAt: pendingAt,
+ })
+ pendingContent.Reset()
+ pendingType = ""
+ pendingAt = time.Time{}
+ }
+
+ appendPending := func(messageType, content string, observedAt time.Time) {
+ if content == "" {
+ return
+ }
mu.Lock()
- if pendingThinking.Len() > 0 {
- s := msgSeq.Add(1)
- batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "thinking",
- Content: pendingThinking.String(),
- CreatedAt: pendingThinkingAt,
- })
- pendingThinking.Reset()
- pendingThinkingAt = time.Time{}
+ defer mu.Unlock()
+ if pendingType != "" && pendingType != messageType {
+ sealPendingLocked()
}
- if pendingText.Len() > 0 {
- s := msgSeq.Add(1)
- batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "text",
- Content: pendingText.String(),
- CreatedAt: pendingTextAt,
- })
- pendingText.Reset()
- pendingTextAt = time.Time{}
+ if pendingContent.Len() == 0 {
+ pendingType = messageType
+ pendingAt = observedAt
}
+ pendingContent.WriteString(content)
+ }
+
+ flush := func() {
+ mu.Lock()
+ sealPendingLocked()
toSend := batch
batch = nil
mu.Unlock()
@@ -9418,13 +9432,12 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
n := toolCount.Add(1)
inFlightTools.Add(1)
taskLog.Info(fmt.Sprintf("tool #%d: %s", n, msg.Tool))
+ mu.Lock()
+ sealPendingLocked()
if msg.CallID != "" {
- mu.Lock()
callIDToTool[msg.CallID] = msg.Tool
- mu.Unlock()
}
s := msgSeq.Add(1)
- mu.Lock()
batch = append(batch, TaskMessageData{
Seq: int(s),
Type: "tool_use",
@@ -9457,16 +9470,15 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
break
}
}
- s := msgSeq.Add(1)
output, outputTruncated := toolOutputPreview(msg.Output)
+ mu.Lock()
+ sealPendingLocked()
toolName := msg.Tool
if toolName == "" && msg.CallID != "" {
- mu.Lock()
toolName = callIDToTool[msg.CallID]
- mu.Unlock()
}
+ s := msgSeq.Add(1)
taskLog.Info("tool_result observed", "seq", s, "tool", toolName, "call_id", msg.CallID)
- mu.Lock()
batch = append(batch, TaskMessageData{
Seq: int(s),
Type: "tool_result",
@@ -9481,28 +9493,17 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
})
mu.Unlock()
case agent.MessageThinking:
- if msg.Content != "" {
- mu.Lock()
- pendingThinking.WriteString(msg.Content)
- if pendingThinkingAt.IsZero() {
- pendingThinkingAt = observedAt
- }
- mu.Unlock()
- }
+ appendPending("thinking", msg.Content, observedAt)
case agent.MessageText:
if msg.Content != "" {
taskLog.Debug("agent", "text", truncateLog(msg.Content, 200))
- mu.Lock()
- pendingText.WriteString(msg.Content)
- if pendingTextAt.IsZero() {
- pendingTextAt = observedAt
- }
- mu.Unlock()
}
+ appendPending("text", msg.Content, observedAt)
case agent.MessageError:
taskLog.Error("agent error", "content", msg.Content)
- s := msgSeq.Add(1)
mu.Lock()
+ sealPendingLocked()
+ s := msgSeq.Add(1)
batch = append(batch, TaskMessageData{
Seq: int(s),
Type: "error",
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index bab455fd16..7faae547a6 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2782,6 +2782,59 @@ func TestExecuteAndDrain_ReportsFirstBufferedChunkTimestamp(t *testing.T) {
}
}
+type orderedTranscriptBackend struct{}
+
+func (orderedTranscriptBackend) Execute(_ context.Context, _ string, _ agent.ExecOptions) (*agent.Session, error) {
+ msgCh := make(chan agent.Message)
+ resCh := make(chan agent.Result, 1)
+ go func() {
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "preface"}
+ msgCh <- agent.Message{Type: agent.MessageThinking, Content: "reasoning"}
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "answer one"}
+ msgCh <- agent.Message{Type: agent.MessageToolUse, Tool: "read", CallID: "ordered"}
+ msgCh <- agent.Message{Type: agent.MessageToolResult, Tool: "read", CallID: "ordered", Output: "ok"}
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "answer two"}
+ msgCh <- agent.Message{Type: agent.MessageError, Content: "warning"}
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "answer three"}
+ close(msgCh)
+ resCh <- agent.Result{Status: "completed", Output: "done"}
+ close(resCh)
+ }()
+ return &agent.Session{Messages: msgCh, Result: resCh}, nil
+}
+
+func TestExecuteAndDrain_PreservesTranscriptArrivalOrderAcrossMessageTypes(t *testing.T) {
+ t.Parallel()
+
+ d, rec := newTranscriptRecorder(t)
+ if _, _, err := d.executeAndDrain(context.Background(), orderedTranscriptBackend{}, "p", agent.ExecOptions{}, slog.Default(), "task-order", "", new(atomic.Int32)); err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+
+ got := rec.snapshot()
+ want := []struct {
+ typ string
+ content string
+ }{
+ {typ: "text", content: "preface"},
+ {typ: "thinking", content: "reasoning"},
+ {typ: "text", content: "answer one"},
+ {typ: "tool_use"},
+ {typ: "tool_result"},
+ {typ: "text", content: "answer two"},
+ {typ: "error", content: "warning"},
+ {typ: "text", content: "answer three"},
+ }
+ if len(got) != len(want) {
+ t.Fatalf("reported %d messages, want %d in arrival order: %+v", len(got), len(want), got)
+ }
+ for i, expected := range want {
+ if got[i].Seq != i+1 || got[i].Type != expected.typ || got[i].Content != expected.content {
+ t.Fatalf("message %d = %+v, want seq=%d type=%q content=%q", i, got[i], i+1, expected.typ, expected.content)
+ }
+ }
+}
+
// TestExecuteAndDrain_SeqContinuesAcrossRetry pins the transcript's ordering
// key: the server sorts a task's messages by seq alone, so a same-task resume
// retry must keep numbering upwards instead of restarting at 1 and