π€― 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(topic): show the elapsed clock on running project topics (#21858)
LiJianbc581ef046cc
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.tsindex 828cbd1b9ad..a19f2c8ba6b 100644--- a/packages/database/src/models/__tests__/project.test.ts+++ b/packages/database/src/models/__tests__/project.test.ts@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';import {+ agentOperations,agents,environments,knowledgeBases,@@ -15,6 +16,7 @@ import {projects,projectWorks,tasks,+ topics,users,works,workspaces,@@ -1097,4 +1099,43 @@ describe('ProjectModel', () => {expect.objectContaining({ agentId: null, agentTitle: null, id: topic.id }),]);});++ // The project sidebar renders a running row's elapsed clock from this. Rows+ // the client holds no local operation for (every non-active running topic+ // after a refresh) otherwise show a spinner with no timer.+ it('resolves runStartedAt for running project topics', async () => {+ const project = await createProject(model, { name: 'Running work' });+ await serverDB.insert(topics).values([+ { id: 't-op', projectId: project.id, status: 'running', title: 'server run', userId },+ {+ id: 't-stamp',+ metadata: { runStartedAt: '2026-01-05T00:00:00Z' },+ projectId: project.id,+ status: 'running',+ title: 'client run',+ userId,+ },+ {+ id: 't-done',+ metadata: { runStartedAt: '2026-01-06T00:00:00Z' },+ projectId: project.id,+ status: 'completed',+ title: 'finished run',+ userId,+ },+ ]);+ await serverDB.insert(agentOperations).values({+ id: 'op-project-run',+ startedAt: new Date('2026-01-02T00:00:00Z'),+ status: 'running',+ topicId: 't-op',+ userId,+ });++ const byId = Object.fromEntries((await model.listTopics(project.id)).map((t) => [t.id, t]));++ expect(byId['t-op'].runStartedAt).toEqual(new Date('2026-01-02T00:00:00Z'));+ expect(byId['t-stamp'].runStartedAt).toEqual(new Date('2026-01-05T00:00:00Z'));+ expect(byId['t-done'].runStartedAt).toBeNull();+ });});diff --git a/packages/database/src/models/__tests__/topics/topic.query.runStartedAt.test.ts b/packages/database/src/models/__tests__/topics/topic.query.runStartedAt.test.tsnew file mode 100644index 00000000000..753a6046d3d--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.query.runStartedAt.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentOperations, agents, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicModel } from '../../topic';++const userId = 'topic-query-run-started-at-user';+const agentId = 'topic-query-run-started-at-agent';+const serverDB: LobeChatDatabase = await getTestDB();+const topicModel = new TopicModel(serverDB, userId);++describe('TopicModel.query runStartedAt', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({ id: agentId, userId });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ // Regression: the agent sidebar reads this list. Client-executed runs+ // (desktop CC, in-browser runtime) create no operation row, so without the+ // topic stamp their running rows showed a spinner and no elapsed clock.+ it('falls back to the topic stamp when the run left no operation row', async () => {+ await serverDB.insert(topics).values([+ {+ agentId,+ id: 't-local',+ metadata: { runStartedAt: '2026-01-05T00:00:00Z' },+ status: 'running',+ title: 'local',+ userId,+ },+ {+ agentId,+ id: 't-both',+ metadata: { runStartedAt: '2026-01-06T00:00:00Z' },+ status: 'running',+ title: 'both',+ userId,+ },+ {+ agentId,+ id: 't-done',+ metadata: { runStartedAt: '2026-01-04T00:00:00Z' },+ status: 'completed',+ title: 'done',+ userId,+ },+ ]);+ await serverDB.insert(agentOperations).values({+ id: 'op-both',+ startedAt: new Date('2026-01-07T00:00:00Z'),+ status: 'running',+ topicId: 't-both',+ userId,+ });++ const { items } = await topicModel.query({ agentId });+ const byId = Object.fromEntries(items.map((t) => [t.id, t]));++ expect(byId['t-local'].runStartedAt).toEqual(new Date('2026-01-05T00:00:00Z'));+ // The server's own record of the run beats the client-reported stamp.+ expect(byId['t-both'].runStartedAt).toEqual(new Date('2026-01-07T00:00:00Z'));+ // A stamp left behind by a finished run must not resurrect a timer.+ expect(byId['t-done'].runStartedAt).toBeNull();+ });+});diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex 41436c51a1e..a70e9eafd94 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -21,6 +21,7 @@ import { topics } from '../schemas/topic';import { works } from '../schemas/work';import type { LobeChatDatabase } from '../type';import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';+import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { AgentModel } from './agent';import { EnvironmentModel } from './environment';@@ -1066,6 +1067,8 @@ export class ProjectModel {userId: topics.userId,title: topics.title,status: topics.status,+ // The project sidebar draws a running row's elapsed clock from this.+ runStartedAt: topicRunStartedAtColumn(this.db),agentId: topics.agentId,agentTitle: agents.title,agentName: agents.name,diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.tsindex b9f71e35155..9f072e64ede 100644--- a/packages/database/src/models/topic/list.ts+++ b/packages/database/src/models/topic/list.ts@@ -21,7 +21,8 @@ import {sql,} from 'drizzle-orm';-import { agentOperations, agents, chatGroups, messages, topics } from '../../schemas';+import { agents, chatGroups, messages, topics } from '../../schemas';+import { topicRunStartedAtColumn } from '../../utils/topicRunStartedAt';import { notChannelTopic } from '../../utils/topicVisibility';import { buildWorkspaceWhere } from '../../utils/workspace';import { topicMetadataWithCreator } from '../topicCreator';@@ -132,33 +133,7 @@ export const query = async (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.- const runStartedAtSubquery = ctx.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 runStartedAtColumn = topicRunStartedAtColumn(ctx.db);const orderBy = buildTopicOrderBy(topicActivityAt, sortBy);@@ -512,42 +487,7 @@ export const queryTopics = async ('private' | 'public' | null>`COALESCE(${chatGroups.visibility}, ${agents.visibility})`.as('parent_visibility');- // 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 = ctx.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);-- // Client-executed runs (desktop heterogeneous CLI, in-browser runtime) never- // reach `agent_operations` β nothing server-side creates the operation β so- // their start is stamped onto the topic by the status write that claims it- // (see {@link TopicModel.update}). The operation row still wins when both- // exist: it is the server's own record of the run, while the stamp is a- // client-reported time.- const localRunStartedAt = sql`(${topics.metadata} ->> 'runStartedAt')::timestamptz`;-- // CASE-gated so only rows that are actually running pay for the lookup β- // and a stale running op (or stamp) under a finished topic can't resurrect- // a timer.- const runStartedAtColumn =- sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN COALESCE((${runStartedAtSubquery}), ${localRunStartedAt}) ELSE NULL END`- .mapWith(agentOperations.startedAt)- .as('run_started_at');+ const runStartedAtColumn = topicRunStartedAtColumn(ctx.db);if (!withLastMessage) {return ctx.dbdiff --git a/packages/database/src/utils/topicRunStartedAt.ts b/packages/database/src/utils/topicRunStartedAt.tsnew file mode 100644index 00000000000..e86fccdf6f3--- /dev/null+++ b/packages/database/src/utils/topicRunStartedAt.ts@@ -0,0 +1,48 @@+import { and, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';++import { agentOperations, topics } from '../schemas';+import type { LobeChatDatabase } from '../type';++/**+ * When the topic's current run started, so a list can show a live elapsed+ * clock instead of `updatedAt` (which moves on every message write). Every+ * topic list that renders running rows must select this β a row whose+ * persisted status is `running` but which lacks it shows a spinner with no+ * timer whenever the client holds no local operation for the topic.+ *+ * Resolution order:+ * 1. 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.+ * 2. Client-executed runs (desktop heterogeneous CLI, in-browser runtime)+ * never reach `agent_operations`, so their start is stamped onto+ * `metadata.runStartedAt` by the status write that claims the topic (see+ * `TopicModel.update`). The operation row wins when both exist: it is the+ * server's own record of the run, while the stamp is a client-reported time.+ *+ * CASE-gated so only rows that are actually running pay for the lookup β and+ * a stale running op (or stamp) under a finished topic can't resurrect a timer.+ */+export const topicRunStartedAtColumn = (db: LobeChatDatabase) => {+ const operationStartedAt = 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);+ const stampedStartedAt = sql`(${topics.metadata} ->> 'runStartedAt')::timestamptz`;++ return sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN COALESCE((${operationStartedAt}), ${stampedStartedAt}) ELSE NULL END`+ .mapWith(agentOperations.startedAt)+ .as('run_started_at');+};