π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(home): anchor running topic clock to operation (#17477)
Arvin Xufb2dead637e7
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 76b9b2ec5bf..da64b17f425 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -3,7 +3,15 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, chatGroups, messages, sessions, topics, users } from '../../schemas';+import {+ agentOperations,+ agents,+ chatGroups,+ messages,+ sessions,+ topics,+ users,+} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { TopicModel } from '../topic';@@ -409,6 +417,74 @@ describe('TopicModel', () => {expect(topic.lastAssistantMessage).toBe(`${'x'.repeat(2000)}β¦`);});++ it('resolves runStartedAt from the latest top-level running operation', async () => {+ await serverDB.insert(topics).values([+ { id: 't-run', status: 'running', title: 'run', userId },+ { id: 't-no-op', status: 'running', title: 'no op', userId },+ ]);+ await serverDB.insert(agentOperations).values([+ // Abandoned row from a crashed earlier run β the live (later) one wins.+ {+ id: 'op-stale',+ startedAt: new Date('2026-01-01T00:00:00Z'),+ status: 'running',+ topicId: 't-run',+ userId,+ },+ {+ id: 'op-live',+ startedAt: new Date('2026-01-02T00:00:00Z'),+ status: 'running',+ topicId: 't-run',+ userId,+ },+ // Sub-operation spawned later must not restart the clock.+ {+ id: 'op-sub',+ parentOperationId: 'op-live',+ startedAt: new Date('2026-01-03T00:00:00Z'),+ status: 'running',+ topicId: 't-run',+ userId,+ },+ // Finished op of the same topic is not the current run.+ {+ id: 'op-done',+ startedAt: new Date('2026-01-04T00:00:00Z'),+ status: 'done',+ topicId: 't-run',+ userId,+ },+ ]);++ const result = await topicModel.queryTopics({ statuses: ['running'] });+ const byId = Object.fromEntries(result.map((t) => [t.id, t]));++ expect(byId['t-run'].runStartedAt).toEqual(new Date('2026-01-02T00:00:00Z'));+ // A run that never wrote an operation row (e.g. client-mode) stays null.+ expect(byId['t-no-op'].runStartedAt).toBeNull();+ });++ it('never resurrects a timer for a non-running topic with a stale running op', async () => {+ await serverDB+ .insert(topics)+ .values({ id: 't-unread', status: 'unread', title: 'u', userId });+ await serverDB.insert(agentOperations).values({+ id: 'op-leftover',+ startedAt: new Date('2026-01-01T00:00:00Z'),+ status: 'running',+ topicId: 't-unread',+ userId,+ });++ const [topic] = await topicModel.queryTopics({+ statuses: ['unread'],+ withLastMessage: true,+ });++ expect(topic.runStartedAt).toBeNull();+ });});describe('count', () => {diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 54b02a89b93..fcb7244aca2 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -23,6 +23,7 @@ import {gt,gte,inArray,+ isNotNull,isNull,lte,ne,@@ -32,7 +33,15 @@ import {} from 'drizzle-orm';import type { TopicItem } from '../schemas';-import { agents, messagePlugins, messages, threads, topicDocuments, topics } from '../schemas';+import {+ agentOperations,+ agents,+ messagePlugins,+ messages,+ threads,+ topicDocuments,+ topics,+} from '../schemas';import type { LobeChatDatabase } from '../type';import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';@@ -56,6 +65,13 @@ const LAST_MESSAGE_PREVIEW_LENGTH = 2000;export interface TopicListItem extends TopicItem {/** The topic's last non-empty assistant reply, truncated with a trailing `β¦`. Only set when `queryTopics` is called with `withLastMessage`. */lastAssistantMessage?: string | null;+ /**+ * When the topic's current run started (`agent_operations.startedAt` of its+ * latest top-level running operation). Only computed for `running` topics;+ * null for everything else, and for runs that never wrote an operation row+ * (e.g. client-mode runs) β callers must keep a fallback.+ */+ runStartedAt?: Date | null;}export interface CreateTopicParams {@@ -624,9 +640,40 @@ export class TopicModel {: undefined,);+ // When the topic's current run started, so a list 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.+ 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');+if (!withLastMessage) {return this.db- .select()+ .select({+ ...getTableColumns(topics),+ runStartedAt: runStartedAtColumn,+ }).from(topics).where(where).orderBy(desc(topics.updatedAt))@@ -663,6 +710,7 @@ export class TopicModel {lastAssistantMessage: sql<string | null>`(${lastAssistantMessageSubquery})`.as('last_assistant_message',),+ runStartedAt: runStartedAtColumn,}).from(topics).where(where)diff --git a/src/features/HomeInbox/RunningElapsedTime.test.tsx b/src/features/HomeInbox/RunningElapsedTime.test.tsxnew file mode 100644index 00000000000..1bf49da17cb--- /dev/null+++ b/src/features/HomeInbox/RunningElapsedTime.test.tsx@@ -0,0 +1,39 @@+import { act, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { resolveTopicTriggerTime, RunningElapsedTime } from './RunningElapsedTime';++describe('RunningElapsedTime', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('ticks from the operation start time once per second', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-07-23T00:12:00Z'));++ render(<RunningElapsedTime startTime={'2026-07-23T00:00:00Z'} />);++ expect(screen.getByText('12:00')).toBeInTheDocument();++ act(() => {+ vi.advanceTimersByTime(1000);+ });++ expect(screen.getByText('12:01')).toBeInTheDocument();+ });++ it('renders nothing when no operation start exists', () => {+ const { container } = render(<RunningElapsedTime />);++ expect(container).toBeEmptyDOMElement();+ });++ it('uses the operation start for the relative trigger time and keeps a fallback', () => {+ const operationStart = '2026-07-23T00:00:00Z';+ const updatedAt = '2026-07-23T00:11:59Z';++ expect(resolveTopicTriggerTime(operationStart, updatedAt)).toBe(operationStart);+ expect(resolveTopicTriggerTime(null, updatedAt)).toBe(updatedAt);+ });+});diff --git a/src/features/HomeInbox/RunningElapsedTime.tsx b/src/features/HomeInbox/RunningElapsedTime.tsxnew file mode 100644index 00000000000..91aa39948c0--- /dev/null+++ b/src/features/HomeInbox/RunningElapsedTime.tsx@@ -0,0 +1,41 @@+import { formatElapsedClockTime } from '@lobechat/utils';+import { Text } from '@lobehub/ui';+import { memo, useEffect, useState } from 'react';++interface RunningElapsedTimeProps {+ startTime?: Date | number | string | null;+}++export const resolveTopicTriggerTime = (+ startTime: Date | number | string | null | undefined,+ fallbackTime: Date | number | string,+) => startTime ?? fallbackTime;++export const RunningElapsedTime = memo<RunningElapsedTimeProps>(({ startTime }) => {+ const startTimeMs = startTime == null ? undefined : new Date(startTime).getTime();+ const hasValidStartTime = startTimeMs !== undefined && Number.isFinite(startTimeMs);+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ if (!hasValidStartTime) return;++ setNow(Date.now());+ const timer = setInterval(() => setNow(Date.now()), 1000);++ return () => clearInterval(timer);+ }, [hasValidStartTime, startTimeMs]);++ if (!hasValidStartTime) return null;++ return (+ <Text+ fontSize={12}+ style={{ flex: 'none', fontVariantNumeric: 'tabular-nums' }}+ type={'secondary'}+ >+ {formatElapsedClockTime(now - startTimeMs)}+ </Text>+ );+});++RunningElapsedTime.displayName = 'RunningElapsedTime';diff --git a/src/features/HomeInbox/TopicRow.tsx b/src/features/HomeInbox/TopicRow.tsxindex 929f82e1023..e586ec7da42 100644--- a/src/features/HomeInbox/TopicRow.tsx+++ b/src/features/HomeInbox/TopicRow.tsx@@ -7,6 +7,7 @@ import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplaimport { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import Time from '@/routes/(main)/home/features/components/Time';+import { resolveTopicTriggerTime, RunningElapsedTime } from './RunningElapsedTime';import { type InboxTopic } from './useHomeInboxTopics';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -54,11 +55,16 @@ const TopicRow = memo<TopicRowProps>(({ topic, leading, trailing }) => {title={agent.title}/>)}- <Text ellipsis fontSize={13} style={{ flex: 1, minWidth: 0 }}>- {topic.title}- </Text>+ <Flexbox horizontal align={'center'} flex={1} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis fontSize={13} style={{ minWidth: 0 }}>+ {topic.title}+ </Text>+ <RunningElapsedTime startTime={topic.runStartedAt} />+ </Flexbox>{trailing}- <Time date={topic.updatedAt ?? topic.createdAt} />+ <Time+ date={resolveTopicTriggerTime(topic.runStartedAt, topic.updatedAt ?? topic.createdAt)}+ /></Flexbox>);});diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 474bd729f32..964c0f03779 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -24,6 +24,12 @@ import {export interface TopicListItem extends ChatTopic {agentId?: string | null;lastAssistantMessage?: string | null;+ /**+ * 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.+ */+ runStartedAt?: Date | null;}export type TopicBatchDeleteScope = 'own' | 'workspace';