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: anchor WS reconnect elapsed timers to the server run start (#19700)

Arvin Xuc2cea4452f93
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index 85e74d562ba..a324b56b0b9 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -399,6 +399,51 @@ describe('TopicModel', () => {
expect(visitorItems.map((t) => t.id)).toEqual(['t-visitor']);
});
+ // Sidebar elapsed timers for running topics that have no local operation
+ // (post-refresh, non-active rows) anchor on this column β€” without it the
+ // timer renders nothing at all.
+ it('resolves runStartedAt for running topics and nulls it otherwise', async () => {
+ await serverDB.insert(agents).values({ id: 'agent-run', userId });
+ await serverDB.insert(topics).values([
+ { agentId: 'agent-run', id: 't-q-run', status: 'running', title: 'run', userId },
+ { agentId: 'agent-run', id: 't-q-active', status: 'active', title: 'act', userId },
+ ]);
+ await serverDB.insert(agentOperations).values([
+ // Top-level running op of the current run β€” this is the anchor.
+ {
+ id: 'op-q-run',
+ startedAt: new Date('2026-01-02T00:00:00Z'),
+ status: 'running',
+ topicId: 't-q-run',
+ userId,
+ },
+ // A sub-operation (callAgent) must not win the anchor.
+ {
+ id: 'op-q-child',
+ parentOperationId: 'op-run',
+ startedAt: new Date('2026-01-03T00:00:00Z'),
+ status: 'running',
+ topicId: 't-q-run',
+ userId,
+ },
+ // An abandoned running row under the finished topic must not
+ // resurrect a timer.
+ {
+ id: 'op-q-stale',
+ startedAt: new Date('2026-01-01T00:00:00Z'),
+ status: 'running',
+ topicId: 't-q-active',
+ userId,
+ },
+ ]);
+
+ const { items } = await topicModel.query({ agentId: 'agent-run' });
+ const byId = Object.fromEntries(items.map((t) => [t.id, t]));
+
+ expect(byId['t-q-run'].runStartedAt).toEqual(new Date('2026-01-02T00:00:00Z'));
+ expect(byId['t-q-active'].runStartedAt).toBeNull();
+ });
+
describe('status filtering & ordering', () => {
it('excludes topics whose status is in excludeStatuses but keeps null status', async () => {
await serverDB.insert(agents).values({ id: 'agent-s', userId });
@@ -545,6 +590,7 @@ describe('TopicModel', () => {
hooks: [{ event: 'onComplete', type: 'webhook', url: 'https://example.com' } as any],
operationId: 'op-1',
scope: 'main',
+ startedAt: '2026-01-02T00:00:00.000Z',
threadId: 'thd-1',
},
},
@@ -563,6 +609,9 @@ describe('TopicModel', () => {
heteroType: 'claude-code',
operationId: 'op-1',
scope: 'main',
+ // startedAt rides along so the visitor's reconnect can anchor elapsed
+ // time; the rest of metadata stays stripped.
+ startedAt: expect.any(String),
threadId: 'thd-1',
});
expect(item).not.toHaveProperty('metadata');
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 98d85429701..687fa4165e4 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -133,6 +133,8 @@ export interface VisitorRunningOperation {
heteroType?: string | null;
operationId: string;
scope?: string;
+ /** Liveness/elapsed-time stamp β€” see `useGatewayReconnect`'s `startedAt`. */
+ startedAt?: string;
threadId?: string | null;
}
@@ -179,8 +181,9 @@ const pickVisitorRunningOperation = (
const runningOperation = metadata?.runningOperation;
if (!runningOperation) return null;
- const { assistantMessageId, operationId, scope, threadId, heteroType } = runningOperation;
- return { assistantMessageId, heteroType, operationId, scope, threadId };
+ const { assistantMessageId, heteroType, operationId, scope, startedAt, threadId } =
+ runningOperation;
+ return { assistantMessageId, heteroType, operationId, scope, startedAt, threadId };
};
export interface CreateTopicParams {
@@ -527,6 +530,36 @@ export class TopicModel {
sql<Date>`COALESCE((${latestMessageAtSubquery}), ${topics.updatedAt})`.mapWith(
topics.updatedAt,
);
+
+ // When the topic's current run started, so a sidebar can show live elapsed
+ // time instead of `updatedAt` (which moves on every message write). The
+ // latest *top-level* running operation is the current run: sub-operations
+ // (callAgent) would restart the clock at their own spawn time, and an
+ // abandoned `running` row from a crashed earlier run sorts below the live
+ // one. Not scoped by `ownership()` β€” in a workspace the run may have been
+ // started by another member, and the topic join is already ownership-gated.
+ // Same shape as the `queryTopics` feed's column of the same name.
+ const runStartedAtSubquery = this.db
+ .select({ value: agentOperations.startedAt })
+ .from(agentOperations)
+ .where(
+ and(
+ eq(agentOperations.topicId, topics.id),
+ eq(agentOperations.status, 'running'),
+ isNull(agentOperations.parentOperationId),
+ isNotNull(agentOperations.startedAt),
+ ),
+ )
+ .orderBy(desc(agentOperations.startedAt))
+ .limit(1);
+
+ // CASE-gated so only rows that are actually running pay for the lookup β€”
+ // and a stale running op under a finished topic can't resurrect a timer.
+ const runStartedAtColumn =
+ sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN (${runStartedAtSubquery}) ELSE NULL END`
+ .mapWith(agentOperations.startedAt)
+ .as('run_started_at');
+
const orderBy = buildTopicOrderBy(topicActivityAt, sortBy);
const detailColumns = withDetails
@@ -598,6 +631,7 @@ export class TopicModel {
metadata: topics.metadata,
model: topics.model,
provider: topics.provider,
+ runStartedAt: runStartedAtColumn,
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
@@ -676,6 +710,7 @@ export class TopicModel {
metadata: topics.metadata,
model: topics.model,
provider: topics.provider,
+ runStartedAt: runStartedAtColumn,
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
@@ -748,6 +783,7 @@ export class TopicModel {
metadata: topics.metadata,
model: topics.model,
provider: topics.provider,
+ runStartedAt: runStartedAtColumn,
sessionId: topics.sessionId,
status: topics.status,
title: topics.title,
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 2c2cad45f0c..b454e533604 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -658,6 +658,15 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
*/
model?: string | null;
provider?: string | null;
+ /**
+ * Start time of the topic's current run β€” the latest top-level running
+ * `agent_operations.startedAt`, only set while `status === 'running'` and
+ * null otherwise. Present on list queries that select the column (per-agent
+ * / group sidebar lists, the queryTopics feed); absent on slim projections.
+ * Lets lists show live elapsed time for runs that have no local operation
+ * (e.g. after a page refresh, where only the active topic is reconnected).
+ */
+ runStartedAt?: Date | string | number | null;
sessionId?: string;
/**
* Sort key for the sidebar list: the topic's latest message-activity time
diff --git a/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx
index 27a16c9013f..39634c24bda 100644
--- a/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx
+++ b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx
@@ -183,6 +183,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
fav={topic.favorite}
id={topic.id}
metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
status={topic.status}
title={topic.title}
userId={topic.userId}
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index 0162a86f4ee..15db1675453 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -219,6 +219,59 @@ describe('TopicItem active state', () => {
expect(screen.getByText('00:33')).toBeInTheDocument();
});
+ // After a page refresh only the ACTIVE topic is reconnected into the
+ // in-memory operation store; every other running row has no local
+ // operation and its timer must fall back to the server-list's
+ // `runStartedAt` or it renders nothing (the arrow-pointed rows in the bug
+ // report's screenshot).
+ it('falls back to the server runStartedAt when no local operation exists', () => {
+ vi.useFakeTimers();
+ const now = Date.UTC(2026, 0, 1, 0, 2, 37);
+ vi.setSystemTime(now);
+ runningStartTimeMock.value = undefined;
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+
+ render(
+ <TopicItem
+ id="tpc_test"
+ runStartedAt={new Date(now - 157_000).toISOString()}
+ status="running"
+ title="Topic"
+ />,
+ );
+
+ expect(screen.getByText('02:37')).toBeInTheDocument();
+ });
+
+ it('prefers the local operation start over the server runStartedAt', () => {
+ vi.useFakeTimers();
+ const now = Date.UTC(2026, 0, 1, 0, 0, 33);
+ vi.setSystemTime(now);
+ runningStartTimeMock.value = now - 33_000;
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+
+ render(
+ <TopicItem
+ id="tpc_test"
+ runStartedAt={new Date(now - 157_000).toISOString()}
+ status="running"
+ title="Topic"
+ />,
+ );
+
+ expect(screen.getByText('00:33')).toBeInTheDocument();
+ });
+
it('preserves the masked running-tail icon state for the active topic', () => {
activeTopicIdMock.value = 'tpc_test';
agentRuntimeRunningMock.value = true;
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index c369b96e189..1729ebcbb13 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -141,15 +141,32 @@ const getWorkingDirectoryDisplay = (metadata: ChatTopicMetadata | undefined) =>
interface RunningElapsedTimeProps {
agentId?: string;
+ /**
+ * Server-side start of the topic's current run (list query's
+ * `runStartedAt`). Fallback for topics that are running on the server but
+ * have no local operation β€” after a page refresh only the ACTIVE topic is
+ * reconnected into the in-memory store, so every other running row would
+ * otherwise render no timer at all.
+ */
+ runStartedAt?: Date | string | number | null;
topicId: string;
}
-const RunningElapsedTime = memo<RunningElapsedTimeProps>(({ agentId, topicId }) => {
- const startTime = useChatStore(
+const RunningElapsedTime = memo<RunningElapsedTimeProps>(({ agentId, runStartedAt, topicId }) => {
+ const localStartTime = useChatStore(
agentId
? operationSelectors.getVisibleAgentRuntimeStartTimeByContext({ agentId, topicId })
: () => undefined,
);
+
+ // Prefer the in-memory operation: it tracks the local run precisely and
+ // updates the moment a run starts/stops. The server stamp only covers the
+ // refresh case above. Normalize like the server fallback does β€” the value
+ // crosses the wire as an ISO string.
+ const serverStartTimeMs = runStartedAt == null ? undefined : new Date(runStartedAt).getTime();
+ const startTime =
+ localStartTime ?? (Number.isFinite(serverStartTimeMs) ? serverStartTimeMs : undefined);
+
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
@@ -175,7 +192,13 @@ interface TopicItemProps {
id?: string;
metadata?: ChatTopicMetadata;
/**
- * Show the topic's project directory as a second line under the title. Used by
+ * Server-side start of the topic's current run (list query's
+ * `runStartedAt`). Lets running topics that have no local operation
+ * (refreshed, non-active) still show an elapsed timer β€” see
+ * `RunningElapsedTime`.
+ */
+ runStartedAt?: Date | string | number | null;
+ /** Show the topic's project directory as a second line under the title. Used by
* the by-status grouping, where the row otherwise carries no project context
* (by-project mode already puts the directory in the group header).
*/
@@ -204,6 +227,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
title,
fav,
metadata,
+ runStartedAt,
status,
showWorkingDirectory,
userId,
@@ -514,7 +538,11 @@ const TopicItemRow = memo<TopicItemRowProps>(
extra={
<>
<TopicMigrationIndicator agentId={activeAgentId} topicId={id} />
- <RunningElapsedTime agentId={activeAgentId} topicId={id} />
+ <RunningElapsedTime
+ agentId={activeAgentId}
+ runStartedAt={runStartedAt}
+ topicId={id}
+ />
</>
}
onClick={handleClick}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index 98ffd420add..4254c7ae919 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -292,6 +292,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
id={topic.id}
key={topic.id}
metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
status={topic.status}
title={topic.title}
userId={topic.userId}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
index 3a07a29d697..c0c3b12e232 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
@@ -55,6 +55,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
id={topic.id}
key={topic.id}
metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
status={topic.status}
title={topic.title}
userId={topic.userId}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
index 9e0baf8e7f2..5a47c064da5 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
@@ -42,6 +42,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
id={topic.id}
key={topic.id}
metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
status={topic.status}
title={topic.title}
userId={topic.userId}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
index 73817fd4f3e..c5e2b8d6989 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -51,6 +51,7 @@ const FlatMode = memo(() => {
id={topic.id}
key={topic.id}
metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
status={topic.status}
title={topic.title}
userId={topic.userId}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx
index 215d6acf8e2..84d9410c6cc 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx
@@ -34,6 +34,7 @@ const SearchResult = memo(() => {
id={topic.id}
key={topic.id}
metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
status={topic.status}
title={topic.title}
userId={topic.userId}
diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.ts
index 7eb6b43d9b6..95f77268b9b 100644
--- a/src/hooks/useGatewayReconnect.ts
+++ b/src/hooks/useGatewayReconnect.ts
@@ -10,6 +10,7 @@ interface RunningOperation {
heteroType?: string | null;
operationId: string;
scope?: string;
+ startedAt?: string;
threadId?: string | null;
}
@@ -60,6 +61,7 @@ export const useGatewayReconnect = (
heteroType: runningOperation.heteroType,
operationId: runningOperation.operationId,
scope: runningOperation.scope,
+ startedAt: runningOperation.startedAt,
threadId: runningOperation.threadId,
topicId,
});
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 60f3f3ec427..4fb0ba185cb 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -34,8 +34,12 @@ export interface TopicListItem extends ChatTopic {
* Start time of the topic's current run (latest top-level running
* `agent_operations` row). Only set for `running` topics; null when the run
* never wrote an operation row (e.g. client-mode) β€” keep a fallback.
+ *
+ * Type widens {@link ChatTopic.runStartedAt}: over-the-wire values arrive as
+ * ISO strings, so a narrowed `Date` here contradicts the base and breaks
+ * assignment in both directions.
*/
- runStartedAt?: Date | null;
+ runStartedAt?: ChatTopic['runStartedAt'];
}
export type TopicBatchDeleteScope = 'own' | 'workspace';
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index d6d06206672..249f96cf935 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1746,11 +1746,15 @@ describe('GatewayActionImpl', () => {
expect.objectContaining({
value: expect.objectContaining({
metadata: expect.objectContaining({
- runningOperation: {
+ runningOperation: expect.objectContaining({
assistantMessageId: 'ast-1',
heteroType: null,
operationId: 'server-op-1',
- },
+ // Server op createdAt echoed onto the optimistic marker so a
+ // refresh-time reconnect can anchor elapsed time without the
+ // messages list having loaded.
+ startedAt: expect.any(String),
+ }),
}),
}),
}),
@@ -2399,6 +2403,71 @@ describe('GatewayActionImpl', () => {
);
});
+ // Cold-boot reconnect races the messages-list fetch: when it wins, the
+ // assistant message isn't in messagesMap yet and the old createdAt anchor
+ // resolved to undefined β†’ startOperation stamped Date.now(), resetting the
+ // elapsed-time displays to 00:00 on every refresh. The marker's
+ // server-written startedAt stamp must win over the message lookup so the
+ // anchor survives regardless of which fetch lands first.
+ it('prefers the marker startedAt over the assistant message when messagesMap is empty', async () => {
+ const markerStartedAtMs = 1_700_000_000_000;
+ const { action, startOperation } = createReconnectTestAction(null);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ startedAt: new Date(markerStartedAtMs).toISOString(),
+ topicId: 'topic-1',
+ });
+
+ expect(startOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ startTime: markerStartedAtMs }),
+ }),
+ );
+ });
+
+ it('prefers the marker startedAt over a later assistant-message createdAt', async () => {
+ const markerStartedAtMs = 1_700_000_000_000;
+ const { action, startOperation } = createReconnectTestAction({
+ createdAt: markerStartedAtMs + 5_000,
+ id: 'ast-1',
+ });
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ startedAt: new Date(markerStartedAtMs).toISOString(),
+ topicId: 'topic-1',
+ });
+
+ expect(startOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ startTime: markerStartedAtMs }),
+ }),
+ );
+ });
+
+ it('falls back to the assistant message when the marker carries no startedAt', async () => {
+ const createdAtMs = 1_700_000_000_000;
+ const { action, startOperation } = createReconnectTestAction({
+ createdAt: createdAtMs,
+ id: 'ast-1',
+ });
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(startOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ startTime: createdAtMs }),
+ }),
+ );
+ });
+
// Surfaces that mount the run drawer off the agent route (task detail, home
// inbox) own an agent the chat store knows nothing about β€” `activeAgentId` is
// whatever the last agent page left behind, or undefined on home. Binding the
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 829793639e0..f80b0b4712c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1110,6 +1110,11 @@ export class GatewayActionImpl {
assistantMessageId: result.assistantMessageId,
heteroType: result.heteroType,
operationId: result.operationId,
+ // Mirror the server marker's liveness stamp so the optimistic
+ // row carries the same elapsed-time anchor a refresh-created
+ // reconnect will read. `createdAt` is when the server created
+ // the operation β€” the same instant its own marker stamps.
+ startedAt: result.createdAt,
},
},
},
@@ -1275,6 +1280,12 @@ export class GatewayActionImpl {
heteroType?: string | null;
operationId: string;
scope?: string;
+ /**
+ * Server-written ISO timestamp of when the run claimed the topic β€” carried
+ * on the topic's `runningOperation` marker so elapsed-time anchors survive
+ * a page refresh even when the messages list hasn't loaded yet.
+ */
+ startedAt?: string;
threadId?: string | null;
topicId: string;
}): Promise<void> => {
@@ -1346,9 +1357,16 @@ export class GatewayActionImpl {
topicId,
};
- // Anchor the operation to the run's real start: the assistant message was
- // created when the run began. Defaulting to Date.now() here would reset
- // elapsed-time displays (OpStatusTray) to zero on every page refresh.
+ // Anchor the operation to the run's real start so elapsed-time displays
+ // (OpStatusTray, topic-list timers) don't reset on page refresh. Priority:
+ // the marker's server-written `startedAt` stamp β†’ the assistant message's
+ // `createdAt` (the message is created when the run begins) β†’ fall through
+ // to startOperation's Date.now() default.
+ //
+ // The message lookup races this reconnect's SWR against the messages-list
+ // fetch, so on a cold boot `messagesMap` can still be empty β€” the marker
+ // stamp is what keeps the anchor correct in exactly that case.
+ const markerStartedAt = params.startedAt ? Date.parse(params.startedAt) : Number.NaN;
const assistantMessage = Object.values(this.#get().messagesMap)
.flat()
.find((m) => m.id === assistantMessageId);
@@ -1358,9 +1376,11 @@ export class GatewayActionImpl {
// converting). Normalize to epoch ms here so the elapsed-time math stays a
// number β€” passing a string/Invalid Date straight through makes
// `Date.now() - startTime` resolve to NaN and renders as "NaN:NaN".
- const startTime = assistantMessage?.createdAt
+ const assistantMessageStart = assistantMessage?.createdAt
? new Date(assistantMessage.createdAt).getTime()
- : undefined;
+ : Number.NaN;
+
+ const startTime = [markerStartedAt, assistantMessageStart].find(Number.isFinite);
// Create a local operation for UI loading state, stashing the server op id
// so intervention flows can find it after reconnect as well.
@@ -1368,7 +1388,7 @@ export class GatewayActionImpl {
context,
metadata: {
serverOperationId: operationId,
- ...(Number.isFinite(startTime) ? { startTime } : {}),
+ ...(startTime !== undefined ? { startTime } : {}),
},
type: 'execServerAgentRuntime',
});