Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(transcript): pair parallel tool results by call identity (#8567)
importcpp67cec3fe3f69
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 9389031374..62163e9954 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -2208,6 +2208,23 @@ describe("issue status catalog schemas", () => {});describe("TaskMessageListSchema", () => {+ it("preserves call IDs and tolerates old or malformed optional identity", () => {+ const base = { task_id: "task-1", seq: 1, type: "tool_result", output: "ok" };+ const parsed = parseWithFallback<{ call_id?: string; output?: string }[]>(+ [+ { ...base, call_id: "execution:A" },+ base,+ { ...base, call_id: null },+ { ...base, call_id: 42 },+ { ...base, call_id: {} },+ ],+ TaskMessageListSchema, [], { endpoint: "GET /api/tasks/:id/messages" },+ );+ expect(parsed).toHaveLength(5);+ expect(parsed.map((m) => m.call_id)).toEqual(["execution:A", undefined, undefined, undefined, undefined]);+ expect(parsed.every((m) => m.output === "ok")).toBe(true);+ });+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 sayingdiff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 45ed09157a..a1c8b3d130 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1864,6 +1864,7 @@ export const AgentTaskListSchema = z.array(AgentTaskSchema);// 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({+ call_id: z.string().optional().catch(undefined),task_id: z.string().default(""),issue_id: z.string().default(""),chat_session_id: z.string().optional(),diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex efc79dc1e8..db0563c892 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -285,6 +285,8 @@ export interface ActivityCreatedPayload {}export interface TaskMessagePayload {+ /** Opaque tool-call identity, scoped to one backend execution. */+ call_id?: string;task_id: string;issue_id: string;chat_session_id?: string;diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsxindex 827a2d123c..b00548e8e1 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx@@ -249,6 +249,27 @@ afterEach(() => {});describe("AgentTranscriptDialog", () => {+ it("opens the matching result and duration for parallel same-tool calls", () => {+ const at = (seconds: number) =>+ new Date(Date.parse(baseTask.started_at!) + seconds * 1000).toISOString();+ renderDialog([+ { seq: 1, type: "tool_use", tool: "Bash", callId: "A", input: { command: "slow-A" }, created_at: at(0) },+ { seq: 2, type: "tool_use", tool: "Bash", callId: "B", input: { command: "fast-B" }, created_at: at(1) },+ { seq: 3, type: "tool_result", tool: "Bash", callId: "B", output: "B finished", created_at: at(3) },+ { seq: 4, type: "tool_result", tool: "Bash", callId: "A", output: "A finished", created_at: at(10) },+ ]);+ const slow = screen.getByRole("button", { name: /slow-A/ });+ const fast = screen.getByRole("button", { name: /fast-B/ });+ expect(slow).toHaveTextContent("10s");+ expect(fast).toHaveTextContent("2.0s");+ fireEvent.click(slow);+ expect(screen.getByText("A finished", { selector: "pre" })).toBeInTheDocument();+ expect(screen.queryByText("B finished", { selector: "pre" })).not.toBeInTheDocument();+ fireEvent.click(fast);+ expect(screen.getByText("B finished", { selector: "pre" })).toBeInTheDocument();+ expect(screen.queryByText("A finished", { selector: "pre" })).not.toBeInTheDocument();+ });+it("explains unavailable live events for an empty Antigravity transcript", async () => {vi.mocked(api.listRuntimes).mockResolvedValue([runtimeFor("antigravity")]);diff --git a/packages/views/common/task-transcript/build-steps.test.ts b/packages/views/common/task-transcript/build-steps.test.tsindex e586d2efd8..f4377b4dd9 100644--- a/packages/views/common/task-transcript/build-steps.test.ts+++ b/packages/views/common/task-transcript/build-steps.test.ts@@ -10,7 +10,7 @@ import {toolKindTotals,type TraceCallStep,} from "./build-steps";-import type { TimelineItem } from "./build-timeline";+import { buildTimeline, type TimelineItem } from "./build-timeline";const T0 = "2026-08-15T10:00:00.000Z";function at(seconds: number): string {@@ -29,6 +29,28 @@ function text(seconds: number, content = "done"): TimelineItem {}describe("buildSteps", () => {+ it("pairs parallel same-tool results by call ID after timeline projection", () => {+ const messages = [+ { ...call("Bash", 0, { command: "slow-A" }), call_id: "attempt-1:A" },+ { ...call("Bash", 1, { command: "fast-B" }), call_id: "attempt-1:B" },+ { ...result("Bash", 3, "B finished"), call_id: "attempt-1:B" },+ { ...result("Bash", 10, "A finished"), call_id: "attempt-1:A" },+ ].map((item) => ({ ...item, task_id: "task-1", issue_id: "issue-1" }));+ // Live snapshots and a fresh history response must use the same pairing.+ for (const rows of [messages.slice(0, 3), messages, structuredClone(messages)]) {+ const steps = buildSteps(buildTimeline(rows)) as TraceCallStep[];+ expect(steps).toHaveLength(2);+ expect(steps[1]!.result?.output).toBe("B finished");+ expect(steps[1]!.durationMs).toBe(2000);+ if (rows.length === 4) {+ expect(steps[0]!.result?.output).toBe("A finished");+ expect(steps[0]!.durationMs).toBe(10000);+ } else {+ expect(steps[0]!.result).toBeUndefined();+ }+ }+ });+it("folds a call and its result into one step", () => {const steps = buildSteps([call("Bash", 0), result("Bash", 4)]);@@ -57,6 +79,55 @@ describe("buildSteps", () => {expect(steps[1]!.result?.output).toBe("second done");});+ it("uses identity when a result omits its tool name", () => {+ const steps = buildSteps([+ { ...call("Bash", 0), callId: "A" },+ { ...result("", 2), callId: "A" },+ ]) as TraceCallStep[];+ expect(steps).toHaveLength(1);+ expect(steps[0]!.tool).toBe("Bash");+ expect(steps[0]!.durationMs).toBe(2000);+ });++ it("keeps unmatched identified results separate from other IDs and legacy calls", () => {+ const steps = buildSteps([+ { ...call("Bash", 0), callId: "previous:A" },+ call("Bash", 1),+ { ...result("Bash", 2, "orphan"), callId: "retry:A" },+ result("Bash", 3, "legacy"),+ { ...result("Bash", 4, "previous"), callId: "previous:A" },+ ]) as TraceCallStep[];+ expect(steps).toHaveLength(3);+ expect(steps[0]!.result?.output).toBe("previous");+ expect(steps[1]!.result?.output).toBe("legacy");+ expect(steps[2]!.call).toBeUndefined();+ expect(steps[2]!.result?.output).toBe("orphan");+ expect(steps[2]!.durationMs).toBeUndefined();+ });++ it("does not attach a result without identity to an identified call", () => {+ const steps = buildSteps([+ { ...call("Bash", 0), callId: "A" },+ result("Bash", 1),+ ]) as TraceCallStep[];+ expect(steps).toHaveLength(2);+ expect(steps[0]!.result).toBeUndefined();+ expect(steps[1]!.call).toBeUndefined();+ });++ it("keeps duplicate results as orphans once their identified call is closed", () => {+ const steps = buildSteps([+ { ...call("Bash", 0), callId: "A" },+ { ...call("Bash", 1), callId: "B" },+ { ...result("Bash", 2), callId: "A" },+ { ...result("Bash", 3), callId: "A" },+ ]) as TraceCallStep[];+ expect(steps).toHaveLength(3);+ expect(steps[0]!.durationMs).toBe(2000);+ expect(steps[1]!.result).toBeUndefined();+ expect(steps[2]!.call).toBeUndefined();+ });+it("does not pair across different tools", () => {const steps = buildSteps([call("Read", 0), result("Bash", 1)]) as TraceCallStep[];@@ -95,6 +166,24 @@ describe("buildSteps", () => {});describe("groupSteps", () => {+ it("spans until the last completion when parallel calls finish out of order", () => {+ const items = [+ { ...call("Read", 0), callId: "A" },+ { ...call("Read", 1), callId: "B" },+ { ...call("Read", 2), callId: "C" },+ { ...result("Read", 3), callId: "B" },+ { ...result("Read", 4), callId: "C" },+ { ...result("Read", 10), callId: "A" },+ ];+ const [group] = groupSteps(buildSteps(items));+ expect(group?.kind).toBe("group");+ if (group?.kind !== "group") throw new Error("expected a group");+ expect(group.endedAt).toBe(at(10));+ expect(group.durationMs).toBe(10000);+ const [pending] = groupSteps(buildSteps(items.slice(0, -1)));+ expect(pending?.kind === "group" && pending.durationMs).toBeUndefined();+ });+it("folds three or more consecutive same-tool calls", () => {const steps = buildSteps([call("Read", 0),diff --git a/packages/views/common/task-transcript/build-steps.ts b/packages/views/common/task-transcript/build-steps.tsindex 683a18b4ef..b6f1c831b7 100644--- a/packages/views/common/task-transcript/build-steps.ts+++ b/packages/views/common/task-transcript/build-steps.ts@@ -10,10 +10,9 @@ import type { TimelineItem } from "./build-timeline";* the pair back together, so one call reads as one line and its result is that* line's detail.*- * Pairing is positional because the events carry no call id. `agent.Message`- * has `CallID` all the way to the daemon, but `TaskMessageData` drops it before- * the report and `task_message` has no column for it — until that lands, a- * result belongs to the oldest still-open call with the same tool name.+ * Identified events pair by their opaque call ID, regardless of completion+ * order or tool name. Only events without identity use the legacy tool-name+ * FIFO; mixing the two would attach orphan results to unrelated calls.*//** One tool call. Either side can be missing: a call still running has no@@ -95,12 +94,12 @@ function durationBetween(start?: string, end?: string): number | undefined {/** Fold `tool_use` / `tool_result` pairs into single steps, in stream order. */export function buildSteps(items: TimelineItem[]): TraceStep[] {const steps: TraceStep[] = [];- // Open calls per tool, oldest first. FIFO rather than nearest-preceding:- // when a provider runs two calls of the same tool in parallel it returns- // them in call order more often than in reverse.+ // Separate ID and tool-name keys so a missing/unmatched ID never consumes+ // an identified call through the legacy fallback (or vice versa).const open = new Map<string, TraceCallStep[]>();for (const item of items) {+ const pairingKey = item.callId ? `id:${item.callId}` : `tool:${item.tool ?? ""}`;if (item.type === "tool_use") {const tool = item.tool ?? "";const step: TraceCallStep = {@@ -111,15 +110,15 @@ export function buildSteps(items: TimelineItem[]): TraceStep[] {startedAt: item.created_at,};steps.push(step);- const queue = open.get(tool);+ const queue = open.get(pairingKey);if (queue) queue.push(step);- else open.set(tool, [step]);+ else open.set(pairingKey, [step]);continue;}if (item.type === "tool_result") {const tool = item.tool ?? "";- const pending = open.get(tool)?.shift();+ const pending = open.get(pairingKey)?.shift();if (pending) {pending.result = item;pending.endedAt = item.created_at;@@ -160,15 +159,21 @@ export function groupSteps(steps: TraceStep[]): TraceRow[] {rows.push(...run);} else {const first = run[0]!;- const last = run[run.length - 1]!;+ // Call order no longer implies completion order. Do not display a+ // completed span while any member still lacks its end timestamp.+ const endedAt = run.every((step) => timeMs(step.endedAt) !== undefined)+ ? run.reduce((latest, step) =>+ timeMs(step.endedAt)! > timeMs(latest)! ? step.endedAt : latest,+ first.endedAt)+ : undefined;rows.push({kind: "group",seq: first.seq,tool: first.tool,steps: run,startedAt: first.startedAt,- endedAt: last.endedAt,- durationMs: durationBetween(first.startedAt, last.endedAt),+ endedAt,+ durationMs: durationBetween(first.startedAt, endedAt),});}run = [];diff --git a/packages/views/common/task-transcript/build-timeline.ts b/packages/views/common/task-transcript/build-timeline.tsindex 8a8085fdb4..9f70158720 100644--- a/packages/views/common/task-transcript/build-timeline.ts+++ b/packages/views/common/task-transcript/build-timeline.ts@@ -6,6 +6,8 @@ export interface TimelineItem {seq: number;type: "tool_use" | "tool_result" | "thinking" | "text" | "error";tool?: string;+ /** Opaque identity for pairing tool events within a backend execution. */+ callId?: string;content?: string;input?: Record<string, unknown>;output?: string;@@ -112,6 +114,7 @@ function mergeRun(run: readonly TaskMessagePayload[]): TimelineItem {seq: first.seq,type: first.type,tool: first.tool,+ callId: first.call_id,content,input: first.input,output: first.output,diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 274389c30e..6b290e411d 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -509,6 +509,8 @@ func (c *Client) ReportProgress(ctx context.Context, taskID, summary string, ste// TaskMessageData represents a single agent execution message for batch reporting.type TaskMessageData struct {+ // CallID is an opaque tool-call identity scoped to one backend execution.+ CallID string `json:"call_id,omitempty"`Seq int `json:"seq"`Type string `json:"type"`Tool string `json:"tool,omitempty"`diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex bf6f88bf71..69b0251bed 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -22,6 +22,8 @@ import ("sync/atomic""time"+ "github.com/google/uuid"+"golang.org/x/sync/errgroup""golang.org/x/sync/singleflight"@@ -9359,6 +9361,21 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, provar pendingAt time.Timevar batch []TaskMessageDatacallIDToTool := map[string]string{}+ // Provider IDs can restart on a same-task retry (for example item_0).+ // Allocate opaque transcript IDs per execution, including orphan results,+ // so neither a retry nor a missing call can steal another call's result.+ transcriptCallIDs := map[string]string{}+ transcriptCallID := func(providerID string) string {+ if providerID == "" {+ return ""+ }+ if id, ok := transcriptCallIDs[providerID]; ok {+ return id+ }+ id := uuid.NewString()+ transcriptCallIDs[providerID] = id+ return id+ }// sealPendingLocked turns the current contiguous text/thinking frame// into a sequenced row. Callers hold mu so a ticker flush cannot assign@@ -9511,6 +9528,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, probatch = append(batch, TaskMessageData{Seq: int(s),Type: "tool_use",+ CallID: transcriptCallID(msg.CallID),Tool: msg.Tool,CreatedAt: observedAt,// Redact before the payload leaves this process, not@@ -9553,6 +9571,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, probatch = append(batch, TaskMessageData{Seq: int(s),Type: "tool_result",+ CallID: transcriptCallID(msg.CallID),Tool: toolName,Output: output,CreatedAt: observedAt,diff --git a/server/internal/daemon/task_message_call_id_test.go b/server/internal/daemon/task_message_call_id_test.gonew file mode 100644index 0000000000..4b3780b485--- /dev/null+++ b/server/internal/daemon/task_message_call_id_test.go@@ -0,0 +1,72 @@+package daemon++import (+ "context"+ "encoding/json"+ "log/slog"+ "slices"+ "sync/atomic"+ "testing"++ "github.com/multica-ai/multica/server/pkg/agent"+)++func TestExecuteAndDrain_ScopesToolCallIdentity(t *testing.T) {+ t.Parallel()+ d, rec := newTranscriptRecorder(t)+ var seq atomic.Int32+ // Both executions reuse provider IDs. The unfinished call in the first+ // attempt must never capture a result from the retry.+ for attempt := 0; attempt < 2; attempt++ {+ messages := make(chan agent.Message, 7)+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "Bash", CallID: "A"}+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "Bash", CallID: "B"}+ messages <- agent.Message{Type: agent.MessageToolResult, CallID: "B", Output: "B finished"}+ messages <- agent.Message{Type: agent.MessageToolResult, CallID: "A", Output: "A finished"}+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "Bash", CallID: "unfinished"}+ messages <- agent.Message{Type: agent.MessageToolResult, Tool: "Bash", CallID: "orphan"}+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "Read"}+ close(messages)+ results := make(chan agent.Result, 1)+ results <- agent.Result{Status: "completed"}+ close(results)+ backend := sessionBackend{session: &agent.Session{Messages: messages, Result: results}}+ if _, _, err := d.executeAndDrain(context.Background(), backend, "p", agent.ExecOptions{},+ slog.Default(), "task-call-id", "", &seq); err != nil {+ t.Fatal(err)+ }+ }+ reported := rec.snapshot()+ slices.SortFunc(reported, func(a, b TaskMessageData) int { return a.Seq - b.Seq })+ wire, err := json.Marshal(reported)+ if err != nil {+ t.Fatal(err)+ }+ var rows []map[string]any+ if err := json.Unmarshal(wire, &rows); err != nil {+ t.Fatal(err)+ }+ if len(rows) != 14 {+ t.Fatalf("got %d messages, want 14", len(rows))+ }+ seen := map[string]bool{}+ for attempt := 0; attempt < 2; attempt++ {+ batch := rows[attempt*7 : (attempt+1)*7]+ for _, i := range []int{0, 1, 4, 5} {+ id, _ := batch[i]["call_id"].(string)+ if id == "" || seen[id] {+ t.Fatalf("missing or reused call identity at attempt %d row %d: %q", attempt, i, id)+ }+ seen[id] = true+ }+ if batch[0]["call_id"] != batch[3]["call_id"] || batch[1]["call_id"] != batch[2]["call_id"] {+ t.Fatalf("out-of-order results lost their call identity: %+v", batch)+ }+ if batch[2]["tool"] != "Bash" || batch[3]["tool"] != "Bash" {+ t.Fatal("tool name resolution changed")+ }+ if _, ok := batch[6]["call_id"]; ok {+ t.Fatal("must not invent an identity when the provider supplies none")+ }+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex b5defe43b6..96d40d75fe 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -5003,6 +5003,8 @@ func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, works// ---------------------------------------------------------------------------type TaskMessageRequest struct {+ // CallID is an opaque tool-call identity scoped to one backend execution.+ CallID string `json:"call_id,omitempty"`Seq int `json:"seq"`Type string `json:"type"`Tool string `json:"tool,omitempty"`@@ -5070,6 +5072,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {Seqs: make([]int32, 0, n),Types: make([]string, 0, n),Tools: make([]string, 0, n),+ CallIds: make([]string, 0, n),Contents: make([]string, 0, n),Inputs: make([]string, 0, n),Outputs: make([]string, 0, n),@@ -5106,6 +5109,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {// than a single row, which is inherent to one-statement writes.msg.Type = util.SanitizeTextForPostgres(msg.Type)msg.Tool = util.SanitizeTextForPostgres(msg.Tool)+ msg.CallID = util.SanitizeTextForPostgres(msg.CallID)msg.Content = util.SanitizeTextForPostgres(msg.Content)msg.Output = util.SanitizeTextForPostgres(msg.Output)if msg.Input != nil {@@ -5133,6 +5137,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {params.Seqs = append(params.Seqs, int32(msg.Seq))params.Types = append(params.Types, msg.Type)params.Tools = append(params.Tools, msg.Tool)+ params.CallIds = append(params.CallIds, msg.CallID)params.Contents = append(params.Contents, msg.Content)params.Inputs = append(params.Inputs, inputJSON)params.Outputs = append(params.Outputs, msg.Output)@@ -5282,6 +5287,7 @@ func taskMessageToPayload(m db.TaskMessage, taskID, issueID string) protocol.TasSeq: int(m.Seq),Type: m.Type,Tool: m.Tool.String,+ CallID: m.CallID.String,Content: m.Content.String,Input: input,Output: m.Output.String,diff --git a/server/internal/handler/task_message_call_id_test.go b/server/internal/handler/task_message_call_id_test.gonew file mode 100644index 0000000000..e70d18a62b--- /dev/null+++ b/server/internal/handler/task_message_call_id_test.go@@ -0,0 +1,105 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "reflect"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestTaskMessageCallIDLiveAndHistory(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ taskID := seedBatchTask(t, "call-id")+ h := *testHandler+ h.Bus = events.New()+ var live []map[string]any+ h.Bus.Subscribe(protocol.EventTaskMessage, func(e events.Event) {+ if e.TaskID != taskID {+ return+ }+ data, err := json.Marshal(e.Payload)+ if err != nil {+ t.Error(err)+ return+ }+ var row map[string]any+ if err := json.Unmarshal(data, &row); err != nil {+ t.Error(err)+ return+ }+ live = append(live, row)+ })+ testutil.Call(t, h.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{+ map[string]any{"seq": 1, "type": "tool_use", "tool": "Bash", "call_id": "attempt:A"},+ map[string]any{"seq": 2, "type": "tool_use", "tool": "Bash", "call_id": "attempt:B"},+ map[string]any{"seq": 3, "type": "tool_result", "tool": "Bash", "call_id": "attempt:B", "output": "B finished"},+ map[string]any{"seq": 4, "type": "tool_result", "tool": "Bash", "call_id": "attempt:A", "output": "A finished"},+ map[string]any{"seq": 5, "type": "tool_use", "tool": "Read"},+ })).Want(http.StatusOK)+ if len(live) != 5 {+ t.Fatalf("got %d live events, want 5", len(live))+ }+ for i, want := range []string{"attempt:A", "attempt:B", "attempt:B", "attempt:A"} {+ if live[i]["call_id"] != want {+ t.Errorf("live row %d call_id = %v, want %s", i, live[i]["call_id"], want)+ }+ }+ if _, ok := live[4]["call_id"]; ok {+ t.Error("legacy message must omit call_id")+ }+ var legacyNull bool+ dbfx.QueryRow(t, `SELECT call_id IS NULL FROM task_message WHERE task_id=$1 AND seq=5`, taskID).Scan(&legacyNull)+ if !legacyNull {+ t.Error("missing call_id must persist as NULL")+ }++ // Both readers and incremental reconnects must agree with the live payload.+ for _, reader := range []struct {+ name string+ handler http.HandlerFunc+ }{+ {"daemon", h.ListTaskMessages}, {"user", h.ListTaskMessagesByUser},+ } {+ for _, suffix := range []string{"", "?since=2"} {+ t.Run(reader.name+suffix, func(t *testing.T) {+ req := testutil.JSONRequest(http.MethodGet, "/api/tasks/"+taskID+"/messages"+suffix, nil)+ req = testutil.WithURLParams(req, "taskId", taskID)+ ctx := middleware.WithDaemonContext(req.Context(), testWorkspaceID, "call-id-daemon")+ ctx = middleware.SetMemberContext(ctx, testWorkspaceID, db.Member{})+ var history []map[string]any+ testutil.Call(t, reader.handler, req.WithContext(ctx)).Want(http.StatusOK).JSON(&history)+ want := live+ if suffix != "" {+ want = live[2:]+ }+ if !reflect.DeepEqual(history, want) {+ t.Fatalf("history differs from live: got %+v want %+v", history, want)+ }+ })+ }+ }+ // The single-row writer is also used outside daemon batch ingestion.+ row, err := h.Queries.CreateTaskMessage(context.Background(), db.CreateTaskMessageParams{+ ID: pgtype.UUID{Bytes: uuid.Must(uuid.NewV7()), Valid: true},+ TaskID: util.MustParseUUID(taskID), Seq: 6, Type: "tool_result",+ CallID: pgtype.Text{String: "single-call", Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ if row.CallID.String != "single-call" {+ t.Fatalf("single writer lost call_id: %+v", row)+ }+}diff --git a/server/migrations/500_task_message_call_id.down.sql b/server/migrations/500_task_message_call_id.down.sqlnew file mode 100644index 0000000000..83293caa4f--- /dev/null+++ b/server/migrations/500_task_message_call_id.down.sql@@ -0,0 +1 @@+ALTER TABLE task_message DROP COLUMN call_id;diff --git a/server/migrations/500_task_message_call_id.up.sql b/server/migrations/500_task_message_call_id.up.sqlnew file mode 100644index 0000000000..31acbd0d7b--- /dev/null+++ b/server/migrations/500_task_message_call_id.up.sql@@ -0,0 +1 @@+ALTER TABLE task_message ADD COLUMN call_id TEXT;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex ba39ca3603..e68f17864d 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1363,6 +1363,7 @@ type TaskMessage struct {Output pgtype.Text `json:"output"`CreatedAt pgtype.Timestamptz `json:"created_at"`OutputTruncated pgtype.Bool `json:"output_truncated"`+ CallID pgtype.Text `json:"call_id"`}type TaskToken struct {diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.goindex 03e6c4d0ab..a0c7dac254 100644--- a/server/pkg/db/generated/task_message.sql.go+++ b/server/pkg/db/generated/task_message.sql.go@@ -12,9 +12,9 @@ import ()const createTaskMessage = `-- name: CreateTaskMessage :one-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+INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated, call_id)+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id`type CreateTaskMessageParams struct {@@ -27,6 +27,7 @@ type CreateTaskMessageParams struct {Input []byte `json:"input"`Output pgtype.Text `json:"output"`OutputTruncated pgtype.Bool `json:"output_truncated"`+ CallID pgtype.Text `json:"call_id"`}func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessageParams) (TaskMessage, error) {@@ -40,6 +41,7 @@ func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessagePaarg.Input,arg.Output,arg.OutputTruncated,+ arg.CallID,)var i TaskMessageerr := row.Scan(@@ -53,6 +55,7 @@ func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessagePa&i.Output,&i.CreatedAt,&i.OutputTruncated,+ &i.CallID,)return i, err}@@ -69,16 +72,17 @@ WITH incoming AS (unnest($2::int4[]) AS seq,unnest($3::text[]) AS type,unnest($4::text[]) AS tool,- unnest($5::text[]) AS content,- unnest($6::text[]) AS input,- unnest($7::text[]) AS output,- unnest($8::text[]) AS created_at,- unnest($9::text[]) AS output_truncated+ unnest($5::text[]) AS call_id,+ unnest($6::text[]) AS content,+ unnest($7::text[]) AS input,+ unnest($8::text[]) AS output,+ unnest($9::text[]) AS created_at,+ unnest($10::text[]) AS output_truncated), inserted AS (- INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, created_at, output_truncated)+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id)SELECTm.id,- $10::uuid,+ $11::uuid,m.seq,m.type,NULLIF(m.tool, ''),@@ -86,11 +90,12 @@ WITH incoming AS (NULLIF(m.input, '')::jsonb,NULLIF(m.output, ''),COALESCE(NULLIF(m.created_at, '')::timestamptz, now()),- NULLIF(m.output_truncated, '')::bool+ NULLIF(m.output_truncated, '')::bool,+ NULLIF(m.call_id, '')FROM incoming AS m- RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated+ RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id)-SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated FROM inserted ORDER BY seq ASC+SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id FROM inserted ORDER BY seq ASC`type CreateTaskMessagesParams struct {@@ -98,6 +103,7 @@ type CreateTaskMessagesParams struct {Seqs []int32 `json:"seqs"`Types []string `json:"types"`Tools []string `json:"tools"`+ CallIds []string `json:"call_ids"`Contents []string `json:"contents"`Inputs []string `json:"inputs"`Outputs []string `json:"outputs"`@@ -117,6 +123,7 @@ type CreateTaskMessagesRow struct {Output pgtype.Text `json:"output"`CreatedAt pgtype.Timestamptz `json:"created_at"`OutputTruncated pgtype.Bool `json:"output_truncated"`+ CallID pgtype.Text `json:"call_id"`}// Batch variant of CreateTaskMessage: persists a whole daemon-reported batch in@@ -168,6 +175,7 @@ func (q *Queries) CreateTaskMessages(ctx context.Context, arg CreateTaskMessagesarg.Seqs,arg.Types,arg.Tools,+ arg.CallIds,arg.Contents,arg.Inputs,arg.Outputs,@@ -193,6 +201,7 @@ func (q *Queries) CreateTaskMessages(ctx context.Context, arg CreateTaskMessages&i.Output,&i.CreatedAt,&i.OutputTruncated,+ &i.CallID,); err != nil {return nil, err}@@ -215,7 +224,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, output_truncated FROM task_message+SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id FROM task_messageWHERE task_id = $1ORDER BY seq ASC`@@ -240,6 +249,7 @@ func (q *Queries) ListTaskMessages(ctx context.Context, taskID pgtype.UUID) ([]T&i.Output,&i.CreatedAt,&i.OutputTruncated,+ &i.CallID,); err != nil {return nil, err}@@ -252,7 +262,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, output_truncated FROM task_message+SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id FROM task_messageWHERE task_id = $1 AND seq > $2ORDER BY seq ASC`@@ -282,6 +292,7 @@ func (q *Queries) ListTaskMessagesSince(ctx context.Context, arg ListTaskMessage&i.Output,&i.CreatedAt,&i.OutputTruncated,+ &i.CallID,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sqlindex 18ba7042da..237c191fff 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, output_truncated)-VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated, call_id)+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)RETURNING *;-- name: CreateTaskMessages :many@@ -58,13 +58,14 @@ WITH incoming AS (unnest(sqlc.arg('seqs')::int4[]) AS seq,unnest(sqlc.arg('types')::text[]) AS type,unnest(sqlc.arg('tools')::text[]) AS tool,+ unnest(sqlc.arg('call_ids')::text[]) AS call_id,unnest(sqlc.arg('contents')::text[]) AS content,unnest(sqlc.arg('inputs')::text[]) AS input,unnest(sqlc.arg('outputs')::text[]) AS output,unnest(sqlc.arg('created_ats')::text[]) AS created_at,unnest(sqlc.arg('output_truncations')::text[]) AS output_truncated), inserted AS (- INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, created_at, output_truncated)+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id)SELECTm.id,sqlc.arg('task_id')::uuid,@@ -75,7 +76,8 @@ WITH incoming AS (NULLIF(m.input, '')::jsonb,NULLIF(m.output, ''),COALESCE(NULLIF(m.created_at, '')::timestamptz, now()),- NULLIF(m.output_truncated, '')::bool+ NULLIF(m.output_truncated, '')::bool,+ NULLIF(m.call_id, '')FROM incoming AS mRETURNING *)diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 95ea0a3ec5..664400c8c2 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -199,6 +199,8 @@ type ChatQuickActionsPayload struct {// TaskMessagePayload represents a single agent execution message (tool call, text, etc.)type TaskMessagePayload struct {+ // CallID is an opaque tool-call identity scoped to one backend execution.+ CallID string `json:"call_id,omitempty"`TaskID string `json:"task_id"`IssueID string `json:"issue_id,omitempty"`Seq int `json:"seq"`