Skip to content

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

Go

feat(transcript): tell the reader when a tool output was truncated MUL-7168 (#8212)

Bohan Jiange04465be0b3e
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index f1582dfa1d..6ba8bf6d2f 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -349,6 +349,10 @@ export const TaskMessagePayloadSchema: z.ZodType<TaskMessagePayload> = z.object(
content: z.string().optional(),
input: z.record(z.string(), z.unknown()).optional(),
output: z.string().optional(),
+ // Optional with no default: absent means no daemon measured this record's
+ // completeness, which is not the same as measured-and-complete. `.catch`
+ // keeps a malformed value from failing the row and emptying the transcript.
+ output_truncated: z.boolean().optional().catch(undefined),
created_at: z.string().optional(),
}).loose();
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 92526f1bfd..784bd41c97 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -322,6 +322,7 @@ import {
SquadListSchema,
SquadMemberStatusListResponseSchema,
SubscribersListSchema,
+ TaskMessageListSchema,
TimelineEntriesSchema,
UserSchema,
WebhookDeliveryResponseSchema,
@@ -2396,7 +2397,10 @@ export class ApiClient {
}
async listTaskMessages(taskId: string): Promise<TaskMessagePayload[]> {
- return this.fetch(`/api/tasks/${taskId}/messages`);
+ const raw = await this.fetch<unknown>(`/api/tasks/${taskId}/messages`);
+ return parseWithFallback<TaskMessagePayload[]>(raw, TaskMessageListSchema, [], {
+ endpoint: "GET /api/tasks/:id/messages",
+ });
}
async listTasksByIssue(issueId: string): Promise<AgentTask[]> {
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 35155d816a..05d0bef349 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -14,6 +14,7 @@ import {
EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE,
AgentTaskListSchema,
+ TaskMessageListSchema,
AutopilotQuotaUsageSchema,
AutopilotRunSchema,
FALLBACK_AUTOPILOT_RUN,
@@ -2108,3 +2109,65 @@ describe("issue status catalog schemas", () => {
expect(parsed).toEqual(EMPTY_ISSUE_STATUS_ENTRY);
});
});
+
+describe("TaskMessageListSchema", () => {
+ const row = { task_id: "task-1", issue_id: "issue-1", seq: 1, type: "tool_result", output: "log line" };
+
+ // The whole point of the field: a server that never sends it is saying
+ // "nobody measured this", and only `undefined` can carry that. A default of
+ // false would make every historical row assert it is complete.
+ it("leaves a missing truncation flag undefined rather than false", () => {
+ const parsed = TaskMessageListSchema.parse([row]);
+ expect(parsed[0]).not.toHaveProperty("output_truncated", false);
+ expect(parsed[0]?.output_truncated).toBeUndefined();
+ });
+
+ it("keeps both measured values", () => {
+ const parsed = TaskMessageListSchema.parse([
+ { ...row, seq: 1, output_truncated: true },
+ { ...row, seq: 2, output_truncated: false },
+ ]);
+ expect(parsed.map((m) => m.output_truncated)).toEqual([true, false]);
+ });
+
+ // Drift defense. Without a field-level catch, one bad boolean fails its row,
+ // the array fails with it, and parseWithFallback hands the viewer an empty
+ // transcript — a malformed flag would delete the whole run from the screen.
+ // Degrading the field to "unknown" is the correct loss.
+ it("keeps the record and forgets the field when the flag is malformed", () => {
+ const parsed = parseWithFallback<{ output?: string; output_truncated?: boolean }[]>(
+ [{ ...row, output_truncated: "false" }],
+ TaskMessageListSchema,
+ [],
+ { endpoint: "GET /api/tasks/:id/messages" },
+ );
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0]?.output).toBe("log line");
+ expect(parsed[0]?.output_truncated).toBeUndefined();
+ });
+
+ it("keeps the surrounding rows when one row's flag is malformed", () => {
+ const parsed = TaskMessageListSchema.parse([
+ { ...row, seq: 1, output_truncated: true },
+ { ...row, seq: 2, output_truncated: 12345 },
+ { ...row, seq: 3, output_truncated: false },
+ ]);
+ expect(parsed.map((m) => m.seq)).toEqual([1, 2, 3]);
+ expect(parsed.map((m) => m.output_truncated)).toEqual([true, undefined, false]);
+ });
+
+ it("falls back to an empty transcript when the response is not a list", () => {
+ const parsed = parseWithFallback(
+ { messages: "nope" },
+ TaskMessageListSchema,
+ [],
+ { endpoint: "GET /api/tasks/:id/messages" },
+ );
+ expect(parsed).toEqual([]);
+ });
+
+ it("downgrades an unknown message type instead of dropping the transcript", () => {
+ const parsed = TaskMessageListSchema.parse([{ ...row, type: "video" }]);
+ expect(parsed[0]?.type).toBe("text");
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 909ac24a09..7f73ad4900 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1780,6 +1780,31 @@ export const AgentTaskSchema = z.object({
export const AgentTaskListSchema = z.array(AgentTaskSchema);
+// One row of a run transcript. `output_truncated` gates a completeness claim
+// the UI makes about a tool's output, so it stays `.optional()` with no
+// default: a server that does not send it means "unknown", and defaulting it
+// to false would turn a missing field into an assertion that the record is
+// complete. `.catch(undefined)` keeps a malformed value that far too — without
+// it a single bad boolean fails its row, the array fails with it, and
+// `parseWithFallback` hands the viewer an empty transcript. Degrading one
+// field to "unknown" is the correct loss; deleting the run is not. Every other
+// field keeps a default for the same reason.
+export const TaskMessagePayloadSchema = z.object({
+ task_id: z.string().default(""),
+ issue_id: z.string().default(""),
+ chat_session_id: z.string().optional(),
+ seq: z.number().default(0),
+ type: z.enum(["text", "thinking", "tool_use", "tool_result", "error"]).catch("text"),
+ tool: z.string().optional(),
+ content: z.string().optional(),
+ input: z.record(z.string(), z.unknown()).optional(),
+ output: z.string().optional(),
+ output_truncated: z.boolean().optional().catch(undefined),
+ created_at: z.string().optional(),
+}).loose();
+
+export const TaskMessageListSchema = z.array(TaskMessagePayloadSchema).default([]);
+
// Task cancellation (`POST /api/tasks/:id/cancel`) is consumed directly by
// chat recovery. Its optional message payload must be well-formed before the
// UI deletes a message from cache or restores text into the input.
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index df159713ba..efc79dc1e8 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -294,6 +294,18 @@ export interface TaskMessagePayload {
content?: string;
input?: Record<string, unknown>;
output?: string;
+ /**
+ * Whether `output` is the whole tool output that ran (`tool_result` only).
+ *
+ * Tri-state on purpose. `undefined` means no daemon ever measured this
+ * record — messages stored before the flag existed, and messages from an
+ * older installed daemon — and must be presented as unknown, never as
+ * complete: the original length is gone and cannot be reconstructed.
+ * `true` means the remainder was never uploaded and no amount of expanding
+ * or scrolling recovers it, which is what separates it from a client-side
+ * display clip.
+ */
+ output_truncated?: boolean;
created_at?: string;
}
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index d353bd951b..44e21d0f97 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -921,3 +921,98 @@ describe("readable issue references", () => {
expect(screen.getByText("multica issue get DEV-17 --output json")).toBeInTheDocument();
});
});
+
+// The completeness indicator, #8182 / #8183. A truncation remark sits at the
+// end of the output it describes and waits for the reader to reveal that end;
+// unknown-ness belongs to the run, because one daemon produced all of it. The
+// state matrix lives in build-timeline.test.ts.
+describe("tool output completeness", () => {
+ const SHORT = "line one";
+ // Past ToolDetailSurface's fade threshold, so the body opens collapsed.
+ const LONG = Array.from({ length: 40 }, (_, i) => `line ${i}`).join("\n");
+
+ function run(output: string, output_truncated?: boolean): TimelineItem[] {
+ return [
+ { seq: 1, type: "tool_use", tool: "exec_command", input: { command: "cat big.log" } },
+ { seq: 2, type: "tool_result", tool: "exec_command", output, output_truncated },
+ ];
+ }
+
+ function openStep(items: TimelineItem[]) {
+ renderDialog(items);
+ fireEvent.click(screen.getByRole("button", { name: /cat big\.log/ }));
+ }
+
+ it("remarks at the end of an output the record could not keep whole", () => {
+ openStep(run(SHORT, true));
+
+ expect(screen.getByText(/only the beginning was kept/i)).toBeInTheDocument();
+ });
+
+ it("says nothing about an output the daemon measured as complete", () => {
+ openStep(run(SHORT, false));
+
+ expect(screen.queryByText(/only the beginning was kept/i)).not.toBeInTheDocument();
+ });
+
+ // The remark answers "was that all of it?", which is a question the reader
+ // only has at the bottom. Showing it over a faded, half-shown body answers
+ // ahead of the question and puts the words nowhere near the end they describe.
+ it("waits for the body to be revealed before remarking", () => {
+ openStep(run(LONG, true));
+ expect(screen.queryByText(/only the beginning was kept/i)).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+
+ expect(screen.getByText(/only the beginning was kept/i)).toBeInTheDocument();
+ });
+
+ // Regression guard: a warning badge next to the tool name announced the
+ // caveat before the reader had asked the question.
+ it("keeps the remark out of the step header", () => {
+ openStep(run(SHORT, true));
+
+ const header = screen.getByRole("button", { name: "Copy this step" }).closest("div");
+ expect(header).toHaveTextContent("exec_command");
+ expect(header).not.toHaveTextContent(/only the beginning was kept/i);
+ });
+
+ // A stored tool result is capped at 8192 bytes upstream, so the render clip
+ // must never reach it: one remark, not a second reporting the rounding error.
+ it("leaves a stored tool result with exactly one remark", () => {
+ openStep(run("x".repeat(8192), true));
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+
+ expect(screen.getByText(/only the beginning was kept/i)).toBeInTheDocument();
+ expect(screen.queryByText(/only the start is displayed/i)).not.toBeInTheDocument();
+ });
+
+ // Tool input has no server-side budget and keeps its existing render ceiling.
+ // Nothing about how long an input renders is this change's business.
+ it("still clips a tool input at its existing length", () => {
+ renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "exec_command",
+ input: { command: "echo", payload: "y".repeat(9000) },
+ },
+ ]);
+ fireEvent.click(screen.getByRole("button", { name: /exec_command/ }));
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+
+ const body = screen.getByText(/only the start is displayed/i);
+ expect(body.textContent).not.toMatch(/copy|whole record|everything that was saved/i);
+ });
+
+ // A record from before the flag existed says nothing at all. The viewer only
+ // speaks when a daemon measured the output and found bytes missing; it never
+ // volunteers that it cannot tell, in the transcript or above it.
+ it("stays silent on a record whose completeness was never measured", () => {
+ openStep(run(LONG, undefined));
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+
+ expect(screen.queryByText(/only the beginning was kept/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/cannot be confirmed|completeness/i)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 77ee78a89e..41cd220909 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -62,7 +62,7 @@ import {
FOLLOW_EDGE_THRESHOLD,
LINE_SCROLL_PX,
} from "./transcript-follow";
-import type { TimelineItem } from "./build-timeline";
+import { isOutputTruncated, type TimelineItem } from "./build-timeline";
import {
buildLanes,
buildSteps,
@@ -1752,10 +1752,17 @@ function InspectorSection({ label, children }: { label: string; children: React.
}
/** One payload, rendered as what it is. */
+/** Pre-existing render ceiling for a body with no server-side budget. */
+const DISPLAY_CLIP_CHARS = 8000;
+
export function StepBody({ item }: { item: TimelineItem }) {
const { t } = useT("agents");
const detail = useMemo(() => traceEventDetail(item), [item]);
const image = useMemo(() => readImageResult(item.output), [item.output]);
+ // Stated where the output actually ends, for a reader who has just reached
+ // the bottom and is wondering whether that was all of it. A header badge said
+ // the same thing louder, before anyone had asked the question.
+ const note = isOutputTruncated(item) ? t(($) => $.transcript.output_truncated_note) : undefined;
// A screenshot is a picture, not a 200KB base64 string in a <pre>.
if (image) {
@@ -1769,6 +1776,7 @@ export function StepBody({ item }: { item: TimelineItem }) {
<figcaption className="pt-1 text-micro text-faint-foreground">
{t(($) => $.transcript.image_result)} · {formatBytes(base64ByteLength(image.base64))}
</figcaption>
+ {note && <span className="block pt-1 text-micro text-faint-foreground">{note}</span>}
</figure>
);
}
@@ -1779,15 +1787,27 @@ export function StepBody({ item }: { item: TimelineItem }) {
case "patch":
return <PatchDetailSurface files={detail.files} truncated={detail.truncated} />;
case "file":
- return (
- <FileWriteSurface text={detail.text} lineCount={detail.lineCount} path={detail.path} />
- );
+ return <FileWriteSurface text={detail.text} lineCount={detail.lineCount} path={detail.path} />;
default: {
const text = detail.text;
+ // A stored tool result is already capped at 8192 bytes by the daemon, so
+ // clipping it again could only shave a couple of hundred more characters
+ // — under a note that already reports the same loss. Tool input has no
+ // server-side budget and keeps the clip at its existing length; nothing
+ // about how long an input renders is this change's business.
+ const clip = item.type === "tool_result" ? null : DISPLAY_CLIP_CHARS;
const clipped =
- text.length > 8000 ? `${redactSecrets(text.slice(0, 8000))}\n... (truncated)` : redactSecrets(text);
+ clip !== null && text.length > clip
+ ? `${redactSecrets(text.slice(0, clip))}\n${t(($) => $.transcript.display_clipped)}`
+ : redactSecrets(text);
const path = item.type === "tool_use" ? readPathFromInput(item.input) : undefined;
- return <ToolDetailSurface text={clipped} language={path ? languageForPath(path) : undefined} />;
+ return (
+ <ToolDetailSurface
+ text={clipped}
+ language={path ? languageForPath(path) : undefined}
+ note={note}
+ />
+ );
}
}
}
diff --git a/packages/views/common/task-transcript/build-timeline.test.ts b/packages/views/common/task-transcript/build-timeline.test.ts
index eb9f6c5563..8dad6d8ffa 100644
--- a/packages/views/common/task-transcript/build-timeline.test.ts
+++ b/packages/views/common/task-transcript/build-timeline.test.ts
@@ -1,7 +1,13 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { TaskMessagePayload } from "@multica/core/types/events";
-import { appendTimelineItem, buildTimeline, coalesceTimelineItems, type TimelineItem } from "./build-timeline";
+import {
+ appendTimelineItem,
+ buildTimeline,
+ coalesceTimelineItems,
+ isOutputTruncated,
+ type TimelineItem,
+} from "./build-timeline";
function message(seq: number, type: TaskMessagePayload["type"], content?: string): TaskMessagePayload {
return {
@@ -103,3 +109,44 @@ describe("task transcript timeline", () => {
expect(items[0]?.created_at).toBe("2026-06-09T09:00:00.000Z");
});
});
+
+describe("tool output completeness", () => {
+ function result(output: string | undefined, output_truncated?: boolean): TimelineItem {
+ return { seq: 1, type: "tool_result", tool: "bash", output, output_truncated };
+ }
+
+ it("carries the server's truncation flag onto the timeline", () => {
+ const items = buildTimeline([
+ { ...message(1, "tool_result"), output: "cut here", output_truncated: true },
+ { ...message(2, "tool_result"), output: "all of it", output_truncated: false },
+ { ...message(3, "tool_result"), output: "who knows" },
+ ]);
+
+ expect(items.map((i) => i.output_truncated)).toEqual([true, false, undefined]);
+ });
+
+ // false is a measurement, undefined is the absence of one. Only a positive
+ // measurement earns the per-step remark.
+ it("marks only an output measured as truncated", () => {
+ expect(isOutputTruncated(result("x", true))).toBe(true);
+ expect(isOutputTruncated(result("x", false))).toBe(false);
+ expect(isOutputTruncated(result("x"))).toBe(false);
+ });
+
+ // A truncated preview keeps the first 8 KiB, so an empty output cannot be one.
+ it("says nothing about an empty output", () => {
+ expect(isOutputTruncated(result("", true))).toBe(false);
+ expect(isOutputTruncated(result(undefined, true))).toBe(false);
+ });
+
+ // The flag only describes tool output; prose and thinking have no preview
+ // budget to overflow.
+ it("ignores message types that have no tool output", () => {
+ const others: TimelineItem[] = [
+ { seq: 1, type: "text", content: "hello" },
+ { seq: 2, type: "thinking", content: "hmm" },
+ { seq: 3, type: "error", content: "boom" },
+ ];
+ expect(others.some(isOutputTruncated)).toBe(false);
+ });
+});
diff --git a/packages/views/common/task-transcript/build-timeline.ts b/packages/views/common/task-transcript/build-timeline.ts
index 8dbda76444..3557fa9697 100644
--- a/packages/views/common/task-transcript/build-timeline.ts
+++ b/packages/views/common/task-transcript/build-timeline.ts
@@ -9,6 +9,12 @@ export interface TimelineItem {
content?: string;
input?: Record<string, unknown>;
output?: string;
+ /**
+ * Whether the stored `output` dropped bytes at the source (`tool_result`
+ * only). `undefined` means unknown — the record predates the flag or came
+ * from an older daemon — and must never be rendered as "complete".
+ */
+ output_truncated?: boolean;
created_at?: string;
}
@@ -49,6 +55,19 @@ function redactTimelineItems(items: TimelineItem[]): TimelineItem[] {
}));
}
+/**
+ * Whether this record's stored output is known to have dropped bytes.
+ *
+ * Only tool results carry the measurement, and an empty output has nothing to
+ * be missing — truncation keeps the first 8 KiB, so a preview that dropped
+ * bytes is never empty.
+ */
+export function isOutputTruncated(item: TimelineItem): boolean {
+ return (
+ item.type === "tool_result" && (item.output?.length ?? 0) > 0 && item.output_truncated === true
+ );
+}
+
/** Build a chronologically ordered timeline from raw task messages. */
export function buildTimeline(msgs: TaskMessagePayload[]): TimelineItem[] {
const items: TimelineItem[] = [];
@@ -60,6 +79,7 @@ export function buildTimeline(msgs: TaskMessagePayload[]): TimelineItem[] {
content: msg.content,
input: msg.input,
output: msg.output,
+ output_truncated: msg.output_truncated,
created_at: msg.created_at,
});
}
diff --git a/packages/views/common/task-transcript/detail-surfaces.tsx b/packages/views/common/task-transcript/detail-surfaces.tsx
index 800e6a7674..7eeb876b55 100644
--- a/packages/views/common/task-transcript/detail-surfaces.tsx
+++ b/packages/views/common/task-transcript/detail-surfaces.tsx
@@ -229,10 +229,24 @@ export function DiffDetailSurface({ lines, path }: { lines: TraceDiffLine[]; pat
);
}
-export function ToolDetailSurface({ text, language }: { text: string; language?: string }) {
+export function ToolDetailSurface({
+ text,
+ language,
+ note,
+}: {
+ text: string;
+ language?: string;
+ /**
+ * A remark about the body, shown at its end once the whole body is on
+ * screen. Withheld while the fade is up: a note that answers "was that all
+ * of it?" is only an answer to a reader who has reached the bottom.
+ */
+ note?: string;
+}) {
const { t } = useT("agents");
const [showAll, setShowAll] = useState(false);
const isLong = text.length > 1600 || text.split("\n").length > 14;
+ const revealed = !isLong || showAll;
// Only file bodies carry a language; command output and JSON stay plain.
const html = useMemo(() => (language ? highlightBlock(text, language) : null), [text, language]);
@@ -265,6 +279,7 @@ export function ToolDetailSurface({ text, language }: { text: string; language?:
</button>
</div>
)}
+ {note && revealed && <p className="px-3 pb-2 text-micro text-faint-foreground">{note}</p>}
</div>
);
}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 5f2216a3e0..1eeba6f002 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -856,6 +856,8 @@
"show_all": "Show all",
"patch_truncated": "... (truncated)",
"patch_body_truncated": "... (body truncated)",
+ "display_clipped": "... (too long to show in full — only the start is displayed)",
+ "output_truncated_note": "Output was too long — only the beginning was kept.",
"patch_no_content": "(no content reported)",
"patch_summary_more": "{{path}} +{{extra}} more",
"status_queued": "Queued",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 2ba1a1b76a..4e84103530 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -734,6 +734,8 @@
"show_all": "すべて表示",
"patch_truncated": "...(切り詰め済み)",
"patch_body_truncated": "...(本文を切り詰めました)",
+ "display_clipped": "...(内容が長いため先頭のみ表示しています)",
+ "output_truncated_note": "出力が長すぎるため、先頭部分のみ保存されています。",
"patch_no_content": "(内容の記録なし)",
"patch_summary_more": "{{path}} 他 {{extra}} 件",
"status_queued": "待機列",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 632ff7d747..5999e5cc5d 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -742,6 +742,8 @@
"show_all": "모두 보기",
"patch_truncated": "...(잘림)",
"patch_body_truncated": "...(본문 잘림)",
+ "display_clipped": "...(내용이 길어 앞부분만 표시합니다)",
+ "output_truncated_note": "출력이 너무 길어 앞부분만 저장되어 있습니다.",
"patch_no_content": "(기록된 내용 없음)",
"patch_summary_more": "{{path}} 외 {{extra}}개",
"status_queued": "대기열",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 6f293c9a3b..2ac553dccd 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -841,6 +841,8 @@
"show_all": "显示全部",
"patch_truncated": "...(已截断)",
"patch_body_truncated": "...(内容已截断)",
+ "display_clipped": "...(内容过长,此处仅显示开头)",
+ "output_truncated_note": "输出内容过长,只保留了开头部分。",
"patch_no_content": "(未记录内容)",
"patch_summary_more": "{{path}},另有 {{extra}} 个文件",
"status_queued": "排队中",
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 4881307254..3873d4a18b 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -514,6 +514,11 @@ type TaskMessageData struct {
Content string `json:"content,omitempty"`
Input map[string]any `json:"input,omitempty"`
Output string `json:"output,omitempty"`
+ // OutputTruncated reports whether Output dropped bytes to fit the preview
+ // budget. Tri-state on purpose: nil means this daemon did not measure it,
+ // which an older installed daemon talking to a newer server cannot say any
+ // other way, and which the server must not record as "complete".
+ OutputTruncated *bool `json:"output_truncated,omitempty"`
}
func (c *Client) ReportTaskMessages(ctx context.Context, taskID string, messages []TaskMessageData) error {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 8623b8cb8f..13be3d1fb9 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9119,7 +9119,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
}
}
s := msgSeq.Add(1)
- output := toolOutputPreview(msg.Output)
+ output, outputTruncated := toolOutputPreview(msg.Output)
toolName := msg.Tool
if toolName == "" && msg.CallID != "" {
mu.Lock()
@@ -9133,6 +9133,11 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
Type: "tool_result",
Tool: toolName,
Output: output,
+ // Always sent, including false: the reader has to be
+ // able to tell "this record is complete" from "this
+ // record predates the flag", and only a daemon that
+ // measured the output can say the former.
+ OutputTruncated: &outputTruncated,
})
mu.Unlock()
case agent.MessageThinking:
diff --git a/server/internal/daemon/tool_output_preview.go b/server/internal/daemon/tool_output_preview.go
index 101dda42ee..e7bbf40a86 100644
--- a/server/internal/daemon/tool_output_preview.go
+++ b/server/internal/daemon/tool_output_preview.go
@@ -10,13 +10,18 @@ import (
// previews. It does not limit the full output consumed by the agent.
const toolOutputPreviewBudget = 8192
-// toolOutputPreview returns the longest complete-rune prefix within the budget.
-// Normalize malformed UTF-8 and NULs with the existing persistence sanitizer
-// first, so normalization cannot expand a byte-bounded preview past the budget.
-func toolOutputPreview(raw string) string {
+// toolOutputPreview returns the longest complete-rune prefix within the budget,
+// and whether anything was dropped to fit it. Normalize malformed UTF-8 and
+// NULs with the existing persistence sanitizer first, so normalization cannot
+// expand a byte-bounded preview past the budget.
+//
+// truncated describes the SOURCE record only: it says the remainder was never
+// uploaded and cannot be recovered by scrolling or expanding. Whatever a client
+// does to fit the preview on screen is a separate, reversible concern.
+func toolOutputPreview(raw string) (preview string, truncated bool) {
output := util.SanitizeTextForPostgres(raw)
if len(output) <= toolOutputPreviewBudget {
- return output
+ return output, false
}
end := toolOutputPreviewBudget
@@ -24,5 +29,5 @@ func toolOutputPreview(raw string) string {
for !utf8.RuneStart(output[end]) {
end--
}
- return output[:end]
+ return output[:end], true
}
diff --git a/server/internal/daemon/tool_output_preview_test.go b/server/internal/daemon/tool_output_preview_test.go
index 638cbaf73a..e9e5e0763b 100644
--- a/server/internal/daemon/tool_output_preview_test.go
+++ b/server/internal/daemon/tool_output_preview_test.go
@@ -15,26 +15,33 @@ func TestToolOutputPreview(t *testing.T) {
t.Parallel()
tests := []struct {
name, input, want string
+ wantTruncated bool
}{
- {"empty", "", ""},
- {"short unicode", "执行完成 😀\n", "执行完成 😀\n"},
- {"under budget", strings.Repeat("a", 8191), strings.Repeat("a", 8191)},
- {"exact budget", strings.Repeat("a", 8192), strings.Repeat("a", 8192)},
- {"over budget", strings.Repeat("a", 8193), strings.Repeat("a", 8192)},
- {"chinese", strings.Repeat("中", 5000), strings.Repeat("中", 2730)},
- {"emoji", strings.Repeat("😀", 3000), strings.Repeat("😀", 2048)},
+ {"empty", "", "", false},
+ {"short unicode", "执行完成 😀\n", "执行完成 😀\n", false},
+ {"under budget", strings.Repeat("a", 8191), strings.Repeat("a", 8191), false},
+ {"exact budget", strings.Repeat("a", 8192), strings.Repeat("a", 8192), false},
+ {"over budget", strings.Repeat("a", 8193), strings.Repeat("a", 8192), true},
+ {"chinese", strings.Repeat("中", 5000), strings.Repeat("中", 2730), true},
+ {"emoji", strings.Repeat("😀", 3000), strings.Repeat("😀", 2048), true},
// Server-side redaction may expand this input. That is not source truncation.
- {"redaction growth", strings.Repeat("TOKEN=x ", 1024), strings.Repeat("TOKEN=x ", 1024)},
- {"nul", "before\x00after", "beforeafter"},
- {"invalid utf8", "a\xffb", "a\uFFFDb"},
- {"normalization growth", strings.Repeat("a", 8191) + "\xff", strings.Repeat("a", 8191)},
- {"normalization shrink", strings.Repeat("a", 8191) + "\x00b", strings.Repeat("a", 8191) + "b"},
+ {"redaction growth", strings.Repeat("TOKEN=x ", 1024), strings.Repeat("TOKEN=x ", 1024), false},
+ {"nul", "before\x00after", "beforeafter", false},
+ {"invalid utf8", "a\xffb", "a\uFFFDb", false},
+ // Sanitizing this input pushes it past the budget, so the record really
+ // does lose bytes — the flag follows the stored preview, not the raw input.
+ {"normalization growth", strings.Repeat("a", 8191) + "\xff", strings.Repeat("a", 8191), true},
+ {"normalization shrink", strings.Repeat("a", 8191) + "\x00b", strings.Repeat("a", 8191) + "b", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := toolOutputPreview(tt.input); got != tt.want {
+ got, truncated := toolOutputPreview(tt.input)
+ if got != tt.want {
t.Fatalf("preview differs from expected text: got %d bytes, want %d", len(got), len(tt.want))
}
+ if truncated != tt.wantTruncated {
+ t.Fatalf("truncated=%v, want %v: the flag must describe whether the stored preview dropped bytes", truncated, tt.wantTruncated)
+ }
})
}
}
@@ -51,9 +58,13 @@ func TestToolOutputPreviewRuneBoundaries(t *testing.T) {
if kept == len(char) {
want += char
}
- if got := toolOutputPreview(prefix + char + "tail"); got != want {
+ got, truncated := toolOutputPreview(prefix + char + "tail")
+ if got != want {
t.Fatalf("cut must retain exactly the complete runes: got %d bytes, want %d", len(got), len(want))
}
+ if !truncated {
+ t.Fatal("every cut in this loop drops the tail, so truncated must be true")
+ }
})
}
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 2ea9e6fb36..07d34c7565 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4683,6 +4683,11 @@ type TaskMessageRequest struct {
Content string `json:"content,omitempty"`
Input map[string]any `json:"input,omitempty"`
Output string `json:"output,omitempty"`
+ // OutputTruncated is absent from every older daemon's payload, so it stays
+ // a pointer all the way to the column: nil must persist as NULL (unknown),
+ // never as false. Recording an unmeasured output as complete is the one
+ // claim this data is not entitled to make.
+ OutputTruncated *bool `json:"output_truncated,omitempty"`
}
type TaskMessageBatchRequest struct {
@@ -4739,6 +4744,9 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
Contents: make([]string, 0, n),
Inputs: make([]string, 0, n),
Outputs: make([]string, 0, n),
+ // Tri-state through a text[]: "" is NULL, matching how the query maps
+ // every other nullable column in this batch.
+ OutputTruncations: make([]string, 0, n),
}
for _, msg := range req.Messages {
id, err := uuid.NewV7()
@@ -4794,6 +4802,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
params.Contents = append(params.Contents, msg.Content)
params.Inputs = append(params.Inputs, inputJSON)
params.Outputs = append(params.Outputs, msg.Output)
+ params.OutputTruncations = append(params.OutputTruncations, boolArrayElement(msg.OutputTruncated))
}
created, err := h.Queries.CreateTaskMessages(r.Context(), params)
@@ -4933,18 +4942,32 @@ func taskMessageToPayload(m db.TaskMessage, taskID, issueID string) protocol.Tas
createdAt = m.CreatedAt.Time.UTC().Format(time.RFC3339Nano)
}
return protocol.TaskMessagePayload{
- TaskID: taskID,
- IssueID: issueID,
- Seq: int(m.Seq),
- Type: m.Type,
- Tool: m.Tool.String,
- Content: m.Content.String,
- Input: input,
- Output: m.Output.String,
- CreatedAt: createdAt,
+ TaskID: taskID,
+ IssueID: issueID,
+ Seq: int(m.Seq),
+ Type: m.Type,
+ Tool: m.Tool.String,
+ Content: m.Content.String,
+ Input: input,
+ Output: m.Output.String,
+ OutputTruncated: util.BoolToPtr(m.OutputTruncated),
+ CreatedAt: createdAt,
}
}
+// boolArrayElement encodes a tri-state bool for the text[] parameters the batch
+// insert uses. Empty string is the query's NULL, so an unmeasured output stays
+// unknown rather than collapsing into false.
+func boolArrayElement(v *bool) string {
+ if v == nil {
+ return ""
+ }
+ if *v {
+ return "true"
+ }
+ return "false"
+}
+
// ListTaskMessages returns the persisted messages for a task (for catch-up after reconnect).
func (h *Handler) ListTaskMessages(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
diff --git a/server/internal/handler/task_message_truncation_test.go b/server/internal/handler/task_message_truncation_test.go
new file mode 100644
index 0000000000..1a28331366
--- /dev/null
+++ b/server/internal/handler/task_message_truncation_test.go
@@ -0,0 +1,106 @@
+package handler
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// The truncation flag is tri-state on purpose. `false` is a measurement an
+// upgraded daemon made; absent is the absence of one, which is all a
+// historical row or an older installed daemon can say. Collapsing absent into
+// false would make every row that predates the flag assert it is complete —
+// the one claim this data cannot support, since the original length is gone.
+func TestCreateTaskMessagesKeepsTruncationTriState(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ agentID := createHandlerTestAgent(t, "TaskMessageTruncation", []byte("[]"))
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": handlerTestRuntimeID(t),
+ "status": "running",
+ })
+
+ yes, no := true, false
+ messages := []TaskMessageRequest{
+ {Seq: 1, Type: "tool_result", Tool: "bash", Output: "cut", OutputTruncated: &yes},
+ {Seq: 2, Type: "tool_result", Tool: "bash", Output: "whole", OutputTruncated: &no},
+ {Seq: 3, Type: "tool_result", Tool: "bash", Output: "unmeasured"},
+ }
+
+ params := db.CreateTaskMessagesParams{
+ TaskID: parseUUID(taskID),
+ Ids: make([]pgtype.UUID, 0, len(messages)),
+ Seqs: make([]int32, 0, len(messages)),
+ Types: make([]string, 0, len(messages)),
+ Tools: make([]string, 0, len(messages)),
+ Contents: make([]string, 0, len(messages)),
+ Inputs: make([]string, 0, len(messages)),
+ Outputs: make([]string, 0, len(messages)),
+ OutputTruncations: make([]string, 0, len(messages)),
+ }
+ for _, msg := range messages {
+ params.Ids = append(params.Ids, pgtype.UUID{Bytes: uuid.Must(uuid.NewV7()), Valid: true})
+ params.Seqs = append(params.Seqs, int32(msg.Seq))
+ params.Types = append(params.Types, msg.Type)
+ params.Tools = append(params.Tools, msg.Tool)
+ params.Contents = append(params.Contents, msg.Content)
+ params.Inputs = append(params.Inputs, "")
+ params.Outputs = append(params.Outputs, msg.Output)
+ params.OutputTruncations = append(params.OutputTruncations, boolArrayElement(msg.OutputTruncated))
+ }
+
+ created, err := testHandler.Queries.CreateTaskMessages(ctx, params)
+ if err != nil {
+ t.Fatalf("CreateTaskMessages: %v", err)
+ }
+ if len(created) != len(messages) {
+ t.Fatalf("inserted %d rows, want %d", len(created), len(messages))
+ }
+
+ // The column, not just the returned row: the text[] parameter has to reach
+ // Postgres as a real NULL, which is what makes the third state storable.
+ var nullCount int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM task_message WHERE task_id = $1 AND output_truncated IS NULL`,
+ taskID).Scan(&nullCount); err != nil {
+ t.Fatalf("count NULL output_truncated: %v", err)
+ }
+ if nullCount != 1 {
+ t.Fatalf("rows stored with NULL output_truncated = %d, want 1 (only the unmeasured message)", nullCount)
+ }
+
+ want := []*bool{&yes, &no, nil}
+ for i, row := range created {
+ got := taskMessageToPayload(db.TaskMessage(row), taskID, "").OutputTruncated
+ switch {
+ case want[i] == nil && got != nil:
+ t.Fatalf("seq %d: payload says truncated=%v, want omitted — an unmeasured output must not report a value", row.Seq, *got)
+ case want[i] != nil && got == nil:
+ t.Fatalf("seq %d: payload omits the flag, want %v", row.Seq, *want[i])
+ case want[i] != nil && *got != *want[i]:
+ t.Fatalf("seq %d: payload says truncated=%v, want %v", row.Seq, *got, *want[i])
+ }
+ }
+}
+
+func TestBoolArrayElement(t *testing.T) {
+ yes, no := true, false
+ // Empty string is the query's NULL, matching how every other nullable
+ // column in this batch is encoded.
+ if got := boolArrayElement(nil); got != "" {
+ t.Fatalf("nil encodes as %q, want the empty string the query maps to NULL", got)
+ }
+ if got := boolArrayElement(&yes); got != "true" {
+ t.Fatalf("true encodes as %q", got)
+ }
+ if got := boolArrayElement(&no); got != "false" {
+ t.Fatalf("false encodes as %q", got)
+ }
+}
diff --git a/server/internal/util/pgx.go b/server/internal/util/pgx.go
index 98bc8ca831..3d410bcb55 100644
--- a/server/internal/util/pgx.go
+++ b/server/internal/util/pgx.go
@@ -63,6 +63,16 @@ func TextToPtr(t pgtype.Text) *string {
return &t.String
}
+// BoolToPtr keeps a nullable boolean column tri-state on the way out. NULL
+// becomes nil, not false: callers that render "complete" on false must not be
+// handed a value the row never contained.
+func BoolToPtr(b pgtype.Bool) *bool {
+ if !b.Valid {
+ return nil
+ }
+ return &b.Bool
+}
+
func PtrToText(s *string) pgtype.Text {
if s == nil {
return pgtype.Text{}
diff --git a/server/migrations/457_task_message_output_truncated.down.sql b/server/migrations/457_task_message_output_truncated.down.sql
new file mode 100644
index 0000000000..eaf6871f22
--- /dev/null
+++ b/server/migrations/457_task_message_output_truncated.down.sql
@@ -0,0 +1 @@
+ALTER TABLE task_message DROP COLUMN IF EXISTS output_truncated;
diff --git a/server/migrations/457_task_message_output_truncated.up.sql b/server/migrations/457_task_message_output_truncated.up.sql
new file mode 100644
index 0000000000..0db17dd834
--- /dev/null
+++ b/server/migrations/457_task_message_output_truncated.up.sql
@@ -0,0 +1,13 @@
+-- Records whether a tool_result's stored output dropped bytes to fit the
+-- daemon's preview budget.
+--
+-- Nullable with NO DEFAULT, and deliberately not backfilled. Three states:
+-- NULL = unknown. The row predates this column, or an older installed
+-- daemon reported it. The original length is gone, so nothing can
+-- recover whether it was complete.
+-- FALSE = the daemon measured the output and stored all of it.
+-- TRUE = the remainder was never uploaded and cannot be recovered.
+--
+-- Backfilling NULL to FALSE would assert completeness the data cannot support,
+-- which is the specific claim the truncation indicator exists to stop making.
+ALTER TABLE task_message ADD COLUMN IF NOT EXISTS output_truncated BOOLEAN;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 9ac8f01a1d..b15e113619 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1311,15 +1311,16 @@ type SysCronExecution struct {
}
type TaskMessage struct {
- ID pgtype.UUID `json:"id"`
- TaskID pgtype.UUID `json:"task_id"`
- Seq int32 `json:"seq"`
- Type string `json:"type"`
- Tool pgtype.Text `json:"tool"`
- Content pgtype.Text `json:"content"`
- Input []byte `json:"input"`
- Output pgtype.Text `json:"output"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ID pgtype.UUID `json:"id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Seq int32 `json:"seq"`
+ Type string `json:"type"`
+ Tool pgtype.Text `json:"tool"`
+ Content pgtype.Text `json:"content"`
+ Input []byte `json:"input"`
+ Output pgtype.Text `json:"output"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ OutputTruncated pgtype.Bool `json:"output_truncated"`
}
type TaskToken struct {
diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.go
index 89ce8c3053..ebda00d929 100644
--- a/server/pkg/db/generated/task_message.sql.go
+++ b/server/pkg/db/generated/task_message.sql.go
@@ -12,20 +12,21 @@ import (
)
const createTaskMessage = `-- name: CreateTaskMessage :one
-INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)
-VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
-RETURNING id, task_id, seq, type, tool, content, input, output, created_at
+INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
+RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated
`
type CreateTaskMessageParams struct {
- ID pgtype.UUID `json:"id"`
- TaskID pgtype.UUID `json:"task_id"`
- Seq int32 `json:"seq"`
- Type string `json:"type"`
- Tool pgtype.Text `json:"tool"`
- Content pgtype.Text `json:"content"`
- Input []byte `json:"input"`
- Output pgtype.Text `json:"output"`
+ ID pgtype.UUID `json:"id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Seq int32 `json:"seq"`
+ Type string `json:"type"`
+ Tool pgtype.Text `json:"tool"`
+ Content pgtype.Text `json:"content"`
+ Input []byte `json:"input"`
+ Output pgtype.Text `json:"output"`
+ OutputTruncated pgtype.Bool `json:"output_truncated"`
}
func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessageParams) (TaskMessage, error) {
@@ -38,6 +39,7 @@ func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessagePa
arg.Content,
arg.Input,
arg.Output,
+ arg.OutputTruncated,
)
var i TaskMessage
err := row.Scan(
@@ -50,6 +52,7 @@ func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessagePa
&i.Input,
&i.Output,
&i.CreatedAt,
+ &i.OutputTruncated,
)
return i, err
}
@@ -68,45 +71,49 @@ WITH incoming AS (
unnest($4::text[]) AS tool,
unnest($5::text[]) AS content,
unnest($6::text[]) AS input,
- unnest($7::text[]) AS output
+ unnest($7::text[]) AS output,
+ unnest($8::text[]) AS output_truncated
), inserted AS (
- INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)
+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated)
SELECT
m.id,
- $8::uuid,
+ $9::uuid,
m.seq,
m.type,
NULLIF(m.tool, ''),
NULLIF(m.content, ''),
NULLIF(m.input, '')::jsonb,
- NULLIF(m.output, '')
+ NULLIF(m.output, ''),
+ NULLIF(m.output_truncated, '')::bool
FROM incoming AS m
- RETURNING id, task_id, seq, type, tool, content, input, output, created_at
+ RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated
)
-SELECT id, task_id, seq, type, tool, content, input, output, created_at FROM inserted ORDER BY seq ASC
+SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated FROM inserted ORDER BY seq ASC
`
type CreateTaskMessagesParams struct {
- Ids []pgtype.UUID `json:"ids"`
- Seqs []int32 `json:"seqs"`
- Types []string `json:"types"`
- Tools []string `json:"tools"`
- Contents []string `json:"contents"`
- Inputs []string `json:"inputs"`
- Outputs []string `json:"outputs"`
- TaskID pgtype.UUID `json:"task_id"`
+ Ids []pgtype.UUID `json:"ids"`
+ Seqs []int32 `json:"seqs"`
+ Types []string `json:"types"`
+ Tools []string `json:"tools"`
+ Contents []string `json:"contents"`
+ Inputs []string `json:"inputs"`
+ Outputs []string `json:"outputs"`
+ OutputTruncations []string `json:"output_truncations"`
+ TaskID pgtype.UUID `json:"task_id"`
}
type CreateTaskMessagesRow struct {
- ID pgtype.UUID `json:"id"`
- TaskID pgtype.UUID `json:"task_id"`
- Seq int32 `json:"seq"`
- Type string `json:"type"`
- Tool pgtype.Text `json:"tool"`
- Content pgtype.Text `json:"content"`
- Input []byte `json:"input"`
- Output pgtype.Text `json:"output"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ID pgtype.UUID `json:"id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Seq int32 `json:"seq"`
+ Type string `json:"type"`
+ Tool pgtype.Text `json:"tool"`
+ Content pgtype.Text `json:"content"`
+ Input []byte `json:"input"`
+ Output pgtype.Text `json:"output"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ OutputTruncated pgtype.Bool `json:"output_truncated"`
}
// Batch variant of CreateTaskMessage: persists a whole daemon-reported batch in
@@ -129,7 +136,10 @@ type CreateTaskMessagesRow struct {
// `pgtype.Text{Valid: x != ""}` mapping the single-row query carries — empty
// string means SQL NULL. input is passed as text and cast here for the same
// reason; it is the one column that genuinely has to be parsed as JSON, because
-// it is a jsonb column.
+// it is a jsonb column. output_truncated rides the same trick for the same
+// reason: it is a genuinely tri-state boolean (NULL = the reporting daemon did
+// not measure it), and a bool[] parameter becomes a Go []bool, which has no way
+// to spell the third state.
//
// Callers MUST still run the Postgres text sanitizer first. A NUL anywhere in
// the batch fails the whole statement (GH #7098) — that is inherent to batching
@@ -157,6 +167,7 @@ func (q *Queries) CreateTaskMessages(ctx context.Context, arg CreateTaskMessages
arg.Contents,
arg.Inputs,
arg.Outputs,
+ arg.OutputTruncations,
arg.TaskID,
)
if err != nil {
@@ -176,6 +187,7 @@ func (q *Queries) CreateTaskMessages(ctx context.Context, arg CreateTaskMessages
&i.Input,
&i.Output,
&i.CreatedAt,
+ &i.OutputTruncated,
); err != nil {
return nil, err
}
@@ -198,7 +210,7 @@ func (q *Queries) DeleteTaskMessages(ctx context.Context, taskID pgtype.UUID) er
}
const listTaskMessages = `-- name: ListTaskMessages :many
-SELECT id, task_id, seq, type, tool, content, input, output, created_at FROM task_message
+SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated FROM task_message
WHERE task_id = $1
ORDER BY seq ASC
`
@@ -222,6 +234,7 @@ func (q *Queries) ListTaskMessages(ctx context.Context, taskID pgtype.UUID) ([]T
&i.Input,
&i.Output,
&i.CreatedAt,
+ &i.OutputTruncated,
); err != nil {
return nil, err
}
@@ -234,7 +247,7 @@ func (q *Queries) ListTaskMessages(ctx context.Context, taskID pgtype.UUID) ([]T
}
const listTaskMessagesSince = `-- name: ListTaskMessagesSince :many
-SELECT id, task_id, seq, type, tool, content, input, output, created_at FROM task_message
+SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated FROM task_message
WHERE task_id = $1 AND seq > $2
ORDER BY seq ASC
`
@@ -263,6 +276,7 @@ func (q *Queries) ListTaskMessagesSince(ctx context.Context, arg ListTaskMessage
&i.Input,
&i.Output,
&i.CreatedAt,
+ &i.OutputTruncated,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sql
index b664c2ac91..58c2f284ce 100644
--- a/server/pkg/db/queries/task_message.sql
+++ b/server/pkg/db/queries/task_message.sql
@@ -1,6 +1,6 @@
-- name: CreateTaskMessage :one
-INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)
-VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *;
-- name: CreateTaskMessages :many
@@ -24,7 +24,10 @@ RETURNING *;
-- `pgtype.Text{Valid: x != ""}` mapping the single-row query carries — empty
-- string means SQL NULL. input is passed as text and cast here for the same
-- reason; it is the one column that genuinely has to be parsed as JSON, because
--- it is a jsonb column.
+-- it is a jsonb column. output_truncated rides the same trick for the same
+-- reason: it is a genuinely tri-state boolean (NULL = the reporting daemon did
+-- not measure it), and a bool[] parameter becomes a Go []bool, which has no way
+-- to spell the third state.
--
-- Callers MUST still run the Postgres text sanitizer first. A NUL anywhere in
-- the batch fails the whole statement (GH #7098) — that is inherent to batching
@@ -56,9 +59,10 @@ WITH incoming AS (
unnest(sqlc.arg('tools')::text[]) AS tool,
unnest(sqlc.arg('contents')::text[]) AS content,
unnest(sqlc.arg('inputs')::text[]) AS input,
- unnest(sqlc.arg('outputs')::text[]) AS output
+ unnest(sqlc.arg('outputs')::text[]) AS output,
+ unnest(sqlc.arg('output_truncations')::text[]) AS output_truncated
), inserted AS (
- INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)
+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated)
SELECT
m.id,
sqlc.arg('task_id')::uuid,
@@ -67,7 +71,8 @@ WITH incoming AS (
NULLIF(m.tool, ''),
NULLIF(m.content, ''),
NULLIF(m.input, '')::jsonb,
- NULLIF(m.output, '')
+ NULLIF(m.output, ''),
+ NULLIF(m.output_truncated, '')::bool
FROM incoming AS m
RETURNING *
)
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index e2947f0495..fdafeb8c58 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -186,15 +186,20 @@ type ChatQuickActionsPayload struct {
// TaskMessagePayload represents a single agent execution message (tool call, text, etc.)
type TaskMessagePayload struct {
- TaskID string `json:"task_id"`
- IssueID string `json:"issue_id,omitempty"`
- Seq int `json:"seq"`
- Type string `json:"type"` // "text", "tool_use", "tool_result", "error"
- Tool string `json:"tool,omitempty"` // tool name for tool_use/tool_result
- Content string `json:"content,omitempty"` // text content
- Input map[string]any `json:"input,omitempty"` // tool input (tool_use only)
- Output string `json:"output,omitempty"` // tool output (tool_result only)
- CreatedAt string `json:"created_at,omitempty"`
+ TaskID string `json:"task_id"`
+ IssueID string `json:"issue_id,omitempty"`
+ Seq int `json:"seq"`
+ Type string `json:"type"` // "text", "tool_use", "tool_result", "error"
+ Tool string `json:"tool,omitempty"` // tool name for tool_use/tool_result
+ Content string `json:"content,omitempty"` // text content
+ Input map[string]any `json:"input,omitempty"` // tool input (tool_use only)
+ Output string `json:"output,omitempty"` // tool output (tool_result only)
+ // OutputTruncated reports whether Output is the whole tool output that ran
+ // (tool_result only). Tri-state: omitted means no daemon ever measured this
+ // record — historical rows and older installed daemons — which clients must
+ // present as unknown rather than as complete.
+ OutputTruncated *bool `json:"output_truncated,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
}
// DaemonRegisterPayload is sent from daemon to server on connection.