diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index c201e1d9f9..fbd110528d 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -816,6 +816,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti turnId: event.payload.turnId, role: event.payload.role, text: nextText, + ...(event.payload.assistantPhase !== undefined + ? { assistantPhase: event.payload.assistantPhase } + : previousMessage?.assistantPhase !== undefined + ? { assistantPhase: previousMessage.assistantPhase } + : {}), ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}), isStreaming: event.payload.streaming, createdAt: previousMessage?.createdAt ?? event.payload.createdAt, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 7db2a23e5e..01135dd754 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -306,6 +306,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { planId: "plan-1", }, }, + turns: [], createdAt: "2026-02-24T00:00:02.000Z", updatedAt: "2026-02-24T00:00:03.000Z", archivedAt: null, @@ -437,8 +438,26 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1")); assert.equal(threadDetail._tag, "Some"); - if (threadDetail._tag === "Some") { - assert.deepEqual(threadDetail.value, snapshot.threads[0]); + const snapshotThread = snapshot.threads[0]; + assert.isDefined(snapshotThread); + if (threadDetail._tag === "Some" && snapshotThread) { + assert.deepEqual(threadDetail.value, { + ...snapshotThread, + turns: [ + { + turnId: asTurnId("turn-1"), + state: "completed", + requestedAt: "2026-02-24T00:00:08.000Z", + startedAt: "2026-02-24T00:00:08.000Z", + completedAt: "2026-02-24T00:00:08.000Z", + assistantMessageId: asMessageId("message-1"), + sourceProposedPlan: { + threadId: ThreadId.make("thread-1"), + planId: "plan-1", + }, + }, + ], + }); } }), ); @@ -1150,6 +1169,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { assert.equal(threadDetail.value.latestTurn?.turnId, asTurnId("turn-running")); assert.equal(threadDetail.value.latestTurn?.state, "running"); assert.equal(threadDetail.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z"); + assert.deepEqual( + threadDetail.value.turns?.map((turn) => turn.turnId), + [asTurnId("turn-completed"), asTurnId("turn-running")], + ); } }), ); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index e629d1604b..23c3511b93 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -1,4 +1,5 @@ import { + AssistantMessagePhase, ChatAttachment, CheckpointRef, IsoDateTime, @@ -70,6 +71,7 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields( const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( Struct.assign({ isStreaming: Schema.Number, + assistantPhase: Schema.NullOr(AssistantMessagePhase), attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))), }), ); @@ -414,6 +416,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { turn_id AS "turnId", role, text, + assistant_phase AS "assistantPhase", attachments_json AS "attachments", is_streaming AS "isStreaming", created_at AS "createdAt", @@ -777,6 +780,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { turn_id AS "turnId", role, text, + assistant_phase AS "assistantPhase", attachments_json AS "attachments", is_streaming AS "isStreaming", created_at AS "createdAt", @@ -877,6 +881,28 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { `, }); + const listTurnRowsByThread = SqlSchema.findAll({ + Request: ThreadIdLookupInput, + Result: ProjectionLatestTurnDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + state, + requested_at AS "requestedAt", + started_at AS "startedAt", + completed_at AS "completedAt", + assistant_message_id AS "assistantMessageId", + source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", + source_proposed_plan_id AS "sourceProposedPlanId" + FROM projection_turns + WHERE thread_id = ${threadId} + AND turn_id IS NOT NULL + ORDER BY requested_at ASC, turn_id ASC + `, + }); + const listCheckpointRowsByThread = SqlSchema.findAll({ Request: ThreadIdLookupInput, Result: ProjectionCheckpointDbRowSchema, @@ -1048,6 +1074,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { id: row.messageId, role: row.role, text: row.text, + ...(row.assistantPhase !== null ? { assistantPhase: row.assistantPhase } : {}), ...(row.attachments !== null ? { attachments: row.attachments } : {}), turnId: row.turnId, streaming: row.isStreaming === 1, @@ -1903,6 +1930,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { activityRows, checkpointRows, latestTurnRow, + turnRows, sessionRow, ] = yield* Effect.all([ getActiveThreadRowById({ threadId }).pipe( @@ -1953,6 +1981,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ), ), + listTurnRowsByThread({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadDetailById:listTurns:query", + "ProjectionSnapshotQuery.getThreadDetailById:listTurns:decodeRows", + ), + ), + ), getThreadSessionRowByThread({ threadId }).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( @@ -1977,6 +2013,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { branch: threadRow.value.branch, worktreePath: threadRow.value.worktreePath, latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null, + turns: turnRows.map(mapLatestTurn), createdAt: threadRow.value.createdAt, updatedAt: threadRow.value.updatedAt, archivedAt: threadRow.value.archivedAt, @@ -1986,6 +2023,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { id: row.messageId, role: row.role, text: row.text, + ...(row.assistantPhase !== null ? { assistantPhase: row.assistantPhase } : {}), turnId: row.turnId, streaming: row.isStreaming === 1, createdAt: row.createdAt, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index dceb594486..9b09e12185 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -703,6 +703,7 @@ describe("ProviderRuntimeIngestion", () => { payload: { itemType: "assistant_message", status: "completed", + messagePhase: "final_answer", }, }); @@ -1544,6 +1545,7 @@ describe("ProviderRuntimeIngestion", () => { payload: { itemType: "assistant_message", status: "completed", + messagePhase: "final_answer", }, }); @@ -2183,6 +2185,7 @@ describe("ProviderRuntimeIngestion", () => { payload: { itemType: "assistant_message", status: "completed", + messagePhase: "final_answer", }, }); harness.emit({ @@ -2223,6 +2226,11 @@ describe("ProviderRuntimeIngestion", () => { ); }); expect(completionEvents).toHaveLength(1); + const completionEvent = completionEvents[0]; + expect(completionEvent?.type).toBe("thread.message-sent"); + if (completionEvent?.type === "thread.message-sent") { + expect(completionEvent.payload.assistantPhase).toBe("final_answer"); + } }); it("maps canonical request events into approval activities with requestKind", async () => { diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 59787e0b54..03b3ee9c29 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -904,6 +904,7 @@ const make = Effect.gen(function* () { commandTag: string; finalDeltaCommandTag: string; fallbackText?: string; + assistantPhase?: "commentary" | "final_answer"; hasProjectedMessage?: boolean; }) => Effect.gen(function* () { @@ -934,6 +935,7 @@ const make = Effect.gen(function* () { commandId: yield* providerCommandId(input.event, input.commandTag), threadId: input.threadId, messageId: input.messageId, + ...(input.assistantPhase ? { assistantPhase: input.assistantPhase } : {}), ...(input.turnId ? { turnId: input.turnId } : {}), createdAt: input.createdAt, }); @@ -1425,6 +1427,7 @@ const make = Effect.gen(function* () { `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, ), fallbackText: event.payload.detail, + messagePhase: event.payload.messagePhase, } : undefined; const proposedPlanCompletion = @@ -1476,6 +1479,9 @@ const make = Effect.gen(function* () { ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText ? { fallbackText: assistantCompletion.fallbackText } : {}), + ...(assistantCompletion.messagePhase + ? { assistantPhase: assistantCompletion.messagePhase } + : {}), }); if (turnId) { diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 0d4af771ca..66fa15178c 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -646,6 +646,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" messageId: command.messageId, role: "assistant", text: "", + ...(command.assistantPhase ? { assistantPhase: command.assistantPhase } : {}), turnId: command.turnId ?? null, streaming: false, createdAt: command.createdAt, diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index 804c1e8a6f..834c5bacdc 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -86,6 +86,7 @@ describe("orchestration projector", () => { branch: null, worktreePath: null, latestTurn: null, + turns: [], createdAt: now, updatedAt: now, archivedAt: null, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 0c92f96543..d3ca937df6 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -260,6 +260,7 @@ export function projectEvent( branch: payload.branch, worktreePath: payload.worktreePath, latestTurn: null, + turns: [], createdAt: payload.createdAt, updatedAt: payload.updatedAt, archivedAt: null, @@ -376,6 +377,9 @@ export function projectEvent( id: payload.messageId, role: payload.role, text: payload.text, + ...(payload.assistantPhase !== undefined + ? { assistantPhase: payload.assistantPhase } + : {}), ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}), turnId: payload.turnId, streaming: payload.streaming, @@ -400,6 +404,9 @@ export function projectEvent( streaming: message.streaming, updatedAt: message.updatedAt, turnId: message.turnId, + ...(message.assistantPhase !== undefined + ? { assistantPhase: message.assistantPhase } + : {}), ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts index b1f394a9e5..dfba027fe8 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts @@ -111,4 +111,39 @@ layer("ProjectionThreadMessageRepository", (it) => { assert.deepEqual(rows[0]?.attachments, []); }), ); + + it.effect("preserves an assistant phase when a later streaming upsert omits it", () => + Effect.gen(function* () { + const repository = yield* ProjectionThreadMessageRepository; + const threadId = ThreadId.make("thread-preserve-assistant-phase"); + const messageId = MessageId.make("message-preserve-assistant-phase"); + const createdAt = "2026-06-05T00:00:00.000Z"; + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "assistant", + text: "done", + assistantPhase: "final_answer", + isStreaming: false, + createdAt, + updatedAt: "2026-06-05T00:00:01.000Z", + }); + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "assistant", + text: "done", + isStreaming: false, + createdAt, + updatedAt: "2026-06-05T00:00:02.000Z", + }); + + const rows = yield* repository.listByThreadId({ threadId }); + assert.equal(rows[0]?.assistantPhase, "final_answer"); + }), + ); }); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts index 7191916688..1d915661a0 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -5,7 +5,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; -import { ChatAttachment } from "@t3tools/contracts"; +import { AssistantMessagePhase, ChatAttachment } from "@t3tools/contracts"; import { toPersistenceSqlError } from "../Errors.ts"; import { @@ -20,6 +20,7 @@ import { const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( Struct.assign({ isStreaming: Schema.Number, + assistantPhase: Schema.NullOr(AssistantMessagePhase), attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))), }), ); @@ -36,6 +37,7 @@ function toProjectionThreadMessage( isStreaming: row.isStreaming === 1, createdAt: row.createdAt, updatedAt: row.updatedAt, + ...(row.assistantPhase !== null ? { assistantPhase: row.assistantPhase } : {}), ...(row.attachments !== null ? { attachments: row.attachments } : {}), }; } @@ -48,6 +50,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { execute: (row) => { const nextAttachmentsJson = row.attachments !== undefined ? JSON.stringify(row.attachments) : null; + const nextAssistantPhase = row.assistantPhase ?? null; return sql` INSERT INTO projection_thread_messages ( message_id, @@ -55,6 +58,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { turn_id, role, text, + assistant_phase, attachments_json, is_streaming, created_at, @@ -66,6 +70,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { ${row.turnId}, ${row.role}, ${row.text}, + COALESCE( + ${nextAssistantPhase}, + ( + SELECT assistant_phase + FROM projection_thread_messages + WHERE message_id = ${row.messageId} + ) + ), COALESCE( ${nextAttachmentsJson}, ( @@ -84,6 +96,10 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { turn_id = excluded.turn_id, role = excluded.role, text = excluded.text, + assistant_phase = COALESCE( + excluded.assistant_phase, + projection_thread_messages.assistant_phase + ), attachments_json = COALESCE( excluded.attachments_json, projection_thread_messages.attachments_json @@ -106,6 +122,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { turn_id AS "turnId", role, text, + assistant_phase AS "assistantPhase", attachments_json AS "attachments", is_streaming AS "isStreaming", created_at AS "createdAt", @@ -127,6 +144,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { turn_id AS "turnId", role, text, + assistant_phase AS "assistantPhase", attachments_json AS "attachments", is_streaming AS "isStreaming", created_at AS "createdAt", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index ba1131ee25..37d3b94097 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -45,6 +45,7 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts"; import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts"; import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts"; +import Migration0033 from "./Migrations/033_ProjectionThreadMessageAssistantPhase.ts"; /** * Migration loader with all migrations defined inline. @@ -89,6 +90,7 @@ export const migrationEntries = [ [30, "ProjectionThreadShellArchiveIndexes", Migration0030], [31, "AuthAuthorizationScopes", Migration0031], [32, "AuthPairingProofKeyThumbprint", Migration0032], + [33, "ProjectionThreadMessageAssistantPhase", Migration0033], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/033_ProjectionThreadMessageAssistantPhase.test.ts b/apps/server/src/persistence/Migrations/033_ProjectionThreadMessageAssistantPhase.test.ts new file mode 100644 index 0000000000..def921b3cc --- /dev/null +++ b/apps/server/src/persistence/Migrations/033_ProjectionThreadMessageAssistantPhase.test.ts @@ -0,0 +1,25 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("033_ProjectionThreadMessageAssistantPhase", (it) => { + it.effect("adds nullable assistant phase storage to projected messages", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 32 }); + yield* runMigrations({ toMigrationInclusive: 33 }); + + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_thread_messages) + `; + assert.isTrue(columns.some((column) => column.name === "assistant_phase")); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/033_ProjectionThreadMessageAssistantPhase.ts b/apps/server/src/persistence/Migrations/033_ProjectionThreadMessageAssistantPhase.ts new file mode 100644 index 0000000000..e0d27b0a72 --- /dev/null +++ b/apps/server/src/persistence/Migrations/033_ProjectionThreadMessageAssistantPhase.ts @@ -0,0 +1,11 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_thread_messages + ADD COLUMN assistant_phase TEXT + `; +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts index d50ff32025..0e056240f5 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -7,6 +7,7 @@ * @module ProjectionThreadMessageRepository */ import { + AssistantMessagePhase, ChatAttachment, MessageId, OrchestrationMessageRole, @@ -27,6 +28,7 @@ export const ProjectionThreadMessage = Schema.Struct({ turnId: Schema.NullOr(TurnId), role: OrchestrationMessageRole, text: Schema.String, + assistantPhase: Schema.optional(AssistantMessagePhase), attachments: Schema.optional(Schema.Array(ChatAttachment)), isStreaming: Schema.Boolean, createdAt: IsoDateTime, diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 3ae98ec248..b826e182d0 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -470,6 +470,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { type: "agentMessage", id: "msg_1", text: "done", + phase: "final_answer", }, }, }; @@ -488,6 +489,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { assert.equal(firstEvent.value.itemId, "msg_1"); assert.equal(firstEvent.value.turnId, "turn-1"); assert.equal(firstEvent.value.payload.itemType, "assistant_message"); + assert.equal(firstEvent.value.payload.messagePhase, "final_answer"); }), ); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 9893cf6c14..30bfffa077 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -476,6 +476,7 @@ function mapItemLifecycle( type: lifecycle, payload: { itemType, + ...(item.type === "agentMessage" && item.phase ? { messagePhase: item.phase } : {}), ...(status ? { status } : {}), ...(itemTitle(itemType) ? { title: itemTitle(itemType) } : {}), ...(detail ? { detail } : {}), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 7fc7669fe6..3f6affac65 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -50,7 +50,6 @@ import { parseStandaloneComposerSlashCommand, } from "../composer-logic"; import { - deriveCompletionDividerBeforeEntryId, derivePendingApprovals, derivePendingUserInputs, derivePhase, @@ -61,9 +60,7 @@ import { findLatestProposedPlan, deriveWorkLogEntries, hasActionableProposedPlan, - hasToolActivityForTurn, isLatestTurnSettled, - formatElapsed, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; import { @@ -1469,12 +1466,8 @@ export default function ChatView(props: ChatViewProps) { const phase = derivePhase(activeThread?.session ?? null); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo( - () => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined), - [activeLatestTurn?.turnId, threadActivities], - ); - const latestTurnHasToolActivity = useMemo( - () => hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId), - [activeLatestTurn?.turnId, threadActivities], + () => deriveWorkLogEntries(threadActivities, undefined), + [threadActivities], ); const pendingApprovals = useMemo( () => derivePendingApprovals(threadActivities), @@ -1810,25 +1803,11 @@ export default function ChatView(props: ChatViewProps) { return byUserMessageId; }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]); - const completionSummary = useMemo(() => { - if (!latestTurnSettled) return null; - if (!activeLatestTurn?.startedAt) return null; - if (!activeLatestTurn.completedAt) return null; - if (!latestTurnHasToolActivity) return null; - - const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt); - return elapsed ? `Worked for ${elapsed}` : null; - }, [ - activeLatestTurn?.completedAt, - activeLatestTurn?.startedAt, - latestTurnHasToolActivity, - latestTurnSettled, - ]); - const completionDividerBeforeEntryId = useMemo(() => { - if (!latestTurnSettled) return null; - if (!completionSummary) return null; - return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn); - }, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]); + const timelineTurns = useMemo(() => { + const turns = activeThread?.turns ?? []; + if (!activeLatestTurn) return turns; + return [...turns.filter((turn) => turn.turnId !== activeLatestTurn.turnId), activeLatestTurn]; + }, [activeLatestTurn, activeThread?.turns]); const gitCwd = activeProject ? projectScriptCwd({ project: { cwd: activeProject.cwd }, @@ -3785,8 +3764,7 @@ export default function ChatView(props: ChatViewProps) { activeTurnStartedAt={activeWorkStartedAt} listRef={legendListRef} timelineEntries={timelineEntries} - completionDividerBeforeEntryId={completionDividerBeforeEntryId} - completionSummary={completionSummary} + turns={timelineTurns} turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId} activeThreadEnvironmentId={activeThread.environmentId} routeThreadKey={routeThreadKey} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 5b643263fe..9e040a97f4 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -205,6 +205,143 @@ describe("resolveAssistantMessageCopyState", () => { }); describe("deriveMessagesTimelineRows", () => { + it("collapses completed turn work and commentary behind a worked-for row", () => { + const timelineEntries = [ + { + id: "user-entry", + kind: "message" as const, + createdAt: "2026-06-05T00:00:00Z", + message: { + id: "user" as never, + role: "user" as const, + text: "Do the work", + turnId: null, + createdAt: "2026-06-05T00:00:00Z", + streaming: false, + }, + }, + { + id: "commentary-entry", + kind: "message" as const, + createdAt: "2026-06-05T00:00:01Z", + message: { + id: "commentary" as never, + role: "assistant" as const, + text: "Inspecting the implementation.", + assistantPhase: "commentary" as const, + turnId: "turn-1" as never, + createdAt: "2026-06-05T00:00:01Z", + completedAt: "2026-06-05T00:00:02Z", + streaming: false, + }, + }, + { + id: "work-entry", + kind: "work" as const, + createdAt: "2026-06-05T00:00:03Z", + entry: { + id: "work", + createdAt: "2026-06-05T00:00:03Z", + turnId: "turn-1" as never, + label: "Read file", + tone: "tool" as const, + }, + }, + { + id: "final-entry", + kind: "message" as const, + createdAt: "2026-06-05T00:00:10Z", + message: { + id: "final" as never, + role: "assistant" as const, + text: "Implemented.", + assistantPhase: "final_answer" as const, + turnId: "turn-1" as never, + createdAt: "2026-06-05T00:00:10Z", + completedAt: "2026-06-05T00:00:11Z", + streaming: false, + }, + }, + ]; + const turn = { + turnId: "turn-1" as never, + state: "completed" as const, + requestedAt: "2026-06-05T00:00:00Z", + startedAt: "2026-06-05T00:00:00Z", + completedAt: "2026-06-05T00:00:11Z", + assistantMessageId: "final" as never, + }; + const baseInput = { + timelineEntries, + turns: [turn], + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }; + + const collapsedRows = deriveMessagesTimelineRows(baseInput); + expect(collapsedRows.map((row) => row.id)).toEqual([ + "user-entry", + "turn-fold:turn-1", + "final-entry", + ]); + expect(collapsedRows[1]).toMatchObject({ + kind: "turn-fold", + completionSummary: "Worked for 11s", + expanded: false, + hiddenCount: 2, + }); + + const expandedRows = deriveMessagesTimelineRows({ + ...baseInput, + expandedTurnIds: new Set(["turn-1" as never]), + }); + expect(expandedRows.map((row) => row.id)).toEqual([ + "user-entry", + "commentary-entry", + "work-entry", + "turn-fold:turn-1", + "final-entry", + ]); + }); + + it("keeps interrupted turn details visible", () => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "commentary-entry", + kind: "message", + createdAt: "2026-06-05T00:00:01Z", + message: { + id: "commentary" as never, + role: "assistant", + text: "Still working", + turnId: "turn-1" as never, + createdAt: "2026-06-05T00:00:01Z", + streaming: false, + }, + }, + ], + turns: [ + { + turnId: "turn-1" as never, + state: "interrupted", + requestedAt: "2026-06-05T00:00:00Z", + startedAt: "2026-06-05T00:00:00Z", + completedAt: "2026-06-05T00:00:02Z", + assistantMessageId: "commentary" as never, + }, + ], + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + expect(rows.map((row) => row.id)).toEqual(["commentary-entry"]); + }); + it("only enables assistant copy for the terminal assistant message in a turn", () => { const rows = deriveMessagesTimelineRows({ timelineEntries: [ diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index ad54dd8bde..d0340d5979 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,7 +1,7 @@ import * as Equal from "effect/Equal"; -import { type TimelineEntry, type WorkLogEntry } from "../../session-logic"; +import { formatElapsed, type TimelineEntry, type WorkLogEntry } from "../../session-logic"; import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types"; -import { type MessageId, type TurnId } from "@t3tools/contracts"; +import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts"; export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; @@ -19,6 +19,15 @@ export type MessagesTimelineRow = createdAt: string; groupedEntries: WorkLogEntry[]; } + | { + kind: "turn-fold"; + id: string; + createdAt: string; + turnId: TurnId; + completionSummary: string; + expanded: boolean; + hiddenCount: number; + } | { kind: "message"; id: string; @@ -86,6 +95,7 @@ export function resolveAssistantMessageCopyState({ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray) { const lastAssistantMessageIdByResponseKey = new Map(); + const finalAnswerResponseKeys = new Set(); let nullTurnResponseIndex = 0; for (const timelineEntry of timelineEntries) { @@ -104,15 +114,90 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray; + readonly completionSummary: string; +} + +function deriveTurnFolds( + timelineEntries: ReadonlyArray, + turns: ReadonlyArray, +): ReadonlyMap { + const assistantEntriesByTurnId = new Map< + TurnId, + Array> + >(); + const workEntryIdsByTurnId = new Map(); + + for (const entry of timelineEntries) { + if (entry.kind === "message" && entry.message.role === "assistant" && entry.message.turnId) { + const assistantEntries = assistantEntriesByTurnId.get(entry.message.turnId) ?? []; + assistantEntries.push(entry); + assistantEntriesByTurnId.set(entry.message.turnId, assistantEntries); + } + if (entry.kind === "work" && entry.entry.turnId) { + const workEntryIds = workEntryIdsByTurnId.get(entry.entry.turnId) ?? []; + workEntryIds.push(entry.id); + workEntryIdsByTurnId.set(entry.entry.turnId, workEntryIds); + } + } + + const foldsByFinalEntryId = new Map(); + for (const turn of turns) { + if (turn.state !== "completed" || !turn.completedAt) { + continue; + } + const assistantEntries = assistantEntriesByTurnId.get(turn.turnId) ?? []; + const finalEntry = + assistantEntries.findLast((entry) => entry.message.assistantPhase === "final_answer") ?? + assistantEntries.find((entry) => entry.message.id === turn.assistantMessageId) ?? + assistantEntries.at(-1); + if (!finalEntry) { + continue; + } + + const hiddenEntryIds = new Set(workEntryIdsByTurnId.get(turn.turnId) ?? []); + for (const entry of assistantEntries) { + if (entry.id !== finalEntry.id) { + hiddenEntryIds.add(entry.id); + } + } + if (hiddenEntryIds.size === 0) { + continue; + } + + const elapsed = formatElapsed(turn.startedAt ?? turn.requestedAt, turn.completedAt); + foldsByFinalEntryId.set(finalEntry.id, { + turnId: turn.turnId, + finalEntryId: finalEntry.id, + hiddenEntryIds, + completionSummary: elapsed ? `Worked for ${elapsed}` : "Worked", + }); + } + return foldsByFinalEntryId; +} + export function deriveMessagesTimelineRows(input: { timelineEntries: ReadonlyArray; - completionDividerBeforeEntryId: string | null; + turns?: ReadonlyArray; + expandedTurnIds?: ReadonlySet; + completionDividerBeforeEntryId?: string | null; completionSummary?: string | null; isWorking: boolean; activeTurnInProgress?: boolean; @@ -126,19 +211,44 @@ export function deriveMessagesTimelineRows(input: { input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), ); const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries); + const turnFoldsByFinalEntryId = deriveTurnFolds(input.timelineEntries, input.turns ?? []); + const collapsedEntryIds = new Set(); + for (const fold of turnFoldsByFinalEntryId.values()) { + if (!input.expandedTurnIds?.has(fold.turnId)) { + for (const entryId of fold.hiddenEntryIds) { + collapsedEntryIds.add(entryId); + } + } + } for (let index = 0; index < input.timelineEntries.length; index += 1) { const timelineEntry = input.timelineEntries[index]; if (!timelineEntry) { continue; } + if (collapsedEntryIds.has(timelineEntry.id)) { + continue; + } + + const turnFold = turnFoldsByFinalEntryId.get(timelineEntry.id); + if (turnFold) { + nextRows.push({ + kind: "turn-fold", + id: `turn-fold:${turnFold.turnId}`, + createdAt: timelineEntry.createdAt, + turnId: turnFold.turnId, + completionSummary: turnFold.completionSummary, + expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false, + hiddenCount: turnFold.hiddenEntryIds.size, + }); + } if (timelineEntry.kind === "work") { const groupedEntries = [timelineEntry.entry]; let cursor = index + 1; while (cursor < input.timelineEntries.length) { const nextEntry = input.timelineEntries[cursor]; - if (!nextEntry || nextEntry.kind !== "work") break; + if (!nextEntry || nextEntry.kind !== "work" || collapsedEntryIds.has(nextEntry.id)) break; groupedEntries.push(nextEntry.entry); cursor += 1; } @@ -235,6 +345,16 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "working": return a.createdAt === (b as typeof a).createdAt; + case "turn-fold": { + const bf = b as typeof a; + return ( + a.createdAt === bf.createdAt && + a.completionSummary === bf.completionSummary && + a.expanded === bf.expanded && + a.hiddenCount === bf.hiddenCount + ); + } + case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c2fb44c80a..a461265e38 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,6 +1,7 @@ import { type EnvironmentId, type MessageId, + type OrchestrationLatestTurn, type ServerProviderSkill, type TurnId, } from "@t3tools/contracts"; @@ -28,6 +29,8 @@ import { import ChatMarkdown from "../ChatMarkdown"; import { BotIcon, + ChevronDownIcon, + ChevronRightIcon, CheckIcon, CircleAlertIcon, EyeIcon, @@ -97,6 +100,7 @@ interface TimelineRowSharedState { onRevertUserMessage: (messageId: MessageId) => void; onImageExpand: (preview: ExpandedImagePreview) => void; onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onToggleTurnDetails: (turnId: TurnId) => void; } interface TimelineRowActivityState { @@ -109,6 +113,7 @@ const TimelineRowActivityCtx = createContext(null!); const TIMELINE_LIST_HEADER =
; const TIMELINE_LIST_FOOTER =
; const EMPTY_TIMELINE_SKILLS: ReadonlyArray> = []; +const EMPTY_TIMELINE_TURNS: ReadonlyArray = []; // --------------------------------------------------------------------------- // Props (public API) @@ -121,8 +126,7 @@ interface MessagesTimelineProps { activeTurnStartedAt: string | null; listRef: React.RefObject; timelineEntries: ReturnType; - completionDividerBeforeEntryId: string | null; - completionSummary: string | null; + turns?: ReadonlyArray; turnDiffSummaryByAssistantMessageId: Map; routeThreadKey: string; onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; @@ -150,8 +154,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ activeTurnStartedAt, listRef, timelineEntries, - completionDividerBeforeEntryId, - completionSummary, + turns = EMPTY_TIMELINE_TURNS, turnDiffSummaryByAssistantMessageId, routeThreadKey, onOpenTurnDiff, @@ -167,12 +170,27 @@ export const MessagesTimeline = memo(function MessagesTimeline({ skills = EMPTY_TIMELINE_SKILLS, onIsAtEndChange, }: MessagesTimelineProps) { + const [expandedTurnIds, setExpandedTurnIds] = useState>(new Set()); + useEffect(() => { + setExpandedTurnIds(new Set()); + }, [routeThreadKey]); + const onToggleTurnDetails = useCallback((turnId: TurnId) => { + setExpandedTurnIds((existing) => { + const next = new Set(existing); + if (next.has(turnId)) { + next.delete(turnId); + } else { + next.add(turnId); + } + return next; + }); + }, []); const rawRows = useMemo( () => deriveMessagesTimelineRows({ timelineEntries, - completionDividerBeforeEntryId, - completionSummary, + turns, + expandedTurnIds, isWorking, activeTurnInProgress, activeTurnId: activeTurnId ?? null, @@ -182,8 +200,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }), [ timelineEntries, - completionDividerBeforeEntryId, - completionSummary, + turns, + expandedTurnIds, isWorking, activeTurnInProgress, activeTurnId, @@ -231,6 +249,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRevertUserMessage, onImageExpand, onOpenTurnDiff, + onToggleTurnDetails, }), [ timestampFormat, @@ -243,6 +262,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRevertUserMessage, onImageExpand, onOpenTurnDiff, + onToggleTurnDetails, ], ); const activityState = useMemo( @@ -323,6 +343,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time data-message-role={row.kind === "message" ? row.message.role : undefined} > {row.kind === "work" ? : null} + {row.kind === "turn-fold" ? : null} {row.kind === "message" && row.message.role === "user" ? : null} {row.kind === "message" && row.message.role === "assistant" ? ( @@ -333,6 +354,25 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time ); }); +function TurnFoldTimelineRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const Icon = row.expanded ? ChevronDownIcon : ChevronRightIcon; + + return ( +
+ +
+ ); +} + function UserTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const userImages = row.message.attachments ?? []; diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 5feffe15b0..c19ce5c1c5 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -50,6 +50,7 @@ export const PROVIDER_OPTIONS: Array<{ export interface WorkLogEntry { id: string; createdAt: string; + turnId?: TurnId | null; label: string; detail?: string; command?: string; @@ -542,6 +543,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo const entry: DerivedWorkLogEntry = { id: activity.id, createdAt: activity.createdAt, + turnId: activity.turnId, label: taskLabel || activity.summary, tone: activity.kind === "task.progress" diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 7d995b5ea7..085b22d561 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -183,6 +183,7 @@ function mapMessage(environmentId: EnvironmentId, message: OrchestrationMessage) id: message.id, role: message.role, text: message.text, + ...(message.assistantPhase !== undefined ? { assistantPhase: message.assistantPhase } : {}), turnId: message.turnId, createdAt: message.createdAt, streaming: message.streaming, @@ -254,6 +255,7 @@ function mapThread(thread: OrchestrationThread, environmentId: EnvironmentId): T archivedAt: thread.archivedAt, updatedAt: thread.updatedAt, latestTurn: thread.latestTurn, + turns: [...(thread.turns ?? [])], pendingSourceProposedPlan: thread.latestTurn?.sourceProposedPlan, branch: thread.branch, worktreePath: thread.worktreePath, @@ -885,6 +887,19 @@ function buildLatestTurn(params: { }; } +function upsertThreadTurn( + turns: Thread["turns"], + turn: Thread["latestTurn"], +): NonNullable { + const existingTurns = turns ?? []; + if (turn === null) { + return existingTurns; + } + return [...existingTurns.filter((entry) => entry.turnId !== turn.turnId), turn].toSorted( + (left, right) => left.requestedAt.localeCompare(right.requestedAt), + ); +} + function rebindTurnDiffSummariesForAssistantMessage( turnDiffSummaries: ReadonlyArray, turnId: TurnId, @@ -1272,6 +1287,7 @@ function applyEnvironmentOrchestrationEvent( branch: event.payload.branch, worktreePath: event.payload.worktreePath, latestTurn: null, + turns: [], createdAt: event.payload.createdAt, updatedAt: event.payload.updatedAt, archivedAt: null, @@ -1353,17 +1369,19 @@ function applyEnvironmentOrchestrationEvent( if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) { return thread; } + const interruptedTurn = buildLatestTurn({ + previous: latestTurn, + turnId: event.payload.turnId, + state: "interrupted", + requestedAt: latestTurn.requestedAt, + startedAt: latestTurn.startedAt ?? event.payload.createdAt, + completedAt: latestTurn.completedAt ?? event.payload.createdAt, + assistantMessageId: latestTurn.assistantMessageId, + }); return { ...thread, - latestTurn: buildLatestTurn({ - previous: latestTurn, - turnId: event.payload.turnId, - state: "interrupted", - requestedAt: latestTurn.requestedAt, - startedAt: latestTurn.startedAt ?? event.payload.createdAt, - completedAt: latestTurn.completedAt ?? event.payload.createdAt, - assistantMessageId: latestTurn.assistantMessageId, - }), + latestTurn: interruptedTurn, + turns: upsertThreadTurn(thread.turns, interruptedTurn), updatedAt: event.occurredAt, }; }); @@ -1375,6 +1393,9 @@ function applyEnvironmentOrchestrationEvent( id: event.payload.messageId, role: event.payload.role, text: event.payload.text, + ...(event.payload.assistantPhase !== undefined + ? { assistantPhase: event.payload.assistantPhase } + : {}), ...(event.payload.attachments !== undefined ? { attachments: event.payload.attachments } : {}), @@ -1396,6 +1417,9 @@ function applyEnvironmentOrchestrationEvent( ? message.text : entry.text, streaming: message.streaming, + ...(message.assistantPhase !== undefined + ? { assistantPhase: message.assistantPhase } + : {}), ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), ...(message.streaming ? entry.completedAt !== undefined @@ -1455,16 +1479,14 @@ function applyEnvironmentOrchestrationEvent( messages: cappedMessages, turnDiffSummaries, latestTurn, + turns: upsertThreadTurn(thread.turns, latestTurn), updatedAt: event.occurredAt, }; }); case "thread.session-set": - return updateThreadState(state, event.payload.threadId, (thread) => ({ - ...thread, - session: mapSession(event.payload.session), - error: sanitizeThreadErrorMessage(event.payload.session.lastError), - latestTurn: + return updateThreadState(state, event.payload.threadId, (thread) => { + const latestTurn = event.payload.session.status === "running" && event.payload.session.activeTurnId !== null ? buildLatestTurn({ previous: thread.latestTurn, @@ -1485,9 +1507,16 @@ function applyEnvironmentOrchestrationEvent( : null, sourceProposedPlan: thread.pendingSourceProposedPlan, }) - : thread.latestTurn, - updatedAt: event.occurredAt, - })); + : thread.latestTurn; + return { + ...thread, + session: mapSession(event.payload.session), + error: sanitizeThreadErrorMessage(event.payload.session.lastError), + latestTurn, + turns: upsertThreadTurn(thread.turns, latestTurn), + updatedAt: event.occurredAt, + }; + }); case "thread.session-stop-requested": return updateThreadState(state, event.payload.threadId, (thread) => @@ -1569,6 +1598,7 @@ function applyEnvironmentOrchestrationEvent( ...thread, turnDiffSummaries, latestTurn, + turns: upsertThreadTurn(thread.turns, latestTurn), updatedAt: event.occurredAt, }; }); @@ -1606,6 +1636,7 @@ function applyEnvironmentOrchestrationEvent( messages, proposedPlans, activities, + turns: thread.turns?.filter((turn) => retainedTurnIds.has(turn.turnId)) ?? [], pendingSourceProposedPlan: undefined, latestTurn: latestCheckpoint === null diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index c2e4b235e2..c7196cfa33 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + AssistantMessagePhase, ModelSelection, OrchestrationLatestTurn, OrchestrationProposedPlanId, @@ -47,6 +48,7 @@ export interface ChatMessage { id: MessageId; role: "user" | "assistant" | "system"; text: string; + assistantPhase?: AssistantMessagePhase; attachments?: ChatAttachment[]; turnId?: TurnId | null; createdAt: string; @@ -110,6 +112,7 @@ export interface Thread { archivedAt: string | null; updatedAt?: string | undefined; latestTurn: OrchestrationLatestTurn | null; + turns?: OrchestrationLatestTurn[]; pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"]; branch: string | null; worktreePath: string | null; diff --git a/packages/client-runtime/src/threadDetailReducer.test.ts b/packages/client-runtime/src/threadDetailReducer.test.ts index 56a2d64dcb..246c636182 100644 --- a/packages/client-runtime/src/threadDetailReducer.test.ts +++ b/packages/client-runtime/src/threadDetailReducer.test.ts @@ -31,6 +31,7 @@ const baseThread: OrchestrationThread = { branch: null, worktreePath: null, latestTurn: null, + turns: [], createdAt: "2026-04-01T00:00:00.000Z", updatedAt: "2026-04-01T00:00:00.000Z", archivedAt: null, diff --git a/packages/client-runtime/src/threadDetailReducer.ts b/packages/client-runtime/src/threadDetailReducer.ts index 125f39428a..dfa4dc1344 100644 --- a/packages/client-runtime/src/threadDetailReducer.ts +++ b/packages/client-runtime/src/threadDetailReducer.ts @@ -52,6 +52,19 @@ const activityOrder = O.combineAll([ O.mapInput(O.String, (a) => a.id), ]); +function upsertTurn( + turns: OrchestrationThread["turns"] | undefined, + turn: OrchestrationLatestTurn | null, +): NonNullable { + const existingTurns = turns ?? []; + if (turn === null) { + return existingTurns; + } + return [...existingTurns.filter((entry) => entry.turnId !== turn.turnId), turn].toSorted( + (left, right) => left.requestedAt.localeCompare(right.requestedAt), + ); +} + /** * Apply a single orchestration event to an `OrchestrationThread`, returning * the updated thread, a deletion signal, or an "unchanged" marker when the @@ -87,6 +100,7 @@ export function applyThreadDetailEvent( branch: event.payload.branch, worktreePath: event.payload.worktreePath, latestTurn: null, + turns: [], createdAt: event.payload.createdAt, updatedAt: event.payload.updatedAt, archivedAt: null, @@ -179,16 +193,18 @@ export function applyThreadDetailEvent( if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) { return { kind: "unchanged" }; } + const interruptedTurn = { + ...latestTurn, + state: "interrupted" as const, + startedAt: latestTurn.startedAt ?? event.payload.createdAt, + completedAt: latestTurn.completedAt ?? event.payload.createdAt, + }; return { kind: "updated", thread: { ...thread, - latestTurn: { - ...latestTurn, - state: "interrupted", - startedAt: latestTurn.startedAt ?? event.payload.createdAt, - completedAt: latestTurn.completedAt ?? event.payload.createdAt, - }, + latestTurn: interruptedTurn, + turns: upsertTurn(thread.turns, interruptedTurn), updatedAt: event.occurredAt, }, }; @@ -200,6 +216,9 @@ export function applyThreadDetailEvent( id: event.payload.messageId, role: event.payload.role, text: event.payload.text, + ...(event.payload.assistantPhase !== undefined + ? { assistantPhase: event.payload.assistantPhase } + : {}), ...(event.payload.attachments !== undefined ? { attachments: event.payload.attachments } : {}), @@ -222,6 +241,9 @@ export function applyThreadDetailEvent( ? message.text : entry.text, streaming: message.streaming, + ...(message.assistantPhase !== undefined + ? { assistantPhase: message.assistantPhase } + : {}), ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), ...(message.streaming ? {} : { updatedAt: message.updatedAt }), ...(message.attachments !== undefined @@ -280,6 +302,7 @@ export function applyThreadDetailEvent( messages: cappedMessages, checkpoints, latestTurn, + turns: upsertTurn(thread.turns, latestTurn), updatedAt: event.occurredAt, }, }; @@ -314,6 +337,7 @@ export function applyThreadDetailEvent( ...thread, session: event.payload.session, latestTurn, + turns: upsertTurn(thread.turns, latestTurn), updatedAt: event.occurredAt, }, }; @@ -394,7 +418,13 @@ export function applyThreadDetailEvent( return { kind: "updated", - thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt }, + thread: { + ...thread, + checkpoints, + latestTurn, + turns: upsertTurn(thread.turns, latestTurn), + updatedAt: event.occurredAt, + }, }; } @@ -435,6 +465,7 @@ export function applyThreadDetailEvent( messages, proposedPlans, activities, + turns: thread.turns?.filter((turn) => retainedTurnIds.has(turn.turnId)) ?? [], latestTurn: latestCheckpoint === null ? null diff --git a/packages/client-runtime/src/threadDetailState.test.ts b/packages/client-runtime/src/threadDetailState.test.ts index df482ce1f6..e51d8c148c 100644 --- a/packages/client-runtime/src/threadDetailState.test.ts +++ b/packages/client-runtime/src/threadDetailState.test.ts @@ -47,6 +47,7 @@ const BASE_THREAD: OrchestrationThread = { branch: null, worktreePath: null, latestTurn: null, + turns: [], createdAt: "2026-04-01T00:00:00.000Z", updatedAt: "2026-04-01T00:00:00.000Z", archivedAt: null, @@ -160,6 +161,16 @@ describe("createThreadDetailManager", () => { completedAt: "2026-04-01T01:00:00.000Z", assistantMessageId: MessageId.make("message-1"), }, + turns: [ + { + turnId: TurnId.make("turn-1"), + state: "completed", + requestedAt: "2026-04-01T01:00:00.000Z", + startedAt: "2026-04-01T01:00:00.000Z", + completedAt: "2026-04-01T01:00:00.000Z", + assistantMessageId: MessageId.make("message-1"), + }, + ], messages: [ { id: MessageId.make("message-1"), diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index 614ea5131f..42d2afc55b 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -20,6 +20,9 @@ export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximu export const IsoDateTime = Schema.String; export type IsoDateTime = typeof IsoDateTime.Type; +export const AssistantMessagePhase = Schema.Literals(["commentary", "final_answer"]); +export type AssistantMessagePhase = typeof AssistantMessagePhase.Type; + /** * Construct a branded identifier. Enforces non-empty trimmed strings */ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 401928171c..54aaae0be0 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -7,6 +7,7 @@ import * as Struct from "effect/Struct"; import { ProviderOptionSelections } from "./model.ts"; import { RepositoryIdentity } from "./environment.ts"; import { + AssistantMessagePhase, ApprovalRequestId, CheckpointRef, CommandId, @@ -217,6 +218,7 @@ export const OrchestrationMessage = Schema.Struct({ id: MessageId, role: OrchestrationMessageRole, text: Schema.String, + assistantPhase: Schema.optional(AssistantMessagePhase), attachments: Schema.optional(Schema.Array(ChatAttachment)), turnId: Schema.NullOr(TurnId), streaming: Schema.Boolean, @@ -342,6 +344,9 @@ export const OrchestrationThread = Schema.Struct({ branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), latestTurn: Schema.NullOr(OrchestrationLatestTurn), + turns: Schema.optional(Schema.Array(OrchestrationLatestTurn)).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), createdAt: IsoDateTime, updatedAt: IsoDateTime, archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))), @@ -709,6 +714,7 @@ const ThreadMessageAssistantCompleteCommand = Schema.Struct({ commandId: CommandId, threadId: ThreadId, messageId: MessageId, + assistantPhase: Schema.optional(AssistantMessagePhase), turnId: Schema.optional(TurnId), createdAt: IsoDateTime, }); @@ -883,6 +889,7 @@ export const ThreadMessageSentPayload = Schema.Struct({ messageId: MessageId, role: OrchestrationMessageRole, text: Schema.String, + assistantPhase: Schema.optional(AssistantMessagePhase), attachments: Schema.optional(Schema.Array(ChatAttachment)), turnId: Schema.NullOr(TurnId), streaming: Schema.Boolean, diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index 5032dc4eb4..fa7970d55e 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + AssistantMessagePhase, EventId, IsoDateTime, NonNegativeInt, @@ -402,6 +403,7 @@ export type TurnDiffUpdatedPayload = typeof TurnDiffUpdatedPayload.Type; export const ItemLifecyclePayload = Schema.Struct({ itemType: CanonicalItemType, + messagePhase: Schema.optional(AssistantMessagePhase), status: Schema.optional(RuntimeItemStatus), title: Schema.optional(TrimmedNonEmptyStringSchema), detail: Schema.optional(TrimmedNonEmptyStringSchema),