Skip to content
TypeScript

perf(web): the legacy sidebar compiles with the React Compiler (#20640)

Julius Marminge23163fdc4887
diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts
index f6585a82a1c..ae8d08a4acc 100644
--- a/apps/web/reactCompiledFiles.ts
+++ b/apps/web/reactCompiledFiles.ts
@@ -97,4 +97,5 @@ export const REACT_COMPILED_FILES = [
"apps/web/src/components/ThreadTerminalDrawer.tsx",
"apps/web/src/components/settings/SettingsPanels.tsx",
"apps/web/src/routes/_chat.pull-requests.tsx",
+ "apps/web/src/components/LegacySidebar.tsx",
] as const;
diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx
index 7c1dd9e502e..bf04efdf4e0 100644
--- a/apps/web/src/components/LegacySidebar.tsx
+++ b/apps/web/src/components/LegacySidebar.tsx
@@ -24,7 +24,7 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { ProjectFavicon } from "./ProjectFavicon";
import { useAtomValue } from "@effect/atom-react";
import { autoAnimate } from "@formkit/auto-animate";
-import React, { useCallback, useEffect, memo, useMemo, useRef, useState } from "react";
+import React, { useEffect, useEffectEvent, memo, useRef, useState } from "react";
import { cn } from "~/lib/utils";
import { useShallow } from "zustand/react/shallow";
import {
@@ -79,6 +79,7 @@ import {
import { isDesktopLocalConnectionTarget, isWslConnectionTarget } from "../connection/desktopLocal";
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { isElectron } from "../env";
+import { useStableCallback } from "../hooks/useStableCallback";
import { useTerminalFocus } from "../hooks/useTerminalFocus";
import { useOpenPrLink } from "../lib/openPullRequestLink";
import { releaseProjectDraftUploads } from "../lib/composerDraftUploads";
@@ -194,7 +195,6 @@ import {
isSidebarNestedLinkClick,
isTrailingDoubleClick,
resolveProjectStatusIndicator,
- resolveThreadRowClassName,
resolveThreadLastVisitedAt,
resolveThreadStatusPill,
orderItemsByPreferredIds,
@@ -291,6 +291,13 @@ function projectGroupingModeDescription(mode: SidebarProjectGroupingMode): strin
}
}
+// Every project row keys on this map, so it gets its own cache: inline, it
+// shared one with the modifier-key state and rebuilt on every key press.
+function useThreadJumpLabelMap(input: Parameters<typeof buildThreadJumpLabelMap>[0]) {
+ "use memo";
+ return buildThreadJumpLabelMap(input);
+}
+
function buildThreadJumpLabelMap(input: {
keybindings: ResolvedKeybindingsConfig;
platform: string;
@@ -376,6 +383,13 @@ function checkTaskPermission(environmentId: EnvironmentId): boolean {
return false;
}
+// The row's handlers key on this ref; built inline, the hooks after it kept the
+// compiler from caching it, so every render rebuilt all of them.
+function useScopedThreadRef(environmentId: EnvironmentId, threadId: ThreadId) {
+ "use memo";
+ return scopeThreadRef(environmentId, threadId);
+}
+
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
@@ -406,20 +420,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
} = props;
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
const canOperatePreview = useEnvironmentScope(thread.environmentId, AuthPreviewOperateScope);
- const threadRef = scopeThreadRef(thread.environmentId, thread.id);
+ const threadRef = useScopedThreadRef(thread.environmentId, thread.id);
const threadKey = scopedThreadKey(threadRef);
const [isFileDragOver, setIsFileDragOver] = useState(false);
- const fileDropHandlers = useMemo(
- () =>
- makeWorkspaceFileDropHandlers({
- setDragActive: setIsFileDragOver,
- addFiles: (files) => {
- onFileDropThreads(threadRef, files);
- },
- addFolders: () => {},
- }),
- [onFileDropThreads, threadRef],
- );
+ const fileDropHandlers = makeWorkspaceFileDropHandlers({
+ setDragActive: setIsFileDragOver,
+ addFiles: (files) => {
+ onFileDropThreads(threadRef, files);
+ },
+ addFolders: () => {},
+ });
useEffect(() => {
if (!isFileDragOver) return;
const clearFileDrag = () => setIsFileDragOver(false);
@@ -453,31 +463,27 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote"))
: null;
const isHighlighted = isActive || isSelected;
- const handleOpenDiscoveredPort = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- const port = discoveredPorts[0];
- if (!port || !canOperatePreview) return;
- event.preventDefault();
- event.stopPropagation();
- navigateToThread(threadRef);
- void (async () => {
- const result = await openDiscoveredPort({ threadRef, port, openPreview });
- if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
- return;
- }
- const error = squashAtomCommandFailure(result);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Unable to open preview",
- description:
- error instanceof Error ? error.message : "The preview could not be opened.",
- }),
- );
- })();
- },
- [canOperatePreview, discoveredPorts, navigateToThread, openPreview, threadRef],
- );
+ const handleOpenDiscoveredPort = (event: React.MouseEvent<HTMLButtonElement>) => {
+ const port = discoveredPorts[0];
+ if (!port || !canOperatePreview) return;
+ event.preventDefault();
+ event.stopPropagation();
+ navigateToThread(threadRef);
+ void (async () => {
+ const result = await openDiscoveredPort({ threadRef, port, openPreview });
+ if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
+ return;
+ }
+ const error = squashAtomCommandFailure(result);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Unable to open preview",
+ description: error instanceof Error ? error.message : "The preview could not be opened.",
+ }),
+ );
+ })();
+ };
const isThreadRunning = !threadRuntimeCanArchive(thread.runtime);
const threadStatus = resolveThreadStatusPill({
thread: {
@@ -505,84 +511,47 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
: canOperateThread && !isThreadRunning
? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
: "pointer-events-none";
- const clearConfirmingArchive = useCallback(() => {
+ const clearConfirmingArchive = () => {
setConfirmingArchiveThreadKey((current) => (current === threadKey ? null : current));
- }, [setConfirmingArchiveThreadKey, threadKey]);
- const handleMouseLeave = useCallback(() => {
+ };
+ const handleMouseLeave = () => {
clearConfirmingArchive();
- }, [clearConfirmingArchive]);
- const handleBlurCapture = useCallback(
- (event: React.FocusEvent<HTMLLIElement>) => {
- const currentTarget = event.currentTarget;
- requestAnimationFrame(() => {
- if (currentTarget.contains(document.activeElement)) {
- return;
- }
- clearConfirmingArchive();
- });
- },
- [clearConfirmingArchive],
- );
- const handleRowClick = useCallback(
- (event: React.MouseEvent) => {
- handleThreadClick(event, threadRef, orderedProjectThreadKeys);
- },
- [handleThreadClick, orderedProjectThreadKeys, threadRef],
- );
- const handleRowDoubleClick = useCallback(
- (event: React.MouseEvent) => {
- if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return;
- if (renamingThreadKey === threadKey) return;
- // On mobile the first tap navigates and closes the sidebar sheet, so the
- // inline rename can't be shown. Renaming there stays on the context menu.
- if (isMobile) return;
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
- if ((event.target as HTMLElement).closest("button, a")) return;
- event.preventDefault();
- startThreadRename(threadKey, thread.title);
- },
- [isMobile, renamingThreadKey, startThreadRename, threadKey, thread.environmentId, thread.title],
- );
- const handleRowKeyDown = useCallback(
- (event: React.KeyboardEvent) => {
- if (event.key !== "Enter" && event.key !== " ") return;
- event.preventDefault();
- navigateToThread(threadRef);
- },
- [navigateToThread, threadRef],
- );
- const handleRowContextMenu = useCallback(
- (event: React.MouseEvent) => {
- event.preventDefault();
- const hasSelection = useThreadSelectionStore.getState().hasSelection();
- if (hasSelection && isSelected) {
- void (async () => {
- const result = await settlePromise(() =>
- handleMultiSelectContextMenu({
- x: event.clientX,
- y: event.clientY,
- }),
- );
- if (result._tag === "Failure") {
- const error = squashAtomCommandFailure(result);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Thread action failed",
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- }
- })();
+ };
+ const handleBlurCapture = (event: React.FocusEvent<HTMLLIElement>) => {
+ const currentTarget = event.currentTarget;
+ requestAnimationFrame(() => {
+ if (currentTarget.contains(document.activeElement)) {
return;
}
-
- if (hasSelection) {
- clearSelection();
- }
+ clearConfirmingArchive();
+ });
+ };
+ const handleRowClick = (event: React.MouseEvent) => {
+ handleThreadClick(event, threadRef, orderedProjectThreadKeys);
+ };
+ const handleRowDoubleClick = (event: React.MouseEvent) => {
+ if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return;
+ if (renamingThreadKey === threadKey) return;
+ // On mobile the first tap navigates and closes the sidebar sheet, so the
+ // inline rename can't be shown. Renaming there stays on the context menu.
+ if (isMobile) return;
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+ if ((event.target as HTMLElement).closest("button, a")) return;
+ event.preventDefault();
+ startThreadRename(threadKey, thread.title);
+ };
+ const handleRowKeyDown = (event: React.KeyboardEvent) => {
+ if (event.key !== "Enter" && event.key !== " ") return;
+ event.preventDefault();
+ navigateToThread(threadRef);
+ };
+ const handleRowContextMenu = (event: React.MouseEvent) => {
+ event.preventDefault();
+ const hasSelection = useThreadSelectionStore.getState().hasSelection();
+ if (hasSelection && isSelected) {
void (async () => {
const result = await settlePromise(() =>
- handleThreadContextMenu(threadRef, {
+ handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
}),
@@ -598,118 +567,105 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
);
}
})();
- },
- [clearSelection, handleMultiSelectContextMenu, handleThreadContextMenu, isSelected, threadRef],
- );
- const handlePrClick = useCallback(
- (event: React.MouseEvent<HTMLAnchorElement>) => {
- const url = prStatus?.url ?? currentLinkedPr?.url;
- if (!url) return;
- const openedInRightPanel = openPrLink(
- event,
- url,
- openPullRequestsInRightPanel ? threadRef : undefined,
+ return;
+ }
+
+ if (hasSelection) {
+ clearSelection();
+ }
+ void (async () => {
+ const result = await settlePromise(() =>
+ handleThreadContextMenu(threadRef, {
+ x: event.clientX,
+ y: event.clientY,
+ }),
);
- if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) {
- navigateToThread(threadRef);
- }
- },
- [
- isActive,
- navigateToThread,
- openPrLink,
- openPullRequestsInRightPanel,
- prStatus,
- currentLinkedPr,
- threadRef,
- ],
- );
- const handleRenameInputRef = useCallback(
- (element: HTMLInputElement | null) => {
- if (element && renamingInputRef.current !== element) {
- renamingInputRef.current = element;
- element.focus();
- element.select();
- }
- },
- [renamingInputRef],
- );
- const handleRenameInputChange = useCallback(
- (event: React.ChangeEvent<HTMLInputElement>) => {
- setRenamingTitle(event.target.value);
- },
- [setRenamingTitle],
- );
- const handleRenameInputKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLInputElement>) => {
- event.stopPropagation();
- if (event.key === "Enter") {
- event.preventDefault();
- renamingCommittedRef.current = true;
- void commitRename(threadRef, renamingTitle, thread.title);
- } else if (event.key === "Escape") {
- event.preventDefault();
- renamingCommittedRef.current = true;
- cancelRename();
+ if (result._tag === "Failure") {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Thread action failed",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ }),
+ );
}
- },
- [cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef],
- );
- const handleRenameInputBlur = useCallback(() => {
+ })();
+ };
+ const handlePrClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
+ const url = prStatus?.url ?? currentLinkedPr?.url;
+ if (!url) return;
+ const openedInRightPanel = openPrLink(
+ event,
+ url,
+ openPullRequestsInRightPanel ? threadRef : undefined,
+ );
+ if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) {
+ navigateToThread(threadRef);
+ }
+ };
+ const handleRenameInputRef = (element: HTMLInputElement | null) => {
+ if (element && renamingInputRef.current !== element) {
+ renamingInputRef.current = element;
+ element.focus();
+ element.select();
+ }
+ };
+ const handleRenameInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ setRenamingTitle(event.target.value);
+ };
+ const handleRenameInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
+ event.stopPropagation();
+ if (event.key === "Enter") {
+ event.preventDefault();
+ renamingCommittedRef.current = true;
+ void commitRename(threadRef, renamingTitle, thread.title);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ renamingCommittedRef.current = true;
+ cancelRename();
+ }
+ };
+ const handleRenameInputBlur = () => {
if (!renamingCommittedRef.current) {
void commitRename(threadRef, renamingTitle, thread.title);
}
- }, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]);
+ };
// Without stopping `dblclick`, double-clicking to select a word would re-fire
// the row's rename handler and reset the in-progress edit back to the title.
- const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
+ const handleRenameInputClick = (event: React.MouseEvent<HTMLInputElement>) => {
event.stopPropagation();
- }, []);
- const handleConfirmArchiveRef = useCallback(
- (element: HTMLButtonElement | null) => {
- if (element) {
- confirmArchiveButtonRefs.current.set(threadKey, element);
- } else {
- confirmArchiveButtonRefs.current.delete(threadKey);
- }
- },
- [confirmArchiveButtonRefs, threadKey],
- );
- const stopPropagationOnPointerDown = useCallback(
- (event: React.PointerEvent<HTMLButtonElement>) => {
- event.stopPropagation();
- },
- [],
- );
- const handleConfirmArchiveClick = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- event.preventDefault();
- event.stopPropagation();
- clearConfirmingArchive();
- void attemptArchiveThread(threadRef);
- },
- [attemptArchiveThread, clearConfirmingArchive, threadRef],
- );
- const handleStartArchiveConfirmation = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- event.preventDefault();
- event.stopPropagation();
- if (!checkTaskPermission(thread.environmentId)) return;
- setConfirmingArchiveThreadKey(threadKey);
- requestAnimationFrame(() => {
- confirmArchiveButtonRefs.current.get(threadKey)?.focus();
- });
- },
- [confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey, thread.environmentId],
- );
- const handleArchiveImmediateClick = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- event.preventDefault();
- event.stopPropagation();
- void attemptArchiveThread(threadRef);
- },
- [attemptArchiveThread, threadRef],
- );
+ };
+ const handleConfirmArchiveRef = (element: HTMLButtonElement | null) => {
+ if (element) {
+ confirmArchiveButtonRefs.current.set(threadKey, element);
+ } else {
+ confirmArchiveButtonRefs.current.delete(threadKey);
+ }
+ };
+ const stopPropagationOnPointerDown = (event: React.PointerEvent<HTMLButtonElement>) => {
+ event.stopPropagation();
+ };
+ const handleConfirmArchiveClick = (event: React.MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ clearConfirmingArchive();
+ void attemptArchiveThread(threadRef);
+ };
+ const handleStartArchiveConfirmation = (event: React.MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!checkTaskPermission(thread.environmentId)) return;
+ setConfirmingArchiveThreadKey(threadKey);
+ requestAnimationFrame(() => {
+ confirmArchiveButtonRefs.current.get(threadKey)?.focus();
+ });
+ };
+ const handleArchiveImmediateClick = (event: React.MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ void attemptArchiveThread(threadRef);
+ };
return (
<SidebarMenuSubItem
@@ -1040,8 +996,8 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
expandThreadListForProject,
collapseThreadListForProject,
} = props;
- const showMoreButtonRender = useMemo(() => <button type="button" />, []);
- const showLessButtonRender = useMemo(() => <button type="button" />, []);
+ const showMoreButtonRender = <button type="button" />;
+ const showLessButtonRender = <button type="button" />;
return (
<SidebarMenuSub
@@ -1149,6 +1105,153 @@ interface SidebarProjectItemProps {
dragHandleProps: SortableProjectHandleProps | null;
}
+function resolveProjectThreadStatus(
+ thread: SidebarThreadSummary,
+ lastVisitedAtByThreadKey: ReadonlyMap<string, string | undefined>,
+) {
+ const lastVisitedAt = lastVisitedAtByThreadKey.get(
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ );
+ return resolveThreadStatusPill({
+ thread: {
+ ...thread,
+ ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
+ },
+ });
+}
+
+// Thread derivations for one project row. Built in their own hooks so they reach
+// SidebarProjectItem frozen: inline, its later calls made the compiler fuse the
+// ordered keys with the route-dependent panel, handing every row a new array.
+function useProjectThreads(project: SidebarProjectSnapshot) {
+ "use memo";
+ const threadSortOrder = useClientSettings<SidebarThreadSortOrder>(
+ (settings) => settings.sidebarThreadSortOrder,
+ );
+ const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);
+ const threadLastVisitedAts = useUiStateStore(
+ useShallow((state) =>
+ sidebarThreads.map(
+ (thread) =>
+ state.threadLastVisitedAtById[
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
+ ] ?? null,
+ ),
+ ),
+ );
+ const sidebarThreadByKey = new Map(
+ sidebarThreads.map(
+ (thread) =>
+ [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
+ ),
+ );
+ const memberProjectByScopedKey = new Map(
+ project.memberProjects.map((member) => [
+ scopedProjectKey(scopeProjectRef(member.environmentId, member.id)),
+ member,
+ ]),
+ );
+ const memberThreadCountByPhysicalKey = new Map<string, number>(
+ project.memberProjects.map((member) => [member.physicalProjectKey, 0] as const),
+ );
+ for (const thread of sidebarThreads) {
+ const member = memberProjectByScopedKey.get(
+ scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
+ );
+ if (!member) {
+ continue;
+ }
+ memberThreadCountByPhysicalKey.set(
+ member.physicalProjectKey,
+ (memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0) + 1,
+ );
+ }
+ const lastVisitedAtByThreadKey = new Map(
+ sidebarThreads.map((thread, index) => [
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined),
+ ]),
+ );
+ const visibleProjectThreads = sortThreads(
+ sidebarThreads.filter((thread) => thread.archivedAt === null),
+ threadSortOrder,
+ );
+ const projectStatus = resolveProjectStatusIndicator(
+ visibleProjectThreads.map((thread) =>
+ resolveProjectThreadStatus(thread, lastVisitedAtByThreadKey),
+ ),
+ );
+ const orderedProjectThreadKeys = visibleProjectThreads.map((thread) =>
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ );
+ return {
+ sidebarThreads,
+ sidebarThreadByKey,
+ memberProjectByScopedKey,
+ memberThreadCountByPhysicalKey,
+ lastVisitedAtByThreadKey,
+ visibleProjectThreads,
+ projectStatus,
+ orderedProjectThreadKeys,
+ };
+}
+
+function useProjectThreadPanel(input: {
+ visibleProjectThreads: readonly SidebarThreadSummary[];
+ lastVisitedAtByThreadKey: ReadonlyMap<string, string | undefined>;
+ activeRouteThreadKey: string | null;
+ projectExpanded: boolean;
+ isThreadListExpanded: boolean;
+}) {
+ "use memo";
+ const {
+ visibleProjectThreads,
+ lastVisitedAtByThreadKey,
+ activeRouteThreadKey,
+ projectExpanded,
+ isThreadListExpanded,
+ } = input;
+ const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>(
+ (settings) => settings.sidebarThreadPreviewCount,
+ );
+ const activeThreadKey = activeRouteThreadKey ?? undefined;
+ const pinnedCollapsedThread =
+ !activeThreadKey || projectExpanded
+ ? null
+ : (visibleProjectThreads.find(
+ (thread) =>
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
+ ) ?? null);
+ const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount;
+ const previewThreads =
+ isThreadListExpanded || !hasOverflowingThreads
+ ? visibleProjectThreads
+ : visibleProjectThreads.slice(0, sidebarThreadPreviewCount);
+ const visibleThreadKeys = new Set(
+ [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) =>
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ ),
+ );
+ const renderedThreads = pinnedCollapsedThread
+ ? [pinnedCollapsedThread]
+ : visibleProjectThreads.filter((thread) =>
+ visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
+ );
+ const hiddenThreads = visibleProjectThreads.filter(
+ (thread) =>
+ !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
+ );
+ return {
+ hasOverflowingThreads,
+ hiddenThreadStatus: resolveProjectStatusIndicator(
+ hiddenThreads.map((thread) => resolveProjectThreadStatus(thread, lastVisitedAtByThreadKey)),
+ ),
+ renderedThreads,
+ showEmptyThreadState: projectExpanded && visibleProjectThreads.length === 0,
+ shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null,
+ };
+}
+
const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjectItemProps) {
const {
project,
@@ -1175,9 +1278,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
: project.allRemoteMembersAreDesktopLocal
? "laptop"
: "cloud";
- const threadSortOrder = useClientSettings<SidebarThreadSortOrder>(
- (settings) => settings.sidebarThreadSortOrder,
- );
const appSettingsConfirmThreadDelete = useClientSettings<boolean>(
(settings) => settings.confirmThreadDelete,
);
@@ -1195,9 +1295,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
reportFailure: false,
});
const updateSettings = useUpdateClientSettings();
- const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>(
- (settings) => settings.sidebarThreadPreviewCount,
- );
const router = useRouter();
const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
@@ -1249,37 +1346,23 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
},
});
const openPrLink = useOpenPrLink();
- const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);
- const sidebarThreadByKey = useMemo(
- () =>
- new Map(
- sidebarThreads.map(
- (thread) =>
- [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
- ),
- ),
- [sidebarThreads],
- );
- // Keep a ref so callbacks can read the latest map without appearing in
- // dependency arrays (avoids invalidating every thread-row memo on each
- // thread-list change).
- const sidebarThreadByKeyRef = useRef(sidebarThreadByKey);
- sidebarThreadByKeyRef.current = sidebarThreadByKey;
- const projectThreads = sidebarThreads;
- const projectPreferenceKeys = useMemo(() => projectExpansionPreferenceKeys(project), [project]);
+ const {
+ sidebarThreads,
+ sidebarThreadByKey,
+ memberProjectByScopedKey,
+ memberThreadCountByPhysicalKey,
+ projectStatus,
+ visibleProjectThreads,
+ orderedProjectThreadKeys,
+ lastVisitedAtByThreadKey,
+ } = useProjectThreads(project);
+ // The "Delete anyway" toast action runs after the toast delay, so it must see
+ // the thread list as of the click, not as of the first prompt.
+ const readSidebarThreadByKey = useStableCallback(() => sidebarThreadByKey);
+ const projectPreferenceKeys = projectExpansionPreferenceKeys(project);
const projectExpanded = useUiStateStore((state) =>
resolveProjectExpanded(state.projectExpandedById, projectPreferenceKeys),
);
- const threadLastVisitedAts = useUiStateStore(
- useShallow((state) =>
- projectThreads.map(
- (thread) =>
- state.threadLastVisitedAtById[
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
- ] ?? null,
- ),
- ),
- );
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
@@ -1299,708 +1382,470 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
- const memberProjectByScopedKey = useMemo(
- () =>
- new Map(
- project.memberProjects.map((member) => [
- scopedProjectKey(scopeProjectRef(member.environmentId, member.id)),
- member,
- ]),
- ),
- [project.memberProjects],
- );
- const memberThreadCountByPhysicalKey = useMemo(() => {
- const counts = new Map<string, number>(
- project.memberProjects.map((member) => [member.physicalProjectKey, 0] as const),
- );
- for (const thread of projectThreads) {
- const member = memberProjectByScopedKey.get(
- scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
- );
- if (!member) {
- continue;
- }
- counts.set(member.physicalProjectKey, (counts.get(member.physicalProjectKey) ?? 0) + 1);
- }
- return counts;
- }, [memberProjectByScopedKey, project.memberProjects, projectThreads]);
-
- const { projectStatus, visibleProjectThreads, orderedProjectThreadKeys } = useMemo(() => {
- const lastVisitedAtByThreadKey = new Map(
- projectThreads.map((thread, index) => [
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined),
- ]),
- );
- const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => {
- const lastVisitedAt = lastVisitedAtByThreadKey.get(
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- );
- return resolveThreadStatusPill({
- thread: {
- ...thread,
- ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
- },
- });
- };
- const visibleProjectThreads = sortThreads(
- projectThreads.filter((thread) => thread.archivedAt === null),
- threadSortOrder,
- );
- const projectStatus = resolveProjectStatusIndicator(
- visibleProjectThreads.map((thread) => resolveProjectThreadStatus(thread)),
- );
- return {
- orderedProjectThreadKeys: visibleProjectThreads.map((thread) =>
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- ),
- projectStatus,
- visibleProjectThreads,
- };
- }, [projectThreads, threadLastVisitedAts, threadSortOrder]);
- const pinnedCollapsedThread = useMemo(() => {
- const activeThreadKey = activeRouteThreadKey ?? undefined;
- if (!activeThreadKey || projectExpanded) {
- return null;
- }
- return (
- visibleProjectThreads.find(
- (thread) =>
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
- ) ?? null
- );
- }, [activeRouteThreadKey, projectExpanded, visibleProjectThreads]);
-
const {
hasOverflowingThreads,
hiddenThreadStatus,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
- } = useMemo(() => {
- const lastVisitedAtByThreadKey = new Map(
- projectThreads.map((thread, index) => [
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined),
- ]),
- );
- const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => {
- const lastVisitedAt = lastVisitedAtByThreadKey.get(
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- );
- return resolveThreadStatusPill({
- thread: {
- ...thread,
- ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
- },
- });
- };
- const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount;
- const previewThreads =
- isThreadListExpanded || !hasOverflowingThreads
- ? visibleProjectThreads
- : visibleProjectThreads.slice(0, sidebarThreadPreviewCount);
- const visibleThreadKeys = new Set(
- [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) =>
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- ),
- );
- const renderedThreads = pinnedCollapsedThread
- ? [pinnedCollapsedThread]
- : visibleProjectThreads.filter((thread) =>
- visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
- );
- const hiddenThreads = visibleProjectThreads.filter(
- (thread) =>
- !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
- );
- return {
- hasOverflowingThreads,
- hiddenThreadStatus: resolveProjectStatusIndicator(
- hiddenThreads.map((thread) => resolveProjectThreadStatus(thread)),
- ),
- renderedThreads,
- showEmptyThreadState: projectExpanded && visibleProjectThreads.length === 0,
- shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null,
- };
- }, [
- isThreadListExpanded,
- pinnedCollapsedThread,
- projectExpanded,
- projectThreads,
- sidebarThreadPreviewCount,
- threadLastVisitedAts,
+ } = useProjectThreadPanel({
visibleProjectThreads,
- ]);
-
- const handleProjectButtonClick = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- if (suppressProjectClickForContextMenuRef.current) {
- suppressProjectClickForContextMenuRef.current = false;
- event.preventDefault();
- event.stopPropagation();
- return;
- }
- if (dragInProgressRef.current) {
- event.preventDefault();
- event.stopPropagation();
- return;
- }
- if (suppressProjectClickAfterDragRef.current) {
- suppressProjectClickAfterDragRef.current = false;
- event.preventDefault();
- event.stopPropagation();
- return;
- }
- if (useThreadSelectionStore.getState().hasSelection()) {
- clearSelection();
- }
- setProjectExpanded(projectPreferenceKeys, !projectExpanded);
- },
- [
- clearSelection,
- dragInProgressRef,
- projectExpanded,
- projectPreferenceKeys,
- setProjectExpanded,
- suppressProjectClickAfterDragRef,
- suppressProjectClickForContextMenuRef,
- ],
- );
+ lastVisitedAtByThreadKey,
+ activeRouteThreadKey,
+ projectExpanded,
+ isThreadListExpanded,
+ });
- const handleProjectButtonKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLButtonElement>) => {
- if (event.key !== "Enter" && event.key !== " ") return;
+ const handleProjectButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
+ if (suppressProjectClickForContextMenuRef.current) {
+ suppressProjectClickForContextMenuRef.current = false;
event.preventDefault();
- if (dragInProgressRef.current) {
- return;
- }
- setProjectExpanded(projectPreferenceKeys, !projectExpanded);
- },
- [dragInProgressRef, projectExpanded, projectPreferenceKeys, setProjectExpanded],
- );
+ event.stopPropagation();
+ return;
+ }
+ if (dragInProgressRef.current) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ if (suppressProjectClickAfterDragRef.current) {
+ suppressProjectClickAfterDragRef.current = false;
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ if (useThreadSelectionStore.getState().hasSelection()) {
+ clearSelection();
+ }
+ setProjectExpanded(projectPreferenceKeys, !projectExpanded);
+ };
- const handleProjectButtonPointerDownCapture = useCallback(
- (event: React.PointerEvent<HTMLButtonElement>) => {
- suppressProjectClickForContextMenuRef.current = false;
- if (
- isContextMenuPointerDown({
- button: event.button,
- ctrlKey: event.ctrlKey,
- isMac: isMacPlatform(navigator.platform),
- })
- ) {
- event.stopPropagation();
- }
+ const handleProjectButtonKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {
+ if (event.key !== "Enter" && event.key !== " ") return;
+ event.preventDefault();
+ if (dragInProgressRef.current) {
+ return;
+ }
+ setProjectExpanded(projectPreferenceKeys, !projectExpanded);
+ };
- suppressProjectClickAfterDragRef.current = false;
- },
- [suppressProjectClickAfterDragRef, suppressProjectClickForContextMenuRef],
- );
+ const handleProjectButtonPointerDownCapture = (event: React.PointerEvent<HTMLButtonElement>) => {
+ suppressProjectClickForContextMenuRef.current = false;
+ if (
+ isContextMenuPointerDown({
+ button: event.button,
+ ctrlKey: event.ctrlKey,
+ isMac: isMacPlatform(navigator.platform),
+ })
+ ) {
+ event.stopPropagation();
+ }
- const openProjectRenameDialog = useCallback((member: SidebarProjectGroupMember) => {
+ suppressProjectClickAfterDragRef.current = false;
+ };
+
+ const openProjectRenameDialog = (member: SidebarProjectGroupMember) => {
if (!checkTaskPermission(member.environmentId)) return;
setProjectRenameTarget(member);
setProjectRenameTitle(member.title);
- }, []);
+ };
- const openProjectGroupingDialog = useCallback(
- (member: SidebarProjectGroupMember) => {
- const overrideKey = deriveProjectGroupingOverrideKey(member);
- setProjectGroupingTarget(member);
- setProjectGroupingSelection(
- projectGroupingSettings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit",
- );
- },
- [projectGroupingSettings.sidebarProjectGroupingOverrides],
- );
+ const openProjectGroupingDialog = (member: SidebarProjectGroupMember) => {
+ const overrideKey = deriveProjectGroupingOverrideKey(member);
+ setProjectGroupingTarget(member);
+ setProjectGroupingSelection(
+ projectGroupingSettings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit",
+ );
+ };
- const removeProject = useCallback(
- async (member: SidebarProjectGroupMember) => {
- const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
- const result = await deleteProject({
- environmentId: member.environmentId,
- input: {
- projectId: member.id,
- force: true,
- },
- });
- if (result._tag === "Failure") {
- return result;
- }
- await waitForProjectRemoval(memberProjectRef);
- const draftStore = useComposerDraftStore.getState();
- releaseProjectDraftUploads(
- memberProjectRef,
- sidebarThreads
- .filter(
- (thread) =>
- thread.environmentId === member.environmentId && thread.projectId === member.id,
- )
- .map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
- );
- const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
- if (projectDraftThread) {
- draftStore.clearDraftThread(projectDraftThread.draftId);
- }
- draftStore.clearProjectDraftThreadId(memberProjectRef);
+ const removeProject = async (member: SidebarProjectGroupMember) => {
+ const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
+ const result = await deleteProject({
+ environmentId: member.environmentId,
+ input: {
+ projectId: member.id,
+ force: true,
+ },
+ });
+ if (result._tag === "Failure") {
return result;
- },
- [deleteProject, sidebarThreads],
- );
+ }
+ await waitForProjectRemoval(memberProjectRef);
+ const draftStore = useComposerDraftStore.getState();
+ releaseProjectDraftUploads(
+ memberProjectRef,
+ sidebarThreads
+ .filter(
+ (thread) =>
+ thread.environmentId === member.environmentId && thread.projectId === member.id,
+ )
+ .map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
+ );
+ const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
+ if (projectDraftThread) {
+ draftStore.clearDraftThread(projectDraftThread.draftId);
+ }
+ draftStore.clearProjectDraftThreadId(memberProjectRef);
+ return result;
+ };
- const handleRemoveProject = useCallback(
- async (member: SidebarProjectGroupMember) => {
- if (!checkTaskPermission(member.environmentId)) return;
- const api = readLocalApi();
- if (!api) {
- return;
- }
+ const handleRemoveProject = async (member: SidebarProjectGroupMember) => {
+ if (!checkTaskPermission(member.environmentId)) return;
+ const api = readLocalApi();
+ if (!api) {
+ return;
+ }
- const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
- const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0;
- if (memberThreadCount > 0) {
- const warningToastId = toastManager.add(
- stackedThreadToast({
- type: "warning",
- title: "Project is not empty",
- description: "Delete all threads in this project before removing it.",
- actionVariant: "destructive",
- actionProps: {
- children: "Delete anyway",
- onClick: () => {
- void (async () => {
- toastManager.close(warningToastId);
- await new Promise<void>((resolve) => {
- window.setTimeout(resolve, 180);
- });
- if (!checkTaskPermission(member.environmentId)) return;
-
- const latestProjectThreads = Array.from(
- sidebarThreadByKeyRef.current.values(),
- ).filter(
- (thread) =>
- thread.environmentId === memberProjectRef.environmentId &&
- thread.projectId === memberProjectRef.projectId,
- );
- const confirmed = await api.dialogs.confirm(
- latestProjectThreads.length > 0
- ? [
- `Remove project "${member.title}" and delete its ${latestProjectThreads.length} thread${
- latestProjectThreads.length === 1 ? "" : "s"
- }?`,
- `Path: ${member.workspaceRoot}`,
- ...(member.environmentLabel
- ? [`Environment: ${member.environmentLabel}`]
- : []),
- "This permanently clears conversation history for those threads and any archived threads.",
- "This removes only this project entry.",
- "This action cannot be undone.",
- ].join("\n")
- : [
- `Remove project "${member.title}"?`,
- `Path: ${member.workspaceRoot}`,
- ...(member.environmentLabel
- ? [`Environment: ${member.environmentLabel}`]
- : []),
- "This permanently clears any archived conversation history.",
- "This removes only this project entry.",
- ].join("\n"),
- { variant: "destructive" },
- );
- if (!confirmed) {
- return;
- }
+ const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
+ const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0;
+ if (memberThreadCount > 0) {
+ const warningToastId = toastManager.add(
+ stackedThreadToast({
+ type: "warning",
+ title: "Project is not empty",
+ description: "Delete all threads in this project before removing it.",
+ actionVariant: "destructive",
+ actionProps: {
+ children: "Delete anyway",
+ onClick: () => {
+ void (async () => {
+ toastManager.close(warningToastId);
+ await new Promise<void>((resolve) => {
+ window.setTimeout(resolve, 180);
+ });
+ if (!checkTaskPermission(member.environmentId)) return;
+
+ const latestProjectThreads = Array.from(readSidebarThreadByKey().values()).filter(
+ (thread) =>
+ thread.environmentId === memberProjectRef.environmentId &&
+ thread.projectId === memberProjectRef.projectId,
+ );
+ const confirmed = await api.dialogs.confirm(
+ latestProjectThreads.length > 0
+ ? [
+ `Remove project "${member.title}" and delete its ${latestProjectThreads.length} thread${
+ latestProjectThreads.length === 1 ? "" : "s"
+ }?`,
+ `Path: ${member.workspaceRoot}`,
+ ...(member.environmentLabel
+ ? [`Environment: ${member.environmentLabel}`]
+ : []),
+ "This permanently clears conversation history for those threads and any archived threads.",
+ "This removes only this project entry.",
+ "This action cannot be undone.",
+ ].join("\n")
+ : [
+ `Remove project "${member.title}"?`,
+ `Path: ${member.workspaceRoot}`,
+ ...(member.environmentLabel
+ ? [`Environment: ${member.environmentLabel}`]
+ : []),
+ "This permanently clears any archived conversation history.",
+ "This removes only this project entry.",
+ ].join("\n"),
+ { variant: "destructive" },
+ );
+ if (!confirmed) {
+ return;
+ }
- const result = await removeProject(member);
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: `Failed to remove "${member.title}"`,
- description:
- error instanceof Error
- ? error.message
- : "Unknown error removing project.",
- }),
- );
- }
- })().catch((error) => {
- const message =
- error instanceof Error ? error.message : "Unknown error removing project.";
- console.error("Failed to remove project", {
- projectId: member.id,
- environmentId: member.environmentId,
- ...safeErrorLogAttributes(error),
- });
+ const result = await removeProject(member);
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: `Failed to remove "${member.title}"`,
- description: message,
+ description:
+ error instanceof Error ? error.message : "Unknown error removing project.",
}),
);
+ }
+ })().catch((error) => {
+ const message =
+ error instanceof Error ? error.message : "Unknown error removing project.";
+ console.error("Failed to remove project", {
+ projectId: member.id,
+ environmentId: member.environmentId,
+ ...safeErrorLogAttributes(error),
});
- },
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: `Failed to remove "${member.title}"`,
+ description: message,
+ }),
+ );
+ });
},
- }),
- );
- return;
- }
-
- const message = [
- `Remove project "${member.title}"?`,
- `Path: ${member.workspaceRoot}`,
- ...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []),
- "This permanently clears any archived conversation history.",
- "This removes only this project entry.",
- ].join("\n");
- const confirmed = await api.dialogs.confirm(message, { variant: "destructive" });
- if (!confirmed) {
- return;
- }
+ },
+ }),
+ );
+ return;
+ }
- const result = await removeProject(member);
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- const message = error instanceof Error ? error.message : "Unknown error removing project.";
- console.error("Failed to remove project", {
- projectId: member.id,
- environmentId: member.environmentId,
- ...safeErrorLogAttributes(error),
- });
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: `Failed to remove "${member.title}"`,
- description: message,
- }),
- );
- }
- },
- [memberThreadCountByPhysicalKey, removeProject],
- );
+ const message = [
+ `Remove project "${member.title}"?`,
+ `Path: ${member.workspaceRoot}`,
+ ...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []),
+ "This permanently clears any archived conversation history.",
+ "This removes only this project entry.",
+ ].join("\n");
+ const confirmed = await api.dialogs.confirm(message, { variant: "destructive" });
+ if (!confirmed) {
+ return;
+ }
- const handleProjectButtonContextMenu = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- event.preventDefault();
- suppressProjectClickForContextMenuRef.current = true;
- void (async () => {
- const api = readLocalApi();
- if (!api) return;
-
- const actionHandlers = new Map<string, () => Promise<void> | void>();
- const makeLeaf = (
- action: "rename" | "grouping" | "copy-path" | "delete",
- member: SidebarProjectGroupMember,
- options?: {
- destructive?: boolean;
- disabled?: boolean;
- },
- ): ContextMenuItem<string> => {
- const id = `${action}:${member.physicalProjectKey}`;
- actionHandlers.set(id, () => {
- switch (action) {
- case "rename":
- openProjectRenameDialog(member);
- return;
- case "grouping":
- openProjectGroupingDialog(member);
- return;
- case "copy-path":
- copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot });
- return;
- case "delete":
- return handleRemoveProject(member);
- }
- });
+ const result = await removeProject(member);
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ const message = error instanceof Error ? error.message : "Unknown error removing project.";
+ console.error("Failed to remove project", {
+ projectId: member.id,
+ environmentId: member.environmentId,
+ ...safeErrorLogAttributes(error),
+ });
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: `Failed to remove "${member.title}"`,
+ description: message,
+ }),
+ );
+ }
+ };
- return {
- id,
- label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
- ...(options?.destructive ? { destructive: true } : {}),
- ...(options?.disabled ? { disabled: true } : {}),
- };
- };
+ const handleProjectButtonContextMenu = (event: React.MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ suppressProjectClickForContextMenuRef.current = true;
+ void (async () => {
+ const api = readLocalApi();
+ if (!api) return;
- const buildTargetedItem = (
- action: "rename" | "grouping" | "copy-path" | "delete",
- label: string,
- options?: {
- destructive?: boolean;
- isDisabled?: (member: SidebarProjectGroupMember) => boolean;
- },
- ): ContextMenuItem<string> => {
- if (project.memberProjects.length === 1) {
- const singleMember = project.memberProjects[0]!;
- return {
- ...makeLeaf(action, singleMember, {
- ...(options?.destructive ? { destructive: true } : {}),
- ...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}),
- }),
- label,
- ...(action === "delete" ? { icon: "trash" } : {}),
- };
+ const actionHandlers = new Map<string, () => Promise<void> | void>();
+ const makeLeaf = (
+ action: "rename" | "grouping" | "copy-path" | "delete",
+ member: SidebarProjectGroupMember,
+ options?: {
+ destructive?: boolean;
+ disabled?: boolean;
+ },
+ ): ContextMenuItem<string> => {
+ const id = `${action}:${member.physicalProjectKey}`;
+ actionHandlers.set(id, () => {
+ switch (action) {
+ case "rename":
+ openProjectRenameDialog(member);
+ return;
+ case "grouping":
+ openProjectGroupingDialog(member);
+ return;
+ case "copy-path":
+ copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot });
+ return;
+ case "delete":
+ return handleRemoveProject(member);
}
+ });
+ return {
+ id,
+ label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
+ ...(options?.destructive ? { destructive: true } : {}),
+ ...(options?.disabled ? { disabled: true } : {}),
+ };
+ };
+
+ const buildTargetedItem = (
+ action: "rename" | "grouping" | "copy-path" | "delete",
+ label: string,
+ options?: {
+ destructive?: boolean;
+ isDisabled?: (member: SidebarProjectGroupMember) => boolean;
+ },
+ ): ContextMenuItem<string> => {
+ if (project.memberProjects.length === 1) {
+ const singleMember = project.memberProjects[0]!;
return {
- id: `${action}:submenu`,
+ ...makeLeaf(action, singleMember, {
+ ...(options?.destructive ? { destructive: true } : {}),
+ ...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}),
+ }),
label,
...(action === "delete" ? { icon: "trash" } : {}),
- children: project.memberProjects.map((member) =>
- makeLeaf(action, member, {
- ...(options?.destructive ? { destructive: true } : {}),
- ...(options?.isDisabled?.(member) ? { disabled: true } : {}),
- }),
- ),
};
- };
-
- actionHandlers.set("project-settings", () => {
- if (isMobile) setOpenMobile(false);
- void router.navigate({
- to: "/projects/$projectKey",
- params: { projectKey: project.projectKey },
- });
- });
-
- const clicked = await api.contextMenu.show(
- [
- buildTargetedItem("rename", "Rename", {
- isDisabled: (member) =>
- !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
- }),
- buildTargetedItem("grouping", "Group into..."),
- buildTargetedItem("copy-path", "Copy Path"),
- { id: "project-settings", label: "Project settings", icon: "settings" },
- buildTargetedItem("delete", "Remove", {
- destructive: true,
- isDisabled: (member) =>
- !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
- }),
- ],
- {
- x: event.clientX,
- y: event.clientY,
- },
- );
-
- if (!clicked) {
- return;
}
- await actionHandlers.get(clicked)?.();
- })();
- },
- [
- copyPathToClipboard,
- handleRemoveProject,
- isMobile,
- openProjectGroupingDialog,
- openProjectRenameDialog,
- project.groupedProjectCount,
- project.memberProjects,
- project.projectKey,
- router,
- setOpenMobile,
- suppressProjectClickForContextMenuRef,
- ],
- );
+ return {
+ id: `${action}:submenu`,
+ label,
+ ...(action === "delete" ? { icon: "trash" } : {}),
+ children: project.memberProjects.map((member) =>
+ makeLeaf(action, member, {
+ ...(options?.destructive ? { destructive: true } : {}),
+ ...(options?.isDisabled?.(member) ? { disabled: true } : {}),
+ }),
+ ),
+ };
+ };
- const navigateToThread = useCallback(
- (threadRef: ScopedThreadRef) => {
- if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
- clearSelection();
- }
- setSelectionAnchor(scopedThreadKey(threadRef));
- if (isMobile) {
- setOpenMobile(false);
- }
- return router.navigate({
- to: "/$environmentId/$threadId",
- params: buildThreadRouteParams(threadRef),
+ actionHandlers.set("project-settings", () => {
+ if (isMobile) setOpenMobile(false);
+ void router.navigate({
+ to: "/projects/$projectKey",
+ params: { projectKey: project.projectKey },
+ });
});
- },
- [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor],
- );
- const handleThreadFileDrop = useCallback(
- async (threadRef: ScopedThreadRef, files: File[]) => {
- const dropId = queuePendingFileDrop({ threadRef, files });
- const targetPathname = router.buildLocation({
- to: "/$environmentId/$threadId",
- params: buildThreadRouteParams(threadRef),
- }).pathname;
- if (targetPathname === router.state.location.pathname) return;
- try {
- await navigateToThread(threadRef);
- if (targetPathname !== router.state.location.pathname) {
- clearPendingFileDrop(dropId);
- }
- } catch {
- clearPendingFileDrop(dropId);
- }
- },
- [clearPendingFileDrop, navigateToThread, queuePendingFileDrop, router],
- );
-
- const handleThreadClick = useCallback(
- (
- event: React.MouseEvent,
- threadRef: ScopedThreadRef,
- orderedProjectThreadKeys: readonly string[],
- ) => {
- if (isSidebarNestedLinkClick(event.target)) return;
- const isMac = isMacPlatform(navigator.platform);
- const isModClick = isMac ? event.metaKey : event.ctrlKey;
- const isShiftClick = event.shiftKey;
- const threadKey = scopedThreadKey(threadRef);
- const currentSelectionCount = useThreadSelectionStore.getState().selectedThreadKeys.size;
- if (isModClick) {
- event.preventDefault();
- toggleThreadSelection(threadKey);
- return;
- }
+ const clicked = await api.contextMenu.show(
+ [
+ buildTargetedItem("rename", "Rename", {
+ isDisabled: (member) =>
+ !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
+ }),
+ buildTargetedItem("grouping", "Group into..."),
+ buildTargetedItem("copy-path", "Copy Path"),
+ { id: "project-settings", label: "Project settings", icon: "settings" },
+ buildTargetedItem("delete", "Remove", {
+ destructive: true,
+ isDisabled: (member) =>
+ !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
+ }),
+ ],
+ {
+ x: event.clientX,
+ y: event.clientY,
+ },
+ );
- if (isShiftClick) {
- event.preventDefault();
- rangeSelectTo(threadKey, orderedProjectThreadKeys);
+ if (!clicked) {
return;
}
- // Ignore the trailing click of a plain double-click so it doesn't navigate
- // while a double-click is starting an inline rename. Placed after the
- // modifier branches so cmd/shift selection still processes every click.
- if (isTrailingDoubleClick(event.detail)) {
- return;
- }
+ await actionHandlers.get(clicked)?.();
+ })();
+ };
- if (currentSelectionCount > 0) {
- clearSelection();
- }
- setSelectionAnchor(threadKey);
- if (isMobile) {
- setOpenMobile(false);
+ const navigateToThread = (threadRef: ScopedThreadRef) => {
+ if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
+ clearSelection();
+ }
+ setSelectionAnchor(scopedThreadKey(threadRef));
+ if (isMobile) {
+ setOpenMobile(false);
+ }
+ return router.navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(threadRef),
+ });
+ };
+ const handleThreadFileDrop = async (threadRef: ScopedThreadRef, files: File[]) => {
+ const dropId = queuePendingFileDrop({ threadRef, files });
+ const targetPathname = router.buildLocation({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(threadRef),
+ }).pathname;
+ if (targetPathname === router.state.location.pathname) return;
+ try {
+ await navigateToThread(threadRef);
+ if (targetPathname !== router.state.location.pathname) {
+ clearPendingFileDrop(dropId);
}
- void router.navigate({
- to: "/$environmentId/$threadId",
- params: buildThreadRouteParams(threadRef),
- });
- },
- [
- clearSelection,
- isMobile,
- rangeSelectTo,
- router,
- setOpenMobile,
- setSelectionAnchor,
- toggleThreadSelection,
- ],
- );
+ } catch {
+ clearPendingFileDrop(dropId);
+ }
+ };
- const handleMultiSelectContextMenu = useCallback(
- async (position: { x: number; y: number }) => {
- const api = readLocalApi();
- if (!api) return;
- const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
- if (threadKeys.length === 0) return;
- const count = threadKeys.length;
- const selectedThreadEntries = threadKeys.flatMap((threadKey) => {
- const threadRef = parseScopedThreadKey(threadKey);
- const thread = threadRef ? readThreadShell(threadRef) : null;
- return threadRef && thread ? [{ threadKey, threadRef, thread }] : [];
- });
- const hasRunningThread = selectedThreadEntries.some(
- ({ thread }) => !threadRuntimeCanArchive(thread.runtime),
- );
- const canOperateSelection = selectedThreadEntries.every(({ threadRef }) =>
- readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
- );
+ const handleThreadClick = (
+ event: React.MouseEvent,
+ threadRef: ScopedThreadRef,
+ orderedProjectThreadKeys: readonly string[],
+ ) => {
+ if (isSidebarNestedLinkClick(event.target)) return;
+ const isMac = isMacPlatform(navigator.platform);
+ const isModClick = isMac ? event.metaKey : event.ctrlKey;
+ const isShiftClick = event.shiftKey;
+ const threadKey = scopedThreadKey(threadRef);
+ const currentSelectionCount = useThreadSelectionStore.getState().selectedThreadKeys.size;
+
+ if (isModClick) {
+ event.preventDefault();
+ toggleThreadSelection(threadKey);
+ return;
+ }
- const clicked = await api.contextMenu.show(
- buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }).map((item) =>
- item.id === "archive" || item.id === "delete"
- ? { ...item, disabled: item.disabled || !canOperateSelection }
- : item,
- ),
- position,
- );
+ if (isShiftClick) {
+ event.preventDefault();
+ rangeSelectTo(threadKey, orderedProjectThreadKeys);
+ return;
+ }
- if (clicked === "mark-unread") {
- for (const { threadRef } of selectedThreadEntries) {
- markThreadUnread(threadRef);
- }
- clearSelection();
- return;
- }
+ // Ignore the trailing click of a plain double-click so it doesn't navigate
+ // while a double-click is starting an inline rename. Placed after the
+ // modifier branches so cmd/shift selection still processes every click.
+ if (isTrailingDoubleClick(event.detail)) {
+ return;
+ }
- if (
- (clicked === "archive" || clicked === "delete") &&
- !selectedThreadEntries.every(({ threadRef }) =>
- checkTaskPermission(threadRef.environmentId),
- )
- ) {
- return;
- }
+ if (currentSelectionCount > 0) {
+ clearSelection();
+ }
+ setSelectionAnchor(threadKey);
+ if (isMobile) {
+ setOpenMobile(false);
+ }
+ void router.navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(threadRef),
+ });
+ };
- if (clicked === "archive") {
- if (appSettingsConfirmThreadArchive) {
- const confirmed = await api.dialogs.confirm(
- `Archive ${count} thread${count === 1 ? "" : "s"}?`,
- );
- if (!confirmed) return;
- }
- if (
- !selectedThreadEntries.every(({ threadRef }) =>
- checkTaskPermission(threadRef.environmentId),
- )
- ) {
- return;
- }
+ const handleMultiSelectContextMenu = async (position: { x: number; y: number }) => {
+ const api = readLocalApi();
+ if (!api) return;
+ const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
+ if (threadKeys.length === 0) return;
+ const count = threadKeys.length;
+ const selectedThreadEntries = threadKeys.flatMap((threadKey) => {
+ const threadRef = parseScopedThreadKey(threadKey);
+ const thread = threadRef ? readThreadShell(threadRef) : null;
+ return threadRef && thread ? [{ threadKey, threadRef, thread }] : [];
+ });
+ const hasRunningThread = selectedThreadEntries.some(
+ ({ thread }) => !threadRuntimeCanArchive(thread.runtime),
+ );
+ const canOperateSelection = selectedThreadEntries.every(({ threadRef }) =>
+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
+ );
- const archiveOutcome = await archiveSelectedThreadEntries({
- entries: selectedThreadEntries,
- archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }),
- });
- for (const failure of archiveOutcome.followupFailures) {
- if (isAtomCommandInterrupted(failure)) continue;
- const error = squashAtomCommandFailure(failure);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Thread archived, but navigation failed",
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- }
- if (archiveOutcome.mutationFailure) {
- removeFromSelection(archiveOutcome.archivedThreadKeys);
- if (!isAtomCommandInterrupted(archiveOutcome.mutationFailure)) {
- const error = squashAtomCommandFailure(archiveOutcome.mutationFailure);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Failed to archive threads",
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- }
- return;
- }
- removeFromSelection(threadKeys);
- return;
+ const clicked = await api.contextMenu.show(
+ buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }).map((item) =>
+ item.id === "archive" || item.id === "delete"
+ ? { ...item, disabled: item.disabled || !canOperateSelection }
+ : item,
+ ),
+ position,
+ );
+
+ if (clicked === "mark-unread") {
+ for (const { threadRef } of selectedThreadEntries) {
+ markThreadUnread(threadRef);
}
+ clearSelection();
+ return;
+ }
- if (clicked !== "delete") return;
+ if (
+ (clicked === "archive" || clicked === "delete") &&
+ !selectedThreadEntries.every(({ threadRef }) => checkTaskPermission(threadRef.environmentId))
+ ) {
+ return;
+ }
- if (appSettingsConfirmThreadDelete) {
+ if (clicked === "archive") {
+ if (appSettingsConfirmThreadArchive) {
const confirmed = await api.dialogs.confirm(
- [
- `Delete ${count} thread${count === 1 ? "" : "s"}?`,
- "This permanently clears conversation history for these threads.",
- ].join("\n"),
- { variant: "destructive" },
+ `Archive ${count} thread${count === 1 ? "" : "s"}?`,
);
if (!confirmed) return;
}
@@ -2012,200 +1857,232 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
- const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
+ const archiveOutcome = await archiveSelectedThreadEntries({
entries: selectedThreadEntries,
- delete: ({ threadRef }, deletedThreadKeys) =>
- deleteThread(threadRef, { deletedThreadKeys }),
+ archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }),
});
- if (firstFailure !== null) {
- const firstError = squashAtomCommandFailure(firstFailure);
+ for (const failure of archiveOutcome.followupFailures) {
+ if (isAtomCommandInterrupted(failure)) continue;
+ const error = squashAtomCommandFailure(failure);
toastManager.add(
stackedThreadToast({
type: "error",
- title: "Failed to delete threads",
- description: firstError instanceof Error ? firstError.message : "An error occurred.",
+ title: "Thread archived, but navigation failed",
+ description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
- removeFromSelection(
- getThreadKeysToDeselectAfterDelete(threadKeys, deletedThreadKeys, (threadKey) => {
- const threadRef = parseScopedThreadKey(threadKey);
- return threadRef !== null && readThreadShell(threadRef) !== null;
- }),
- );
- },
- [
- appSettingsConfirmThreadArchive,
- appSettingsConfirmThreadDelete,
- archiveThread,
- clearSelection,
- deleteThread,
- markThreadUnread,
- removeFromSelection,
- ],
- );
-
- const createThreadForProjectMember = useCallback(
- (member: SidebarProjectGroupMember) => {
- if (isMobile) {
- setOpenMobile(false);
- }
- void (async () => {
- const result = await settlePromise(() =>
- handleNewThread(scopeProjectRef(member.environmentId, member.id)),
- );
- if (result._tag === "Failure") {
- const error = squashAtomCommandFailure(result);
+ if (archiveOutcome.mutationFailure) {
+ removeFromSelection(archiveOutcome.archivedThreadKeys);
+ if (!isAtomCommandInterrupted(archiveOutcome.mutationFailure)) {
+ const error = squashAtomCommandFailure(archiveOutcome.mutationFailure);
toastManager.add(
stackedThreadToast({
type: "error",
- title: "Could not create thread",
+ title: "Failed to archive threads",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
- })();
- },
- [handleNewThread, isMobile, setOpenMobile],
- );
-
- const handleCreateThreadClick = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- event.preventDefault();
- event.stopPropagation();
-
- if (project.memberProjects.length === 1) {
- createThreadForProjectMember(project.memberProjects[0]!);
return;
}
+ removeFromSelection(threadKeys);
+ return;
+ }
- void (async () => {
- const api = readLocalApi();
- if (!api) {
- return;
- }
- const clickedResult = await settlePromise(() =>
- api.contextMenu.show(
- project.memberProjects.map((member) => ({
- id: member.physicalProjectKey,
- label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
- })),
- {
- x: event.clientX,
- y: event.clientY,
- },
- ),
- );
- if (clickedResult._tag === "Failure") {
- const error = squashAtomCommandFailure(clickedResult);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Could not choose environment",
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- return;
- }
- const clicked = clickedResult.value;
- if (!clicked) {
- return;
- }
- const targetMember = project.memberProjects.find(
- (member) => member.physicalProjectKey === clicked,
- );
- if (!targetMember) {
- return;
- }
- createThreadForProjectMember(targetMember);
- })();
- },
- [createThreadForProjectMember, project.groupedProjectCount, project.memberProjects],
- );
+ if (clicked !== "delete") return;
- const attemptArchiveThread = useCallback(
- async (threadRef: ScopedThreadRef) => {
- if (!checkTaskPermission(threadRef.environmentId)) return;
- const result = await archiveThread(threadRef);
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ if (appSettingsConfirmThreadDelete) {
+ const confirmed = await api.dialogs.confirm(
+ [
+ `Delete ${count} thread${count === 1 ? "" : "s"}?`,
+ "This permanently clears conversation history for these threads.",
+ ].join("\n"),
+ { variant: "destructive" },
+ );
+ if (!confirmed) return;
+ }
+ if (
+ !selectedThreadEntries.every(({ threadRef }) => checkTaskPermission(threadRef.environmentId))
+ ) {
+ return;
+ }
+
+ const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
+ entries: selectedThreadEntries,
+ delete: ({ threadRef }, deletedThreadKeys) => deleteThread(threadRef, { deletedThreadKeys }),
+ });
+ if (firstFailure !== null) {
+ const firstError = squashAtomCommandFailure(firstFailure);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Failed to delete threads",
+ description: firstError instanceof Error ? firstError.message : "An error occurred.",
+ }),
+ );
+ }
+ removeFromSelection(
+ getThreadKeysToDeselectAfterDelete(threadKeys, deletedThreadKeys, (threadKey) => {
+ const threadRef = parseScopedThreadKey(threadKey);
+ return threadRef !== null && readThreadShell(threadRef) !== null;
+ }),
+ );
+ };
+
+ const createThreadForProjectMember = (member: SidebarProjectGroupMember) => {
+ if (isMobile) {
+ setOpenMobile(false);
+ }
+ void (async () => {
+ const result = await settlePromise(() =>
+ handleNewThread(scopeProjectRef(member.environmentId, member.id)),
+ );
+ if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
- title: "Failed to archive thread",
+ title: "Could not create thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
- },
- [archiveThread],
- );
-
- const cancelRename = useCallback(() => {
- setRenamingThreadKey(null);
- renamingInputRef.current = null;
- }, []);
+ })();
+ };
- const startThreadRename = useCallback((threadKey: string, title: string) => {
- const threadRef = parseScopedThreadKey(threadKey);
- if (!threadRef || !checkTaskPermission(threadRef.environmentId)) return;
- setRenamingThreadKey(threadKey);
- setRenamingTitle(title);
- renamingCommittedRef.current = false;
- }, []);
+ const handleCreateThreadClick = (event: React.MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
- const commitRename = useCallback(
- async (threadRef: ScopedThreadRef, newTitle: string, originalTitle: string) => {
- const threadKey = scopedThreadKey(threadRef);
- const finishRename = () => {
- setRenamingThreadKey((current) => {
- if (current !== threadKey) return current;
- renamingInputRef.current = null;
- return null;
- });
- };
+ if (project.memberProjects.length === 1) {
+ createThreadForProjectMember(project.memberProjects[0]!);
+ return;
+ }
- const trimmed = newTitle.trim();
- if (trimmed.length === 0) {
- toastManager.add({
- type: "warning",
- title: "Thread title cannot be empty",
- });
- finishRename();
- return;
- }
- if (trimmed === originalTitle) {
- finishRename();
+ void (async () => {
+ const api = readLocalApi();
+ if (!api) {
return;
}
- const result = await updateThreadMetadata({
- environmentId: threadRef.environmentId,
- input: {
- threadId: threadRef.threadId,
- title: trimmed,
- },
- });
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
+ const clickedResult = await settlePromise(() =>
+ api.contextMenu.show(
+ project.memberProjects.map((member) => ({
+ id: member.physicalProjectKey,
+ label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
+ })),
+ {
+ x: event.clientX,
+ y: event.clientY,
+ },
+ ),
+ );
+ if (clickedResult._tag === "Failure") {
+ const error = squashAtomCommandFailure(clickedResult);
toastManager.add(
stackedThreadToast({
type: "error",
- title: "Failed to rename thread",
+ title: "Could not choose environment",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
+ return;
+ }
+ const clicked = clickedResult.value;
+ if (!clicked) {
+ return;
+ }
+ const targetMember = project.memberProjects.find(
+ (member) => member.physicalProjectKey === clicked,
+ );
+ if (!targetMember) {
+ return;
}
+ createThreadForProjectMember(targetMember);
+ })();
+ };
+
+ const attemptArchiveThread = async (threadRef: ScopedThreadRef) => {
+ if (!checkTaskPermission(threadRef.environmentId)) return;
+ const result = await archiveThread(threadRef);
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Failed to archive thread",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ }),
+ );
+ }
+ };
+
+ const cancelRename = () => {
+ setRenamingThreadKey(null);
+ renamingInputRef.current = null;
+ };
+
+ const startThreadRename = (threadKey: string, title: string) => {
+ const threadRef = parseScopedThreadKey(threadKey);
+ if (!threadRef || !checkTaskPermission(threadRef.environmentId)) return;
+ setRenamingThreadKey(threadKey);
+ setRenamingTitle(title);
+ renamingCommittedRef.current = false;
+ };
+
+ const commitRename = async (
+ threadRef: ScopedThreadRef,
+ newTitle: string,
+ originalTitle: string,
+ ) => {
+ const threadKey = scopedThreadKey(threadRef);
+ const finishRename = () => {
+ setRenamingThreadKey((current) => {
+ if (current !== threadKey) return current;
+ renamingInputRef.current = null;
+ return null;
+ });
+ };
+
+ const trimmed = newTitle.trim();
+ if (trimmed.length === 0) {
+ toastManager.add({
+ type: "warning",
+ title: "Thread title cannot be empty",
+ });
finishRename();
- },
- [updateThreadMetadata],
- );
+ return;
+ }
+ if (trimmed === originalTitle) {
+ finishRename();
+ return;
+ }
+ const result = await updateThreadMetadata({
+ environmentId: threadRef.environmentId,
+ input: {
+ threadId: threadRef.threadId,
+ title: trimmed,
+ },
+ });
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Failed to rename thread",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ }),
+ );
+ }
+ finishRename();
+ };
- const closeProjectRenameDialog = useCallback(() => {
+ const closeProjectRenameDialog = () => {
setProjectRenameTarget(null);
setProjectRenameTitle("");
- }, []);
+ };
- const submitProjectRename = useCallback(async () => {
+ const submitProjectRename = async () => {
if (!projectRenameTarget) {
return;
}
@@ -2243,14 +2120,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}),
);
}
- }, [closeProjectRenameDialog, projectRenameTarget, projectRenameTitle, updateProject]);
+ };
- const closeProjectGroupingDialog = useCallback(() => {
+ const closeProjectGroupingDialog = () => {
setProjectGroupingTarget(null);
setProjectGroupingSelection("inherit");
- }, []);
+ };
- const saveProjectGroupingPreference = useCallback(() => {
+ const saveProjectGroupingPreference = () => {
if (!projectGroupingTarget) {
return;
}
@@ -2268,20 +2145,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
sidebarProjectGroupingOverrides: nextOverrides,
});
closeProjectGroupingDialog();
- }, [
- closeProjectGroupingDialog,
- projectGroupingSelection,
- projectGroupingSettings.sidebarProjectGroupingOverrides,
- projectGroupingTarget,
- updateSettings,
- ]);
+ };
- const handleThreadContextMenu = useCallback(
+ // Every thread row receives this, so it keeps one identity while the thread
+ // list changes instead of re-rendering all of them.
+ const handleThreadContextMenu = useStableCallback(
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
const api = readLocalApi();
if (!api) return;
const threadKey = scopedThreadKey(threadRef);
- const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null;
+ const thread = sidebarThreadByKey.get(threadKey) ?? null;
if (!thread) return;
const threadProject = memberProjectByScopedKey.get(
scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
@@ -2398,21 +2271,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
}
},
- [
- appSettingsConfirmThreadDelete,
- copyPathToClipboard,
- copyThreadIdToClipboard,
- deleteThread,
- handleNewThread,
- isMobile,
- markThreadUnread,
- memberProjectByScopedKey,
- project.projectKey,
- project.workspaceRoot,
- router,
- setOpenMobile,
- startThreadRename,
- ],
);
return (
@@ -2698,7 +2556,7 @@ function LocalSecondaryStatus() {
// exist; the hook polls because the bridge has no change event.
const secondaries = useDesktopLocalBootstraps();
- const localEnvByUrl = useMemo(() => {
+ const localEnvByUrl = (() => {
const map = new Map<string, { phase: string; error: string | null }>();
for (const environment of environments) {
if (
@@ -2712,7 +2570,7 @@ function LocalSecondaryStatus() {
}
}
return map;
- }, [environments]);
+ })();
const connecting: string[] = [];
const failed: Array<{ label: string; error: string | null }> = [];
@@ -2777,19 +2635,16 @@ function ProjectSortMenu({
onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void;
}) {
- const handleThreadPreviewCountChange = useCallback(
- (nextValue: number | null) => {
- if (nextValue === null) {
- return;
- }
+ const handleThreadPreviewCountChange = (nextValue: number | null) => {
+ if (nextValue === null) {
+ return;
+ }
- const clampedValue = clampSidebarThreadPreviewCount(nextValue);
- if (clampedValue !== threadPreviewCount) {
- onThreadPreviewCountChange(clampedValue);
- }
- },
- [onThreadPreviewCountChange, threadPreviewCount],
- );
+ const clampedValue = clampSidebarThreadPreviewCount(nextValue);
+ if (clampedValue !== threadPreviewCount) {
+ onThreadPreviewCountChange(clampedValue);
+ }
+ };
return (
<Menu>
@@ -2944,6 +2799,7 @@ interface SidebarProjectsContentProps {
deleteThread: ReturnType<typeof useThreadActions>["deleteThread"];
markThreadUnread: ReturnType<typeof useThreadActions>["markThreadUnread"];
sortedProjects: readonly SidebarProjectSnapshot[];
+ sortedProjectKeys: string[];
expandedThreadListsByProject: ReadonlySet<string>;
activeRouteProjectKey: string | null;
routeThreadKey: string | null;
@@ -2987,6 +2843,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
deleteThread,
markThreadUnread,
sortedProjects,
+ sortedProjectKeys,
expandedThreadListsByProject,
activeRouteProjectKey,
routeThreadKey,
@@ -3004,24 +2861,15 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
projectsLength,
} = props;
- const handleProjectSortOrderChange = useCallback(
- (sortOrder: SidebarProjectSortOrder) => {
- updateSettings({ sidebarProjectSortOrder: sortOrder });
- },
- [updateSettings],
- );
- const handleThreadSortOrderChange = useCallback(
- (sortOrder: SidebarThreadSortOrder) => {
- updateSettings({ sidebarThreadSortOrder: sortOrder });
- },
- [updateSettings],
- );
- const handleThreadPreviewCountChange = useCallback(
- (count: SidebarThreadPreviewCount) => {
- updateSettings({ sidebarThreadPreviewCount: count });
- },
- [updateSettings],
- );
+ const handleProjectSortOrderChange = (sortOrder: SidebarProjectSortOrder) => {
+ updateSettings({ sidebarProjectSortOrder: sortOrder });
+ };
+ const handleThreadSortOrderChange = (sortOrder: SidebarThreadSortOrder) => {
+ updateSettings({ sidebarThreadSortOrder: sortOrder });
+ };
+ const handleThreadPreviewCountChange = (count: SidebarThreadPreviewCount) => {
+ updateSettings({ sidebarThreadPreviewCount: count });
+ };
return (
<SidebarContent
@@ -3100,16 +2948,13 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
<DndContext
sensors={projectDnDSensors}
collisionDetection={projectCollisionDetection}
- modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
+ modifiers={PROJECT_DND_MODIFIERS}
onDragStart={handleProjectDragStart}
onDragEnd={handleProjectDragEnd}
onDragCancel={handleProjectDragCancel}
>
<SidebarMenu>
- <SortableContext
- items={sortedProjects.map((project) => project.projectKey)}
- strategy={verticalListSortingStrategy}
- >
+ <SortableContext items={sortedProjectKeys} strategy={verticalListSortingStrategy}>
{sortedProjects.map((project) => (
<SortableProjectItem key={project.projectKey} projectId={project.projectKey}>
{(dragHandleProps) => (
@@ -3173,24 +3018,253 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
</SidebarMenu>
)}
- {projectsLength === 0 && (
- <div className="px-2 pt-4 text-center text-secondary-label text-xs">No projects yet</div>
- )}
- </SidebarGroup>
- </SidebarContent>
+ {projectsLength === 0 && (
+ <div className="px-2 pt-4 text-center text-secondary-label text-xs">No projects yet</div>
+ )}
+ </SidebarGroup>
+ </SidebarContent>
+ );
+});
+
+const PROJECT_POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } };
+const PROJECT_DND_MODIFIERS = [restrictToVerticalAxis, restrictToFirstScrollableAncestor];
+
+const projectCollisionDetection: CollisionDetection = (args) => {
+ const pointerCollisions = pointerWithin(args);
+ if (pointerCollisions.length > 0) {
+ return pointerCollisions;
+ }
+
+ return closestCorners(args);
+};
+
+function openAddProjectCommandPalette() {
+ openCommandPalette({ open: "add-project" });
+}
+
+// Project and thread derivations live in their own hooks so they reach
+// LegacySidebar frozen and cached on their real inputs; inline, its later hook
+// calls made the compiler recompute them, and the props of every row with them.
+function useLegacySidebarProjects() {
+ "use memo";
+ const projects = useProjects();
+ const projectOrder = useUiStateStore((store) => store.projectOrder);
+ const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
+ const { environments } = useEnvironments();
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const environmentLabelById = new Map(
+ environments.map((environment) => [environment.environmentId, environment.label] as const),
+ );
+ const desktopLocalEnvironmentIds = new Set(
+ environments
+ .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target))
+ .map((environment) => environment.environmentId),
+ );
+ const wslEnvironmentIds = new Set(
+ environments
+ .filter((environment) => isWslConnectionTarget(environment.entry.target))
+ .map((environment) => environment.environmentId),
+ );
+ const orderedProjects = orderItemsByPreferredIds({
+ items: projects,
+ preferredIds: projectOrder,
+ getId: getProjectOrderKey,
+ getPreferenceIds: (project) => [
+ getProjectOrderKey(project),
+ legacyProjectCwdPreferenceKey(project.workspaceRoot),
+ ],
+ });
+ const physicalToLogicalKey = buildPhysicalToLogicalProjectKeyMap({
+ projects: orderedProjects,
+ settings: projectGroupingSettings,
+ primaryEnvironmentId,
+ });
+ const projectPhysicalKeyByScopedRef = new Map(
+ orderedProjects.map((project) => [
+ scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
+ derivePhysicalProjectKey(project),
+ ]),
+ );
+ const sidebarProjects: SidebarProjectSnapshot[] = buildSidebarProjectSnapshots({
+ projects: orderedProjects,
+ settings: projectGroupingSettings,
+ primaryEnvironmentId,
+ resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
+ isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId),
+ isWslEnvironment: (environmentId) => wslEnvironmentIds.has(environmentId),
+ });
+ return {
+ projectsLength: projects.length,
+ orderedProjects,
+ physicalToLogicalKey,
+ projectPhysicalKeyByScopedRef,
+ sidebarProjects,
+ };
+}
+
+// Kept apart from useLegacySidebarProjects so a thread change re-sorts the
+// projects without rebuilding their snapshots, which every project row keys on.
+function useSortedLegacySidebarProjects(input: {
+ sidebarProjects: readonly SidebarProjectSnapshot[];
+ physicalToLogicalKey: ReadonlyMap<string, string>;
+ projectPhysicalKeyByScopedRef: ReadonlyMap<string, string>;
+ sidebarProjectSortOrder: SidebarProjectSortOrder;
+}) {
+ "use memo";
+ const {
+ sidebarProjects,
+ physicalToLogicalKey,
+ projectPhysicalKeyByScopedRef,
+ sidebarProjectSortOrder,
+ } = input;
+ const sidebarThreads = useThreadShells();
+ const sidebarProjectByKey = new Map(
+ sidebarProjects.map((project) => [project.projectKey, project] as const),
+ );
+ const sortableProjects = sidebarProjects.map((project) => ({
+ ...project,
+ id: project.projectKey,
+ }));
+ const sortableThreads = sidebarThreads
+ .filter((thread) => thread.archivedAt === null)
+ .map((thread) => {
+ const physicalKey =
+ projectPhysicalKeyByScopedRef.get(
+ scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
+ ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
+ return {
+ ...thread,
+ projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId,
+ };
+ });
+ const sortedProjects = sortProjectsForSidebar(
+ sortableProjects,
+ sortableThreads,
+ sidebarProjectSortOrder,
+ ).flatMap((project) => {
+ const resolvedProject = sidebarProjectByKey.get(project.id);
+ return resolvedProject ? [resolvedProject] : [];
+ });
+ return {
+ sortedProjects,
+ sortedProjectKeys: sortedProjects.map((project) => project.projectKey),
+ };
+}
+
+function useLegacySidebarThreads(input: {
+ sortedProjects: readonly SidebarProjectSnapshot[];
+ physicalToLogicalKey: ReadonlyMap<string, string>;
+ projectPhysicalKeyByScopedRef: ReadonlyMap<string, string>;
+ routeThreadKey: string | null;
+ sidebarThreadSortOrder: SidebarThreadSortOrder;
+ sidebarThreadPreviewCount: number;
+ expandedThreadListsByProject: ReadonlySet<string>;
+}) {
+ "use memo";
+ const {
+ sortedProjects,
+ physicalToLogicalKey,
+ projectPhysicalKeyByScopedRef,
+ routeThreadKey,
+ sidebarThreadSortOrder,
+ sidebarThreadPreviewCount,
+ expandedThreadListsByProject,
+ } = input;
+ const sidebarThreads = useThreadShells();
+ const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);
+ const sidebarThreadByKey = new Map(
+ sidebarThreads.map(
+ (thread) =>
+ [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
+ ),
);
-});
+ const logicalProjectKeyForThread = (thread: SidebarThreadSummary) => {
+ const physicalKey =
+ projectPhysicalKeyByScopedRef.get(
+ scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
+ ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
+ return physicalToLogicalKey.get(physicalKey) ?? physicalKey;
+ };
+ const activeRouteThread = routeThreadKey ? sidebarThreadByKey.get(routeThreadKey) : undefined;
+ const activeRouteProjectKey = activeRouteThread
+ ? logicalProjectKeyForThread(activeRouteThread)
+ : null;
+ const threadsByProjectKey = new Map<string, SidebarThreadSummary[]>();
+ for (const thread of sidebarThreads) {
+ const logicalKey = logicalProjectKeyForThread(thread);
+ const existing = threadsByProjectKey.get(logicalKey);
+ if (existing) {
+ existing.push(thread);
+ } else {
+ threadsByProjectKey.set(logicalKey, [thread]);
+ }
+ }
+ const visibleSidebarThreadKeys = sortedProjects.flatMap((project) => {
+ const projectThreads = sortThreads(
+ (threadsByProjectKey.get(project.projectKey) ?? []).filter(
+ (thread) => thread.archivedAt === null,
+ ),
+ sidebarThreadSortOrder,
+ );
+ const projectExpanded = resolveProjectExpanded(
+ projectExpandedById,
+ projectExpansionPreferenceKeys(project),
+ );
+ const activeThreadKey = routeThreadKey ?? undefined;
+ const pinnedCollapsedThread =
+ !projectExpanded && activeThreadKey
+ ? (projectThreads.find(
+ (thread) =>
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
+ ) ?? null)
+ : null;
+ const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null;
+ if (!shouldShowThreadPanel) {
+ return [];
+ }
+ const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey);
+ const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount;
+ const previewThreads =
+ isThreadListExpanded || !hasOverflowingThreads
+ ? projectThreads
+ : projectThreads.slice(0, sidebarThreadPreviewCount);
+ const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
+ return renderedThreads.map((thread) =>
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ );
+ });
+ const threadJumpCommandByKey = new Map<
+ string,
+ NonNullable<ReturnType<typeof threadJumpCommandForIndex>>
+ >();
+ for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) {
+ const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
+ if (!jumpCommand) {
+ break;
+ }
+ threadJumpCommandByKey.set(threadKey, jumpCommand);
+ }
+ const prewarmedSidebarThreadRefs = getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys).flatMap(
+ (threadKey) => {
+ const ref = parseScopedThreadKey(threadKey);
+ return ref ? [ref] : [];
+ },
+ );
+ return {
+ sidebarThreadByKey,
+ activeRouteProjectKey,
+ visibleSidebarThreadKeys,
+ threadJumpCommandByKey,
+ threadJumpThreadKeys: [...threadJumpCommandByKey.keys()],
+ prewarmedSidebarThreadRefs,
+ };
+}
export default function LegacySidebar() {
- const projects = useProjects();
- const sidebarThreads = useThreadShells();
- const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);
- const projectOrder = useUiStateStore((store) => store.projectOrder);
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
const navigate = useNavigate();
const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount);
const updateSettings = useUpdateClientSettings();
const handleNewThread = useNewThreadHandler();
@@ -3203,10 +3277,7 @@ export default function LegacySidebar() {
const routeDraftThread = useComposerDraftStore((store) =>
routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
);
- const routeThreadRef = useMemo(
- () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread),
- [routeDraftThread, routeTarget],
- );
+ const routeThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
const routeTerminalOpen = useTerminalUiStateStore((state) =>
routeThreadRef
@@ -3214,10 +3285,6 @@ export default function LegacySidebar() {
: false,
);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
- const openAddProjectCommandPalette = useCallback(
- () => openCommandPalette({ open: "add-project" }),
- [],
- );
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<string>
>(() => new Set());
@@ -3232,346 +3299,124 @@ export default function LegacySidebar() {
const platform = navigator.platform;
const shortcutModifiers = useShortcutModifierState();
const terminalFocused = useTerminalFocus();
- const { environments } = useEnvironments();
- const primaryEnvironmentId = usePrimaryEnvironmentId();
- const environmentLabelById = useMemo(
- () =>
- new Map(
- environments.map((environment) => [environment.environmentId, environment.label] as const),
- ),
- [environments],
- );
- const desktopLocalEnvironmentIds = useMemo(
- () =>
- new Set(
- environments
- .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target))
- .map((environment) => environment.environmentId),
- ),
- [environments],
- );
- const wslEnvironmentIds = useMemo(
- () =>
- new Set(
- environments
- .filter((environment) => isWslConnectionTarget(environment.entry.target))
- .map((environment) => environment.environmentId),
- ),
- [environments],
- );
- const orderedProjects = useMemo(() => {
- return orderItemsByPreferredIds({
- items: projects,
- preferredIds: projectOrder,
- getId: getProjectOrderKey,
- getPreferenceIds: (project) => [
- getProjectOrderKey(project),
- legacyProjectCwdPreferenceKey(project.workspaceRoot),
- ],
- });
- }, [projectOrder, projects]);
-
- const physicalToLogicalKey = useMemo(() => {
- return buildPhysicalToLogicalProjectKeyMap({
- projects: orderedProjects,
- settings: projectGroupingSettings,
- primaryEnvironmentId,
- });
- }, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
- const projectPhysicalKeyByScopedRef = useMemo(
- () =>
- new Map(
- orderedProjects.map((project) => [
- scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
- derivePhysicalProjectKey(project),
- ]),
- ),
- [orderedProjects],
- );
-
- const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(() => {
- return buildSidebarProjectSnapshots({
- projects: orderedProjects,
- settings: projectGroupingSettings,
- primaryEnvironmentId,
- resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
- isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId),
- isWslEnvironment: (environmentId) => wslEnvironmentIds.has(environmentId),
- });
- }, [
- environmentLabelById,
- desktopLocalEnvironmentIds,
- wslEnvironmentIds,
+ const {
+ projectsLength,
orderedProjects,
- projectGroupingSettings,
- primaryEnvironmentId,
- ]);
-
- const sidebarProjectByKey = useMemo(
- () => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)),
- [sidebarProjects],
- );
- const sidebarThreadByKey = useMemo(
- () =>
- new Map(
- sidebarThreads.map(
- (thread) =>
- [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
- ),
- ),
- [sidebarThreads],
- );
- const activeRouteProjectKey = useMemo(() => {
- if (!routeThreadKey) {
- return null;
- }
- const activeThread = sidebarThreadByKey.get(routeThreadKey);
- if (!activeThread) return null;
- const physicalKey =
- projectPhysicalKeyByScopedRef.get(
- scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)),
- ) ?? scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId));
- return physicalToLogicalKey.get(physicalKey) ?? physicalKey;
- }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey, projectPhysicalKeyByScopedRef]);
-
- const threadsByProjectKey = useMemo(() => {
- const next = new Map<string, SidebarThreadSummary[]>();
- for (const thread of sidebarThreads) {
- const physicalKey =
- projectPhysicalKeyByScopedRef.get(
- scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
- ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
- const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
- const existing = next.get(logicalKey);
- if (existing) {
- existing.push(thread);
- } else {
- next.set(logicalKey, [thread]);
- }
- }
- return next;
- }, [sidebarThreads, physicalToLogicalKey, projectPhysicalKeyByScopedRef]);
- const getCurrentSidebarShortcutContext = useCallback(
- () => ({
- terminalFocus: isTerminalFocused(),
- terminalOpen: routeTerminalOpen,
- modelPickerOpen: isModelPickerOpen(),
- }),
- [routeTerminalOpen],
- );
- const newThreadShortcutLabelOptions = useMemo(
- () => ({
- platform,
- context: {
- terminalFocus: false,
- terminalOpen: false,
- },
- }),
- [platform],
- );
+ physicalToLogicalKey,
+ projectPhysicalKeyByScopedRef,
+ sidebarProjects,
+ } = useLegacySidebarProjects();
+ const { sortedProjects, sortedProjectKeys } = useSortedLegacySidebarProjects({
+ sidebarProjects,
+ physicalToLogicalKey,
+ projectPhysicalKeyByScopedRef,
+ sidebarProjectSortOrder,
+ });
+ const {
+ sidebarThreadByKey,
+ activeRouteProjectKey,
+ visibleSidebarThreadKeys,
+ threadJumpCommandByKey,
+ threadJumpThreadKeys,
+ prewarmedSidebarThreadRefs,
+ } = useLegacySidebarThreads({
+ sortedProjects,
+ physicalToLogicalKey,
+ projectPhysicalKeyByScopedRef,
+ routeThreadKey,
+ sidebarThreadSortOrder,
+ sidebarThreadPreviewCount,
+ expandedThreadListsByProject,
+ });
+ const newThreadShortcutLabelOptions = {
+ platform,
+ context: {
+ terminalFocus: false,
+ terminalOpen: false,
+ },
+ };
const newThreadShortcutLabel =
shortcutLabelForCommand(keybindings, "chat.newLocal", newThreadShortcutLabelOptions) ??
shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions);
- const navigateToThread = useCallback(
- (threadRef: ScopedThreadRef) => {
- if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
- clearSelection();
- }
- setSelectionAnchor(scopedThreadKey(threadRef));
- if (isMobile) {
- setOpenMobile(false);
- }
- void navigate({
- to: "/$environmentId/$threadId",
- params: buildThreadRouteParams(threadRef),
- });
- },
- [clearSelection, isMobile, navigate, setOpenMobile, setSelectionAnchor],
- );
-
- const projectDnDSensors = useSensors(
- useSensor(PointerSensor, {
- activationConstraint: { distance: 6 },
- }),
- );
- const projectCollisionDetection = useCallback<CollisionDetection>((args) => {
- const pointerCollisions = pointerWithin(args);
- if (pointerCollisions.length > 0) {
- return pointerCollisions;
+ const navigateToThread = (threadRef: ScopedThreadRef) => {
+ if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
+ clearSelection();
}
+ setSelectionAnchor(scopedThreadKey(threadRef));
+ if (isMobile) {
+ setOpenMobile(false);
+ }
+ void navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(threadRef),
+ });
+ };
- return closestCorners(args);
- }, []);
+ const projectDnDSensors = useSensors(useSensor(PointerSensor, PROJECT_POINTER_SENSOR_OPTIONS));
- const handleProjectDragEnd = useCallback(
- (event: DragEndEvent) => {
- if (sidebarProjectSortOrder !== "manual") {
- dragInProgressRef.current = false;
- return;
- }
+ // DndContext keeps these across a drag, so they keep one identity and read the
+ // latest projects when called.
+ const handleProjectDragEnd = useStableCallback((event: DragEndEvent) => {
+ if (sidebarProjectSortOrder !== "manual") {
dragInProgressRef.current = false;
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- const activeProject = sidebarProjects.find((project) => project.projectKey === active.id);
- const overProject = sidebarProjects.find((project) => project.projectKey === over.id);
- if (!activeProject || !overProject) return;
- const activeMemberKeys = activeProject.memberProjects.map(
- (member) => member.physicalProjectKey,
- );
- const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey);
- reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys);
- },
- [orderedProjects, sidebarProjectSortOrder, reorderProjects, sidebarProjects],
- );
+ return;
+ }
+ dragInProgressRef.current = false;
+ const { active, over } = event;
+ if (!over || active.id === over.id) return;
+ const activeProject = sidebarProjects.find((project) => project.projectKey === active.id);
+ const overProject = sidebarProjects.find((project) => project.projectKey === over.id);
+ if (!activeProject || !overProject) return;
+ const activeMemberKeys = activeProject.memberProjects.map(
+ (member) => member.physicalProjectKey,
+ );
+ const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey);
+ reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys);
+ });
- const handleProjectDragStart = useCallback(
- (_event: DragStartEvent) => {
- if (sidebarProjectSortOrder !== "manual") {
- return;
- }
- dragInProgressRef.current = true;
- suppressProjectClickAfterDragRef.current = true;
- },
- [sidebarProjectSortOrder],
- );
+ const handleProjectDragStart = useStableCallback((_event: DragStartEvent) => {
+ if (sidebarProjectSortOrder !== "manual") {
+ return;
+ }
+ dragInProgressRef.current = true;
+ suppressProjectClickAfterDragRef.current = true;
+ });
- const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => {
+ const handleProjectDragCancel = (_event: DragCancelEvent) => {
dragInProgressRef.current = false;
- }, []);
+ };
const animatedProjectListsRef = useRef(new WeakSet<HTMLElement>());
- const attachProjectListAutoAnimateRef = useCallback((node: HTMLElement | null) => {
+ const attachProjectListAutoAnimateRef = (node: HTMLElement | null) => {
if (!node || animatedProjectListsRef.current.has(node)) {
return;
}
autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);
animatedProjectListsRef.current.add(node);
- }, []);
+ };
const animatedThreadListsRef = useRef(new WeakSet<HTMLElement>());
- const attachThreadListAutoAnimateRef = useCallback((node: HTMLElement | null) => {
+ const attachThreadListAutoAnimateRef = (node: HTMLElement | null) => {
if (!node || animatedThreadListsRef.current.has(node)) {
return;
}
autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);
animatedThreadListsRef.current.add(node);
- }, []);
+ };
- const visibleThreads = useMemo(
- () => sidebarThreads.filter((thread) => thread.archivedAt === null),
- [sidebarThreads],
- );
- const sortedProjects = useMemo(() => {
- const sortableProjects = sidebarProjects.map((project) => ({
- ...project,
- id: project.projectKey,
- }));
- const sortableThreads = visibleThreads.map((thread) => {
- const physicalKey =
- projectPhysicalKeyByScopedRef.get(
- scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
- ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
- return {
- ...thread,
- projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId,
- };
- });
- return sortProjectsForSidebar(
- sortableProjects,
- sortableThreads,
- sidebarProjectSortOrder,
- ).flatMap((project) => {
- const resolvedProject = sidebarProjectByKey.get(project.id);
- return resolvedProject ? [resolvedProject] : [];
- });
- }, [
- sidebarProjectSortOrder,
- physicalToLogicalKey,
- projectPhysicalKeyByScopedRef,
- sidebarProjectByKey,
- sidebarProjects,
- visibleThreads,
- ]);
const isManualProjectSorting = sidebarProjectSortOrder === "manual";
- const visibleSidebarThreadKeys = useMemo(
- () =>
- sortedProjects.flatMap((project) => {
- const projectThreads = sortThreads(
- (threadsByProjectKey.get(project.projectKey) ?? []).filter(
- (thread) => thread.archivedAt === null,
- ),
- sidebarThreadSortOrder,
- );
- const projectExpanded = resolveProjectExpanded(
- projectExpandedById,
- projectExpansionPreferenceKeys(project),
- );
- const activeThreadKey = routeThreadKey ?? undefined;
- const pinnedCollapsedThread =
- !projectExpanded && activeThreadKey
- ? (projectThreads.find(
- (thread) =>
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) ===
- activeThreadKey,
- ) ?? null)
- : null;
- const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null;
- if (!shouldShowThreadPanel) {
- return [];
- }
- const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey);
- const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount;
- const previewThreads =
- isThreadListExpanded || !hasOverflowingThreads
- ? projectThreads
- : projectThreads.slice(0, sidebarThreadPreviewCount);
- const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
- return renderedThreads.map((thread) =>
- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- );
- }),
- [
- sidebarThreadSortOrder,
- sidebarThreadPreviewCount,
- expandedThreadListsByProject,
- projectExpandedById,
- routeThreadKey,
- sortedProjects,
- threadsByProjectKey,
- ],
- );
- const threadJumpCommandByKey = useMemo(() => {
- const mapping = new Map<string, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
- for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) {
- const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
- if (!jumpCommand) {
- return mapping;
- }
- mapping.set(threadKey, jumpCommand);
- }
-
- return mapping;
- }, [visibleSidebarThreadKeys]);
- const threadJumpThreadKeys = useMemo(
- () => [...threadJumpCommandByKey.keys()],
- [threadJumpCommandByKey],
- );
const sidebarShortcutContext = {
terminalFocus: terminalFocused,
terminalOpen: routeTerminalOpen,
modelPickerOpen: isModelPickerOpen(),
};
- const threadJumpLabelByKey = useMemo(
- () =>
- buildThreadJumpLabelMap({
- keybindings,
- platform,
- terminalOpen: sidebarShortcutContext.terminalOpen,
- threadJumpCommandByKey,
- }),
- [keybindings, platform, sidebarShortcutContext.terminalOpen, threadJumpCommandByKey],
- );
+ const threadJumpLabelByKey = useThreadJumpLabelMap({
+ keybindings,
+ platform,
+ terminalOpen: routeTerminalOpen,
+ threadJumpCommandByKey,
+ });
const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers(
shortcutModifiers,
keybindings,
@@ -3584,62 +3429,33 @@ export default function LegacySidebar() {
? threadJumpLabelByKey
: EMPTY_THREAD_JUMP_LABELS;
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
- const prewarmedSidebarThreadKeys = useMemo(
- () => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
- [visibleSidebarThreadKeys],
- );
- const prewarmedSidebarThreadRefs = useMemo(
- () =>
- prewarmedSidebarThreadKeys.flatMap((threadKey) => {
- const ref = parseScopedThreadKey(threadKey);
- return ref ? [ref] : [];
- }),
- [prewarmedSidebarThreadKeys],
- );
useEffect(() => {
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
}, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]);
- useEffect(() => {
- const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
- const shortcutContext = getCurrentSidebarShortcutContext();
+ const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => {
+ const shortcutContext = {
+ terminalFocus: isTerminalFocused(),
+ terminalOpen: routeTerminalOpen,
+ modelPickerOpen: isModelPickerOpen(),
+ };
- if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) {
- return;
- }
+ if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) {
+ return;
+ }
- const command = resolveShortcutCommand(event, keybindings, {
- platform,
- context: shortcutContext,
+ const command = resolveShortcutCommand(event, keybindings, {
+ platform,
+ context: shortcutContext,
+ });
+ const traversalDirection = threadTraversalDirectionFromCommand(command);
+ if (traversalDirection !== null) {
+ const targetThreadKey = resolveAdjacentThreadId({
+ threadIds: orderedSidebarThreadKeys,
+ currentThreadId: routeThreadKey,
+ direction: traversalDirection,
});
- const traversalDirection = threadTraversalDirectionFromCommand(command);
- if (traversalDirection !== null) {
- const targetThreadKey = resolveAdjacentThreadId({
- threadIds: orderedSidebarThreadKeys,
- currentThreadId: routeThreadKey,
- direction: traversalDirection,
- });
- if (!targetThreadKey) {
- return;
- }
- const targetThread = sidebarThreadByKey.get(targetThreadKey);
- if (!targetThread) {
- return;
- }
-
- event.preventDefault();
- event.stopPropagation();
- navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
- return;
- }
-
- const jumpIndex = threadJumpIndexFromCommand(command ?? "");
- if (jumpIndex === null) {
- return;
- }
-
- const targetThreadKey = threadJumpThreadKeys[jumpIndex];
if (!targetThreadKey) {
return;
}
@@ -3651,23 +3467,34 @@ export default function LegacySidebar() {
event.preventDefault();
event.stopPropagation();
navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
- };
+ return;
+ }
+
+ const jumpIndex = threadJumpIndexFromCommand(command ?? "");
+ if (jumpIndex === null) {
+ return;
+ }
- window.addEventListener("keydown", onWindowKeyDown);
+ const targetThreadKey = threadJumpThreadKeys[jumpIndex];
+ if (!targetThreadKey) {
+ return;
+ }
+ const targetThread = sidebarThreadByKey.get(targetThreadKey);
+ if (!targetThread) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
+ });
+ useEffect(() => {
+ const handleWindowKeyDown = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event);
+ window.addEventListener("keydown", handleWindowKeyDown);
return () => {
- window.removeEventListener("keydown", onWindowKeyDown);
+ window.removeEventListener("keydown", handleWindowKeyDown);
};
- }, [
- getCurrentSidebarShortcutContext,
- keybindings,
- navigateToThread,
- orderedSidebarThreadKeys,
- platform,
- routeThreadKey,
- sidebarThreadByKey,
- threadJumpThreadKeys,
- ]);
+ }, []);
useEffect(() => {
const onMouseDown = (event: globalThis.MouseEvent) => {
@@ -3696,7 +3523,7 @@ export default function LegacySidebar() {
const commandPaletteShortcutLabel = isMobile
? null
: shortcutLabelForCommand(keybindings, "commandPalette.toggle", newThreadShortcutLabelOptions);
- const handleDesktopUpdateButtonClick = useCallback(async () => {
+ const handleDesktopUpdateButtonClick = async () => {
const bridge = window.desktopBridge;
if (!bridge || !desktopUpdateState) return;
if (
@@ -3786,30 +3613,25 @@ export default function LegacySidebar() {
})
.finally(() => setDesktopUpdateActionPending(false));
}
- }, [
- desktopUpdateActionPending,
- desktopUpdateButtonAction,
- desktopUpdateButtonDisabled,
- desktopUpdateState,
- ]);
+ };
- const expandThreadListForProject = useCallback((projectKey: string) => {
+ const expandThreadListForProject = (projectKey: string) => {
setExpandedThreadListsByProject((current) => {
if (current.has(projectKey)) return current;
const next = new Set(current);
next.add(projectKey);
return next;
});
- }, []);
+ };
- const collapseThreadListForProject = useCallback((projectKey: string) => {
+ const collapseThreadListForProject = (projectKey: string) => {
setExpandedThreadListsByProject((current) => {
if (!current.has(projectKey)) return current;
const next = new Set(current);
next.delete(projectKey);
return next;
});
- }, []);
+ };
return (
<>
@@ -3841,6 +3663,7 @@ export default function LegacySidebar() {
deleteThread={deleteThread}
markThreadUnread={markThreadUnread}
sortedProjects={sortedProjects}
+ sortedProjectKeys={sortedProjectKeys}
expandedThreadListsByProject={expandedThreadListsByProject}
activeRouteProjectKey={activeRouteProjectKey}
routeThreadKey={routeThreadKey}
@@ -3855,7 +3678,7 @@ export default function LegacySidebar() {
suppressProjectClickAfterDragRef={suppressProjectClickAfterDragRef}
suppressProjectClickForContextMenuRef={suppressProjectClickForContextMenuRef}
attachProjectListAutoAnimateRef={attachProjectListAutoAnimateRef}
- projectsLength={projects.length}
+ projectsLength={projectsLength}
/>
<SidebarChromeFooter />
</>