feat: branching messages

This commit is contained in:
Yash Singh committed 2026-05-04 02:40:16 -05:00
1 parent 658ef9cd6b
commit b0b1fb4f2c
8 files changed
+307 -11

No files matched your search

@@ -172,7 +172,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
}
describe("decideOrchestrationCommand thread.branch", () => {
it("creates a branched thread and copies transcript messages as new frozen messages", async () => {
it("creates a branched thread and copies transcript messages and activities", async () => {
const readModel = await seedReadModel();
const decided = await Effect.runPromise(
decideOrchestrationCommand({
@@ -259,4 +259,127 @@ describe("decideOrchestrationCommand thread.branch", () => {
expect(branchedThread?.activities.map((activity) => activity.summary)).toEqual(["Read file"]);
expect(branchedThread?.activities.every((activity) => activity.turnId === null)).toBe(true);
});
it("branches through a selected completed assistant message", async () => {
const readModel = await projectEvents(await seedReadModel(), [
{
eventId: asEventId("evt-message-assistant-complete"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:02:30.000Z",
commandId: asCommandId("cmd-message-assistant-complete"),
causationEventId: null,
correlationId: asCommandId("cmd-message-assistant-complete"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-assistant"),
role: "assistant",
text: "",
turnId: asTurnId("turn-source"),
streaming: false,
createdAt: "2026-01-01T00:02:30.000Z",
updatedAt: "2026-01-01T00:02:30.000Z",
},
},
{
eventId: asEventId("evt-later-message-user"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:04:00.000Z",
commandId: asCommandId("cmd-later-message-user"),
causationEventId: null,
correlationId: asCommandId("cmd-later-message-user"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-later-user"),
role: "user",
text: "later prompt",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:04:00.000Z",
updatedAt: "2026-01-01T00:04:00.000Z",
},
},
{
eventId: asEventId("evt-later-activity-tool"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.activity-appended",
occurredAt: "2026-01-01T00:05:00.000Z",
commandId: asCommandId("cmd-later-activity-tool"),
causationEventId: null,
correlationId: asCommandId("cmd-later-activity-tool"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
activity: {
id: asEventId("activity-later-tool"),
tone: "tool",
kind: "tool.completed",
summary: "Edited file",
payload: {
toolCallId: "tool-call-later",
detail: "edit src/index.ts",
},
turnId: asTurnId("turn-later"),
sequence: 20,
createdAt: "2026-01-01T00:05:00.000Z",
},
},
},
{
eventId: asEventId("evt-later-message-assistant"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:06:00.000Z",
commandId: asCommandId("cmd-later-message-assistant"),
causationEventId: null,
correlationId: asCommandId("cmd-later-message-assistant"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-later-assistant"),
role: "assistant",
text: "later response",
turnId: asTurnId("turn-later"),
streaming: false,
createdAt: "2026-01-01T00:06:00.000Z",
updatedAt: "2026-01-01T00:06:00.000Z",
},
},
]);
const decided = await Effect.runPromise(
decideOrchestrationCommand({
readModel,
command: {
type: "thread.branch",
commandId: asCommandId("cmd-thread-branch-message"),
sourceThreadId: asThreadId("thread-source"),
sourceMessageId: asMessageId("message-assistant"),
threadId: asThreadId("thread-branch-message"),
createdAt: "2026-01-01T01:00:00.000Z",
},
}),
);
const events = Array.isArray(decided) ? decided : [decided];
const branchedReadModel = await projectEvents(readModel, events);
const branchedThread = branchedReadModel.threads.find(
(thread) => thread.id === asThreadId("thread-branch-message"),
);
expect(branchedThread?.messages.map((message) => message.text)).toEqual([
"hello",
"partial response",
]);
expect(branchedThread?.activities.map((activity) => activity.summary)).toEqual(["Read file"]);
expect(branchedThread?.messages.every((message) => message.turnId === null)).toBe(true);
expect(branchedThread?.activities.every((activity) => activity.turnId === null)).toBe(true);
});
});
+42 -2
View File
@@ -260,6 +260,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
threadId: command.threadId,
});
const sourceMessageIndex =
command.sourceMessageId === undefined
? -1
: sourceThread.messages.findIndex((message) => message.id === command.sourceMessageId);
if (command.sourceMessageId !== undefined && sourceMessageIndex === -1) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Message '${command.sourceMessageId}' does not exist on source thread '${command.sourceThreadId}'.`,
});
}
const sourceMessage =
sourceMessageIndex >= 0 ? sourceThread.messages[sourceMessageIndex] : undefined;
if (sourceMessage !== undefined && sourceMessage.role !== "assistant") {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Message '${sourceMessage.id}' is not an assistant message and cannot be used as a branch point.`,
});
}
if (sourceMessage !== undefined && sourceMessage.streaming) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Assistant message '${sourceMessage.id}' is still streaming and cannot be used as a branch point.`,
});
}
const threadCreatedEvent: PlannedOrchestrationEvent = {
...withEventBase({
@@ -284,14 +308,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
const copiedThreadEvents: PlannedOrchestrationEvent[] = [];
const sourceMessages =
sourceMessageIndex >= 0
? sourceThread.messages.slice(0, sourceMessageIndex + 1)
: sourceThread.messages;
const includedTurnIds = new Set(
sourceMessages.flatMap((message) => (message.turnId === null ? [] : [message.turnId])),
);
const sourceActivities =
sourceMessage === undefined
? sourceThread.activities
: sourceThread.activities.filter((activity) => {
if (activity.turnId !== null && includedTurnIds.has(activity.turnId)) {
return true;
}
return activity.createdAt <= sourceMessage.updatedAt;
});
const sourceEntries = [
...sourceThread.messages.map((message, sourceIndex) => ({
...sourceMessages.map((message, sourceIndex) => ({
kind: "message" as const,
createdAt: message.createdAt,
sourceIndex,
message,
})),
...sourceThread.activities.map((activity, sourceIndex) => ({
...sourceActivities.map((activity, sourceIndex) => ({
kind: "activity" as const,
createdAt: activity.createdAt,
sourceIndex,
+57
View File
@@ -3489,6 +3489,62 @@ export default function ChatView(props: ChatViewProps) {
}
void onRevertToTurnCountRef.current(targetTurnCount);
}, []);
const activeThreadValueRef = useRef(activeThread);
activeThreadValueRef.current = activeThread;
const onBranchAssistantMessage = useCallback(
async (messageId: MessageId) => {
const thread = activeThreadValueRef.current;
if (!thread || !isServerThread) {
return;
}
if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
setThreadError(
thread.id,
`Reconnect ${activeEnvironmentUnavailableLabel} before branching this message.`,
);
return;
}
const api = readEnvironmentApi(thread.environmentId);
if (!api) {
setThreadError(thread.id, "Thread API unavailable.");
return;
}
const branchThreadId = newThreadId();
try {
await api.orchestration.dispatchCommand({
type: "thread.branch",
commandId: newCommandId(),
sourceThreadId: thread.id,
sourceMessageId: messageId,
threadId: branchThreadId,
title: `${thread.title} (Branched)`,
createdAt: new Date().toISOString(),
});
await navigate({
to: "/$environmentId/$threadId",
params: {
environmentId: thread.environmentId,
threadId: branchThreadId,
},
});
} catch (error) {
setThreadError(
thread.id,
error instanceof Error ? error.message : "Failed to branch from this message.",
);
}
},
[
activeEnvironmentUnavailable,
activeEnvironmentUnavailableLabel,
isServerThread,
navigate,
setThreadError,
],
);
// Empty state: no active thread
if (!activeThread) {
@@ -3568,6 +3624,7 @@ export default function ChatView(props: ChatViewProps) {
onOpenTurnDiff={onOpenTurnDiff}
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
onRevertUserMessage={onRevertUserMessage}
onBranchAssistantMessage={onBranchAssistantMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
@@ -62,6 +62,7 @@ function buildProps() {
onOpenTurnDiff: vi.fn(),
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: vi.fn(),
onBranchAssistantMessage: vi.fn(),
isRevertingCheckpoint: false,
onImageExpand: vi.fn(),
activeThreadEnvironmentId: EnvironmentId.make("environment-local"),
@@ -88,6 +88,7 @@ function buildProps() {
onOpenTurnDiff: () => {},
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: () => {},
onBranchAssistantMessage: () => {},
isRevertingCheckpoint: false,
onImageExpand: () => {},
activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
@@ -186,4 +187,44 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
});
it("renders assistant branch action next to the completed assistant copy action", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-user",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-user"),
role: "user",
text: "do the thing",
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
{
id: "entry-assistant",
kind: "message",
createdAt: "2026-03-17T19:12:30.000Z",
message: {
id: MessageId.make("message-assistant"),
role: "assistant",
text: "done",
turnId: "turn-1" as never,
createdAt: "2026-03-17T19:12:30.000Z",
completedAt: "2026-03-17T19:12:35.000Z",
streaming: false,
},
},
]}
/>,
);
expect(markup).toContain('aria-label="Copy link"');
expect(markup).toContain('aria-label="Branch from message"');
});
});
@@ -20,6 +20,7 @@ import {
CheckIcon,
CircleAlertIcon,
EyeIcon,
GitBranchIcon,
GlobeIcon,
HammerIcon,
type LucideIcon,
@@ -82,6 +83,7 @@ interface TimelineRowSharedState {
workspaceRoot: string | undefined;
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onBranchAssistantMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}
@@ -106,6 +108,7 @@ interface MessagesTimelineProps {
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
revertTurnCountByUserMessageId: Map<MessageId, number>;
onRevertUserMessage: (messageId: MessageId) => void;
onBranchAssistantMessage: (messageId: MessageId) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
activeThreadEnvironmentId: EnvironmentId;
@@ -134,6 +137,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
revertTurnCountByUserMessageId,
onRevertUserMessage,
onBranchAssistantMessage,
isRevertingCheckpoint,
onImageExpand,
activeThreadEnvironmentId,
@@ -205,6 +209,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
activeThreadEnvironmentId,
onRevertUserMessage,
onBranchAssistantMessage,
onImageExpand,
onOpenTurnDiff,
}),
@@ -221,6 +226,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
activeThreadEnvironmentId,
onRevertUserMessage,
onBranchAssistantMessage,
onImageExpand,
onOpenTurnDiff,
],
@@ -390,6 +396,8 @@ function TimelineRowContent({ row }: { row: TimelineRow }) {
showCopyButton: row.showAssistantCopyButton,
streaming: row.message.streaming || assistantTurnStillInProgress,
});
const showAssistantBranchButton =
row.showAssistantCopyButton && !row.message.streaming && !assistantTurnStillInProgress;
return (
<>
{row.showCompletionDivider && (
@@ -429,14 +437,37 @@ function TimelineRowContent({ row }: { row: TimelineRow }) {
)
)}
</p>
{assistantCopyState.visible ? (
<div className="flex items-center opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
<MessageCopyButton
text={assistantCopyState.text ?? ""}
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
{assistantCopyState.visible || showAssistantBranchButton ? (
<div className="flex items-center gap-1 opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
{assistantCopyState.visible ? (
<MessageCopyButton
text={assistantCopyState.text ?? ""}
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
) : null}
{showAssistantBranchButton ? (
<Tooltip>
<TooltipTrigger
render={
<Button
aria-label="Branch from message"
onClick={() => ctx.onBranchAssistantMessage(row.message.id)}
type="button"
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
}
>
<GitBranchIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup>
<p>Branch from this message</p>
</TooltipPopup>
</Tooltip>
) : null}
</div>
) : null}
</div>
@@ -347,6 +347,7 @@ it.effect("decodes thread branch commands", () =>
type: "thread.branch",
commandId: "cmd-branch-1",
sourceThreadId: "thread-source",
sourceMessageId: "message-source",
threadId: "thread-branch",
title: "Source (Branched)",
createdAt: "2026-01-01T00:00:00.000Z",
@@ -354,6 +355,7 @@ it.effect("decodes thread branch commands", () =>
assert.strictEqual(branch.type, "thread.branch");
assert.strictEqual(branch.sourceThreadId, "thread-source");
assert.strictEqual(branch.sourceMessageId, "message-source");
assert.strictEqual(branch.threadId, "thread-branch");
}),
);
+1
View File
@@ -493,6 +493,7 @@ const ThreadBranchCommand = Schema.Struct({
type: Schema.Literal("thread.branch"),
commandId: CommandId,
sourceThreadId: ThreadId,
sourceMessageId: Schema.optional(MessageId),
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
createdAt: IsoDateTime,