Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(topic): sort sidebar by activity time to stop list jumping (#16868)

YuTengjing7e0993ecd551
diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.ts
index e51175303af..dea5ab25a96 100644
--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts
@@ -196,6 +196,43 @@ describe('TopicModel - Query', () => {
expect(result.items.map((t) => t.id)).toEqual(['waiting', 'active']);
});
+ it('returns the latest message activity as `sortUpdatedAt` while `updatedAt` stays the row value', async () => {
+ // The client sorts the sidebar by `sortUpdatedAt`, so it must carry the same
+ // activity time the server ORDER BY uses (topicActivityAt) β€” otherwise the two
+ // sorts disagree and the list jumps. `updatedAt` stays the raw row value so
+ // rename/favorite edits still show a real edit time. (LOBE-11543)
+ await serverDB.insert(topics).values([
+ { id: 'has-msg', sessionId, updatedAt: new Date('2023-01-01'), userId },
+ { id: 'no-msg', sessionId, updatedAt: new Date('2023-03-01'), userId },
+ ]);
+ // An assistant message (any role counts) that is newer than the row.
+ await serverDB.insert(messages).values([
+ {
+ id: 'has-msg-latest',
+ role: 'assistant',
+ topicId: 'has-msg',
+ updatedAt: new Date('2023-06-01'),
+ userId,
+ },
+ ]);
+
+ const result = await topicModel.query({ containerId: sessionId });
+
+ const byId = Object.fromEntries(result.items.map((t) => [t.id, t]));
+ // sortUpdatedAt reflects the message time (2023-06), NOT its row updatedAt (2023-01).
+ expect(byId['has-msg'].sortUpdatedAt?.toISOString()).toBe(
+ new Date('2023-06-01').toISOString(),
+ );
+ // updatedAt still carries the raw row value (2023-01), untouched by message activity.
+ expect(byId['has-msg'].updatedAt.toISOString()).toBe(new Date('2023-01-01').toISOString());
+ // no-msg has no messages β†’ sortUpdatedAt COALESCE falls back to the row updatedAt.
+ expect(byId['no-msg'].sortUpdatedAt?.toISOString()).toBe(
+ new Date('2023-03-01').toISOString(),
+ );
+ // And the order follows the activity time (2023-06 before 2023-03).
+ expect(result.items.map((t) => t.id)).toEqual(['has-msg', 'no-msg']);
+ });
+
it('should query topics with pagination', async () => {
await serverDB.insert(topics).values([
{ id: '1', userId, updatedAt: new Date('2023-01-01') },
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 28aaedb2be1..10ddb8dbb7e 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -298,6 +298,14 @@ export class TopicModel {
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
+ // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β€” the
+ // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE
+ // fallback to the row's own updatedAt). Keeping it separate from the
+ // display `updatedAt` above matches the client-side sort key to the server
+ // order (otherwise the two disagree and the list visibly jumps) while a
+ // rename/favorite edit still shows its real edit time. See rankTopics for
+ // the same activity-time pattern. (LOBE-11543)
+ sortUpdatedAt: topicActivityAt,
...detailColumns,
} as any)
.from(topics)
@@ -360,6 +368,14 @@ export class TopicModel {
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
+ // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β€” the
+ // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE
+ // fallback to the row's own updatedAt). Keeping it separate from the
+ // display `updatedAt` above matches the client-side sort key to the server
+ // order (otherwise the two disagree and the list visibly jumps) while a
+ // rename/favorite edit still shows its real edit time. See rankTopics for
+ // the same activity-time pattern. (LOBE-11543)
+ sortUpdatedAt: topicActivityAt,
...detailColumns,
} as any)
.from(topics)
@@ -418,6 +434,14 @@ export class TopicModel {
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
+ // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β€” the
+ // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE
+ // fallback to the row's own updatedAt). Keeping it separate from the
+ // display `updatedAt` above matches the client-side sort key to the server
+ // order (otherwise the two disagree and the list visibly jumps) while a
+ // rename/favorite edit still shows its real edit time. See rankTopics for
+ // the same activity-time pattern. (LOBE-11543)
+ sortUpdatedAt: topicActivityAt,
...detailColumns,
} as any)
.from(topics)
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index dd19dd3550c..1637d41e02f 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -250,6 +250,14 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
messageCount?: number | null;
metadata?: ChatTopicMetadata;
sessionId?: string;
+ /**
+ * Sort key for the sidebar list: the topic's latest message-activity time
+ * (server `topicActivityAt`), falling back to `updatedAt`. Kept separate from
+ * `updatedAt` so the client sort matches the server ORDER BY (no list jumping)
+ * while `updatedAt` still reflects real row edits like rename/favorite.
+ * (LOBE-11543)
+ */
+ sortUpdatedAt?: number;
status?: ChatTopicStatus | null;
title: string;
/** Server-side mock until real token aggregation lands. */
diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.ts
index c8388ebe324..7bf7bea8faa 100644
--- a/packages/utils/src/client/topic.test.ts
+++ b/packages/utils/src/client/topic.test.ts
@@ -220,6 +220,49 @@ describe('groupTopicsByUpdatedTime', () => {
// By updatedAt: grouped under yesterday
expect(byUpdated[0].id).toBe('yesterday');
});
+
+ it('should group and sort by sortUpdatedAt (activity time) when present, ignoring updatedAt', () => {
+ const lastYear = dayjs().subtract(1, 'year').valueOf();
+ const today = dayjs().valueOf();
+
+ // Row was edited last year (updatedAt) but had message activity today
+ // (sortUpdatedAt) β€” the sidebar must group it under "today". (LOBE-11543)
+ const topic: ChatTopic = {
+ id: 'active',
+ title: 'Recently active',
+ createdAt: lastYear,
+ updatedAt: lastYear,
+ sortUpdatedAt: today,
+ };
+
+ const result = groupTopicsByUpdatedTime([topic]);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('today');
+ });
+
+ it('should order rows by sortUpdatedAt (activity) over updatedAt (row edit time)', () => {
+ const base = dayjs().subtract(1, 'month').valueOf();
+ // `a` has an older row edit time but newer activity β†’ must sort first.
+ const a: ChatTopic = {
+ id: 'a',
+ title: 'Older edit, newer activity',
+ createdAt: base,
+ updatedAt: dayjs().hour(9).valueOf(),
+ sortUpdatedAt: dayjs().hour(11).valueOf(),
+ };
+ const b: ChatTopic = {
+ id: 'b',
+ title: 'Newer edit, older activity',
+ createdAt: base,
+ updatedAt: dayjs().hour(10).valueOf(),
+ sortUpdatedAt: dayjs().hour(10).valueOf(),
+ };
+
+ const result = groupTopicsByUpdatedTime([b, a]);
+
+ expect(result[0].children.map((t) => t.id)).toEqual(['a', 'b']);
+ });
});
describe('working directory topic helpers', () => {
diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.ts
index b174eee5c65..39c34622268 100644
--- a/packages/utils/src/client/topic.ts
+++ b/packages/utils/src/client/topic.ts
@@ -71,6 +71,15 @@ const sortGroups = (groups: GroupedTopic[]): GroupedTopic[] => {
});
};
+/**
+ * Resolve the timestamp a topic sorts/groups by for the given field. For
+ * `updatedAt` this is the server-provided `sortUpdatedAt` (latest message
+ * activity), falling back to the raw `updatedAt` when absent β€” so the sidebar
+ * order matches the server ORDER BY and doesn't jump. (LOBE-11543)
+ */
+export const getTopicSortTime = (topic: ChatTopic, field: 'createdAt' | 'updatedAt'): number =>
+ field === 'updatedAt' ? (topic.sortUpdatedAt ?? topic.updatedAt) : topic.createdAt;
+
// Generic time-based grouping parameterized by field
const groupTopicsByField = (
topics: ChatTopic[],
@@ -78,11 +87,13 @@ const groupTopicsByField = (
): GroupedTopic[] => {
if (!topics.length) return [];
- const sortedTopics = [...topics].sort((a, b) => b[field] - a[field]);
+ const sortedTopics = [...topics].sort(
+ (a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field),
+ );
const groupsMap = new Map<TimeGroupId, ChatTopic[]>();
for (const topic of sortedTopics) {
- const groupId = getTopicGroupId(topic[field]);
+ const groupId = getTopicGroupId(getTopicSortTime(topic, field));
const existing = groupsMap.get(groupId);
if (existing) {
existing.push(topic);
@@ -162,7 +173,7 @@ export const groupTopicsByProject = (
// Sort topics inside each group by chosen field desc
for (const group of groupsMap.values()) {
- group.children.sort((a, b) => b[field] - a[field]);
+ group.children.sort((a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field));
}
const groups: GroupedTopic[] = Array.from(groupsMap.entries()).map(
@@ -177,8 +188,8 @@ export const groupTopicsByProject = (
return groups.sort((a, b) => {
if (a.id === NO_PROJECT_GROUP_ID) return 1;
if (b.id === NO_PROJECT_GROUP_ID) return -1;
- const aTime = a.children[0]?.[field] ?? 0;
- const bTime = b.children[0]?.[field] ?? 0;
+ const aTime = a.children[0] ? getTopicSortTime(a.children[0], field) : 0;
+ const bTime = b.children[0] ? getTopicSortTime(b.children[0], field) : 0;
return bTime - aTime;
});
};
@@ -251,7 +262,7 @@ export const groupTopicsByStatus = (
// Sort topics inside each group by chosen field desc
for (const children of groupsMap.values()) {
- children.sort((a, b) => b[field] - a[field]);
+ children.sort((a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field));
}
// Emit only non-empty groups, in the fixed priority order
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index b1ea0129281..edc45a3dc1f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -1978,8 +1978,8 @@ describe('ConversationLifecycle actions', () => {
});
});
- describe('optimistic topic updatedAt', () => {
- it('should optimistically update topic updatedAt when sending message to existing topic', async () => {
+ describe('optimistic topic sortUpdatedAt', () => {
+ it('should optimistically bump topic sortUpdatedAt when sending message to existing topic', async () => {
const { result } = renderHook(() => useChatStore());
const topicId = TEST_IDS.TOPIC_ID;
@@ -2001,17 +2001,17 @@ describe('ConversationLifecycle actions', () => {
});
});
- // Should call internal_dispatchTopic with updateTopic to touch updatedAt
+ // Should call internal_dispatchTopic with updateTopic to bump the sidebar sort key
expect(dispatchTopicSpy).toHaveBeenCalledWith(
expect.objectContaining({
type: 'updateTopic',
id: topicId,
- value: { updatedAt: expect.any(Number) },
+ value: { sortUpdatedAt: expect.any(Number) },
}),
);
});
- it('should NOT optimistically update topic updatedAt when server returns topics (new topic)', async () => {
+ it('should NOT optimistically bump topic sortUpdatedAt when server returns topics (new topic)', async () => {
const { result } = renderHook(() => useChatStore());
const dispatchTopicSpy = vi.spyOn(result.current, 'internal_dispatchTopic');
@@ -2035,9 +2035,9 @@ describe('ConversationLifecycle actions', () => {
});
});
- // Should NOT call internal_dispatchTopic with updateTopic for updatedAt
+ // Should NOT call internal_dispatchTopic with updateTopic for sortUpdatedAt
const updateTopicCalls = dispatchTopicSpy.mock.calls.filter(
- ([payload]) => payload.type === 'updateTopic' && 'updatedAt' in (payload.value || {}),
+ ([payload]) => payload.type === 'updateTopic' && 'sortUpdatedAt' in (payload.value || {}),
);
expect(updateTopicCalls).toHaveLength(0);
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index a63b08801c3..250565fd955 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1196,11 +1196,14 @@ export class ConversationLifecycleActionImpl {
this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });
void Promise.resolve(this.#get().refreshTopic()).catch(console.error);
} else if (operationContext.topicId) {
- // Optimistically update topic's updatedAt so sidebar re-groups immediately
+ // Optimistically bump the sort key (`sortUpdatedAt`, the sidebar's activity-time
+ // sort/group key) so the topic jumps to the top immediately, before the SWR
+ // refetch returns the server's fresh `topicActivityAt`. Bumping `updatedAt` here
+ // would no longer reorder anything β€” the sidebar sorts by `sortUpdatedAt`. (LOBE-11543)
this.#get().internal_dispatchTopic({
type: 'updateTopic',
id: operationContext.topicId,
- value: { updatedAt: Date.now() },
+ value: { sortUpdatedAt: Date.now() },
});
}
diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.ts
index d8d9cc8d4f3..17d14455bce 100644
--- a/src/store/chat/slices/topic/reducer.ts
+++ b/src/store/chat/slices/topic/reducer.ts
@@ -53,6 +53,10 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
favorite: false,
id: payload.value.id ?? Date.now().toString(),
sessionId: payload.value.sessionId || undefined,
+ // A brand-new topic is fresh activity: seed the sidebar sort key so it
+ // lands at the top immediately, matching the server's `topicActivityAt`
+ // once the real row is fetched. (LOBE-11543)
+ sortUpdatedAt: Date.now(),
updatedAt: Date.now(),
});
@@ -72,19 +76,13 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
// Only update if the merged value is different from current (excluding updatedAt).
// Compare against a plain snapshot, not the raw draft proxy β€” see message/reducer.ts.
if (!isEqual(current(currentTopic), mergedTopic)) {
- // Status flips (running/unread/read bookkeeping) are not user activity β€”
- // bumping updatedAt here reorders the updatedAt-sorted sidebar on every
- // run end / topic read, and the bump reverts on the next refetch (the
- // server orders by latest-message time), so rows visibly jump around.
- const isStatusOnlyWrite = Object.keys(value).every((key) => key === 'status');
-
- if (isStatusOnlyWrite) {
- draftState[topicIndex] = mergedTopic;
- } else {
- // TODO: updatedAt type needs to be changed to Date later
- // @ts-ignore
- draftState[topicIndex] = { ...mergedTopic, updatedAt: new Date() };
- }
+ // Bump `updatedAt` (display/edit time) on every real write. The sidebar
+ // no longer sorts by `updatedAt` β€” it sorts by `sortUpdatedAt` (activity
+ // time) β€” so a status flip bumping `updatedAt` here can't reorder the
+ // list; only an explicit `sortUpdatedAt` in `value` moves a row. (LOBE-11543)
+ // TODO: updatedAt type needs to be changed to Date later
+ // @ts-ignore
+ draftState[topicIndex] = { ...mergedTopic, updatedAt: new Date() };
}
}
});
@@ -105,6 +103,10 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
...nextTopic,
...value,
id: nextId,
+ // Resolving a first-send optimistic topic to its real id is fresh activity:
+ // keep it pinned to the top via the sidebar sort key (`sortUpdatedAt`), not
+ // just `updatedAt` which the sidebar no longer sorts by. (LOBE-11543)
+ sortUpdatedAt: Date.now(),
updatedAt: Date.now(),
};
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 61f3ae8209d..a0568164f7c 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -10,6 +10,7 @@ import {
type TopicSortBy,
} from '@/types/topic';
import {
+ getTopicSortTime,
groupTopicsByProject,
groupTopicsByStatus,
groupTopicsByTime,
@@ -130,7 +131,7 @@ const isSearchingTopic = (s: ChatStoreState) => s.isSearchingTopic;
const sortTopics = (topics: ChatTopic[], sortBy: TopicSortBy): ChatTopic[] => {
const field = sortBy === 'createdAt' ? 'createdAt' : 'updatedAt';
- return [...topics].sort((a, b) => b[field] - a[field]);
+ return [...topics].sort((a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field));
};
// Limit topics for sidebar display based on user's page size preference