Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge d497cd72f7 Fix BranchToolbar errors silently dropped for draft threads
Route errors through onError callback prop so draft thread errors
are handled via ChatView's setThreadError, which correctly updates
localDraftErrorsByThreadId instead of dispatching SET_ERROR that
silently no-ops for threads not in state.threads.

Co-authored-by: Julius Marminge <[email protected]>
2026-03-02 06:44:05 +00:00
Julius Marminge 9e99b8efdc Preserve draft env mode across thread and branch context updates
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
2026-03-01 22:26:54 -08:00
Julius Marmingeandcodex 4b4e3b1836 Show branch toolbar for local draft threads
Co-authored-by: codex <[email protected]>
2026-03-01 21:35:42 -08:00
Julius Marminge 822d8dfc17 Run setup script after promoting local draft threads
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
2026-03-01 20:21:28 -08:00
Julius Marminge 7c0b8bee70 Cover runtime undefined draft thread options in store test
- Build options object with runtime `undefined` values via cast
- Pass object into `setProjectDraftThreadId` to verify handling path
2026-03-01 20:21:28 -08:00
Julius Marminge 39fd14b73e Preserve draft branch/worktree when update options are undefined
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
2026-03-01 20:21:28 -08:00
Julius Marminge bd43372053 Clean up orphaned composer drafts and harden draft checks
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
2026-03-01 20:21:28 -08:00
Julius Marmingeandcodex 123eb96c52 Preserve explicit DEFAULT_MODEL draft overrides
Co-authored-by: codex <[email protected]>
2026-03-01 20:21:28 -08:00
Julius Marmingeandcodex ec18318e3c Address PR review feedback for draft model/error/persistence handling
Co-authored-by: codex <[email protected]>
2026-03-01 20:21:28 -08:00
Julius Marminge 5a904fc8cc Simplify composer draft persistence and remove debug instrumentation
- Remove ChatView draft persistence debug logging and storage size plumbing
- Drop in-memory persisted draft cache; use JSON storage directly
- Reconcile attachment IDs from localStorage and streamline image hydration
2026-03-01 20:21:28 -08:00
Julius Marminge a74511e765 Refactor draft thread lookups and cache persisted draft state
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
2026-03-01 20:21:28 -08:00
Julius Marminge ac39b6fe05 Defer thread creation until first message send
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
2026-03-01 20:21:28 -08:00
Julius Marminge 696cbcc7fd Unify project draft thread state in composer draft store
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
2026-03-01 20:21:28 -08:00
Julius Marminge 3a5a14c6ed Preserve draft metadata and dedupe composer image retries
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
2026-03-01 20:21:28 -08:00
Julius Marminge cadef14a84 Persist per-thread composer drafts and reuse project draft threads
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
2026-03-01 20:21:28 -08:00
8 changed files with 2002 additions and 166 deletions

No files matched your search

+2 -1
View File
@@ -27,7 +27,8 @@
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0"
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11"
},
"devDependencies": {
"@effect/language-service": "catalog:",
+68 -26
View File
@@ -9,6 +9,7 @@ import {
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
dedupeRemoteBranchesWithLocalMatches,
@@ -33,6 +34,7 @@ interface BranchToolbarProps {
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
onComposerFocusRequest?: () => void;
onError?: (error: string | null) => void;
}
export default function BranchToolbar({
@@ -41,19 +43,28 @@ export default function BranchToolbar({
onEnvModeChange,
envLocked,
onComposerFocusRequest,
onError,
}: BranchToolbarProps) {
const { state, dispatch } = useStore();
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const activeThread = state.threads.find((thread) => thread.id === threadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
const activeWorktreePath = activeThread?.worktreePath ?? null;
const serverThread = state.threads.find((thread) => thread.id === threadId);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = state.projects.find((project) => project.id === activeProjectId);
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode: "local" | "worktree" =
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
? "worktree"
: envMode;
// ── Queries ───────────────────────────────────────────────────────────
@@ -63,7 +74,7 @@ export default function BranchToolbar({
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
@@ -88,14 +99,14 @@ export default function BranchToolbar({
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
envMode: effectiveEnvMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api) {
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -104,13 +115,30 @@ export default function BranchToolbar({
worktreePath: null,
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
if (hasServerThread) {
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
return;
}
setDraftThreadContext(threadId, {
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
}, [
activeThreadId,
activeWorktreePath,
activeThreadBranch,
queryBranches,
effectiveEnvMode,
dispatch,
hasServerThread,
setDraftThreadContext,
threadId,
]);
useEffect(() => {
if (isBranchMenuOpen) return;
@@ -121,7 +149,11 @@ export default function BranchToolbar({
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
if (hasServerThread) {
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
} else {
onError?.(error);
}
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
@@ -129,7 +161,7 @@ export default function BranchToolbar({
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = activeThread?.session?.sessionId;
const sessionId = serverThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
@@ -140,7 +172,7 @@ export default function BranchToolbar({
})
.catch(() => undefined);
}
if (api) {
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -149,7 +181,15 @@ export default function BranchToolbar({
worktreePath,
});
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
if (hasServerThread) {
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
return;
}
setDraftThreadContext(threadId, {
branch,
worktreePath,
envMode: effectiveEnvMode,
});
};
const selectBranch = (branch: GitBranch) => {
@@ -157,7 +197,7 @@ export default function BranchToolbar({
if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch.
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
@@ -221,7 +261,7 @@ export default function BranchToolbar({
});
};
if (!activeThread || !activeProject) return null;
if (!activeThreadId || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
@@ -236,9 +276,11 @@ export default function BranchToolbar({
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
onClick={() =>
onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")
}
>
{envMode === "worktree" ? "New worktree" : "Local"}
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
@@ -248,7 +290,7 @@ export default function BranchToolbar({
autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen}
value={activeThread.branch}
value={activeThreadBranch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
@@ -256,10 +298,10 @@ export default function BranchToolbar({
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate">
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
{activeThreadBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${activeThreadBranch}`
: activeThreadBranch
: "Select branch"}
</span>
<ChevronDownIcon />
@@ -313,7 +355,7 @@ export default function BranchToolbar({
key={itemValue}
value={itemValue}
className={
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
+417 -97
View File
@@ -17,6 +17,7 @@ import {
type ProviderApprovalDecision,
type ThreadId,
type TurnId,
normalizeModelSlug,
resolveModelSlug,
} from "@t3tools/contracts";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -53,7 +54,7 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type ChatImageAttachment,
type Thread,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
@@ -111,6 +112,14 @@ import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import { getAppModelOptions, useAppSettings } from "../appSettings";
import {
type ComposerImageAttachment,
type DraftThreadEnvMode,
type DraftThreadState,
type PersistedComposerImageAttachment,
useComposerDraftStore,
useComposerThreadDraft,
} from "../composerDraftStore";
import { clamp } from "effect/Number";
function formatMessageMeta(createdAt: string, duration: string | null): string {
@@ -156,11 +165,6 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
return "text-muted-foreground/40";
}
interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
interface ExpandedImageItem {
src: string;
name: string;
@@ -191,6 +195,62 @@ function buildExpandedImagePreview(
};
}
function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
fallbackModel: string,
error: string | null,
): Thread {
return {
id: threadId,
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
model: fallbackModel,
terminalOpen: false,
terminalHeight: 280,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
error,
createdAt: draftThread.createdAt,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
turnDiffSummaries: [],
activities: [],
};
}
function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
return;
}
URL.revokeObjectURL(previewUrl);
}
function revokeUserMessagePreviewUrls(message: ChatMessage): void {
if (message.role !== "user" || !message.attachments) {
return;
}
for (const attachment of message.attachments) {
if (attachment.type !== "image") {
continue;
}
revokeBlobPreviewUrl(attachment.previewUrl);
}
}
type ComposerCommandItem =
| {
id: string;
@@ -239,6 +299,20 @@ function buildTemporaryWorktreeBranchName(): string {
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
function cloneComposerImageForRetry(image: ComposerImageAttachment): ComposerImageAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
try {
return {
...image,
previewUrl: URL.createObjectURL(image.file),
};
} catch {
return image;
}
}
const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
pathValue: string;
kind: "file" | "directory";
@@ -372,23 +446,44 @@ export default function ChatView({ threadId }: ChatViewProps) {
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const [prompt, setPrompt] = useState("");
const composerDraft = useComposerThreadDraft(threadId);
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
const composerCursor = composerDraft.cursor;
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const setComposerDraftCursor = useComposerDraftStore((store) => store.setCursor);
const setComposerDraftModel = useComposerDraftStore((store) => store.setModel);
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.clearPersistedAttachments,
);
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.syncPersistedAttachments,
);
const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const draftThread = useComposerDraftStore((store) => store.draftThreadsByThreadId[threadId] ?? null);
const promptRef = useRef(prompt);
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
const [envMode, setEnvMode] = useState<DraftThreadEnvMode>("local");
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerCursor, setComposerCursor] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
Record<string, string>
@@ -402,7 +497,55 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const activeThread = state.threads.find((t) => t.id === threadId);
const setPrompt = useCallback(
(nextPrompt: string) => {
setComposerDraftPrompt(threadId, nextPrompt);
},
[setComposerDraftPrompt, threadId],
);
const setComposerCursor = useCallback(
(nextCursor: number) => {
setComposerDraftCursor(threadId, nextCursor);
},
[setComposerDraftCursor, threadId],
);
const addComposerImage = useCallback(
(image: ComposerImageAttachment) => {
addComposerDraftImage(threadId, image);
},
[addComposerDraftImage, threadId],
);
const addComposerImagesToDraft = useCallback(
(images: ComposerImageAttachment[]) => {
addComposerDraftImages(threadId, images);
},
[addComposerDraftImages, threadId],
);
const removeComposerImageFromDraft = useCallback(
(imageId: string) => {
removeComposerDraftImage(threadId, imageId);
},
[removeComposerDraftImage, threadId],
);
const serverThread = state.threads.find((t) => t.id === threadId);
const fallbackDraftProject = state.projects.find((project) => project.id === draftThread?.projectId);
const localDraftError = localDraftErrorsByThreadId[threadId] ?? null;
const localDraftThread = useMemo(
() =>
draftThread
? buildLocalDraftThread(
threadId,
draftThread,
fallbackDraftProject?.model ?? DEFAULT_MODEL,
localDraftError,
)
: undefined,
[draftThread, fallbackDraftProject?.model, localDraftError, threadId],
);
const activeThread = serverThread ?? localDraftThread;
const isServerThread = serverThread !== undefined;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
@@ -413,6 +556,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
useEffect(() => {
if (!serverThread) {
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if (!(threadId in existing)) {
return existing;
}
const { [threadId]: _removed, ...rest } = existing;
return rest as Record<ThreadId, string | null>;
});
}, [serverThread, threadId]);
useEffect(() => {
if (!activeThread?.id) return;
if (!latestTurnSettled) return;
@@ -434,9 +590,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
dispatch,
]);
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
const baseThreadModel = resolveModelSlug(activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL);
const selectedModel = resolveModelSlug(composerDraft.model ?? baseThreadModel);
const selectedEffort = composerDraft.effort ?? DEFAULT_REASONING;
const modelOptions = useMemo(
() => getAppModelOptions(settings.customCodexModels, selectedModel),
[selectedModel, settings.customCodexModels],
@@ -645,6 +801,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
null,
[composerHighlightedItemId, composerMenuItems],
);
const nonPersistedComposerImageIdSet = useMemo(
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
);
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
const threadTerminalRuntimeEnv = useMemo(() => {
if (!activeProject?.cwd) return {};
@@ -693,12 +853,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
for (const image of images) {
if (!image.previewUrl) continue;
URL.revokeObjectURL(image.previewUrl);
}
}, []);
const focusComposer = useCallback(() => {
const textarea = textareaRef.current;
if (!textarea) return;
@@ -788,10 +942,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath?: string | null;
preferNewTerminal?: boolean;
rememberAsLastInvoked?: boolean;
allowLocalDraftThread?: boolean;
},
) => {
const api = readNativeApi();
if (!api || !activeThreadId || !activeProject || !activeThread) return;
if (!isServerThread && !options?.allowLocalDraftThread) return;
if (options?.rememberAsLastInvoked !== false) {
setLastInvokedScriptByProjectId((current) => {
if (current[activeProject.id] === script.id) return current;
@@ -863,7 +1019,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
},
[activeProject, activeThread, activeThreadId, dispatch, gitCwd],
[activeProject, activeThread, activeThreadId, dispatch, gitCwd, isServerThread],
);
const persistProjectScripts = useCallback(
async (input: {
@@ -1074,7 +1230,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThread?.id) {
setOptimisticUserMessages([]);
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
}
return [];
});
return;
}
if (activeThread.messages.length === 0) {
@@ -1082,32 +1243,98 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
const serverIds = new Set(activeThread.messages.map((message) => message.id));
setOptimisticUserMessages((existing) => {
const removed = existing.filter((message) => serverIds.has(message.id));
for (const message of removed) {
revokeUserMessagePreviewUrls(message);
}
const next = existing.filter((message) => !serverIds.has(message.id));
return next.length === existing.length ? existing : next;
});
}, [activeThread?.id, activeThread?.messages]);
useEffect(() => {
setComposerImages((existing) => {
revokePreviewUrls(existing);
promptRef.current = prompt;
}, [prompt]);
useEffect(() => {
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
}
return [];
});
setOptimisticUserMessages([]);
setPrompt("");
promptRef.current = "";
setSendPhase("idle");
setComposerCursor(0);
setComposerHighlightedItemId(null);
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [activeThread?.id, revokePreviewUrls]);
}, [threadId]);
useEffect(() => {
let cancelled = false;
void (async () => {
if (composerImages.length === 0) {
clearComposerDraftPersistedAttachments(threadId);
return;
}
try {
const currentPersistedAttachments =
useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
const existingPersistedById = new Map(
currentPersistedAttachments.map((attachment) => [attachment.id, attachment]),
);
const stagedAttachmentById = new Map<string, PersistedComposerImageAttachment>();
await Promise.all(
composerImages.map(async (image) => {
try {
const dataUrl = await readFileAsDataUrl(image.file);
stagedAttachmentById.set(image.id, {
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl,
});
} catch {
const existingPersisted = existingPersistedById.get(image.id);
if (existingPersisted) {
stagedAttachmentById.set(image.id, existingPersisted);
}
}
}),
);
const serialized = Array.from(stagedAttachmentById.values());
if (cancelled) {
return;
}
// Stage attachments in persisted draft state first so persist middleware can write them.
syncComposerDraftPersistedAttachments(threadId, serialized);
} catch {
const currentImageIds = new Set(composerImages.map((image) => image.id));
const fallbackPersistedAttachments =
useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
const fallbackPersistedIds = fallbackPersistedAttachments
.map((attachment) => attachment.id)
.filter((id) => currentImageIds.has(id));
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
fallbackPersistedIdSet.has(attachment.id),
);
if (cancelled) {
return;
}
syncComposerDraftPersistedAttachments(threadId, fallbackAttachments);
}
})();
return () => {
revokePreviewUrls(composerImagesRef.current);
cancelled = true;
};
}, [revokePreviewUrls]);
}, [
clearComposerDraftPersistedAttachments,
composerImages,
syncComposerDraftPersistedAttachments,
threadId,
]);
const closeExpandedImage = useCallback(() => {
setExpandedImage(null);
@@ -1161,8 +1388,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThread?.id) return;
setEnvMode(activeWorktreePath ? "worktree" : "local");
}, [activeThread?.id, activeWorktreePath]);
if (activeWorktreePath) {
setEnvMode("worktree");
return;
}
if (isLocalDraftThread) {
setEnvMode(draftThread?.envMode ?? "local");
return;
}
setEnvMode("local");
}, [activeThread?.id, activeWorktreePath, draftThread?.envMode, isLocalDraftThread]);
// Auto-resize textarea
useEffect(() => {
@@ -1298,19 +1533,32 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(threadId: ThreadId | null, error: string | null) => {
if (!threadId) return;
dispatch({
type: "SET_ERROR",
threadId,
error,
if (state.threads.some((thread) => thread.id === threadId)) {
dispatch({
type: "SET_ERROR",
threadId,
error,
});
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if ((existing[threadId] ?? null) === error) {
return existing;
}
return {
...existing,
[threadId]: error,
};
});
},
[dispatch],
[dispatch, state.threads],
);
const addComposerImages = (files: File[]) => {
if (!activeThreadId || files.length === 0) return;
const nextImages = [...composerImagesRef.current];
const nextImages: ComposerImageAttachment[] = [];
let nextImageCount = composerImagesRef.current.length;
let error: string | null = null;
for (const file of files) {
if (!file.type.startsWith("image/")) {
@@ -1321,7 +1569,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue;
}
if (nextImages.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
}
@@ -1336,20 +1584,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
previewUrl,
file,
});
nextImageCount += 1;
}
setComposerImages(nextImages);
if (nextImages.length === 1 && nextImages[0]) {
addComposerImage(nextImages[0]);
} else if (nextImages.length > 1) {
addComposerImagesToDraft(nextImages);
}
setThreadError(activeThreadId, error);
};
const removeComposerImage = (imageId: string) => {
setComposerImages((existing) => {
const match = existing.find((image) => image.id === imageId);
if (match?.previewUrl) {
URL.revokeObjectURL(match.previewUrl);
}
return existing.filter((image) => image.id !== imageId);
});
removeComposerImageFromDraft(imageId);
};
const onComposerPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
@@ -1460,7 +1707,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
const threadIdForSend = activeThread.id;
const isFirstMessage = activeThread.messages.length === 0;
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
const baseBranchForWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch
@@ -1516,12 +1763,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
setThreadError(threadIdForSend, null);
promptRef.current = "";
setPrompt("");
setComposerImages([]);
setComposerCursor(0);
clearComposerDraftContent(threadIdForSend);
setComposerHighlightedItemId(null);
let attemptedTurnStart = false;
let createdServerThreadForLocalDraft = false;
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
try {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
@@ -1532,39 +1780,63 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: baseBranchForWorktree,
newBranch,
});
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
await runProjectScript(setupScript, {
cwd: result.worktree.path,
nextThreadBranch = result.worktree.branch;
nextThreadWorktreePath = result.worktree.path;
if (isServerThread) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
});
}
}
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
if (isLocalDraftThread) {
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: threadIdForSend,
projectId: activeProject.id,
title,
model: selectedModel ?? activeProject.model ?? DEFAULT_MODEL,
branch: nextThreadBranch,
worktreePath: nextThreadWorktreePath,
createdAt: activeThread.createdAt,
});
createdServerThreadForLocalDraft = true;
}
const setupScript = baseBranchForWorktree
? setupProjectScript(activeProject.scripts)
: null;
if (setupScript && (isServerThread || createdServerThreadForLocalDraft)) {
await runProjectScript(setupScript, {
worktreePath: nextThreadWorktreePath,
rememberAsLastInvoked: false,
allowLocalDraftThread: createdServerThreadForLocalDraft,
...(nextThreadWorktreePath ? { cwd: nextThreadWorktreePath } : {}),
});
}
// Auto-title from first message
if (isFirstMessage) {
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
if (isFirstMessage && isServerThread) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -1575,7 +1847,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
setSendPhase("sending-turn");
const turnAttachments = await turnAttachmentsPromise;
attemptedTurnStart = true;
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
const sandboxMode =
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
@@ -1596,18 +1867,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
sandboxMode,
createdAt: messageCreatedAt,
});
turnStartSucceeded = true;
if (isFirstMessage) {
clearDraftThread(threadIdForSend);
}
} catch (err) {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: threadIdForSend,
})
.catch(() => undefined);
}
if (
!attemptedTurnStart &&
!turnStartSucceeded &&
promptRef.current.length === 0 &&
composerImagesRef.current.length === 0
) {
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
setOptimisticUserMessages((existing) => {
const removed = existing.filter((message) => message.id === messageIdForSend);
for (const message of removed) {
revokeUserMessagePreviewUrls(message);
}
const next = existing.filter((message) => message.id !== messageIdForSend);
return next.length === existing.length ? existing : next;
});
promptRef.current = trimmed;
setPrompt(trimmed);
setComposerImages(composerImagesSnapshot);
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
setComposerCursor(trimmed.length);
}
setThreadError(
@@ -1663,33 +1952,45 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onModelSelect = useCallback(
(model: string) => {
const normalizedModel = normalizeModelSlug(model);
const resolvedModel = normalizedModel ?? baseThreadModel;
setComposerDraftModel(threadId, resolvedModel === baseThreadModel ? null : resolvedModel);
const api = readNativeApi();
if (!activeThread) return;
if (api) {
if (api && isServerThread && activeThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThread.id,
model: resolveModelSlug(model),
model: resolvedModel,
});
}
scheduleComposerFocus();
},
[activeThread, scheduleComposerFocus],
[
activeThread,
baseThreadModel,
isServerThread,
scheduleComposerFocus,
setComposerDraftModel,
threadId,
],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
setSelectedEffort(effort);
setComposerDraftEffort(threadId, effort);
scheduleComposerFocus();
},
[scheduleComposerFocus],
[scheduleComposerFocus, setComposerDraftEffort, threadId],
);
const onEnvModeChange = useCallback(
(mode: "local" | "worktree") => {
(mode: DraftThreadEnvMode) => {
setEnvMode(mode);
if (isLocalDraftThread) {
setDraftThreadContext(threadId, { envMode: mode });
}
scheduleComposerFocus();
},
[scheduleComposerFocus],
[isLocalDraftThread, scheduleComposerFocus, setDraftThreadContext, threadId],
);
const applyPromptReplacement = useCallback(
@@ -1705,7 +2006,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerCursor(next.cursor);
});
},
[],
[setComposerCursor, setPrompt],
);
const onSelectComposerItem = useCallback(
@@ -1748,7 +2049,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
setComposerCursor(nextCursor);
}, []);
}, [setComposerCursor, setPrompt]);
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (composerMenuOpen && composerMenuItems.length > 0) {
@@ -1960,6 +2261,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
{image.name}
</div>
)}
{nonPersistedComposerImageIdSet.has(image.id) && (
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label="Draft attachment may not persist"
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
>
<CircleAlertIcon className="size-3" />
</span>
}
/>
<TooltipPopup side="top" className="max-w-64 whitespace-normal leading-tight">
Draft attachment could not be saved locally and may be lost on navigation.
</TooltipPopup>
</Tooltip>
)}
<Button
variant="ghost"
size="icon-xs"
@@ -2144,6 +2463,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onEnvModeChange={onEnvModeChange}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
onError={(error) => setThreadError(activeThread.id, error)}
/>
)}
+104 -39
View File
@@ -20,6 +20,7 @@ import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -228,6 +229,19 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
export default function Sidebar() {
const { state, dispatch } = useStore();
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const clearProjectDraftThreadId = useComposerDraftStore(
(store) => store.clearProjectDraftThreadId,
);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
);
const navigate = useNavigate();
const { settings: appSettings } = useAppSettings();
const routeThreadId = useParams({
@@ -265,15 +279,14 @@ export default function Sidebar() {
[projectCwdById, state.threads],
);
const threadGitStatusCwds = useMemo(
() =>
[
...new Set(
threadGitTargets
.filter((target) => target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
],
() => [
...new Set(
threadGitTargets
.filter((target) => target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
],
[threadGitTargets],
);
const threadGitStatusQueries = useQueries({
@@ -332,42 +345,71 @@ export default function Sidebar() {
options?: {
branch?: string | null;
worktreePath?: string | null;
envMode?: DraftThreadEnvMode;
},
): Promise<void> => {
const api = readNativeApi();
if (!api) return Promise.resolve();
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
const hasEnvModeOption = options?.envMode !== undefined;
const storedDraftThread = getDraftThreadByProjectId(projectId);
if (storedDraftThread) {
return (async () => {
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
setDraftThreadContext(storedDraftThread.threadId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
}
setProjectDraftThreadId(projectId, storedDraftThread.threadId);
if (routeThreadId === storedDraftThread.threadId) {
return;
}
await navigate({
to: "/$threadId",
params: { threadId: storedDraftThread.threadId },
});
})();
}
clearProjectDraftThreadId(projectId);
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
if (activeDraftThread && routeThreadId && activeDraftThread.projectId === projectId) {
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
setDraftThreadContext(routeThreadId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
}
setProjectDraftThreadId(projectId, routeThreadId);
return Promise.resolve();
}
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const model =
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
return (async () => {
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId,
projectId,
title: "New thread",
model,
setProjectDraftThreadId(projectId, threadId, {
createdAt,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
createdAt,
envMode: options?.envMode ?? "local",
});
// Ensure route guards can see the new thread before navigating.
try {
const snapshot = await api.orchestration.getSnapshot();
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
} catch {
// Event stream can still hydrate the thread shortly after dispatch.
}
await navigate({
to: "/$threadId",
params: { threadId },
});
})();
},
[dispatch, navigate, state.projects],
[
clearProjectDraftThreadId,
getDraftThreadByProjectId,
navigate,
getDraftThread,
routeThreadId,
setDraftThreadContext,
setProjectDraftThreadId,
],
);
const focusMostRecentThreadForProject = useCallback(
@@ -517,6 +559,8 @@ export default function Sidebar() {
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
@@ -556,6 +600,8 @@ export default function Sidebar() {
},
[
appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
dispatch,
navigate,
removeWorktreeMutation,
@@ -591,6 +637,11 @@ export default function Sidebar() {
if (!confirmed) return;
try {
const projectDraftThread = getDraftThreadByProjectId(projectId);
if (projectDraftThread) {
clearComposerDraftForThread(projectDraftThread.threadId);
}
clearProjectDraftThreadId(projectId);
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: newCommandId(),
@@ -606,7 +657,13 @@ export default function Sidebar() {
});
}
},
[state.projects, state.threads],
[
clearComposerDraftForThread,
clearProjectDraftThreadId,
getDraftThreadByProjectId,
state.projects,
state.threads,
],
);
useEffect(() => {
@@ -614,8 +671,10 @@ export default function Sidebar() {
const activeThread = routeThreadId
? state.threads.find((thread) => thread.id === routeThreadId)
: undefined;
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId);
@@ -623,12 +682,16 @@ export default function Sidebar() {
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ??
(activeThread?.worktreePath ? "worktree" : "local"),
});
};
@@ -636,7 +699,7 @@ export default function Sidebar() {
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
const onCreateThreadClick = () => {
if (state.projects.length === 0) {
@@ -693,7 +756,7 @@ export default function Sidebar() {
<SidebarGroup className="px-2 py-2">
<SidebarMenu>
{state.projects.map((project) => {
const threads = state.threads
const visibleThreads = state.threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
@@ -736,12 +799,14 @@ export default function Sidebar() {
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
<span className="text-[10px] text-muted-foreground/60">
{visibleThreads.length}
</span>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
{threads.map((thread) => {
{visibleThreads.map((thread) => {
const isActive = routeThreadId === thread.id;
const threadStatus = threadStatusPill(
thread,
+350
View File
@@ -0,0 +1,350 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
function makeImage(input: {
id: string;
previewUrl: string;
name?: string;
mimeType?: string;
sizeBytes?: number;
lastModified?: number;
}): ComposerImageAttachment {
const name = input.name ?? "image.png";
const mimeType = input.mimeType ?? "image/png";
const sizeBytes = input.sizeBytes ?? 4;
const lastModified = input.lastModified ?? 1_700_000_000_000;
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
type: mimeType,
lastModified,
});
return {
type: "image",
id: input.id,
name,
mimeType,
sizeBytes: file.size,
previewUrl: input.previewUrl,
file,
};
}
describe("composerDraftStore addImages", () => {
const threadId = ThreadId.makeUnsafe("thread-dedupe");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("deduplicates identical images in one batch by file signature", () => {
const first = makeImage({
id: "img-1",
previewUrl: "blob:first",
name: "same.png",
mimeType: "image/png",
sizeBytes: 12,
lastModified: 12345,
});
const duplicate = makeImage({
id: "img-2",
previewUrl: "blob:duplicate",
name: "same.png",
mimeType: "image/png",
sizeBytes: 12,
lastModified: 12345,
});
useComposerDraftStore.getState().addImages(threadId, [first, duplicate]);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-1"]);
expect(revokeSpy).toHaveBeenCalledWith("blob:duplicate");
});
it("deduplicates against existing images across calls by file signature", () => {
const first = makeImage({
id: "img-a",
previewUrl: "blob:a",
name: "same.png",
mimeType: "image/png",
sizeBytes: 9,
lastModified: 777,
});
const duplicateLater = makeImage({
id: "img-b",
previewUrl: "blob:b",
name: "same.png",
mimeType: "image/png",
sizeBytes: 9,
lastModified: 999,
});
useComposerDraftStore.getState().addImage(threadId, first);
useComposerDraftStore.getState().addImage(threadId, duplicateLater);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-a"]);
expect(revokeSpy).toHaveBeenCalledWith("blob:b");
});
it("does not revoke blob URLs that are still used by an accepted duplicate image", () => {
const first = makeImage({
id: "img-shared",
previewUrl: "blob:shared",
});
const duplicateSameUrl = makeImage({
id: "img-shared",
previewUrl: "blob:shared",
});
useComposerDraftStore.getState().addImages(threadId, [first, duplicateSameUrl]);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-shared"]);
expect(revokeSpy).not.toHaveBeenCalledWith("blob:shared");
});
});
describe("composerDraftStore clearComposerContent", () => {
const threadId = ThreadId.makeUnsafe("thread-clear");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("does not revoke blob preview URLs when clearing composer content", () => {
const first = makeImage({
id: "img-optimistic",
previewUrl: "blob:optimistic",
});
useComposerDraftStore.getState().addImage(threadId, first);
useComposerDraftStore.getState().clearComposerContent(threadId);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft).toBeUndefined();
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
});
});
describe("composerDraftStore project draft thread mapping", () => {
const projectId = ProjectId.makeUnsafe("project-a");
const otherProjectId = ProjectId.makeUnsafe("project-b");
const threadId = ThreadId.makeUnsafe("thread-a");
const otherThreadId = ThreadId.makeUnsafe("thread-b");
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("stores and reads project draft thread ids via actions", () => {
const store = useComposerDraftStore.getState();
expect(store.getDraftThreadByProjectId(projectId)).toBeNull();
expect(store.getDraftThread(threadId)).toBeNull();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toEqual({
threadId,
projectId,
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toEqual({
projectId,
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
createdAt: "2026-01-01T00:00:00.000Z",
});
});
it("clears only matching project draft mapping entries", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "hello");
store.clearProjectDraftThreadById(projectId, otherThreadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
threadId,
);
store.clearProjectDraftThreadById(projectId, threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears project draft mapping by project id", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "hello");
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears orphaned composer drafts when remapping a project to a new draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "orphan me");
store.setProjectDraftThreadId(projectId, otherThreadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
otherThreadId,
);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("keeps composer drafts when the thread is still mapped by another project", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setProjectDraftThreadId(otherProjectId, threadId);
store.setPrompt(threadId, "keep me");
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId).toBe(
threadId,
);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("clears draft registration independently", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.clearDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
});
it("updates branch context on an existing draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "main",
worktreePath: null,
});
store.setDraftThreadContext(threadId, {
branch: "feature/next",
worktreePath: "/tmp/feature-next",
});
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
threadId,
);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "feature/next",
worktreePath: "/tmp/feature-next",
envMode: "worktree",
});
});
it("preserves existing branch and worktree when setProjectDraftThreadId receives undefined", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "main",
worktreePath: "/tmp/main-worktree",
});
const runtimeUndefinedOptions = {
branch: undefined,
worktreePath: undefined,
} as unknown as {
branch?: string | null;
worktreePath?: string | null;
};
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "main",
worktreePath: "/tmp/main-worktree",
envMode: "worktree",
});
});
it("preserves worktree env mode without a worktree path", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "feature/base",
worktreePath: null,
envMode: "worktree",
});
const runtimeUndefinedOptions = {
branch: undefined,
worktreePath: undefined,
envMode: undefined,
} as unknown as {
branch?: string | null;
worktreePath?: string | null;
envMode?: "local" | "worktree";
};
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "feature/base",
worktreePath: null,
envMode: "worktree",
});
});
});
describe("composerDraftStore setModel", () => {
const threadId = ThreadId.makeUnsafe("thread-model");
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
const store = useComposerDraftStore.getState();
store.setModel(threadId, "gpt-5.3-codex");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe("gpt-5.3-codex");
});
});
File diff suppressed because it is too large. Load diff
+8 -3
View File
@@ -3,6 +3,7 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
import ChatView from "../components/ChatView";
import { useComposerDraftStore } from "../composerDraftStore";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
@@ -139,6 +140,10 @@ function ChatThreadRouteView() {
});
const search = Route.useSearch();
const threadExists = state.threads.some((thread) => thread.id === threadId);
const draftThreadExists = useComposerDraftStore(
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
);
const routeThreadExists = threadExists || draftThreadExists;
const diffOpen = search.diff === "1";
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const closeDiff = useCallback(() => {
@@ -166,13 +171,13 @@ function ChatThreadRouteView() {
return;
}
if (!threadExists) {
if (!routeThreadExists) {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, state.threadsHydrated, threadExists, threadId]);
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
if (!state.threadsHydrated || !threadExists) {
if (!state.threadsHydrated || !routeThreadExists) {
return null;
}
+3
View File
@@ -79,6 +79,7 @@
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11",
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -1417,6 +1418,8 @@
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg=="],
"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],