Compare commits

...
Author SHA1 Message Date
Cursor Agent e09809f495 Fix NaN from NEGATIVE_INFINITY subtraction in sortThreadsForSidebar
When two threads both yield Number.NEGATIVE_INFINITY timestamps, the
subtraction (-Infinity) - (-Infinity) produces NaN, which bypasses the
ID-based tiebreaker and causes unpredictable sort order.

Use explicit comparison (=== / >) instead of subtraction, matching the
pattern already used in sortProjectsForSidebar.
2026-03-24 19:10:49 +00:00
Julius Marminge 1f96d6da92 Handle missing sort timestamps in sidebar ordering
- Treat missing or invalid timestamps as absent instead of zero
- Fall back to name and id ordering when projects have no sortable dates
- Add coverage for timestamp-less project sorting
2026-03-24 11:59:50 -07:00
Julius Marminge 04a4545bbb Show active thread in collapsed sidebar previews
- Keep the current thread visible in folded project thread lists
- Extract shared visible-thread selection logic and cover it with tests
2026-03-24 11:57:22 -07:00
3 changed files with 319 additions and 177 deletions

No files matched your search

@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
getVisibleThreadsForProject,
getProjectSortTimestamp,
hasUnseenCompletion,
resolveProjectStatusIndicator,
@@ -292,6 +293,55 @@ describe("resolveProjectStatusIndicator", () => {
});
});
describe("getVisibleThreadsForProject", () => {
it("includes the active thread even when it falls below the folded preview", () => {
const threads = Array.from({ length: 8 }, (_, index) =>
makeThread({
id: ThreadId.makeUnsafe(`thread-${index + 1}`),
title: `Thread ${index + 1}`,
}),
);
const result = getVisibleThreadsForProject({
threads,
activeThreadId: ThreadId.makeUnsafe("thread-8"),
isThreadListExpanded: false,
previewLimit: 6,
});
expect(result.hasHiddenThreads).toBe(true);
expect(result.visibleThreads.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
ThreadId.makeUnsafe("thread-4"),
ThreadId.makeUnsafe("thread-5"),
ThreadId.makeUnsafe("thread-6"),
ThreadId.makeUnsafe("thread-8"),
]);
});
it("returns all threads when the list is expanded", () => {
const threads = Array.from({ length: 8 }, (_, index) =>
makeThread({
id: ThreadId.makeUnsafe(`thread-${index + 1}`),
}),
);
const result = getVisibleThreadsForProject({
threads,
activeThreadId: ThreadId.makeUnsafe("thread-8"),
isThreadListExpanded: true,
previewLimit: 6,
});
expect(result.hasHiddenThreads).toBe(true);
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
threads.map((thread) => thread.id),
);
});
});
function makeProject(overrides: Partial<Project> = {}): Project {
return {
id: ProjectId.makeUnsafe("project-1"),
@@ -502,6 +552,32 @@ describe("sortProjectsForSidebar", () => {
]);
});
it("falls back to name and id ordering when projects have no sortable timestamps", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Beta",
createdAt: undefined,
updatedAt: undefined,
}),
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Alpha",
createdAt: undefined,
updatedAt: undefined,
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("preserves manual project ordering", () => {
const projects = [
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),
+73 -17
View File
@@ -187,36 +187,81 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
function toSortableTimestamp(iso: string | undefined): number {
if (!iso) return Number.NEGATIVE_INFINITY;
export function getVisibleThreadsForProject(input: {
threads: readonly Thread[];
activeThreadId: Thread["id"] | undefined;
isThreadListExpanded: boolean;
previewLimit: number;
}): {
hasHiddenThreads: boolean;
visibleThreads: Thread[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
if (!hasHiddenThreads || isThreadListExpanded) {
return {
hasHiddenThreads,
visibleThreads: [...threads],
};
}
const previewThreads = threads.slice(0, previewLimit);
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
return {
hasHiddenThreads: true,
visibleThreads: previewThreads,
};
}
const activeThread = threads.find((thread) => thread.id === activeThreadId);
if (!activeThread) {
return {
hasHiddenThreads: true,
visibleThreads: previewThreads,
};
}
const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
return {
hasHiddenThreads: true,
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
};
}
function toSortableTimestamp(iso: string | undefined): number | null {
if (!iso) return null;
const ms = Date.parse(iso);
return Number.isFinite(ms) ? ms : Number.NEGATIVE_INFINITY;
return Number.isFinite(ms) ? ms : null;
}
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
let latestUserMessageTimestamp = Number.NEGATIVE_INFINITY;
let latestUserMessageTimestamp: number | null = null;
for (const message of thread.messages) {
if (message.role !== "user") continue;
latestUserMessageTimestamp = Math.max(
latestUserMessageTimestamp,
toSortableTimestamp(message.createdAt),
);
const messageTimestamp = toSortableTimestamp(message.createdAt);
if (messageTimestamp === null) continue;
latestUserMessageTimestamp =
latestUserMessageTimestamp === null
? messageTimestamp
: Math.max(latestUserMessageTimestamp, messageTimestamp);
}
if (latestUserMessageTimestamp !== Number.NEGATIVE_INFINITY) {
if (latestUserMessageTimestamp !== null) {
return latestUserMessageTimestamp;
}
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt);
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function getThreadSortTimestamp(
function getThreadSortTimestamp(
thread: SidebarThreadSortInput,
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
): number {
if (sortOrder === "created_at") {
return toSortableTimestamp(thread.createdAt);
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
}
return getLatestUserMessageTimestamp(thread);
}
@@ -225,8 +270,10 @@ export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
const byTimestamp =
getThreadSortTimestamp(right, sortOrder) - getThreadSortTimestamp(left, sortOrder);
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
if (byTimestamp !== 0) return byTimestamp;
return right.id.localeCompare(left.id);
});
@@ -245,9 +292,9 @@ export function getProjectSortTimestamp(
}
if (sortOrder === "created_at") {
return toSortableTimestamp(project.createdAt);
return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
return toSortableTimestamp(project.updatedAt ?? project.createdAt);
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
@@ -267,9 +314,18 @@ export function sortProjectsForSidebar<TProject extends SidebarProject, TThread
}
return [...projects].toSorted((left, right) => {
const rightTimestamp = getProjectSortTimestamp(
right,
threadsByProjectId.get(right.id) ?? [],
sortOrder,
);
const leftTimestamp = getProjectSortTimestamp(
left,
threadsByProjectId.get(left.id) ?? [],
sortOrder,
);
const byTimestamp =
getProjectSortTimestamp(right, threadsByProjectId.get(right.id) ?? [], sortOrder) -
getProjectSortTimestamp(left, threadsByProjectId.get(left.id) ?? [], sortOrder);
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
if (byTimestamp !== 0) return byTimestamp;
return left.name.localeCompare(right.name) || left.id.localeCompare(right.id);
});
+170 -160
View File
@@ -91,6 +91,7 @@ import { useThreadSelectionStore } from "../threadSelectionStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
import {
getVisibleThreadsForProject,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
@@ -1110,16 +1111,175 @@ export default function Sidebar() {
}),
),
);
const activeThreadId = routeThreadId ?? undefined;
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
const visibleThreads =
hasHiddenThreads && !isThreadListExpanded
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
: projectThreads;
const pinnedCollapsedThread =
!project.expanded && activeThreadId
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
const { hasHiddenThreads, visibleThreads } = getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleThreads;
const renderThreadRow = (thread: (typeof projectThreads)[number]) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
});
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
);
return (
<SidebarMenuSubItem key={thread.id} className="w-full" data-thread-item>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={resolveThreadRowClassName({
isActive,
isSelected,
})}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
if (selectedThreadIds.size > 0) {
clearSelection();
}
setSelectionAnchor(thread.id);
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onContextMenu={(event) => {
event.preventDefault();
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
});
} else {
if (selectedThreadIds.size > 0) {
clearSelection();
}
void handleThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
}
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(thread.id, renamingTitle, thread.title);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(thread.id, renamingTitle, thread.title);
}
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTime(thread.updatedAt ?? thread.createdAt)}
</span>
</div>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
};
return (
<Collapsible className="group/collapsible" open={project.expanded}>
<Collapsible className="group/collapsible" open={shouldShowThreadPanel}>
<div className="group/project-header relative">
<SidebarMenuButton
ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}
@@ -1200,164 +1360,14 @@ export default function Sidebar() {
</Tooltip>
</div>
<CollapsibleContent keepMounted>
<CollapsibleContent>
<SidebarMenuSub
ref={attachThreadListAutoAnimateRef}
className="mx-1 my-0 w-full translate-x-0 gap-0.5 px-1.5 py-0"
>
{visibleThreads.map((thread) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
});
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
);
{renderedThreads.map((thread) => renderThreadRow(thread))}
return (
<SidebarMenuSubItem key={thread.id} className="w-full" data-thread-item>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={resolveThreadRowClassName({
isActive,
isSelected,
})}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
if (selectedThreadIds.size > 0) {
clearSelection();
}
setSelectionAnchor(thread.id);
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onContextMenu={(event) => {
event.preventDefault();
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
});
} else {
if (selectedThreadIds.size > 0) {
clearSelection();
}
void handleThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
}
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(thread.id, renamingTitle, thread.title);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(thread.id, renamingTitle, thread.title);
}
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTime(thread.updatedAt ?? thread.createdAt)}
</span>
</div>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
{hasHiddenThreads && !isThreadListExpanded && (
{project.expanded && hasHiddenThreads && !isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
@@ -1372,7 +1382,7 @@ export default function Sidebar() {
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
{hasHiddenThreads && isThreadListExpanded && (
{project.expanded && hasHiddenThreads && isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}