fold completed turn work in chat history

This commit is contained in:
Theo Browne committed 2026-06-04 18:37:39 -07:00
1 parent 65f080aeef
commit 11849617ae
29 files changed
+620 -69

No files matched your search

@@ -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,
@@ -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")],
);
}
}),
);
@@ -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,
@@ -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 () => {
@@ -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) {
+1
View File
@@ -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,
@@ -86,6 +86,7 @@ describe("orchestration projector", () => {
branch: null,
worktreePath: null,
latestTurn: null,
turns: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -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 }
: {}),
@@ -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");
}),
);
});
@@ -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",
@@ -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) =>
@@ -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"));
}),
);
});
@@ -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
`;
});
@@ -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,
@@ -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");
}),
);
@@ -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 } : {}),
+8 -30
View File
@@ -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}
@@ -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: [
@@ -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<TimelineEntry>) {
const lastAssistantMessageIdByResponseKey = new Map<string, string>();
const finalAnswerResponseKeys = new Set<string>();
let nullTurnResponseIndex = 0;
for (const timelineEntry of timelineEntries) {
@@ -104,15 +114,90 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
const responseKey = message.turnId
? `turn:${message.turnId}`
: `unkeyed:${nullTurnResponseIndex}`;
if (message.assistantPhase === "final_answer") {
lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
finalAnswerResponseKeys.add(responseKey);
continue;
}
if (finalAnswerResponseKeys.has(responseKey)) {
continue;
}
lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
}
return new Set(lastAssistantMessageIdByResponseKey.values());
}
interface TurnFold {
readonly turnId: TurnId;
readonly finalEntryId: string;
readonly hiddenEntryIds: ReadonlySet<string>;
readonly completionSummary: string;
}
function deriveTurnFolds(
timelineEntries: ReadonlyArray<TimelineEntry>,
turns: ReadonlyArray<OrchestrationLatestTurn>,
): ReadonlyMap<string, TurnFold> {
const assistantEntriesByTurnId = new Map<
TurnId,
Array<Extract<TimelineEntry, { kind: "message" }>>
>();
const workEntryIdsByTurnId = new Map<TurnId, string[]>();
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<string, TurnFold>();
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<string>(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<TimelineEntry>;
completionDividerBeforeEntryId: string | null;
turns?: ReadonlyArray<OrchestrationLatestTurn>;
expandedTurnIds?: ReadonlySet<TurnId>;
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<string>();
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;
@@ -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<TimelineRowActivityState>(null!);
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
const EMPTY_TIMELINE_TURNS: ReadonlyArray<OrchestrationLatestTurn> = [];
// ---------------------------------------------------------------------------
// Props (public API)
@@ -121,8 +126,7 @@ interface MessagesTimelineProps {
activeTurnStartedAt: string | null;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
turns?: ReadonlyArray<OrchestrationLatestTurn>;
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
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<ReadonlySet<TurnId>>(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<TimelineRowActivityState>(
@@ -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" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "assistant" ? (
<AssistantTimelineRow row={row} />
@@ -333,6 +354,25 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
);
});
function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
const ctx = use(TimelineRowCtx);
const Icon = row.expanded ? ChevronDownIcon : ChevronRightIcon;
return (
<div className="border-b border-border/60 pb-2">
<button
type="button"
className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
aria-expanded={row.expanded}
onClick={() => ctx.onToggleTurnDetails(row.turnId)}
>
<span>{row.completionSummary}</span>
<Icon className="size-4" />
</button>
</div>
);
}
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const ctx = use(TimelineRowCtx);
const userImages = row.message.attachments ?? [];
+2
View File
@@ -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"
+48 -17
View File
@@ -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<Thread["turns"]> {
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<TurnDiffSummary>,
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
+3
View File
@@ -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;
@@ -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,
@@ -52,6 +52,19 @@ const activityOrder = O.combineAll<OrchestrationThreadActivity>([
O.mapInput(O.String, (a) => a.id),
]);
function upsertTurn(
turns: OrchestrationThread["turns"] | undefined,
turn: OrchestrationLatestTurn | null,
): NonNullable<OrchestrationThread["turns"]> {
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
@@ -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"),
+3
View File
@@ -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
*/
+7
View File
@@ -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,
@@ -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),