Skip to content

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

Go

MUL-7248: fix agent log duration timestamps (#8271)

Jiayuan Zhangaac4aa3f445c
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 569b167f06..827a2d123c 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -384,6 +384,57 @@ describe("AgentTranscriptDialog", () => {
expect(screen.getByText("total 0")).toBeInTheDocument();
});
+ it("shows a meaningful bound instead of rounding a fast call to zero", () => {
+ renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Bash",
+ input: { command: "sed -n 1,20p README.md" },
+ created_at: "2026-06-08T08:00:00.000Z",
+ },
+ {
+ seq: 2,
+ type: "tool_result",
+ tool: "Bash",
+ output: "ok",
+ created_at: "2026-06-08T08:00:00.040Z",
+ },
+ ]);
+
+ expect(screen.getByText("<0.1s")).toBeInTheDocument();
+ expect(screen.queryByText("0.0s")).not.toBeInTheDocument();
+ });
+
+ it("does not claim a duration for legacy calls whose batched timestamps are identical", () => {
+ renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Bash",
+ input: { command: "pwd" },
+ created_at: "2026-06-08T08:00:00.000Z",
+ },
+ {
+ seq: 2,
+ type: "tool_result",
+ tool: "Bash",
+ output: "/repo",
+ created_at: "2026-06-08T08:00:00.000Z",
+ },
+ ]);
+
+ const unknownDuration = screen.getByText("—");
+ expect(unknownDuration).toHaveAttribute("aria-hidden", "true");
+ expect(unknownDuration.parentElement).toHaveAttribute("title", "Exact duration is unavailable.");
+ expect(unknownDuration.parentElement).not.toHaveAttribute("aria-label");
+ expect(screen.getByText("Exact duration is unavailable.")).toHaveClass("sr-only");
+ const row = screen.getByRole("button", { name: /Exact duration is unavailable\./ });
+ fireEvent.click(row);
+ expect(screen.getAllByText("Exact duration is unavailable.")).toHaveLength(2);
+ expect(screen.queryByText("0.0s")).not.toBeInTheDocument();
+ });
+
it("keeps a screenshot out of the list and renders it as an image", () => {
const output = JSON.stringify([
{ type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgo=" } },
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index f778f3801e..367bc8950b 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -153,6 +153,8 @@ function formatElapsedMs(ms: number): string {
/** A step's own duration, in the compact form the right column carries. */
function formatStepDuration(ms: number): string {
+ if (ms <= 0) return "—";
+ if (ms < 100) return "<0.1s";
if (ms < 1000) return `${(ms / 1000).toFixed(1)}s`;
if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
const minutes = Math.floor(ms / 60_000);
@@ -1419,8 +1421,28 @@ function DurationCell({ ms, pending }: { ms?: number; pending?: boolean }) {
}
if (ms === undefined) return <span className="w-12 shrink-0" />;
return (
- <span className="w-12 shrink-0 pt-0.5 text-right font-mono text-micro tabular-nums text-faint-foreground">
- {formatStepDuration(ms)}
+ <StepDuration
+ ms={ms}
+ unknownLabel={t(($) => $.transcript.step_duration_unknown)}
+ className="w-12 shrink-0 pt-0.5 text-right font-mono text-micro tabular-nums text-faint-foreground"
+ />
+ );
+}
+
+function StepDuration({
+ ms,
+ unknownLabel,
+ className,
+}: {
+ ms: number;
+ unknownLabel: string;
+ className?: string;
+}) {
+ const unknown = ms <= 0;
+ return (
+ <span className={className} title={unknown ? unknownLabel : undefined}>
+ <span aria-hidden={unknown || undefined}>{formatStepDuration(ms)}</span>
+ {unknown && <span className="sr-only">{unknownLabel}</span>}
</span>
);
}
@@ -1607,9 +1629,15 @@ function GroupRow({
<span className="truncate font-mono text-muted-foreground">
{callSummary(step, summaryLabels) || step.tool}
</span>
- <span className="ml-auto shrink-0 font-mono tabular-nums text-faint-foreground">
- {step.durationMs === undefined ? "" : formatStepDuration(step.durationMs)}
- </span>
+ {step.durationMs === undefined ? (
+ <span className="ml-auto shrink-0" />
+ ) : (
+ <StepDuration
+ ms={step.durationMs}
+ unknownLabel={t(($) => $.transcript.step_duration_unknown)}
+ className="ml-auto shrink-0 font-mono tabular-nums text-faint-foreground"
+ />
+ )}
</button>
))}
</div>
@@ -1696,7 +1724,11 @@ function StepInspector({
{call?.durationMs !== undefined && (
<>
<FactDot />
- <span className="font-mono tabular-nums">{formatStepDuration(call.durationMs)}</span>
+ <StepDuration
+ ms={call.durationMs}
+ unknownLabel={t(($) => $.transcript.step_duration_unknown)}
+ className="font-mono tabular-nums"
+ />
</>
)}
</span>
diff --git a/packages/views/common/task-transcript/build-steps.ts b/packages/views/common/task-transcript/build-steps.ts
index a59fe3a5ef..683a18b4ef 100644
--- a/packages/views/common/task-transcript/build-steps.ts
+++ b/packages/views/common/task-transcript/build-steps.ts
@@ -87,8 +87,8 @@ function durationBetween(start?: string, end?: string): number | undefined {
const a = timeMs(start);
const b = timeMs(end);
if (a === undefined || b === undefined) return undefined;
- // Clamp rather than drop: the daemon flushes in 500ms batches, so a fast
- // call can land with its result on the same tick or one tick earlier.
+ // Clamp rather than drop: a daemon wall-clock adjustment can make a result
+ // appear just before its call. Zero is preserved as "unknown" in the UI.
return Math.max(0, b - a);
}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index ec294c9b6b..319b0df76c 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -911,6 +911,7 @@
"group_calls_one": "{{count}} call",
"group_calls_other": "{{count}} calls",
"step_running": "Still running",
+ "step_duration_unknown": "Exact duration is unavailable.",
"step_input": "Input",
"step_result": "Result",
"copy_step": "Copy this step",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 629d725e2b..ab34d763ae 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -786,6 +786,7 @@
"kind_error": "エラー",
"group_calls_other": "{{count}} 回の呼び出し",
"step_running": "実行中",
+ "step_duration_unknown": "正確な所要時間は記録されていません。",
"step_input": "入力",
"step_result": "結果",
"copy_step": "このステップをコピー",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 241bc467da..2585e84f68 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -794,6 +794,7 @@
"kind_error": "오류",
"group_calls_other": "호출 {{count}}회",
"step_running": "진행 중",
+ "step_duration_unknown": "정확한 소요 시간을 확인할 수 없습니다.",
"step_input": "입력",
"step_result": "결과",
"copy_step": "이 단계 복사",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index a5d26d8a49..f55c1505ec 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -893,6 +893,7 @@
"kind_error": "错误",
"group_calls_other": "{{count}} 次调用",
"step_running": "进行中",
+ "step_duration_unknown": "无法确定准确耗时。",
"step_input": "输入",
"step_result": "结果",
"copy_step": "复制这一步",
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 36ba5052ca..3ee56d6c21 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -299,10 +299,10 @@ var concurrentIndexCleanups = map[string]string{
"445_comment_delegated_failure_unsettled_index": "idx_comment_delegated_failure_unsettled",
"446_issue_properties_bigm_index": "idx_issue_properties_bigm",
"452_agent_task_pending_thread_unique": "idx_one_pending_task_per_issue_agent_thread",
- "458_activity_log_member_assignee_frequency_index": "idx_activity_log_member_assignee_frequency",
"459_chat_message_assistant_task_index": "idx_chat_message_assistant_task",
"460_agent_task_queue_autopilot_run_created_at_index": "idx_agent_task_queue_autopilot_run_created_at",
"465_agent_task_queue_chat_with_session_index": "idx_agent_task_queue_chat_with_session_created_at",
+ "466_activity_log_member_assignee_frequency_index": "idx_activity_log_member_assignee_frequency",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/migrate/migrate_assignee_frequency_renumber_test.go b/server/cmd/migrate/migrate_assignee_frequency_renumber_test.go
new file mode 100644
index 0000000000..4260fa2a14
--- /dev/null
+++ b/server/cmd/migrate/migrate_assignee_frequency_renumber_test.go
@@ -0,0 +1,107 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+)
+
+func TestAssigneeFrequencyRenumberPreservesExistingIndex(t *testing.T) {
+ const version = "466_activity_log_member_assignee_frequency_index"
+ const legacyVersion = "458_activity_log_member_assignee_frequency_index"
+ const index = "idx_activity_log_member_assignee_frequency"
+
+ for _, previouslyApplied := range []bool{false, true} {
+ t.Run(fmt.Sprintf("previously_applied_%t", previouslyApplied), func(t *testing.T) {
+ admin := openTestPool(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ schema := fmt.Sprintf("migrate_assignee_renumber_%d_%d", time.Now().UnixNano(), rand.Uint32())
+ ident := pgx.Identifier{schema}.Sanitize()
+ if _, err := admin.Exec(ctx, "CREATE SCHEMA "+ident); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+ident+" CASCADE"); err != nil {
+ t.Errorf("cleanup schema: %v", err)
+ }
+ })
+ pool := openTestPoolWithSearchPath(t, schema)
+ if _, err := pool.Exec(ctx, `CREATE TABLE activity_log (
+ workspace_id UUID, actor_id UUID, actor_type TEXT, action TEXT, details JSONB
+ );
+ CREATE TABLE schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ DEFAULT now())`); err != nil {
+ t.Fatal(err)
+ }
+ files := realMigrationFiles(t, []string{version}, "up")
+ var originalOID uint32
+ if previouslyApplied {
+ // Simulate an installation that applied the identical index SQL
+ // before its migration filename was renumbered.
+ sql, err := os.ReadFile(files[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, string(sql)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, "INSERT INTO schema_migrations (version) VALUES ($1)", legacyVersion); err != nil {
+ t.Fatal(err)
+ }
+ if err := pool.QueryRow(ctx, "SELECT $1::regclass::oid", schema+"."+index).Scan(&originalOID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ options := runOptions{
+ Direction: "up", Files: files,
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("up"),
+ }
+ if preMigrationHooks[version] == nil {
+ t.Fatal("renumbered migration lost its interrupted-index repair hook")
+ }
+ for range 2 {
+ if err := runMigrations(ctx, pool, options); err != nil {
+ t.Fatal(err)
+ }
+ }
+ assertIndexValidity(t, pool, schema, index, true)
+ var recorded bool
+ if err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)", version).Scan(&recorded); err != nil || !recorded {
+ t.Fatalf("new version recorded = %t, error = %v", recorded, err)
+ }
+ if previouslyApplied {
+ var currentOID uint32
+ if err := pool.QueryRow(ctx, "SELECT $1::regclass::oid", schema+"."+index).Scan(&currentOID); err != nil {
+ t.Fatal(err)
+ }
+ if currentOID != originalOID {
+ t.Fatal("upgrade rebuilt the existing valid index")
+ }
+ if err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)", legacyVersion).Scan(&recorded); err != nil || !recorded {
+ t.Fatalf("historical version preserved = %t, error = %v", recorded, err)
+ }
+ }
+ options.Direction = "down"
+ options.Files = realMigrationFiles(t, []string{version}, "down")
+ options.Hooks = hooksForDirection("down")
+ if err := runMigrations(ctx, pool, options); err != nil {
+ t.Fatal(err)
+ }
+ assertIndexExists(t, pool, schema, index, false)
+ options.Direction, options.Files, options.Hooks = "up", files, hooksForDirection("up")
+ if err := runMigrations(ctx, pool, options); err != nil {
+ t.Fatal(err)
+ }
+ assertIndexValidity(t, pool, schema, index, true)
+ })
+ }
+}
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 3873d4a18b..9d2093a610 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -514,6 +514,9 @@ type TaskMessageData struct {
Content string `json:"content,omitempty"`
Input map[string]any `json:"input,omitempty"`
Output string `json:"output,omitempty"`
+ // CreatedAt is when the daemon observed the event, before the 500ms report
+ // batch. Without it, every row in one batch gets the same database time.
+ CreatedAt time.Time `json:"created_at"`
// 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
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 13be3d1fb9..c0cc418fdb 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8968,6 +8968,8 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
var mu sync.Mutex
var pendingText strings.Builder
var pendingThinking strings.Builder
+ var pendingTextAt time.Time
+ var pendingThinkingAt time.Time
var batch []TaskMessageData
callIDToTool := map[string]string{}
@@ -8976,20 +8978,24 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
if pendingThinking.Len() > 0 {
s := msgSeq.Add(1)
batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "thinking",
- Content: pendingThinking.String(),
+ Seq: int(s),
+ Type: "thinking",
+ Content: pendingThinking.String(),
+ CreatedAt: pendingThinkingAt,
})
pendingThinking.Reset()
+ pendingThinkingAt = time.Time{}
}
if pendingText.Len() > 0 {
s := msgSeq.Add(1)
batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "text",
- Content: pendingText.String(),
+ Seq: int(s),
+ Type: "text",
+ Content: pendingText.String(),
+ CreatedAt: pendingTextAt,
})
pendingText.Reset()
+ pendingTextAt = time.Time{}
}
toSend := batch
batch = nil
@@ -9041,7 +9047,8 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
// gone silent — stamping before processing makes sure a
// slow downstream call (mu.Lock contention, batch resize)
// can't be misattributed to backend silence.
- lastActivityAt.Store(time.Now().UnixNano())
+ observedAt := time.Now().UTC()
+ lastActivityAt.Store(observedAt.UnixNano())
switch msg.Type {
case agent.MessageStatus:
// Persist the session/work_dir as soon as the backend
@@ -9088,9 +9095,10 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
s := msgSeq.Add(1)
mu.Lock()
batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "tool_use",
- Tool: msg.Tool,
+ Seq: int(s),
+ Type: "tool_use",
+ Tool: msg.Tool,
+ CreatedAt: observedAt,
// Redact before the payload leaves this process, not
// only on arrival. The server redacts again in its
// ingest handler, but that is the *remote* side: a
@@ -9129,10 +9137,11 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
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",
- Tool: toolName,
- Output: output,
+ Seq: int(s),
+ Type: "tool_result",
+ Tool: toolName,
+ Output: output,
+ CreatedAt: observedAt,
// 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
@@ -9144,6 +9153,9 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
if msg.Content != "" {
mu.Lock()
pendingThinking.WriteString(msg.Content)
+ if pendingThinkingAt.IsZero() {
+ pendingThinkingAt = observedAt
+ }
mu.Unlock()
}
case agent.MessageText:
@@ -9151,6 +9163,9 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
taskLog.Debug("agent", "text", truncateLog(msg.Content, 200))
mu.Lock()
pendingText.WriteString(msg.Content)
+ if pendingTextAt.IsZero() {
+ pendingTextAt = observedAt
+ }
mu.Unlock()
}
case agent.MessageError:
@@ -9158,9 +9173,10 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
s := msgSeq.Add(1)
mu.Lock()
batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "error",
- Content: msg.Content,
+ Seq: int(s),
+ Type: "error",
+ Content: msg.Content,
+ CreatedAt: observedAt,
})
mu.Unlock()
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 16d3356999..8c90d3d588 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2691,6 +2691,97 @@ func TestExecuteAndDrain_FlushesTranscriptBeforeReturningResult(t *testing.T) {
}
}
+// timedTranscriptBackend keeps a tool open long enough to prove the daemon
+// records event occurrence time rather than giving a whole flush batch one
+// server insertion time.
+type timedTranscriptBackend struct{}
+
+func (timedTranscriptBackend) 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.MessageToolUse, Tool: "bash", CallID: "timed"}
+ time.Sleep(10 * time.Millisecond)
+ msgCh <- agent.Message{Type: agent.MessageToolResult, Tool: "bash", CallID: "timed", Output: "ok"}
+ close(msgCh)
+ resCh <- agent.Result{Status: "completed", Output: "done"}
+ close(resCh)
+ }()
+ return &agent.Session{Messages: msgCh, Result: resCh}, nil
+}
+
+func TestExecuteAndDrain_ReportsPerEventTimestamps(t *testing.T) {
+ t.Parallel()
+
+ d, rec := newTranscriptRecorder(t)
+ if _, _, err := d.executeAndDrain(context.Background(), timedTranscriptBackend{}, "p", agent.ExecOptions{}, slog.Default(), "task-timing", "", new(atomic.Int32)); err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+
+ got := rec.snapshot()
+ if len(got) != 2 {
+ t.Fatalf("reported %d messages, want tool use and result: %+v", len(got), got)
+ }
+ if got[0].CreatedAt.IsZero() || !got[1].CreatedAt.After(got[0].CreatedAt) {
+ t.Fatalf("event timestamps = [%s, %s], want distinct ordered times", got[0].CreatedAt, got[1].CreatedAt)
+ }
+}
+
+type chunkedTranscriptBackend struct {
+ thinkingSecondStartedAt chan time.Time
+ textSecondStartedAt chan time.Time
+}
+
+func (b *chunkedTranscriptBackend) 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.MessageThinking, Content: "think one "}
+ time.Sleep(20 * time.Millisecond)
+ b.thinkingSecondStartedAt <- time.Now()
+ msgCh <- agent.Message{Type: agent.MessageThinking, Content: "think two"}
+
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "text one "}
+ time.Sleep(20 * time.Millisecond)
+ b.textSecondStartedAt <- time.Now()
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "text two"}
+ close(msgCh)
+ resCh <- agent.Result{Status: "completed", Output: "done"}
+ close(resCh)
+ }()
+ return &agent.Session{Messages: msgCh, Result: resCh}, nil
+}
+
+func TestExecuteAndDrain_ReportsFirstBufferedChunkTimestamp(t *testing.T) {
+ t.Parallel()
+
+ backend := &chunkedTranscriptBackend{
+ thinkingSecondStartedAt: make(chan time.Time, 1),
+ textSecondStartedAt: make(chan time.Time, 1),
+ }
+ d, rec := newTranscriptRecorder(t)
+ if _, _, err := d.executeAndDrain(context.Background(), backend, "p", agent.ExecOptions{}, slog.Default(), "task-chunks", "", new(atomic.Int32)); err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+
+ got := rec.snapshot()
+ if len(got) != 2 {
+ t.Fatalf("reported %d messages, want thinking and text: %+v", len(got), got)
+ }
+ if got[0].Type != "thinking" || got[0].Content != "think one think two" {
+ t.Fatalf("thinking message = %+v", got[0])
+ }
+ if boundary := <-backend.thinkingSecondStartedAt; !got[0].CreatedAt.Before(boundary) {
+ t.Fatalf("thinking created_at = %s, want before second chunk started at %s", got[0].CreatedAt, boundary)
+ }
+ if got[1].Type != "text" || got[1].Content != "text one text two" {
+ t.Fatalf("text message = %+v", got[1])
+ }
+ if boundary := <-backend.textSecondStartedAt; !got[1].CreatedAt.Before(boundary) {
+ t.Fatalf("text created_at = %s, want before second chunk started at %s", got[1].CreatedAt, boundary)
+ }
+}
+
// 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
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index d05577461a..20a42ab67a 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4683,6 +4683,9 @@ type TaskMessageRequest struct {
Content string `json:"content,omitempty"`
Input map[string]any `json:"input,omitempty"`
Output string `json:"output,omitempty"`
+ // CreatedAt is optional so installed daemons can roll forward or back
+ // independently of the server. Missing values keep the database-time fallback.
+ CreatedAt *time.Time `json:"created_at,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
@@ -4744,11 +4747,16 @@ 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),
+ // Optional for mixed-version rollout. Older daemons omit the event
+ // timestamp, and one missing or implausible value makes the whole batch
+ // use database time so paired events never mix clocks.
+ CreatedAts: 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 {
+ createdAts := taskMessageCreatedAts(req.Messages, time.Now().UTC())
+ for i, msg := range req.Messages {
id, err := uuid.NewV7()
if err != nil {
slog.Error("failed to generate task message id", "task_id", taskID, "error", err)
@@ -4802,6 +4810,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.CreatedAts = append(params.CreatedAts, createdAts[i])
params.OutputTruncations = append(params.OutputTruncations, boolArrayElement(msg.OutputTruncated))
}
@@ -4968,6 +4977,37 @@ func boolArrayElement(v *bool) string {
return "false"
}
+const maxTaskMessageClockSkew = 2 * time.Minute
+
+// taskMessageCreatedAt encodes the daemon-observed event time for the batch
+// query's nullable text[] transport. Empty means an older daemon omitted the
+// field or its wall clock is implausibly far from the server, so PostgreSQL
+// falls back to its normal insertion time.
+func taskMessageCreatedAt(v *time.Time, serverNow time.Time) string {
+ if v == nil || v.IsZero() {
+ return ""
+ }
+ if skew := v.Sub(serverNow); skew < -maxTaskMessageClockSkew || skew > maxTaskMessageClockSkew {
+ return ""
+ }
+ return v.UTC().Format(time.RFC3339Nano)
+}
+
+// taskMessageCreatedAts keeps every timestamp in a report batch on the same
+// clock. If any event lacks a plausible daemon timestamp, returning all empty
+// values makes PostgreSQL assign one database timestamp to the whole batch.
+func taskMessageCreatedAts(messages []TaskMessageRequest, serverNow time.Time) []string {
+ createdAts := make([]string, len(messages))
+ for i := range messages {
+ createdAts[i] = taskMessageCreatedAt(messages[i].CreatedAt, serverNow)
+ if createdAts[i] == "" {
+ clear(createdAts)
+ return createdAts
+ }
+ }
+ return createdAts
+}
+
// 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_batch_test.go b/server/internal/handler/task_message_batch_test.go
index 536f6f0aa3..f23a36697f 100644
--- a/server/internal/handler/task_message_batch_test.go
+++ b/server/internal/handler/task_message_batch_test.go
@@ -3,8 +3,10 @@ package handler
import (
"context"
"net/http"
+ "slices"
"sync"
"testing"
+ "time"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
@@ -57,17 +59,31 @@ func TestReportTaskMessagesPersistsWholeBatch(t *testing.T) {
}
ctx := context.Background()
taskID := seedBatchTask(t, "batch-messages")
+ // PostgreSQL timestamptz preserves microseconds, so keep the fixture on that
+ // boundary while still proving daemon event precision survives.
+ observedAt := time.Now().UTC().Add(-time.Second).Truncate(time.Microsecond)
testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{
- map[string]any{"seq": 1, "type": "thinking", "content": "planning"},
map[string]any{
- "seq": 2,
- "type": "tool_use",
- "tool": "fs_read",
- "input": map[string]any{"path": "/etc/hosts", "nested": map[string]any{"depth": 2}},
- "output": "127.0.0.1 localhost",
+ "seq": 1,
+ "type": "thinking",
+ "content": "planning",
+ "created_at": observedAt.Format(time.RFC3339Nano),
+ },
+ map[string]any{
+ "seq": 2,
+ "type": "tool_use",
+ "tool": "fs_read",
+ "input": map[string]any{"path": "/etc/hosts", "nested": map[string]any{"depth": 2}},
+ "output": "127.0.0.1 localhost",
+ "created_at": observedAt.Add(10 * time.Millisecond).Format(time.RFC3339Nano),
+ },
+ map[string]any{
+ "seq": 3,
+ "type": "text",
+ "content": "done",
+ "created_at": observedAt.Add(20 * time.Millisecond).Format(time.RFC3339Nano),
},
- map[string]any{"seq": 3, "type": "text", "content": "done"},
})).Want(http.StatusOK)
stored, err := testHandler.Queries.ListTaskMessages(ctx, util.MustParseUUID(taskID))
@@ -86,6 +102,12 @@ func TestReportTaskMessagesPersistsWholeBatch(t *testing.T) {
if stored[0].Type != "thinking" || stored[0].Content.String != "planning" {
t.Fatalf("thinking row = %+v, want type=thinking content=planning", stored[0])
}
+ if !stored[0].CreatedAt.Time.Equal(observedAt) {
+ t.Fatalf("daemon-observed created_at = %s, want %s", stored[0].CreatedAt.Time, observedAt)
+ }
+ if want := observedAt.Add(10 * time.Millisecond); !stored[1].CreatedAt.Time.Equal(want) {
+ t.Fatalf("second daemon-observed created_at = %s, want %s", stored[1].CreatedAt.Time, want)
+ }
// Fields the daemon did not send must be NULL, not "".
if stored[0].Tool.Valid || stored[0].Output.Valid || stored[0].Input != nil {
t.Fatalf("thinking row should have NULL tool/output/input, got %+v", stored[0])
@@ -113,6 +135,45 @@ func TestReportTaskMessagesPersistsWholeBatch(t *testing.T) {
}
}
+func TestReportTaskMessagesFallsBackWholeBatchForClockSkew(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ taskID := seedBatchTask(t, "batch-clock-skew")
+ validAt := time.Now().UTC().Add(-time.Second)
+ invalidAt := validAt.Add(-maxTaskMessageClockSkew - time.Minute)
+ fallbackBefore := time.Now().UTC()
+
+ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{
+ map[string]any{
+ "seq": 1,
+ "type": "tool_use",
+ "tool": "bash",
+ "created_at": validAt.Format(time.RFC3339Nano),
+ },
+ map[string]any{
+ "seq": 2,
+ "type": "tool_result",
+ "tool": "bash",
+ "created_at": invalidAt.Format(time.RFC3339Nano),
+ },
+ })).Want(http.StatusOK)
+ fallbackAfter := time.Now().UTC()
+
+ stored, err := testHandler.Queries.ListTaskMessages(context.Background(), util.MustParseUUID(taskID))
+ if err != nil {
+ t.Fatalf("list persisted task messages: %v", err)
+ }
+ if len(stored) != 2 {
+ t.Fatalf("persisted %d task messages, want 2", len(stored))
+ }
+ for _, row := range stored {
+ if got := row.CreatedAt.Time; got.Before(fallbackBefore) || got.After(fallbackAfter) {
+ t.Fatalf("seq %d created_at = %s, want database fallback between %s and %s", row.Seq, got, fallbackBefore, fallbackAfter)
+ }
+ }
+}
+
// TestReportTaskMessagesPublishesInSeqOrder pins the realtime ordering the batch
// insert has to preserve. The per-message loop it replaced published in request
// order; `INSERT ... RETURNING` has no row-order guarantee, so the order now
@@ -199,14 +260,16 @@ func TestCreateTaskMessagesBatchIsAtomic(t *testing.T) {
})
_, err := testHandler.Queries.CreateTaskMessages(ctx, db.CreateTaskMessagesParams{
- TaskID: util.MustParseUUID(taskID),
- Ids: []pgtype.UUID{util.MustParseUUID("018f0000-0000-7000-8000-000000000002"), util.MustParseUUID(dupID)},
- Seqs: []int32{2, 3},
- Types: []string{"text", "text"},
- Tools: []string{"", ""},
- Contents: []string{"ok", "collides"},
- Inputs: []string{"", ""},
- Outputs: []string{"", ""},
+ TaskID: util.MustParseUUID(taskID),
+ Ids: []pgtype.UUID{util.MustParseUUID("018f0000-0000-7000-8000-000000000002"), util.MustParseUUID(dupID)},
+ Seqs: []int32{2, 3},
+ Types: []string{"text", "text"},
+ Tools: []string{"", ""},
+ Contents: []string{"ok", "collides"},
+ Inputs: []string{"", ""},
+ Outputs: []string{"", ""},
+ CreatedAts: []string{"", ""},
+ OutputTruncations: []string{"", ""},
})
if err == nil {
t.Fatal("CreateTaskMessages accepted a batch with a duplicate primary key")
@@ -218,3 +281,60 @@ func TestCreateTaskMessagesBatchIsAtomic(t *testing.T) {
"the batch persisted a prefix instead of rolling back", count)
}
}
+
+func TestTaskMessageCreatedAtRejectsImplausibleClockSkew(t *testing.T) {
+ t.Parallel()
+
+ serverNow := time.Date(2026, time.September, 10, 12, 0, 0, 0, time.UTC)
+ zero := time.Time{}
+ insidePast := serverNow.Add(-maxTaskMessageClockSkew)
+ insideFuture := serverNow.Add(maxTaskMessageClockSkew)
+ outsidePast := insidePast.Add(-time.Nanosecond)
+ outsideFuture := insideFuture.Add(time.Nanosecond)
+
+ tests := []struct {
+ name string
+ at *time.Time
+ want string
+ }{
+ {name: "missing"},
+ {name: "zero", at: &zero},
+ {name: "past boundary", at: &insidePast, want: insidePast.Format(time.RFC3339Nano)},
+ {name: "future boundary", at: &insideFuture, want: insideFuture.Format(time.RFC3339Nano)},
+ {name: "too far in the past", at: &outsidePast},
+ {name: "too far in the future", at: &outsideFuture},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ if got := taskMessageCreatedAt(tt.at, serverNow); got != tt.want {
+ t.Fatalf("taskMessageCreatedAt() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestTaskMessageCreatedAtsFallsBackWholeBatch(t *testing.T) {
+ t.Parallel()
+
+ serverNow := time.Date(2026, time.September, 10, 12, 0, 0, 0, time.UTC)
+ valid := serverNow.Add(-time.Second)
+ invalid := serverNow.Add(-maxTaskMessageClockSkew - time.Nanosecond)
+
+ got := taskMessageCreatedAts([]TaskMessageRequest{
+ {CreatedAt: &valid},
+ {CreatedAt: &invalid},
+ }, serverNow)
+ if want := []string{"", ""}; !slices.Equal(got, want) {
+ t.Fatalf("taskMessageCreatedAts() = %q, want whole-batch fallback %q", got, want)
+ }
+
+ got = taskMessageCreatedAts([]TaskMessageRequest{
+ {CreatedAt: &valid},
+ {CreatedAt: &serverNow},
+ }, serverNow)
+ if want := []string{valid.Format(time.RFC3339Nano), serverNow.Format(time.RFC3339Nano)}; !slices.Equal(got, want) {
+ t.Fatalf("taskMessageCreatedAts() = %q, want %q", got, want)
+ }
+}
diff --git a/server/internal/handler/task_message_truncation_test.go b/server/internal/handler/task_message_truncation_test.go
index 1a28331366..a5d2024f82 100644
--- a/server/internal/handler/task_message_truncation_test.go
+++ b/server/internal/handler/task_message_truncation_test.go
@@ -43,6 +43,7 @@ func TestCreateTaskMessagesKeepsTruncationTriState(t *testing.T) {
Contents: make([]string, 0, len(messages)),
Inputs: make([]string, 0, len(messages)),
Outputs: make([]string, 0, len(messages)),
+ CreatedAts: make([]string, 0, len(messages)),
OutputTruncations: make([]string, 0, len(messages)),
}
for _, msg := range messages {
@@ -53,6 +54,7 @@ func TestCreateTaskMessagesKeepsTruncationTriState(t *testing.T) {
params.Contents = append(params.Contents, msg.Content)
params.Inputs = append(params.Inputs, "")
params.Outputs = append(params.Outputs, msg.Output)
+ params.CreatedAts = append(params.CreatedAts, "")
params.OutputTruncations = append(params.OutputTruncations, boolArrayElement(msg.OutputTruncated))
}
diff --git a/server/migrations/458_activity_log_member_assignee_frequency_index.down.sql b/server/migrations/466_activity_log_member_assignee_frequency_index.down.sql
similarity index 100%
rename from server/migrations/458_activity_log_member_assignee_frequency_index.down.sql
rename to server/migrations/466_activity_log_member_assignee_frequency_index.down.sql
diff --git a/server/migrations/458_activity_log_member_assignee_frequency_index.up.sql b/server/migrations/466_activity_log_member_assignee_frequency_index.up.sql
similarity index 75%
rename from server/migrations/458_activity_log_member_assignee_frequency_index.up.sql
rename to server/migrations/466_activity_log_member_assignee_frequency_index.up.sql
index caa36ac26e..e3aa4215ea 100644
--- a/server/migrations/458_activity_log_member_assignee_frequency_index.up.sql
+++ b/server/migrations/466_activity_log_member_assignee_frequency_index.up.sql
@@ -1,3 +1,6 @@
+-- Renumbered from 458 to avoid the cancellation-provenance migration.
+-- IF NOT EXISTS preserves an index already created under the old version;
+-- the runner records this version without rewriting the historical ledger.
-- CountAssigneeChangesByActor filters by workspace and member actor, then
-- groups on the assignment target stored in details. Keep the expressions in
-- key order so PostgreSQL can aggregate the matching history directly from
diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.go
index ebda00d929..03e6c4d0ab 100644
--- a/server/pkg/db/generated/task_message.sql.go
+++ b/server/pkg/db/generated/task_message.sql.go
@@ -72,18 +72,20 @@ WITH incoming AS (
unnest($5::text[]) AS content,
unnest($6::text[]) AS input,
unnest($7::text[]) AS output,
- unnest($8::text[]) AS output_truncated
+ unnest($8::text[]) AS created_at,
+ unnest($9::text[]) AS output_truncated
), inserted AS (
- INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, output_truncated)
+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, created_at, output_truncated)
SELECT
m.id,
- $9::uuid,
+ $10::uuid,
m.seq,
m.type,
NULLIF(m.tool, ''),
NULLIF(m.content, ''),
NULLIF(m.input, '')::jsonb,
NULLIF(m.output, ''),
+ COALESCE(NULLIF(m.created_at, '')::timestamptz, now()),
NULLIF(m.output_truncated, '')::bool
FROM incoming AS m
RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated
@@ -99,6 +101,7 @@ type CreateTaskMessagesParams struct {
Contents []string `json:"contents"`
Inputs []string `json:"inputs"`
Outputs []string `json:"outputs"`
+ CreatedAts []string `json:"created_ats"`
OutputTruncations []string `json:"output_truncations"`
TaskID pgtype.UUID `json:"task_id"`
}
@@ -136,10 +139,11 @@ 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. 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.
+// it is a jsonb column. created_at also rides this transport so an older daemon
+// can omit its event time and keep the database-time fallback. output_truncated
+// uses the same trick because 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
@@ -167,6 +171,7 @@ func (q *Queries) CreateTaskMessages(ctx context.Context, arg CreateTaskMessages
arg.Contents,
arg.Inputs,
arg.Outputs,
+ arg.CreatedAts,
arg.OutputTruncations,
arg.TaskID,
)
diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sql
index 58c2f284ce..18ba7042da 100644
--- a/server/pkg/db/queries/task_message.sql
+++ b/server/pkg/db/queries/task_message.sql
@@ -24,10 +24,11 @@ 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. 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.
+-- it is a jsonb column. created_at also rides this transport so an older daemon
+-- can omit its event time and keep the database-time fallback. output_truncated
+-- uses the same trick because 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
@@ -60,9 +61,10 @@ WITH incoming AS (
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, output_truncated)
+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output, created_at, output_truncated)
SELECT
m.id,
sqlc.arg('task_id')::uuid,
@@ -72,6 +74,7 @@ WITH incoming AS (
NULLIF(m.content, ''),
NULLIF(m.input, '')::jsonb,
NULLIF(m.output, ''),
+ COALESCE(NULLIF(m.created_at, '')::timestamptz, now()),
NULLIF(m.output_truncated, '')::bool
FROM incoming AS m
RETURNING *