Compare commits

...
Author SHA1 Message Date
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 1994 additions and 165 deletions

No files matched your search

+2 -1
View File
@@ -27,7 +27,8 @@
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0" "tailwind-merge": "^3.4.0",
"zustand": "^5.0.11"
}, },
"devDependencies": { "devDependencies": {
"@effect/language-service": "catalog:", "@effect/language-service": "catalog:",
+61 -25
View File
@@ -9,6 +9,7 @@ import {
gitCreateBranchAndCheckoutMutationOptions, gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery"; } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi"; import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store"; import { useStore } from "../store";
import { import {
dedupeRemoteBranchesWithLocalMatches, dedupeRemoteBranchesWithLocalMatches,
@@ -43,17 +44,25 @@ export default function BranchToolbar({
onComposerFocusRequest, onComposerFocusRequest,
}: BranchToolbarProps) { }: BranchToolbarProps) {
const { state, dispatch } = useStore(); const { state, dispatch } = useStore();
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false); const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState(""); const [branchQuery, setBranchQuery] = useState("");
const activeThread = state.threads.find((thread) => thread.id === threadId); const serverThread = state.threads.find((thread) => thread.id === threadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId); const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeThreadId = activeThread?.id; const activeProject = state.projects.find((project) => project.id === activeProjectId);
const activeThreadBranch = activeThread?.branch ?? null; const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeWorktreePath = activeThread?.worktreePath ?? null; const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null; const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode: "local" | "worktree" =
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
? "worktree"
: envMode;
// ── Queries ─────────────────────────────────────────────────────────── // ── Queries ───────────────────────────────────────────────────────────
@@ -63,7 +72,7 @@ export default function BranchToolbar({
const branchNames = branches.map((branch) => branch.name); const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch])); const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim(); const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0; const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery); const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}` ? `__create_new_branch__:${trimmedBranchQuery}`
@@ -88,14 +97,14 @@ export default function BranchToolbar({
const syncedBranch = deriveSyncedLocalBranch({ const syncedBranch = deriveSyncedLocalBranch({
activeThreadId, activeThreadId,
activeWorktreePath, activeWorktreePath,
envMode, envMode: effectiveEnvMode,
activeThreadBranch, activeThreadBranch,
queryBranches, queryBranches,
}); });
if (!activeThreadId || !syncedBranch) return; if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi(); const api = readNativeApi();
if (api) { if (api && hasServerThread) {
void api.orchestration.dispatchCommand({ void api.orchestration.dispatchCommand({
type: "thread.meta.update", type: "thread.meta.update",
commandId: newCommandId(), commandId: newCommandId(),
@@ -104,13 +113,30 @@ export default function BranchToolbar({
worktreePath: null, worktreePath: null,
}); });
} }
dispatch({ if (hasServerThread) {
type: "SET_THREAD_BRANCH", dispatch({
threadId: activeThreadId, type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
return;
}
setDraftThreadContext(threadId, {
branch: syncedBranch, branch: syncedBranch,
worktreePath: null, worktreePath: null,
}); });
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]); }, [
activeThreadId,
activeWorktreePath,
activeThreadBranch,
queryBranches,
effectiveEnvMode,
dispatch,
hasServerThread,
setDraftThreadContext,
threadId,
]);
useEffect(() => { useEffect(() => {
if (isBranchMenuOpen) return; if (isBranchMenuOpen) return;
@@ -129,7 +155,7 @@ export default function BranchToolbar({
const api = readNativeApi(); const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the // If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd. // 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) { if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration void api.orchestration
.dispatchCommand({ .dispatchCommand({
@@ -140,7 +166,7 @@ export default function BranchToolbar({
}) })
.catch(() => undefined); .catch(() => undefined);
} }
if (api) { if (api && hasServerThread) {
void api.orchestration.dispatchCommand({ void api.orchestration.dispatchCommand({
type: "thread.meta.update", type: "thread.meta.update",
commandId: newCommandId(), commandId: newCommandId(),
@@ -149,7 +175,15 @@ export default function BranchToolbar({
worktreePath, 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) => { const selectBranch = (branch: GitBranch) => {
@@ -157,7 +191,7 @@ export default function BranchToolbar({
if (!api || !activeThreadId || !branchCwd) return; if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch. // For new worktree mode, selecting a branch picks the base branch.
if (envMode === "worktree" && !envLocked && !activeWorktreePath) { if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null); setThreadError(null);
setThreadBranch(branch.name, null); setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false); setIsBranchMenuOpen(false);
@@ -221,7 +255,7 @@ export default function BranchToolbar({
}); });
}; };
if (!activeThread || !activeProject) return null; if (!activeThreadId || !activeProject) return null;
return ( return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1"> <div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
@@ -236,9 +270,11 @@ export default function BranchToolbar({
variant="ghost" variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80" className="text-muted-foreground/70 hover:text-foreground/80"
size="xs" 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> </Button>
)} )}
</div> </div>
@@ -248,7 +284,7 @@ export default function BranchToolbar({
autoHighlight autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)} onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen} open={isBranchMenuOpen}
value={activeThread.branch} value={activeThreadBranch}
> >
<ComboboxTrigger <ComboboxTrigger
render={<Button variant="ghost" size="xs" />} render={<Button variant="ghost" size="xs" />}
@@ -256,10 +292,10 @@ export default function BranchToolbar({
disabled={branchesQuery.isLoading} disabled={branchesQuery.isLoading}
> >
<span className="max-w-[240px] truncate"> <span className="max-w-[240px] truncate">
{activeThread.branch {activeThreadBranch
? envMode === "worktree" && !activeWorktreePath ? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}` ? `From ${activeThreadBranch}`
: activeThread.branch : activeThreadBranch
: "Select branch"} : "Select branch"}
</span> </span>
<ChevronDownIcon /> <ChevronDownIcon />
@@ -313,7 +349,7 @@ export default function BranchToolbar({
key={itemValue} key={itemValue}
value={itemValue} value={itemValue}
className={ className={
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
} }
onClick={() => selectBranch(branch)} onClick={() => selectBranch(branch)}
> >
+416 -97
View File
@@ -17,6 +17,7 @@ import {
type ProviderApprovalDecision, type ProviderApprovalDecision,
type ThreadId, type ThreadId,
type TurnId, type TurnId,
normalizeModelSlug,
resolveModelSlug, resolveModelSlug,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -53,7 +54,7 @@ import {
DEFAULT_THREAD_TERMINAL_ID, DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT, MAX_THREAD_TERMINAL_COUNT,
type ChatMessage, type ChatMessage,
type ChatImageAttachment, type Thread,
type TurnDiffSummary, type TurnDiffSummary,
} from "../types"; } from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons"; import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
@@ -111,6 +112,14 @@ import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId } from "~/lib/utils"; import { newCommandId, newMessageId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi"; import { readNativeApi } from "~/nativeApi";
import { getAppModelOptions, useAppSettings } from "../appSettings"; import { getAppModelOptions, useAppSettings } from "../appSettings";
import {
type ComposerImageAttachment,
type DraftThreadEnvMode,
type DraftThreadState,
type PersistedComposerImageAttachment,
useComposerDraftStore,
useComposerThreadDraft,
} from "../composerDraftStore";
import { clamp } from "effect/Number"; import { clamp } from "effect/Number";
function formatMessageMeta(createdAt: string, duration: string | null): string { 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"; return "text-muted-foreground/40";
} }
interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
interface ExpandedImageItem { interface ExpandedImageItem {
src: string; src: string;
name: 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 = type ComposerCommandItem =
| { | {
id: string; id: string;
@@ -239,6 +299,20 @@ function buildTemporaryWorktreeBranchName(): string {
return `${WORKTREE_BRANCH_PREFIX}/${token}`; 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: { const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
pathValue: string; pathValue: string;
kind: "file" | "directory"; kind: "file" | "directory";
@@ -372,23 +446,44 @@ export default function ChatView({ threadId }: ChatViewProps) {
const { resolvedTheme } = useTheme(); const { resolvedTheme } = useTheme();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient })); 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 promptRef = useRef(prompt);
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
const [isDragOverComposer, setIsDragOverComposer] = useState(false); const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null); const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]); const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [sendPhase, setSendPhase] = useState<SendPhase>("idle"); const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
const [isConnecting, _setIsConnecting] = useState(false); const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING); const [envMode, setEnvMode] = useState<DraftThreadEnvMode>("local");
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false); const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]); const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({}); const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [nowTick, setNowTick] = useState(() => Date.now()); const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0); const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerCursor, setComposerCursor] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null); const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState< const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
Record<string, string> Record<string, string>
@@ -402,7 +497,55 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0); const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({}); 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( const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>), () => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch], [rawSearch],
@@ -413,6 +556,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null); const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId); 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(() => { useEffect(() => {
if (!activeThread?.id) return; if (!activeThread?.id) return;
if (!latestTurnSettled) return; if (!latestTurnSettled) return;
@@ -434,9 +590,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
dispatch, dispatch,
]); ]);
const selectedModel = resolveModelSlug( const baseThreadModel = resolveModelSlug(activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL);
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL, const selectedModel = resolveModelSlug(composerDraft.model ?? baseThreadModel);
); const selectedEffort = composerDraft.effort ?? DEFAULT_REASONING;
const modelOptions = useMemo( const modelOptions = useMemo(
() => getAppModelOptions(settings.customCodexModels, selectedModel), () => getAppModelOptions(settings.customCodexModels, selectedModel),
[selectedModel, settings.customCodexModels], [selectedModel, settings.customCodexModels],
@@ -645,6 +801,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
null, null,
[composerHighlightedItemId, composerMenuItems], [composerHighlightedItemId, composerMenuItems],
); );
const nonPersistedComposerImageIdSet = useMemo(
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
);
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS; const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
const threadTerminalRuntimeEnv = useMemo(() => { const threadTerminalRuntimeEnv = useMemo(() => {
if (!activeProject?.cwd) return {}; if (!activeProject?.cwd) return {};
@@ -693,12 +853,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const hasReachedTerminalLimit = const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT; (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 focusComposer = useCallback(() => {
const textarea = textareaRef.current; const textarea = textareaRef.current;
if (!textarea) return; if (!textarea) return;
@@ -788,10 +942,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath?: string | null; worktreePath?: string | null;
preferNewTerminal?: boolean; preferNewTerminal?: boolean;
rememberAsLastInvoked?: boolean; rememberAsLastInvoked?: boolean;
allowLocalDraftThread?: boolean;
}, },
) => { ) => {
const api = readNativeApi(); const api = readNativeApi();
if (!api || !activeThreadId || !activeProject || !activeThread) return; if (!api || !activeThreadId || !activeProject || !activeThread) return;
if (!isServerThread && !options?.allowLocalDraftThread) return;
if (options?.rememberAsLastInvoked !== false) { if (options?.rememberAsLastInvoked !== false) {
setLastInvokedScriptByProjectId((current) => { setLastInvokedScriptByProjectId((current) => {
if (current[activeProject.id] === script.id) return 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( const persistProjectScripts = useCallback(
async (input: { async (input: {
@@ -1074,7 +1230,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => { useEffect(() => {
if (!activeThread?.id) { if (!activeThread?.id) {
setOptimisticUserMessages([]); setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
}
return [];
});
return; return;
} }
if (activeThread.messages.length === 0) { 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)); const serverIds = new Set(activeThread.messages.map((message) => message.id));
setOptimisticUserMessages((existing) => { 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)); const next = existing.filter((message) => !serverIds.has(message.id));
return next.length === existing.length ? existing : next; return next.length === existing.length ? existing : next;
}); });
}, [activeThread?.id, activeThread?.messages]); }, [activeThread?.id, activeThread?.messages]);
useEffect(() => { useEffect(() => {
setComposerImages((existing) => { promptRef.current = prompt;
revokePreviewUrls(existing); }, [prompt]);
useEffect(() => {
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
}
return []; return [];
}); });
setOptimisticUserMessages([]);
setPrompt("");
promptRef.current = "";
setSendPhase("idle"); setSendPhase("idle");
setComposerCursor(0);
setComposerHighlightedItemId(null); setComposerHighlightedItemId(null);
dragDepthRef.current = 0; dragDepthRef.current = 0;
setIsDragOverComposer(false); setIsDragOverComposer(false);
setExpandedImage(null); setExpandedImage(null);
}, [activeThread?.id, revokePreviewUrls]); }, [threadId]);
useEffect(() => { 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 () => { return () => {
revokePreviewUrls(composerImagesRef.current); cancelled = true;
}; };
}, [revokePreviewUrls]); }, [
clearComposerDraftPersistedAttachments,
composerImages,
syncComposerDraftPersistedAttachments,
threadId,
]);
const closeExpandedImage = useCallback(() => { const closeExpandedImage = useCallback(() => {
setExpandedImage(null); setExpandedImage(null);
@@ -1161,8 +1388,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => { useEffect(() => {
if (!activeThread?.id) return; if (!activeThread?.id) return;
setEnvMode(activeWorktreePath ? "worktree" : "local"); if (activeWorktreePath) {
}, [activeThread?.id, activeWorktreePath]); setEnvMode("worktree");
return;
}
if (isLocalDraftThread) {
setEnvMode(draftThread?.envMode ?? "local");
return;
}
setEnvMode("local");
}, [activeThread?.id, activeWorktreePath, draftThread?.envMode, isLocalDraftThread]);
// Auto-resize textarea // Auto-resize textarea
useEffect(() => { useEffect(() => {
@@ -1298,19 +1533,32 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback( const setThreadError = useCallback(
(threadId: ThreadId | null, error: string | null) => { (threadId: ThreadId | null, error: string | null) => {
if (!threadId) return; if (!threadId) return;
dispatch({ if (state.threads.some((thread) => thread.id === threadId)) {
type: "SET_ERROR", dispatch({
threadId, type: "SET_ERROR",
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[]) => { const addComposerImages = (files: File[]) => {
if (!activeThreadId || files.length === 0) return; if (!activeThreadId || files.length === 0) return;
const nextImages = [...composerImagesRef.current]; const nextImages: ComposerImageAttachment[] = [];
let nextImageCount = composerImagesRef.current.length;
let error: string | null = null; let error: string | null = null;
for (const file of files) { for (const file of files) {
if (!file.type.startsWith("image/")) { 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.`; error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue; 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.`; error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break; break;
} }
@@ -1336,20 +1584,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
previewUrl, previewUrl,
file, file,
}); });
nextImageCount += 1;
} }
setComposerImages(nextImages); if (nextImages.length === 1 && nextImages[0]) {
addComposerImage(nextImages[0]);
} else if (nextImages.length > 1) {
addComposerImagesToDraft(nextImages);
}
setThreadError(activeThreadId, error); setThreadError(activeThreadId, error);
}; };
const removeComposerImage = (imageId: string) => { const removeComposerImage = (imageId: string) => {
setComposerImages((existing) => { removeComposerImageFromDraft(imageId);
const match = existing.find((image) => image.id === imageId);
if (match?.previewUrl) {
URL.revokeObjectURL(match.previewUrl);
}
return existing.filter((image) => image.id !== imageId);
});
}; };
const onComposerPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => { const onComposerPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
@@ -1460,7 +1707,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!trimmed && composerImages.length === 0) return; if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return; if (!activeProject) return;
const threadIdForSend = activeThread.id; const threadIdForSend = activeThread.id;
const isFirstMessage = activeThread.messages.length === 0; const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
const baseBranchForWorktree = const baseBranchForWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch ? activeThread.branch
@@ -1516,12 +1763,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
setThreadError(threadIdForSend, null); setThreadError(threadIdForSend, null);
promptRef.current = ""; promptRef.current = "";
setPrompt(""); clearComposerDraftContent(threadIdForSend);
setComposerImages([]);
setComposerCursor(0);
setComposerHighlightedItemId(null); setComposerHighlightedItemId(null);
let attemptedTurnStart = false; let createdServerThreadForLocalDraft = false;
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
try { try {
// On first message: lock in branch + create worktree if needed. // On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) { if (baseBranchForWorktree) {
@@ -1532,39 +1780,63 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: baseBranchForWorktree, branch: baseBranchForWorktree,
newBranch, newBranch,
}); });
await api.orchestration.dispatchCommand({ nextThreadBranch = result.worktree.branch;
type: "thread.meta.update", nextThreadWorktreePath = result.worktree.path;
commandId: newCommandId(), if (isServerThread) {
threadId: threadIdForSend, await api.orchestration.dispatchCommand({
branch: result.worktree.branch, type: "thread.meta.update",
worktreePath: result.worktree.path, commandId: newCommandId(),
}); threadId: threadIdForSend,
// Keep local thread state in sync immediately so terminal drawer opens branch: result.worktree.branch,
// with the worktree cwd/env instead of briefly using the project root. worktreePath: result.worktree.path,
dispatch({ });
type: "SET_THREAD_BRANCH", // Keep local thread state in sync immediately so terminal drawer opens
threadId: threadIdForSend, // with the worktree cwd/env instead of briefly using the project root.
branch: result.worktree.branch, dispatch({
worktreePath: result.worktree.path, type: "SET_THREAD_BRANCH",
}); threadId: threadIdForSend,
const setupScript = setupProjectScript(activeProject.scripts); branch: result.worktree.branch,
if (setupScript) {
await runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path, 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 // Auto-title from first message
if (isFirstMessage) { if (isFirstMessage && isServerThread) {
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
await api.orchestration.dispatchCommand({ await api.orchestration.dispatchCommand({
type: "thread.meta.update", type: "thread.meta.update",
commandId: newCommandId(), commandId: newCommandId(),
@@ -1575,7 +1847,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
setSendPhase("sending-turn"); setSendPhase("sending-turn");
const turnAttachments = await turnAttachmentsPromise; const turnAttachments = await turnAttachmentsPromise;
attemptedTurnStart = true;
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request"; const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
const sandboxMode = const sandboxMode =
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write"; state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
@@ -1596,18 +1867,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
sandboxMode, sandboxMode,
createdAt: messageCreatedAt, createdAt: messageCreatedAt,
}); });
turnStartSucceeded = true;
if (isFirstMessage) {
clearDraftThread(threadIdForSend);
}
} catch (err) { } catch (err) {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: threadIdForSend,
})
.catch(() => undefined);
}
if ( if (
!attemptedTurnStart && !turnStartSucceeded &&
promptRef.current.length === 0 && promptRef.current.length === 0 &&
composerImagesRef.current.length === 0 composerImagesRef.current.length === 0
) { ) {
setOptimisticUserMessages((existing) => setOptimisticUserMessages((existing) => {
existing.filter((message) => message.id !== messageIdForSend), 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; promptRef.current = trimmed;
setPrompt(trimmed); setPrompt(trimmed);
setComposerImages(composerImagesSnapshot); addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
setComposerCursor(trimmed.length); setComposerCursor(trimmed.length);
} }
setThreadError( setThreadError(
@@ -1663,33 +1952,45 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onModelSelect = useCallback( const onModelSelect = useCallback(
(model: string) => { (model: string) => {
const normalizedModel = normalizeModelSlug(model);
const resolvedModel = normalizedModel ?? baseThreadModel;
setComposerDraftModel(threadId, resolvedModel === baseThreadModel ? null : resolvedModel);
const api = readNativeApi(); const api = readNativeApi();
if (!activeThread) return; if (api && isServerThread && activeThread) {
if (api) {
void api.orchestration.dispatchCommand({ void api.orchestration.dispatchCommand({
type: "thread.meta.update", type: "thread.meta.update",
commandId: newCommandId(), commandId: newCommandId(),
threadId: activeThread.id, threadId: activeThread.id,
model: resolveModelSlug(model), model: resolvedModel,
}); });
} }
scheduleComposerFocus(); scheduleComposerFocus();
}, },
[activeThread, scheduleComposerFocus], [
activeThread,
baseThreadModel,
isServerThread,
scheduleComposerFocus,
setComposerDraftModel,
threadId,
],
); );
const onEffortSelect = useCallback( const onEffortSelect = useCallback(
(effort: ReasoningEffort) => { (effort: ReasoningEffort) => {
setSelectedEffort(effort); setComposerDraftEffort(threadId, effort);
scheduleComposerFocus(); scheduleComposerFocus();
}, },
[scheduleComposerFocus], [scheduleComposerFocus, setComposerDraftEffort, threadId],
); );
const onEnvModeChange = useCallback( const onEnvModeChange = useCallback(
(mode: "local" | "worktree") => { (mode: DraftThreadEnvMode) => {
setEnvMode(mode); setEnvMode(mode);
if (isLocalDraftThread) {
setDraftThreadContext(threadId, { envMode: mode });
}
scheduleComposerFocus(); scheduleComposerFocus();
}, },
[scheduleComposerFocus], [isLocalDraftThread, scheduleComposerFocus, setDraftThreadContext, threadId],
); );
const applyPromptReplacement = useCallback( const applyPromptReplacement = useCallback(
@@ -1705,7 +2006,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerCursor(next.cursor); setComposerCursor(next.cursor);
}); });
}, },
[], [setComposerCursor, setPrompt],
); );
const onSelectComposerItem = useCallback( const onSelectComposerItem = useCallback(
@@ -1748,7 +2049,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
promptRef.current = nextPrompt; promptRef.current = nextPrompt;
setPrompt(nextPrompt); setPrompt(nextPrompt);
setComposerCursor(nextCursor); setComposerCursor(nextCursor);
}, []); }, [setComposerCursor, setPrompt]);
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (composerMenuOpen && composerMenuItems.length > 0) { if (composerMenuOpen && composerMenuItems.length > 0) {
@@ -1960,6 +2261,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
{image.name} {image.name}
</div> </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 <Button
variant="ghost" variant="ghost"
size="icon-xs" size="icon-xs"
+104 -39
View File
@@ -20,6 +20,7 @@ import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery"; import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery"; import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi"; import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
import { toastManager } from "./ui/toast"; import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -228,6 +229,19 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
export default function Sidebar() { export default function Sidebar() {
const { state, dispatch } = useStore(); 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 navigate = useNavigate();
const { settings: appSettings } = useAppSettings(); const { settings: appSettings } = useAppSettings();
const routeThreadId = useParams({ const routeThreadId = useParams({
@@ -265,15 +279,14 @@ export default function Sidebar() {
[projectCwdById, state.threads], [projectCwdById, state.threads],
); );
const threadGitStatusCwds = useMemo( const threadGitStatusCwds = useMemo(
() => () => [
[ ...new Set(
...new Set( threadGitTargets
threadGitTargets .filter((target) => target.branch !== null)
.filter((target) => target.branch !== null) .map((target) => target.cwd)
.map((target) => target.cwd) .filter((cwd): cwd is string => cwd !== null),
.filter((cwd): cwd is string => cwd !== null), ),
), ],
],
[threadGitTargets], [threadGitTargets],
); );
const threadGitStatusQueries = useQueries({ const threadGitStatusQueries = useQueries({
@@ -332,42 +345,71 @@ export default function Sidebar() {
options?: { options?: {
branch?: string | null; branch?: string | null;
worktreePath?: string | null; worktreePath?: string | null;
envMode?: DraftThreadEnvMode;
}, },
): Promise<void> => { ): Promise<void> => {
const api = readNativeApi(); const hasBranchOption = options?.branch !== undefined;
if (!api) return Promise.resolve(); 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 threadId = newThreadId();
const createdAt = new Date().toISOString(); const createdAt = new Date().toISOString();
const model =
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
return (async () => { return (async () => {
await api.orchestration.dispatchCommand({ setProjectDraftThreadId(projectId, threadId, {
type: "thread.create", createdAt,
commandId: newCommandId(),
threadId,
projectId,
title: "New thread",
model,
branch: options?.branch ?? null, branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? 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({ await navigate({
to: "/$threadId", to: "/$threadId",
params: { threadId }, params: { threadId },
}); });
})(); })();
}, },
[dispatch, navigate, state.projects], [
clearProjectDraftThreadId,
getDraftThreadByProjectId,
navigate,
getDraftThread,
routeThreadId,
setDraftThreadContext,
setProjectDraftThreadId,
],
); );
const focusMostRecentThreadForProject = useCallback( const focusMostRecentThreadForProject = useCallback(
@@ -517,6 +559,8 @@ export default function Sidebar() {
commandId: newCommandId(), commandId: newCommandId(),
threadId, threadId,
}); });
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
if (shouldNavigateToFallback) { if (shouldNavigateToFallback) {
if (fallbackThreadId) { if (fallbackThreadId) {
void navigate({ void navigate({
@@ -556,6 +600,8 @@ export default function Sidebar() {
}, },
[ [
appSettings.confirmThreadDelete, appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
dispatch, dispatch,
navigate, navigate,
removeWorktreeMutation, removeWorktreeMutation,
@@ -591,6 +637,11 @@ export default function Sidebar() {
if (!confirmed) return; if (!confirmed) return;
try { try {
const projectDraftThread = getDraftThreadByProjectId(projectId);
if (projectDraftThread) {
clearComposerDraftForThread(projectDraftThread.threadId);
}
clearProjectDraftThreadId(projectId);
await api.orchestration.dispatchCommand({ await api.orchestration.dispatchCommand({
type: "project.delete", type: "project.delete",
commandId: newCommandId(), commandId: newCommandId(),
@@ -606,7 +657,13 @@ export default function Sidebar() {
}); });
} }
}, },
[state.projects, state.threads], [
clearComposerDraftForThread,
clearProjectDraftThreadId,
getDraftThreadByProjectId,
state.projects,
state.threads,
],
); );
useEffect(() => { useEffect(() => {
@@ -614,8 +671,10 @@ export default function Sidebar() {
const activeThread = routeThreadId const activeThread = routeThreadId
? state.threads.find((thread) => thread.id === routeThreadId) ? state.threads.find((thread) => thread.id === routeThreadId)
: undefined; : undefined;
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
if (isChatNewLocalShortcut(event, keybindings)) { 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; if (!projectId) return;
event.preventDefault(); event.preventDefault();
void handleNewThread(projectId); void handleNewThread(projectId);
@@ -623,12 +682,16 @@ export default function Sidebar() {
} }
if (!isChatNewShortcut(event, keybindings)) return; 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; if (!projectId) return;
event.preventDefault(); event.preventDefault();
void handleNewThread(projectId, { void handleNewThread(projectId, {
branch: activeThread?.branch ?? null, branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null, worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ??
(activeThread?.worktreePath ? "worktree" : "local"),
}); });
}; };
@@ -636,7 +699,7 @@ export default function Sidebar() {
return () => { return () => {
window.removeEventListener("keydown", onWindowKeyDown); window.removeEventListener("keydown", onWindowKeyDown);
}; };
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]); }, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
const onCreateThreadClick = () => { const onCreateThreadClick = () => {
if (state.projects.length === 0) { if (state.projects.length === 0) {
@@ -693,7 +756,7 @@ export default function Sidebar() {
<SidebarGroup className="px-2 py-2"> <SidebarGroup className="px-2 py-2">
<SidebarMenu> <SidebarMenu>
{state.projects.map((project) => { {state.projects.map((project) => {
const threads = state.threads const visibleThreads = state.threads
.filter((thread) => thread.projectId === project.id) .filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => { .toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(); 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"> <span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name} {project.name}
</span> </span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span> <span className="text-[10px] text-muted-foreground/60">
{visibleThreads.length}
</span>
</CollapsibleTrigger> </CollapsibleTrigger>
<CollapsibleContent> <CollapsibleContent>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0"> <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 isActive = routeThreadId === thread.id;
const threadStatus = threadStatusPill( const threadStatus = threadStatusPill(
thread, 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 { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
import ChatView from "../components/ChatView"; import ChatView from "../components/ChatView";
import { useComposerDraftStore } from "../composerDraftStore";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useMediaQuery } from "../hooks/useMediaQuery"; import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store"; import { useStore } from "../store";
@@ -139,6 +140,10 @@ function ChatThreadRouteView() {
}); });
const search = Route.useSearch(); const search = Route.useSearch();
const threadExists = state.threads.some((thread) => thread.id === threadId); 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 diffOpen = search.diff === "1";
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY); const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const closeDiff = useCallback(() => { const closeDiff = useCallback(() => {
@@ -166,13 +171,13 @@ function ChatThreadRouteView() {
return; return;
} }
if (!threadExists) { if (!routeThreadExists) {
void navigate({ to: "/", replace: true }); void navigate({ to: "/", replace: true });
return; return;
} }
}, [navigate, state.threadsHydrated, threadExists, threadId]); }, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
if (!state.threadsHydrated || !threadExists) { if (!state.threadsHydrated || !routeThreadExists) {
return null; return null;
} }
+3
View File
@@ -79,6 +79,7 @@
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0", "tailwind-merge": "^3.4.0",
"zustand": "^5.0.11",
}, },
"devDependencies": { "devDependencies": {
"@effect/language-service": "catalog:", "@effect/language-service": "catalog:",
@@ -1417,6 +1418,8 @@
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], "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=="], "zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], "@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],