π€― 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(agent-runtime): never interrupt another member's live run (#22037)
Arvin Xubd515b4dacf7
diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.tsindex 02674fd784c..e3f6cc49dac 100644--- a/apps/server/src/routers/lambda/aiAgent/exec.ts+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts@@ -20,7 +20,10 @@ import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/worimport { startComposerRun } from '@/server/services/aiAgent/composerRun';import { RequestedDeviceIgnoredError } from '@/server/services/aiAgent/pipeline/turnSetup';import { AgentRelayHopLimitError } from '@/server/services/aiAgent/sourceAttribution';-import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';+import {+ ForeignLiveRunError,+ TopicStartReservationError,+} from '@/server/services/aiAgent/topicStartReservation';import type { ExecAgentInput } from './execSchemas';import {@@ -305,6 +308,16 @@ export const execRouter = router({});}+ // Another member's run drives the topic; a send never interrupts it, and+ // nothing was written.+ if (error instanceof ForeignLiveRunError) {+ throw new TRPCError({+ cause: error,+ code: 'CONFLICT',+ message: 'Another member is running this conversation; wait until their turn finishes.',+ });+ }+// A device the caller required would be dropped by the agent's fixed// execution target; nothing was written.if (error instanceof RequestedDeviceIgnoredError) {diff --git a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts b/apps/server/src/services/agentRuntime/StaleOperationReaper.tsindex 3022d522206..7c9833537f2 100644--- a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts+++ b/apps/server/src/services/agentRuntime/StaleOperationReaper.ts@@ -16,22 +16,13 @@ import { QueueService } from '@/server/services/queue';import { AbandonOperationService } from './AbandonOperationService';import { BACKGROUND_OPERATION_TRIGGERS } from './foregroundOperation';+import {+ HETERO_OPERATION_SILENCE_MS as HETERO_SILENCE_MS,+ OPERATION_LEASE_STALE_MS as DEFAULT_STALE_AFTER_MS,+} from './operationLease';const log = debug('lobe-server:stale-operation-reaper');-/**- * How long an operation may go without refreshing its durable liveness lease- * before this sweep treats it as dead.- *- * `AgentRuntimeService.startStepLockHeartbeat` touches the row every- * `STEP_LOCK_HEARTBEAT_MS * DURABLE_LEASE_HEARTBEAT_EVERY_TICKS` = 90s while a- * step holds the step lock, so five minutes is three missed beats: comfortably- * past jitter, and far tighter than the 30-minute in-flight window the gateway- * watchdog has to use (it can only reason about stream events, which stop for- * legitimately slow first-token latency too).- */-const DEFAULT_STALE_AFTER_MS = 5 * 60_000;-/*** Redriving costs a real LLM call, so a step that dies deterministically* (poison payload, an input that reliably OOMs the host) must not be retried@@ -57,20 +48,6 @@ const DEFAULT_LIMIT = 50;*/const DEFAULT_LOOKBACK_MS = 24 * 60 * 60_000;-/**- * How long a heterogeneous run (Claude Code, Codex, β¦) may go without any- * `heteroIngest` batch before this sweep retires it.- *- * Deliberately the same window as the agent-gateway inactivity watchdog uses- * for hetero runs (`INACTIVITY_WATCHDOG_TIMEOUT_HETERO`, 60 min): a long shell- * command inside the CLI reaches the server as silence, and this must not be- * stricter than the path it backs up. The two read the same clock β every- * ingest batch both refreshes this lease and pushes the events that reset the- * gateway's β so whichever runs first wins and the other finds the row- * terminal.- */-const HETERO_SILENCE_MS = 60 * 60_000;-const isHeterogeneousProvider = (provider: string | null | undefined): boolean =>!!provider &&(isLocalHeterogeneousType(provider) ||diff --git a/apps/server/src/services/agentRuntime/operationLease.ts b/apps/server/src/services/agentRuntime/operationLease.tsnew file mode 100644index 00000000000..7661ac6760a--- /dev/null+++ b/apps/server/src/services/agentRuntime/operationLease.ts@@ -0,0 +1,35 @@+/**+ * How long an operation may go without refreshing its durable liveness lease+ * (`agent_operations.updated_at`) before it is treated as dead.+ *+ * `AgentRuntimeService.startStepLockHeartbeat` touches the row every+ * `STEP_LOCK_HEARTBEAT_MS * DURABLE_LEASE_HEARTBEAT_EVERY_TICKS` = 90s while a+ * step holds the step lock, so five minutes is three missed beats: comfortably+ * past jitter, and far tighter than the 30-minute in-flight window the gateway+ * watchdog has to use (it can only reason about stream events, which stop for+ * legitimately slow first-token latency too).+ */+export const OPERATION_LEASE_STALE_MS = 5 * 60_000;++/**+ * How long a heterogeneous run (Claude Code, Codex, β¦) may go without any+ * `heteroIngest` batch before it is treated as dead.+ *+ * Deliberately the same window as the agent-gateway inactivity watchdog uses+ * for hetero runs (`INACTIVITY_WATCHDOG_TIMEOUT_HETERO`, 60 min): a long shell+ * command inside the CLI reaches the server as silence, and this must not be+ * stricter than the path it backs up. The two read the same clock β every+ * ingest batch both refreshes this lease and pushes the events that reset the+ * gateway's β so whichever runs first wins and the other finds the row+ * terminal.+ */+export const HETERO_OPERATION_SILENCE_MS = 60 * 60_000;++/** Whether a `running` row's lease was refreshed recently enough to count as alive. */+export const isOperationLeaseFresh = (+ operation: { updatedAt: Date },+ options: { heterogeneous?: boolean; now?: number } = {},+): boolean => {+ const window = options.heterogeneous ? HETERO_OPERATION_SILENCE_MS : OPERATION_LEASE_STALE_MS;+ return (options.now ?? Date.now()) - operation.updatedAt.getTime() < window;+};diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.tsindex fdfa5665209..8dded3fc034 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts@@ -2,6 +2,7 @@ import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';+import { ForeignLiveRunError } from '../topicStartReservation';const {mockFindOperationById,@@ -223,6 +224,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()mockFindOperationById.mockImplementation(async (id: string) => ({id,status: 'running',+ userId: 'test-user-id',topicId: 'topic-1',trigger: 'chat',}));@@ -248,7 +250,9 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()it('ignores a replaced operation that is not on this topic', async () => {mockFindOperationById.mockImplementation(async (id: string) =>- id === 'op-foreign' ? null : { id, status: 'running', topicId: 'topic-1', trigger: 'chat' },+ id === 'op-foreign'+ ? null+ : { id, status: 'running', topicId: 'topic-1', trigger: 'chat', userId: 'test-user-id' },);await service.execAgent({@@ -313,6 +317,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()id: 'op-live',status: 'running',trigger: 'onboarding',+ userId: 'test-user-id',});await service.execAgent({@@ -334,6 +339,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()status: 'running',topicId: 'topic-1',trigger: 'agent_signal',+ userId: 'test-user-id',});await service.execAgent({@@ -370,6 +376,108 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()expect(interruptTask).not.toHaveBeenCalled();});+ // Workspace topics are shared: a teammate's send used to interrupt the run+ // its starter was driving, because the holder was retired regardless of owner.+ it("refuses the send instead of interrupting another member's running holder", async () => {+ mockFindOperationById.mockResolvedValue({+ id: 'op-live',+ status: 'running',+ topicId: 'topic-1',+ trigger: 'chat',+ updatedAt: new Date(),+ userId: 'teammate-id',+ });++ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'keep going',+ }),+ ).rejects.toBeInstanceOf(ForeignLiveRunError);++ expect(interruptTask).not.toHaveBeenCalled();+ expect(mockMessageCreate).not.toHaveBeenCalled();+ expect(mockReleaseReservation).toHaveBeenCalled();+ });++ it("does not interrupt another member's run named as the replaced operation", async () => {+ mockFindOperationById.mockResolvedValue({+ id: 'op-live',+ status: 'running',+ topicId: 'topic-1',+ trigger: 'chat',+ updatedAt: new Date(),+ userId: 'teammate-id',+ });++ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'keep going',+ replacesOperationId: 'op-live',+ }),+ ).rejects.toBeInstanceOf(ForeignLiveRunError);++ expect(interruptTask).not.toHaveBeenCalled();+ });++ it("retires another member's run whose lease froze, which nothing would otherwise settle", async () => {+ mockFindOperationById.mockResolvedValue({+ id: 'op-live',+ status: 'running',+ topicId: 'topic-1',+ trigger: 'chat',+ updatedAt: new Date(Date.now() - 10 * 60_000),+ userId: 'teammate-id',+ });++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'keep going',+ });++ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });+ });++ it("refuses the send next to another member's live device-hosted run", async () => {+ mockFindTopicById.mockResolvedValue({+ id: 'topic-1',+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-old',+ heteroType: 'claude-code',+ operationId: 'op-live',+ },+ },+ });+ mockFindOperationById.mockResolvedValue({+ id: 'op-live',+ status: 'running',+ topicId: 'topic-1',+ trigger: 'chat',+ updatedAt: new Date(Date.now() - 20 * 60_000),+ userId: 'teammate-id',+ });++ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'keep going',+ replacesOperationId: 'op-live',+ }),+ ).rejects.toBeInstanceOf(ForeignLiveRunError);++ expect(interruptTask).not.toHaveBeenCalled();+ });+it.each([['a finished marker holder', { status: 'done', trigger: 'chat' }],['a parked marker holder', { status: 'waiting_for_human', trigger: 'chat' }],diff --git a/apps/server/src/services/aiAgent/pipeline/topicStart.ts b/apps/server/src/services/aiAgent/pipeline/topicStart.tsindex 02690456bda..f2bf318fa12 100644--- a/apps/server/src/services/aiAgent/pipeline/topicStart.ts+++ b/apps/server/src/services/aiAgent/pipeline/topicStart.ts@@ -12,10 +12,15 @@ import {type SupersedeKind,type SupersedeRecord,} from '@/server/services/agentRuntime/foregroundOperation';+import { isOperationLeaseFresh } from '@/server/services/agentRuntime/operationLease';import { redisService } from '@/server/services/redis';import type { SteerQueueScope } from '@/server/services/redis/steerQueue';-import { acquireTopicStartReservation, TopicStartReservationError } from '../topicStartReservation';+import {+ acquireTopicStartReservation,+ ForeignLiveRunError,+ TopicStartReservationError,+} from '../topicStartReservation';import type { InternalExecAgentParams } from '../types';const log = debug('lobe-server:ai-agent-service');@@ -53,7 +58,10 @@ export const resolveReplacedOperationId = async (if (!replacesOperationId || !params.interactiveStart) return replacesOperationId;const replaced = await deps.agentOperationModel.findById(replacesOperationId);- return replaced?.topicId === topicId ? replacesOperationId : undefined;+ // Workspace reads are member-wide, so the row may be a teammate's run.+ return replaced?.topicId === topicId && replaced.userId === deps.userId+ ? replacesOperationId+ : undefined;};/**@@ -80,6 +88,10 @@ export const resolveReplacedOperationId = async (* concurrent send would fail. Those settle through `replacesOperationId`* before reserving.*+ * A send never retires another member's live run: in a workspace topic a+ * teammate may be driving it, so the start is refused with+ * {@link ForeignLiveRunError}. That also covers a teammate's device-hosted run.+ ** @returns the retired run and whether it had already been asked to stop, so* the caller can record the overlap on the new run.*/@@ -91,11 +103,29 @@ export const supersedeRunningForegroundOperation = async (const topic = await deps.topicModel.findById(topicId);const marker = topic?.metadata?.runningOperation;const holderId = marker?.operationId;- if (!holderId || marker.heteroType || alreadyHandledOperationIds.includes(holderId)) return;+ if (!holderId || alreadyHandledOperationIds.includes(holderId)) return;const holder = await deps.agentOperationModel.findById(holderId);if (holder?.status !== 'running') return;++ // A teammate's run the send would retire (or run next to, for a device+ // process) refuses the send. One whose lease froze is dead β often a+ // `running` row nothing will ever settle β and must not lock the topic, so+ // it keeps the behavior below.+ const heterogeneous = Boolean(marker.heteroType);+ const refuseIfForeignAndAlive = () => {+ if (holder.userId === deps.userId || !isOperationLeaseFresh(holder, { heterogeneous })) return;+ throw new ForeignLiveRunError(+ `Topic ${topicId} is driven by another member's running operation ${holderId}`,+ );+ };++ if (heterogeneous) {+ refuseIfForeignAndAlive();+ return;+ }if (!isComposerSupersedableTrigger(holder.trigger)) return;+ refuseIfForeignAndAlive();// Read before interrupting: afterwards the sentinel is always set. The// read is diagnostic only, so a failure must not fail the send.diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.tsindex ec065953295..84107d8991a 100644--- a/apps/server/src/services/aiAgent/topicStartReservation.ts+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts@@ -20,6 +20,19 @@ export class TopicStartReservationError extends Error {}}+/**+ * An interactive send found the topic driven by another member's live+ * foreground run. A send only ever retires its own sender's runs, so the+ * start is refused β before anything is written, like+ * {@link TopicStartReservationError} β instead of interrupting a teammate.+ */+export class ForeignLiveRunError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ForeignLiveRunError';+ }+}+/*** Claim the gap between choosing a conversation parent and publishing the* operation's `runningOperation` marker. Every existing-topic start uses thediff --git a/packages/openapi/src/services/__tests__/im.service.test.ts b/packages/openapi/src/services/__tests__/im.service.test.tsindex 3771b681766..187b15ee129 100644--- a/packages/openapi/src/services/__tests__/im.service.test.ts+++ b/packages/openapi/src/services/__tests__/im.service.test.ts@@ -17,6 +17,7 @@ import {users,workspaces,} from '@/database/schemas';+import { ForeignLiveRunError } from '@/server/services/aiAgent/topicStartReservation';import { ImSendRequestSchema } from '../../types/im.type';import { ImRestService } from '../im.service';@@ -732,6 +733,14 @@ describe('ImRestService.send', () => {);});+ it("answers a conflict when another member's run drives the conversation", async () => {+ execAgentMock.mockRejectedValue(new ForeignLiveRunError('topic busy'));++ await expect(+ service.send({ agentId: AGENT, content: 'keep going', topicId: TOPIC }),+ ).rejects.toMatchObject({ name: 'ConflictError' });+ });+it('refuses an agentId that is not a member of the group', async () => {await insertGroup();diff --git a/packages/openapi/src/services/im.service.ts b/packages/openapi/src/services/im.service.tsindex 61d48d11893..4a215168119 100644--- a/packages/openapi/src/services/im.service.ts+++ b/packages/openapi/src/services/im.service.ts@@ -11,6 +11,7 @@ import { agentOperations, messages, messagesFiles, pushTokens, topics } from '@/import type { LobeChatDatabase } from '@/database/type';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';import { AiAgentService } from '@/server/services/aiAgent';+import { ForeignLiveRunError } from '@/server/services/aiAgent/topicStartReservation';import { FileService } from '@/server/services/file';import { BaseService } from '../common/base.service';@@ -238,6 +239,12 @@ export class ImRestService extends BaseService {// receipt that won instead of failing a request the client will retry.const raced = await this.idempotentReceipt(input.clientMessageId);if (raced) return raced;+ // Another member's run drives the topic; nothing was written.+ if (error instanceof ForeignLiveRunError) {+ throw this.createConflictError(+ 'Another member is running this conversation; wait until their turn finishes.',+ );+ }throw error;}