From 082c59871625eb41a1b6cbc35f2f624bb42b5fae Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 7 Aug 2026 03:24:32 -0700 Subject: [PATCH] refactor(clients): share thread list v2 ordering --- apps/mobile/src/features/home/HomeHeader.tsx | 4 +- apps/mobile/src/features/home/HomeScreen.tsx | 3 +- .../features/settings/SettingsRouteScreen.tsx | 4 +- .../threads/ThreadNavigationSidebar.tsx | 4 +- .../features/threads/thread-list-v2-items.tsx | 3 +- .../src/features/threads/threadListV2.test.ts | 61 ++++++-- .../src/features/threads/threadListV2.ts | 76 +++++----- apps/web/src/components/Sidebar.logic.test.ts | 143 ------------------ apps/web/src/components/Sidebar.logic.ts | 92 ----------- apps/web/src/components/SidebarV2.tsx | 30 ++-- .../components/settings/BetaSettingsPanel.tsx | 2 +- .../src/state/threadSort.test.ts | 99 +++++++++++- .../client-runtime/src/state/threadSort.ts | 81 ++++++++++ 13 files changed, 290 insertions(+), 312 deletions(-) diff --git a/apps/mobile/src/features/home/HomeHeader.tsx b/apps/mobile/src/features/home/HomeHeader.tsx index a209dbd762..91b891d022 100644 --- a/apps/mobile/src/features/home/HomeHeader.tsx +++ b/apps/mobile/src/features/home/HomeHeader.tsx @@ -68,7 +68,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) { const iconColor = useThemeColor("--color-icon"); const mutedColor = useThemeColor("--color-foreground-muted"); const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant); - // Thread List v2 lays the list out in fixed creation order, so the + // Thread List v2 owns ordering (attention priority, then creation), so the // sort/group filter controls would be silently ignored — hide them and // key the "customized" icon state off the environment filter alone. const threadListV2Enabled = useThreadListV2Enabled(); @@ -290,7 +290,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) { function IosHomeHeader(props: HomeHeaderProps) { const searchBarRef = useRef(null); const iconColor = useThemeColor("--color-icon"); - // Thread List v2 lays the list out in fixed creation order, so the + // Thread List v2 owns ordering (attention priority, then creation), so the // sort/group filter controls would be silently ignored — hide them and // key the "customized" icon state off the environment filter alone. const threadListV2Enabled = useThreadListV2Enabled(); diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index ba32dc6b60..f1adee69c2 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -475,7 +475,8 @@ export function HomeScreen(props: HomeScreenProps) { ), [v2ScopedProjectGroup], ); - // Thread List v2 (beta): one flat list in creation order, no grouping. + // Thread List v2 (beta): one flat list, attention priority then creation + // order, with no grouping. // Settled threads collapse into a recency tail below the card block. // Settled threads stay in the live shell stream (settled ≠ archived), so // the partition works directly off live shells — no snapshot merging or diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 8547859add..043eb77846 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -556,8 +556,8 @@ function BetaSettingsSection() { /> - One flat thread list in creation order. Active work renders as cards; settled threads - collapse to compact rows. Switch back any time. + One flat thread list. Woke and un-settled work comes first; settled threads collapse to + compact rows. Switch back any time. ); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 322ac60759..e610b6f7b6 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -644,8 +644,8 @@ function ThreadNavigationSidebarPane( ], }, ] satisfies MenuAction[])), - // v2 lays the list out in fixed creation order — offering sort/group - // controls it silently ignores would be a lie. Environment still + // v2 owns ordering (attention priority, then creation) — offering + // sort/group controls it silently ignores would be a lie. Environment still // scopes the v2 partition, so it stays. ...(threadListV2Enabled ? [] diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 24f7166916..c67ec0c86e 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -4,6 +4,7 @@ import type { } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search"; import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled"; +import { resolveSettledTimestamp } from "@t3tools/client-runtime/state/thread-sort"; import type { MenuAction } from "@react-native-menu/menu"; import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react"; import { @@ -812,7 +813,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { > {snoozedRow && props.snoozeWakeLabelText !== undefined ? props.snoozeWakeLabelText - : relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)} + : relativeTime(resolveSettledTimestamp(thread) ?? thread.createdAt)} diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 1316b3480c..9f0c989332 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -21,7 +21,6 @@ import { resolveThreadListV2SnoozeGateExpiryMs, resolveThreadListV2Status, resolveThreadListV2SwipeActions, - sortThreadsForListV2, } from "./threadListV2"; const environmentId = EnvironmentId.make("environment-1"); @@ -247,17 +246,6 @@ describe("resolveThreadListV2SnoozeGateExpiryMs", () => { }); }); -describe("sortThreadsForListV2", () => { - it("orders by creation time, newest first, ignoring activity", () => { - const sorted = sortThreadsForListV2([ - { id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" }, - { id: "newest", createdAt: "2026-06-01T12:00:00.000Z" }, - { id: "middle", createdAt: "2026-06-01T10:00:00.000Z" }, - ]); - expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]); - }); -}); - describe("buildThreadListV2Items", () => { it("hides snoozed threads and counts them — visibility parity with web", () => { const layout = buildThreadListV2Items({ @@ -282,12 +270,53 @@ describe("buildThreadListV2Items", () => { now: NOW, }); - // Same createdAt → static sort tiebreaks by id; the point is the woken - // thread is BACK in the card block and the snoozed one is gone. - expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]); + expect(layout.items.map((item) => item.thread.id)).toEqual(["woken", "active"]); expect(layout.snoozedCount).toBe(1); }); + it("shares web attention priority while preserving the pinned block", () => { + const layout = buildThreadListV2Items({ + threads: [ + makeThread({ + id: ThreadId.make("woke"), + title: "Woke", + createdAt: "2026-05-01T00:00:00.000Z", + latestUserMessageAt: "2026-05-01T00:00:00.000Z", + snoozedAt: "2026-05-29T00:00:00.000Z", + snoozedUntil: "2026-05-30T00:00:00.000Z", + }), + makeThread({ + id: ThreadId.make("unsettled"), + title: "Un-settled", + createdAt: "2026-06-01T08:00:00.000Z", + settledOverride: "active", + }), + makeThread({ + id: ThreadId.make("default"), + title: "Default", + createdAt: "2026-06-01T12:00:00.000Z", + }), + makeThread({ + id: ThreadId.make("pinned"), + title: "Pinned", + createdAt: "2026-04-01T00:00:00.000Z", + pinnedAt: "2026-06-01T12:00:00.000Z", + }), + ], + environmentId: null, + searchQuery: "", + autoSettleAfterDays: 3, + now: NOW, + }); + + expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([ + ["pinned", "card"], + ["woke", "card"], + ["unsettled", "card"], + ["default", "card"], + ]); + }); + it("renders pinned threads first and exempts them from auto-settle — parity with web", () => { const layout = buildThreadListV2Items({ threads: [ @@ -678,7 +707,7 @@ describe("buildThreadListV2Items settled paging", () => { id: ThreadId.make(`settled-${index}`), title: `Settled ${index}`, settledOverride: "settled", - settledAt: NOW, + settledAt: `2026-06-01T0${index}:20:00.000Z`, latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`, // A turn adopted the message (same requestedAt): without it the // thread reads as a queued turn start, which never settles. diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index fa5f58d5d0..4311e60a04 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -5,8 +5,14 @@ import { QUEUED_TURN_START_GRACE_MS, resolveSnoozePresets, snoozeWakeLabel, + threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; +import { + sortSettledThreadsForListV2, + sortThreadsForListV2, + threadListV2Priority, +} from "@t3tools/client-runtime/state/thread-sort"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; @@ -146,35 +152,6 @@ function parseTimestampMs(isoDate: string): number { return Number.isNaN(parsed) ? 0 : parsed; } -/** First VALID timestamp wins: a present-yet-malformed string falls through - to the next candidate rather than sinking the row to the epoch. */ -function firstValidTimestampMs(...candidates: ReadonlyArray): number { - for (const candidate of candidates) { - if (candidate == null) continue; - const parsed = Date.parse(candidate); - if (!Number.isNaN(parsed)) return parsed; - } - return 0; -} - -/** - * v2 sort: static creation order, newest thread on top. Activity NEVER - * reorders the list — a row holds its position from open until settled, so - * the screen only moves at lifecycle transitions. Mirrors web's - * sortThreadsForSidebarV2. - */ -export function sortThreadsForListV2( - threads: readonly T[], -): T[] { - // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 - // change-by-copy array methods. - return [...threads].sort( - (left, right) => - parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) || - left.id.localeCompare(right.id), - ); -} - export interface ThreadListV2Item { readonly thread: EnvironmentThreadShell; readonly variant: "card" | "slim"; @@ -304,8 +281,9 @@ export function buildThreadListV2ListItems(input: { } /** - * Partitions visible threads into the active card block (creation order) and - * the settled recency tail, matching the web v2 list. `autoSettleAfterDays` + * Partitions visible threads into the active card block (attention priority, + * then creation order) and the settled recency tail, matching web v2. + * `autoSettleAfterDays` * mirrors the web default of 3 — mobile has no client-settings sync yet, so * the default is fixed here rather than user-configurable. */ @@ -357,6 +335,7 @@ export function buildThreadListV2Items(input: { const active: EnvironmentThreadShell[] = []; const settled: EnvironmentThreadShell[] = []; const snoozed: EnvironmentThreadShell[] = []; + const wokeAtByThreadKey = new Map(); let nextSnoozeWakeAt: string | null = null; for (const thread of input.threads) { // Callers pass live (unarchived) shells; settled threads are among them @@ -381,6 +360,16 @@ export function buildThreadListV2Items(input: { const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true; const changeRequestState = input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null; + const wokeAt = supportsSnooze ? threadWokeAt(thread, { now: snoozeNow }) : null; + if (wokeAt !== null) { + wokeAtByThreadKey.set( + threadSearchMatchKey({ + environmentId: thread.environmentId, + threadId: thread.id, + }), + wokeAt, + ); + } // Visibility parity with web: snooze outranks everything, including a // pin — a snoozed thread leaves the list until it wakes (or raises its // hand). The pin survives underneath, so a woken thread reappears at @@ -404,7 +393,12 @@ export function buildThreadListV2Items(input: { } if ( supportsSettlement && - effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState }) + effectiveSettled(thread, { + now, + autoSettleAfterDays, + changeRequestState, + suppressAutoSettle: wokeAt !== null, + }) ) { settled.push(thread); } else { @@ -412,7 +406,17 @@ export function buildThreadListV2Items(input: { } } - const orderedActive = sortThreadsForListV2(active); + const orderedActive = sortThreadsForListV2(active, (thread) => + threadListV2Priority(thread, { + wokeAt: + wokeAtByThreadKey.get( + threadSearchMatchKey({ + environmentId: thread.environmentId, + threadId: thread.id, + }), + ) ?? null, + }), + ); const orderedSnoozed = [...snoozed].sort( (left, right) => parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""), @@ -424,11 +428,7 @@ export function buildThreadListV2Items(input: { : orderedSnoozed.filter( (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey, ); - const orderedSettled = [...settled].sort( - (left, right) => - firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) - - firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt), - ); + const orderedSettled = sortSettledThreadsForListV2(settled); const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY; const pagedSettled = orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled; diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index cbb58d586f..4192d95e3c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -14,7 +14,6 @@ import { isContextMenuPointerDown, isTrailingDoubleClick, orderItemsByPreferredIds, - isSidebarV2ThreadWoke, resolveProjectStatusIndicator, resolveSidebarStageBadgeLabel, resolveThreadRowClassName, @@ -26,8 +25,6 @@ import { shouldNavigateAfterProjectRemoval, shouldClearThreadSelectionOnMouseDown, sortLogicalProjectsForSidebar, - sortSettledThreadsForSidebarV2, - sortThreadsForSidebarV2, sortProjectsForSidebar, sortScopedProjectsForSidebar, THREAD_JUMP_HINT_SHOW_DELAY_MS, @@ -713,146 +710,6 @@ describe("searchSidebarThreadsByTitle", () => { }); }); -describe("sortThreadsForSidebarV2", () => { - const sortable = (input: { id: string; createdAt: string }) => ({ - id: input.id, - createdAt: input.createdAt, - }); - - it("orders by creation time, newest first, ignoring activity", () => { - const sorted = sortThreadsForSidebarV2([ - sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }), - sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }), - sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]); - }); - - it("breaks creation-time ties by id so the order is stable", () => { - const sorted = sortThreadsForSidebarV2([ - sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }), - sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]); - }); - - it("puts woke threads first, then manually un-settled threads", () => { - const threads = [ - sortable({ id: "ordinary-new", createdAt: "2026-03-09T12:00:00.000Z" }), - sortable({ id: "unsettled-old", createdAt: "2026-03-09T08:00:00.000Z" }), - sortable({ id: "woke-old", createdAt: "2026-03-09T07:00:00.000Z" }), - sortable({ id: "woke-new", createdAt: "2026-03-09T09:00:00.000Z" }), - ]; - const priorities: ReadonlyMap = new Map([ - ["unsettled-old", "unsettled"], - ["woke-old", "woke"], - ["woke-new", "woke"], - ] as const); - - const sorted = sortThreadsForSidebarV2( - threads, - (thread) => priorities.get(thread.id) ?? "default", - ); - - expect(sorted.map((thread) => thread.id)).toEqual([ - "woke-new", - "woke-old", - "unsettled-old", - "ordinary-new", - ]); - }); -}); - -describe("isSidebarV2ThreadWoke", () => { - const wokeAt = "2026-03-09T10:00:00.000Z"; - - it("stays woke until a visit at or after the wake", () => { - expect(isSidebarV2ThreadWoke({ wokeAt, lastVisitedAt: undefined })).toBe(true); - expect( - isSidebarV2ThreadWoke({ - wokeAt, - lastVisitedAt: "2026-03-09T09:59:59.999Z", - }), - ).toBe(true); - expect(isSidebarV2ThreadWoke({ wokeAt, lastVisitedAt: wokeAt })).toBe(false); - }); - - it("keeps a valid wake visible when local visit data is malformed", () => { - expect(isSidebarV2ThreadWoke({ wokeAt, lastVisitedAt: "not-a-date" })).toBe(true); - expect(isSidebarV2ThreadWoke({ wokeAt: "not-a-date", lastVisitedAt: undefined })).toBe(false); - }); -}); - -describe("sortSettledThreadsForSidebarV2", () => { - const settled = (input: { - id: string; - settledAt?: string | null; - latestUserMessageAt?: string | null; - latestTurn?: OrchestrationLatestTurn | null; - updatedAt?: string; - }) => ({ - id: input.id, - settledAt: input.settledAt ?? null, - latestUserMessageAt: input.latestUserMessageAt ?? null, - latestTurn: input.latestTurn ?? null, - updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z", - }); - - it("orders by settle time, most recently settled first", () => { - const sorted = sortSettledThreadsForSidebarV2([ - settled({ - id: "settled-first", - settledAt: "2026-03-09T10:00:00.000Z", - // Created/active later than the other thread: settle time must win. - latestUserMessageAt: "2026-03-09T09:59:00.000Z", - }), - settled({ - id: "settled-last", - settledAt: "2026-03-09T12:00:00.000Z", - latestUserMessageAt: "2026-03-09T08:00:00.000Z", - }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]); - }); - - it("falls back to last activity for auto-settled threads without a settledAt stamp", () => { - const sorted = sortSettledThreadsForSidebarV2([ - settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }), - settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }), - settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]); - }); - - it("counts a turn completion as activity for auto-settled threads", () => { - // The message came in before the other thread's, but its turn finished - // after: completion time is the real "work ended" moment. - const sorted = sortSettledThreadsForSidebarV2([ - settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }), - settled({ - id: "completed-later", - latestUserMessageAt: "2026-03-09T10:00:00.000Z", - latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }), - }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]); - }); - - it("breaks timestamp ties by id so the order is stable", () => { - const sorted = sortSettledThreadsForSidebarV2([ - settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }), - settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]); - }); -}); - describe("resolveWorkingStartedAt", () => { const session = { threadId: ThreadId.make("thread-1"), diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 8fe36710ff..e4ae3b707e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -463,13 +463,6 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2S return "ready"; } -/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not - poison the whole ordering, so it sinks to the epoch instead. */ -export function parseTimestampMs(isoDate: string): number { - const parsed = Date.parse(isoDate); - return Number.isNaN(parsed) ? 0 : parsed; -} - /** First VALID timestamp wins: `a ?? b` falls through on null, but a present- yet-malformed string must also fall through to the next candidate rather than sink the row to the epoch. */ @@ -496,46 +489,6 @@ export function firstValidTimestamp( return null; } -export type SidebarV2ThreadPriority = "woke" | "unsettled" | "default"; - -const SIDEBAR_V2_THREAD_PRIORITY_RANK: Record = { - woke: 0, - unsettled: 1, - default: 2, -}; - -/** A wake remains attention-bearing until the user visits it. Invalid local - visit data must not silently clear a valid server-backed wake. */ -export function isSidebarV2ThreadWoke(input: { - readonly wokeAt: string | null; - readonly lastVisitedAt: string | undefined; -}): boolean { - if (input.wokeAt === null) return false; - const wokeAtMs = Date.parse(input.wokeAt); - if (Number.isNaN(wokeAtMs)) return false; - if (input.lastVisitedAt === undefined) return true; - const lastVisitedAtMs = Date.parse(input.lastVisitedAt); - return Number.isNaN(lastVisitedAtMs) || lastVisitedAtMs < wokeAtMs; -} - -// v2 sort: attention transitions come first (woke, then manually -// un-settled), with static creation order inside each group. Ordinary -// activity never reorders the list. -export function sortThreadsForSidebarV2< - T extends { readonly id: string; readonly createdAt: string }, ->( - threads: readonly T[], - getPriority: (thread: T) => SidebarV2ThreadPriority = () => "default", -): T[] { - return [...threads].toSorted( - (left, right) => - SIDEBAR_V2_THREAD_PRIORITY_RANK[getPriority(left)] - - SIDEBAR_V2_THREAD_PRIORITY_RANK[getPriority(right)] || - parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) || - left.id.localeCompare(right.id), - ); -} - /** * Search the already-ordered sidebar thread collection by title only. * Keeping the input order means lifecycle ordering (active, snoozed, settled) @@ -550,51 +503,6 @@ export function searchSidebarThreadsByTitle thread.title.toLowerCase().includes(normalizedQuery)); } -type SettledTimestampInput = Pick< - SidebarThreadSummary, - "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt" ->; - -/** The timestamp a settled row sorts and labels by: settledAt when stamped - (explicit settles), otherwise last activity — the same candidates - threadLastActivityAt feeds the auto-settle window (user message plus all - latestTurn stamps), so a thread whose last activity was a turn completion - doesn't sort by an older message time. updatedAt is the final net. */ -export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null { - const settledAt = firstValidTimestamp(thread.settledAt); - if (settledAt !== null) return settledAt; - let latest: string | null = null; - let latestMs = Number.NEGATIVE_INFINITY; - for (const candidate of [ - thread.latestUserMessageAt, - thread.latestTurn?.requestedAt, - thread.latestTurn?.startedAt, - thread.latestTurn?.completedAt, - ]) { - if (candidate == null) continue; - const parsed = Date.parse(candidate); - if (!Number.isNaN(parsed) && parsed > latestMs) { - latest = candidate; - latestMs = parsed; - } - } - return latest ?? firstValidTimestamp(thread.updatedAt); -} - -// Settled rows are history, so they order by when the work ENDED, not when -// the thread was created or last touched. -export function sortSettledThreadsForSidebarV2< - T extends SettledTimestampInput & { readonly id: string }, ->(threads: readonly T[]): T[] { - const timestampMs = (thread: T) => { - const timestamp = resolveSettledTimestamp(thread); - return timestamp === null ? 0 : Date.parse(timestamp); - }; - return [...threads].toSorted( - (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id), - ); -} - /** The timestamp a working thread's elapsed label counts from: the running turn's start (request time until adoption), falling back to the session's last transition when the turn projection lags behind. Malformed diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index df12bb88d0..e1666ac706 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -6,6 +6,12 @@ import { effectiveSnoozed, threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; +import { + resolveSettledTimestamp, + sortSettledThreadsForListV2, + sortThreadsForListV2, + threadListV2Priority, +} from "@t3tools/client-runtime/state/thread-sort"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; import { scopeProjectRef, @@ -117,14 +123,11 @@ import { isTrailingDoubleClick, orderItemsByPreferredIds, resolveAdjacentThreadId, - resolveSettledTimestamp, resolveSidebarV2Status, searchSidebarThreadsByTitle, resolveWorkingStartedAt, shouldNavigateAfterProjectRemoval, sortLogicalProjectsForSidebar, - sortSettledThreadsForSidebarV2, - sortThreadsForSidebarV2, } from "./Sidebar.logic"; import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic"; import { @@ -505,8 +508,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { prState !== "closed"; // Background work and approvals recede when read. Input requests stay // fully prominent because the agent cannot continue without the user. - const isInFlight = - status === "working" || status === "monitoring" || status === "approval"; + const isInFlight = status === "working" || status === "monitoring" || status === "approval"; const shouldRecede = (status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected; // Status hues follow the system-wide convention set by sidebar v1 and the @@ -1736,20 +1738,22 @@ export default function SidebarV2() { return { // Same static creation order as the inbox: a pin freezes prominence, // it does not introduce a new ordering scheme. - pinnedThreads: sortThreadsForSidebarV2(pinned), - activeThreads: sortThreadsForSidebarV2(active, (thread) => { - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - if (wokeAtByThreadKey.has(threadKey)) return "woke"; - if (thread.settledOverride === "active") return "unsettled"; - return "default"; - }), + pinnedThreads: sortThreadsForListV2(pinned), + activeThreads: sortThreadsForListV2(active, (thread) => + threadListV2Priority(thread, { + wokeAt: + wokeAtByThreadKey.get( + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + ) ?? null, + }), + ), // Soonest wake first: "what comes back next" is the shelf's question. snoozedThreads: snoozed.toSorted( (left, right) => firstValidTimestampMs(left.snoozedUntil ?? null) - firstValidTimestampMs(right.snoozedUntil ?? null), ), - settledThreads: sortSettledThreadsForSidebarV2(settled), + settledThreads: sortSettledThreadsForListV2(settled), snoozeNow: preciseNow, }; }, [ diff --git a/apps/web/src/components/settings/BetaSettingsPanel.tsx b/apps/web/src/components/settings/BetaSettingsPanel.tsx index 4b96fb1539..5220e132f2 100644 --- a/apps/web/src/components/settings/BetaSettingsPanel.tsx +++ b/apps/web/src/components/settings/BetaSettingsPanel.tsx @@ -68,7 +68,7 @@ export function BetaSettingsPanel() { { expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]); }); }); + +describe("sortThreadsForListV2", () => { + const threads = [ + { id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" }, + { id: "newest", createdAt: "2026-06-01T12:00:00.000Z" }, + { id: "middle", createdAt: "2026-06-01T10:00:00.000Z" }, + ] as const; + + it("orders by creation time within the default priority", () => { + expect(sortThreadsForListV2(threads).map((thread) => thread.id)).toEqual([ + "newest", + "middle", + "oldest", + ]); + }); + + it("ranks server-backed wakes and manual un-settles above default threads", () => { + const priorityById: Record = { + oldest: "woke", + middle: "unsettled", + newest: "default", + }; + expect( + sortThreadsForListV2(threads, (thread) => priorityById[thread.id] ?? "default").map( + (thread) => thread.id, + ), + ).toEqual(["oldest", "middle", "newest"]); + }); + + it("breaks equal creation timestamps by id", () => { + const tied = [ + { id: "b", createdAt: "2026-06-01T10:00:00.000Z" }, + { id: "a", createdAt: "2026-06-01T10:00:00.000Z" }, + ]; + expect(sortThreadsForListV2(tied).map((thread) => thread.id)).toEqual(["a", "b"]); + }); +}); + +describe("threadListV2Priority", () => { + it("lets a manual un-settle consume older wake priority", () => { + expect( + threadListV2Priority({ settledOverride: "active" }, { wokeAt: "2026-06-01T10:00:00.000Z" }), + ).toBe("unsettled"); + expect(threadListV2Priority({ settledOverride: "active" }, { wokeAt: null })).toBe("unsettled"); + expect( + threadListV2Priority({ settledOverride: null }, { wokeAt: "2026-06-01T10:00:00.000Z" }), + ).toBe("woke"); + expect(threadListV2Priority({ settledOverride: null }, { wokeAt: null })).toBe("default"); + }); +}); + +describe("sortSettledThreadsForListV2", () => { + const settled = (input: { + id: string; + settledAt?: string | null; + latestUserMessageAt?: string | null; + completedAt?: string | null; + updatedAt?: string; + }) => ({ + id: input.id, + settledAt: input.settledAt ?? null, + latestUserMessageAt: input.latestUserMessageAt ?? null, + latestTurn: + input.completedAt === undefined + ? null + : { + requestedAt: "2026-03-09T10:00:00.000Z", + startedAt: "2026-03-09T10:00:00.000Z", + completedAt: input.completedAt, + }, + updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z", + }); + + it("orders by settle time and falls back to the latest activity", () => { + const sorted = sortSettledThreadsForListV2([ + settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }), + settled({ id: "message", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }), + settled({ id: "completed", completedAt: "2026-03-09T12:00:00.000Z" }), + ]); + expect(sorted.map((thread) => thread.id)).toEqual(["completed", "message", "explicit"]); + }); + + it("breaks timestamp ties by id", () => { + const sorted = sortSettledThreadsForListV2([ + settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }), + settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }), + ]); + expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]); + }); +}); diff --git a/packages/client-runtime/src/state/threadSort.ts b/packages/client-runtime/src/state/threadSort.ts index aed63cd442..78d5eac260 100644 --- a/packages/client-runtime/src/state/threadSort.ts +++ b/packages/client-runtime/src/state/threadSort.ts @@ -13,6 +13,14 @@ export interface ThreadSortInput { }>; } +export type ThreadListV2Priority = "woke" | "unsettled" | "default"; + +const THREAD_LIST_V2_PRIORITY_RANK: Record = { + woke: 0, + unsettled: 1, + default: 2, +}; + export function toSortableTimestamp(iso: string | undefined): number | null { if (!iso) return null; const ms = Date.parse(iso); @@ -57,6 +65,79 @@ function getLatestUserMessageTimestamp(thread: ThreadSortInput): number { return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY; } +/** Priority from server-backed state only so web and mobile derive the same + order. A manual un-settle supersedes an older retained wake marker. */ +export function threadListV2Priority( + thread: { readonly settledOverride: "settled" | "active" | null }, + options: { readonly wokeAt: string | null }, +): ThreadListV2Priority { + if (thread.settledOverride === "active") return "unsettled"; + if (options.wokeAt !== null) return "woke"; + return "default"; +} + +/** Attention transitions first, then static creation order within a group. */ +export function sortThreadsForListV2( + threads: readonly T[], + getPriority: (thread: T) => ThreadListV2Priority = () => "default", +): T[] { + // Hermes does not ship the ES2023 change-by-copy array methods. + return [...threads].sort( + (left, right) => + THREAD_LIST_V2_PRIORITY_RANK[getPriority(left)] - + THREAD_LIST_V2_PRIORITY_RANK[getPriority(right)] || + (toSortableTimestamp(right.createdAt) ?? 0) - (toSortableTimestamp(left.createdAt) ?? 0) || + left.id.localeCompare(right.id), + ); +} + +export interface SettledSortInput { + readonly settledAt: string | null; + readonly latestUserMessageAt: string | null; + readonly latestTurn: { + readonly requestedAt: string; + readonly startedAt: string | null; + readonly completedAt: string | null; + } | null; + readonly updatedAt: string; +} + +/** Timestamp shared by settled-row ordering and labels. */ +export function resolveSettledTimestamp(thread: SettledSortInput): string | null { + if (thread.settledAt !== null && toSortableTimestamp(thread.settledAt) !== null) { + return thread.settledAt; + } + let latest: string | null = null; + let latestMs = Number.NEGATIVE_INFINITY; + for (const candidate of [ + thread.latestUserMessageAt, + thread.latestTurn?.requestedAt, + thread.latestTurn?.startedAt, + thread.latestTurn?.completedAt, + ]) { + if (candidate == null) continue; + const parsed = toSortableTimestamp(candidate); + if (parsed !== null && parsed > latestMs) { + latest = candidate; + latestMs = parsed; + } + } + if (latest !== null) return latest; + return toSortableTimestamp(thread.updatedAt) !== null ? thread.updatedAt : null; +} + +export function sortSettledThreadsForListV2( + threads: readonly T[], +): T[] { + const timestampMs = (thread: T) => { + const timestamp = resolveSettledTimestamp(thread); + return timestamp === null ? 0 : (toSortableTimestamp(timestamp) ?? 0); + }; + return [...threads].sort( + (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id), + ); +} + export function getThreadSortTimestamp( thread: ThreadSortInput, sortOrder: SidebarThreadSortOrder | Exclude,