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(conversation-flow): coerce string createdAt before ordering (#20690)

Arvin Xu18638ef385f0
diff --git a/packages/conversation-flow/src/__tests__/stringTimestamp.test.ts b/packages/conversation-flow/src/__tests__/stringTimestamp.test.ts
new file mode 100644
index 00000000000..bc1c87c68e9
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/stringTimestamp.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import type { Message } from '../types/shared';
+
+/**
+ * Regression tests for string `createdAt` payloads (LOBE-14005 / T-614).
+ *
+ * The Gateway snapshot serializes timestamps as ISO strings while the static
+ * contract says `number`. Every ordering site used arithmetic comparison, so a
+ * string payload produced `NaN` comparators: `sort` kept traversal order and
+ * the renderer showed out-of-order messages with stale bubbles pinned at the
+ * bottom of the list. All ordering sites now coerce through `toTime`.
+ */
+const iso = (minutesAgo: number) =>
+ new Date(Date.UTC(2026, 9, 10, 12, 0, 0) - minutesAgo * 60_000).toISOString();
+
+const base = (overrides: Partial<Message> & { id: string }): Message =>
+ ({
+ content: '',
+ createdAt: Date.now(),
+ role: 'user',
+ ...overrides,
+ }) as Message;
+
+describe('string createdAt payloads (LOBE-14005)', () => {
+ it('orders a linear conversation chronologically when createdAt is ISO strings', () => {
+ const messages: Message[] = [
+ base({ id: 'msg-old', createdAt: iso(30), role: 'user', content: 'first' }),
+ base({
+ id: 'msg-a-old',
+ createdAt: iso(20),
+ role: 'assistant',
+ content: 'reply-old',
+ parentId: 'msg-old',
+ }),
+ base({
+ id: 'msg-new',
+ createdAt: iso(10),
+ role: 'user',
+ content: 'second',
+ parentId: 'msg-a-old',
+ }),
+ base({
+ id: 'msg-a-new',
+ createdAt: iso(5),
+ role: 'assistant',
+ content: 'reply-new',
+ parentId: 'msg-new',
+ }),
+ ];
+
+ const { flatList } = parse(messages);
+ expect(flatList.map((m) => m.id)).toEqual(['msg-old', 'msg-a-old', 'msg-new', 'msg-a-new']);
+ });
+
+ it('restores chronology when parallel tool continuations under different agents are appended out of order', () => {
+ // A fan-out turn with two tool results; each result continues under a
+ // different agent (so neither continuation is suppressed as an inactive
+ // branch). The DFS walk reaches tool-1's newer continuation before
+ // tool-2's older one; the final flatList.sort must restore the persisted
+ // chronology. With a string payload the numeric comparator used to be
+ // NaN and the stale continuation stayed pinned after the newer one.
+ const messages: Message[] = [
+ base({ id: 'root', createdAt: iso(40), role: 'user', content: 'go' }),
+ {
+ ...base({
+ id: 'a1',
+ createdAt: iso(35),
+ role: 'assistant',
+ content: 'fan out',
+ parentId: 'root',
+ }),
+ tools: [
+ { id: 'tool-1', type: 'default', apiName: 'x', identifier: 'p', arguments: '{}' },
+ { id: 'tool-2', type: 'default', apiName: 'y', identifier: 'p', arguments: '{}' },
+ ],
+ },
+ base({ id: 'tool-1', createdAt: iso(34), role: 'tool', parentId: 'a1', tool_call_id: 'tool-1' }),
+ base({ id: 'tool-2', createdAt: iso(33), role: 'tool', parentId: 'a1', tool_call_id: 'tool-2' }),
+ base({
+ id: 'cont-new',
+ createdAt: iso(25),
+ role: 'assistant',
+ content: 'newer continuation (tool-1)',
+ parentId: 'tool-1',
+ agentId: 'agent-a',
+ }),
+ base({
+ id: 'cont-old',
+ createdAt: iso(30),
+ role: 'assistant',
+ content: 'older continuation (tool-2)',
+ parentId: 'tool-2',
+ agentId: 'agent-b',
+ }),
+ ];
+
+ const { flatList } = parse(messages);
+ const order = flatList.map((m) => m.id);
+ expect(order).toContain('cont-old');
+ expect(order).toContain('cont-new');
+ // persisted chronology: older continuation renders first
+ expect(order.indexOf('cont-old')).toBeLessThan(order.indexOf('cont-new'));
+ });
+
+ it('does not regress numeric createdAt conversations', () => {
+ const t0 = Date.UTC(2026, 9, 10, 12, 0, 0);
+ const messages: Message[] = [
+ base({ id: 'm1', createdAt: t0 - 30_000, role: 'user', content: 'a' }),
+ base({ id: 'm2', createdAt: t0 - 20_000, role: 'assistant', content: 'b', parentId: 'm1' }),
+ base({ id: 'm3', createdAt: t0 - 10_000, role: 'user', content: 'c', parentId: 'm2' }),
+ ];
+
+ const { flatList } = parse(messages);
+ expect(flatList.map((m) => m.id)).toEqual(['m1', 'm2', 'm3']);
+ });
+});
diff --git a/packages/conversation-flow/src/doctor/diagnose.ts b/packages/conversation-flow/src/doctor/diagnose.ts
index b3e9d877ab8..e408d1644a2 100644
--- a/packages/conversation-flow/src/doctor/diagnose.ts
+++ b/packages/conversation-flow/src/doctor/diagnose.ts
@@ -1,4 +1,5 @@
import { parse } from '../parse';
+import { toTime } from '../utils/timestamp';
import type { Message, MessageGroupMetadata } from '../types';
import type { RepairOp, TopicDiagnosis, TopicIssue } from './types';
@@ -73,8 +74,8 @@ const canAnchor = (message: Message): boolean =>
message.role !== 'tool' && !getSignal(message) && !isEmptyShell(message);
const timeSpan = (messages: Message[]): [number, number] => [
- Math.min(...messages.map((m) => m.createdAt)),
- Math.max(...messages.map((m) => m.createdAt)),
+ Math.min(...messages.map((m) => toTime(m.createdAt))),
+ Math.max(...messages.map((m) => toTime(m.createdAt))),
];
const overlaps = (a: [number, number], b: [number, number]): boolean =>
@@ -96,7 +97,7 @@ export const diagnoseTopic = (
const mainFlow = messages.filter((m) => !m.threadId);
if (mainFlow.length === 0) return { hiddenCount: 0, issues: [], patch: [] };
- const sorted = [...mainFlow].sort((a, b) => a.createdAt - b.createdAt);
+ const sorted = [...mainFlow].sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt));
const byId = new Map(sorted.map((m) => [m.id, m]));
const childrenOf = new Map<string, Message[]>();
@@ -174,8 +175,8 @@ export const diagnoseTopic = (
// a message inside this very section can't anchor it.
const sectionIds = new Set(section.map((m) => m.id));
const anchor = sorted
- .filter((m) => canAnchor(m) && m.createdAt < root.createdAt && !sectionIds.has(m.id))
- .sort((a, b) => b.createdAt - a.createdAt)[0];
+ .filter((m) => canAnchor(m) && toTime(m.createdAt) < toTime(root.createdAt) && !sectionIds.has(m.id))
+ .sort((a, b) => toTime(b.createdAt) - toTime(a.createdAt))[0];
if (!anchor) continue;
report(
@@ -216,7 +217,7 @@ export const diagnoseTopic = (
const runIds = new Set(runSubtree.map((m) => m.id));
const anchor = [...runSubtree]
.filter((m) => canAnchor(m))
- .sort((a, b) => b.createdAt - a.createdAt)[0];
+ .sort((a, b) => toTime(b.createdAt) - toTime(a.createdAt))[0];
// The shape is wrong, but if the reader still gets everything on screen there is
// nothing to fix and no reason to rewrite the user's history.
@@ -256,7 +257,7 @@ export const diagnoseTopic = (
const ownIds = new Set(ownSubtree.map((m) => m.id));
const candidates = sorted.filter(
- (m) => m.role === 'tool' && m.createdAt < message.createdAt && !ownIds.has(m.id),
+ (m) => m.role === 'tool' && toTime(m.createdAt) < toTime(message.createdAt) && !ownIds.has(m.id),
);
// The signal names the tool call it is reacting to; fall back to the most recent tool
// result only when that call cannot be found.
diff --git a/packages/conversation-flow/src/transformation/BranchResolver.ts b/packages/conversation-flow/src/transformation/BranchResolver.ts
index 8209f459188..f76cec88dd7 100644
--- a/packages/conversation-flow/src/transformation/BranchResolver.ts
+++ b/packages/conversation-flow/src/transformation/BranchResolver.ts
@@ -1,4 +1,5 @@
import type { IdNode, Message } from '../types';
+import { toTime } from '../utils/timestamp';
/**
* BranchResolver - Handles branch resolution logic
@@ -151,7 +152,7 @@ export class BranchResolver {
if (descendant?.threadId) continue;
if (descendant?.role === 'user') {
- const timestamp = descendant.createdAt;
+ const timestamp = toTime(descendant.createdAt);
if (timestamp > latestTimestamp) {
latestTimestamp = timestamp;
selectedBranchId = branchId;
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 977f8263ee4..6db87ca614e 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -1,5 +1,7 @@
import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';
+import { toTime } from '../utils/timestamp';
+
import { isInThreadScope } from '../indexing';
import type { Message, MessageGroupMetadata, ThreadScope } from '../types';
import type { BranchResolver } from './BranchResolver';
@@ -124,7 +126,7 @@ export class FlatListBuilder {
// leaving a stale assistant response at the request tail. A stable final sort
// restores the persisted chronology without changing group membership or the
// order of nodes with identical timestamps.
- flatList.sort((first, second) => first.createdAt - second.createdAt);
+ flatList.sort((first, second) => toTime(first.createdAt) - toTime(second.createdAt));
return flatList;
}
@@ -729,8 +731,8 @@ export class FlatListBuilder {
message?.role === 'user' &&
!message.threadId &&
!processedIds.has(id) &&
- message.createdAt >= assistant.createdAt &&
- message.createdAt <= tail.createdAt
+ toTime(message.createdAt) >= toTime(assistant.createdAt) &&
+ toTime(message.createdAt) <= toTime(tail.createdAt)
);
});
if (interruptions.length === 0) continue;
@@ -878,7 +880,7 @@ export class FlatListBuilder {
.filter((child): child is Message => !!child && !processedIds.has(child.id))
.map((child) => ({ child, parentId })),
)
- .sort((a, b) => a.child.createdAt - b.child.createdAt)[0];
+ .sort((a, b) => toTime(a.child.createdAt) - toTime(b.child.createdAt))[0];
}
private shouldDrainParentContinuations(parentId: string, processedIds: Set<string>): boolean {
@@ -991,7 +993,7 @@ export class FlatListBuilder {
const firstColumnMessages = childIds.map((id) => this.messageMap.get(id)).filter(Boolean);
const createdAt =
firstColumnMessages.length > 0
- ? Math.min(...firstColumnMessages.map((m) => m!.createdAt))
+ ? Math.min(...firstColumnMessages.map((m) => toTime(m!.createdAt)))
: parentMessage.createdAt;
const updatedAt =
firstColumnMessages.length > 0
@@ -1086,7 +1088,7 @@ export class FlatListBuilder {
const allMemberMessages = memberChildIds.map((id) => this.messageMap.get(id)).filter(Boolean);
const createdAt =
allMemberMessages.length > 0
- ? Math.min(...allMemberMessages.map((m) => m!.createdAt))
+ ? Math.min(...allMemberMessages.map((m) => toTime(m!.createdAt)))
: parentMessage.createdAt;
const updatedAt =
allMemberMessages.length > 0
@@ -1121,7 +1123,7 @@ export class FlatListBuilder {
activeColumnId,
columns: columns as any,
content: '',
- createdAt: Math.min(...members.map((m) => m.createdAt)),
+ createdAt: Math.min(...members.map((m) => toTime(m.createdAt))),
extra: {
groupMode: group.mode,
parentMessageId: group.parentMessageId,
@@ -1535,7 +1537,7 @@ export class FlatListBuilder {
}
// Sort by createdAt to maintain order
- taskMessages.sort((a, b) => a.createdAt - b.createdAt);
+ taskMessages.sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt));
// Generate ID with parent message id and all task message ids
const taskIdsStr = taskMessages.map((t) => t.id).join('-');
@@ -1544,7 +1546,7 @@ export class FlatListBuilder {
// Calculate timestamps from task messages
const createdAt =
taskMessages.length > 0
- ? Math.min(...taskMessages.map((m) => m.createdAt))
+ ? Math.min(...taskMessages.map((m) => toTime(m.createdAt)))
: parentMessage.createdAt;
const updatedAt =
taskMessages.length > 0
@@ -1583,7 +1585,7 @@ export class FlatListBuilder {
}
// Sort by createdAt to maintain order
- taskMessages.sort((a, b) => a.createdAt - b.createdAt);
+ taskMessages.sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt));
// Generate ID with parent message id and all task message ids
const taskIdsStr = taskMessages.map((t) => t.id).join('-');
@@ -1592,7 +1594,7 @@ export class FlatListBuilder {
// Calculate timestamps from task messages
const createdAt =
taskMessages.length > 0
- ? Math.min(...taskMessages.map((m) => m.createdAt))
+ ? Math.min(...taskMessages.map((m) => toTime(m.createdAt)))
: parentMessage.createdAt;
const updatedAt =
taskMessages.length > 0
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index 9a554d4662f..efe2c2752d1 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -1,4 +1,5 @@
import { isInThreadScope } from '../indexing';
+import { toTime } from '../utils/timestamp';
import type {
ContextNode,
IdNode,
@@ -357,7 +358,7 @@ export class MessageCollector {
.flatMap((parentId) => this.childrenOf(allMessages, parentId))
.filter((m) => m.role !== 'tool' && !processedIds.has(m.id))
.filter((m) => m.role === 'assistant' && m.agentId === groupAgentId && !getMessageSignal(m))
- .sort((a, b) => a.createdAt - b.createdAt || position.get(a.id)! - position.get(b.id)!);
+ .sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt) || position.get(a.id)! - position.get(b.id)!);
const activeId = this.resolveActiveContinuationId(candidates, currentAssistant);
if (!activeId) {
@@ -534,7 +535,7 @@ export class MessageCollector {
completions.push(child);
}
}
- completions.sort((a, b) => a.createdAt - b.createdAt);
+ completions.sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt));
return completions;
}
@@ -634,7 +635,7 @@ export class MessageCollector {
(c) =>
c.msg?.role === 'assistant' && c.msg.agentId === groupAgentId && !getMessageSignal(c.msg),
)
- .sort((a, b) => a.msg!.createdAt - b.msg!.createdAt);
+ .sort((a, b) => toTime(a.msg!.createdAt) - toTime(b.msg!.createdAt));
const activeId = this.resolveActiveContinuationId(
eligible.map((c) => c.msg!),
diff --git a/packages/conversation-flow/src/utils/timestamp.ts b/packages/conversation-flow/src/utils/timestamp.ts
new file mode 100644
index 00000000000..45a7826a92c
--- /dev/null
+++ b/packages/conversation-flow/src/utils/timestamp.ts
@@ -0,0 +1,18 @@
+/**
+ * Coerce a message timestamp into a numeric epoch value.
+ *
+ * The static contract on `UIChatMessage` is `createdAt: number`, but real-world
+ * payloads violate it: the Gateway snapshot (LOBE-14005) serializes timestamps
+ * as ISO strings, and historical DB rows can carry the same shape. Arithmetic
+ * or relational comparison on a string silently produces `NaN`, which disables
+ * every sort that relies on it — the renderer then falls back to traversal
+ * order, surfacing as "out-of-order messages pinned at the bottom of the list".
+ *
+ * `toTime` accepts `number | string | Date` (and anything `new Date()` can
+ * parse), so every ordering site in this package stays correct regardless of
+ * which shape the caller passed in.
+ */
+export const toTime = (createdAt: number | string | Date): number => {
+ if (typeof createdAt === 'number') return createdAt;
+ return new Date(createdAt).getTime();
+};