π€― 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): supersede the running op on interactive send (#20136)
YuTengjing7ce191418aa3
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex fda712b024f..9774887b202 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -16,6 +16,7 @@ import type * as ModelBankModule from 'model-bank';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';+import { AiAgentService } from '@/server/services/aiAgent';import {assertCanPerformResourceAction,getResourceMeta,@@ -494,6 +495,24 @@ describe('AI Agent Router Integration Tests', () => {expect(assistantMessages).toHaveLength(1);expect(assistantMessages[0].parentId).toBe(userMsg.id);});++ it('forwards the replaced operation to the service', async () => {+ const execAgent = vi+ .spyOn(AiAgentService.prototype, 'execAgent')+ .mockResolvedValue({ operationId: 'op-new', success: true } as any);+ const caller = aiAgentRouter.createCaller(createTestContext());++ await caller.execAgent({+ agentId: testAgentId,+ prompt: 'send now',+ replacesOperationId: 'op-old',+ });++ expect(execAgent).toHaveBeenCalledWith(+ expect.objectContaining({ interactiveStart: true, replacesOperationId: 'op-old' }),+ );+ execAgent.mockRestore();+ });});describe('issueGatewayUserToken', () => {diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex e1b5204dac6..70ca75ce8b0 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -90,6 +90,7 @@ import {ResolveAgentInterventionSchema,} from '@/server/routers/lambda/_schema/agentIntervention';import { AgentRuntimeService } from '@/server/services/agentRuntime';+import { MAX_CLIENT_OPERATION_SNAPSHOT } from '@/server/services/agentRuntime/foregroundOperation';import { AiAgentService } from '@/server/services/aiAgent';import { AiChatService } from '@/server/services/aiChat';import { getFileProxyUrl } from '@/server/services/file';@@ -1079,6 +1080,21 @@ const ExecAgentSchema = zparentMessageId: z.string().optional(),/** Existing gateway operation this fresh turn atomically supersedes. */replacesOperationId: z.string().optional(),+ /**+ * The server runs the composer tracked on this conversation at send time.+ * Diagnostic only: recorded when this send has to supersede a live run.+ */+ clientOperations: z+ .array(+ z.object({+ isAborting: z.boolean().optional(),+ operationId: z.string(),+ status: z.string(),+ visibleLoadingDone: z.boolean().optional(),+ }),+ )+ .max(MAX_CLIENT_OPERATION_SNAPSHOT)+ .optional(),/** The user input/prompt */prompt: z.string(),/**@@ -2399,6 +2415,10 @@ export const aiAgentRouter = router({appContext,autoStart,clientIds: input.clientIds,+ clientRunSnapshot: {+ operations: input.clientOperations ?? [],+ replacesOperationId: input.replacesOperationId,+ },includeFinalState: input.includeFinalState,// This procedure serves the composer (`aiAgentService.execAgentTask`).// The client already queues follow-ups behind a live run and shows the@@ -2416,6 +2436,7 @@ export const aiAgentRouter = router({mentionedAgents,parentMessageId,prompt,+ replacesOperationId: input.replacesOperationId,// When parentMessageId is provided, this is a regeneration/continue or a// human-approval resume β either way, skip user message creation.resume: !!parentMessageId,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 91106efdeda..a08c8fca330 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -686,6 +686,14 @@ export class AgentRuntimeService {// ==================== Operation Interruption ====================+ /**+ * Whether someone already asked this run to stop (the interrupt sentinel is+ * set), even though it may still be finishing its current step.+ */+ async isOperationInterrupted(operationId: string): Promise<boolean> {+ return this.coordinator.isInterrupted(operationId);+ }+/*** Interrupt a running agent operation by setting its state to 'interrupted'.* The agent will stop at the next step boundary (cannot abort an in-flight LLM call).diff --git a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts b/apps/server/src/services/agentRuntime/StaleOperationReaper.tsindex 53e7142abff..18c6dcb1fc4 100644--- a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts+++ b/apps/server/src/services/agentRuntime/StaleOperationReaper.ts@@ -1,6 +1,6 @@import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';import debug from 'debug';-import { and, asc, eq, isNull, lt, or } from 'drizzle-orm';+import { and, asc, eq, isNotNull, isNull, lt, notInArray, or, sql } from 'drizzle-orm';import urlJoin from 'url-join';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -10,6 +10,7 @@ import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimport { QueueService } from '@/server/services/queue';import { AbandonOperationService } from './AbandonOperationService';+import { BACKGROUND_OPERATION_TRIGGERS } from './foregroundOperation';const log = debug('lobe-server:stale-operation-reaper');@@ -37,6 +38,9 @@ const DEFAULT_MAX_REDRIVE_ATTEMPTS = 3;/** Bound the work of a single cron tick so one sweep cannot run long. */const DEFAULT_LIMIT = 50;+/** Bound how many overlapping topics one sweep reports. */+const CONCURRENT_FOREGROUND_REPORT_LIMIT = 20;+export interface ReapStaleOperationsParams {limit?: number;maxRedriveAttempts?: number;@@ -48,6 +52,15 @@ export interface ReapStaleOperationsResult {abandoned: number;/** Candidates whose lease was refreshed between select and claim. */alive: number;+ /**+ * Topics with two or more foreground runs `running` at once where an older+ * run was never asked to stop. Composer sends supersede the previous run, so+ * such an overlap means a start path slipped past that and both runs are+ * spending on the same conversation. An older run that already carries the+ * interrupt sentinel is only finishing its current step and is not counted.+ * Detection only: nothing is interrupted.+ */+ concurrentForegroundTopics: number;examined: number;/*** Candidates whose recovery threw (Redis, database or queue failure). Reported@@ -115,6 +128,7 @@ export class StaleOperationReaper {const result: ReapStaleOperationsResult = {abandoned: 0,alive: 0,+ concurrentForegroundTopics: 0,examined: candidates.length,failed: 0,redriven: 0,@@ -132,10 +146,66 @@ export class StaleOperationReaper {}}+ try {+ result.concurrentForegroundTopics = await this.reportConcurrentForegroundRuns();+ } catch (e) {+ log('concurrent foreground patrol failed: %O', e);+ }+log('sweep done: %O', result);return result;}+ /**+ * Warn about topics where more than one foreground run is live. Top-level+ * runs only: sub-agent children (`parentOperationId`) and thread runs+ * (`threadId`) legitimately run beside the topic's main run.+ */+ private async reportConcurrentForegroundRuns(): Promise<number> {+ const rows = await this.db+ .select({+ operationIds: sql<+ string[]+ >`array_agg(${agentOperations.id} order by ${agentOperations.createdAt})`,+ topicId: agentOperations.topicId,+ })+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.status, 'running'),+ isNotNull(agentOperations.topicId),+ isNull(agentOperations.threadId),+ isNull(agentOperations.parentOperationId),+ or(+ isNull(agentOperations.trigger),+ notInArray(agentOperations.trigger, [...BACKGROUND_OPERATION_TRIGGERS]),+ ),+ ),+ )+ .groupBy(agentOperations.topicId)+ .having(sql`count(*) > 1`)+ .limit(CONCURRENT_FOREGROUND_REPORT_LIMIT);++ let reported = 0;+ for (const row of rows) {+ // The newest run is the one that should survive; an older run with the+ // sentinel set was stopped (Stop / Send now / supersede) and exits at its+ // next step boundary, which can be minutes into a long LLM call.+ const older = row.operationIds.slice(0, -1);+ const interrupted = await Promise.all(older.map((id) => this.coordinator.isInterrupted(id)));+ const unstopped = older.filter((_, index) => !interrupted[index]);+ if (unstopped.length === 0) continue;++ reported += 1;+ console.warn('[StaleOperationReaper] concurrent foreground operations on one topic', {+ ...row,+ unstoppedOperationIds: unstopped,+ });+ }++ return reported;+ }+/*** Stale candidates across all tenants. Queried directly rather than through* `AgentOperationModel`, which is user-scoped by construction β this is adiff --git a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.tsindex b5bb7352da0..56c948aa41b 100644--- a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts@@ -23,12 +23,18 @@ vi.mock('../AbandonOperationService', () => ({}),}));-/** Minimal drizzle select chain returning `rows`. */-const buildDb = (rows: any[]) =>+/**+ * Minimal drizzle select chains: the stale-candidate query (`orderBy`) returns+ * `rows`, the concurrent-foreground patrol (`groupBy`) returns `overlapRows`.+ */+const buildDb = (rows: any[], overlapRows: any[] = []) =>({select: () => ({from: () => ({where: () => ({+ groupBy: () => ({+ having: () => ({ limit: vi.fn().mockResolvedValue(overlapRows) }),+ }),orderBy: () => ({ limit: vi.fn().mockResolvedValue(rows) }),}),}),@@ -43,8 +49,13 @@ const candidate = (id = 'op_x') => ({workspaceId: null,});-const buildCoordinator = (state: any, history: any[] = []) => ({+const buildCoordinator = (+ state: any,+ history: any[] = [],+ isInterrupted: (id: string) => boolean = () => false,+) => ({getExecutionHistory: vi.fn().mockResolvedValue(history),+ isInterrupted: vi.fn(async (id: string) => isInterrupted(id)),loadAgentState: vi.fn().mockResolvedValue(state),});const buildQueue = () => ({ scheduleMessage: vi.fn().mockResolvedValue('msg_1') });@@ -264,4 +275,56 @@ describe('StaleOperationReaper', () => {expect(maxAttempts).toBe(3);expect(staleBefore.getTime()).toBeLessThanOrEqual(before - 60_000 + 5);});++ it('reports topics with more than one foreground run live', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const overlap = { operationIds: ['op_a', 'op_b'], topicId: 'tpc_x' };+ const reaper = new StaleOperationReaper(buildDb([], [overlap]), {+ coordinator: buildCoordinator(null) as any,+ queueService: buildQueue() as any,+ });++ const result = await reaper.sweep();++ expect(result.concurrentForegroundTopics).toBe(1);+ expect(warn).toHaveBeenCalledWith(+ '[StaleOperationReaper] concurrent foreground operations on one topic',+ { ...overlap, unstoppedOperationIds: ['op_a'] },+ );+ warn.mockRestore();+ });++ it('ignores an overlap whose older runs were already asked to stop', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const overlap = { operationIds: ['op_a', 'op_b'], topicId: 'tpc_x' };+ const reaper = new StaleOperationReaper(buildDb([], [overlap]), {+ coordinator: buildCoordinator(null, [], (id) => id === 'op_a') as any,+ queueService: buildQueue() as any,+ });++ const result = await reaper.sweep();++ expect(result.concurrentForegroundTopics).toBe(0);+ expect(warn).not.toHaveBeenCalled();+ warn.mockRestore();+ });++ it('still reports recovery results when the patrol query fails', async () => {+ const db = buildDb([candidate()]);+ const select = db.select;+ let calls = 0;+ db.select = () => {+ calls += 1;+ if (calls === 1) return select();+ throw new Error('db down');+ };+ const reaper = new StaleOperationReaper(db, {+ coordinator: buildCoordinator(runningState(), historyFor(6)) as any,+ queueService: buildQueue() as any,+ });++ const result = await reaper.sweep();++ expect(result).toMatchObject({ concurrentForegroundTopics: 0, redriven: 1 });+ });});diff --git a/apps/server/src/services/agentRuntime/foregroundOperation.ts b/apps/server/src/services/agentRuntime/foregroundOperation.tsnew file mode 100644index 00000000000..82d256bf978--- /dev/null+++ b/apps/server/src/services/agentRuntime/foregroundOperation.ts@@ -0,0 +1,70 @@+import { RequestTrigger } from '@lobechat/types';++/**+ * Triggers of runs started by a producer other than the composer. Any other+ * trigger (chat, onboarding, β¦, or a legacy row without one) counts as a+ * foreground run: at most one of those should be live on a topic at a time.+ */+export const BACKGROUND_OPERATION_TRIGGERS: ReadonlySet<string> = new Set<string>([+ RequestTrigger.AgentShare,+ RequestTrigger.AgentSignal,+ RequestTrigger.Api,+ RequestTrigger.Bot,+ RequestTrigger.Cli,+ RequestTrigger.Cron,+ RequestTrigger.Eval,+ RequestTrigger.Goal,+ RequestTrigger.Notify,+ RequestTrigger.Openapi,+ RequestTrigger.Scheduled,+ RequestTrigger.Scm,+ RequestTrigger.Task,+ RequestTrigger.Verify,+]);++export const isForegroundOperationTrigger = (trigger: string | null | undefined): boolean =>+ !trigger || !BACKGROUND_OPERATION_TRIGGERS.has(trigger);++/**+ * How a composer send found the topic's previous foreground run still `running`.+ *+ * - `already_stopping`: the client had already interrupted it (Stop / Send now)+ * and it is finishing its current step β the expected overlap.+ * - `client_missed`: nothing had asked it to stop. The client neither cancelled+ * nor replaced a run that was still live; the server-side supersede is the+ * only thing that stopped it.+ * - `unknown`: the interrupt sentinel could not be read, so the overlap was+ * superseded without classifying it.+ */+export type SupersedeKind = 'already_stopping' | 'client_missed' | 'unknown';++/** One server run the client tracked on this conversation when it sent. */+export interface ClientOperationSnapshotItem {+ isAborting?: boolean;+ operationId: string;+ status: string;+ visibleLoadingDone?: boolean;+}++/**+ * What the client believed about this conversation's runs when it sent.+ * Recorded only when a supersede happens, to tell *why* the client missed a+ * live run: absent from `operations` means it never tracked the run; present+ * as cancelled means its stop never reached the server.+ */+export interface ClientRunSnapshot {+ operations: ClientOperationSnapshotItem[];+ /** The run the client asked to replace, as sent on the request. */+ replacesOperationId?: string;+}++/** Upper bound on snapshot entries accepted from the client. */+export const MAX_CLIENT_OPERATION_SNAPSHOT = 10;++/** Written to `agent_operations.metadata.supersede` of the run that superseded another. */+export interface SupersedeRecord {+ client?: ClientRunSnapshot;+ kind: SupersedeKind;+ supersededAt: string;+ supersededOperationId: string;+}diff --git a/apps/server/src/services/agentRuntime/index.ts b/apps/server/src/services/agentRuntime/index.tsindex 2c4ab9009b8..f53935f86b5 100644--- a/apps/server/src/services/agentRuntime/index.ts+++ b/apps/server/src/services/agentRuntime/index.ts@@ -1,4 +1,5 @@export * from './AbandonOperationService';export * from './AgentRuntimeService';+export * from './foregroundOperation';export * from './StaleOperationReaper';export * from './types';diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.tsnew file mode 100644index 00000000000..986d1d9cfb9--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts@@ -0,0 +1,490 @@+import type * as ModelBankModule from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++const {+ mockFindOperationById,+ mockFindTopicById,+ mockIsOperationInterrupted,+ mockMergeMetadata,+ mockGetLatestNonToolMessageId,+ mockGetLatestSpineMessageId,+ mockMessageCreate,+ mockReleaseReservation,+ mockTryReserve,+} = vi.hoisted(() => ({+ mockFindOperationById: vi.fn(),+ mockFindTopicById: vi.fn(),+ mockIsOperationInterrupted: vi.fn(),+ mockMergeMetadata: vi.fn(),+ mockGetLatestNonToolMessageId: vi.fn(),+ mockGetLatestSpineMessageId: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockReleaseReservation: vi.fn(),+ mockTryReserve: vi.fn(),+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ create: mockMessageCreate,+ getLatestNonToolMessageId: mockGetLatestNonToolMessageId,+ getLatestSpineMessageId: mockGetLatestSpineMessageId,+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ };+ }),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ queryAgents: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: mockFindTopicById,+ releaseTaskCallbackReservation: mockReleaseReservation,+ tryReserveTaskCallback: mockTryReserve,+ updateMetadata: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return { findById: mockFindOperationById, mergeMetadata: mockMergeMetadata };+ }),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ }),+}));++vi.mock('@/database/models/chatGroup', () => ({+ ChatGroupModel: vi.fn().mockImplementation(function () {+ return {+ findById: vi.fn().mockResolvedValue(undefined),+ getGroupAgentsWithMeta: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ isOperationInterrupted: mockIsOperationInterrupted,+ };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(function () {+ return {+ getComposioManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {+ uploadFromUrl: vi.fn(),+ };+ }),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++const topicWithMarker = (operationId: string) => ({+ id: 'topic-1',+ metadata: { runningOperation: { assistantMessageId: 'asst-old', operationId } },+});++/**+ * Regression: a composer send that starts a new run on a topic must retire the+ * foreground run still holding `runningOperation`. The client picks only one+ * op as `replacesOperationId`; when it picks an older, already-stopping op, the+ * live marker holder used to keep running next to the new run. Both then read+ * the same topic, interleave writes, and break each other's prompt cache.+ */+describe('AiAgentService.execAgent - supersede running foreground operation', () => {+ let service: AiAgentService;+ let interruptTask: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockMessageCreate.mockImplementation(async (payload: { role: string }) => ({+ id: payload.role === 'user' ? 'user-msg-1' : 'assistant-msg-1',+ }));+ mockGetLatestSpineMessageId.mockResolvedValue('spine-head-1');+ mockGetLatestNonToolMessageId.mockResolvedValue(undefined);+ mockTryReserve.mockResolvedValue(true);+ mockReleaseReservation.mockResolvedValue(undefined);+ mockFindTopicById.mockResolvedValue(topicWithMarker('op-live'));+ mockFindOperationById.mockImplementation(async (id: string) => ({+ id,+ status: 'running',+ topicId: 'topic-1',+ trigger: 'chat',+ }));+ mockIsOperationInterrupted.mockResolvedValue(false);+ mockMergeMetadata.mockResolvedValue(true);++ service = new AiAgentService({} as any, 'test-user-id');+ interruptTask = vi.spyOn(service, 'interruptTask').mockResolvedValue({ success: true });+ });++ it('interrupts the live marker holder when the client replaced a different operation', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ replacesOperationId: 'op-stopping',+ });++ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-stopping', topicId: 'topic-1' });+ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });+ });++ 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' },+ );++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ replacesOperationId: 'op-foreign',+ });++ expect(interruptTask).not.toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op-foreign' }),+ );+ expect(mockTryReserve).toHaveBeenCalledWith(+ 'topic-1',+ expect.any(String),+ expect.objectContaining({ replacesOperationId: undefined }),+ );+ });++ it('refuses the send when a replaced device run does not confirm it exited', async () => {+ interruptTask.mockResolvedValue({ deviceCancellationConfirmed: false, success: false });++ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ replacesOperationId: 'op-stopping',+ }),+ ).rejects.toThrow('Replaced heterogeneous agent process did not confirm termination');+ expect(mockTryReserve).not.toHaveBeenCalled();+ });++ it('interrupts the live marker holder when the client sent no replacement', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(interruptTask).toHaveBeenCalledTimes(1);+ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });+ });++ it('does not interrupt the marker holder twice when it is the replaced operation', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ replacesOperationId: 'op-live',+ });++ expect(interruptTask).toHaveBeenCalledTimes(1);+ });++ it('interrupts a running onboarding holder, which also comes from the composer', async () => {+ mockFindOperationById.mockResolvedValue({+ id: 'op-live',+ status: 'running',+ trigger: 'onboarding',+ });++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });+ });++ it('leaves a device-hosted heterogeneous holder to the replacement path', async () => {+ mockFindTopicById.mockResolvedValue({+ id: 'topic-1',+ metadata: {+ runningOperation: { deviceId: 'dev-1', heteroType: 'claude-code', operationId: 'op-live' },+ },+ });++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(interruptTask).not.toHaveBeenCalled();+ });++ it.each([+ ['a finished marker holder', { status: 'done', trigger: 'chat' }],+ ['a parked marker holder', { status: 'waiting_for_human', trigger: 'chat' }],+ ['a cron marker holder', { status: 'running', trigger: 'cron' }],+ ['a task marker holder', { status: 'running', trigger: 'task' }],+ ])('leaves %s alone', async (_, operation) => {+ mockFindOperationById.mockResolvedValue({ id: 'op-live', ...operation });++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(interruptTask).not.toHaveBeenCalled();+ });++ it('records a client_missed supersede with the client snapshot on the new run', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const clientRunSnapshot = {+ operations: [{ operationId: 'op-old', status: 'success' }],+ replacesOperationId: 'op-stopping',+ };++ const result = await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ clientRunSnapshot,+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(mockMergeMetadata).toHaveBeenCalledWith(result.operationId, {+ supersede: {+ client: clientRunSnapshot,+ kind: 'client_missed',+ supersededAt: expect.any(String),+ supersededOperationId: 'op-live',+ },+ });+ expect(warn).toHaveBeenCalledWith(+ '[execAgent] client missed a running foreground operation',+ expect.objectContaining({ supersededOperationId: 'op-live', topicId: 'topic-1' }),+ );+ warn.mockRestore();+ });++ it('records an already_stopping supersede without warning', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mockIsOperationInterrupted.mockResolvedValue(true);++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(mockMergeMetadata).toHaveBeenCalledWith(expect.any(String), {+ supersede: expect.objectContaining({ kind: 'already_stopping' }),+ });+ expect(warn).not.toHaveBeenCalledWith(+ '[execAgent] client missed a running foreground operation',+ expect.anything(),+ );+ warn.mockRestore();+ });++ it('does not fail the send when recording the supersede fails', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ mockMergeMetadata.mockRejectedValue(new Error('db down'));++ const result = await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(result.success).toBe(true);+ error.mockRestore();+ });++ it('still supersedes when the interrupt state cannot be read', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ mockIsOperationInterrupted.mockRejectedValue(new Error('redis down'));++ const result = await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(result.success).toBe(true);+ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });+ expect(mockMergeMetadata).toHaveBeenCalledWith(result.operationId, {+ supersede: expect.objectContaining({ kind: 'unknown' }),+ });+ error.mockRestore();+ });++ it('starts the new run and warns when the supersede is not confirmed', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ interruptTask.mockResolvedValue({ success: false });++ const result = await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(result.success).toBe(true);+ expect(warn).toHaveBeenCalledWith('[execAgent] supersede of %s was not confirmed', 'op-live', {+ topicId: 'topic-1',+ });+ warn.mockRestore();+ });++ it('records nothing when no run was superseded', async () => {+ mockFindOperationById.mockResolvedValue({ id: 'op-live', status: 'done', trigger: 'chat' });++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ interactiveStart: true,+ prompt: 'please hurry',+ });++ expect(mockMergeMetadata).not.toHaveBeenCalled();+ });++ it('keeps non-interactive starts on the existing path', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ prompt: 'task callback',+ });++ expect(interruptTask).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 7fd45312db2..7256a917a96 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -44,6 +44,12 @@ import type {} from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { getAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';+// Imported from the module itself: tests mock the `agentRuntime` barrel.+import {+ isForegroundOperationTrigger,+ type SupersedeKind,+ type SupersedeRecord,+} from '@/server/services/agentRuntime/foregroundOperation';import type {ExecGroupMemberParams,ExecGroupMemberResult,@@ -603,13 +609,17 @@ export class AiAgentService {return withCreatedThread(await this.execAgentWithApprovalRollback(params));}+ const replacesOperationId = isInterventionThreadStart+ ? undefined+ : await this.resolveReplacedOperationId(params, topicId);+// A replacement is allowed to take over the topic marker, but the device// process that owned the old marker may still hold a native Codex/CC writer.// Settle that physical run before reserving and dispatching the replacement;// otherwise two `lh hetero exec` wrappers can resume the same thread.- if (params.replacesOperationId && !isInterventionThreadStart) {+ if (replacesOperationId) {const interruption = await this.interruptTask({- operationId: params.replacesOperationId,+ operationId: replacesOperationId,topicId,});if (interruption.deviceCancellationConfirmed === false) {@@ -618,7 +628,7 @@ export class AiAgentService {}const reserved = await acquireTopicStartReservation({allowSameReservationReentry: !params.approvalResolutionRequestId,- replacesOperationId: isInterventionThreadStart ? undefined : params.replacesOperationId,+ replacesOperationId,allowRunningOperationId: params.topicStartOwnerOperationId,// A thread continuation shares the topic row but never owns/replaces its// main runningOperation anchor. It uses only the short initializer fence.@@ -633,12 +643,140 @@ export class AiAgentService {}try {- return withCreatedThread(await this.execAgentWithApprovalRollback(params));+ const superseded =+ params.interactiveStart && !isInterventionThreadStart+ ? await this.supersedeRunningForegroundOperation(topicId, [+ replacesOperationId,+ params.topicStartOwnerOperationId,+ ])+ : undefined;+ const result = await this.execAgentWithApprovalRollback(params);+ if (superseded) {+ await this.recordSupersede(topicId, result.operationId, superseded, params);+ }+ return withCreatedThread(result);} finally {await this.topicModel.releaseTaskCallbackReservation(topicId, reservationId);}}+ /**+ * The run this start replaces. A composer send names it from client state, so+ * it is honored only when it is one of this user's runs on the same topic;+ * server-derived continuations are trusted as given.+ */+ private async resolveReplacedOperationId(+ params: InternalExecAgentParams,+ topicId: string,+ ): Promise<string | undefined> {+ const { replacesOperationId } = params;+ if (!replacesOperationId || !params.interactiveStart) return replacesOperationId;++ const replaced = await this.agentOperationModel.findById(replacesOperationId);+ return replaced?.topicId === topicId ? replacesOperationId : undefined;+ }++ /**+ * Retire the foreground run that still owns the topic's `runningOperation`+ * before an interactive send starts the next one.+ *+ * The client is expected to stop a live run before sending (Stop / Send now)+ * or to queue the send until the run yields. When it misses one, nothing else+ * stops that run: `startOperation` overwrites the marker, and both runs keep+ * reading the same topic, interleave writes, and invalidate each other's+ * prompt cache, multiplying the conversation's cost for as long as the old+ * run lives.+ *+ * Runs inside the topic-start reservation so two fast sends cannot both read+ * the same stale holder. Only a `running` foreground run is retired; these+ * keep the existing behavior:+ * - a parked run (`waiting_for_human` etc.) β the send may be its answer;+ * - a background producer's run (task, cron, bot, β¦), see+ * `BACKGROUND_OPERATION_TRIGGERS` in `agentRuntime/foregroundOperation`;+ * - a device-hosted Claude Code / Codex run: cancelling it waits up to 10s+ * for the device, far past the reservation's ~3s retry budget, so a+ * concurrent send would fail. Those settle through `replacesOperationId`+ * before reserving.+ *+ * @returns the retired run and whether it had already been asked to stop, so+ * the caller can record the overlap on the new run.+ */+ private async supersedeRunningForegroundOperation(+ topicId: string,+ alreadyHandledOperationIds: (string | undefined)[],+ ): Promise<{ holderId: string; kind: SupersedeKind } | undefined> {+ const topic = await this.topicModel.findById(topicId);+ const marker = topic?.metadata?.runningOperation;+ const holderId = marker?.operationId;+ if (!holderId || marker.heteroType || alreadyHandledOperationIds.includes(holderId)) return;++ const holder = await this.agentOperationModel.findById(holderId);+ if (holder?.status !== 'running') return;+ if (!isForegroundOperationTrigger(holder.trigger)) return;++ // Read before interrupting: afterwards the sentinel is always set. The+ // read is diagnostic only, so a failure must not fail the send.+ let kind: SupersedeKind;+ try {+ kind = (await this.agentRuntimeService.isOperationInterrupted(holderId))+ ? 'already_stopping'+ : 'client_missed';+ } catch (error) {+ console.error('[execAgent] failed to read interrupt state of %s:', holderId, error);+ kind = 'unknown';+ }++ log(+ 'execAgent: superseding running foreground operation %s on topic %s (%s)',+ holderId,+ topicId,+ kind,+ );+ const interrupted = await this.interruptTask({ operationId: holderId, topicId });+ // Unconfirmed only when the run has no runtime state left but its row has+ // not settled yet: nothing executes its next step, so the send proceeds+ // rather than failing on a run that cannot spend any more.+ if (!interrupted.success) {+ console.warn('[execAgent] supersede of %s was not confirmed', holderId, { topicId });+ }+ return { holderId, kind };+ }++ /**+ * Persist the supersede on the new run's `metadata.supersede`, with the+ * client's view of its runs at send time. A `client_missed` supersede means+ * the client let a live run keep going β the case to investigate β so it is+ * also warned. Diagnostic only: a failure here never fails the send.+ */+ private async recordSupersede(+ topicId: string,+ operationId: string,+ superseded: { holderId: string; kind: SupersedeKind },+ params: InternalExecAgentParams,+ ): Promise<void> {+ const record: SupersedeRecord = {+ client: params.clientRunSnapshot,+ kind: superseded.kind,+ supersededAt: new Date().toISOString(),+ supersededOperationId: superseded.holderId,+ };++ if (superseded.kind === 'client_missed') {+ console.warn('[execAgent] client missed a running foreground operation', {+ client: params.clientRunSnapshot,+ operationId,+ supersededOperationId: superseded.holderId,+ topicId,+ });+ }++ try {+ await this.agentOperationModel.mergeMetadata(operationId, { supersede: record });+ } catch (error) {+ console.error('[execAgent] failed to record supersede on %s:', operationId, error);+ }+ }+/*** A human decision is claimed before the rest of operation preparation reads* message history. Keep its rollback guard outside the large preparationdiff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.tsindex d4b0842c9a2..3fd6b7d8b70 100644--- a/apps/server/src/services/aiAgent/types.ts+++ b/apps/server/src/services/aiAgent/types.ts@@ -13,6 +13,7 @@ import type {import type { EvalContext } from '@/server/modules/Mecha/ContextEngineering/types';import type { AgentConfigWithId } from '@/server/services/agent';+import type { ClientRunSnapshot } from '@/server/services/agentRuntime/foregroundOperation';import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';@@ -102,6 +103,11 @@ export interface InternalExecAgentParams extends ExecAgentParams {* set by the callSubAgent thread-run path, never client-passable.*/chatConfigOverride?: Partial<LobeAgentChatConfig> | null;+ /**+ * The composer's view of this conversation's runs at send time. Diagnostic+ * only: persisted when this start supersedes a live run, never used to decide.+ */+ clientRunSnapshot?: ClientRunSnapshot;/*** Thread `execAgent` materialised from `appContext.newThread` for THIS turn.* Internal-only: set by the wrapper after it creates the row, neverdiff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex bae29a119bd..85b9d6e370a 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -421,6 +421,33 @@ describe('AgentOperationModel', () => {});});+ describe('mergeMetadata', () => {+ it('merges keys into existing metadata and is scoped to the owner', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-merge-metadata';+ await model.recordStart({ operationId });+ await serverDB+ .update(agentOperations)+ .set({ metadata: { existing: 1 } })+ .where(eq(agentOperations.id, operationId));++ expect(await model.mergeMetadata(operationId, { supersede: { kind: 'client_missed' } })).toBe(+ true,+ );+ expect((await model.findById(operationId))!.metadata).toEqual({+ existing: 1,+ supersede: { kind: 'client_missed' },+ });++ expect(+ await new AgentOperationModel(serverDB, otherUserId).mergeMetadata(operationId, {+ foreign: true,+ }),+ ).toBe(false);+ expect((await model.findById(operationId))!.metadata).not.toHaveProperty('foreign');+ });+ });+describe('operation lease', () => {it('answers whether a run is still live on a given topic', async () => {// The ingest path falls back to this when a topic loses itsdiff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex a9a31660827..3e03ab4e584 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -421,6 +421,22 @@ export class AgentOperationModel {return Boolean(row);}+ /**+ * Shallow-merge top-level keys into the run's durable `metadata`, leaving+ * every other key intact. Not gated on status: diagnostic records may land on+ * a run that has already settled.+ */+ async mergeMetadata(operationId: string, patch: Record<string, unknown>): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`,+ })+ .where(and(eq(agentOperations.id, operationId), this.ownership()))+ .returning({ id: agentOperations.id });+ return Boolean(row);+ }+/** Refresh the durable liveness lease while an operation owns an execution step. */async touchRunning(operationId: string): Promise<boolean> {const [row] = await this.dbdiff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 15e8dfe11dc..784217a6a2c 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -96,6 +96,16 @@ export interface GetAgentInterventionReviewBySourceParams {targets: Array<{ toolCallId: string; toolMessageId: string }>;}+/** Must not exceed the server's `ExecAgentSchema.clientOperations` bound. */+export const MAX_CLIENT_OPERATION_SNAPSHOT = 10;++export interface ClientOperationSnapshot {+ isAborting?: boolean;+ operationId: string;+ status: string;+ visibleLoadingDone?: boolean;+}+export interface ExecAgentTaskParams {agentId?: string;appContext?: ExecAgentAppContext;@@ -107,6 +117,12 @@ export interface ExecAgentTaskParams {* sends only; resume / regeneration must not replay them.*/clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };+ /**+ * Server runs the composer tracked on this conversation at send time. The+ * server records them only when this send has to stop a run the client left+ * live, to tell whether the client never saw it or its stop never landed.+ */+ clientOperations?: ClientOperationSnapshot[];deviceId?: string;existingMessageIds?: string[];/** File IDs of already-uploaded attachments to attach to the new user message */diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 50f3cd9cf7b..056a25688ba 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -622,6 +622,51 @@ describe('ConversationLifecycle actions', () => {expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeUndefined();});+ it('should send a snapshot of the tracked server runs with a gateway send', async () => {+ const context = { ...createTestContext(), topicId: TEST_IDS.TOPIC_ID };+ const contextKey = messageMapKey(context);+ const executeGatewayAgent = vi.fn().mockResolvedValue({ operationId: 'srv-new' });+ useChatStore.setState({+ executeGatewayAgent,+ isGatewayModeEnabled: () => true,+ operations: {+ 'op-finished-output': {+ childOperationIds: [],+ context,+ id: 'op-finished-output',+ metadata: { serverOperationId: 'srv-live', visibleLoadingDone: true },+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ 'op-not-started': {+ childOperationIds: [],+ context,+ id: 'op-not-started',+ metadata: { isAborting: true },+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ } as any,+ operationsByContext: { [contextKey]: ['op-finished-output', 'op-not-started'] },+ });++ await useChatStore.getState().sendMessage({ context, message: 'next turn' });++ expect(executeGatewayAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ // Only runs that reached the server are useful to diagnose.+ clientOperations: [+ {+ isAborting: undefined,+ operationId: 'srv-live',+ status: 'running',+ visibleLoadingDone: true,+ },+ ],+ }),+ );+ });+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.diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 588a77ae043..4d4349ad6d3 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -47,7 +47,7 @@ import {} from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { agentService } from '@/services/agent';-import { aiAgentService } from '@/services/aiAgent';+import { aiAgentService, MAX_CLIENT_OPERATION_SNAPSHOT } from '@/services/aiAgent';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';@@ -824,15 +824,28 @@ export class ConversationLifecycleActionImpl {return;}- const replaceableGatewayOperationId = queueCandidateKeys+ const serverRuntimeOperations = queueCandidateKeys.flatMap((key) => this.#get().operationsByContext[key] || []).map((id) => this.#get().operations[id])- .findLast(- (operation) =>- operation?.type === 'execServerAgentRuntime' &&- operation.status === 'running' &&- (operation.metadata.isAborting || operation.metadata.visibleLoadingDone),- )?.metadata.serverOperationId;+ .filter((operation) => operation?.type === 'execServerAgentRuntime');++ const replaceableGatewayOperationId = serverRuntimeOperations.findLast(+ (operation) =>+ operation.status === 'running' &&+ (operation.metadata.isAborting || operation.metadata.visibleLoadingDone),+ )?.metadata.serverOperationId;++ // What this client believes about the conversation's server runs. The+ // server keeps it only when the send has to stop a run left live.+ const clientOperations = serverRuntimeOperations+ .filter((operation) => operation.metadata.serverOperationId)+ .slice(-MAX_CLIENT_OPERATION_SNAPSHOT)+ .map((operation) => ({+ isAborting: operation.metadata.isAborting,+ operationId: operation.metadata.serverOperationId!,+ status: operation.status,+ visibleLoadingDone: operation.metadata.visibleLoadingDone,+ }));if (onlyAddUserMessage) {await this.#get().addUserMessage({@@ -1806,6 +1819,7 @@ export class ConversationLifecycleActionImpl {onMessageAccepted: notifyMessageAccepted,onTopicCreated: context.isolatedTopic ? onTopicCreated : undefined,parentOperationId: operationId,+ clientOperations,replacesOperationId: replaceableGatewayOperationId,optimisticTopic,// Forward @-mentioned tool ids so the server runtime enables them fordiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 6669626f7a4..1b45a03c3d9 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -37,6 +37,7 @@ import {import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';import {aiAgentService,+ type ClientOperationSnapshot,type ResumeApprovalParam,type ResumeToolResultParam,} from '@/services/aiAgent';@@ -807,6 +808,8 @@ export class GatewayActionImpl {precreatedResult?: ExecAgentResult;/** Server operation whose visible output ended before this fresh turn. */replacesOperationId?: string;+ /** Diagnostic snapshot of the conversation's server runs, see `ExecAgentTaskParams`. */+ clientOperations?: ClientOperationSnapshot[];/*** Caller-owned operation that should be completed once the gateway side* has finished phase-1 init (network round-trip + child@@ -863,6 +866,7 @@ export class GatewayActionImpl {}): Promise<ExecAgentResult> => {const {clientIds,+ clientOperations,context: executionContext,fileIds,message,@@ -1030,6 +1034,7 @@ export class GatewayActionImpl {viewedGoal: executionContext.viewedGoal,},...desktopDeviceHints,+ clientOperations,fileIds,replacesOperationId,mentionedAgents,