Refactor web store usage to granular selectors

- Replace broad `useStore` state reads with targeted selector/action hooks across chat, diff, sidebar, and routing views
- Remove dispatch-style calls in favor of direct store actions to reduce unnecessary rerenders
- Improve chat UI interactions (composer menu navigation, image preview buttons, modal click targets)
- Add local `react-doctor` agent skill docs under `apps/web/.agents/react-doctor`
This commit is contained in:
Julius Marminge committed 2026-03-02 10:20:53 -08:00
1 parent 5c09614319
commit 5679c5fbea
10 files changed
+472 -340

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# React Doctor
Run after making React changes to catch issues early. Use when reviewing code, finishing a feature, or fixing bugs in a React project.
Scans your React codebase for security, performance, correctness, and architecture issues. Outputs a 0-100 score with actionable diagnostics.
## Usage
```bash
npx -y react-doctor@latest . --verbose --diff
```
## Workflow
Run after making changes to catch issues early. Fix errors first, then re-run to verify the score improved.
+19
View File
@@ -0,0 +1,19 @@
---
name: react-doctor
description: Run after making React changes to catch issues early. Use when reviewing code, finishing a feature, or fixing bugs in a React project.
version: 1.0.0
---
# React Doctor
Scans your React codebase for security, performance, correctness, and architecture issues. Outputs a 0-100 score with actionable diagnostics.
## Usage
```bash
npx -y react-doctor@latest . --verbose --diff
```
## Workflow
Run after making changes to catch issues early. Fix errors first, then re-run to verify the score improved.
+24 -20
View File
@@ -1,6 +1,6 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { newCommandId } from "../lib/utils";
import {
@@ -43,17 +43,26 @@ export default function BranchToolbar({
envLocked,
onComposerFocusRequest,
}: BranchToolbarProps) {
const { state, dispatch } = useStore();
const setThreadBranchAction = useStore((state) => state.setThreadBranch);
const setThreadErrorAction = useStore((state) => state.setThreadError);
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const serverThread = useStore(
useCallback((state) => state.threads.find((thread) => thread.id === threadId), [threadId]),
);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = useStore(
useCallback(
(state) =>
activeProjectId ? state.projects.find((project) => project.id === activeProjectId) : undefined,
[activeProjectId],
),
);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const serverThread = state.threads.find((thread) => thread.id === threadId);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = state.projects.find((project) => project.id === activeProjectId);
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
@@ -114,12 +123,7 @@ export default function BranchToolbar({
});
}
if (hasServerThread) {
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
setThreadBranchAction(activeThreadId, syncedBranch, null);
return;
}
setDraftThreadContext(threadId, {
@@ -132,22 +136,17 @@ export default function BranchToolbar({
activeThreadBranch,
queryBranches,
effectiveEnvMode,
dispatch,
setThreadBranchAction,
hasServerThread,
setDraftThreadContext,
threadId,
]);
useEffect(() => {
if (isBranchMenuOpen) return;
setBranchQuery("");
}, [isBranchMenuOpen]);
// ── Helpers ───────────────────────────────────────────────────────────
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
setThreadErrorAction(activeThreadId, error);
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
@@ -176,7 +175,7 @@ export default function BranchToolbar({
});
}
if (hasServerThread) {
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
setThreadBranchAction(activeThreadId, branch, worktreePath);
return;
}
setDraftThreadContext(threadId, {
@@ -282,7 +281,12 @@ export default function BranchToolbar({
<Combobox
items={branchPickerItems}
autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)}
onOpenChange={(open) => {
setIsBranchMenuOpen(open);
if (!open) {
setBranchQuery("");
}
}}
open={isBranchMenuOpen}
value={activeThreadBranch}
>
+193 -185
View File
@@ -101,7 +101,7 @@ import { CursorIcon, Icon } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
import { Command, CommandItem, CommandList } from "./ui/command";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
@@ -337,15 +337,12 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
kind: "file" | "directory";
theme: "light" | "dark";
}) {
const [failed, setFailed] = useState(false);
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
const iconUrl = useMemo(
() => getVscodeIconUrlForEntry(props.pathValue, props.kind, props.theme),
[props.kind, props.pathValue, props.theme],
);
useEffect(() => {
setFailed(false);
}, [iconUrl]);
const failed = failedIconUrl === iconUrl;
if (failed) {
return props.kind === "directory" ? (
@@ -362,7 +359,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
aria-hidden="true"
className="size-4 shrink-0"
loading="lazy"
onError={() => setFailed(true)}
onError={() => setFailedIconUrl(iconUrl)}
/>
);
});
@@ -411,7 +408,6 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
triggerKind: ComposerTriggerKind | null;
onHighlightedItemChange: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
commandInputRef: React.RefObject<HTMLInputElement | null>;
}) {
return (
<Command
@@ -423,9 +419,6 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
}}
>
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
<div className="pointer-events-none absolute h-0 w-0 overflow-hidden opacity-0">
<CommandInput autoFocus={false} ref={props.commandInputRef} />
</div>
<CommandList className="max-h-64">
{props.items.map((item) => (
<ComposerCommandMenuItem
@@ -455,7 +448,17 @@ interface ChatViewProps {
}
export default function ChatView({ threadId }: ChatViewProps) {
const { state, dispatch } = useStore();
const markThreadVisited = useStore((state) => state.markThreadVisited);
const setThreadTerminalOpen = useStore((state) => state.setThreadTerminalOpen);
const splitThreadTerminalAction = useStore((state) => state.splitThreadTerminal);
const newThreadTerminalAction = useStore((state) => state.newThreadTerminal);
const setThreadActiveTerminal = useStore((state) => state.setThreadActiveTerminal);
const closeThreadTerminalAction = useStore((state) => state.closeThreadTerminal);
const setThreadErrorAction = useStore((state) => state.setThreadError);
const setThreadBranchAction = useStore((state) => state.setThreadBranch);
const setRuntimeMode = useStore((state) => state.setRuntimeMode);
const setThreadTerminalHeight = useStore((state) => state.setThreadTerminalHeight);
const runtimeMode = useStore((state) => state.runtimeMode);
const { settings } = useAppSettings();
const navigate = useNavigate();
const rawSearch = useSearch({
@@ -487,6 +490,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const draftThread = useComposerDraftStore((store) => store.draftThreadsByThreadId[threadId] ?? null);
const serverThread = useStore(
useCallback((state) => state.threads.find((thread) => thread.id === threadId), [threadId]),
);
const fallbackDraftProjectId = draftThread?.projectId ?? null;
const fallbackDraftProject = useStore(
useCallback(
(state) =>
fallbackDraftProjectId
? state.projects.find((project) => project.id === fallbackDraftProjectId)
: undefined,
[fallbackDraftProjectId],
),
);
const promptRef = useRef(prompt);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
@@ -511,6 +527,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
Record<string, string>
>(() => readLastInvokedScriptByProjectFromStorage());
const messagesScrollRef = useRef<HTMLDivElement>(null);
const [messagesScrollElement, setMessagesScrollElement] = useState<HTMLDivElement | null>(null);
const shouldAutoScrollRef = useRef(true);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -523,6 +540,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const setMessagesScrollContainerRef = useCallback((element: HTMLDivElement | null) => {
messagesScrollRef.current = element;
setMessagesScrollElement(element);
}, []);
const setPrompt = useCallback(
(nextPrompt: string) => {
@@ -555,8 +576,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
[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(
() =>
@@ -581,7 +600,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore(
useCallback(
(state) =>
activeProjectId ? state.projects.find((project) => project.id === activeProjectId) : undefined,
[activeProjectId],
),
);
useEffect(() => {
if (!serverThread) {
@@ -605,16 +631,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
dispatch({
type: "MARK_THREAD_VISITED",
threadId: activeThread.id,
});
markThreadVisited(activeThread.id);
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
activeLatestTurn?.completedAt,
latestTurnSettled,
dispatch,
markThreadVisited,
]);
const baseThreadModel = resolveModelSlug(activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL);
@@ -981,41 +1004,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [focusComposer]);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: !activeThread?.terminalOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
setThreadTerminalOpen(activeThreadId, !activeThread?.terminalOpen);
}, [activeThread?.terminalOpen, activeThreadId, setThreadTerminalOpen]);
const splitTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
splitThreadTerminalAction(activeThreadId, `terminal-${crypto.randomUUID()}`);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
}, [activeThreadId, hasReachedTerminalLimit, splitThreadTerminalAction]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
newThreadTerminalAction(activeThreadId, `terminal-${crypto.randomUUID()}`);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
}, [activeThreadId, hasReachedTerminalLimit, newThreadTerminalAction]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setThreadActiveTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, dispatch],
[activeThreadId, setThreadActiveTerminal],
);
const closeTerminal = useCallback(
(terminalId: string) => {
@@ -1038,14 +1045,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
} else {
void fallbackExitWrite();
}
dispatch({
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
closeThreadTerminalAction(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThread?.terminalIds.length, activeThreadId, dispatch],
[activeThread?.terminalIds.length, activeThreadId, closeThreadTerminalAction],
);
const runProjectScript = useCallback(
async (
@@ -1079,23 +1082,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
? `terminal-${crypto.randomUUID()}`
: baseTerminalId;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
setThreadTerminalOpen(activeThreadId, true);
if (shouldCreateNewTerminal) {
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
newThreadTerminalAction(activeThreadId, targetTerminalId);
} else {
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
setThreadActiveTerminal(activeThreadId, targetTerminalId);
}
setTerminalFocusRequestId((value) => value + 1);
@@ -1126,14 +1117,23 @@ export default function ChatView({ threadId }: ChatViewProps) {
data: `${script.command}\r`,
});
} catch (error) {
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
});
setThreadErrorAction(
activeThreadId,
error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
);
}
},
[activeProject, activeThread, activeThreadId, dispatch, gitCwd, isServerThread],
[
activeProject,
activeThread,
activeThreadId,
gitCwd,
isServerThread,
newThreadTerminalAction,
setThreadActiveTerminal,
setThreadErrorAction,
setThreadTerminalOpen,
],
);
const persistProjectScripts = useCallback(
async (input: {
@@ -1236,35 +1236,34 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
if (mode === runtimeMode) return;
setRuntimeMode(mode);
scheduleComposerFocus();
const api = readNativeApi();
if (!api) return;
const runningThreadIds = state.threads
const runningThreadIds = useStore
.getState()
.threads
.filter((thread) => thread.session !== null && thread.session.status !== "closed")
.map((thread) => thread.id);
if (runningThreadIds.length === 0) return;
setIsSwitchingRuntimeMode(true);
try {
await Promise.all(
runningThreadIds.map((threadId) =>
api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined),
),
);
} finally {
setIsSwitchingRuntimeMode(false);
}
await Promise.all(
runningThreadIds.map((threadId) =>
api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined),
),
);
setIsSwitchingRuntimeMode(false);
};
useEffect(() => {
@@ -1642,11 +1641,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
setThreadTerminalOpen(activeThreadId, true);
}
splitTerminal();
return;
@@ -1664,11 +1659,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
setThreadTerminalOpen(activeThreadId, true);
}
createNewTerminal();
return;
@@ -1698,23 +1689,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThreadId,
closeTerminal,
createNewTerminal,
dispatch,
runProjectScript,
splitTerminal,
keybindings,
onToggleDiff,
setThreadTerminalOpen,
toggleTerminalVisibility,
]);
const setThreadError = useCallback(
(threadId: ThreadId | null, error: string | null) => {
if (!threadId) return;
if (state.threads.some((thread) => thread.id === threadId)) {
dispatch({
type: "SET_ERROR",
threadId,
error,
});
if (useStore.getState().threads.some((thread) => thread.id === threadId)) {
setThreadErrorAction(threadId, error);
return;
}
setLocalDraftErrorsByThreadId((existing) => {
@@ -1727,7 +1714,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
});
},
[dispatch, state.threads],
[setThreadErrorAction],
);
const addComposerImages = (files: File[]) => {
@@ -1868,9 +1855,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThread.id,
err instanceof Error ? err.message : "Failed to revert thread state.",
);
} finally {
setIsRevertingCheckpoint(false);
}
setIsRevertingCheckpoint(false);
},
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
);
@@ -1894,11 +1880,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) {
dispatch({
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
setThreadErrorAction(
threadIdForSend,
"Select a base branch before sending in New worktree mode.",
);
return;
}
@@ -1971,12 +1956,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
setThreadBranchAction(
threadIdForSend,
result.worktree.branch,
result.worktree.path,
);
}
}
@@ -2026,9 +2010,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
setSendPhase("sending-turn");
const turnAttachments = await turnAttachmentsPromise;
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
const sandboxMode =
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
const approvalPolicy = runtimeMode === "full-access" ? "never" : "on-request";
const sandboxMode = runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
@@ -2082,10 +2065,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadIdForSend,
err instanceof Error ? err.message : "Failed to send message.",
);
} finally {
sendInFlightRef.current = false;
setSendPhase("idle");
}
sendInFlightRef.current = false;
setSendPhase("idle");
};
const onInterrupt = async () => {
@@ -2117,16 +2099,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
setThreadErrorAction(
activeThreadId,
err instanceof Error ? err.message : "Failed to submit approval decision.",
);
}
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
},
[activeThreadId, dispatch],
[activeThreadId, setThreadErrorAction],
);
const onModelSelect = useCallback(
@@ -2211,13 +2191,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onComposerMenuItemHighlighted = useCallback((itemId: string | null) => {
setComposerHighlightedItemId(itemId);
}, []);
const nudgeComposerMenuHighlight = useCallback((key: "ArrowDown" | "ArrowUp") => {
const commandInput = composerCommandInputRef.current;
if (!commandInput) return;
commandInput.dispatchEvent(
new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }),
);
}, []);
const nudgeComposerMenuHighlight = useCallback(
(key: "ArrowDown" | "ArrowUp") => {
if (composerMenuItems.length === 0) {
return;
}
const highlightedIndex = composerMenuItems.findIndex(
(item) => item.id === composerHighlightedItemId,
);
const normalizedIndex =
highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0;
const offset = key === "ArrowDown" ? 1 : -1;
const nextIndex =
(normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length;
const nextItem = composerMenuItems[nextIndex];
setComposerHighlightedItemId(nextItem?.id ?? null);
},
[composerHighlightedItemId, composerMenuItems],
);
const isComposerMenuLoading =
composerTriggerKind === "path" &&
((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) ||
@@ -2359,7 +2350,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Messages */}
<div
ref={messagesScrollRef}
ref={setMessagesScrollContainerRef}
className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain px-3 py-3 sm:px-5 sm:py-4"
onScroll={onMessagesScroll}
>
@@ -2369,7 +2360,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
isWorking={isWorking}
activeTurnInProgress={!latestTurnSettled}
activeTurnStartedAt={activeLatestTurn?.startedAt ?? null}
scrollContainerRef={messagesScrollRef}
scrollContainer={messagesScrollElement}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
@@ -2414,7 +2405,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
triggerKind={composerTriggerKind}
onHighlightedItemChange={onComposerMenuItemHighlighted}
onSelect={onSelectComposerItem}
commandInputRef={composerCommandInputRef}
/>
</div>
)}
@@ -2427,16 +2417,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full w-full cursor-zoom-in object-cover"
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(composerImages, image.id);
if (!preview) return;
setExpandedImage(preview);
}}
/>
>
<img
src={image.previewUrl}
alt={image.name}
className="h-full w-full object-cover"
/>
</button>
) : (
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
{image.name}
@@ -2538,18 +2534,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
disabled={isSwitchingRuntimeMode}
onClick={() =>
void handleRuntimeModeChange(
state.runtimeMode === "full-access" ? "approval-required" : "full-access",
runtimeMode === "full-access" ? "approval-required" : "full-access",
)
}
title={
state.runtimeMode === "full-access"
runtimeMode === "full-access"
? "Full access — click to require approvals"
: "Approval required — click for full access"
}
>
{state.runtimeMode === "full-access" ? <LockOpenIcon /> : <LockIcon />}
{runtimeMode === "full-access" ? <LockOpenIcon /> : <LockIcon />}
<span className="sr-only sm:not-sr-only">
{state.runtimeMode === "full-access" ? "Full access" : "Supervised"}
{runtimeMode === "full-access" ? "Full access" : "Supervised"}
</span>
</Button>
</div>
@@ -2670,13 +2666,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
onHeightChange={(height) => setThreadTerminalHeight(activeThread.id, height)}
/>
);
})()}
@@ -2687,27 +2677,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
role="dialog"
aria-modal="true"
aria-label="Expanded image preview"
onClick={closeExpandedImage}
>
<button
type="button"
className="absolute inset-0 z-0 cursor-zoom-out"
aria-label="Close image preview"
onClick={closeExpandedImage}
/>
{expandedImage.images.length > 1 && (
<Button
type="button"
size="icon"
variant="ghost"
className="absolute left-2 top-1/2 z-10 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:left-6"
className="absolute left-2 top-1/2 z-20 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:left-6"
aria-label="Previous image"
onClick={(event) => {
event.stopPropagation();
onClick={() => {
navigateExpandedImage(-1);
}}
>
<ChevronLeftIcon className="size-5" />
</Button>
)}
<div
className="relative isolate max-h-[92vh] max-w-[92vw]"
onClick={(event) => event.stopPropagation()}
>
<div className="relative isolate z-10 max-h-[92vh] max-w-[92vw]">
<Button
type="button"
size="icon-xs"
@@ -2736,10 +2727,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="button"
size="icon"
variant="ghost"
className="absolute right-2 top-1/2 z-10 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:right-6"
className="absolute right-2 top-1/2 z-20 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:right-6"
aria-label="Next image"
onClick={(event) => {
event.stopPropagation();
onClick={() => {
navigateExpandedImage(1);
}}
>
@@ -2950,7 +2940,7 @@ interface MessagesTimelineProps {
isWorking: boolean;
activeTurnInProgress: boolean;
activeTurnStartedAt: string | null;
scrollContainerRef: React.RefObject<HTMLDivElement | null>;
scrollContainer: HTMLDivElement | null;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
@@ -3004,7 +2994,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
activeTurnInProgress,
activeTurnStartedAt,
scrollContainerRef,
scrollContainer,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
@@ -3114,7 +3104,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainerRef.current,
getScrollElement: () => scrollContainer,
// Use stable row ids so virtual measurements do not leak across thread switches.
getItemKey: (index: number) => rows[index]?.id ?? index,
estimateSize: (index: number) => {
@@ -3242,18 +3232,24 @@ const MessagesTimeline = memo(function MessagesTimeline({
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(userImages, image.id);
if (!preview) return;
onImageExpand(preview);
}}
/>
>
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
/>
</button>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
@@ -3545,9 +3541,21 @@ const OpenInPicker = memo(function OpenInPicker({
] satisfies { label: string; Icon: Icon; value: EditorId }[];
const primaryOption = options.find(({ value }) => value === lastEditor);
const { state } = useStore();
const activeThread = state.threads.find((t) => t.id === activeThreadId);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const activeThread = useStore(
useCallback(
(state) =>
activeThreadId ? state.threads.find((thread) => thread.id === activeThreadId) : undefined,
[activeThreadId],
),
);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore(
useCallback(
(state) =>
activeProjectId ? state.projects.find((project) => project.id === activeProjectId) : undefined,
[activeProjectId],
),
);
const openInEditor = useCallback(
(editorId: EditorId | null) => {
+29 -11
View File
@@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
@@ -156,7 +156,6 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { state } = useStore();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
@@ -168,8 +167,21 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const activeThreadId = routeThreadId;
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThread = useStore(
useCallback(
(state) =>
activeThreadId ? state.threads.find((thread) => thread.id === activeThreadId) : undefined,
[activeThreadId],
),
);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore(
useCallback(
(state) =>
activeProjectId ? state.projects.find((project) => project.id === activeProjectId) : undefined,
[activeProjectId],
),
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -342,7 +354,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
if (!element) return;
element.scrollBy({ left: offset, behavior: "smooth" });
}, []);
const onTurnStripWheel = useCallback((event: WheelEvent) => {
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
const element = turnStripRef.current;
if (!element) return;
if (element.scrollWidth <= element.clientWidth + 1) return;
@@ -356,24 +368,26 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const element = turnStripRef.current;
if (!element) return;
updateTurnStripScrollState();
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
const onScroll = () => updateTurnStripScrollState();
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
resizeObserver.observe(element);
return () => {
window.cancelAnimationFrame(frameId);
element.removeEventListener("scroll", onScroll);
element.removeEventListener("wheel", onTurnStripWheel);
resizeObserver.disconnect();
};
}, [updateTurnStripScrollState, onTurnStripWheel]);
}, [updateTurnStripScrollState]);
useEffect(() => {
updateTurnStripScrollState();
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
return () => {
window.cancelAnimationFrame(frameId);
};
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
useEffect(() => {
@@ -422,7 +436,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
>
<ChevronRightIcon className="size-3.5" />
</button>
<div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
onWheel={onTurnStripWheel}
>
<button
type="button"
className="shrink-0 rounded-md"
+67 -59
View File
@@ -228,7 +228,10 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
}
export default function Sidebar() {
const { state, dispatch } = useStore();
const projects = useStore((state) => state.projects);
const threads = useStore((state) => state.threads);
const markThreadUnread = useStore((state) => state.markThreadUnread);
const toggleProject = useStore((state) => state.toggleProject);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
@@ -260,23 +263,23 @@ export default function Sidebar() {
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of state.threads) {
for (const thread of threads) {
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
}
return map;
}, [state.threads]);
}, [threads]);
const projectCwdById = useMemo(
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
[state.projects],
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
[projects],
);
const threadGitTargets = useMemo(
() =>
state.threads.map((thread) => ({
threads.map((thread) => ({
threadId: thread.id,
branch: thread.branch,
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
})),
[projectCwdById, state.threads],
[projectCwdById, threads],
);
const threadGitStatusCwds = useMemo(
() => [
@@ -414,7 +417,7 @@ export default function Sidebar() {
const focusMostRecentThreadForProject = useCallback(
(projectId: ProjectId) => {
const latestThread = state.threads
const latestThread = threads
.filter((thread) => thread.projectId === projectId)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
@@ -428,7 +431,7 @@ export default function Sidebar() {
params: { threadId: latestThread.id },
});
},
[navigate, state.threads],
[navigate, threads],
);
const addProjectFromPath = useCallback(
@@ -438,34 +441,36 @@ export default function Sidebar() {
const api = readNativeApi();
setIsAddingProject(true);
try {
if (!api) return;
const existing = state.projects.find((project) => project.cwd === cwd);
if (api) {
const existing = projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
} else {
const projectId = newProjectId();
const createdAt = new Date().toISOString();
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
const projectCreated = await api.orchestration
.dispatchCommand({
type: "project.create",
commandId: newCommandId(),
projectId,
title,
workspaceRoot: cwd,
defaultModel: DEFAULT_MODEL,
createdAt,
})
.then(() => true)
.catch(() => false);
if (projectCreated) {
await handleNewThread(projectId).catch(() => undefined);
}
}
const projectId = newProjectId();
const createdAt = new Date().toISOString();
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: newCommandId(),
projectId,
title,
workspaceRoot: cwd,
defaultModel: DEFAULT_MODEL,
createdAt,
});
await handleNewThread(projectId);
} finally {
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
}
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
},
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
);
const handleAddProject = () => {
@@ -476,13 +481,16 @@ export default function Sidebar() {
const api = readNativeApi();
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
let pickedPath: string | null = null;
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
await addProjectFromPath(pickedPath);
} finally {
setIsPickingFolder(false);
pickedPath = await api.dialogs.pickFolder();
} catch {
// Ignore picker failures and leave the current thread selection unchanged.
}
if (pickedPath) {
await addProjectFromPath(pickedPath);
}
setIsPickingFolder(false);
};
const handleThreadContextMenu = useCallback(
@@ -497,12 +505,12 @@ export default function Sidebar() {
position,
);
if (clicked === "mark-unread") {
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
markThreadUnread(threadId);
return;
}
if (clicked !== "delete") return;
const thread = state.threads.find((t) => t.id === threadId);
const thread = threads.find((t) => t.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
@@ -515,8 +523,8 @@ export default function Sidebar() {
return;
}
}
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const threadProject = projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
@@ -553,7 +561,7 @@ export default function Sidebar() {
}
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
@@ -602,12 +610,12 @@ export default function Sidebar() {
appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
dispatch,
markThreadUnread,
navigate,
removeWorktreeMutation,
routeThreadId,
state.projects,
state.threads,
projects,
threads,
],
);
@@ -618,10 +626,10 @@ export default function Sidebar() {
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
const project = state.projects.find((entry) => entry.id === projectId);
const project = projects.find((entry) => entry.id === projectId);
if (!project) return;
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
const projectThreads = threads.filter((thread) => thread.projectId === projectId);
if (projectThreads.length > 0) {
toastManager.add({
type: "warning",
@@ -661,20 +669,20 @@ export default function Sidebar() {
clearComposerDraftForThread,
clearProjectDraftThreadId,
getDraftThreadByProjectId,
state.projects,
state.threads,
projects,
threads,
],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const activeThread = routeThreadId
? state.threads.find((thread) => thread.id === routeThreadId)
? threads.find((thread) => thread.id === routeThreadId)
: undefined;
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId);
@@ -683,7 +691,7 @@ export default function Sidebar() {
if (!isChatNewShortcut(event, keybindings)) return;
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId, {
@@ -697,14 +705,14 @@ export default function Sidebar() {
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, projects, threads]);
const onCreateThreadClick = () => {
if (state.projects.length === 0) {
if (projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = state.projects[0];
const firstProject = projects[0];
if (firstProject) void handleNewThread(firstProject.id);
};
@@ -753,8 +761,8 @@ export default function Sidebar() {
<SidebarContent className="gap-0">
<SidebarGroup className="px-2 py-2">
<SidebarMenu>
{state.projects.map((project) => {
const visibleThreads = state.threads
{projects.map((project) => {
const visibleThreads = threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
@@ -769,7 +777,7 @@ export default function Sidebar() {
open={project.expanded}
onOpenChange={(open) => {
if (open === project.expanded) return;
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
toggleProject(project.id);
}}
>
<SidebarMenuItem>
@@ -929,7 +937,7 @@ export default function Sidebar() {
})}
</SidebarMenu>
{state.projects.length === 0 && !addingProject && (
{projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
+16 -17
View File
@@ -123,14 +123,19 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const { dispatch } = useStore();
const syncServerReadModel = useStore((state) => state.syncServerReadModel);
const setThreadTerminalActivity = useStore((state) => state.setThreadTerminalActivity);
const setProjectExpanded = useStore((state) => state.setProjectExpanded);
const queryClient = useQueryClient();
const navigate = useNavigate();
const pathname = useRouterState({ select: (state) => state.location.pathname });
const pathnameRef = useRef(pathname);
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
pathnameRef.current = pathname;
useEffect(() => {
pathnameRef.current = pathname;
}, [pathname]);
useEffect(() => {
const api = readNativeApi();
@@ -144,7 +149,7 @@ function EventRouter() {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
syncServerReadModel(snapshot);
if (pending) {
pending = false;
await flushSnapshotSync();
@@ -157,14 +162,13 @@ function EventRouter() {
return;
}
syncing = true;
pending = false;
try {
pending = false;
await flushSnapshotSync();
} catch {
// Keep prior state and wait for next domain event to trigger a resync.
} finally {
syncing = false;
}
syncing = false;
};
void syncSnapshot().catch(() => undefined);
@@ -184,12 +188,11 @@ function EventRouter() {
if (hasRunningSubprocess === null) {
return;
}
dispatch({
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe(event.threadId),
terminalId: event.terminalId,
setThreadTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
hasRunningSubprocess,
});
);
});
const unsubWelcome = onServerWelcome((payload) => {
void (async () => {
@@ -201,11 +204,7 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
dispatch({
type: "SET_PROJECT_EXPANDED",
projectId: payload.bootstrapProjectId,
expanded: true,
});
setProjectExpanded(payload.bootstrapProjectId, true);
if (pathnameRef.current !== "/") {
return;
@@ -270,7 +269,7 @@ function EventRouter() {
unsubWelcome();
unsubServerConfigUpdated();
};
}, [dispatch, navigate, queryClient]);
}, [navigate, queryClient, setProjectExpanded, setThreadTerminalActivity, syncServerReadModel]);
return null;
}
+7 -5
View File
@@ -133,13 +133,15 @@ const DiffPanelInlineSidebar = (props: {
};
function ChatThreadRouteView() {
const { state } = useStore();
const threadsHydrated = useStore((state) => state.threadsHydrated);
const navigate = useNavigate();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
});
const search = Route.useSearch();
const threadExists = state.threads.some((thread) => thread.id === threadId);
const threadExists = useStore(
useCallback((state) => state.threads.some((thread) => thread.id === threadId), [threadId]),
);
const draftThreadExists = useComposerDraftStore(
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
);
@@ -167,7 +169,7 @@ function ChatThreadRouteView() {
}, [navigate, threadId]);
useEffect(() => {
if (!state.threadsHydrated) {
if (!threadsHydrated) {
return;
}
@@ -175,9 +177,9 @@ function ChatThreadRouteView() {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
if (!state.threadsHydrated || !routeThreadExists) {
if (!threadsHydrated || !routeThreadExists) {
return null;
}
+18 -18
View File
@@ -48,7 +48,8 @@ const RUNTIME_MODE_OPTIONS = [
function SettingsRouteView() {
const { theme, setTheme, resolvedTheme } = useTheme();
const { state, dispatch } = useStore();
const runtimeMode = useStore((state) => state.runtimeMode);
const setRuntimeMode = useStore((state) => state.setRuntimeMode);
const { settings, defaults, updateSettings } = useAppSettings();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
@@ -186,9 +187,10 @@ function SettingsRouteView() {
</div>
<div className="space-y-4">
<label className="block space-y-1">
<label htmlFor="codex-binary-path" className="block space-y-1">
<span className="text-xs font-medium text-foreground">Codex binary path</span>
<Input
id="codex-binary-path"
value={codexBinaryPath}
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
placeholder="codex"
@@ -199,9 +201,10 @@ function SettingsRouteView() {
</span>
</label>
<label className="block space-y-1">
<label htmlFor="codex-home-path" className="block space-y-1">
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
<Input
id="codex-home-path"
value={codexHomePath}
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
placeholder="/Users/you/.codex"
@@ -242,16 +245,11 @@ function SettingsRouteView() {
</div>
<div className="space-y-4">
<form
className="flex flex-col gap-3 sm:flex-row sm:items-start"
onSubmit={(event) => {
event.preventDefault();
addCustomModel();
}}
>
<label className="block flex-1 space-y-1">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start">
<label htmlFor="custom-model-slug" className="block flex-1 space-y-1">
<span className="text-xs font-medium text-foreground">Custom model slug</span>
<Input
id="custom-model-slug"
value={customModelInput}
onChange={(event) => {
setCustomModelInput(event.target.value);
@@ -259,6 +257,11 @@ function SettingsRouteView() {
setCustomModelError(null);
}
}}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
addCustomModel();
}}
placeholder="your-model-slug"
spellCheck={false}
/>
@@ -267,10 +270,10 @@ function SettingsRouteView() {
</span>
</label>
<Button className="sm:mt-6" type="submit">
<Button className="sm:mt-6" type="button" onClick={addCustomModel}>
Add model
</Button>
</form>
</div>
{customModelError ? (
<p className="text-xs text-destructive">{customModelError}</p>
@@ -333,7 +336,7 @@ function SettingsRouteView() {
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
{RUNTIME_MODE_OPTIONS.map((option) => {
const selected = state.runtimeMode === option.value;
const selected = runtimeMode === option.value;
return (
<button
key={option.value}
@@ -346,10 +349,7 @@ function SettingsRouteView() {
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => {
dispatch({
type: "SET_RUNTIME_MODE",
mode: option.value,
});
setRuntimeMode(option.value);
}}
>
<span className="flex flex-col">
+84 -25
View File
@@ -1,12 +1,5 @@
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import { type ReactNode } from "react";
import { create } from "zustand";
import {
DEFAULT_MODEL,
@@ -67,6 +60,29 @@ export interface AppState {
runtimeMode: RuntimeMode;
}
interface AppStore extends AppState {
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId) => void;
toggleProject: (projectId: Project["id"]) => void;
setThreadTerminalActivity: (
threadId: ThreadId,
terminalId: string,
hasRunningSubprocess: boolean,
) => void;
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
toggleThreadTerminal: (threadId: ThreadId) => void;
setThreadTerminalOpen: (threadId: ThreadId, open: boolean) => void;
setThreadTerminalHeight: (threadId: ThreadId, height: number) => void;
splitThreadTerminal: (threadId: ThreadId, terminalId: string) => void;
newThreadTerminal: (threadId: ThreadId, terminalId: string) => void;
setThreadActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
closeThreadTerminal: (threadId: ThreadId, terminalId: string) => void;
setThreadError: (threadId: ThreadId, error: string | null) => void;
setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
setRuntimeMode: (mode: RuntimeMode) => void;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v6",
@@ -804,23 +820,66 @@ export function reducer(state: AppState, action: Action): AppState {
}
}
// ── Context ──────────────────────────────────────────────────────────
function toAppState(store: AppStore): AppState {
return {
projects: store.projects,
threads: store.threads,
threadsHydrated: store.threadsHydrated,
runtimeMode: store.runtimeMode,
};
}
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export const useStore = create<AppStore>((set, get) => {
const applyAction = (action: Action): void => {
const currentState = toAppState(get());
const nextState = reducer(currentState, action);
if (nextState === currentState) {
return;
}
persistState(nextState);
set(nextState);
};
return {
...readPersistedState(),
syncServerReadModel: (readModel) => applyAction({ type: "SYNC_SERVER_READ_MODEL", readModel }),
markThreadVisited: (threadId, visitedAt) =>
applyAction({
type: "MARK_THREAD_VISITED",
threadId,
...(visitedAt === undefined ? {} : { visitedAt }),
}),
markThreadUnread: (threadId) => applyAction({ type: "MARK_THREAD_UNREAD", threadId }),
toggleProject: (projectId) => applyAction({ type: "TOGGLE_PROJECT", projectId }),
setThreadTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
applyAction({
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId,
terminalId,
hasRunningSubprocess,
}),
setProjectExpanded: (projectId, expanded) =>
applyAction({ type: "SET_PROJECT_EXPANDED", projectId, expanded }),
toggleThreadTerminal: (threadId) => applyAction({ type: "TOGGLE_THREAD_TERMINAL", threadId }),
setThreadTerminalOpen: (threadId, open) =>
applyAction({ type: "SET_THREAD_TERMINAL_OPEN", threadId, open }),
setThreadTerminalHeight: (threadId, height) =>
applyAction({ type: "SET_THREAD_TERMINAL_HEIGHT", threadId, height }),
splitThreadTerminal: (threadId, terminalId) =>
applyAction({ type: "SPLIT_THREAD_TERMINAL", threadId, terminalId }),
newThreadTerminal: (threadId, terminalId) =>
applyAction({ type: "NEW_THREAD_TERMINAL", threadId, terminalId }),
setThreadActiveTerminal: (threadId, terminalId) =>
applyAction({ type: "SET_THREAD_ACTIVE_TERMINAL", threadId, terminalId }),
closeThreadTerminal: (threadId, terminalId) =>
applyAction({ type: "CLOSE_THREAD_TERMINAL", threadId, terminalId }),
setThreadError: (threadId, error) => applyAction({ type: "SET_ERROR", threadId, error }),
setThreadBranch: (threadId, branch, worktreePath) =>
applyAction({ type: "SET_THREAD_BRANCH", threadId, branch, worktreePath }),
setRuntimeMode: (mode) => applyAction({ type: "SET_RUNTIME_MODE", mode }),
};
});
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
return useContext(StoreContext);
return children;
}