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(chat): stop a dead topic lock from swallowing sent messages (#18497)

Arvin Xu0583794a258e
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index e2dcc728ad2..246d523c837 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1303,6 +1303,10 @@ export const aiAgentRouter = router({
appContext,
autoStart,
clientIds: input.clientIds,
+ // This procedure serves the composer (`aiAgentService.execAgentTask`).
+ // The client already queues follow-ups behind a live run and shows the
+ // user a tray; refusing here would only make the message disappear.
+ interactiveStart: true,
// Propagate the originating request's client IP / user agent into the run
// so downstream LLM-call metadata can carry them for auditing and spend
// attribution. These are server-derived from the tRPC context and are
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 68d44b55b5e..605daa61424 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -1032,6 +1032,21 @@ export const topicRouter = router({
return ctx.topicModel.updateMetadata(input.id, input.metadata);
}),
+
+ settleRunningOperation: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ operationId: z.string(),
+ status: chatTopicStatusSchema.optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+
+ return ctx.topicModel.settleRunningOperation(input.id, input.operationId, input.status);
+ }),
});
export type TopicRouter = typeof topicRouter;
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 0df8962ac36..5ac238f9589 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -1027,12 +1027,11 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
'parent-operation',
expect.objectContaining({ operationId: expect.stringContaining('op_') }),
);
- expect(topicMock.tryReserveTaskCallback).toHaveBeenCalledWith(
- 'topic-1',
- expect.any(String),
- 'parent-operation',
- undefined,
- );
+ expect(topicMock.tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', expect.any(String), {
+ allowRunningOperationId: 'parent-operation',
+ ignoreRunningOperation: undefined,
+ replacesOperationId: undefined,
+ });
expect(mockCreateOperationMetadata).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ mirrorToOperationId: 'parent-operation' }),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
index 9db08e26cd7..d87ab50e696 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
@@ -201,12 +201,11 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {
expect(userMessageCall()![0]).toMatchObject({ parentId: 'spine-head-1', role: 'user' });
// No spine candidate is missing, so the fallback must not be queried.
expect(mockGetLatestNonToolMessageId).not.toHaveBeenCalled();
- expect(mockTryReserve).toHaveBeenCalledWith(
- 'topic-1',
- expect.stringMatching(/^agent-start-/),
- undefined,
- undefined,
- );
+ expect(mockTryReserve).toHaveBeenCalledWith('topic-1', expect.stringMatching(/^agent-start-/), {
+ allowRunningOperationId: undefined,
+ ignoreRunningOperation: undefined,
+ replacesOperationId: undefined,
+ });
expect(mockReleaseReservation).toHaveBeenCalledWith(
'topic-1',
expect.stringMatching(/^agent-start-/),
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index f567b6b7bbf..2b8c3605bf6 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -435,6 +435,14 @@ interface InternalExecAgentParams extends ExecAgentParams {
hooks?: AgentHook[];
/** Initial step count offset for resumed operations (accumulated from previous runs) */
initialStepCount?: number;
+ /**
+ * This start came from a person waiting at a composer, not from a background
+ * producer (task callback, cron, bot, API). Interactive starts serialize only
+ * on the short topic-start reservation and never on `runningOperation` β€” the
+ * client already owns "one foreground turn at a time" with a queue and a UI,
+ * and a refusal here destroys the message before it is ever persisted.
+ */
+ interactiveStart?: boolean;
/** Maximum steps for the agent operation */
maxSteps?: number;
/**
@@ -1342,6 +1350,7 @@ export class AiAgentService {
const reserved = await acquireTopicStartReservation({
replacesOperationId: params.replacesOperationId,
allowRunningOperationId: params.topicStartOwnerOperationId,
+ ignoreRunningOperation: params.interactiveStart,
reservationId,
topicId,
topicModel: this.topicModel,
@@ -2528,6 +2537,7 @@ export class AiAgentService {
const childOperation = {
assistantMessageId: assistantMessageRecord.id,
hooks: serializedHooks,
+ startedAt: new Date().toISOString(),
...(isRemoteHetero && remoteDeviceId
? {
deviceId: remoteDeviceId,
@@ -4863,6 +4873,9 @@ export class AiAgentService {
assistantMessageId: assistantMessageRecord.id,
operationId,
scope: appContext?.scope ?? undefined,
+ // Liveness stamp β€” without it this marker can never be proven dead
+ // and would hold the topic against background starts forever.
+ startedAt: new Date().toISOString(),
threadId: appContext?.threadId ?? undefined,
},
});
diff --git a/apps/server/src/services/aiAgent/topicStartReservation.test.ts b/apps/server/src/services/aiAgent/topicStartReservation.test.ts
index 3702aff2aa2..8b05920d1ac 100644
--- a/apps/server/src/services/aiAgent/topicStartReservation.test.ts
+++ b/apps/server/src/services/aiAgent/topicStartReservation.test.ts
@@ -53,12 +53,11 @@ describe('acquireTopicStartReservation', () => {
topicModel,
});
- expect(tryReserveTaskCallback).toHaveBeenCalledWith(
- 'topic-1',
- 'new-start',
- undefined,
- 'old-operation',
- );
+ expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'new-start', {
+ allowRunningOperationId: undefined,
+ ignoreRunningOperation: undefined,
+ replacesOperationId: 'old-operation',
+ });
});
it('passes the parent operation ownership through for in-group children', async () => {
@@ -74,11 +73,28 @@ describe('acquireTopicStartReservation', () => {
}),
).resolves.toBe(true);
- expect(tryReserveTaskCallback).toHaveBeenCalledWith(
- 'topic-1',
- 'child-operation',
- 'parent-operation',
- undefined,
- );
+ expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'child-operation', {
+ allowRunningOperationId: 'parent-operation',
+ ignoreRunningOperation: undefined,
+ replacesOperationId: undefined,
+ });
+ });
+
+ it('forwards the interactive bypass so a composer send never waits on a run', async () => {
+ const tryReserveTaskCallback = vi.fn().mockResolvedValue(true);
+ const topicModel = { tryReserveTaskCallback } as unknown as TopicModel;
+
+ await acquireTopicStartReservation({
+ ignoreRunningOperation: true,
+ reservationId: 'composer-send',
+ topicId: 'topic-1',
+ topicModel,
+ });
+
+ expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'composer-send', {
+ allowRunningOperationId: undefined,
+ ignoreRunningOperation: true,
+ replacesOperationId: undefined,
+ });
});
});
diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.ts
index f537d80b528..f8820c9ca1d 100644
--- a/apps/server/src/services/aiAgent/topicStartReservation.ts
+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts
@@ -14,29 +14,37 @@ const delay = (milliseconds: number): Promise<void> =>
* the topic as idle and create competing continuations.
*
* The bounded backoff deliberately throws instead of holding a workflow
- * request indefinitely. QStash retries callback deliveries on the resulting
- * 500 response, while interactive callers receive a finite busy failure.
+ * request indefinitely; QStash retries callback deliveries on the resulting 500
+ * response. Interactive sends pass `ignoreRunningOperation` so they contend
+ * only for the short reservation and practically never reach that throw β€” a
+ * busy failure there is indistinguishable from the message being swallowed,
+ * since the gate runs before the user message is persisted.
*/
export const acquireTopicStartReservation = async ({
allowRunningOperationId,
+ ignoreRunningOperation,
replacesOperationId,
reservationId,
topicId,
topicModel,
}: {
allowRunningOperationId?: string;
+ /**
+ * Serialize only on the short reservation, not on `runningOperation`. Set by
+ * interactive sends β€” see `TopicModel.tryReserveTaskCallback`.
+ */
+ ignoreRunningOperation?: boolean;
replacesOperationId?: string;
reservationId: string;
topicId: string;
topicModel: TopicModel;
}): Promise<boolean> => {
for (let attempt = 0; attempt < MAX_RESERVATION_ATTEMPTS; attempt += 1) {
- const reservation = await topicModel.tryReserveTaskCallback(
- topicId,
- reservationId,
+ const reservation = await topicModel.tryReserveTaskCallback(topicId, reservationId, {
allowRunningOperationId,
+ ignoreRunningOperation,
replacesOperationId,
- );
+ });
if (reservation === null) return false;
if (reservation) return true;
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index 72a6741df0b..a3121cd89ea 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -605,6 +605,22 @@ describe('TopicModel', () => {
expect(row?.status).toBe('unread');
});
+ it('uses the requested terminal status only for the matching operation', async () => {
+ const topic = await topicModel.create({
+ metadata: {
+ runningOperation: { assistantMessageId: 'msg-old', operationId: 'op-old' },
+ },
+ title: 'active matching operation',
+ });
+ await topicModel.update(topic.id, { status: 'running' });
+
+ await topicModel.settleRunningOperation(topic.id, 'op-old', 'active');
+
+ const row = await topicModel.findById(topic.id);
+ expect(row?.metadata?.runningOperation).toBeNull();
+ expect(row?.status).toBe('active');
+ });
+
it('atomically removes only a matching child operation', async () => {
const childHooks = [
{
diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.ts
index 3c0f29ada53..07ce5423fb2 100644
--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts
@@ -2,7 +2,7 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import { messages, sessions, topics, users } from '../../../schemas';
+import { agentOperations, messages, sessions, topics, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { TopicModel } from '../../topic';
@@ -11,8 +11,32 @@ const sessionId = 'topic-update-session';
const serverDB: LobeChatDatabase = await getTestDB();
const topicModel = new TopicModel(serverDB, userId);
+/**
+ * Seed the `agent_operations` row a `runningOperation` marker points at β€” the
+ * authority `tryReserveTaskCallback` consults to decide whether the run still
+ * owns the topic. `topicId` is deliberately left unset: the liveness lookup is
+ * by operation id, and setting it would require the topic row to exist first.
+ */
+const seedOperation = async ({
+ createdAt,
+ id,
+ status,
+}: {
+ createdAt?: Date;
+ id: string;
+ status: 'done' | 'error' | 'idle' | 'running' | 'waiting_for_async_tool' | 'waiting_for_human';
+}) => {
+ await serverDB.insert(agentOperations).values({
+ id,
+ status,
+ userId,
+ ...(createdAt ? { createdAt } : {}),
+ });
+};
+
describe('TopicModel - Update', () => {
beforeEach(async () => {
+ await serverDB.delete(agentOperations);
await serverDB.delete(users);
await serverDB.transaction(async (tx) => {
await tx.insert(users).values([{ id: userId }]);
@@ -159,6 +183,7 @@ describe('TopicModel - Update', () => {
runningOperation: {
assistantMessageId: 'assistant-1',
operationId: 'operation-1',
+ startedAt: new Date().toISOString(),
},
},
});
@@ -180,15 +205,20 @@ describe('TopicModel - Update', () => {
runningOperation: {
assistantMessageId: 'assistant-1',
operationId: 'old-operation',
+ startedAt: new Date().toISOString(),
},
},
});
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'new-start', undefined, 'different-operation'),
+ topicModel.tryReserveTaskCallback(topicId, 'new-start', {
+ replacesOperationId: 'different-operation',
+ }),
).resolves.toBe(false);
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'new-start', undefined, 'old-operation'),
+ topicModel.tryReserveTaskCallback(topicId, 'new-start', {
+ replacesOperationId: 'old-operation',
+ }),
).resolves.toBe(true);
const topic = await serverDB.query.topics.findFirst({ where: eq(topics.id, topicId) });
@@ -211,13 +241,19 @@ describe('TopicModel - Update', () => {
});
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'child-operation-1', 'operation-parent'),
+ topicModel.tryReserveTaskCallback(topicId, 'child-operation-1', {
+ allowRunningOperationId: 'operation-parent',
+ }),
).resolves.toBe(true);
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'child-operation-2', 'operation-parent'),
+ topicModel.tryReserveTaskCallback(topicId, 'child-operation-2', {
+ allowRunningOperationId: 'operation-parent',
+ }),
).resolves.toBe(true);
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'unrelated-operation', 'operation-other'),
+ topicModel.tryReserveTaskCallback(topicId, 'unrelated-operation', {
+ allowRunningOperationId: 'operation-other',
+ }),
).resolves.toBe(false);
const topic = await topicModel.findById(topicId);
@@ -331,6 +367,164 @@ describe('TopicModel - Update', () => {
});
});
+ it('recovers a topic whose runningOperation already reached a terminal state', async () => {
+ // Regression: `taskCallbackReservation` expires after a TTL, but
+ // `runningOperation` was checked bare. Every clear site is best-effort
+ // (ServerOperationStore.clearRunningMark swallows failures; the gateway
+ // client clears it from `onSessionComplete`, which never runs if the tab
+ // closed or the function was killed), so a marker left behind by a
+ // finished run blocked every later start on that topic β€” permanently,
+ // since nothing sweeps it.
+ const topicId = 'topic-start-terminal-running-operation';
+ await seedOperation({ id: 'finished-operation', status: 'error' });
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'finished-operation',
+ },
+ },
+ });
+
+ await expect(topicModel.tryReserveTaskCallback(topicId, 'later-start')).resolves.toBe(true);
+ });
+
+ it('recovers a topic whose runningOperation row no longer exists and carries no stamp', async () => {
+ // A marker with neither an operation row nor a `startedAt` cannot be
+ // proven live; holding the topic on it keeps an already-stuck
+ // conversation stuck forever.
+ const topicId = 'topic-start-orphan-running-operation';
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: { assistantMessageId: 'assistant-1', operationId: 'no-such-operation' },
+ },
+ });
+
+ await expect(topicModel.tryReserveTaskCallback(topicId, 'later-start')).resolves.toBe(true);
+ });
+
+ it('keeps holding the topic for a run parked on a human, however long it waits', async () => {
+ // `startedAt` is never refreshed, so an age-based check declared any run
+ // older than the TTL dead and let a callback start a competing
+ // continuation. An approval wait legitimately lasts days.
+ const topicId = 'topic-start-long-approval-wait';
+ await seedOperation({
+ createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
+ id: 'parked-operation',
+ status: 'waiting_for_human',
+ });
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'parked-operation',
+ startedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
+ },
+ },
+ });
+
+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(false);
+ });
+
+ it('keeps holding the topic for a live run whose marker predates the stamp', async () => {
+ // Rolling deployment: an older server instance writes `runningOperation`
+ // without `startedAt`. Treating unstamped markers as dead would let a new
+ // instance start a competing run against a live one.
+ const topicId = 'topic-start-unstamped-live-operation';
+ await seedOperation({ id: 'old-instance-operation', status: 'running' });
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'old-instance-operation',
+ },
+ },
+ });
+
+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(false);
+ });
+
+ it('ages out a run that still claims running long after its process died', async () => {
+ // A killed process never writes a terminal status, so status alone would
+ // hold the topic forever. Only non-parked states are aged out.
+ const topicId = 'topic-start-abandoned-running-operation';
+ await seedOperation({
+ createdAt: new Date(Date.now() - 12 * 60 * 60 * 1000),
+ id: 'abandoned-operation',
+ status: 'running',
+ });
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'abandoned-operation',
+ },
+ },
+ });
+
+ await expect(topicModel.tryReserveTaskCallback(topicId, 'later-start')).resolves.toBe(true);
+ });
+
+ it('lets an interactive start through while a run still owns the topic', async () => {
+ // "One foreground turn at a time" is a client-side UX policy with a queue
+ // tray and a Send-now escape hatch. Re-deciding it here can only fail
+ // worse: the gate runs before the user message is persisted, so a refusal
+ // destroys the message instead of parking it.
+ const topicId = 'topic-start-interactive-bypass';
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'live-operation',
+ startedAt: new Date().toISOString(),
+ },
+ },
+ });
+
+ await expect(
+ topicModel.tryReserveTaskCallback(topicId, 'composer-send', {
+ ignoreRunningOperation: true,
+ }),
+ ).resolves.toBe(true);
+
+ // A background delivery arriving at the same topic still waits.
+ await topicModel.releaseTaskCallbackReservation(topicId, 'composer-send');
+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(false);
+ });
+
+ it('still serializes an interactive start behind the short reservation', async () => {
+ // Bypassing `runningOperation` must not bypass the mutex that makes parent
+ // selection atomic β€” two sends landing together would otherwise both pick
+ // the same parent and fork the spine.
+ const topicId = 'topic-start-interactive-reservation';
+ await serverDB.insert(topics).values({ id: topicId, title: 'Test', userId });
+
+ await expect(
+ topicModel.tryReserveTaskCallback(topicId, 'send-1', { ignoreRunningOperation: true }),
+ ).resolves.toBe(true);
+ await expect(
+ topicModel.tryReserveTaskCallback(topicId, 'send-2', { ignoreRunningOperation: true }),
+ ).resolves.toBe(false);
+ });
+
it('recovers a stale reservation left by a crashed delivery worker', async () => {
const topicId = 'task-callback-stale-reservation';
await serverDB.insert(topics).values({
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 746d87f94be..ecc77e8a59a 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -64,6 +64,32 @@ type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'>
*/
const LAST_MESSAGE_PREVIEW_LENGTH = 2000;
const TASK_CALLBACK_RESERVATION_TTL_MS = 5 * 60 * 1000;
+/**
+ * How long an operation that still claims `running` / `idle` may hold the topic
+ * against a background start before it is treated as abandoned.
+ *
+ * Only a backstop for the case the operation row cannot describe: a process
+ * killed mid-run leaves its row at `running` forever, and every marker clear
+ * site is best-effort (`ServerOperationStore.clearRunningMark` swallows
+ * failures; the gateway client clears it from `onSessionComplete`, which never
+ * runs if the tab closed). Runs parked on a human or an async tool are exempt β€”
+ * those legitimately last days β€” so this only has to be longer than a plausible
+ * uninterrupted generation. The real reaper remains the gateway watchdog's
+ * `finalize-abandoned` call.
+ */
+const ABANDONED_OPERATION_TTL_MS = 6 * 60 * 60 * 1000;
+/**
+ * Operation statuses that mean "this run is still the topic's owner". Parked
+ * states are included on purpose: a run waiting for approval is not stuck.
+ */
+const LIVE_OPERATION_STATUSES = new Set([
+ 'idle',
+ 'running',
+ 'waiting_for_human',
+ 'waiting_for_async_tool',
+]);
+/** Parked states are exempt from the abandoned-age backstop β€” see above. */
+const UNBOUNDED_OPERATION_STATUSES = new Set(['waiting_for_human', 'waiting_for_async_tool']);
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`. */
@@ -1309,7 +1335,11 @@ export class TopicModel {
* already cleared their marker, while a callback that observes a newer
* operation must stop before dispatching lifecycle hooks for the wrong run.
*/
- settleRunningOperation = async (id: string, operationId: string) => {
+ settleRunningOperation = async (
+ id: string,
+ operationId: string,
+ status: TopicItem['status'] = 'unread',
+ ) => {
return this.db.transaction(async (tx) => {
const [existing] = await tx
.select({ metadata: topics.metadata, status: topics.status })
@@ -1350,7 +1380,7 @@ export class TopicModel {
.update(topics)
.set({
metadata,
- ...(isRoot && existing.status === 'running' ? { status: 'unread' as const } : {}),
+ ...(isRoot && existing.status === 'running' ? { status } : {}),
updatedAt: new Date(),
})
.where(and(eq(topics.id, id), this.ownership()));
@@ -1646,6 +1676,49 @@ export class TopicModel {
return { isRoot: false, operation: child };
});
+ /**
+ * Whether the run a `runningOperation` marker points at is still the topic's
+ * legitimate owner.
+ *
+ * The marker itself cannot answer this β€” it carries no heartbeat and is
+ * cleared best-effort β€” so the authority is the operation row, which both the
+ * in-process runtime (`createOperation`) and the heterogeneous path
+ * (`CompletionLifecycle.recordStart`) write before publishing the marker.
+ *
+ * Falls back to the marker's own `startedAt` only when no row exists: hetero's
+ * `recordStart` is deliberately non-fatal, so a DB hiccup can leave a live run
+ * with a marker and no row. A marker with neither a row nor a stamp cannot be
+ * proven live and must not keep an already-stuck topic stuck.
+ */
+ private isRunningOperationAlive = async (
+ tx: Pick<LobeChatDatabase, 'select'>,
+ runningOperation: NonNullable<ChatTopicMetadata['runningOperation']>,
+ ): Promise<boolean> => {
+ const [operation] = await tx
+ .select({ createdAt: agentOperations.createdAt, status: agentOperations.status })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, runningOperation.operationId))
+ .limit(1);
+
+ if (!operation) {
+ const markerStartedAt = runningOperation.startedAt
+ ? Date.parse(runningOperation.startedAt)
+ : Number.NaN;
+ return (
+ Number.isFinite(markerStartedAt) &&
+ Date.now() - markerStartedAt < ABANDONED_OPERATION_TTL_MS
+ );
+ }
+
+ if (!LIVE_OPERATION_STATUSES.has(operation.status)) return false;
+ if (UNBOUNDED_OPERATION_STATUSES.has(operation.status)) return true;
+
+ // Claims `running`/`idle`, but a killed process never writes a terminal
+ // status β€” age it out so the topic is not held forever.
+ const startedAt = operation.createdAt ? new Date(operation.createdAt).getTime() : Number.NaN;
+ return !Number.isFinite(startedAt) || Date.now() - startedAt < ABANDONED_OPERATION_TTL_MS;
+ };
+
/**
* Atomically reserve an idle topic for one task-callback delivery.
*
@@ -1658,8 +1731,26 @@ export class TopicModel {
tryReserveTaskCallback = async (
id: string,
messageId: string,
- allowRunningOperationId?: string,
- replacesOperationId?: string,
+ options?: {
+ /**
+ * Permit a start that runs *under* this marker (a group member starting
+ * beneath its supervisor). A pure permission check β€” it never takes the
+ * reservation.
+ */
+ allowRunningOperationId?: string;
+ /**
+ * Skip the `runningOperation` check entirely and serialize only on the
+ * short reservation. Set by interactive sends: "don't run two foreground
+ * turns at once" is a UX policy the client already owns end to end (queue
+ * tray, "Send now", FIFO drain), and it is the only layer that can show
+ * the user anything. A second, blind copy of that policy here can only
+ * fail worse β€” it used to destroy the message before it was ever
+ * persisted. Background starts (task callbacks, cron, bots) have no such
+ * queue and keep the check.
+ */
+ ignoreRunningOperation?: boolean;
+ replacesOperationId?: string;
+ },
): Promise<boolean | null> =>
this.db.transaction(async (tx) => {
const [existing] = await tx
@@ -1678,13 +1769,28 @@ export class TopicModel {
Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;
if (reservation?.messageId === messageId && hasLiveReservation) return true;
+
const runningOperation = existing.metadata?.runningOperation;
const ownedRunningOperation =
- !!allowRunningOperationId && runningOperation?.operationId === allowRunningOperationId;
- if (allowRunningOperationId) return ownedRunningOperation;
+ !!options?.allowRunningOperationId &&
+ runningOperation?.operationId === options.allowRunningOperationId;
+ if (options?.allowRunningOperationId) return ownedRunningOperation;
+
const canReplaceRunningOperation =
- !!replacesOperationId && runningOperation?.operationId === replacesOperationId;
- if ((runningOperation && !canReplaceRunningOperation) || hasLiveReservation) return false;
+ !!options?.replacesOperationId &&
+ runningOperation?.operationId === options.replacesOperationId;
+
+ // Only a run that can prove it is still alive may hold the topic. Ask the
+ // operation row rather than the marker's age: the marker is never
+ // refreshed, so age alone declares a legitimately long run (an approval
+ // wait can last days) dead and lets a competing continuation start.
+ const hasLiveRunningOperation =
+ !!runningOperation &&
+ !canReplaceRunningOperation &&
+ !options?.ignoreRunningOperation &&
+ (await this.isRunningOperationAlive(tx, runningOperation));
+
+ if (hasLiveRunningOperation || hasLiveReservation) return false;
await tx
.update(topics)
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 59b88e45e82..cb66c3b014e 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -259,6 +259,16 @@ export interface ChatTopicMetadata {
operationId: string;
orchestrationRole?: 'supervisor' | 'member';
scope?: string;
+ /**
+ * When this run claimed the topic, as an ISO string. This marker gates every
+ * background existing-topic start (`TopicModel.tryReserveTaskCallback`), so
+ * without a liveness stamp a run that dies before clearing it holds the
+ * topic hostage forever.
+ *
+ * Optional for back-compat: markers written before this field existed carry
+ * no stamp and cannot be proven live.
+ */
+ startedAt?: string;
threadId?: string | null;
} | null;
/**
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 936eb31c288..e7b028a4086 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -159,6 +159,14 @@ export class TopicService {
return lambdaClient.topic.updateTopicMetadata.mutate({ id, metadata });
};
+ settleRunningOperation = (
+ id: string,
+ operationId: string,
+ status?: NonNullable<ChatTopic['status']>,
+ ) => {
+ return lambdaClient.topic.settleRunningOperation.mutate({ id, operationId, status });
+ };
+
getShareInfo = (topicId: string) => {
return lambdaClient.topic.getShareInfo.query({ topicId });
};
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 498dab24df2..da0c181b240 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -432,6 +432,170 @@ describe('ConversationLifecycle actions', () => {
expect(setDocument).not.toHaveBeenCalled();
});
+ it('should restore the pre-send editor snapshot when a gateway send fails', async () => {
+ // Regression: the composer is cleared the instant Enter is pressed, and
+ // only the client-runtime branch put the text back. The gateway branch
+ // just logged, failed the op and deleted the optimistic pair β€” so a
+ // server-side start refusal (e.g. `Topic <id> remained busy while
+ // starting operation ...`, thrown by the reservation gate before the
+ // user message is ever persisted) made the message vanish with no trace
+ // and no way to recover what was typed.
+ const { result } = renderHook(() => useChatStore());
+ const inputEditorState = {
+ root: {
+ children: [
+ {
+ children: [{ text: 'Swallowed by gateway', type: 'text', version: 1 }],
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ type: 'root',
+ version: 1,
+ },
+ };
+ const setDocument = vi.fn();
+ const setJSONState = vi.fn();
+ const executeGatewayAgentSpy = vi
+ .fn()
+ .mockRejectedValue(
+ new TRPCClientError('Topic tpc_test remained busy while starting operation'),
+ );
+
+ act(() => {
+ useChatStore.setState({
+ isGatewayModeEnabled: () => true,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ mainInputEditor: {
+ getJSONState: vi.fn().mockReturnValue({ root: { children: [], type: 'root' } }),
+ setDocument,
+ setJSONState,
+ } as any,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ editorData: inputEditorState as any,
+ message: 'Swallowed by gateway',
+ });
+ });
+
+ const sendMessageOperation = Object.values(result.current.operations).find(
+ (operation) => operation.type === 'sendMessage',
+ );
+
+ // Prove the gateway branch actually ran and failed β€” otherwise a silent
+ // early bail would satisfy the restore assertions below by accident.
+ expect(executeGatewayAgentSpy).toHaveBeenCalled();
+ expect(sendMessageOperation?.status).toBe('failed');
+
+ expect(setJSONState).toHaveBeenCalledWith(inputEditorState);
+ expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeTruthy();
+ });
+
+ it('should not restore the composer when gateway setup fails after message acceptance', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const setDocument = vi.fn();
+ const setJSONState = vi.fn();
+ const executeGatewayAgentSpy = vi.fn().mockImplementation(async (params) => {
+ params.onMessageAccepted();
+ throw new Error('gateway client initialization failed');
+ });
+
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ mainInputEditor: {
+ getJSONState: vi.fn().mockReturnValue({ root: { children: [], type: 'root' } }),
+ setDocument,
+ setJSONState,
+ } as any,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ message: 'Already persisted',
+ });
+ });
+
+ const sendMessageOperation = Object.values(result.current.operations).find(
+ (operation) => operation.type === 'sendMessage',
+ );
+ expect(executeGatewayAgentSpy).toHaveBeenCalledOnce();
+ expect(setDocument).not.toHaveBeenCalled();
+ expect(setJSONState).not.toHaveBeenCalled();
+ expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeUndefined();
+ });
+
+ it('should restore the pre-send editor snapshot when a hetero send fails', async () => {
+ // Same silent-discard shape as the gateway branch above: persistence
+ // throws, the temp rows are cleaned up, and the typed text is gone.
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const inputEditorState = {
+ root: {
+ children: [
+ {
+ children: [{ text: 'Swallowed by hetero', type: 'text', version: 1 }],
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ type: 'root',
+ version: 1,
+ },
+ };
+ const setDocument = vi.fn();
+ const setJSONState = vi.fn();
+ const sendMessageInServerSpy = vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockRejectedValue(
+ new TRPCClientError('Topic tpc_test remained busy while starting operation'),
+ );
+
+ act(() => {
+ useChatStore.setState({
+ mainInputEditor: {
+ getJSONState: vi.fn().mockReturnValue({ root: { children: [], type: 'root' } }),
+ setDocument,
+ setJSONState,
+ } as any,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ editorData: inputEditorState as any,
+ message: 'Swallowed by hetero',
+ });
+ });
+
+ const sendMessageOperation = Object.values(result.current.operations).find(
+ (operation) => operation.type === 'sendMessage',
+ );
+
+ // Prove the hetero persistence branch actually ran and failed.
+ expect(sendMessageInServerSpy).toHaveBeenCalled();
+ expect(sendMessageOperation?.status).toBe('failed');
+
+ expect(setJSONState).toHaveBeenCalledWith(inputEditorState);
+ expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeTruthy();
+ });
+
it('should move and adopt a first-turn voice row without sending local-only history', async () => {
const { result } = renderHook(() => useChatStore());
const context = createTestContext();
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 fd8d518b2b5..042cd5767bb 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -27,6 +27,7 @@ vi.mock('@/services/message', () => ({
vi.mock('@/services/topic', () => ({
topicService: {
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
},
}));
@@ -167,6 +168,7 @@ function createTestAction() {
describe('GatewayActionImpl', () => {
beforeEach(() => {
moveChatContextSelections.mockClear();
+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);
mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };
mockUserDefaultConfig.disableGatewayMode = undefined;
mockToolInterventionConfig.approvalMode = 'manual';
@@ -1345,14 +1347,10 @@ describe('GatewayActionImpl', () => {
});
});
- // A late close of a finished op must NOT retire a NEWER operation that a
- // racing retry/send already wrote β€” that would break reconnect-after-reload
- // for the live run AND flip its topic out of the running state. None of the
- // three writes (local marker, server marker, topic status) may fire when the
- // topic has moved on. Reachable whenever a follow-up starts before the
- // previous session closes: the terminal queue drain does it 100ms after the
- // terminal, and a send right after `visible_output_end` does it sooner still.
- it('does not retire the topic when its marker already belongs to a newer operation', async () => {
+ // A late close may observe a stale local marker even after another tab has
+ // started a newer operation. Send the completing operation id to the server
+ // so its row-locked compare-and-set can reject the stale clear.
+ it('settles by operation id without retiring a newer local operation', async () => {
const connectToGateway = vi.fn();
const internalDispatchTopic = vi.fn();
const updateTopicStatus = vi.fn();
@@ -1426,13 +1424,17 @@ describe('GatewayActionImpl', () => {
// Ignore any dispatches / writes from the optimistic-update path during setup.
internalDispatchTopic.mockClear();
updateTopicStatus.mockClear();
- vi.mocked(topicService.updateTopicMetadata).mockClear();
- vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);
+ vi.mocked(topicService.settleRunningOperation).mockClear();
+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);
onSessionComplete({ succeeded: false, terminalReceived: true });
expect(internalDispatchTopic).not.toHaveBeenCalled();
- expect(topicService.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'server-op-1',
+ 'active',
+ );
expect(updateTopicStatus).not.toHaveBeenCalled();
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 9cf8f116fa8..2aa00c9fe95 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -24,7 +24,6 @@ import {
} from '@lobechat/types';
import { generateEntityId, nanoid } from '@lobechat/utils';
import { toast } from '@lobehub/ui/base-ui';
-import { TRPCClientError } from '@trpc/client';
import { t } from 'i18next';
import { type ChatInputEditor } from '@/features/ChatInput';
@@ -818,6 +817,39 @@ export class ConversationLifecycleActionImpl {
const ids = options?.preserveOptimisticUser ? [tempAssistantId] : [tempId, tempAssistantId];
this.#get().internal_dispatchMessage({ ids, type: 'deleteMessages' }, { operationId });
};
+ /**
+ * Put the typed message back in the composer when a send fails before the
+ * user message was persisted. The composer is cleared the instant Enter is
+ * pressed, so without this the text is gone for good β€” the run never
+ * happened, and there is no persisted row to recover it from.
+ *
+ * Shared by all three runtime branches. Gateway and hetero previously only
+ * logged and deleted the optimistic pair, so a server-side start refusal
+ * (e.g. the topic-start reservation reporting the topic busy) was
+ * indistinguishable from the message being silently swallowed.
+ */
+ const restoreComposerAfterFailedSend = (error: unknown) => {
+ if (preserveComposer || hasNotifiedMessageAccepted) return;
+
+ // Cancellation is a deliberate user action with its own restore path
+ // (`inputEditorTempState` is replayed by the cancel flow); re-filling the
+ // composer here would fight it.
+ const isAbort =
+ error instanceof Error &&
+ (error.message.includes('aborted') || error.name === 'AbortError');
+ if (isAbort) return;
+
+ this.#get().updateOperationMetadata(operationId, {
+ inputSendErrorMsg: error instanceof Error ? error.message : 'Unknown error',
+ });
+
+ const op = this.#get().operations[operationId];
+ if (op?.metadata.inputEditorTempState) {
+ targetInputEditor?.setJSONState(op.metadata.inputEditorTempState);
+ } else {
+ targetInputEditor?.setDocument('markdown', message);
+ }
+ };
const restoreUnacceptedVoiceMessageContext = () => {
if (!optimisticUserMessageId || hasNotifiedMessageAccepted) return;
@@ -1320,6 +1352,7 @@ export class ConversationLifecycleActionImpl {
message: e instanceof Error ? e.message : 'Unknown error',
type: 'HeterogeneousAgentError',
});
+ restoreComposerAfterFailedSend(e);
}
cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });
detachUnacceptedCallerAbort();
@@ -1698,6 +1731,7 @@ export class ConversationLifecycleActionImpl {
message: e instanceof Error ? e.message : 'Unknown error',
type: 'GatewayError',
});
+ restoreComposerAfterFailedSend(e);
cleanupTempMessages({
preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),
});
@@ -1935,19 +1969,7 @@ export class ConversationLifecycleActionImpl {
});
}
- if (!preserveComposer && e instanceof TRPCClientError) {
- const isAbort = e.message.includes('aborted') || e.name === 'AbortError';
- // Check if error is due to cancellation
- if (!isAbort) {
- this.#get().updateOperationMetadata(operationId, { inputSendErrorMsg: e.message });
- const op = this.#get().operations[operationId];
- if (op?.metadata.inputEditorTempState) {
- targetInputEditor?.setJSONState(op.metadata.inputEditorTempState);
- } else {
- targetInputEditor?.setDocument('markdown', message);
- }
- }
- }
+ restoreComposerAfterFailedSend(e);
} finally {
// Roll the optimistic pair back only when the send did not land (cancel or
// failure). On success there is nothing to clean up: the rows were created
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 44c92414f6e..3ae56f773c9 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -850,39 +850,19 @@ export class GatewayActionImpl {
// terminal-missing fallback so the op never sticks `running`.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
if (result.topicId) {
- // A later run already took this topic over β€” its start wrote the new
- // `runningOperation`, and this close is just our own session winding
- // down. Both writes below are unconditional stomps, so they'd retire a
- // run that is still going: the status write kills its sidebar/home
- // "running" state and the metadata clear drops the marker
- // `useGatewayReconnect` needs to resume it after a reload.
- const superseded = this.#isSupersededRunningOperation({
- agentId: resolvedMessageContext.agentId,
- groupId: resolvedMessageContext.groupId,
- operationId: result.operationId,
- topicId: result.topicId,
- });
-
// A clean completion the user isn't watching is owned by
- // `markTopicUnread` (status: 'unread'); skip the 'active' write so
- // the two never race over the status field. Every other case (viewing,
- // error, abort) clears the running state back to 'active' as before.
+ // `markTopicUnread` (status: 'unread'). Every other case (viewing,
+ // error, abort) settles the running state back to 'active'. The server
+ // compares the operation id under the topic row lock so a late close
+ // from another tab cannot clear or settle a newer run.
const viewing = this.#get().activeTopicId === result.topicId;
- if (!superseded && (viewing || !succeeded)) {
- void this.#get().updateTopicStatus?.({
- agentId: resolvedMessageContext.agentId,
- groupId: resolvedMessageContext.groupId,
- status: 'active',
- topicId: result.topicId,
- });
- }
- // Clear running operation from topic metadata (best-effort from frontend;
- // if browser was closed, reconnect logic will handle stale entries)
- if (!superseded) {
- topicService
- .updateTopicMetadata(result.topicId, { runningOperation: null })
- .catch(() => {});
- }
+ topicService
+ .settleRunningOperation(
+ result.topicId,
+ result.operationId,
+ viewing || !succeeded ? 'active' : 'unread',
+ )
+ .catch(console.error);
// Also clear the local store copy β€” the server clear above does NOT touch
// the Zustand topic map that useGatewayReconnect reads. Ownership-guarded
// on its own, so it is safe to call either way.