diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 574e33d4da..8db87451bf 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -19,6 +19,7 @@ import { resolveThreadStatusPill, shouldClearThreadSelectionOnMouseDown, sortProjectsForSidebar, + threadNeedsAttention, THREAD_JUMP_HINT_SHOW_DELAY_MS, } from "./Sidebar.logic"; import { @@ -742,46 +743,67 @@ 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.make(`thread-${index + 1}`), - title: `Thread ${index + 1}`, - }), - ); + // Fixture threads are stamped 2026-03-09T10:00Z; this "now" puts them all + // far outside the recency window unless a test overrides their timestamps. + const NOW_MS = Date.parse("2026-03-12T10:00:00.000Z"); - const result = getVisibleThreadsForProject({ + type FoldThread = { + id: string; + createdAt: string; + updatedAt: string; + latestUserMessageAt?: string | null; + }; + + const makeFoldThread = (id: string, overrides: Partial = {}): FoldThread => ({ + id, + createdAt: "2026-03-09T10:00:00.000Z", + updatedAt: "2026-03-09T10:00:00.000Z", + ...overrides, + }); + + const foldThreads = ( + threads: readonly FoldThread[], + overrides: Partial<{ + activeThreadKey: string; + isThreadListExpanded: boolean; + previewLimit: number; + needsAttention: (thread: FoldThread) => boolean; + }> = {}, + ) => + getVisibleThreadsForProject({ threads, - activeThreadId: ThreadId.make("thread-8"), - isThreadListExpanded: false, - previewLimit: 6, + getThreadKey: (thread) => thread.id, + activeThreadKey: overrides.activeThreadKey, + isThreadListExpanded: overrides.isThreadListExpanded ?? false, + previewLimit: overrides.previewLimit ?? 6, + nowMs: NOW_MS, + needsAttention: overrides.needsAttention ?? (() => false), }); + it("includes the active thread even when it falls below the folded preview", () => { + const threads = Array.from({ length: 8 }, (_, index) => makeFoldThread(`thread-${index + 1}`)); + + const result = foldThreads(threads, { activeThreadKey: "thread-8" }); + expect(result.hasHiddenThreads).toBe(true); expect(result.visibleThreads.map((thread) => thread.id)).toEqual([ - ThreadId.make("thread-1"), - ThreadId.make("thread-2"), - ThreadId.make("thread-3"), - ThreadId.make("thread-4"), - ThreadId.make("thread-5"), - ThreadId.make("thread-6"), - ThreadId.make("thread-8"), + "thread-1", + "thread-2", + "thread-3", + "thread-4", + "thread-5", + "thread-6", + "thread-8", ]); - expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ThreadId.make("thread-7")]); + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual(["thread-7"]); }); it("returns all threads when the list is expanded", () => { - const threads = Array.from({ length: 8 }, (_, index) => - makeThread({ - id: ThreadId.make(`thread-${index + 1}`), - }), - ); + const threads = Array.from({ length: 8 }, (_, index) => makeFoldThread(`thread-${index + 1}`)); - const result = getVisibleThreadsForProject({ - threads, - activeThreadId: ThreadId.make("thread-8"), + const result = foldThreads(threads, { + activeThreadKey: "thread-8", isThreadListExpanded: true, - previewLimit: 6, }); expect(result.hasHiddenThreads).toBe(true); @@ -790,6 +812,108 @@ describe("getVisibleThreadsForProject", () => { ); expect(result.hiddenThreads).toEqual([]); }); + + it("keeps threads that need attention visible below the folded preview", () => { + const threads = Array.from({ length: 9 }, (_, index) => makeFoldThread(`thread-${index + 1}`)); + + const result = foldThreads(threads, { + needsAttention: (thread) => thread.id === "thread-9", + }); + + expect(result.visibleThreads.map((thread) => thread.id)).toContain("thread-9"); + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual(["thread-7", "thread-8"]); + }); + + it("keeps threads with recent activity visible below the folded preview", () => { + const threads = [ + ...Array.from({ length: 7 }, (_, index) => makeFoldThread(`thread-${index + 1}`)), + makeFoldThread("thread-recent", { + updatedAt: new Date(NOW_MS - 10 * 60 * 1000).toISOString(), + }), + ]; + + const result = foldThreads(threads); + + expect(result.visibleThreads.map((thread) => thread.id)).toContain("thread-recent"); + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual(["thread-7"]); + }); + + it("treats a recent agent completion as activity even when the prompt is old", () => { + // `updated_at` sorting prefers the latest user message, so recency must + // also consider `updatedAt` for threads whose agent finished after an + // old prompt. + const threads = [ + ...Array.from({ length: 6 }, (_, index) => makeFoldThread(`thread-${index + 1}`)), + makeFoldThread("thread-finished", { + latestUserMessageAt: "2026-03-09T10:00:00.000Z", + updatedAt: new Date(NOW_MS - 5 * 60 * 1000).toISOString(), + }), + ]; + + const result = foldThreads(threads); + + expect(result.visibleThreads.map((thread) => thread.id)).toContain("thread-finished"); + }); + + it("caps recency-driven visibility but never drops attention threads", () => { + // 20 recent threads + 1 old attention thread; the cap (15) trims the + // recency overflow while the attention thread stays visible. + const recentThreads = Array.from({ length: 20 }, (_, index) => + makeFoldThread(`recent-${String(index + 1).padStart(2, "0")}`, { + latestUserMessageAt: new Date(NOW_MS - (index + 1) * 60 * 1000).toISOString(), + }), + ); + const threads = [...recentThreads, makeFoldThread("thread-attention")]; + + const result = foldThreads(threads, { + needsAttention: (thread) => thread.id === "thread-attention", + }); + + expect(result.hasHiddenThreads).toBe(true); + expect(result.visibleThreads.length).toBe(15); + expect(result.visibleThreads.map((thread) => thread.id)).toContain("thread-attention"); + // The most recent candidates win the capped slots, so the trailing + // recent threads fold. + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ + "recent-15", + "recent-16", + "recent-17", + "recent-18", + "recent-19", + "recent-20", + ]); + }); + + it("reports no hidden threads when every thread qualifies", () => { + const threads = Array.from({ length: 8 }, (_, index) => + makeFoldThread(`thread-${index + 1}`, { + updatedAt: new Date(NOW_MS - 60 * 1000).toISOString(), + }), + ); + + const result = foldThreads(threads); + + expect(result.hasHiddenThreads).toBe(false); + expect(result.visibleThreads.map((thread) => thread.id)).toEqual( + threads.map((thread) => thread.id), + ); + expect(result.hiddenThreads).toEqual([]); + }); +}); + +describe("threadNeedsAttention", () => { + it("is true when the thread has any status pill and false otherwise", () => { + const base = { + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, + interactionMode: DEFAULT_INTERACTION_MODE, + latestTurn: null, + session: null, + }; + expect(threadNeedsAttention({ ...base, hasPendingApprovals: true })).toBe(true); + expect(threadNeedsAttention(base)).toBe(false); + }); }); function makeProject(overrides: Partial = {}): Project { diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 4e7614ed55..b9b66fe88c 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,4 +1,5 @@ import * as React from "react"; +import { MAX_SIDEBAR_THREAD_PREVIEW_COUNT } from "@t3tools/contracts/settings"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; import { getThreadSortTimestamp, @@ -442,19 +443,70 @@ export function resolveProjectStatusIndicator( return highestPriorityStatus; } -export function getVisibleThreadsForProject>(input: { +export const SIDEBAR_RECENT_THREAD_WINDOW_MS = 2 * 60 * 60 * 1000; + +export function threadNeedsAttention(thread: ThreadStatusInput): boolean { + return resolveThreadStatusPill({ thread }) !== null; +} + +// `getThreadSortTimestamp("updated_at")` prefers the latest user message, so a +// thread whose agent finished recently but whose prompt is hours old would not +// count as recent activity without also considering `updatedAt`. +function getThreadActivityTimestamp(thread: ThreadSortInput): number { + return Math.max( + getThreadSortTimestamp(thread, "updated_at"), + toSortableTimestamp(thread.updatedAt) ?? Number.NEGATIVE_INFINITY, + ); +} + +// The preview limit is a floor, not a ceiling: beyond the first N threads, +// folding keeps visible the active thread, any thread that still needs the +// user's attention (it has a status pill: pending approval/input, running, +// plan ready, or unseen completion), and threads with activity inside the +// recency window. Recent-but-quiet threads are capped so a busy afternoon of +// launches doesn't unfold the whole list; attention and active threads are +// never dropped by the cap. +export function getVisibleThreadsForProject(input: { threads: readonly T[]; - activeThreadId: T["id"] | undefined; + getThreadKey: (thread: T) => string; + activeThreadKey: string | undefined; isThreadListExpanded: boolean; previewLimit: number; + nowMs: number; + needsAttention: (thread: T) => boolean; }): { hasHiddenThreads: boolean; visibleThreads: T[]; hiddenThreads: T[]; } { - const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input; - const hasHiddenThreads = threads.length > previewLimit; + const { activeThreadKey, getThreadKey, isThreadListExpanded, previewLimit, threads } = input; + const visibleThreadKeys = new Set(); + for (const thread of threads.slice(0, previewLimit)) { + visibleThreadKeys.add(getThreadKey(thread)); + } + for (const thread of threads) { + const threadKey = getThreadKey(thread); + if (threadKey === activeThreadKey || input.needsAttention(thread)) { + visibleThreadKeys.add(threadKey); + } + } + + const maxAutoShownThreads = Math.max(previewLimit, MAX_SIDEBAR_THREAD_PREVIEW_COUNT); + const recencyCutoffMs = input.nowMs - SIDEBAR_RECENT_THREAD_WINDOW_MS; + const recentHiddenThreads = threads + .filter( + (thread) => + !visibleThreadKeys.has(getThreadKey(thread)) && + getThreadActivityTimestamp(thread) >= recencyCutoffMs, + ) + .sort((a, b) => getThreadActivityTimestamp(b) - getThreadActivityTimestamp(a)); + for (const thread of recentHiddenThreads) { + if (visibleThreadKeys.size >= maxAutoShownThreads) break; + visibleThreadKeys.add(getThreadKey(thread)); + } + + const hasHiddenThreads = visibleThreadKeys.size < threads.length; if (!hasHiddenThreads || isThreadListExpanded) { return { hasHiddenThreads, @@ -463,30 +515,10 @@ export function getVisibleThreadsForProject>(input: }; } - const previewThreads = threads.slice(0, previewLimit); - if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) { - return { - hasHiddenThreads: true, - hiddenThreads: threads.slice(previewLimit), - visibleThreads: previewThreads, - }; - } - - const activeThread = threads.find((thread) => thread.id === activeThreadId); - if (!activeThread) { - return { - hasHiddenThreads: true, - hiddenThreads: threads.slice(previewLimit), - visibleThreads: previewThreads, - }; - } - - const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id)); - return { hasHiddenThreads: true, - hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)), - visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)), + hiddenThreads: threads.filter((thread) => !visibleThreadKeys.has(getThreadKey(thread))), + visibleThreads: threads.filter((thread) => visibleThreadKeys.has(getThreadKey(thread))), }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 21525b56b7..d48191e3ac 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -185,10 +185,12 @@ import { useThreadSelectionStore } from "../threadSelectionStore"; import { useOpenAddProjectCommandPalette } from "../commandPaletteContext"; import { getSidebarThreadIdsToPrewarm, + getVisibleThreadsForProject, resolveAdjacentThreadId, isContextMenuPointerDown, isTrailingDoubleClick, resolveProjectStatusIndicator, + threadNeedsAttention, resolveSidebarNewThreadSeedContext, resolveSidebarNewThreadEnvMode, resolveSidebarStageBadgeLabel, @@ -1315,27 +1317,29 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec }, }); }; - 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))), + // `Date.now()` is read inside the memo on purpose: the fold only + // re-evaluates when its inputs change, so rows never vanish from a + // static list just because the recency window slid past them. + const { hasHiddenThreads, visibleThreads, hiddenThreads } = getVisibleThreadsForProject({ + threads: visibleProjectThreads, + getThreadKey: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + activeThreadKey: activeRouteThreadKey ?? undefined, + isThreadListExpanded, + previewLimit: sidebarThreadPreviewCount, + nowMs: Date.now(), + needsAttention: (thread) => { + const lastVisitedAt = lastVisitedAtByThreadKey.get( + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), ); - const hiddenThreads = visibleProjectThreads.filter( - (thread) => - !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), - ); + return threadNeedsAttention({ + ...thread, + ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}), + }); + }, + }); + const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleThreads; return { - hasOverflowingThreads, + hasOverflowingThreads: hasHiddenThreads, hiddenThreadStatus: resolveProjectStatusIndicator( hiddenThreads.map((thread) => resolveProjectThreadStatus(thread)), ), @@ -1344,6 +1348,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null, }; }, [ + activeRouteThreadKey, isThreadListExpanded, pinnedCollapsedThread, projectExpanded, @@ -3106,6 +3111,7 @@ export default function Sidebar() { const projects = useProjects(); const sidebarThreads = useThreadShells(); const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); + const threadLastVisitedAtById = useUiStateStore((store) => store.threadLastVisitedAtById); const projectOrder = useUiStateStore((store) => store.projectOrder); const reorderProjects = useUiStateStore((store) => store.reorderProjects); const navigate = useNavigate(); @@ -3428,12 +3434,28 @@ export default function Sidebar() { 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; + // Must mirror the fold in SidebarProjectThreadList's renderedThreads + // memo, otherwise jump-hint keys land on the wrong rows. + const { visibleThreads } = getVisibleThreadsForProject({ + threads: projectThreads, + getThreadKey: (thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + activeThreadKey, + isThreadListExpanded, + previewLimit: sidebarThreadPreviewCount, + nowMs: Date.now(), + needsAttention: (thread) => { + const lastVisitedAt = + threadLastVisitedAtById[ + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) + ]; + return threadNeedsAttention({ + ...thread, + ...(lastVisitedAt !== undefined ? { lastVisitedAt } : {}), + }); + }, + }); + const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleThreads; return renderedThreads.map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), ); @@ -3445,6 +3467,7 @@ export default function Sidebar() { projectExpandedById, routeThreadKey, sortedProjects, + threadLastVisitedAtById, threadsByProjectKey, ], );