feat: context menu branching

This commit is contained in:
Yash Singh committed 2026-05-04 01:42:57 -05:00
1 parent d501ebe877
commit 658ef9cd6b
5 files changed
+469 -5

No files matched your search

@@ -0,0 +1,262 @@
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 as new frozen messages", 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);
});
});
+137 -4
View File
@@ -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,128 @@ 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 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 sourceEntries = [
...sourceThread.messages.map((message, sourceIndex) => ({
kind: "message" as const,
createdAt: message.createdAt,
sourceIndex,
message,
})),
...sourceThread.activities.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,
+42 -1
View File
@@ -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,
],
);
@@ -341,6 +341,23 @@ 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",
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.threadId, "thread-branch");
}),
);
it.effect("decodes thread archived and unarchived events", () =>
Effect.gen(function* () {
const archived = yield* decodeOrchestrationEvent({
+11
View File
@@ -489,6 +489,15 @@ const ThreadCreateCommand = Schema.Struct({
createdAt: IsoDateTime,
});
const ThreadBranchCommand = Schema.Struct({
type: Schema.Literal("thread.branch"),
commandId: CommandId,
sourceThreadId: ThreadId,
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
createdAt: IsoDateTime,
});
const ThreadDeleteCommand = Schema.Struct({
type: Schema.Literal("thread.delete"),
commandId: CommandId,
@@ -644,6 +653,7 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ProjectMetaUpdateCommand,
ProjectDeleteCommand,
ThreadCreateCommand,
ThreadBranchCommand,
ThreadDeleteCommand,
ThreadArchiveCommand,
ThreadUnarchiveCommand,
@@ -665,6 +675,7 @@ export const ClientOrchestrationCommand = Schema.Union([
ProjectMetaUpdateCommand,
ProjectDeleteCommand,
ThreadCreateCommand,
ThreadBranchCommand,
ThreadDeleteCommand,
ThreadArchiveCommand,
ThreadUnarchiveCommand,