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
This commit is contained in:
1 parent
10660f376c
commit
cadef14a84
7 files changed
+1084
-56
No files matched your search
@@ -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:",
|
||||
|
||||
@@ -53,7 +53,6 @@ import {
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type ChatImageAttachment,
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
@@ -111,6 +110,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 PersistedComposerImageAttachment,
|
||||
readPersistedComposerDraftAttachments,
|
||||
useComposerDraftStore,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import { clearProjectDraftThreadById } from "../projectDraftThreads";
|
||||
import { clamp } from "effect/Number";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
@@ -130,6 +137,8 @@ const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
const ENABLE_DRAFT_PERSIST_DEBUG_LOGS = import.meta.env.DEV;
|
||||
|
||||
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
|
||||
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
|
||||
@@ -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;
|
||||
@@ -239,6 +243,25 @@ function buildTemporaryWorktreeBranchName(): string {
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
function readComposerDraftStorageChars(): number | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = window.localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
return raw?.length ?? 0;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function debugDraftPersist(message: string, payload: Record<string, unknown>): void {
|
||||
if (!ENABLE_DRAFT_PERSIST_DEBUG_LOGS) {
|
||||
return;
|
||||
}
|
||||
console.debug(`[draft-persist] ${message}`, payload);
|
||||
}
|
||||
|
||||
const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
@@ -372,23 +395,38 @@ 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 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 [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 [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,6 +440,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const dragDepthRef = useRef(0);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
|
||||
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 activeThread = state.threads.find((t) => t.id === threadId);
|
||||
const diffSearch = useMemo(
|
||||
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
|
||||
@@ -435,8 +504,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
composerDraft.model ?? activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const selectedEffort = composerDraft.effort ?? DEFAULT_REASONING;
|
||||
const modelOptions = useMemo(
|
||||
() => getAppModelOptions(settings.customCodexModels, selectedModel),
|
||||
[selectedModel, settings.customCodexModels],
|
||||
@@ -645,6 +715,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 +767,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;
|
||||
@@ -1088,26 +1156,115 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}, [activeThread?.id, activeThread?.messages]);
|
||||
|
||||
useEffect(() => {
|
||||
setComposerImages((existing) => {
|
||||
revokePreviewUrls(existing);
|
||||
return [];
|
||||
});
|
||||
promptRef.current = prompt;
|
||||
}, [prompt]);
|
||||
|
||||
useEffect(() => {
|
||||
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>();
|
||||
const serializationFailedImageIds: string[] = [];
|
||||
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);
|
||||
} else {
|
||||
serializationFailedImageIds.push(image.id);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serialized = Array.from(stagedAttachmentById.values());
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
// Stage attachments in persisted draft state first so persist middleware can write them.
|
||||
const stagedAttachmentIds = serialized.map((attachment) => attachment.id);
|
||||
debugDraftPersist("stage", {
|
||||
threadId,
|
||||
attachmentCount: serialized.length,
|
||||
serializationFailedCount: serializationFailedImageIds.length,
|
||||
serializationFailedImageIds,
|
||||
attachmentMeta: serialized.map((attachment) => ({
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
dataUrlChars: attachment.dataUrl.length,
|
||||
})),
|
||||
storageCharsBefore: readComposerDraftStorageChars(),
|
||||
});
|
||||
syncComposerDraftPersistedAttachments(
|
||||
threadId,
|
||||
serialized,
|
||||
);
|
||||
debugDraftPersist("reconcile-request", {
|
||||
threadId,
|
||||
stagedCount: stagedAttachmentIds.length,
|
||||
serializationFailedCount: serializationFailedImageIds.length,
|
||||
storageCharsAfter: readComposerDraftStorageChars(),
|
||||
});
|
||||
} catch (error) {
|
||||
const currentImageIds = new Set(composerImages.map((image) => image.id));
|
||||
const fallbackPersistedAttachments = readPersistedComposerDraftAttachments(threadId);
|
||||
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),
|
||||
);
|
||||
debugDraftPersist("error", {
|
||||
threadId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
imageIds: composerImages.map((image) => image.id),
|
||||
fallbackPersistedCount: fallbackPersistedIds.length,
|
||||
storageChars: readComposerDraftStorageChars(),
|
||||
});
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
syncComposerDraftPersistedAttachments(threadId, fallbackAttachments);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
revokePreviewUrls(composerImagesRef.current);
|
||||
cancelled = true;
|
||||
};
|
||||
}, [revokePreviewUrls]);
|
||||
}, [
|
||||
clearComposerDraftPersistedAttachments,
|
||||
composerImages,
|
||||
syncComposerDraftPersistedAttachments,
|
||||
threadId,
|
||||
]);
|
||||
|
||||
const closeExpandedImage = useCallback(() => {
|
||||
setExpandedImage(null);
|
||||
@@ -1310,7 +1467,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
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 +1479,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 +1494,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>) => {
|
||||
@@ -1516,9 +1673,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
promptRef.current = "";
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
setComposerCursor(0);
|
||||
clearComposerDraftContent(threadIdForSend);
|
||||
setComposerHighlightedItemId(null);
|
||||
|
||||
let attemptedTurnStart = false;
|
||||
@@ -1596,6 +1751,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
sandboxMode,
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
if (isFirstMessage) {
|
||||
clearProjectDraftThreadById(activeProject.id, threadIdForSend);
|
||||
}
|
||||
} catch (err) {
|
||||
if (
|
||||
!attemptedTurnStart &&
|
||||
@@ -1607,7 +1765,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
promptRef.current = trimmed;
|
||||
setPrompt(trimmed);
|
||||
setComposerImages(composerImagesSnapshot);
|
||||
addComposerImagesToDraft(composerImagesSnapshot);
|
||||
setComposerCursor(trimmed.length);
|
||||
}
|
||||
setThreadError(
|
||||
@@ -1663,26 +1821,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const onModelSelect = useCallback(
|
||||
(model: string) => {
|
||||
const normalizedModel = resolveModelSlug(model);
|
||||
setComposerDraftModel(threadId, normalizedModel);
|
||||
const api = readNativeApi();
|
||||
if (!activeThread) return;
|
||||
if (api) {
|
||||
if (api && activeThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThread.id,
|
||||
model: resolveModelSlug(model),
|
||||
model: normalizedModel,
|
||||
});
|
||||
}
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[activeThread, scheduleComposerFocus],
|
||||
[activeThread, scheduleComposerFocus, setComposerDraftModel, threadId],
|
||||
);
|
||||
const onEffortSelect = useCallback(
|
||||
(effort: ReasoningEffort) => {
|
||||
setSelectedEffort(effort);
|
||||
setComposerDraftEffort(threadId, effort);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus],
|
||||
[scheduleComposerFocus, setComposerDraftEffort, threadId],
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: "local" | "worktree") => {
|
||||
@@ -1705,7 +1864,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerCursor(next.cursor);
|
||||
});
|
||||
},
|
||||
[],
|
||||
[setComposerCursor, setPrompt],
|
||||
);
|
||||
|
||||
const onSelectComposerItem = useCallback(
|
||||
@@ -1748,7 +1907,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 +2119,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"
|
||||
|
||||
@@ -20,6 +20,13 @@ import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
clearProjectDraftThreadById,
|
||||
clearProjectDraftThreadId,
|
||||
readProjectDraftThreadId,
|
||||
writeProjectDraftThreadId,
|
||||
} from "../projectDraftThreads";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -74,6 +81,10 @@ interface PrStatusIndicator {
|
||||
|
||||
type ThreadPr = GitStatusResult["pr"];
|
||||
|
||||
function shouldShowThreadInSidebar(thread: Thread): boolean {
|
||||
return thread.messages.some((message) => message.role === "user");
|
||||
}
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
@@ -228,6 +239,7 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
const navigate = useNavigate();
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const routeThreadId = useParams({
|
||||
@@ -336,6 +348,42 @@ export default function Sidebar() {
|
||||
): Promise<void> => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return Promise.resolve();
|
||||
const storedDraftThreadId = readProjectDraftThreadId(projectId);
|
||||
const storedDraftThread = storedDraftThreadId
|
||||
? state.threads.find((thread) => thread.id === storedDraftThreadId)
|
||||
: undefined;
|
||||
const reusableStoredDraftThreadId =
|
||||
storedDraftThread &&
|
||||
storedDraftThread.projectId === projectId &&
|
||||
!shouldShowThreadInSidebar(storedDraftThread)
|
||||
? storedDraftThread.id
|
||||
: null;
|
||||
if (reusableStoredDraftThreadId) {
|
||||
if (routeThreadId === reusableStoredDraftThreadId) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: reusableStoredDraftThreadId },
|
||||
});
|
||||
}
|
||||
if (storedDraftThreadId) {
|
||||
clearProjectDraftThreadId(projectId);
|
||||
}
|
||||
|
||||
const activeThread = routeThreadId
|
||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
const reusableDraftThreadId =
|
||||
activeThread &&
|
||||
activeThread.projectId === projectId &&
|
||||
!shouldShowThreadInSidebar(activeThread)
|
||||
? activeThread.id
|
||||
: null;
|
||||
if (reusableDraftThreadId) {
|
||||
writeProjectDraftThreadId(projectId, reusableDraftThreadId);
|
||||
return Promise.resolve();
|
||||
}
|
||||
const threadId = newThreadId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const model =
|
||||
@@ -352,6 +400,7 @@ export default function Sidebar() {
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
createdAt,
|
||||
});
|
||||
writeProjectDraftThreadId(projectId, threadId);
|
||||
|
||||
// Ensure route guards can see the new thread before navigating.
|
||||
try {
|
||||
@@ -367,7 +416,7 @@ export default function Sidebar() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[dispatch, navigate, state.projects],
|
||||
[dispatch, navigate, routeThreadId, state.projects, state.threads],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -517,6 +566,8 @@ export default function Sidebar() {
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
});
|
||||
clearComposerDraftForThread(threadId);
|
||||
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -556,6 +607,7 @@ export default function Sidebar() {
|
||||
},
|
||||
[
|
||||
appSettings.confirmThreadDelete,
|
||||
clearComposerDraftForThread,
|
||||
dispatch,
|
||||
navigate,
|
||||
removeWorktreeMutation,
|
||||
@@ -576,7 +628,9 @@ export default function Sidebar() {
|
||||
if (!project) return;
|
||||
|
||||
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
|
||||
if (projectThreads.length > 0) {
|
||||
const visibleThreads = projectThreads.filter(shouldShowThreadInSidebar);
|
||||
const draftThreads = projectThreads.filter((thread) => !shouldShowThreadInSidebar(thread));
|
||||
if (visibleThreads.length > 0) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Project is not empty",
|
||||
@@ -591,6 +645,15 @@ export default function Sidebar() {
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
for (const draftThread of draftThreads) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
threadId: draftThread.id,
|
||||
});
|
||||
clearComposerDraftForThread(draftThread.id);
|
||||
}
|
||||
clearProjectDraftThreadId(projectId);
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.delete",
|
||||
commandId: newCommandId(),
|
||||
@@ -606,7 +669,7 @@ export default function Sidebar() {
|
||||
});
|
||||
}
|
||||
},
|
||||
[state.projects, state.threads],
|
||||
[clearComposerDraftForThread, state.projects, state.threads],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -693,8 +756,9 @@ 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)
|
||||
.filter(shouldShowThreadInSidebar)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
if (byDate !== 0) return byDate;
|
||||
@@ -736,12 +800,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,
|
||||
|
||||
@@ -0,0 +1,687 @@
|
||||
import {
|
||||
DEFAULT_REASONING,
|
||||
REASONING_OPTIONS,
|
||||
ThreadId,
|
||||
normalizeModelSlug,
|
||||
type ReasoningEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ChatImageAttachment } from "./types";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
|
||||
|
||||
const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
|
||||
const SAFE_LOCAL_STORAGE: StateStorage = {
|
||||
getItem: (key) => {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return window.localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
setItem: (key, value) => {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
window.localStorage.setItem(key, value);
|
||||
} catch {
|
||||
// Swallow quota/storage errors so draft state stays usable in-memory.
|
||||
}
|
||||
},
|
||||
removeItem: (key) => {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export interface PersistedComposerImageAttachment {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
dataUrl: string;
|
||||
}
|
||||
|
||||
export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
|
||||
previewUrl: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
interface PersistedComposerThreadDraftState {
|
||||
prompt: string;
|
||||
cursor: number;
|
||||
attachments: PersistedComposerImageAttachment[];
|
||||
model?: string | null;
|
||||
effort?: ReasoningEffort | null;
|
||||
}
|
||||
|
||||
interface PersistedComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, PersistedComposerThreadDraftState>;
|
||||
}
|
||||
|
||||
export interface ComposerThreadDraftState {
|
||||
prompt: string;
|
||||
cursor: number;
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
model: string | null;
|
||||
effort: ReasoningEffort | null;
|
||||
}
|
||||
|
||||
interface ComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setCursor: (threadId: ThreadId, cursor: number) => void;
|
||||
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
|
||||
setEffort: (threadId: ThreadId, effort: ReasoningEffort | null | undefined) => void;
|
||||
addImage: (threadId: ThreadId, image: ComposerImageAttachment) => void;
|
||||
addImages: (threadId: ThreadId, images: ComposerImageAttachment[]) => void;
|
||||
removeImage: (threadId: ThreadId, imageId: string) => void;
|
||||
clearPersistedAttachments: (threadId: ThreadId) => void;
|
||||
syncPersistedAttachments: (threadId: ThreadId, attachments: PersistedComposerImageAttachment[]) => void;
|
||||
clearComposerContent: (threadId: ThreadId) => void;
|
||||
clearThreadDraft: (threadId: ThreadId) => void;
|
||||
}
|
||||
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
||||
const EMPTY_THREAD_DRAFT: ComposerThreadDraftState = {
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
model: null,
|
||||
effort: null,
|
||||
};
|
||||
|
||||
const REASONING_EFFORT_VALUES = new Set<ReasoningEffort>(REASONING_OPTIONS);
|
||||
|
||||
function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
return {
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
model: null,
|
||||
effort: null,
|
||||
};
|
||||
}
|
||||
|
||||
function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
return (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.model === null &&
|
||||
draft.effort === null
|
||||
);
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
if (typeof URL === "undefined") {
|
||||
return;
|
||||
}
|
||||
if (!previewUrl.startsWith("blob:")) {
|
||||
return;
|
||||
}
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
|
||||
function normalizePersistedAttachment(value: unknown): PersistedComposerImageAttachment | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const id = candidate.id;
|
||||
const name = candidate.name;
|
||||
const mimeType = candidate.mimeType;
|
||||
const sizeBytes = candidate.sizeBytes;
|
||||
const dataUrl = candidate.dataUrl;
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
typeof name !== "string" ||
|
||||
typeof mimeType !== "string" ||
|
||||
typeof sizeBytes !== "number" ||
|
||||
!Number.isFinite(sizeBytes) ||
|
||||
typeof dataUrl !== "string" ||
|
||||
id.length === 0 ||
|
||||
dataUrl.length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
dataUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePersistedComposerDraftState(value: unknown): PersistedComposerDraftStoreState {
|
||||
if (!value || typeof value !== "object") {
|
||||
return { draftsByThreadId: {} };
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const rawDraftMap = candidate.draftsByThreadId;
|
||||
if (!rawDraftMap || typeof rawDraftMap !== "object") {
|
||||
return { draftsByThreadId: {} };
|
||||
}
|
||||
const nextDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
|
||||
for (const [threadId, draftValue] of Object.entries(rawDraftMap as Record<string, unknown>)) {
|
||||
if (typeof threadId !== "string" || threadId.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (!draftValue || typeof draftValue !== "object") {
|
||||
continue;
|
||||
}
|
||||
const draftCandidate = draftValue as Record<string, unknown>;
|
||||
const prompt = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
||||
const cursor =
|
||||
typeof draftCandidate.cursor === "number" && Number.isFinite(draftCandidate.cursor)
|
||||
? Math.max(0, Math.floor(draftCandidate.cursor))
|
||||
: 0;
|
||||
const attachments = Array.isArray(draftCandidate.attachments)
|
||||
? draftCandidate.attachments.flatMap((entry) => {
|
||||
const normalized = normalizePersistedAttachment(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const model =
|
||||
typeof draftCandidate.model === "string" ? normalizeModelSlug(draftCandidate.model) : null;
|
||||
const effortCandidate =
|
||||
typeof draftCandidate.effort === "string" ? draftCandidate.effort : null;
|
||||
const effort =
|
||||
effortCandidate && REASONING_EFFORT_VALUES.has(effortCandidate as ReasoningEffort)
|
||||
? (effortCandidate as ReasoningEffort)
|
||||
: null;
|
||||
if (prompt.length === 0 && attachments.length === 0 && !model && !effort) {
|
||||
continue;
|
||||
}
|
||||
nextDraftsByThreadId[threadId as ThreadId] = {
|
||||
prompt,
|
||||
cursor,
|
||||
attachments,
|
||||
...(model ? { model } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
};
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
}
|
||||
|
||||
function fileFromDataUrl(dataUrl: string, name: string, mimeType: string): File | null {
|
||||
const [rawHeader, payload] = dataUrl.split(",", 2);
|
||||
const header = rawHeader ?? "";
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const isBase64 = header.includes(";base64");
|
||||
if (!isBase64) {
|
||||
const decodedText = decodeURIComponent(payload);
|
||||
const inferredMimeType =
|
||||
header.startsWith("data:") && header.includes(";")
|
||||
? header.slice("data:".length, header.indexOf(";"))
|
||||
: mimeType;
|
||||
return new File([decodedText], name, { type: inferredMimeType || mimeType });
|
||||
}
|
||||
const binary = atob(payload);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return new File([bytes], name, { type: mimeType });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function hydrateImagesFromPersisted(
|
||||
attachments: PersistedComposerImageAttachment[],
|
||||
): ComposerImageAttachment[] {
|
||||
return attachments.flatMap((attachment) => {
|
||||
const file = fileFromDataUrl(attachment.dataUrl, attachment.name, attachment.mimeType);
|
||||
if (!file) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: attachment.dataUrl,
|
||||
file,
|
||||
} satisfies ComposerImageAttachment,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function readPersistedDraftStateFromLocalStorage(): PersistedComposerDraftStoreState {
|
||||
if (typeof window === "undefined") {
|
||||
return { draftsByThreadId: {} };
|
||||
}
|
||||
try {
|
||||
const raw = window.localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return { draftsByThreadId: {} };
|
||||
}
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (parsed && typeof parsed === "object" && "state" in parsed) {
|
||||
return normalizePersistedComposerDraftState((parsed as { state?: unknown }).state);
|
||||
}
|
||||
return normalizePersistedComposerDraftState(parsed);
|
||||
} catch {
|
||||
return { draftsByThreadId: {} };
|
||||
}
|
||||
}
|
||||
|
||||
function toHydratedThreadDraft(
|
||||
persistedDraft: PersistedComposerThreadDraftState,
|
||||
): ComposerThreadDraftState {
|
||||
return {
|
||||
prompt: persistedDraft.prompt,
|
||||
cursor: persistedDraft.cursor,
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: persistedDraft.attachments,
|
||||
model: persistedDraft.model ?? null,
|
||||
effort: persistedDraft.effort ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
draftsByThreadId: {},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const cursor = Math.min(existing.cursor, prompt.length);
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt,
|
||||
cursor,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setCursor: (threadId, cursor) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const nextCursor = Number.isFinite(cursor) ? Math.max(0, Math.floor(cursor)) : 0;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && nextCursor === 0) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const boundedCursor = Math.min(nextCursor, base.prompt.length);
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
cursor: boundedCursor,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModel: (threadId, model) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedModel = normalizeModelSlug(model) ?? null;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedModel === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (base.model === normalizedModel) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
model: normalizedModel,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setEffort: (threadId, effort) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const nextEffort =
|
||||
effort &&
|
||||
REASONING_EFFORT_VALUES.has(effort) &&
|
||||
effort !== DEFAULT_REASONING
|
||||
? effort
|
||||
: null;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && nextEffort === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (base.effort === nextEffort) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
effort: nextEffort,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
addImage: (threadId, image) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
get().addImages(threadId, [image]);
|
||||
},
|
||||
addImages: (threadId, images) => {
|
||||
if (threadId.length === 0 || images.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const existingIds = new Set(existing.images.map((image) => image.id));
|
||||
const dedupedIncoming: ComposerImageAttachment[] = [];
|
||||
for (const image of images) {
|
||||
if (existingIds.has(image.id)) {
|
||||
revokeObjectPreviewUrl(image.previewUrl);
|
||||
continue;
|
||||
}
|
||||
dedupedIncoming.push(image);
|
||||
existingIds.add(image.id);
|
||||
}
|
||||
if (dedupedIncoming.length === 0) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
draftsByThreadId: {
|
||||
...state.draftsByThreadId,
|
||||
[threadId]: {
|
||||
...existing,
|
||||
images: [...existing.images, ...dedupedIncoming],
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
removeImage: (threadId, imageId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = get().draftsByThreadId[threadId];
|
||||
if (!existing) {
|
||||
return;
|
||||
}
|
||||
const removedImage = existing.images.find((image) => image.id === imageId);
|
||||
if (removedImage) {
|
||||
revokeObjectPreviewUrl(removedImage.previewUrl);
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
images: current.images.filter((image) => image.id !== imageId),
|
||||
nonPersistedImageIds: current.nonPersistedImageIds.filter((id) => id !== imageId),
|
||||
persistedAttachments: current.persistedAttachments.filter(
|
||||
(attachment) => attachment.id !== imageId,
|
||||
),
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearPersistedAttachments: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
persistedAttachments: [],
|
||||
nonPersistedImageIds: [],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
syncPersistedAttachments: (threadId, attachments) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const attachmentIdSet = new Set(attachments.map((attachment) => attachment.id));
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
// Stage attempted attachments so persist middleware can try writing them.
|
||||
persistedAttachments: attachments,
|
||||
nonPersistedImageIds: current.nonPersistedImageIds.filter((id) =>
|
||||
!attachmentIdSet.has(id),
|
||||
),
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
Promise.resolve().then(() => {
|
||||
const persistedIdSet = new Set(readPersistedComposerDraftAttachmentIds(threadId));
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const imageIdSet = new Set(current.images.map((image) => image.id));
|
||||
const persistedAttachments = attachments.filter(
|
||||
(attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
|
||||
);
|
||||
const nonPersistedImageIds = current.images
|
||||
.map((image) => image.id)
|
||||
.filter((imageId) => !persistedIdSet.has(imageId));
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
persistedAttachments,
|
||||
nonPersistedImageIds,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
});
|
||||
},
|
||||
clearComposerContent: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = get().draftsByThreadId[threadId];
|
||||
if (existing) {
|
||||
for (const image of existing.images) {
|
||||
revokeObjectPreviewUrl(image.previewUrl);
|
||||
}
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearThreadDraft: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = get().draftsByThreadId[threadId];
|
||||
if (existing) {
|
||||
for (const image of existing.images) {
|
||||
revokeObjectPreviewUrl(image.previewUrl);
|
||||
}
|
||||
}
|
||||
set((state) => {
|
||||
if (state.draftsByThreadId[threadId] === undefined) {
|
||||
return state;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = state.draftsByThreadId;
|
||||
return { draftsByThreadId: rest };
|
||||
});
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: COMPOSER_DRAFT_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => SAFE_LOCAL_STORAGE),
|
||||
partialize: (state) => {
|
||||
const persistedDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
|
||||
for (const [threadId, draft] of Object.entries(state.draftsByThreadId)) {
|
||||
if (typeof threadId !== "string" || threadId.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.model === null &&
|
||||
draft.effort === null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const persistedDraft: PersistedComposerThreadDraftState = {
|
||||
prompt: draft.prompt,
|
||||
cursor: Math.min(Math.max(0, draft.cursor), draft.prompt.length),
|
||||
attachments: draft.persistedAttachments,
|
||||
};
|
||||
if (draft.model) {
|
||||
persistedDraft.model = draft.model;
|
||||
}
|
||||
if (draft.effort) {
|
||||
persistedDraft.effort = draft.effort;
|
||||
}
|
||||
persistedDraftsByThreadId[threadId as ThreadId] = persistedDraft;
|
||||
}
|
||||
return {
|
||||
draftsByThreadId: persistedDraftsByThreadId,
|
||||
};
|
||||
},
|
||||
merge: (persistedState, currentState) => {
|
||||
const normalizedPersisted = normalizePersistedComposerDraftState(persistedState);
|
||||
const draftsByThreadId = Object.fromEntries(
|
||||
Object.entries(normalizedPersisted.draftsByThreadId).map(([threadId, draft]) => [
|
||||
threadId,
|
||||
toHydratedThreadDraft(draft),
|
||||
]),
|
||||
);
|
||||
return {
|
||||
...currentState,
|
||||
draftsByThreadId,
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export function useComposerThreadDraft(threadId: ThreadId): ComposerThreadDraftState {
|
||||
return useComposerDraftStore((state) => state.draftsByThreadId[threadId] ?? EMPTY_THREAD_DRAFT);
|
||||
}
|
||||
|
||||
export function readPersistedComposerDraftAttachmentIds(threadId: ThreadId): string[] {
|
||||
if (threadId.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return readPersistedComposerDraftAttachments(threadId).map((attachment) => attachment.id);
|
||||
}
|
||||
|
||||
export function readPersistedComposerDraftAttachments(
|
||||
threadId: ThreadId,
|
||||
): PersistedComposerImageAttachment[] {
|
||||
if (threadId.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const persisted = readPersistedDraftStateFromLocalStorage();
|
||||
return persisted.draftsByThreadId[threadId]?.attachments ?? [];
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
const PROJECT_DRAFT_THREADS_STORAGE_KEY = "t3code:project-draft-threads:v1";
|
||||
|
||||
type ProjectDraftThreadMap = Record<ProjectId, ThreadId>;
|
||||
|
||||
function readAllProjectDraftThreads(): ProjectDraftThreadMap {
|
||||
if (typeof window === "undefined") {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
const raw = window.localStorage.getItem(PROJECT_DRAFT_THREADS_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return {};
|
||||
}
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return {};
|
||||
}
|
||||
const next: ProjectDraftThreadMap = {};
|
||||
for (const [projectId, threadId] of Object.entries(parsed as Record<string, unknown>)) {
|
||||
if (typeof projectId !== "string" || typeof threadId !== "string") {
|
||||
continue;
|
||||
}
|
||||
if (projectId.length === 0 || threadId.length === 0) {
|
||||
continue;
|
||||
}
|
||||
next[projectId as ProjectId] = threadId as ThreadId;
|
||||
}
|
||||
return next;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function persistAllProjectDraftThreads(next: ProjectDraftThreadMap): void {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const entries = Object.entries(next);
|
||||
if (entries.length === 0) {
|
||||
window.localStorage.removeItem(PROJECT_DRAFT_THREADS_STORAGE_KEY);
|
||||
return;
|
||||
}
|
||||
window.localStorage.setItem(PROJECT_DRAFT_THREADS_STORAGE_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
// Best-effort persistence only.
|
||||
}
|
||||
}
|
||||
|
||||
export function readProjectDraftThreadId(projectId: ProjectId): ThreadId | null {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const all = readAllProjectDraftThreads();
|
||||
return all[projectId] ?? null;
|
||||
}
|
||||
|
||||
export function writeProjectDraftThreadId(projectId: ProjectId, threadId: ThreadId): void {
|
||||
if (projectId.length === 0 || threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const all = readAllProjectDraftThreads();
|
||||
all[projectId] = threadId;
|
||||
persistAllProjectDraftThreads(all);
|
||||
}
|
||||
|
||||
export function clearProjectDraftThreadId(projectId: ProjectId): void {
|
||||
if (projectId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const all = readAllProjectDraftThreads();
|
||||
if (all[projectId] === undefined) {
|
||||
return;
|
||||
}
|
||||
const { [projectId]: _removed, ...rest } = all;
|
||||
persistAllProjectDraftThreads(rest);
|
||||
}
|
||||
|
||||
export function clearProjectDraftThreadById(projectId: ProjectId, threadId: ThreadId): void {
|
||||
if (projectId.length === 0 || threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const all = readAllProjectDraftThreads();
|
||||
if (all[projectId] !== threadId) {
|
||||
return;
|
||||
}
|
||||
const { [projectId]: _removed, ...rest } = all;
|
||||
persistAllProjectDraftThreads(rest);
|
||||
}
|
||||
@@ -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=="],
|
||||
|
||||
@@ -11,8 +11,11 @@ export type ModelSlug = string;
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, BuiltInModelSlug> = {
|
||||
"gpt-5": "gpt-5.3-codex",
|
||||
"gpt-5-codex": "gpt-5.3-codex",
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"gpt-5-codex-spark": "gpt-5.3-codex-spark",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user