Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae56cd1502 | ||
|
|
7cd3857d39 | ||
|
|
36aa0dd4d1 | ||
|
|
b99a543ed7 | ||
|
|
ac0dda8278 | ||
|
|
8e44a09487 | ||
|
|
28298df342 | ||
|
|
69a0b7f2ba | ||
|
|
4010fcfb63 | ||
|
|
92fe14b53e | ||
|
|
fcc903e53e | ||
|
|
669ef4a61b | ||
|
|
51a0254156 | ||
|
|
b8a953b6d0 | ||
|
|
fc87d52ce4 | ||
|
|
d6c1bd7793 | ||
|
|
ef85d8d1d6 | ||
|
|
5679c5fbea |
No files matched your search
@@ -43,7 +43,10 @@ export default function BranchToolbar({
|
||||
envLocked,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarProps) {
|
||||
const { state, dispatch } = useStore();
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||
const setThreadErrorAction = useStore((store) => store.setError);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -51,9 +54,9 @@ export default function BranchToolbar({
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const serverThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const serverThread = threads.find((thread) => thread.id === threadId);
|
||||
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||
const activeProject = state.projects.find((project) => project.id === activeProjectId);
|
||||
const activeProject = 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 +117,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 +130,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 +169,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 +275,12 @@ export default function BranchToolbar({
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
autoHighlight
|
||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
||||
onOpenChange={(open) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
}
|
||||
}}
|
||||
open={isBranchMenuOpen}
|
||||
value={activeThreadBranch}
|
||||
>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,13 @@ 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((store) =>
|
||||
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||
);
|
||||
const activeProjectId = activeThread?.projectId ?? null;
|
||||
const activeProject = useStore((store) =>
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
@@ -342,7 +346,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 +360,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 +428,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"
|
||||
|
||||
@@ -21,6 +21,7 @@ import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -126,8 +127,10 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
||||
return null;
|
||||
}
|
||||
|
||||
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
|
||||
if (thread.runningTerminalIds.length === 0) {
|
||||
function terminalStatusFromRunningIds(
|
||||
runningTerminalIds: string[],
|
||||
): TerminalStatusIndicator | null {
|
||||
if (runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
@@ -228,12 +231,17 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const clearProjectDraftThreadId = useComposerDraftStore(
|
||||
@@ -260,23 +268,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 +422,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 +436,7 @@ export default function Sidebar() {
|
||||
params: { threadId: latestThread.id },
|
||||
});
|
||||
},
|
||||
[navigate, state.threads],
|
||||
[navigate, threads],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
@@ -436,20 +444,27 @@ export default function Sidebar() {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
setIsAddingProject(true);
|
||||
try {
|
||||
if (!api) return;
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
const finishAddingProject = () => {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
};
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
await api.orchestration.dispatchCommand({
|
||||
const existing = projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
finishAddingProject();
|
||||
return;
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -457,15 +472,15 @@ export default function Sidebar() {
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
createdAt,
|
||||
});
|
||||
await handleNewThread(projectId);
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (projectCreated) {
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
}
|
||||
finishAddingProject();
|
||||
},
|
||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
|
||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
@@ -476,13 +491,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 +515,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 +533,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 +571,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(),
|
||||
@@ -561,6 +579,7 @@ export default function Sidebar() {
|
||||
});
|
||||
clearComposerDraftForThread(threadId);
|
||||
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||
clearTerminalState(threadId);
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -602,12 +621,13 @@ export default function Sidebar() {
|
||||
appSettings.confirmThreadDelete,
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
dispatch,
|
||||
clearTerminalState,
|
||||
markThreadUnread,
|
||||
navigate,
|
||||
projects,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -618,10 +638,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 +681,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 +703,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 +717,14 @@ export default function Sidebar() {
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, 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 +773,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 +789,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>
|
||||
@@ -811,7 +831,10 @@ export default function Sidebar() {
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
const terminalStatus = terminalStatusFromRunningIds(
|
||||
selectThreadTerminalState(terminalStateByThreadId, thread.id)
|
||||
.runningTerminalIds,
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarMenuSubItem key={thread.id} className="w-full">
|
||||
@@ -929,7 +952,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 />
|
||||
|
||||
@@ -389,6 +389,9 @@ function TerminalViewport({
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
// autoFocus is intentionally omitted;
|
||||
// it is only read at mount time and must not trigger terminal teardown/recreation.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [cwd, runtimeEnv, terminalId, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -20,10 +20,9 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
|
||||
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
|
||||
) {
|
||||
const chipsRef = React.useRef<Element | null>(null);
|
||||
const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
|
||||
return (
|
||||
<ComboboxContext.Provider
|
||||
value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
|
||||
>
|
||||
<ComboboxContext.Provider value={value}>
|
||||
<ComboboxPrimitive.Root {...props} />
|
||||
</ComboboxContext.Provider>
|
||||
);
|
||||
|
||||
@@ -22,6 +22,7 @@ function ToggleGroup({
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const value = React.useMemo(() => ({ size, variant }), [size, variant]);
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
className={cn(
|
||||
@@ -42,11 +43,7 @@ function ToggleGroup({
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider
|
||||
value={React.useMemo(() => ({ size, variant }), [size, variant])}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
@@ -123,13 +124,18 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
const { dispatch } = useStore();
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
|
||||
const removeOrphanedTerminalStates = useTerminalStateStore(
|
||||
(store) => store.removeOrphanedTerminalStates,
|
||||
);
|
||||
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(() => {
|
||||
@@ -144,7 +150,13 @@ 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);
|
||||
const activeThreadIds = new Set(
|
||||
snapshot.threads
|
||||
.filter((t) => t.deletedAt === null)
|
||||
.map((t) => t.id),
|
||||
);
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
if (pending) {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
@@ -157,14 +169,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 +195,11 @@ function EventRouter() {
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe(event.threadId),
|
||||
terminalId: event.terminalId,
|
||||
useTerminalStateStore.getState().setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
});
|
||||
);
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
@@ -201,11 +211,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 +276,7 @@ function EventRouter() {
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [dispatch, navigate, queryClient]);
|
||||
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -133,13 +133,13 @@ const DiffPanelInlineSidebar = (props: {
|
||||
};
|
||||
|
||||
function ChatThreadRouteView() {
|
||||
const { state } = useStore();
|
||||
const threadsHydrated = useStore((store) => store.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((store) => store.threads.some((thread) => thread.id === threadId));
|
||||
const draftThreadExists = useComposerDraftStore(
|
||||
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
|
||||
);
|
||||
@@ -167,7 +167,7 @@ function ChatThreadRouteView() {
|
||||
}, [navigate, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.threadsHydrated) {
|
||||
if (!threadsHydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -175,9 +175,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;
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ function ChatThreadRouteView() {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView threadId={threadId} />
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
||||
</>
|
||||
@@ -195,7 +195,7 @@ function ChatThreadRouteView() {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView threadId={threadId} />
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={<DiffLoadingFallback inline={false} />}>
|
||||
|
||||
@@ -48,7 +48,8 @@ const RUNTIME_MODE_OPTIONS = [
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const { state, dispatch } = useStore();
|
||||
const runtimeMode = useStore((store) => store.runtimeMode);
|
||||
const setRuntimeMode = useStore((store) => store.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">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { reducer, type AppState } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
import { markThreadUnread, type AppState } from "./store";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
turnDiffSummaries: [],
|
||||
@@ -54,8 +42,8 @@ function makeState(thread: Thread): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer", () => {
|
||||
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
|
||||
describe("store pure functions", () => {
|
||||
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
|
||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
@@ -71,10 +59,7 @@ describe("store reducer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
|
||||
const updatedThread = next.threads[0];
|
||||
expect(updatedThread).toBeDefined();
|
||||
@@ -84,7 +69,7 @@ describe("store reducer", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("does not change a thread without a completed turn", () => {
|
||||
it("markThreadUnread does not change a thread without a completed turn", () => {
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: null,
|
||||
@@ -92,70 +77,8 @@ describe("store reducer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
|
||||
expect(next).toEqual(initialState);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store terminal activity reducer", () => {
|
||||
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
|
||||
});
|
||||
|
||||
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
runningTerminalIds: ["alt"],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: false,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores activity events for unknown terminal ids", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "missing",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
+214
-627
@@ -1,13 +1,4 @@
|
||||
import {
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProviderSessionId,
|
||||
@@ -16,48 +7,15 @@ import {
|
||||
type OrchestrationSessionStatus,
|
||||
resolveModelSlug,
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
|
||||
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
|
||||
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
|
||||
| {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY";
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
hasRunningSubprocess: boolean;
|
||||
}
|
||||
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
|
||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
||||
| { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: ThreadId;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppState {
|
||||
@@ -87,11 +45,10 @@ const initialState: AppState = {
|
||||
};
|
||||
const persistedExpandedProjectCwds = new Set<string>();
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
// ── Persist helpers ──────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
if (!raw) return initialState;
|
||||
@@ -119,7 +76,6 @@ function readPersistedState(): AppState {
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
PERSISTED_STATE_KEY,
|
||||
@@ -138,12 +94,21 @@ function persistState(state: AppState): void {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Pure helpers ──────────────────────────────────────────────────────
|
||||
|
||||
function updateThread(
|
||||
threads: Thread[],
|
||||
threadId: ThreadId,
|
||||
updater: (t: Thread) => Thread,
|
||||
): Thread[] {
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
let changed = false;
|
||||
const next = threads.map((t) => {
|
||||
if (t.id !== threadId) return t;
|
||||
const updated = updater(t);
|
||||
if (updated !== t) changed = true;
|
||||
return updated;
|
||||
});
|
||||
return changed ? next : threads;
|
||||
}
|
||||
|
||||
function mapProjectsFromReadModel(
|
||||
@@ -193,9 +158,7 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
if (typeof window === "undefined") return "";
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
@@ -204,10 +167,7 @@ function resolveWsHttpOrigin(): string {
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
if (!wsCandidate) return window.location.origin;
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
@@ -233,594 +193,221 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||
return `/attachments/${encodeURIComponent(attachmentId)}`;
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
// ── Pure state transition functions ────────────────────────────────────
|
||||
|
||||
function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: string[],
|
||||
terminalIds: string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const groups: ThreadTerminalGroup[] = [];
|
||||
|
||||
for (const group of thread.terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (groups.length > 0) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
const terminalIds = normalizeTerminalIds(thread.terminalIds);
|
||||
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
|
||||
const activeGroupIndexFromId = terminalGroups.findIndex(
|
||||
(group) => group.id === thread.activeTerminalGroupId,
|
||||
export function syncServerReadModel(
|
||||
state: AppState,
|
||||
readModel: OrchestrationReadModel,
|
||||
): AppState {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: activeGroupIndexFromTerminal >= 0
|
||||
? activeGroupIndexFromTerminal
|
||||
: 0;
|
||||
const activeTerminalGroupId =
|
||||
terminalGroups[activeGroupIndex]?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(activeTerminalId);
|
||||
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const threads = readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.session?.providerThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
session: thread.session
|
||||
? {
|
||||
sessionId:
|
||||
thread.session.providerSessionId ??
|
||||
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
|
||||
provider: toLegacyProvider(thread.session.providerName),
|
||||
status: toLegacySessionStatus(thread.session.status),
|
||||
orchestrationStatus: thread.session.status,
|
||||
threadId: thread.session.providerThreadId,
|
||||
activeTurnId: thread.session.activeTurnId ?? undefined,
|
||||
createdAt: thread.session.updatedAt,
|
||||
updatedAt: thread.session.updatedAt,
|
||||
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
...(message.streaming ? {} : { completedAt: message.updatedAt }),
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
return normalizedMessage;
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
|
||||
turnId: checkpoint.turnId,
|
||||
completedAt: checkpoint.completedAt,
|
||||
status: checkpoint.status,
|
||||
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
|
||||
checkpointTurnCount: checkpoint.checkpointTurnCount,
|
||||
checkpointRef: checkpoint.checkpointRef,
|
||||
files: checkpoint.files.map((file) => ({ ...file })),
|
||||
})),
|
||||
activities: thread.activities.map((activity) => ({ ...activity })),
|
||||
};
|
||||
});
|
||||
return {
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
if (!thread.terminalIds.includes(terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: nextTerminalGroupId,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: nextTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
|
||||
const closedTerminalGroup = thread.terminalGroups.find((group) =>
|
||||
group.terminalIds.includes(terminalId),
|
||||
);
|
||||
const closedTerminalGroupIndex = closedTerminalGroup
|
||||
? closedTerminalGroup.terminalIds.indexOf(terminalId)
|
||||
: -1;
|
||||
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
|
||||
(id) => id !== terminalId,
|
||||
);
|
||||
const nextActiveTerminalId =
|
||||
thread.activeTerminalId === terminalId
|
||||
? (remainingTerminalsInClosedGroup[
|
||||
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
|
||||
] ??
|
||||
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: thread.activeTerminalId;
|
||||
const nextTerminalGroups = thread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
visitedAt?: string,
|
||||
): AppState {
|
||||
const at = visitedAt ?? new Date().toISOString();
|
||||
const visitedAtMs = Date.parse(at);
|
||||
const threads = updateThread(state.threads, threadId, (thread) => {
|
||||
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
|
||||
if (
|
||||
Number.isFinite(previousVisitedAtMs) &&
|
||||
Number.isFinite(visitedAtMs) &&
|
||||
previousVisitedAtMs >= visitedAtMs
|
||||
) {
|
||||
return thread;
|
||||
}
|
||||
return { ...thread, lastVisitedAt: at };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
thread: Thread,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): Thread {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(terminalId)) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIds],
|
||||
export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) return thread;
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) return thread;
|
||||
return { ...thread, lastVisitedAt: unreadVisitedAt };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "SYNC_SERVER_READ_MODEL": {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
action.readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const threads = action.readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.session?.providerThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
terminalOpen: existing?.terminalOpen ?? false,
|
||||
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: existing?.runningTerminalIds ?? [],
|
||||
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: existing?.terminalGroups ?? [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId:
|
||||
existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: thread.session
|
||||
? {
|
||||
sessionId:
|
||||
thread.session.providerSessionId ??
|
||||
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
|
||||
provider: toLegacyProvider(thread.session.providerName),
|
||||
status: toLegacySessionStatus(thread.session.status),
|
||||
orchestrationStatus: thread.session.status,
|
||||
threadId: thread.session.providerThreadId,
|
||||
activeTurnId: thread.session.activeTurnId ?? undefined,
|
||||
createdAt: thread.session.updatedAt,
|
||||
updatedAt: thread.session.updatedAt,
|
||||
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
...(message.streaming ? {} : { completedAt: message.updatedAt }),
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
return normalizedMessage;
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
|
||||
turnId: checkpoint.turnId,
|
||||
completedAt: checkpoint.completedAt,
|
||||
status: checkpoint.status,
|
||||
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
|
||||
checkpointTurnCount: checkpoint.checkpointTurnCount,
|
||||
checkpointRef: checkpoint.checkpointRef,
|
||||
files: checkpoint.files.map((file) => ({ ...file })),
|
||||
})),
|
||||
activities: thread.activities.map((activity) => ({ ...activity })),
|
||||
});
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_VISITED": {
|
||||
const visitedAt = action.visitedAt ?? new Date().toISOString();
|
||||
const visitedAtMs = Date.parse(visitedAt);
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
|
||||
if (
|
||||
Number.isFinite(previousVisitedAtMs) &&
|
||||
Number.isFinite(visitedAtMs) &&
|
||||
previousVisitedAtMs >= visitedAtMs
|
||||
) {
|
||||
return thread;
|
||||
}
|
||||
return {
|
||||
...thread,
|
||||
lastVisitedAt: visitedAt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_UNREAD": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) {
|
||||
return thread;
|
||||
}
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) {
|
||||
return thread;
|
||||
}
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) {
|
||||
return thread;
|
||||
}
|
||||
return {
|
||||
...thread,
|
||||
lastVisitedAt: unreadVisitedAt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_ACTIVITY":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_PROJECT_EXPANDED":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalOpen: !t.terminalOpen,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_OPEN":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalOpen: action.open,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_HEIGHT":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalHeight: action.height,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SPLIT_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
|
||||
...group,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
let activeGroupIndex = terminalGroups.findIndex(
|
||||
(group) => group.id === normalizedThread.activeTerminalGroupId,
|
||||
);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(
|
||||
terminalGroups,
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
terminalGroups.push({
|
||||
id: fallbackGroupId(normalizedThread.activeTerminalId),
|
||||
terminalIds: [normalizedThread.activeTerminalId],
|
||||
});
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
|
||||
existingGroupIndex
|
||||
]!.terminalIds.filter((id) => id !== action.terminalId);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
if (existingGroupIndex < activeGroupIndex) {
|
||||
activeGroupIndex -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalizedThread;
|
||||
}
|
||||
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(action.terminalId);
|
||||
}
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "NEW_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
const nextGroupId = fallbackGroupId(action.terminalId);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_ACTIVE_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
const nextActiveGroupIndex = findGroupIndexByTerminalId(
|
||||
normalizedThread.terminalGroups,
|
||||
action.terminalId,
|
||||
);
|
||||
const activeTerminalGroupId =
|
||||
nextActiveGroupIndex >= 0
|
||||
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
|
||||
normalizedThread.activeTerminalGroupId)
|
||||
: normalizedThread.activeTerminalGroupId;
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "CLOSE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
closeThreadTerminal(thread, action.terminalId),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_ERROR":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
error: action.error,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
// When the effective cwd changes (worktreePath differs), the old
|
||||
// session is no longer valid — clear it so ensureSession creates a
|
||||
// new one with the correct cwd on the next message.
|
||||
const cwdChanged = t.worktreePath !== action.worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch: action.branch,
|
||||
worktreePath: action.worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Context ──────────────────────────────────────────────────────────
|
||||
export function setProjectExpanded(
|
||||
state: AppState,
|
||||
projectId: Project["id"],
|
||||
expanded: boolean,
|
||||
): AppState {
|
||||
let changed = false;
|
||||
const projects = state.projects.map((p) => {
|
||||
if (p.id !== projectId || p.expanded === expanded) return p;
|
||||
changed = true;
|
||||
return { ...p, expanded };
|
||||
});
|
||||
return changed ? { ...state, projects } : state;
|
||||
}
|
||||
|
||||
const StoreContext = createContext<{
|
||||
state: AppState;
|
||||
dispatch: Dispatch<Action>;
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (t) => {
|
||||
if (t.error === error) return t;
|
||||
return { ...t, error };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
}
|
||||
|
||||
export function setThreadBranch(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (t) => {
|
||||
if (t.branch === branch && t.worktreePath === worktreePath) return t;
|
||||
const cwdChanged = t.worktreePath !== worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch,
|
||||
worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
}
|
||||
|
||||
export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
|
||||
if (state.runtimeMode === mode) return state;
|
||||
return { ...state, runtimeMode: mode };
|
||||
}
|
||||
|
||||
// ── Zustand store ────────────────────────────────────────────────────
|
||||
|
||||
interface AppStore extends AppState {
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
|
||||
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
|
||||
markThreadUnread: (threadId: ThreadId) => void;
|
||||
toggleProject: (projectId: Project["id"]) => void;
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
setThreadBranch: (
|
||||
threadId: ThreadId,
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
) => void;
|
||||
setRuntimeMode: (mode: RuntimeMode) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppStore>((set) => ({
|
||||
...readPersistedState(),
|
||||
syncServerReadModel: (readModel) =>
|
||||
set((state) => syncServerReadModel(state, readModel)),
|
||||
markThreadVisited: (threadId, visitedAt) =>
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId) =>
|
||||
set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) =>
|
||||
set((state) => toggleProject(state, projectId)),
|
||||
setProjectExpanded: (projectId, expanded) =>
|
||||
set((state) => setProjectExpanded(state, projectId, expanded)),
|
||||
setError: (threadId, error) =>
|
||||
set((state) => setError(state, threadId, error)),
|
||||
setThreadBranch: (threadId, branch, worktreePath) =>
|
||||
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
|
||||
setRuntimeMode: (mode) =>
|
||||
set((state) => setRuntimeMode(state, mode)),
|
||||
}));
|
||||
|
||||
// Persist on every state change (only runtimeMode + expandedProjectCwds)
|
||||
useStore.subscribe((state) => persistState(state));
|
||||
|
||||
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);
|
||||
persistState(useStore.getState());
|
||||
}, []);
|
||||
return createElement(Fragment, null, children);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "./terminalStateStore";
|
||||
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
|
||||
describe("terminalStateStore actions", () => {
|
||||
beforeEach(() => {
|
||||
if (typeof localStorage !== "undefined") {
|
||||
localStorage.clear();
|
||||
}
|
||||
useTerminalStateStore.setState({ terminalStateByThreadId: {} });
|
||||
});
|
||||
|
||||
it("returns a closed default terminal state for unknown threads", () => {
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens and splits terminals into the active group", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_ID, true);
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates new terminals in a separate group", () => {
|
||||
useTerminalStateStore.getState().newTerminal(THREAD_ID, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.activeTerminalGroupId).toBe("group-terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("tracks and clears terminal subprocess activity", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([
|
||||
"terminal-2",
|
||||
]);
|
||||
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.closeTerminal(THREAD_ID, "default");
|
||||
|
||||
expect(useTerminalStateStore.getState().terminalStateByThreadId[THREAD_ID]).toBeUndefined();
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).terminalIds).toEqual(["default"]);
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.splitTerminal(THREAD_ID, "terminal-3");
|
||||
store.closeTerminal(THREAD_ID, "terminal-3");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,532 @@
|
||||
/**
|
||||
* Single Zustand store for terminal UI state keyed by threadId.
|
||||
*
|
||||
* Terminal transition helpers are intentionally private to keep the public
|
||||
* API constrained to store actions/selectors.
|
||||
*/
|
||||
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
interface ThreadTerminalState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))].slice(
|
||||
0,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
);
|
||||
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(runningTerminalIds: string[], terminalIds: string[]): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
|
||||
let candidate = baseId;
|
||||
let index = 2;
|
||||
while (usedGroupIds.has(candidate)) {
|
||||
candidate = `${baseId}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
usedGroupIds.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(terminalGroups: ThreadTerminalGroup[], terminalId: string): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
const usedGroupIds = new Set<string>();
|
||||
|
||||
for (const group of terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
if (a[index] !== b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
const leftGroup = left[index];
|
||||
const rightGroup = right[index];
|
||||
if (!leftGroup || !rightGroup) return false;
|
||||
if (leftGroup.id !== rightGroup.id) return false;
|
||||
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
|
||||
return (
|
||||
left.terminalOpen === right.terminalOpen &&
|
||||
left.terminalHeight === right.terminalHeight &&
|
||||
left.activeTerminalId === right.activeTerminalId &&
|
||||
left.activeTerminalGroupId === right.activeTerminalGroupId &&
|
||||
arraysEqual(left.terminalIds, right.terminalIds) &&
|
||||
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
|
||||
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
});
|
||||
|
||||
function createDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return {
|
||||
...DEFAULT_THREAD_TERMINAL_STATE,
|
||||
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
|
||||
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
|
||||
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
|
||||
};
|
||||
}
|
||||
|
||||
function getDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return DEFAULT_THREAD_TERMINAL_STATE;
|
||||
}
|
||||
|
||||
function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)
|
||||
? state.activeTerminalGroupId
|
||||
: null;
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
|
||||
|
||||
const normalized: ThreadTerminalState = {
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight:
|
||||
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
|
||||
? state.terminalHeight
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
runningTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
};
|
||||
return threadTerminalStateEqual(state, normalized) ? state : normalized;
|
||||
}
|
||||
|
||||
function isDefaultThreadTerminalState(state: ThreadTerminalState): boolean {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
return threadTerminalStateEqual(normalized, DEFAULT_THREAD_TERMINAL_STATE);
|
||||
}
|
||||
|
||||
function isValidTerminalId(terminalId: string): boolean {
|
||||
return terminalId.trim().length > 0;
|
||||
}
|
||||
|
||||
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
|
||||
return groups.map((group) => ({
|
||||
id: group.id,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
}
|
||||
|
||||
function upsertTerminalIntoGroups(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
mode: "split" | "new",
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!isValidTerminalId(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const isNewTerminal = !normalized.terminalIds.includes(terminalId);
|
||||
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const terminalIds = isNewTerminal ? [...normalized.terminalIds, terminalId] : normalized.terminalIds;
|
||||
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[existingGroupIndex]!.terminalIds.filter(
|
||||
(id) => id !== terminalId,
|
||||
);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(normalized.activeTerminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalOpen(state: ThreadTerminalState, open: boolean): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (normalized.terminalOpen === open) return normalized;
|
||||
return { ...normalized, terminalOpen: open };
|
||||
}
|
||||
|
||||
function setThreadTerminalHeight(state: ThreadTerminalState, height: number): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
|
||||
return normalized;
|
||||
}
|
||||
return { ...normalized, terminalHeight: height };
|
||||
}
|
||||
|
||||
function splitThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "split");
|
||||
}
|
||||
|
||||
function newThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "new");
|
||||
}
|
||||
|
||||
function setThreadActiveTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const activeTerminalGroupId =
|
||||
normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
|
||||
normalized.activeTerminalGroupId;
|
||||
if (
|
||||
normalized.activeTerminalId === terminalId &&
|
||||
normalized.activeTerminalGroupId === activeTerminalGroupId
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
activeTerminalId: terminalId,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return createDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
|
||||
const nextActiveTerminalId =
|
||||
normalized.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(nextActiveTerminalId);
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
terminalOpen: normalized.terminalOpen,
|
||||
terminalHeight: normalized.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
|
||||
if (hasRunningSubprocess === alreadyRunning) {
|
||||
return normalized;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalized.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
|
||||
}
|
||||
|
||||
export function selectThreadTerminalState(
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
|
||||
threadId: ThreadId,
|
||||
): ThreadTerminalState {
|
||||
if (threadId.length === 0) {
|
||||
return getDefaultThreadTerminalState();
|
||||
}
|
||||
return terminalStateByThreadId[threadId] ?? getDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
function updateTerminalStateByThreadId(
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
|
||||
threadId: ThreadId,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
): Record<ThreadId, ThreadTerminalState> {
|
||||
if (threadId.length === 0) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
const current = selectThreadTerminalState(terminalStateByThreadId, threadId);
|
||||
const next = updater(current);
|
||||
if (next === current) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
if (isDefaultThreadTerminalState(next)) {
|
||||
if (terminalStateByThreadId[threadId] === undefined) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = terminalStateByThreadId;
|
||||
return rest as Record<ThreadId, ThreadTerminalState>;
|
||||
}
|
||||
|
||||
return {
|
||||
...terminalStateByThreadId,
|
||||
[threadId]: next,
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalStateStoreState {
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
|
||||
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
|
||||
setTerminalHeight: (threadId: ThreadId, height: number) => void;
|
||||
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
newTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setTerminalActivity: (
|
||||
threadId: ThreadId,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
) => void;
|
||||
clearTerminalState: (threadId: ThreadId) => void;
|
||||
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
|
||||
}
|
||||
|
||||
export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
persist(
|
||||
(set) => {
|
||||
const updateTerminal = (
|
||||
threadId: ThreadId,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
) => {
|
||||
set((state) => {
|
||||
const nextTerminalStateByThreadId = updateTerminalStateByThreadId(
|
||||
state.terminalStateByThreadId,
|
||||
threadId,
|
||||
updater,
|
||||
);
|
||||
if (nextTerminalStateByThreadId === state.terminalStateByThreadId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
terminalStateByThreadId: {},
|
||||
setTerminalOpen: (threadId, open) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalOpen(state, open)),
|
||||
setTerminalHeight: (threadId, height) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalHeight(state, height)),
|
||||
splitTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
|
||||
newTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
|
||||
setActiveTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadId, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
clearTerminalState: (threadId) =>
|
||||
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
|
||||
removeOrphanedTerminalStates: (activeThreadIds) =>
|
||||
set((state) => {
|
||||
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
|
||||
(id) => !activeThreadIds.has(id as ThreadId),
|
||||
);
|
||||
if (orphanedIds.length === 0) return state;
|
||||
const next = { ...state.terminalStateByThreadId };
|
||||
for (const id of orphanedIds) {
|
||||
delete next[id as ThreadId];
|
||||
}
|
||||
return { terminalStateByThreadId: next };
|
||||
}),
|
||||
};
|
||||
},
|
||||
{
|
||||
name: TERMINAL_STATE_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({
|
||||
terminalStateByThreadId: state.terminalStateByThreadId,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -79,13 +79,6 @@ export interface Thread {
|
||||
projectId: ProjectId;
|
||||
title: string;
|
||||
model: string;
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
session: ThreadSession | null;
|
||||
messages: ChatMessage[];
|
||||
error: string | null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
turnDiffSummaries: [],
|
||||
|
||||
Reference in new issue
Block a user