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.

✨ feat(agent-share): count shared Agent run results as an OTEL metric (#23714)

YuTengjingbe85ad8d911f
diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
index 884df86f922..ca05c31302d 100644
--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts
+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
@@ -381,6 +381,7 @@ export class AbandonOperationService {
}).dispatchHooks(operationId, finalState, 'error', {
settledAsAbandoned: claimedStatus === 'abandoned',
skipErrorMessageWrite: result.assistantMessageUpdated,
+ terminalClaimed: claimedStatus !== undefined,
});
} catch (e) {
reportSettleFailure(
@@ -706,10 +707,12 @@ export class AbandonOperationService {
},
'error',
// Persist onto the pre-claimed `abandoned` row instead of being refused
- // as a conflicting terminal owner, which would skip the hooks.
+ // as a conflicting terminal owner, which would skip the hooks. Either way
+ // this abandonment already retired the row (its claim, or the write above),
+ // so the lifecycle's write is the run's end, not a replay.
preClaimedAbandoned
- ? { settledAsAbandoned: true, skipErrorMessageWrite: true }
- : { skipErrorMessageWrite: true },
+ ? { settledAsAbandoned: true, skipErrorMessageWrite: true, terminalClaimed: true }
+ : { skipErrorMessageWrite: true, terminalClaimed: true },
);
} catch (e) {
reportSettleFailure(
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts
index 11601c135dc..2bcc149855c 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts
@@ -44,7 +44,7 @@ describe('CompletionLifecycle.dispatchHooks β€” lastAssistantContent DB recovery
});
const setupSpies = (lifecycle: CompletionLifecycle) => {
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
vi.spyOn(verifyServices, 'scheduleVerifyOnCompletion').mockResolvedValue(undefined);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts
index a76037000ee..bdc93a2b975 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts
@@ -36,7 +36,7 @@ describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
it('awaits the start-time verify-plan instantiation before running the completion gate', async () => {
const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -152,7 +152,7 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
it('persists the parked status but does NOT fire onComplete or unregister hooks', async () => {
const lifecycle = buildLifecycle();
- const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -163,6 +163,7 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
parkedState,
'waiting_for_async_tool',
undefined,
+ undefined,
);
expect(dispatchSpy).not.toHaveBeenCalled();
expect(unregisterSpy).not.toHaveBeenCalled();
@@ -170,21 +171,27 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
it('treats a waiting_for_client park the same way: persisted, no onComplete, hooks kept', async () => {
const lifecycle = buildLifecycle();
- const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
const clientPark = { ...parkedState, status: 'waiting_for_client' };
await lifecycle.dispatchHooks('op-1', clientPark, 'waiting_for_client');
- expect(persistSpy).toHaveBeenCalledWith('op-1', clientPark, 'waiting_for_client', undefined);
+ expect(persistSpy).toHaveBeenCalledWith(
+ 'op-1',
+ clientPark,
+ 'waiting_for_client',
+ undefined,
+ undefined,
+ );
expect(dispatchSpy).not.toHaveBeenCalled();
expect(unregisterSpy).not.toHaveBeenCalled();
});
it('fires onComplete and unregisters on a terminal completion', async () => {
const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -203,7 +210,7 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
});
const stubSideEffects = (lifecycle: CompletionLifecycle) => {
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts
index 3f18488307a..f0fff280fb4 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts
@@ -39,7 +39,7 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
const budget = { required: 12 };
(lifecycle as any).messageModel = { update: updateMessage };
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -81,7 +81,7 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
const findLatestAssistantByOperationId = vi.fn().mockResolvedValue({ id: 'msg-run' });
(lifecycle as any).messageModel = { findLatestAssistantByOperationId, update: updateMessage };
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -112,9 +112,7 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
it('rethrows critical webhook failures after terminal persistence', async () => {
const lifecycle = buildLifecycle();
- const persistCompletion = vi
- .spyOn(lifecycle as any, 'persistCompletion')
- .mockResolvedValue(undefined);
+ const persistCompletion = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
const dispatch = vi
.spyOn(hookDispatcher, 'dispatch')
.mockRejectedValue(
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts
index e162c6c7b3b..a889587ba3b 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts
@@ -103,7 +103,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
const order: string[] = [];
vi.spyOn(lifecycle as any, 'persistCompletion').mockImplementation(async () => {
order.push('persist-operation');
- return true;
+ return {};
});
mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
mockNotifyAgentInterventionRequired.mockImplementation(async () => {
@@ -149,7 +149,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
it('fails the parked lifecycle when one row is outside the sealed batch', async () => {
const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
(lifecycle as any).messageModel = {
findById: vi.fn().mockResolvedValue({
@@ -185,7 +185,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
it('propagates a durable Review create failure so the parked lifecycle can retry', async () => {
const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
mockNotifyAgentInterventionRequired.mockRejectedValueOnce(new Error('database unavailable'));
stubDurablePendingRows(lifecycle);
@@ -210,7 +210,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
it('continues after post-create push fanout fails inside the business slot', async () => {
const lifecycle = buildLifecycle();
const pushFanout = vi.fn().mockRejectedValue(new Error('APNs unavailable'));
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
mockNotifyAgentInterventionRequired.mockImplementation(async () => {
// Cloud owns this boundary: the generic row is already durable here, so
@@ -255,7 +255,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
mockRegister.mockClear();
mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -274,7 +274,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
mockRegister.mockClear();
mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
const parkedState = {
host: { hooks: [] },
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts
index f6a73b9a260..db81140d0e8 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts
@@ -29,7 +29,7 @@ const marker = { metadata: { interruptedMidStream: true } };
const run = async (latestRunRow: { id: string } | undefined, reason = 'interrupted') => {
const lifecycle = new CompletionLifecycle({} as any, 'user-1');
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
const update = vi.fn().mockResolvedValue({ success: true });
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.shareRunMetrics.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.shareRunMetrics.test.ts
new file mode 100644
index 00000000000..5458ac8e181
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.shareRunMetrics.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { hookDispatcher } from '../hooks';
+import { CompletionLifecycle } from '.';
+
+const { recordShareRunResult } = vi.hoisted(() => ({ recordShareRunResult: vi.fn() }));
+
+vi.mock('@/server/services/aiAgent/shareGate/runMetrics', () => ({ recordShareRunResult }));
+vi.mock('@/business/server/agent-run/runConcurrency', () => ({ releaseAgentRunSlot: vi.fn() }));
+vi.mock('@/business/server/agent-run/runFee', () => ({ settleAgentRunFee: vi.fn(async () => {}) }));
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+interface Row {
+ parentOperationId?: string | null;
+ previousStatus?: string;
+ trigger?: string | null;
+}
+
+/**
+ * The completion write the lifecycle sees: by default a share run's first move out of `running`.
+ * `null` is a write refused because another terminal owner holds the row.
+ */
+const buildLifecycle = (row: Row | null = {}) => {
+ const lifecycle = new CompletionLifecycle({} as any, 'owner');
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => (row ? null : { status: 'error' })),
+ recordCompletion: vi.fn(async () =>
+ row
+ ? {
+ id: 'op',
+ parentOperationId: null,
+ previousStatus: 'running',
+ trigger: 'agent_share',
+ ...row,
+ }
+ : undefined,
+ ),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+ (lifecycle as any).messageModel = {
+ findById: vi.fn(async () => null),
+ update: vi.fn(async () => ({ success: true })),
+ };
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ return lifecycle;
+};
+
+const shareState = (status: string, extra: Record<string, unknown> = {}) => ({
+ host: { hooks: [] },
+ messages: [{ content: 'reply', role: 'assistant' }],
+ origin: { agentId: 'agt_shared', userId: 'owner' },
+ principal: { actor: { shareVisitor: { visitorUserId: 'visitor' } } },
+ status,
+ ...extra,
+});
+
+describe('CompletionLifecycle.dispatchHooks β€” share run metrics', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ recordShareRunResult.mockReset();
+ });
+
+ it.each([
+ ['done', 'success'],
+ ['max_steps', 'success'],
+ ['interrupted', 'interrupted'],
+ ])('counts a shared run ending in %s as %s', async (reason, outcome) => {
+ await buildLifecycle().dispatchHooks('op', shareState(reason), reason);
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith({ outcome, stage: 'run' });
+ });
+
+ it('counts a failed shared run with its error type', async () => {
+ await buildLifecycle().dispatchHooks(
+ 'op',
+ shareState('error', { error: { message: 'boom', type: 'ProviderBizError' } }),
+ 'error',
+ { skipErrorMessageWrite: true },
+ );
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ errorType: 'ProviderBizError', outcome: 'error', stage: 'run' }),
+ );
+ });
+
+ // The Channel fails a reply whose run stopped on a tool call at its step cap; counting it as a
+ // success hid a failure the visitor saw.
+ it('counts a capped run that left no reply as a failure typed by its cap', async () => {
+ await buildLifecycle().dispatchHooks(
+ 'op',
+ shareState('max_steps', { messages: [{ content: '', role: 'assistant', tools: [{}] }] }),
+ 'max_steps',
+ );
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith({
+ errorType: 'max_steps',
+ outcome: 'error',
+ stage: 'run',
+ });
+ });
+
+ // A device dispatch failure or an abandonment settles through a synthetic state that carries no
+ // share visitor; the row's trigger still marks the share run.
+ it('counts a share run settled without a share visitor on its state', async () => {
+ const { principal: _, ...syntheticState } = shareState('error', {
+ error: { message: 'offline', type: 'ShareHeteroDeviceUnavailable' },
+ });
+ await buildLifecycle().dispatchHooks('op', syntheticState, 'error', {
+ skipErrorMessageWrite: true,
+ });
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ errorType: 'ShareHeteroDeviceUnavailable', outcome: 'error' }),
+ );
+ });
+
+ // A retried hook delivery or a repeated device finish writes the same terminal status again.
+ it('does not count a replay of the status the row already holds', async () => {
+ await buildLifecycle({ previousStatus: 'done' }).dispatchHooks(
+ 'op',
+ shareState('done'),
+ 'done',
+ );
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ });
+
+ // The watchdog's claim writes `error` before the lifecycle persists `error` onto it.
+ it('counts an abandonment whose claim already wrote the terminal status', async () => {
+ await buildLifecycle({ previousStatus: 'error' }).dispatchHooks(
+ 'op',
+ shareState('error', { error: { message: 'stalled', type: 'AgentRuntimeError' } }),
+ 'error',
+ { skipErrorMessageWrite: true, terminalClaimed: true },
+ );
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ errorType: 'AgentRuntimeError', outcome: 'error' }),
+ );
+ });
+
+ it('does not count the owner’s own runs', async () => {
+ const { principal: _, ...ownerState } = shareState('done');
+ await buildLifecycle({ trigger: 'chat' }).dispatchHooks('op', ownerState, 'done');
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a sub-agent', {}, { isSubAgent: true }],
+ ['a child operation', { parentOperationId: 'op-parent' }, undefined],
+ ['a group member', {}, { orchestrationRole: 'member' }],
+ ])('does not count %s of a shared run on its own', async (_, row, lineage) => {
+ await buildLifecycle(row).dispatchHooks(
+ 'op',
+ shareState('done', { origin: { agentId: 'agt_shared', lineage, userId: 'owner' } }),
+ 'done',
+ );
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ });
+
+ it.each(['waiting_for_human', 'waiting_for_async_tool'])(
+ 'does not count a shared run parked in %s',
+ async (reason) => {
+ await buildLifecycle().dispatchHooks('op', shareState(reason), reason);
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does not count a completion another owner already settled', async () => {
+ await buildLifecycle(null).dispatchHooks('op', shareState('done'), 'done');
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
index a1260a81c97..e250a03e026 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
@@ -1,3 +1,4 @@
+import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { releaseAgentRunSlot } from '@/business/server/agent-run/runConcurrency';
@@ -10,6 +11,7 @@ import { MessageModel } from '@/database/models/message';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
+import { recordShareRunResult } from '@/server/services/aiAgent/shareGate/runMetrics';
import {
instantiateVerifyPlanOnStart,
releaseUndeliveredRound,
@@ -31,7 +33,7 @@ import {
} from './intervention';
import { buildLifecycleEvent, extractErrorMessage } from './lifecycleEvent';
import { extractOutboundAttachments, extractTextFromMessageContent } from './messageContent';
-import { persistCompletion, settleRunThread } from './persistence';
+import { type CompletionTransition, persistCompletion, settleRunThread } from './persistence';
import { recallUserOnCompletion } from './recall';
import { emitSignalEvents, isAgentShareRun } from './signals';
import type {
@@ -76,6 +78,60 @@ export const isSuccessLikeCompletionReason = (reason: string): boolean =>
reason === 'cost_limit' ||
reason === 'tool_call_repeat_limit';
+/**
+ * Count a shared Agent run's terminal result, once: only the write that moved the row out of an
+ * in-flight status counts, so a replayed completion (a retried hook delivery, a repeated device
+ * finish) does not count the run again. The row's `trigger` identifies a share run on synthetic
+ * terminals (a device dispatch failure, an abandonment) whose state carries no share visitor.
+ *
+ * Only the visitor's own top-level run counts: a sub-agent or group member it spawns is part of
+ * that run, and counting it too would inflate both the total and the failure rate. A capped run
+ * (`max_steps` and the like) that stopped without a reply is a failure the visitor saw, typed
+ * by its cap.
+ */
+const recordShareRunCompletion = (
+ state: any,
+ reason: string,
+ event: {
+ attachments?: unknown[];
+ errorAttribution?: string;
+ errorType?: string;
+ lastAssistantContent?: string;
+ },
+ runOrigin: ReturnType<typeof buildLifecycleEvent>['origin'],
+ transition: CompletionTransition | undefined,
+) => {
+ if (!transition) return;
+ if (!isAgentShareRun(state) && transition.trigger !== RequestTrigger.AgentShare) return;
+ if (
+ transition.parentOperationId ||
+ runOrigin.lineage?.parentOperationId ||
+ runOrigin.lineage?.isSubAgent === true ||
+ runOrigin.lineage?.orchestrationRole === 'member'
+ )
+ return;
+ if (reason === 'done' || reason === 'interrupted') {
+ recordShareRunResult({ outcome: reason === 'done' ? 'success' : 'interrupted', stage: 'run' });
+ return;
+ }
+ if (isSuccessLikeCompletionReason(reason)) {
+ const replied = !!event.lastAssistantContent?.trim() || !!event.attachments?.length;
+ recordShareRunResult(
+ replied
+ ? { outcome: 'success', stage: 'run' }
+ : { errorType: reason, outcome: 'error', stage: 'run' },
+ );
+ return;
+ }
+ if (reason === 'error')
+ recordShareRunResult({
+ attribution: event.errorAttribution,
+ errorType: event.errorType,
+ outcome: 'error',
+ stage: 'run',
+ });
+};
+
/**
* Owns everything that happens once an operation reaches a terminal state:
* building the lifecycle event payload, emitting completion AgentSignal source
@@ -221,8 +277,16 @@ export class CompletionLifecycle {
state: any,
reason: string,
settledAsAbandoned?: boolean,
- ): Promise<boolean> {
- return persistCompletion(this.deps(), operationId, state, reason, settledAsAbandoned);
+ terminalClaimed?: boolean,
+ ) {
+ return persistCompletion(
+ this.deps(),
+ operationId,
+ state,
+ reason,
+ settledAsAbandoned,
+ terminalClaimed,
+ );
}
/**
@@ -399,6 +463,7 @@ export class CompletionLifecycle {
state,
reason,
options?.settledAsAbandoned,
+ options?.terminalClaimed,
);
if (completionAccepted === false) {
log('[%s] Skipping hooks for an operation with a conflicting terminal owner', operationId);
@@ -468,6 +533,9 @@ export class CompletionLifecycle {
}
}
+ // After content recovery: a capped run counts as a success only when it left a reply.
+ recordShareRunCompletion(state, reason, event, runOrigin, completionAccepted.transition);
+
await hookDispatcher.dispatch(operationId, 'onComplete', event, state?.host?.hooks);
// Recall the user when a run finishes with a deliverable while they may be
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
index 9114f7d69e9..b1aa6214ec1 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
@@ -137,10 +137,19 @@ export async function settleRunThread(
}
}
+/**
+ * The row this completion moved out of an in-flight status, read from the write itself. Absent
+ * for a replay of a status the row already held, and when the write did not land.
+ */
+export interface CompletionTransition {
+ parentOperationId: string | null;
+ trigger: string | null;
+}
+
/**
* Persist terminal state to `agent_operations`. Fire-and-forget: a DB
* outage must never block hook dispatch or the executor's terminal
- * cleanup path.
+ * cleanup path. `false` when a conflicting terminal owner holds the row.
*/
export async function persistCompletion(
deps: CompletionLifecycleDeps,
@@ -148,7 +157,8 @@ export async function persistCompletion(
state: any,
reason: string,
settledAsAbandoned?: boolean,
-): Promise<boolean> {
+ terminalClaimed?: boolean,
+): Promise<false | { transition?: CompletionTransition }> {
const completionReason: any = settledAsAbandoned
? 'lease_expired'
: reason === 'max_steps' ||
@@ -203,6 +213,7 @@ export async function persistCompletion(
// but NOT when a terminal owner got there first with a different one β€” see
// the fallback below.
let durableStatus: AgentOperationStatus = status;
+ let transition: CompletionTransition | undefined;
try {
const accepted = await deps.agentOperationModel.recordCompletion(operationId, {
completedAt,
@@ -237,6 +248,10 @@ export async function persistCompletion(
});
if (accepted) {
completionDurable = true;
+ // An abandonment pre-claims the row with its own compare-and-set, which runs once; this
+ // write lands on the claimed status, so it still is the run's end.
+ if (accepted.previousStatus !== status || terminalClaimed)
+ transition = { parentOperationId: accepted.parentOperationId, trigger: accepted.trigger };
} else {
const operation = await deps.agentOperationModel.findById(operationId);
// Preserve the historical best-effort behavior when no durable start
@@ -285,7 +300,7 @@ export async function persistCompletion(
}
}
- return true;
+ return { transition };
}
/**
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
index fa6b80da362..4f8e16ebd95 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
@@ -99,6 +99,12 @@ export interface CompleteOperationOptions {
* dispatch-failure path, which surfaces a device-specific `detail`).
*/
skipErrorMessageWrite?: boolean;
+ /**
+ * The caller already moved the row to its terminal status with a compare-and-set it won (an
+ * abandonment claim), so this completion is the run's end even though the row already holds
+ * that status. Without it, the write reads as a replay of a settled run.
+ */
+ terminalClaimed?: boolean;
}
/** What the extracted completion steps read off a `CompletionLifecycle` instance. */
diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
index 5d3efc11f90..2d666434388 100644
--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
@@ -56,6 +56,8 @@ const findOperationMock = vi.fn().mockResolvedValue(null);
const recordCompletionMock = vi.fn().mockResolvedValue(undefined);
const settleLiveMock = vi.fn().mockResolvedValue(true);
const claimForAbandonmentMock = vi.fn().mockResolvedValue(true);
+/** Lifecycle options of an abandonment that retired the row itself and wrote the error bubble. */
+const claimedHooks = { skipErrorMessageWrite: true, terminalClaimed: true };
const markAbandonmentFinalizedMock = vi.fn().mockResolvedValue(undefined);
const markAbandonmentHandoffPendingMock = vi.fn().mockResolvedValue(undefined);
vi.mock('@/database/models/agentOperation', () => ({
@@ -323,7 +325,7 @@ describe('AbandonOperationService', () => {
userId: 'user_x',
}),
'error',
- { skipErrorMessageWrite: true },
+ claimedHooks,
);
});
@@ -333,7 +335,7 @@ describe('AbandonOperationService', () => {
expect(completeOperationMock).toHaveBeenCalledWith(
expect.objectContaining({ serializedHooks: [taskHook] }),
'error',
- { skipErrorMessageWrite: true },
+ claimedHooks,
);
});
@@ -373,7 +375,7 @@ describe('AbandonOperationService', () => {
expect(completeOperationMock).toHaveBeenCalledWith(
expect.objectContaining({ operationId: 'op_x', serializedHooks: undefined }),
'error',
- { skipErrorMessageWrite: true },
+ claimedHooks,
);
},
);
@@ -449,7 +451,7 @@ describe('AbandonOperationService', () => {
});
expect(completeOperationMock).toHaveBeenCalledWith(expect.anything(), 'error', {
settledAsAbandoned: true,
- skipErrorMessageWrite: true,
+ ...claimedHooks,
});
});
@@ -617,7 +619,7 @@ describe('AbandonOperationService', () => {
'op_x',
expect.anything(),
'error',
- expect.objectContaining({ settledAsAbandoned: false }),
+ expect.objectContaining({ settledAsAbandoned: false, terminalClaimed: true }),
);
// Only once everything landed does the claim stop being resumable.
expect(markAbandonmentFinalizedMock).toHaveBeenCalledWith('op_x');
@@ -801,9 +803,7 @@ describe('AbandonOperationService', () => {
'op_x',
expect.objectContaining({ status: 'error' }),
);
- expect(completeOperationMock).toHaveBeenCalledWith(expect.anything(), 'error', {
- skipErrorMessageWrite: true,
- });
+ expect(completeOperationMock).toHaveBeenCalledWith(expect.anything(), 'error', claimedHooks);
});
it('leaves the turn alone when the run settles before the claim lands', async () => {
@@ -966,7 +966,7 @@ describe('AbandonOperationService', () => {
'error',
// No operation row was readable here, so nothing was claimed and the
// lifecycle decides for itself.
- { settledAsAbandoned: false, skipErrorMessageWrite: true },
+ { settledAsAbandoned: false, skipErrorMessageWrite: true, terminalClaimed: false },
);
// Coordinator state cleaned
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts
index a7e4920e215..513371a3a1a 100644
--- a/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts
@@ -29,7 +29,7 @@ describe('CompletionLifecycle β€” topic run settled', () => {
const lifecycle = new CompletionLifecycle({} as any, 'user-1', undefined, {
onTopicRunSettled,
});
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
vi.spyOn(lifecycle as any, 'notifyPendingAgentIntervention').mockResolvedValue(undefined);
vi.spyOn(lifecycle as any, 'registerFileWorks').mockResolvedValue(undefined);
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
index 1279c1376cf..6173896a9e3 100644
--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
@@ -29,7 +29,7 @@ describe('CompletionLifecycle β€” verify gate scheduling', () => {
it('hands the verify gate to its own delivery instead of this request', async () => {
const lifecycle = new CompletionLifecycle({} as any, 'user-1');
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
@@ -54,7 +54,7 @@ describe('CompletionLifecycle β€” verify gate scheduling', () => {
'does not wait for unfinished plan generation on %s',
async (reason) => {
const lifecycle = new CompletionLifecycle({} as any, 'user-1');
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
let release!: () => void;
@@ -81,7 +81,7 @@ describe('CompletionLifecycle β€” verify gate scheduling', () => {
it.each(['error', 'interrupted'])('settles an aborted repair on %s', async (reason) => {
const lifecycle = new CompletionLifecycle({} as any, 'user-1');
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
const settle = vi.spyOn(verifyServices, 'settleFailedRepair').mockResolvedValue(false);
@@ -100,7 +100,7 @@ describe('CompletionLifecycle β€” verify gate scheduling', () => {
vi.spyOn(verifyServices, 'settleFailedRepair').mockResolvedValue(false);
const release = vi.spyOn(verifyServices, 'releaseUndeliveredRound').mockResolvedValue(true);
const lifecycle = new CompletionLifecycle({} as any, 'user-1');
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
index a8cc200faa2..35b63d82e46 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
@@ -108,7 +108,7 @@ describe('AgentRuntimeService.executeStep - agent-document index snapshot', () =
}),
);
vi.spyOn(completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
- vi.spyOn(completionLifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ vi.spyOn(completionLifecycle as any, 'persistCompletion').mockResolvedValue({});
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
await service.executeStep({
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 6baf2c102f5..50a5646fd3b 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -558,7 +558,7 @@ describe('AgentRuntimeService.executeStep - durable Review lifecycle retry', ()
runtime: { step: runtimeStep },
});
vi.spyOn(completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
- vi.spyOn(completionLifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ vi.spyOn(completionLifecycle as any, 'persistCompletion').mockResolvedValue({});
const notifyPendingReview = vi
.spyOn(completionLifecycle as any, 'notifyPendingAgentIntervention')
.mockRejectedValueOnce(
diff --git a/apps/server/src/services/aiAgent/shareGate/runMetrics.test.ts b/apps/server/src/services/aiAgent/shareGate/runMetrics.test.ts
new file mode 100644
index 00000000000..c39fea20135
--- /dev/null
+++ b/apps/server/src/services/aiAgent/shareGate/runMetrics.test.ts
@@ -0,0 +1,48 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { normalizeShareRunErrorType, recordShareRunResult } from './runMetrics';
+
+const { add } = vi.hoisted(() => ({ add: vi.fn() }));
+vi.mock('@lobechat/observability-otel/modules/agent-share', () => ({
+ agentShareRunCounter: { add },
+}));
+
+describe('share run metrics', () => {
+ beforeEach(() => add.mockReset());
+
+ it('keeps known error types and folds free-text ones into a closed set', () => {
+ expect(normalizeShareRunErrorType('ShareSpendLimitExceeded')).toBe('ShareSpendLimitExceeded');
+ expect(normalizeShareRunErrorType('ProviderBizError')).toBe('ProviderBizError');
+ expect(normalizeShareRunErrorType('rate limit hit for org_123')).toBe('Other');
+ expect(normalizeShareRunErrorType(undefined)).toBe('Unknown');
+ expect(normalizeShareRunErrorType('')).toBe('Unknown');
+ });
+
+ it('labels a success with no error', () => {
+ recordShareRunResult({ errorType: 'ProviderBizError', outcome: 'success', stage: 'run' });
+
+ expect(add).toHaveBeenCalledWith(1, {
+ error_attribution: 'none',
+ error_type: 'none',
+ outcome: 'success',
+ stage: 'run',
+ });
+ });
+
+ it('labels a failure by its type and attribution', () => {
+ recordShareRunResult({
+ attribution: 'provider',
+ errorType: 'ProviderBizError',
+ outcome: 'error',
+ stage: 'run',
+ });
+
+ expect(add).toHaveBeenCalledWith(1, {
+ error_attribution: 'provider',
+ error_type: 'ProviderBizError',
+ outcome: 'error',
+ stage: 'run',
+ });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/runMetrics.ts b/apps/server/src/services/aiAgent/shareGate/runMetrics.ts
new file mode 100644
index 00000000000..c556429ec51
--- /dev/null
+++ b/apps/server/src/services/aiAgent/shareGate/runMetrics.ts
@@ -0,0 +1,59 @@
+import {
+ agentShareRunCounter,
+ type AgentShareRunOutcome,
+ type AgentShareRunStage,
+} from '@lobechat/observability-otel/modules/agent-share';
+import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';
+
+/**
+ * `ChatErrorType` also carries HTTP status codes (`401`, `500`, ...), compared as strings. The
+ * run caps type a capped run that stopped without a reply.
+ */
+const KNOWN_ERROR_TYPES = new Set<string>([
+ ...[...Object.values(ChatErrorType), ...Object.values(AgentRuntimeErrorType)].map(String),
+ 'cost_limit',
+ 'max_steps',
+ 'tool_call_repeat_limit',
+]);
+
+const KNOWN_ATTRIBUTIONS = new Set(['harness', 'provider', 'system', 'user']);
+
+/**
+ * Keep `error_type` a closed set: an error type is free text on some paths (a provider's own
+ * code, a thrown message), and one unbounded value is enough to blow up the series count.
+ */
+export const normalizeShareRunErrorType = (type: unknown): string => {
+ if (type === undefined || type === null || type === '') return 'Unknown';
+ const value = String(type);
+ return KNOWN_ERROR_TYPES.has(value) ? value : 'Other';
+};
+
+export interface ShareRunResult {
+ attribution?: string;
+ errorType?: unknown;
+ outcome: AgentShareRunOutcome;
+ stage: AgentShareRunStage;
+}
+
+/**
+ * Count one terminal shared Agent run. Never throws: telemetry must not change how a run ends.
+ */
+export const recordShareRunResult = ({
+ attribution,
+ errorType,
+ outcome,
+ stage,
+}: ShareRunResult) => {
+ try {
+ const success = outcome === 'success';
+ agentShareRunCounter.add(1, {
+ error_attribution:
+ !success && attribution && KNOWN_ATTRIBUTIONS.has(attribution) ? attribution : 'none',
+ error_type: success ? 'none' : normalizeShareRunErrorType(errorType),
+ outcome,
+ stage,
+ });
+ } catch (error) {
+ console.error('[agentShare:runMetrics] failed to record a share run result', error);
+ }
+};
diff --git a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
index 0ebbfe50b06..834cfc6bb77 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
@@ -14,6 +14,7 @@ const {
findOperation,
findShare,
getScopedOnlineDevices,
+ recordShareRunResult,
resolveChannelAttachments,
serviceOptions,
} = vi.hoisted(() => ({
@@ -41,6 +42,7 @@ const {
),
findOperation: vi.fn(),
findShare: vi.fn(),
+ recordShareRunResult: vi.fn(),
resolveChannelAttachments: vi.fn(),
serviceOptions: [] as Array<{ options: unknown; userId: string }>,
}));
@@ -75,6 +77,7 @@ vi.mock('@/server/services/aiAgent', () => ({
}
},
}));
+vi.mock('@/server/services/aiAgent/shareGate/runMetrics', () => ({ recordShareRunResult }));
vi.mock('@/server/globalConfig', () => ({ getServerDefaultAgentConfig: () => ({}) }));
vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: {} }));
vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({ getScopedOnlineDevices }));
@@ -255,6 +258,81 @@ describe('dispatching a contact’s shared Agent', () => {
});
});
+ // A refusal before the run starts never reaches the runtime's completion, so the share's
+ // failure dashboard missed every limit refusal (trigger stays `channel` on these rows).
+ it('counts a refused reply as a share admission refusal by its type', async () => {
+ checkSpend.mockResolvedValue({ allowed: false });
+ executions.retireReservation.mockResolvedValue('error');
+ await coordinator().advance('channel');
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith({
+ errorType: 'ShareSpendLimitExceeded',
+ outcome: 'refused',
+ stage: 'admission',
+ });
+ });
+
+ it('counts an untyped dispatch failure as an admission error', async () => {
+ findShare.mockResolvedValue({ ...liveShare, ownerId: 'x' });
+ executions.retireReservation.mockResolvedValue('error');
+ await coordinator().advance('channel');
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith({
+ errorType: undefined,
+ outcome: 'error',
+ stage: 'admission',
+ });
+ });
+
+ it('counts nothing at dispatch for a run that started', async () => {
+ await coordinator().advance('channel');
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ });
+
+ it('counts a reply its requester cancelled before the run as interrupted, not a failure', async () => {
+ checkSpend.mockResolvedValue({ allowed: false });
+ executions.retireReservation.mockResolvedValue('interrupted');
+ await coordinator().advance('channel');
+
+ expect(recordShareRunResult).toHaveBeenCalledExactlyOnceWith({
+ outcome: 'interrupted',
+ stage: 'admission',
+ });
+ });
+
+ // The visitor pressed Stop after the reply was reserved but before its run started.
+ it.each([
+ [{ share }, 1],
+ [{ runtime: 'native' }, 0],
+ ])('counts a reply stopped before its run started (%o)', async (config, calls) => {
+ executions.retireReservation.mockResolvedValue('interrupted');
+ const row = { config, operation: { userId: 'owner' } };
+ const query = Object.assign(Promise.resolve([row]), {
+ from: () => query,
+ innerJoin: () => query,
+ where: () => query,
+ });
+ await new ChannelCoordinator({ select: () => query } as never).stopWriters([
+ { channelId: 'channel', id: 'job', operationId: 'op' },
+ ]);
+
+ expect(recordShareRunResult).toHaveBeenCalledTimes(calls);
+ if (calls)
+ expect(recordShareRunResult).toHaveBeenCalledWith({
+ outcome: 'interrupted',
+ stage: 'admission',
+ });
+ });
+
+ it('counts nothing when another worker already settled the reservation', async () => {
+ checkSpend.mockResolvedValue({ allowed: false });
+ executions.retireReservation.mockResolvedValue(false);
+ await coordinator().advance('channel');
+
+ expect(recordShareRunResult).not.toHaveBeenCalled();
+ });
+
// A shared Claude Code / Codex Agent's run stops at the share gate when the share grants the
// visitor no device, or the owner's device is offline; the visitor must learn which.
it.each(['ShareHeterogeneousAgentUnsupported', 'ShareHeteroDeviceUnavailable'])(
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index 632a7aa5eb9..ff619633241 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -24,6 +24,7 @@ import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { AiAgentService } from '@/server/services/aiAgent';
import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';
import { resolveShareVisitorDeviceAccess } from '@/server/services/aiAgent/shareGate/deviceAccess';
+import { recordShareRunResult } from '@/server/services/aiAgent/shareGate/runMetrics';
import { detectNoReply } from '@/server/services/conversationWake/noReply';
import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
@@ -86,6 +87,27 @@ const dispatchFailure = (error: unknown): { message: string; type: string } | un
return { message: SHARE_REFUSAL_MESSAGES[error.message], type: error.message };
};
+/**
+ * Count a shared Agent's reply retired before its run started. Such a reply never reaches the
+ * runtime's completion, which counts every run that did start. A reply its requester cancelled
+ * meanwhile is `interrupted`, not a failure; nothing counts when another worker settled it.
+ */
+const countShareAdmission = (
+ retired: 'error' | 'interrupted' | false,
+ failure?: { message: string; type: string },
+) => {
+ if (!retired) return;
+ if (retired === 'interrupted') {
+ recordShareRunResult({ outcome: 'interrupted', stage: 'admission' });
+ return;
+ }
+ recordShareRunResult({
+ errorType: failure?.type,
+ outcome: failure ? 'refused' : 'error',
+ stage: 'admission',
+ });
+};
+
/** A co-addressed Agent as the run reads it: its name, and its title when that says more. */
const describePeer = (agent: ChannelCoAddressedAgent) => {
const name = agentDisplayName(agent);
@@ -446,7 +468,8 @@ export class ChannelCoordinator {
workspaceId ?? undefined,
).findById(job.operationId);
if (operation?.status === 'idle') {
- await this.executions.retireReservation(job.channelId, job.id, failure);
+ const retired = await this.executions.retireReservation(job.channelId, job.id, failure);
+ if (share) countShareAdmission(retired, failure);
} else
await this.executions.fail(
job.channelId,
@@ -480,8 +503,9 @@ export class ChannelCoordinator {
) {
// A reservation that was never started can be retired. Its old dispatcher cannot
// initialise this now-terminal operation, even if it resumes after a process stall.
- if (await this.executions.retireReservation(channelId, jobId))
- await this.reportFailure(channelId, jobId);
+ const retired = await this.executions.retireReservation(channelId, jobId);
+ if (job.executionConfig?.share) countShareAdmission(retired);
+ if (retired) await this.reportFailure(channelId, jobId);
return;
}
if (job.publicationRevoked && operation.status !== 'done') {
@@ -646,7 +670,12 @@ export class ChannelCoordinator {
.innerJoin(channelJobs, eq(channelJobs.operationId, agentOperations.id))
.where(eq(agentOperations.id, job.operationId));
if (!row?.operation.userId) continue;
- if (await this.executions.retireReservation(job.channelId, job.id)) continue;
+ const retired = await this.executions.retireReservation(job.channelId, job.id);
+ if (retired) {
+ // A reply stopped before its run started never reaches the runtime's count.
+ if (row.config?.share) countShareAdmission(retired);
+ continue;
+ }
// Cancellation must not release the writer while a dispatcher can still submit
// its network request. An operation result alone does not prove device exit.
const [current] = await this.db.select().from(channelJobs).where(eq(channelJobs.id, job.id));
diff --git a/packages/database/src/models/__tests__/agentOperation.recovery.test.ts b/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
index 911485c97b0..4231def231a 100644
--- a/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
@@ -102,7 +102,7 @@ describe('AgentOperationModel recovery lookups', () => {
provider: 'openai',
status: 'done',
}),
- ).toBe(true);
+ ).toBeDefined();
expect(await model().findById('op-provenance')).toMatchObject({
model: 'gpt-5',
provider: 'openai',
@@ -110,6 +110,65 @@ describe('AgentOperationModel recovery lookups', () => {
});
});
+ describe('recordCompletion', () => {
+ it('reads back the status before the write, so a same-status replay is not a transition', async () => {
+ await model().recordStart({
+ operationId: 'op-transition',
+ parentOperationId: 'op-parent',
+ trigger: 'agent_share',
+ });
+
+ const first = await model().recordCompletion('op-transition', {
+ completionReason: 'error',
+ status: 'error',
+ });
+ expect(first).toEqual({
+ id: 'op-transition',
+ parentOperationId: 'op-parent',
+ previousStatus: 'running',
+ trigger: 'agent_share',
+ });
+
+ const replay = await model().recordCompletion('op-transition', {
+ completionReason: 'error',
+ status: 'error',
+ });
+ expect(replay?.previousStatus).toBe('error');
+ expect((await model().findById('op-transition'))?.status).toBe('error');
+ });
+
+ // Two terminal callbacks for one run can overlap; only one of them may read the live status.
+ it('reports the move out of running to only one of two overlapping writes', async () => {
+ await model().recordStart({ operationId: 'op-overlap' });
+
+ const writes = await Promise.all(
+ [model(), model()].map((m) =>
+ m.recordCompletion('op-overlap', { completionReason: 'error', status: 'error' }),
+ ),
+ );
+
+ expect(writes.map((w) => w?.previousStatus).sort()).toEqual(['error', 'running']);
+ });
+
+ it('writes nothing over a different terminal status or another owner’s row', async () => {
+ await model().recordStart({ operationId: 'op-settled' });
+ await model().recordCompletion('op-settled', { completionReason: 'done', status: 'done' });
+
+ expect(
+ await model().recordCompletion('op-settled', {
+ completionReason: 'error',
+ status: 'error',
+ }),
+ ).toBeUndefined();
+ expect(
+ await model(otherUserId).recordCompletion('op-settled', {
+ completionReason: 'done',
+ status: 'done',
+ }),
+ ).toBeUndefined();
+ });
+ });
+
describe('sumCostByTask', () => {
it('sums the cost bound to a task, and reports zero when none is bound', async () => {
await serverDB.insert(tasks).values({
@@ -299,7 +358,7 @@ describe('AgentOperationModel recovery lookups', () => {
completionReason: 'error',
status: 'error',
}),
- ).toBe(true);
+ ).toBeDefined();
});
it('leaves a run alone once an ingest refreshed it after dispatch', async () => {
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index 8386cfd3929..c52c6c688d0 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -541,7 +541,7 @@ describe('AgentOperationModel', () => {
completionReason: 'done',
status: 'done',
}),
- ).toBe(false);
+ ).toBeUndefined();
expect(await model.findById(operationId)).toMatchObject({
completionReason: 'lease_expired',
status: 'abandoned',
@@ -566,14 +566,14 @@ describe('AgentOperationModel', () => {
completionReason: 'error',
status: 'error',
}),
- ).toBe(false);
+ ).toBeUndefined();
expect(
await model.recordCompletion(operationId, {
completionReason: 'lease_expired',
status: 'abandoned',
stepCount: 4,
}),
- ).toBe(true);
+ ).toBeDefined();
expect(await model.findById(operationId)).toMatchObject({
completionReason: 'lease_expired',
status: 'abandoned',
@@ -708,7 +708,12 @@ describe('AgentOperationModel', () => {
await park(model, 'op-claim-async', 'waiting_for_async_tool');
await park(model, 'op-claim-client', 'waiting_for_client');
- for (const id of ['op-claim-running', 'op-claim-human', 'op-claim-async', 'op-claim-client']) {
+ for (const id of [
+ 'op-claim-running',
+ 'op-claim-human',
+ 'op-claim-async',
+ 'op-claim-client',
+ ]) {
expect(await model.claimForAbandonment(id, 'inactivity_watchdog')).toBe(true);
expect(await model.findById(id)).toMatchObject({
completionReason: 'error',
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index ce0d1c0dbcf..c5e08b266d7 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -267,11 +267,12 @@ export class AgentOperationModel {
* Update the row when the operation reaches a terminal state. Scoped by
* `userId` so a leaked operationId can't be used to flip another user's
* row. No-op when the start row was never written.
+ *
+ * Returns the written row's provenance and the status it held before this write, so a caller
+ * can act once per transition: a replay of the same terminal status is accepted again and
+ * reads back that status. `undefined` when nothing was written.
*/
- async recordCompletion(
- operationId: string,
- params: RecordOperationCompletionParams,
- ): Promise<boolean> {
+ async recordCompletion(operationId: string, params: RecordOperationCompletionParams) {
const updates: Partial<NewAgentOperation> = {
completionReason: params.completionReason,
status: params.status,
@@ -298,27 +299,42 @@ export class AgentOperationModel {
if (params.interruption !== undefined) updates.interruption = params.interruption;
if (params.traceS3Key !== undefined) updates.traceS3Key = params.traceS3Key;
- const [row] = await this.db
- .update(agentOperations)
- .set(updates)
- .where(
- and(
- eq(agentOperations.id, operationId),
- or(
- inArray(agentOperations.status, [
- 'running',
- 'waiting_for_human',
- 'waiting_for_async_tool',
- 'waiting_for_client',
- ]),
- eq(agentOperations.status, params.status),
+ return this.db.transaction(async (tx) => {
+ // Lock the row before reading its status: two overlapping terminal writes would otherwise
+ // both read the status from before either committed, and both look like the first one.
+ const [previous] = await tx
+ .select({ status: agentOperations.status })
+ .from(agentOperations)
+ .where(and(eq(agentOperations.id, operationId), this.ownership()))
+ .for('update');
+ if (!previous) return undefined;
+
+ const [row] = await tx
+ .update(agentOperations)
+ .set(updates)
+ .where(
+ and(
+ eq(agentOperations.id, operationId),
+ or(
+ inArray(agentOperations.status, [
+ 'running',
+ 'waiting_for_human',
+ 'waiting_for_async_tool',
+ 'waiting_for_client',
+ ]),
+ eq(agentOperations.status, params.status),
+ ),
+ this.ownership(),
),
- this.ownership(),
- ),
- )
- .returning({ id: agentOperations.id });
-
- return Boolean(row);
+ )
+ .returning({
+ id: agentOperations.id,
+ parentOperationId: agentOperations.parentOperationId,
+ trigger: agentOperations.trigger,
+ });
+
+ return row && { ...row, previousStatus: previous.status };
+ });
}
/**
diff --git a/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts b/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts
index 2738229250d..0192817583b 100644
--- a/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts
@@ -189,7 +189,7 @@ describe('Channel dispatch reservation', () => {
it('fences a dispatcher that resumes after its reservation was retired', async () => {
const { channel, job, operationId, start } = await reserve();
- expect(await executions.retireReservation(channel.id, job.id)).toBe(true);
+ expect(await executions.retireReservation(channel.id, job.id)).toBe('error');
await expect(start()).rejects.toThrow('reservation');
expect(await jobById(db, job.id)).toMatchObject({ status: 'failed', writerHeld: false });
expect(await operationById(db, operationId)).toMatchObject({ status: 'error' });
diff --git a/packages/database/src/repositories/channel/__tests__/execution.test.ts b/packages/database/src/repositories/channel/__tests__/execution.test.ts
index 02e60b3f315..813fd11ff1b 100644
--- a/packages/database/src/repositories/channel/__tests__/execution.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/execution.test.ts
@@ -229,7 +229,7 @@ describe('ChannelExecutionRepository', () => {
expect(await execution.claim(channel.id, nextJob.id, lease)).toBeNull();
expect(await jobById(nextJob.id)).toMatchObject({ blockedCode: 'member_busy' });
- expect(await execution.retireReservation(channel.id, job.id)).toBe(true);
+ expect(await execution.retireReservation(channel.id, job.id)).toBe('error');
expect(await jobById(job.id)).toMatchObject({ status: 'failed', writerHeld: false });
expect(await execution.claim(channel.id, nextJob.id, lease)).not.toBeNull();
expect(await jobById(nextJob.id)).toMatchObject({ blockedCode: null });
@@ -284,7 +284,7 @@ describe('ChannelExecutionRepository', () => {
expect(await execution.claim(channel.id, b1.id, lease)).not.toBeNull();
expect(await execution.claim(channel.id, main.id, lease)).not.toBeNull();
- expect(await execution.retireReservation(channel.id, a1.id)).toBe(true);
+ expect(await execution.retireReservation(channel.id, a1.id)).toBe('error');
expect(await execution.claim(channel.id, a2.id, lease)).not.toBeNull();
});
@@ -326,7 +326,7 @@ describe('ChannelExecutionRepository', () => {
expect(await execution.claim(channel.id, rootJob.id, lease)).not.toBeNull();
expect(await execution.claim(channel.id, threadJob.id, lease)).toBeNull();
- expect(await execution.retireReservation(channel.id, rootJob.id)).toBe(true);
+ expect(await execution.retireReservation(channel.id, rootJob.id)).toBe('error');
expect(await execution.claim(channel.id, threadJob.id, lease)).not.toBeNull();
});
@@ -608,7 +608,7 @@ describe('ChannelExecutionRepository', () => {
code: 'CONFLICT',
});
- expect(await execution.retireReservation(channel.id, job.id)).toBe(true);
+ expect(await execution.retireReservation(channel.id, job.id)).toBe('error');
await expect(execution.accepted(channel.id, job.id)).rejects.toMatchObject({
code: 'CONFLICT',
});
@@ -634,7 +634,24 @@ describe('ChannelExecutionRepository', () => {
expect(await execution.heartbeat(job.id, lease)).toBe(true);
expect(await execution.heartbeat(job.id, { ...lease, leaseOwner: 'other' })).toBe(false);
- expect(await execution.retireReservation(channel.id, job.id)).toBe(true);
+ expect(await execution.retireReservation(channel.id, job.id)).toBe('error');
expect(await execution.heartbeat(job.id, lease)).toBe(false);
});
+
+ it('retires a reservation cancelled before it started as interrupted', async () => {
+ const { channel, job } = await mentionAgent();
+ const claim = (await execution.claim(channel.id, job.id, lease))!;
+ await db
+ .update(channelJobs)
+ .set({ publicationRevoked: true })
+ .where(eq(channelJobs.id, job.id));
+
+ expect(await execution.retireReservation(channel.id, job.id)).toBe('interrupted');
+ const [operation] = await db
+ .select({ status: agentOperations.status })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, claim.job.operationId!));
+ expect(operation.status).toBe('interrupted');
+ expect((await jobById(job.id)).status).toBe('cancelled');
+ });
});
diff --git a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
index ca3e2be377e..f1beb13a166 100644
--- a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
@@ -376,7 +376,7 @@ describe('a contact’s shared Agent in a direct conversation', () => {
message: 'This shared Agent reached its monthly usage limit',
type: 'ShareSpendLimitExceeded',
}),
- ).toBe(true);
+ ).toBe('error');
const job = (await visitor.detail(channel.id))!.jobs.find(
(item) => item.id === claim.job.id,
)!;
diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.ts
index bec463eb35c..f3287270e43 100644
--- a/packages/database/src/repositories/channel/execution.ts
+++ b/packages/database/src/repositories/channel/execution.ts
@@ -176,13 +176,15 @@ export class ChannelExecutionRepository {
/**
* Retire only an untouched reservation, racing recordStart on the operation row itself.
- * `failure` records why dispatch refused it, for a reason the requester can act on.
+ * `failure` records why dispatch refused it, for a reason the requester can act on. Returns
+ * the status the operation ended in (`interrupted` when the reply was cancelled meanwhile),
+ * or `false` when there was no untouched reservation to retire.
*/
retireReservation = async (
channelId: string,
jobId: string,
failure?: { message: string; type?: string },
- ) =>
+ ): Promise<'error' | 'interrupted' | false> =>
withChannelLock(this.db, channelId, async (tx) => {
const job = await claimed(tx, channelId, jobId, true);
if (!job.operationId || !job.writerHeld) return false;
@@ -204,7 +206,7 @@ export class ChannelExecutionRepository {
})
.where(eq(channelJobs.id, job.id));
await audit(tx, channelId, 'reservation_retired', job.id, { status });
- return true;
+ return status;
});
/** Writes back a routing decision for `attempt`; null when the result is stale. */
diff --git a/packages/observability-otel/package.json b/packages/observability-otel/package.json
index 29281577951..b87f88e13cc 100644
--- a/packages/observability-otel/package.json
+++ b/packages/observability-otel/package.json
@@ -8,6 +8,7 @@
"./trpc": "./src/trpc/index.ts",
"./gen-ai": "./src/gen-ai/index.ts",
"./modules/agent-runtime": "./src/modules/agent-runtime/index.ts",
+ "./modules/agent-share": "./src/modules/agent-share/index.ts",
"./modules/agent-signal": "./src/modules/agent-signal/index.ts",
"./modules/bot-wake": "./src/modules/bot-wake/index.ts",
"./modules/legacy-plugin-write": "./src/modules/legacy-plugin-write/index.ts",
diff --git a/packages/observability-otel/src/modules/agent-share/index.ts b/packages/observability-otel/src/modules/agent-share/index.ts
new file mode 100644
index 00000000000..2a767ec414c
--- /dev/null
+++ b/packages/observability-otel/src/modules/agent-share/index.ts
@@ -0,0 +1,29 @@
+import { metrics } from '@opentelemetry/api';
+
+const meter = metrics.getMeter('server-services-agent-share');
+
+/**
+ * Where a shared Agent run ended:
+ * - `admission` β€” refused before the run started (share limits, a revoked share, a dispatch
+ * failure); the Agent never ran
+ * - `run` β€” the run started and reached a terminal state in the runtime
+ */
+export type AgentShareRunStage = 'admission' | 'run';
+
+/** `refused` is an admission refusal the visitor can act on (a typed share limit). */
+export type AgentShareRunOutcome = 'error' | 'interrupted' | 'refused' | 'success';
+
+/**
+ * Terminal results of shared Agent runs, whichever surface the visitor used.
+ *
+ * Labels (all small closed sets; never a user, share, Agent or operation id):
+ * - `stage`: {@link AgentShareRunStage}
+ * - `outcome`: {@link AgentShareRunOutcome}
+ * - `error_type`: the normalized error type, `none` on success, `Other` for a type outside the
+ * known error taxonomy, `Unknown` when the failure carried no type
+ * - `error_attribution`: `user` | `provider` | `harness` | `system` | `none`
+ */
+export const agentShareRunCounter = meter.createCounter('agent_share_runs_total', {
+ description: 'Terminal results of shared Agent runs, by stage, outcome and error type.',
+ unit: '{run}',
+});