Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3b41bce3a | ||
|
|
31f82efd2e | ||
|
|
d27c215014 |
No files matched your search
@@ -111,6 +111,81 @@ describe("OrchestrationEngine", () => {
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("seeds branched thread history during thread creation", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-branch-seed"),
|
||||
projectId: asProjectId("project-branch-seed"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-branch-seed",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-branch-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-branch-seed"),
|
||||
projectId: asProjectId("project-branch-seed"),
|
||||
title: "Branch of Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: "feature/source",
|
||||
worktreePath: null,
|
||||
seedMessages: [
|
||||
{
|
||||
messageId: asMessageId("msg-seed-user"),
|
||||
role: "user",
|
||||
text: "original question",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:00.000Z",
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
messageId: asMessageId("msg-seed-assistant"),
|
||||
role: "assistant",
|
||||
text: "original answer",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:01.000Z",
|
||||
updatedAt: "2026-02-01T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const readModel = await system.run(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === "thread-branch-seed");
|
||||
expect(thread?.messages.map((message) => message.text)).toEqual([
|
||||
"original question",
|
||||
"original answer",
|
||||
]);
|
||||
expect(thread?.messages.every((message) => message.turnId === null)).toBe(true);
|
||||
expect(thread?.session).toBeNull();
|
||||
|
||||
const events = await system.run(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
"thread.message-sent",
|
||||
"thread.message-sent",
|
||||
]);
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("replays append-only events from sequence", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
@@ -144,7 +144,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
const threadCreatedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -165,6 +165,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
const seedMessageEvents: ReadonlyArray<Omit<OrchestrationEvent, "sequence">> =
|
||||
command.seedMessages?.map((message) => ({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.message-sent" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: message.messageId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.updatedAt,
|
||||
},
|
||||
})) ?? [];
|
||||
|
||||
return seedMessageEvents.length > 0
|
||||
? [threadCreatedEvent, ...seedMessageEvents]
|
||||
: threadCreatedEvent;
|
||||
}
|
||||
|
||||
case "thread.delete": {
|
||||
|
||||
@@ -1143,6 +1143,72 @@ describe("WebSocket Server", () => {
|
||||
expect(response.error?.message).toContain("exceeds current turn count");
|
||||
});
|
||||
|
||||
it("returns seeded thread messages in snapshots after thread creation", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-seed-project-create",
|
||||
projectId: "project-seed",
|
||||
title: "Seed Project",
|
||||
workspaceRoot: "/tmp/ws-seed-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
expect(createProjectResponse.error).toBeUndefined();
|
||||
|
||||
const createThreadResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "thread.create",
|
||||
commandId: "cmd-seed-thread-create",
|
||||
threadId: "thread-seed",
|
||||
projectId: "project-seed",
|
||||
title: "Seed Thread",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
seedMessages: [
|
||||
{
|
||||
messageId: "msg-seed-1",
|
||||
role: "user",
|
||||
text: "seeded question",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:00.000Z",
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
messageId: "msg-seed-2",
|
||||
role: "assistant",
|
||||
text: "seeded answer",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:01.000Z",
|
||||
updatedAt: "2026-02-01T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
createdAt,
|
||||
});
|
||||
expect(createThreadResponse.error).toBeUndefined();
|
||||
|
||||
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
||||
expect(snapshotResponse.error).toBeUndefined();
|
||||
const snapshot = snapshotResponse.result as {
|
||||
threads: Array<{ id: string; messages: Array<{ text: string }> }>;
|
||||
};
|
||||
const thread = snapshot.threads.find((entry) => entry.id === "thread-seed");
|
||||
expect(thread?.messages.map((message) => message.text)).toEqual([
|
||||
"seeded question",
|
||||
"seeded answer",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps orchestration domain push behavior for provider runtime events", async () => {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
@@ -108,6 +109,8 @@ import {
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { buildBootstrapInput, resolveTurnBootstrapMessages } from "../historyBootstrap";
|
||||
import { buildTemporaryWorktreeBranchName } from "../worktreeBranches";
|
||||
import {
|
||||
buildTurnDiffTree,
|
||||
summarizeTurnDiffStats,
|
||||
@@ -134,6 +137,7 @@ import {
|
||||
DiffIcon,
|
||||
EllipsisIcon,
|
||||
FolderClosedIcon,
|
||||
GitBranchIcon,
|
||||
LockIcon,
|
||||
LockOpenIcon,
|
||||
Undo2Icon,
|
||||
@@ -186,6 +190,11 @@ import {
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
branchConversationThread,
|
||||
createBranchedThreadWorktree,
|
||||
selectBranchedMessages,
|
||||
} from "./threadBranching";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
@@ -240,7 +249,6 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
|
||||
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
|
||||
@@ -418,12 +426,6 @@ function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
function cloneComposerImageForRetry(image: ComposerImageAttachment): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
@@ -584,6 +586,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
const bootstrapMessages = composerDraft.bootstrapMessages;
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
@@ -593,6 +596,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
(store) => store.setInteractionMode,
|
||||
);
|
||||
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
|
||||
const setBootstrapMessages = useComposerDraftStore((store) => store.setBootstrapMessages);
|
||||
const setComposerDraftCodexFastMode = useComposerDraftStore((store) => store.setCodexFastMode);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
@@ -793,6 +797,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const reasoningOptions = getReasoningEffortOptions(selectedProvider);
|
||||
const supportsReasoningEffort = reasoningOptions.length > 0;
|
||||
const selectedEffort = composerDraft.effort ?? getDefaultReasoningEffort(selectedProvider);
|
||||
const turnBootstrapMessages = resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages: bootstrapMessages,
|
||||
threadMessages: activeThread?.messages ?? [],
|
||||
providerThreadId: activeThread?.codexThreadId ?? null,
|
||||
});
|
||||
const selectedCodexFastModeEnabled =
|
||||
selectedProvider === "codex" ? composerDraft.codexFastMode : false;
|
||||
const selectedModelOptionsForDispatch = useMemo(() => {
|
||||
@@ -993,8 +1002,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS);
|
||||
}, []);
|
||||
const serverMessages = activeThread?.messages;
|
||||
const displayMessages = useMemo(() => {
|
||||
if (serverMessages && serverMessages.length > 0) {
|
||||
return serverMessages;
|
||||
}
|
||||
if (bootstrapMessages.length > 0 && (activeThread?.codexThreadId ?? null) === null) {
|
||||
return bootstrapMessages;
|
||||
}
|
||||
return serverMessages ?? [];
|
||||
}, [activeThread?.codexThreadId, bootstrapMessages, serverMessages]);
|
||||
const timelineMessages = useMemo(() => {
|
||||
const messages = serverMessages ?? [];
|
||||
const messages = displayMessages;
|
||||
const serverMessagesWithPreviewHandoff =
|
||||
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
|
||||
? messages
|
||||
@@ -1045,7 +1063,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return serverMessagesWithPreviewHandoff;
|
||||
}
|
||||
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
|
||||
}, [serverMessages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
|
||||
}, [displayMessages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
|
||||
const timelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
|
||||
@@ -1291,7 +1309,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.messages.length > 0 ||
|
||||
(displayMessages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const hasReachedTerminalLimit = terminalState.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
@@ -2481,6 +2499,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
const title = truncateTitle(titleSeed);
|
||||
const promptTextForSend =
|
||||
turnBootstrapMessages.length > 0 && (activeThread?.codexThreadId ?? null) === null
|
||||
? buildBootstrapInput(
|
||||
turnBootstrapMessages,
|
||||
trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
).text
|
||||
: (trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT);
|
||||
let threadCreateModel: ModelSlug =
|
||||
selectedModel || (activeProject.model as ModelSlug) || DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
@@ -2556,7 +2582,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
message: {
|
||||
messageId: messageIdForSend,
|
||||
role: "user",
|
||||
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
text: promptTextForSend,
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
model: selectedModel || undefined,
|
||||
@@ -3283,6 +3309,50 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
void onRevertToTurnCount(targetTurnCount);
|
||||
};
|
||||
const onBranchAssistantMessage = useCallback(
|
||||
(messageId: MessageId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThread) return;
|
||||
|
||||
void branchConversationThread({
|
||||
api,
|
||||
thread: activeThread,
|
||||
seedMessages: selectBranchedMessages({
|
||||
messages: displayMessages,
|
||||
targetMessageId: messageId,
|
||||
}),
|
||||
projectCwd: activeProject?.cwd ?? null,
|
||||
createWorktree: ({ cwd, branch }) =>
|
||||
createBranchedThreadWorktree({
|
||||
createWorktree: (args) => createWorktreeMutation.mutateAsync(args),
|
||||
cwd,
|
||||
branch,
|
||||
}),
|
||||
syncServerReadModel,
|
||||
setBootstrapMessages,
|
||||
navigateToThread: (threadId) =>
|
||||
navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
}),
|
||||
}).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to branch conversation",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
},
|
||||
[
|
||||
activeProject?.cwd,
|
||||
activeThread,
|
||||
createWorktreeMutation,
|
||||
displayMessages,
|
||||
navigate,
|
||||
setBootstrapMessages,
|
||||
syncServerReadModel,
|
||||
],
|
||||
);
|
||||
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
@@ -3379,6 +3449,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
|
||||
onRevertUserMessage={onRevertUserMessage}
|
||||
onBranchAssistantMessage={onBranchAssistantMessage}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
@@ -4620,6 +4691,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;
|
||||
markdownCwd: string | undefined;
|
||||
@@ -4674,6 +4746,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onOpenTurnDiff,
|
||||
revertTurnCountByUserMessageId,
|
||||
onRevertUserMessage,
|
||||
onBranchAssistantMessage,
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
@@ -5022,6 +5095,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
row.message.role === "assistant" &&
|
||||
(() => {
|
||||
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||
const canBranchFromAssistantMessage = !row.message.streaming;
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && (
|
||||
@@ -5033,7 +5107,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<div className="group min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={markdownCwd}
|
||||
@@ -5095,14 +5169,30 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
row.message.streaming
|
||||
? formatElapsed(row.message.createdAt, nowIso)
|
||||
: formatElapsed(row.message.createdAt, row.message.completedAt),
|
||||
)}
|
||||
</p>
|
||||
<div className="mt-1.5 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||
{canBranchFromAssistantMessage && (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onBranchAssistantMessage(row.message.id)}
|
||||
title="Branch from this response"
|
||||
>
|
||||
<GitBranchIcon className="size-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
row.message.streaming
|
||||
? formatElapsed(row.message.createdAt, nowIso)
|
||||
: formatElapsed(row.message.createdAt, row.message.completedAt),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { planBranchedThread } from "./Sidebar.logic";
|
||||
|
||||
describe("planBranchedThread", () => {
|
||||
it("reuses the source branch without cloning a worktree for local threads", () => {
|
||||
expect(
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: null,
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Branch of Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: null,
|
||||
createWorktree: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("requests a fresh worktree when branching a worktree-backed thread", () => {
|
||||
expect(
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: "/tmp/original",
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Branch of Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: null,
|
||||
createWorktree: {
|
||||
cwd: "/repo",
|
||||
branch: "feature/original",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a generic fallback title when the source title is blank", () => {
|
||||
expect(
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: " ",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}).title,
|
||||
).toBe("Branched thread");
|
||||
});
|
||||
|
||||
it("rejects worktree threads that are missing a branch", () => {
|
||||
expect(() =>
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: null,
|
||||
worktreePath: "/tmp/original",
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toThrow("Cannot branch a worktree thread without a branch.");
|
||||
});
|
||||
|
||||
it("rejects worktree threads when the project cwd is unavailable", () => {
|
||||
expect(() =>
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: "/tmp/original",
|
||||
},
|
||||
projectCwd: null,
|
||||
}),
|
||||
).toThrow("Project working directory is unavailable.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { Thread } from "../types";
|
||||
import { truncateTitle } from "../truncateTitle";
|
||||
|
||||
export interface BranchedThreadPlan {
|
||||
title: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
createWorktree: {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export function planBranchedThread(input: {
|
||||
thread: Pick<Thread, "title" | "branch" | "worktreePath">;
|
||||
projectCwd: string | null;
|
||||
}): BranchedThreadPlan {
|
||||
const { thread, projectCwd } = input;
|
||||
|
||||
if (thread.worktreePath) {
|
||||
if (!thread.branch) {
|
||||
throw new Error("Cannot branch a worktree thread without a branch.");
|
||||
}
|
||||
if (!projectCwd) {
|
||||
throw new Error("Project working directory is unavailable.");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
title: truncateTitle(
|
||||
thread.title.trim().length > 0 ? `Branch of ${thread.title}` : "Branched thread",
|
||||
),
|
||||
branch: thread.branch,
|
||||
worktreePath: null,
|
||||
createWorktree: thread.worktreePath
|
||||
? {
|
||||
cwd: projectCwd!,
|
||||
branch: thread.branch!,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -26,7 +26,11 @@ import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import {
|
||||
gitCreateWorktreeMutationOptions,
|
||||
gitRemoveWorktreeMutationOptions,
|
||||
gitStatusQueryOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
@@ -60,6 +64,7 @@ import {
|
||||
} from "./ui/sidebar";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import { branchConversationThread, createBranchedThreadWorktree } from "./threadBranching";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
@@ -260,6 +265,7 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
export default function Sidebar() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
@@ -267,6 +273,7 @@ export default function Sidebar() {
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||
const setBootstrapMessages = useComposerDraftStore((store) => store.setBootstrapMessages);
|
||||
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
@@ -288,6 +295,7 @@ export default function Sidebar() {
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
@@ -588,12 +596,40 @@ export default function Sidebar() {
|
||||
[],
|
||||
);
|
||||
|
||||
const branchConversation = useCallback(
|
||||
async (thread: Thread) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
await branchConversationThread({
|
||||
api,
|
||||
thread,
|
||||
seedMessages: thread.messages,
|
||||
projectCwd: projectCwdById.get(thread.projectId) ?? null,
|
||||
createWorktree: ({ cwd, branch }) =>
|
||||
createBranchedThreadWorktree({
|
||||
createWorktree: (args) => createWorktreeMutation.mutateAsync(args),
|
||||
cwd,
|
||||
branch,
|
||||
}),
|
||||
syncServerReadModel,
|
||||
setBootstrapMessages,
|
||||
navigateToThread: (threadId) =>
|
||||
navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
}),
|
||||
});
|
||||
},
|
||||
[createWorktreeMutation, navigate, projectCwdById, setBootstrapMessages, syncServerReadModel],
|
||||
);
|
||||
|
||||
const handleThreadContextMenu = useCallback(
|
||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "branch", label: "Branch conversation" },
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
@@ -604,6 +640,19 @@ export default function Sidebar() {
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (clicked === "branch") {
|
||||
try {
|
||||
await branchConversation(thread);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to branch conversation",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadId(threadId);
|
||||
setRenamingTitle(thread.title);
|
||||
@@ -733,6 +782,7 @@ export default function Sidebar() {
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalState,
|
||||
branchConversation,
|
||||
markThreadUnread,
|
||||
navigate,
|
||||
projects,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ChatMessage } from "../types";
|
||||
import { selectBranchedMessages } from "./threadBranching";
|
||||
|
||||
function messageId(value: string): MessageId {
|
||||
return MessageId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function makeMessage(input: {
|
||||
id: string;
|
||||
role: ChatMessage["role"];
|
||||
text: string;
|
||||
createdAt?: string;
|
||||
}): ChatMessage {
|
||||
return {
|
||||
id: messageId(input.id),
|
||||
role: input.role,
|
||||
text: input.text,
|
||||
createdAt: input.createdAt ?? "2026-03-05T00:00:00.000Z",
|
||||
streaming: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("selectBranchedMessages", () => {
|
||||
it("returns the full transcript when no target message is provided", () => {
|
||||
const messages = [
|
||||
makeMessage({ id: "msg-1", role: "user", text: "first" }),
|
||||
makeMessage({ id: "msg-2", role: "assistant", text: "second" }),
|
||||
];
|
||||
|
||||
expect(selectBranchedMessages({ messages })).toEqual(messages);
|
||||
});
|
||||
|
||||
it("returns messages up to and including the targeted assistant message", () => {
|
||||
const messages = [
|
||||
makeMessage({ id: "msg-1", role: "user", text: "first" }),
|
||||
makeMessage({ id: "msg-2", role: "assistant", text: "second" }),
|
||||
makeMessage({ id: "msg-3", role: "user", text: "third" }),
|
||||
makeMessage({ id: "msg-4", role: "assistant", text: "fourth" }),
|
||||
];
|
||||
|
||||
expect(
|
||||
selectBranchedMessages({
|
||||
messages,
|
||||
targetMessageId: messageId("msg-2"),
|
||||
}).map((message) => message.id),
|
||||
).toEqual([messageId("msg-1"), messageId("msg-2")]);
|
||||
});
|
||||
|
||||
it("rejects non-assistant branch targets", () => {
|
||||
expect(() =>
|
||||
selectBranchedMessages({
|
||||
messages: [makeMessage({ id: "msg-1", role: "user", text: "first" })],
|
||||
targetMessageId: messageId("msg-1"),
|
||||
}),
|
||||
).toThrow("Can only branch from an assistant message.");
|
||||
});
|
||||
|
||||
it("rejects missing branch targets", () => {
|
||||
expect(() =>
|
||||
selectBranchedMessages({
|
||||
messages: [makeMessage({ id: "msg-1", role: "assistant", text: "first" })],
|
||||
targetMessageId: messageId("missing"),
|
||||
}),
|
||||
).toThrow("Branch target message was not found.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { MessageId, NativeApi, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { newCommandId, newThreadId } from "../lib/utils";
|
||||
|
||||
import type { ChatMessage, Thread } from "../types";
|
||||
import { buildTemporaryWorktreeBranchName } from "../worktreeBranches";
|
||||
import { planBranchedThread } from "./Sidebar.logic";
|
||||
|
||||
export function selectBranchedMessages(input: {
|
||||
messages: ReadonlyArray<ChatMessage>;
|
||||
targetMessageId?: MessageId | null;
|
||||
}): ChatMessage[] {
|
||||
if (!input.targetMessageId) {
|
||||
return [...input.messages];
|
||||
}
|
||||
|
||||
const targetIndex = input.messages.findIndex((message) => message.id === input.targetMessageId);
|
||||
if (targetIndex < 0) {
|
||||
throw new Error("Branch target message was not found.");
|
||||
}
|
||||
|
||||
const targetMessage = input.messages[targetIndex];
|
||||
if (!targetMessage || targetMessage.role !== "assistant") {
|
||||
throw new Error("Can only branch from an assistant message.");
|
||||
}
|
||||
|
||||
return input.messages.slice(0, targetIndex + 1);
|
||||
}
|
||||
|
||||
export async function branchConversationThread(input: {
|
||||
api: NativeApi;
|
||||
thread: Thread;
|
||||
seedMessages: ChatMessage[];
|
||||
projectCwd: string | null;
|
||||
createWorktree: (args: { cwd: string; branch: string }) => Promise<{
|
||||
branch: string;
|
||||
path: string;
|
||||
}>;
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
|
||||
setBootstrapMessages: (threadId: ThreadId, messages: ChatMessage[]) => void;
|
||||
navigateToThread: (threadId: ThreadId) => Promise<void>;
|
||||
}): Promise<ThreadId> {
|
||||
const branchedThreadId = newThreadId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const plan = planBranchedThread({ thread: input.thread, projectCwd: input.projectCwd });
|
||||
let branchedThreadBranch = plan.branch;
|
||||
let branchedThreadWorktreePath = plan.worktreePath;
|
||||
|
||||
if (plan.createWorktree) {
|
||||
const result = await input.createWorktree({
|
||||
cwd: plan.createWorktree.cwd,
|
||||
branch: plan.createWorktree.branch,
|
||||
});
|
||||
branchedThreadBranch = result.branch;
|
||||
branchedThreadWorktreePath = result.path;
|
||||
}
|
||||
|
||||
await input.api.orchestration.dispatchCommand({
|
||||
type: "thread.create",
|
||||
commandId: newCommandId(),
|
||||
threadId: branchedThreadId,
|
||||
projectId: input.thread.projectId,
|
||||
title: plan.title,
|
||||
model: input.thread.model,
|
||||
runtimeMode: input.thread.runtimeMode,
|
||||
interactionMode: input.thread.interactionMode,
|
||||
branch: branchedThreadBranch,
|
||||
worktreePath: branchedThreadWorktreePath,
|
||||
seedMessages: input.seedMessages.map((message) => ({
|
||||
messageId: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
attachments: message.attachments ?? [],
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.completedAt ?? message.createdAt,
|
||||
})),
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const snapshot = await input.api.orchestration.getSnapshot();
|
||||
input.syncServerReadModel(snapshot);
|
||||
if (input.seedMessages.length > 0) {
|
||||
input.setBootstrapMessages(branchedThreadId, input.seedMessages);
|
||||
}
|
||||
|
||||
await input.navigateToThread(branchedThreadId);
|
||||
return branchedThreadId;
|
||||
}
|
||||
|
||||
export async function createBranchedThreadWorktree(input: {
|
||||
createWorktree: (args: { cwd: string; branch: string; newBranch: string }) => Promise<{
|
||||
worktree: { branch: string; path: string };
|
||||
}>;
|
||||
cwd: string;
|
||||
branch: string;
|
||||
}): Promise<{ branch: string; path: string }> {
|
||||
const result = await input.createWorktree({
|
||||
cwd: input.cwd,
|
||||
branch: input.branch,
|
||||
newBranch: buildTemporaryWorktreeBranchName(),
|
||||
});
|
||||
return {
|
||||
branch: result.worktree.branch,
|
||||
path: result.worktree.path,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
|
||||
@@ -152,6 +152,35 @@ describe("composerDraftStore clearComposerContent", () => {
|
||||
expect(draft).toBeUndefined();
|
||||
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
|
||||
});
|
||||
|
||||
it("preserves hidden bootstrap transcript state", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setPrompt(threadId, "draft prompt");
|
||||
store.setBootstrapMessages(threadId, [
|
||||
{
|
||||
id: MessageId.makeUnsafe("msg-bootstrap"),
|
||||
role: "user",
|
||||
text: "Earlier context",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
|
||||
store.clearComposerContent(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
prompt: "",
|
||||
bootstrapMessages: [
|
||||
{
|
||||
id: "msg-bootstrap",
|
||||
role: "user",
|
||||
text: "Earlier context",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore project draft thread mapping", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
ThreadId,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type ChatImageAttachment,
|
||||
type ChatMessage,
|
||||
} from "./types";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
@@ -36,6 +38,7 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
|
||||
interface PersistedComposerThreadDraftState {
|
||||
prompt: string;
|
||||
attachments: PersistedComposerImageAttachment[];
|
||||
bootstrapMessages?: ChatMessage[];
|
||||
provider?: ProviderKind | null;
|
||||
model?: string | null;
|
||||
runtimeMode?: RuntimeMode | null;
|
||||
@@ -66,6 +69,7 @@ interface ComposerThreadDraftState {
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
bootstrapMessages: ChatMessage[];
|
||||
provider: ProviderKind | null;
|
||||
model: string | null;
|
||||
runtimeMode: RuntimeMode | null;
|
||||
@@ -122,6 +126,8 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setBootstrapMessages: (threadId: ThreadId, messages: ChatMessage[]) => void;
|
||||
clearBootstrapMessages: (threadId: ThreadId) => void;
|
||||
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
|
||||
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
|
||||
setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
|
||||
@@ -152,14 +158,17 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
||||
const EMPTY_BOOTSTRAP_MESSAGES: ChatMessage[] = [];
|
||||
Object.freeze(EMPTY_IMAGES);
|
||||
Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
Object.freeze(EMPTY_BOOTSTRAP_MESSAGES);
|
||||
const EMPTY_THREAD_DRAFT = Object.freeze({
|
||||
prompt: "",
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
bootstrapMessages: EMPTY_BOOTSTRAP_MESSAGES,
|
||||
provider: null,
|
||||
model: null,
|
||||
runtimeMode: null,
|
||||
@@ -178,6 +187,7 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
bootstrapMessages: [],
|
||||
provider: null,
|
||||
model: null,
|
||||
runtimeMode: null,
|
||||
@@ -198,6 +208,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
draft.prompt.length === 0 &&
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.bootstrapMessages.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -252,6 +263,81 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBootstrapAttachment(
|
||||
value: unknown,
|
||||
): Omit<ChatImageAttachment, "previewUrl"> | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const id = candidate.id;
|
||||
const name = candidate.name;
|
||||
const mimeType = candidate.mimeType;
|
||||
const sizeBytes = candidate.sizeBytes;
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
id.length === 0 ||
|
||||
typeof name !== "string" ||
|
||||
name.length === 0 ||
|
||||
typeof mimeType !== "string" ||
|
||||
mimeType.length === 0 ||
|
||||
typeof sizeBytes !== "number" ||
|
||||
!Number.isFinite(sizeBytes)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
id,
|
||||
name,
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBootstrapMessage(value: unknown): ChatMessage | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const id = candidate.id;
|
||||
const role = candidate.role;
|
||||
const text = candidate.text;
|
||||
const createdAt = candidate.createdAt;
|
||||
const streaming = candidate.streaming;
|
||||
const completedAt = candidate.completedAt;
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
id.length === 0 ||
|
||||
(role !== "user" && role !== "assistant" && role !== "system") ||
|
||||
typeof text !== "string" ||
|
||||
typeof createdAt !== "string" ||
|
||||
createdAt.length === 0 ||
|
||||
typeof streaming !== "boolean"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const attachments = Array.isArray(candidate.attachments)
|
||||
? candidate.attachments.flatMap((entry) => {
|
||||
const normalized = normalizeBootstrapAttachment(entry);
|
||||
if (!normalized) {
|
||||
return [];
|
||||
}
|
||||
return [normalized];
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: MessageId.makeUnsafe(id),
|
||||
role,
|
||||
text,
|
||||
createdAt,
|
||||
streaming,
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
...(typeof completedAt === "string" && completedAt.length > 0 ? { completedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeDraftThreadEnvMode(
|
||||
value: unknown,
|
||||
fallbackWorktreePath: string | null,
|
||||
@@ -366,6 +452,12 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const bootstrapMessages = Array.isArray(draftCandidate.bootstrapMessages)
|
||||
? draftCandidate.bootstrapMessages.flatMap((entry) => {
|
||||
const normalized = normalizeBootstrapMessage(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const provider = normalizeProviderKind(draftCandidate.provider);
|
||||
const model =
|
||||
typeof draftCandidate.model === "string"
|
||||
@@ -392,6 +484,7 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
if (
|
||||
prompt.length === 0 &&
|
||||
attachments.length === 0 &&
|
||||
bootstrapMessages.length === 0 &&
|
||||
!provider &&
|
||||
!model &&
|
||||
!runtimeMode &&
|
||||
@@ -404,6 +497,7 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
nextDraftsByThreadId[threadId as ThreadId] = {
|
||||
prompt,
|
||||
attachments,
|
||||
...(bootstrapMessages.length > 0 ? { bootstrapMessages } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(model ? { model } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
@@ -511,6 +605,7 @@ function toHydratedThreadDraft(
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: persistedDraft.attachments,
|
||||
bootstrapMessages: persistedDraft.bootstrapMessages ?? [],
|
||||
provider: persistedDraft.provider ?? null,
|
||||
model: persistedDraft.model ?? null,
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
@@ -778,6 +873,47 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setBootstrapMessages: (threadId, messages) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
bootstrapMessages: [...messages],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearBootstrapMessages: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
bootstrapMessages: [],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProvider: (threadId, provider) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1179,6 +1315,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.bootstrapMessages.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -1192,6 +1329,22 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
prompt: draft.prompt,
|
||||
attachments: draft.persistedAttachments,
|
||||
};
|
||||
if (draft.bootstrapMessages.length > 0) {
|
||||
persistedDraft.bootstrapMessages = draft.bootstrapMessages.map((message) => ({
|
||||
...message,
|
||||
...(message.attachments
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
}
|
||||
if (draft.model) {
|
||||
persistedDraft.model = draft.model;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildBootstrapInput } from "./historyBootstrap";
|
||||
import {
|
||||
buildBootstrapInput,
|
||||
resolveTurnBootstrapMessages,
|
||||
selectBootstrapMessages,
|
||||
} from "./historyBootstrap";
|
||||
|
||||
const messageId = (value: string) => MessageId.makeUnsafe(value);
|
||||
|
||||
@@ -122,4 +126,126 @@ describe("buildBootstrapInput", () => {
|
||||
expect(result.text).toContain("Attached image");
|
||||
expect(result.text).toContain("screenshot.png");
|
||||
});
|
||||
|
||||
it("labels system messages distinctly in transcript blocks", () => {
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: messageId("sys-1"),
|
||||
role: "system",
|
||||
text: "Follow repository rules.",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"continue",
|
||||
1_500,
|
||||
);
|
||||
|
||||
expect(result.text).toContain("SYSTEM:\nFollow repository rules.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectBootstrapMessages", () => {
|
||||
it("returns the newest fitting suffix in chronological order", () => {
|
||||
const result = selectBootstrapMessages(
|
||||
[
|
||||
{
|
||||
id: messageId("u-1"),
|
||||
role: "user",
|
||||
text: "first question with details",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: messageId("a-1"),
|
||||
role: "assistant",
|
||||
text: "first answer with details",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: messageId("u-2"),
|
||||
role: "user",
|
||||
text: "second question with details",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"final request",
|
||||
320,
|
||||
);
|
||||
|
||||
expect(result.omittedCount).toBeGreaterThan(0);
|
||||
expect(result.messages.map((message) => message.id)).toEqual([messageId("u-2")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveTurnBootstrapMessages", () => {
|
||||
it("prefers explicit draft bootstrap messages", () => {
|
||||
const draftBootstrapMessages = [
|
||||
{
|
||||
id: messageId("draft-1"),
|
||||
role: "user" as const,
|
||||
text: "draft bootstrap",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const threadMessages = [
|
||||
{
|
||||
id: messageId("thread-1"),
|
||||
role: "assistant" as const,
|
||||
text: "visible history",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
|
||||
expect(
|
||||
resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages,
|
||||
threadMessages,
|
||||
providerThreadId: null,
|
||||
}),
|
||||
).toEqual(draftBootstrapMessages);
|
||||
});
|
||||
|
||||
it("reuses visible thread history when no provider thread exists yet", () => {
|
||||
const threadMessages = [
|
||||
{
|
||||
id: messageId("thread-1"),
|
||||
role: "assistant" as const,
|
||||
text: "visible history",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
|
||||
expect(
|
||||
resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages: [],
|
||||
threadMessages,
|
||||
providerThreadId: null,
|
||||
}),
|
||||
).toEqual(threadMessages);
|
||||
});
|
||||
|
||||
it("skips bootstrap when the provider thread already exists", () => {
|
||||
expect(
|
||||
resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages: [],
|
||||
threadMessages: [
|
||||
{
|
||||
id: messageId("thread-1"),
|
||||
role: "assistant" as const,
|
||||
text: "visible history",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
providerThreadId: "provider-thread-1",
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,28 @@ export interface BootstrapInputResult {
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export interface BootstrapMessageSelectionResult {
|
||||
messages: ChatMessage[];
|
||||
omittedCount: number;
|
||||
promptTruncated: boolean;
|
||||
}
|
||||
|
||||
export function resolveTurnBootstrapMessages(input: {
|
||||
draftBootstrapMessages: ChatMessage[];
|
||||
threadMessages: ChatMessage[];
|
||||
providerThreadId: string | null;
|
||||
}): ChatMessage[] {
|
||||
if (input.draftBootstrapMessages.length > 0) {
|
||||
return input.draftBootstrapMessages;
|
||||
}
|
||||
|
||||
if (input.providerThreadId === null && input.threadMessages.length > 0) {
|
||||
return input.threadMessages;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
const BOOTSTRAP_PREAMBLE =
|
||||
"Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";
|
||||
const TRANSCRIPT_HEADER = "Transcript context:";
|
||||
@@ -14,8 +36,14 @@ const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";
|
||||
const OMITTED_SUMMARY = (count: number) =>
|
||||
`[${count} earlier message(s) omitted to stay within input limits.]`;
|
||||
|
||||
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
|
||||
return message.role === "assistant" ? "ASSISTANT" : "USER";
|
||||
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" | "SYSTEM" {
|
||||
if (message.role === "assistant") {
|
||||
return "ASSISTANT";
|
||||
}
|
||||
if (message.role === "system") {
|
||||
return "SYSTEM";
|
||||
}
|
||||
return "USER";
|
||||
}
|
||||
|
||||
function attachmentSummary(message: ChatMessage): string | null {
|
||||
@@ -57,6 +85,85 @@ function finalizeWithPrompt(
|
||||
return text.length <= maxChars ? text : null;
|
||||
}
|
||||
|
||||
function buildTranscriptBody(messages: ReadonlyArray<ChatMessage>, omittedCount: number): string {
|
||||
const transcript = messages.map(buildMessageBlock).join("\n\n");
|
||||
if (omittedCount === 0) {
|
||||
return transcript;
|
||||
}
|
||||
if (transcript.length === 0) {
|
||||
return OMITTED_SUMMARY(omittedCount);
|
||||
}
|
||||
return `${OMITTED_SUMMARY(omittedCount)}\n\n${transcript}`;
|
||||
}
|
||||
|
||||
export function selectBootstrapMessages(
|
||||
previousMessages: ChatMessage[],
|
||||
latestPrompt: string,
|
||||
maxChars: number,
|
||||
): BootstrapMessageSelectionResult {
|
||||
const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;
|
||||
const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);
|
||||
const promptTruncated = latestPrompt.length !== promptOnly.length;
|
||||
|
||||
if (previousMessages.length === 0) {
|
||||
return {
|
||||
messages: [],
|
||||
omittedCount: 0,
|
||||
promptTruncated,
|
||||
};
|
||||
}
|
||||
|
||||
const newestFirstMessages: ChatMessage[] = [];
|
||||
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = previousMessages[index];
|
||||
if (!message) continue;
|
||||
newestFirstMessages.push(message);
|
||||
}
|
||||
|
||||
if (newestFirstMessages.length === 0) {
|
||||
return {
|
||||
messages: [],
|
||||
omittedCount: previousMessages.length,
|
||||
promptTruncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
let includedNewestFirst: ChatMessage[] = [];
|
||||
for (const message of newestFirstMessages) {
|
||||
const nextNewestFirst = [...includedNewestFirst, message];
|
||||
const nextChronological = nextNewestFirst.toReversed();
|
||||
const omittedCount = newestFirstMessages.length - nextChronological.length;
|
||||
const transcriptBody = buildTranscriptBody(nextChronological, omittedCount);
|
||||
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
break;
|
||||
}
|
||||
includedNewestFirst = nextNewestFirst;
|
||||
}
|
||||
|
||||
let includedChronological = includedNewestFirst.toReversed();
|
||||
while (true) {
|
||||
const omittedCount = newestFirstMessages.length - includedChronological.length;
|
||||
const transcriptBody = buildTranscriptBody(includedChronological, omittedCount);
|
||||
if (finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
return {
|
||||
messages: includedChronological,
|
||||
omittedCount,
|
||||
promptTruncated,
|
||||
};
|
||||
}
|
||||
|
||||
if (includedChronological.length === 0) {
|
||||
return {
|
||||
messages: [],
|
||||
omittedCount: previousMessages.length,
|
||||
promptTruncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
includedChronological = includedChronological.slice(1);
|
||||
}
|
||||
}
|
||||
|
||||
export function buildBootstrapInput(
|
||||
previousMessages: ChatMessage[],
|
||||
latestPrompt: string,
|
||||
@@ -73,15 +180,8 @@ export function buildBootstrapInput(
|
||||
truncated: promptOnly.length !== latestPrompt.length,
|
||||
};
|
||||
}
|
||||
|
||||
const newestFirstBlocks: string[] = [];
|
||||
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = previousMessages[index];
|
||||
if (!message) continue;
|
||||
newestFirstBlocks.push(buildMessageBlock(message));
|
||||
}
|
||||
|
||||
if (newestFirstBlocks.length === 0) {
|
||||
const selection = selectBootstrapMessages(previousMessages, latestPrompt, budget);
|
||||
if (selection.messages.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
@@ -90,50 +190,21 @@ export function buildBootstrapInput(
|
||||
};
|
||||
}
|
||||
|
||||
// Include a contiguous suffix from newest to oldest, then reverse to chronological.
|
||||
let includedNewestFirst: string[] = [];
|
||||
for (const block of newestFirstBlocks) {
|
||||
const nextNewestFirst = [...includedNewestFirst, block];
|
||||
const nextChronological = nextNewestFirst.toReversed();
|
||||
const omittedCount = newestFirstBlocks.length - nextChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`
|
||||
: nextChronological.join("\n\n");
|
||||
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
break;
|
||||
}
|
||||
includedNewestFirst = nextNewestFirst;
|
||||
const transcriptBody = buildTranscriptBody(selection.messages, selection.omittedCount);
|
||||
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
|
||||
if (!finalized) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: previousMessages.length,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
let includedChronological = includedNewestFirst.toReversed();
|
||||
while (true) {
|
||||
const omittedCount = newestFirstBlocks.length - includedChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
? includedChronological.length > 0
|
||||
? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`
|
||||
: OMITTED_SUMMARY(omittedCount)
|
||||
: includedChronological.join("\n\n");
|
||||
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
|
||||
if (finalized) {
|
||||
return {
|
||||
text: finalized,
|
||||
includedCount: includedChronological.length,
|
||||
omittedCount,
|
||||
truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,
|
||||
};
|
||||
}
|
||||
|
||||
if (includedChronological.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: previousMessages.length,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
includedChronological = includedChronological.slice(1);
|
||||
}
|
||||
return {
|
||||
text: finalized,
|
||||
includedCount: selection.messages.length,
|
||||
omittedCount: selection.omittedCount,
|
||||
truncated: selection.omittedCount > 0 || selection.promptTruncated,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
@@ -317,6 +317,18 @@ const ThreadCreateCommand = Schema.Struct({
|
||||
),
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||
seedMessages: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
messageId: MessageId,
|
||||
role: OrchestrationMessageRole,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(ChatAttachment),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user