The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): rank dragged sessions inside their date group
Brooklyn Nicholson03b759db8691
diff --git a/apps/desktop/src/app/chat/sidebar/order.test.ts b/apps/desktop/src/app/chat/sidebar/order.test.tsindex e1a48bc5fbf..911d451fc68 100644--- a/apps/desktop/src/app/chat/sidebar/order.test.ts+++ b/apps/desktop/src/app/chat/sidebar/order.test.ts@@ -1,6 +1,16 @@import { describe, expect, it } from 'vitest'-import { orderByIds, reconcileOrderIds, resolveManualSessionOrderIds, sameIds } from './order'+import type { SidebarListRow } from '@/lib/session-date-groups'+import type { SessionInfo } from '@/types/hermes'++import {+ orderByIds,+ orderRowsWithinGroups,+ reconcileOrderIds,+ reorderableRowIds,+ resolveManualSessionOrderIds,+ sameIds+} from './order'describe('resolveManualSessionOrderIds', () => {it('clears legacy auto-seeded order until the user manually reorders sessions', () => {@@ -30,13 +40,28 @@ describe('orderByIds', () => {it('reorders by the given ids and drops missing ones', () => {const items = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]- expect(orderByIds(items, id, ['c', 'gone', 'a'])).toEqual([{ id: 'b' }, { id: 'c' }, { id: 'a' }])+ // 'b' isn't in the order and sits after 'a' (the first ordered item), so+ // it's an older row: it sinks below the hand-picked pair, not above it.+ expect(orderByIds(items, id, ['c', 'gone', 'a'])).toEqual([{ id: 'c' }, { id: 'a' }, { id: 'b' }])})it('surfaces items absent from the order first', () => {const items = [{ id: 'fresh' }, { id: 'a' }, { id: 'b' }]expect(orderByIds(items, id, ['b', 'a'])).toEqual([{ id: 'fresh' }, { id: 'b' }, { id: 'a' }])})++ it('keeps a newly-loaded older page below the hand-picked order', () => {+ // Callers pass recency-sorted lists, so an unknown id BELOW the ordered+ // ones is an older page that just loaded — hoisting it to the top was+ // dumping 50 stale sessions above the user's arrangement.+ const items = [{ id: 'a' }, { id: 'b' }, { id: 'old1' }, { id: 'old2' }]+ expect(orderByIds(items, id, ['b', 'a'])).toEqual([{ id: 'b' }, { id: 'a' }, { id: 'old1' }, { id: 'old2' }])+ })++ it('splits unknown ids either side of the order by their own position', () => {+ const items = [{ id: 'new' }, { id: 'a' }, { id: 'b' }, { id: 'old' }]+ expect(orderByIds(items, id, ['b', 'a'])).toEqual([{ id: 'new' }, { id: 'b' }, { id: 'a' }, { id: 'old' }])+ })})describe('reconcileOrderIds', () => {@@ -60,3 +85,74 @@ describe('sameIds', () => {expect(sameIds(['a'], ['a', 'b'])).toBe(false)})})++const session = (id: string, branchStem?: string): SidebarListRow => ({+ entry: { branchStem, session: { id } as SessionInfo },+ kind: 'session'+})++const divider = (key: string): SidebarListRow =>+ ({ bucket: { key }, key, kind: 'divider' }) as unknown as SidebarListRow++const ids = (rows: SidebarListRow[]): string[] =>+ rows.map(row => (row.kind === 'divider' ? `--${row.key}--` : `${row.entry.branchStem ?? ''}${row.entry.session.id}`))++describe('orderRowsWithinGroups', () => {+ it('returns the same rows when no order is given', () => {+ const rows = [session('a'), session('b')]+ expect(orderRowsWithinGroups(rows, [])).toBe(rows)+ })++ it('keeps identity when the order changes nothing', () => {+ const rows = [session('a'), session('b')]+ expect(orderRowsWithinGroups(rows, ['a', 'b'])).toBe(rows)+ })++ it('reorders within a group without moving the dividers', () => {+ const rows = [session('a'), session('b'), divider('yesterday'), session('c'), session('d')]++ expect(ids(orderRowsWithinGroups(rows, ['b', 'a', 'd', 'c']))).toEqual([+ 'b',+ 'a',+ '--yesterday--',+ 'd',+ 'c'+ ])+ })++ it('never moves a row across a date divider', () => {+ // 'd' is ranked first overall, but it lives below the divider and must+ // stay there — chronology owns the groups, the drag only ranks inside one.+ const rows = [session('a'), session('b'), divider('lastWeek'), session('c'), session('d')]++ expect(ids(orderRowsWithinGroups(rows, ['d', 'c', 'b', 'a']))).toEqual([+ 'b',+ 'a',+ '--lastWeek--',+ 'd',+ 'c'+ ])+ })++ it('leaves rows the order does not name in their recency slot', () => {+ // Only 'a' and 'c' are ranked; 'b' never moves, and the ranked pair swap+ // into the two slots they already occupied.+ const rows = [session('a'), session('b'), session('c')]++ expect(ids(orderRowsWithinGroups(rows, ['c', 'a']))).toEqual(['c', 'b', 'a'])+ })++ it('carries branch children with their parent', () => {+ const rows = [session('parent'), session('child', '└─ '), session('other')]++ expect(ids(orderRowsWithinGroups(rows, ['other', 'parent']))).toEqual(['other', 'parent', '└─ child'])+ })+})++describe('reorderableRowIds', () => {+ it('lists root session ids in render order, skipping dividers and branches', () => {+ const rows = [session('a'), session('branch', '├─ '), divider('yesterday'), session('b')]++ expect(reorderableRowIds(rows)).toEqual(['a', 'b'])+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/order.ts b/apps/desktop/src/app/chat/sidebar/order.tsindex 9cefea57d01..9998243722d 100644--- a/apps/desktop/src/app/chat/sidebar/order.ts+++ b/apps/desktop/src/app/chat/sidebar/order.ts@@ -1,10 +1,44 @@-/** New ids first, then ids still present in the persisted order. */+import type { SidebarListRow } from '@/lib/session-date-groups'++/**+ * Fold ids absent from the persisted order back in, on the side they belong.+ *+ * Callers hand us a recency-sorted `currentIds`, so an id's position relative+ * to the newest id the saved order still knows about says which side it goes:+ * ahead of it is genuinely newer (a session created since the last reconcile,+ * which must not sink), behind it is an older page that just loaded. Hoisting+ * every unknown id to the top treated those two cases the same, so one "load+ * more" dropped 50 of the oldest sessions above the hand-ordered list.+ */+function mergeFreshByPosition(currentIds: string[], keptIds: string[]): string[] {+ const kept = new Set(keptIds)+ const firstKept = currentIds.findIndex(id => kept.has(id))+ const newer: string[] = []+ const older: string[] = []++ currentIds.forEach((id, index) => {+ if (kept.has(id)) {+ return+ }++ if (firstKept >= 0 && index < firstKept) {+ newer.push(id)+ } else {+ older.push(id)+ }+ })++ return [...newer, ...keptIds, ...older]+}++/** Ids still present in the persisted order, with new ids folded in by position. */export function reconcileFreshFirst(currentIds: string[], orderIds: string[]): string[] {const current = new Set(currentIds)- const retained = orderIds.filter(id => current.has(id))- const retainedSet = new Set(retained)- return [...currentIds.filter(id => !retainedSet.has(id)), ...retained]+ return mergeFreshByPosition(+ currentIds,+ orderIds.filter(id => current.has(id))+ )}export function resolveManualSessionOrderIds(currentIds: string[], orderIds: string[], manual: boolean): string[] {@@ -22,7 +56,12 @@ export function resolveManualSessionOrderIds(currentIds: string[], orderIds: strreturn reconcileFreshFirst(currentIds, orderIds)}-/** Reorder `items` by `orderIds`; items missing from the order surface first. */+/**+ * Reorder `items` by `orderIds`. Items missing from the order are folded in by+ * position, same rule as {@link reconcileFreshFirst}: a brand-new session ahead+ * of everything the order knows stays on top, an older page that just loaded+ * sinks below the hand-picked list instead of jumping it.+ */export function orderByIds<T>(items: T[], getId: (item: T) => string, orderIds: string[]): T[] {if (!orderIds.length) {return items@@ -41,17 +80,30 @@ export function orderByIds<T>(items: T[], getId: (item: T) => string, orderIds:}}- // Items missing from the persisted order are new since it was last- // reconciled. Callers pass recency-sorted lists (newest first), so surface- // these at the TOP instead of burying them beneath the saved order —- // otherwise a brand-new session sinks to the bottom of the sidebar and reads- // as "my latest session never showed up".- const fresh = items.filter(item => !seen.has(getId(item)))+ if (seen.size === items.length) {+ return ordered+ }++ const firstOrdered = items.findIndex(item => seen.has(getId(item)))+ const newer: T[] = []+ const older: T[] = []- return fresh.length ? [...fresh, ...ordered] : ordered+ items.forEach((item, index) => {+ if (seen.has(getId(item))) {+ return+ }++ if (firstOrdered >= 0 && index < firstOrdered) {+ newer.push(item)+ } else {+ older.push(item)+ }+ })++ return [...newer, ...ordered, ...older]}-/** Reconcile a persisted order against the live id set (fresh-first). */+/** Reconcile a persisted order against the live id set. */export function reconcileOrderIds(currentIds: string[], orderIds: string[]): string[] {if (!currentIds.length) {return []@@ -68,3 +120,87 @@ export function reconcileOrderIds(currentIds: string[], orderIds: string[]): strexport function sameIds(left: string[], right: string[]): boolean {return left.length === right.length && left.every((item, index) => item === right[index])}++/**+ * Apply a hand-picked order WITHIN each chronological group, never across them.+ *+ * A drag used to switch the whole list into a frozen manual mode with no date+ * dividers at all: one reorder and the sidebar stopped being chronological,+ * permanently and for every row. Ranking and grouping are separate concerns —+ * the calendar buckets stay exactly where recency put them, and the manual+ * order only decides the sequence of rows inside a bucket.+ *+ * Rows are permuted as clusters (a parent plus the branch children nested under+ * it) so a reorder can't strand a branch away from its parent, and clusters the+ * saved order doesn't know about keep the slot recency gave them — only the+ * ones it names are re-slotted, into the positions they already occupied.+ */+export function orderRowsWithinGroups(rows: SidebarListRow[], orderIds: string[]): SidebarListRow[] {+ if (!orderIds.length || !rows.length) {+ return rows+ }++ const rank = new Map(orderIds.map((id, index) => [id, index]))+ const out: SidebarListRow[] = []+ let cluster: SidebarListRow[][] = []+ let reordered = false++ // Re-slot the clusters the saved order names, leaving every other cluster+ // (and every divider) exactly where it is.+ const flushGroup = () => {+ const ranked = cluster+ .map((rows_, index) => ({ index, rank: rank.get(clusterId(rows_)) }))+ .filter((entry): entry is { index: number; rank: number } => entry.rank !== undefined)++ const slots = ranked.map(entry => entry.index)+ const sorted = [...ranked].sort((a, b) => a.rank - b.rank)+ const next = [...cluster]++ slots.forEach((slot, i) => {+ const source = cluster[sorted[i].index]++ reordered ||= source !== next[slot]+ next[slot] = source+ })++ for (const rows_ of next) {+ out.push(...rows_)+ }++ cluster = []+ }++ for (const row of rows) {+ if (row.kind === 'divider') {+ flushGroup()+ out.push(row)++ continue+ }++ // A branch child rides with the parent cluster above it.+ if (row.entry.branchStem && cluster.length) {+ cluster[cluster.length - 1].push(row)++ continue+ }++ cluster.push([row])+ }++ flushGroup()++ return reordered ? out : rows+}++/** A cluster's identity: its root row's session id. */+function clusterId(rows: SidebarListRow[]): string {+ const root = rows[0]++ return root.kind === 'session' ? root.entry.session.id : ''+}++/** The reorderable ids of a rendered row list: root sessions, in render order. */+export function reorderableRowIds(rows: SidebarListRow[]): string[] {+ return rows.flatMap(row => (row.kind === 'session' && !row.entry.branchStem ? [row.entry.session.id] : []))+}diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section.tsxindex 684d217856f..37d6be11555 100644--- a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx+++ b/apps/desktop/src/app/chat/sidebar/sessions-section.tsx@@ -15,6 +15,7 @@ import { cn } from '@/lib/utils'import { sessionPinId } from '@/store/session'import { SidebarDateDivider, SidebarSectionMeta } from './chrome'+import { orderRowsWithinGroups, reorderableRowIds } from './order'import {EnteredProjectContent,ProjectOverviewRow,@@ -132,6 +133,11 @@ interface SidebarSessionsSectionProps {// When false the section header is static (no caret/toggle) and always open.collapsible?: booleansortable?: boolean+ // The persisted drag order, applied WITHIN each date group (see+ // orderRowsWithinGroups). Chronology decides the groups; this decides the+ // sequence inside one, so a reorder no longer costs the whole list its+ // dividers. Pinned passes nothing — its rows arrive in pin order already.+ manualOrderIds?: string[]// The flat session list is the only hand-reorderable surface (grouped/project// views sort deterministically), so it owns the one ReorderableList.onReorderSessions?: (ids: string[]) => void@@ -185,6 +191,7 @@ export function SidebarSessionsSection({labelIcon,collapsible = true,sortable = false,+ manualOrderIds,onReorderSessions,onReorderProjects,projectBackRow,@@ -214,15 +221,12 @@ export function SidebarSessionsSection({// The flat recents/pinned list is the only place sessions reorder by hand;// grouped/tree views always sort by creation date and never drag.const sessionsDraggable = sortable && !!onReorderSessions- // Pinned and manual-drag lists pass sessions already in the caller's order.- // Default recents stay dateGrouped and still re-sort roots by group recency- // so partition buckets stay truthful — but NEVER for pins, where a turn- // finishing was floating background tasks over the user's fixed ranking.- const preserveInputOrder = pinned || (sessionsDraggable && !dateGrouped)-+ // Only Pinned arrives pre-ordered as a flat sequence. Recents keeps its+ // recency sort — the drag order is layered on per date group below, so the+ // buckets stay truthful and a reorder never costs the list its dividers.const displayEntries = useMemo(- () => flattenSessionsWithBranches(sessions, { preserveOrder: preserveInputOrder }),- [sessions, preserveInputOrder]+ () => flattenSessionsWithBranches(sessions, { preserveOrder: pinned }),+ [sessions, pinned])const renderRow = useCallback(@@ -294,10 +298,20 @@ export function SidebarSessionsSection({)// Flat recents as list rows: grouped by recency when enabled, plain otherwise.- const flatRows: SidebarListRow[] = useMemo(- () => (dateGrouped ? groupEntriesByRecency(displayEntries) : toSessionRows(displayEntries)),- [dateGrouped, displayEntries]- )+ // The hand-picked order is then applied INSIDE each date group, so dragging a+ // row ranks it among its own day's chats instead of freezing the whole list+ // into an undated manual mode.+ const flatRows: SidebarListRow[] = useMemo(() => {+ const rows = dateGrouped ? groupEntriesByRecency(displayEntries) : toSessionRows(displayEntries)++ return manualOrderIds?.length ? orderRowsWithinGroups(rows, manualOrderIds) : rows+ }, [dateGrouped, displayEntries, manualOrderIds])++ // dnd-kit must see exactly the ids it renders, in render order: the sortable+ // set is derived from the rows, not from `sessions`. Feeding it the unrendered+ // session order made a drop compute its target index against a list the user+ // wasn't looking at — the drag that landed a row in the wrong slot.+ const sortableRowIds = useMemo(() => reorderableRowIds(flatRows), [flatRows])const flatVirtualized =!showEmptyState &&@@ -410,7 +424,7 @@ export function SidebarSessionsSection({inner =sessionsDraggable && onReorderSessions ? (- <ReorderableList ids={sessions.map(s => s.id)} onReorder={onReorderSessions} sensors={dndSensors}>+ <ReorderableList ids={sortableRowIds} onReorder={onReorderSessions} sensors={dndSensors}>{virtual}</ReorderableList>) : (@@ -418,7 +432,7 @@ export function SidebarSessionsSection({)} else if (sessionsDraggable && onReorderSessions) {inner = (- <ReorderableList ids={sessions.map(s => s.id)} onReorder={onReorderSessions} sensors={dndSensors}>+ <ReorderableList ids={sortableRowIds} onReorder={onReorderSessions} sensors={dndSensors}>{flatRows.map(row => renderListRow(row, true))}</ReorderableList>)