Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0b1fb4f2c | ||
|
|
658ef9cd6b |
No files matched your search
@@ -0,0 +1,385 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const asCommandId = (value: string): CommandId => CommandId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
|
||||
async function projectEvents(
|
||||
readModel: OrchestrationReadModel,
|
||||
events: ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
|
||||
): Promise<OrchestrationReadModel> {
|
||||
let next = readModel;
|
||||
let sequence = readModel.snapshotSequence;
|
||||
for (const event of events) {
|
||||
sequence += 1;
|
||||
const sequencedEvent = {
|
||||
...event,
|
||||
sequence,
|
||||
} as OrchestrationEvent;
|
||||
next = await Effect.runPromise(projectEvent(next, sequencedEvent));
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
async function seedReadModel(): Promise<OrchestrationReadModel> {
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
return projectEvents(createEmptyReadModel(createdAt), [
|
||||
{
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-branch"),
|
||||
type: "project.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: asCommandId("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-branch"),
|
||||
title: "Project Branch",
|
||||
workspaceRoot: "/tmp/project-branch",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
{
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-source"),
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: asCommandId("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-source"),
|
||||
projectId: asProjectId("project-branch"),
|
||||
title: "Source Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: "feature/source",
|
||||
worktreePath: "/tmp/project-branch-worktree",
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
{
|
||||
eventId: asEventId("evt-message-user"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-source"),
|
||||
type: "thread.message-sent",
|
||||
occurredAt: "2026-01-01T00:01:00.000Z",
|
||||
commandId: asCommandId("cmd-message-user"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-message-user"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-source"),
|
||||
messageId: asMessageId("message-user"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-source-00000000-0000-4000-8000-000000000001",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 123,
|
||||
},
|
||||
],
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:01:00.000Z",
|
||||
updatedAt: "2026-01-01T00:01:00.000Z",
|
||||
},
|
||||
},
|
||||
{
|
||||
eventId: asEventId("evt-message-assistant"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-source"),
|
||||
type: "thread.message-sent",
|
||||
occurredAt: "2026-01-01T00:02:00.000Z",
|
||||
commandId: asCommandId("cmd-message-assistant"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-message-assistant"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-source"),
|
||||
messageId: asMessageId("message-assistant"),
|
||||
role: "assistant",
|
||||
text: "partial response",
|
||||
turnId: asTurnId("turn-source"),
|
||||
streaming: true,
|
||||
createdAt: "2026-01-01T00:02:00.000Z",
|
||||
updatedAt: "2026-01-01T00:02:00.000Z",
|
||||
},
|
||||
},
|
||||
{
|
||||
eventId: asEventId("evt-activity-tool"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-source"),
|
||||
type: "thread.activity-appended",
|
||||
occurredAt: "2026-01-01T00:03:00.000Z",
|
||||
commandId: asCommandId("cmd-activity-tool"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-activity-tool"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-source"),
|
||||
activity: {
|
||||
id: asEventId("activity-tool-source"),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Read file",
|
||||
payload: {
|
||||
toolCallId: "tool-call-source",
|
||||
detail: "read README.md",
|
||||
requestId: "source-request-id",
|
||||
},
|
||||
turnId: asTurnId("turn-source"),
|
||||
sequence: 10,
|
||||
createdAt: "2026-01-01T00:03:00.000Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
describe("decideOrchestrationCommand thread.branch", () => {
|
||||
it("creates a branched thread and copies transcript messages and activities", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
const decided = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
readModel,
|
||||
command: {
|
||||
type: "thread.branch",
|
||||
commandId: asCommandId("cmd-thread-branch"),
|
||||
sourceThreadId: asThreadId("thread-source"),
|
||||
threadId: asThreadId("thread-branch"),
|
||||
createdAt: "2026-01-01T01:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const events = Array.isArray(decided) ? decided : [decided];
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"thread.created",
|
||||
"thread.message-sent",
|
||||
"thread.message-sent",
|
||||
"thread.activity-appended",
|
||||
]);
|
||||
|
||||
const created = events[0];
|
||||
expect(created?.type).toBe("thread.created");
|
||||
if (created?.type !== "thread.created") {
|
||||
throw new Error("Expected first event to create a thread.");
|
||||
}
|
||||
expect(created.payload).toMatchObject({
|
||||
threadId: asThreadId("thread-branch"),
|
||||
projectId: asProjectId("project-branch"),
|
||||
title: "Source Thread (Branched)",
|
||||
runtimeMode: "approval-required",
|
||||
branch: "feature/source",
|
||||
worktreePath: "/tmp/project-branch-worktree",
|
||||
});
|
||||
|
||||
const copiedMessages = events.filter((event) => event.type === "thread.message-sent");
|
||||
expect(copiedMessages.every((event) => event.type === "thread.message-sent")).toBe(true);
|
||||
for (const event of copiedMessages) {
|
||||
if (event.type !== "thread.message-sent") {
|
||||
throw new Error("Expected copied event to be a message.");
|
||||
}
|
||||
expect(event.payload.threadId).toBe(asThreadId("thread-branch"));
|
||||
expect(event.payload.turnId).toBeNull();
|
||||
expect(event.payload.streaming).toBe(false);
|
||||
expect(event.payload.messageId).not.toBe(asMessageId("message-user"));
|
||||
expect(event.payload.messageId).not.toBe(asMessageId("message-assistant"));
|
||||
expect(event.payload.attachments).toBeUndefined();
|
||||
expect(event.causationEventId).toBe(created.eventId);
|
||||
}
|
||||
|
||||
const copiedActivity = events.find((event) => event.type === "thread.activity-appended");
|
||||
expect(copiedActivity?.type).toBe("thread.activity-appended");
|
||||
if (copiedActivity?.type !== "thread.activity-appended") {
|
||||
throw new Error("Expected copied tool activity.");
|
||||
}
|
||||
expect(copiedActivity.payload.threadId).toBe(asThreadId("thread-branch"));
|
||||
expect(copiedActivity.payload.activity.id).not.toBe(asEventId("activity-tool-source"));
|
||||
expect(copiedActivity.payload.activity.turnId).toBeNull();
|
||||
expect(copiedActivity.payload.activity).toMatchObject({
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Read file",
|
||||
payload: {
|
||||
toolCallId: "tool-call-source",
|
||||
detail: "read README.md",
|
||||
},
|
||||
});
|
||||
expect(copiedActivity.payload.activity.payload).not.toMatchObject({
|
||||
requestId: "source-request-id",
|
||||
});
|
||||
expect(copiedActivity.causationEventId).toBe(created.eventId);
|
||||
|
||||
const branchedReadModel = await projectEvents(readModel, events);
|
||||
const branchedThread = branchedReadModel.threads.find(
|
||||
(thread) => thread.id === asThreadId("thread-branch"),
|
||||
);
|
||||
expect(branchedThread?.messages.map((message) => message.text)).toEqual([
|
||||
"hello",
|
||||
"partial response",
|
||||
]);
|
||||
expect(branchedThread?.messages.every((message) => message.turnId === null)).toBe(true);
|
||||
expect(branchedThread?.messages.every((message) => !message.streaming)).toBe(true);
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
@@ -18,6 +20,15 @@ import {
|
||||
import { projectEvent } from "./projector.ts";
|
||||
|
||||
const nowIso = () => new Date().toISOString();
|
||||
const timestampOffsetIso = (baseIso: string, offsetMs: number) =>
|
||||
new Date(new Date(baseIso).getTime() + offsetMs).toISOString();
|
||||
const sanitizeCopiedActivityPayload = (payload: unknown): unknown => {
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
||||
return payload;
|
||||
}
|
||||
const { requestId: _requestId, ...rest } = payload as Record<string, unknown>;
|
||||
return rest;
|
||||
};
|
||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
||||
aggregateKind: "thread",
|
||||
@@ -233,6 +244,168 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.branch": {
|
||||
const sourceThread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.sourceThreadId,
|
||||
});
|
||||
yield* requireProject({
|
||||
readModel,
|
||||
command,
|
||||
projectId: sourceThread.projectId,
|
||||
});
|
||||
yield* requireThreadAbsent({
|
||||
readModel,
|
||||
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({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
projectId: sourceThread.projectId,
|
||||
title: command.title ?? `${sourceThread.title} (Branched)`,
|
||||
modelSelection: sourceThread.modelSelection,
|
||||
runtimeMode: sourceThread.runtimeMode,
|
||||
interactionMode: sourceThread.interactionMode,
|
||||
branch: sourceThread.branch,
|
||||
worktreePath: sourceThread.worktreePath,
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
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 = [
|
||||
...sourceMessages.map((message, sourceIndex) => ({
|
||||
kind: "message" as const,
|
||||
createdAt: message.createdAt,
|
||||
sourceIndex,
|
||||
message,
|
||||
})),
|
||||
...sourceActivities.map((activity, sourceIndex) => ({
|
||||
kind: "activity" as const,
|
||||
createdAt: activity.createdAt,
|
||||
sourceIndex,
|
||||
activity,
|
||||
})),
|
||||
].toSorted((left, right) => {
|
||||
const createdAtComparison = left.createdAt.localeCompare(right.createdAt);
|
||||
if (createdAtComparison !== 0) {
|
||||
return createdAtComparison;
|
||||
}
|
||||
if (left.kind !== right.kind) {
|
||||
return left.kind === "message" ? -1 : 1;
|
||||
}
|
||||
return left.sourceIndex - right.sourceIndex;
|
||||
});
|
||||
|
||||
for (const [index, sourceEntry] of sourceEntries.entries()) {
|
||||
const copiedAt = timestampOffsetIso(command.createdAt, index + 1);
|
||||
const eventBase = withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: copiedAt,
|
||||
commandId: command.commandId,
|
||||
});
|
||||
const copiedBase = {
|
||||
eventId: eventBase.eventId,
|
||||
aggregateKind: eventBase.aggregateKind,
|
||||
aggregateId: eventBase.aggregateId,
|
||||
occurredAt: eventBase.occurredAt,
|
||||
commandId: eventBase.commandId,
|
||||
causationEventId: threadCreatedEvent.eventId,
|
||||
correlationId: eventBase.correlationId,
|
||||
metadata: eventBase.metadata,
|
||||
};
|
||||
if (sourceEntry.kind === "message") {
|
||||
copiedThreadEvents.push({
|
||||
...copiedBase,
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: MessageId.make(crypto.randomUUID()),
|
||||
role: sourceEntry.message.role,
|
||||
text: sourceEntry.message.text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: copiedAt,
|
||||
updatedAt: copiedAt,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
copiedThreadEvents.push({
|
||||
...copiedBase,
|
||||
type: "thread.activity-appended",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: sourceEntry.activity.tone,
|
||||
kind: sourceEntry.activity.kind,
|
||||
summary: sourceEntry.activity.summary,
|
||||
payload: sanitizeCopiedActivityPayload(sourceEntry.activity.payload),
|
||||
turnId: null,
|
||||
sequence: index,
|
||||
createdAt: copiedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return [threadCreatedEvent, ...copiedThreadEvents];
|
||||
}
|
||||
|
||||
case "thread.delete": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -61,7 +61,7 @@ import { usePrimaryEnvironmentId } from "../environments/primary";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { isMacPlatform, newCommandId } from "../lib/utils";
|
||||
import { isMacPlatform, newCommandId, newThreadId } from "../lib/utils";
|
||||
import {
|
||||
selectProjectByRef,
|
||||
selectProjectsAcrossEnvironments,
|
||||
@@ -1905,6 +1905,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "branch", label: "Branch thread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
@@ -1919,6 +1920,45 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "branch") {
|
||||
const environmentApi = readEnvironmentApi(threadRef.environmentId);
|
||||
if (!environmentApi) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to branch thread",
|
||||
description: "Thread API unavailable.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const branchThreadRef = scopeThreadRef(threadRef.environmentId, newThreadId());
|
||||
try {
|
||||
await environmentApi.orchestration.dispatchCommand({
|
||||
type: "thread.branch",
|
||||
commandId: newCommandId(),
|
||||
sourceThreadId: threadRef.threadId,
|
||||
threadId: branchThreadRef.threadId,
|
||||
title: `${thread.title} (Branched)`,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
await router.navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(branchThreadRef),
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to branch thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
|
||||
return;
|
||||
@@ -1963,6 +2003,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
markThreadUnread,
|
||||
memberProjectByScopedKey,
|
||||
project.cwd,
|
||||
router,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -341,6 +341,25 @@ it.effect("decodes thread archive and unarchive commands", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread branch commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const branch = yield* decodeOrchestrationCommand({
|
||||
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",
|
||||
});
|
||||
|
||||
assert.strictEqual(branch.type, "thread.branch");
|
||||
assert.strictEqual(branch.sourceThreadId, "thread-source");
|
||||
assert.strictEqual(branch.sourceMessageId, "message-source");
|
||||
assert.strictEqual(branch.threadId, "thread-branch");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread archived and unarchived events", () =>
|
||||
Effect.gen(function* () {
|
||||
const archived = yield* decodeOrchestrationEvent({
|
||||
|
||||
@@ -489,6 +489,16 @@ const ThreadCreateCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
const ThreadDeleteCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.delete"),
|
||||
commandId: CommandId,
|
||||
@@ -644,6 +654,7 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||
ProjectMetaUpdateCommand,
|
||||
ProjectDeleteCommand,
|
||||
ThreadCreateCommand,
|
||||
ThreadBranchCommand,
|
||||
ThreadDeleteCommand,
|
||||
ThreadArchiveCommand,
|
||||
ThreadUnarchiveCommand,
|
||||
@@ -665,6 +676,7 @@ export const ClientOrchestrationCommand = Schema.Union([
|
||||
ProjectMetaUpdateCommand,
|
||||
ProjectDeleteCommand,
|
||||
ThreadCreateCommand,
|
||||
ThreadBranchCommand,
|
||||
ThreadDeleteCommand,
|
||||
ThreadArchiveCommand,
|
||||
ThreadUnarchiveCommand,
|
||||
|
||||
Reference in new issue
Block a user