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-runtime): record device vs transport time for dispatched tools (#18899)

Arvin Xuf2784b13052b
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 77046901257..1ec34e32b50 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -220,8 +220,19 @@ describe('connect command', () => {
expect(executeToolCall).toHaveBeenCalledWith('readLocalFile', '{"path":"/test"}', undefined);
expect(lastSentToolResponse).toEqual({
requestId: 'req-1',
- result: { content: 'tool result', error: undefined, success: true },
+ result: {
+ content: 'tool result',
+ error: undefined,
+ // Timed on this machine's clock, so the value is whatever the mock took
+ // β€” what matters is that the device reports one at all: the server can
+ // only observe the round trip, and cannot otherwise tell a slow tool
+ // from slow transport.
+ executionTimeMs: expect.any(Number),
+ state: undefined,
+ success: true,
+ },
});
+ expect(lastSentToolResponse.result.executionTimeMs).toBeGreaterThanOrEqual(0);
});
it('should handle system info requests', async () => {
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 704d6f40885..8ef9698da00 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -859,11 +859,16 @@ function bindGatewayClientHandlers(
log.toolCall(toolCall.apiName, requestId, toolCall.arguments, operationId);
}
+ // Timed on the DEVICE's clock. The server can only see the whole dispatch
+ // round trip, so reporting this back is what separates a slow tool from
+ // slow transport.
+ const startedAt = performance.now();
const result = await executeToolCall(toolCall.apiName, toolCall.arguments, timeout);
+ const executionTimeMs = Math.round(performance.now() - startedAt);
if (isDaemonChild) {
appendLog(
- `[RESULT] ${result.success ? 'OK' : 'FAIL'}${operationId ? ` op=${operationId}` : ''} (${requestId})`,
+ `[RESULT] ${result.success ? 'OK' : 'FAIL'} ${executionTimeMs}ms${operationId ? ` op=${operationId}` : ''} (${requestId})`,
);
} else {
log.toolResult(requestId, result.success, result.content, operationId);
@@ -874,6 +879,7 @@ function bindGatewayClientHandlers(
result: {
content: result.content,
error: result.error,
+ executionTimeMs,
state: result.state,
success: result.success,
},
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 76f183e6d68..76a177ff611 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -632,6 +632,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-err',
result: {
+ executionTimeMs: expect.any(Number),
content: 'File not found',
error: 'File not found',
success: false,
@@ -650,6 +651,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-unknown',
result: {
+ executionTimeMs: expect.any(Number),
content: errorMsg,
error: errorMsg,
success: false,
@@ -718,10 +720,34 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'mcp-ok',
- result: { content: 'stock: 100', state: { rows: 1 }, success: true },
+ result: {
+ content: 'stock: 100',
+ executionTimeMs: expect.any(Number),
+ state: { rows: 1 },
+ success: true,
+ },
});
});
+ it('reports how long the tool took on this device', async () => {
+ vi.mocked(mockLocalFileCtr.readFile).mockResolvedValueOnce({
+ content: 'ok',
+ success: true,
+ } as never);
+ const client = await connectAndOpen();
+
+ client.simulateToolCallRequest('readFile', { path: '/x' }, 'req-timed');
+ await vi.advanceTimersByTimeAsync(0);
+
+ // The server can only observe the whole dispatch round trip, so this
+ // number is the only way to tell a slow tool from slow transport. Desktop
+ // is where most device tool calls happen β€” omitting it here would bias
+ // the measurement toward calls made through `lh connect`.
+ const { result } = client.sendToolCallResponse.mock.calls.at(-1)![0];
+ expect(typeof result.executionTimeMs).toBe('number');
+ expect(result.executionTimeMs).toBeGreaterThanOrEqual(0);
+ });
+
it('should send error response when the MCP call throws', async () => {
vi.mocked(mockMcpCtr.runStdioMcpTool).mockRejectedValueOnce(new Error('spawn ENOENT'));
const client = await connectAndOpen();
@@ -736,7 +762,12 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'mcp-err',
- result: { content: 'spawn ENOENT', error: 'spawn ENOENT', success: false },
+ result: {
+ content: 'spawn ENOENT',
+ error: 'spawn ENOENT',
+ executionTimeMs: expect.any(Number),
+ success: false,
+ },
});
});
});
@@ -1621,6 +1652,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-cap',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({ available: true, version: '1.2.3' }),
state: { available: true, version: '1.2.3' },
success: true,
@@ -1646,6 +1678,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-cap-nover',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({ available: true }),
state: { available: true },
success: true,
@@ -1669,6 +1702,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-missing',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({
available: false,
reason: 'openclaw is not installed on this device',
@@ -1699,6 +1733,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-unknown-plat',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({ available: false, reason: 'Unknown platform: unknownBot' }),
state: { available: false, reason: 'Unknown platform: unknownBot' },
success: true,
@@ -1719,6 +1754,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-profile',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({}),
state: {},
success: true,
@@ -1751,6 +1787,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-openclaw',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({ avatar: '🦞', title: 'Clawd' }),
state: { avatar: '🦞', description: undefined, title: 'Clawd' },
success: true,
@@ -1779,6 +1816,7 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-hermes',
result: {
+ executionTimeMs: expect.any(Number),
content: JSON.stringify({ avatar: '⚑', title: 'research' }),
state: { avatar: '⚑', description: undefined, title: 'research' },
success: true,
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index dcc2d201d94..0b24f938e4f 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -762,6 +762,13 @@ export default class GatewayConnectionService extends ServiceModule {
`Received tool call: apiName=${apiName}, requestId=${requestId}, type=${type ?? 'tool'}`,
);
+ // Timed on THIS machine's clock, around both routes. The server can only
+ // observe the whole dispatch round trip, so without this number a slow tool
+ // and slow transport are indistinguishable β€” and desktop is where most
+ // device tool calls actually happen, so leaving it out here would bias the
+ // measurement toward the `lh connect` subset.
+ const startedAt = performance.now();
+
try {
let result: ToolCallResult;
@@ -793,6 +800,7 @@ export default class GatewayConnectionService extends ServiceModule {
// when present so payloads stay minimal.
const wireResult: ToolCallResponseMessage['result'] = {
content: result.content,
+ executionTimeMs: Math.round(performance.now() - startedAt),
success: result.success,
};
const wireError = serializeWireError(result.error);
@@ -809,6 +817,9 @@ export default class GatewayConnectionService extends ServiceModule {
result: {
content: errorMsg,
error: errorMsg,
+ // A failure is timed too: a tool that took 30s to fail is as
+ // interesting as one that took 30s to succeed.
+ executionTimeMs: Math.round(performance.now() - startedAt),
success: false,
},
});
diff --git a/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts b/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts
index 45ee59fd1c6..275e40d9840 100644
--- a/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts
+++ b/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts
@@ -10,6 +10,11 @@ export interface ToolResultPayload {
message: string;
type?: string;
};
+ /**
+ * Wall time the tool took on the device, by the device's own clock. Absent
+ * when the device or the gateway is too old to report it.
+ */
+ executionTimeMs?: number;
state?: Record<string, any>;
success: boolean;
toolCallId: string;
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
index a1496096c05..ee9774a308b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
@@ -209,6 +209,51 @@ describe('dispatchClientTool', () => {
expect(result.workRegistration).toEqual(workRegistration);
});
+ it('reports the device clock alongside the server-observed span', async () => {
+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);
+ const streamManager = makeStreamManager(sendToolExecute);
+
+ mockBlpop.mockResolvedValue([
+ 'tool_result:call-1',
+ JSON.stringify({
+ content: 'done',
+ executionTimeMs: 42,
+ success: true,
+ toolCallId: 'call-1',
+ }),
+ ]);
+
+ const result = await dispatchClientTool(makePayload(), {
+ operationId: 'op-1',
+ streamManager,
+ });
+
+ // `executionTime` is the round trip this process measured; the device's own
+ // number rides beside it. Without both, a slow tool and slow transport are
+ // indistinguishable β€” which is the whole reason the device reports one.
+ expect(result.deviceExecutionTime).toBe(42);
+ expect(result.executionTime).toBeGreaterThanOrEqual(0);
+ });
+
+ it('leaves the device clock undefined when the payload omits it', async () => {
+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);
+ const streamManager = makeStreamManager(sendToolExecute);
+
+ // An older device, or a gateway that drops the field.
+ mockBlpop.mockResolvedValue([
+ 'tool_result:call-1',
+ JSON.stringify({ content: 'done', success: true, toolCallId: 'call-1' }),
+ ]);
+
+ const result = await dispatchClientTool(makePayload(), {
+ operationId: 'op-1',
+ streamManager,
+ });
+
+ expect(result.deviceExecutionTime).toBeUndefined();
+ expect(result.executionTime).toBeGreaterThanOrEqual(0);
+ });
+
it('leaves workRegistration undefined when the BLPOP payload omits it', async () => {
const sendToolExecute = vi.fn().mockResolvedValue(undefined);
const streamManager = makeStreamManager(sendToolExecute);
diff --git a/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts b/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
index 1a21137f90f..a72e5a88733 100644
--- a/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
+++ b/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
@@ -155,6 +155,9 @@ function projectToExecutionResult(
): ToolExecutionResultResponse {
return {
content: payload.content ?? '',
+ // Absent when the device or the gateway is too old to report it; the
+ // server-observed `executionTime` is always present.
+ deviceExecutionTime: payload.executionTimeMs,
error: payload.error,
executionTime,
state: payload.state,
diff --git a/apps/server/src/router-hono/agent/handlers/toolResult.ts b/apps/server/src/router-hono/agent/handlers/toolResult.ts
index 578c11f2bfa..f47ea828e62 100644
--- a/apps/server/src/router-hono/agent/handlers/toolResult.ts
+++ b/apps/server/src/router-hono/agent/handlers/toolResult.ts
@@ -16,6 +16,13 @@ const ToolResultBodySchema = z.object({
type: z.string().optional(),
})
.optional(),
+ /**
+ * Wall time the tool took on the DEVICE, by its own clock. `z.object` strips
+ * unknown keys, so this has to be declared to survive at all β€” and it is
+ * optional because it only arrives when both the device and the gateway are
+ * new enough to send it.
+ */
+ executionTimeMs: z.number().nonnegative().optional(),
state: z.record(z.string(), z.any()).optional(),
success: z.boolean(),
toolCallId: z.string().min(1),
diff --git a/apps/server/src/services/agentRuntime/stepPresentation.ts b/apps/server/src/services/agentRuntime/stepPresentation.ts
index b73b44c7597..76fcbcdcb35 100644
--- a/apps/server/src/services/agentRuntime/stepPresentation.ts
+++ b/apps/server/src/services/agentRuntime/stepPresentation.ts
@@ -43,7 +43,14 @@ export function buildStepPresentation(
let reasoning: string | undefined;
let toolsCalling: Array<{ apiName: string; arguments?: string; identifier: string }> | undefined;
let toolsResult:
- | Array<{ apiName: string; identifier: string; isSuccess?: boolean; output?: string }>
+ | Array<{
+ apiName: string;
+ deviceExecutionTimeMs?: number;
+ executionTimeMs?: number;
+ identifier: string;
+ isSuccess?: boolean;
+ output?: string;
+ }>
| undefined;
let summary: string;
@@ -56,6 +63,8 @@ export function buildStepPresentation(
toolsResult = [
{
apiName,
+ deviceExecutionTimeMs: toolPayload?.deviceExecutionTime,
+ executionTimeMs: toolPayload?.executionTime,
identifier,
isSuccess: toolPayload?.isSuccess !== false,
output: serializeToolOutput(output),
@@ -68,6 +77,8 @@ export function buildStepPresentation(
const rawToolResults = nextPayload?.toolResults || [];
toolsResult = rawToolResults.map((r: any) => ({
apiName: r.toolCall?.apiName || 'unknown',
+ deviceExecutionTimeMs: r.data?.deviceExecutionTime,
+ executionTimeMs: r.executionTime,
identifier: r.toolCall?.identifier || 'unknown',
isSuccess: r?.isSuccess !== false,
output: serializeToolOutput(r.data),
@@ -77,8 +88,7 @@ export function buildStepPresentation(
} else {
// Check for done event first (finish step with no next context).
const doneEvent = stepResult.events?.find((e) => e.type === 'done') as
- | { reason?: string; reasonDetail?: string; type: 'done' }
- | undefined;
+ { reason?: string; reasonDetail?: string; type: 'done' } | undefined;
if (doneEvent) {
summary = `[done] reason=${doneEvent.reason ?? 'unknown'}`;
@@ -90,8 +100,7 @@ export function buildStepPresentation(
// Use parsed ChatToolPayload from payload (has identifier + apiName).
const payloadToolsCalling = (stepResult.nextContext?.payload as any)?.toolsCalling as
- | Array<{ apiName: string; arguments: string; identifier: string }>
- | undefined;
+ Array<{ apiName: string; arguments: string; identifier: string }> | undefined;
const hasToolCalls = Array.isArray(payloadToolsCalling) && payloadToolsCalling.length > 0;
if (hasToolCalls) {
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 8a907b9a49f..822bb5dd55a 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -340,6 +340,13 @@ export interface ToolExecutionResult {
}
export interface ToolExecutionResultResponse extends ToolExecutionResult {
+ /**
+ * Wall time the tool took on the DEVICE, by the device's own clock, when the
+ * call was dispatched to one. Paired with the server-observed
+ * `executionTime`, the difference is pure dispatch overhead β€” the number that
+ * decides whether moving the agent loop onto the device is worth it.
+ */
+ deviceExecutionTime?: number;
executionTime: number;
}
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index 282d54c0712..102169feb18 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -722,6 +722,9 @@ export const callTool =
nextContext: {
payload: {
data: executionResult,
+ // Server-observed span vs the device's own β€” their difference is
+ // the dispatch overhead, which only the trace can show after the fact.
+ deviceExecutionTime: execution.result.deviceExecutionTime,
executionTime,
isSuccess,
parentMessageId: toolMessageId,
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index af62f0006f9..b00446b83ce 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -13,6 +13,13 @@ export interface ToolRunResult {
content: string;
/** Server tool paused (client/device dispatch) β€” result arrives later. */
deferred?: boolean;
+ /**
+ * Wall time the tool took on the DEVICE, by the device's own clock, when the
+ * call was dispatched to one. Paired with the server-observed
+ * `executionTime`, the difference is pure dispatch overhead β€” the number that
+ * decides whether moving the agent loop onto the device is worth it.
+ */
+ deviceExecutionTime?: number;
error?: unknown;
executionTime?: number;
state?: Record<string, any>;
diff --git a/packages/agent-tracing/src/types.ts b/packages/agent-tracing/src/types.ts
index 11d270e31c4..ad8e61f7793 100644
--- a/packages/agent-tracing/src/types.ts
+++ b/packages/agent-tracing/src/types.ts
@@ -108,6 +108,16 @@ export interface StepSnapshot {
toolsetBaseline?: any;
toolsResult?: Array<{
apiName: string;
+ /**
+ * Wall time the tool took on the DEVICE, by its own clock β€” present only
+ * for calls dispatched to one, and only when the device and gateway are new
+ * enough to report it. `executionTimeMs - deviceExecutionTimeMs` is the
+ * dispatch overhead: how much of a device tool call is transport rather
+ * than work.
+ */
+ deviceExecutionTimeMs?: number;
+ /** Wall time the server observed for the call, dispatch included. */
+ executionTimeMs?: number;
identifier: string;
isSuccess?: boolean;
output?: string;
diff --git a/packages/agent-tracing/src/viewer/index.ts b/packages/agent-tracing/src/viewer/index.ts
index 129e8415cf0..ed390b002de 100644
--- a/packages/agent-tracing/src/viewer/index.ts
+++ b/packages/agent-tracing/src/viewer/index.ts
@@ -358,6 +358,26 @@ function renderMessageList(lines: string[], messages: any[], maxContentLen: numb
}
}
+/**
+ * `total (device Xms + transport Yms)` for a device-dispatched call.
+ *
+ * The split is the whole point of recording both clocks: it says how much of a
+ * device tool call was actual work and how much was getting there and back.
+ * Falls back to the total alone when the device reported nothing.
+ */
+function renderToolTiming(tool: NonNullable<StepSnapshot['toolsResult']>[number]): string {
+ const { deviceExecutionTimeMs, executionTimeMs } = tool;
+ if (executionTimeMs === undefined) return '';
+ if (deviceExecutionTimeMs === undefined) return dim(` ${formatMs(executionTimeMs)}`);
+
+ const transport = Math.max(0, executionTimeMs - deviceExecutionTimeMs);
+
+ return dim(
+ ` ${formatMs(executionTimeMs)}` +
+ ` (device ${formatMs(deviceExecutionTimeMs)} + transport ${formatMs(transport)})`,
+ );
+}
+
function renderToolStep(lines: string[], step: StepSnapshot, prefix: string): void {
if (step.toolsResult) {
for (let i = 0; i < step.toolsResult.length; i++) {
@@ -366,7 +386,7 @@ function renderToolStep(lines: string[], step: StepSnapshot, prefix: string): vo
const connector = isLast ? '└─' : 'β”œβ”€';
const status = tool.isSuccess === false ? red('βœ—') : green('βœ“');
const name = tool.identifier || tool.apiName;
- lines.push(`${prefix}${dim(connector)} Tool ${name} ${status}`);
+ lines.push(`${prefix}${dim(connector)} Tool ${name} ${status}${renderToolTiming(tool)}`);
}
}
}
diff --git a/packages/agent-tracing/src/viewer/toolTiming.test.ts b/packages/agent-tracing/src/viewer/toolTiming.test.ts
new file mode 100644
index 00000000000..2c5f3002baf
--- /dev/null
+++ b/packages/agent-tracing/src/viewer/toolTiming.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ExecutionSnapshot, StepSnapshot } from '../types';
+import { renderSnapshot } from './index';
+
+const toolStep = (toolsResult: NonNullable<StepSnapshot['toolsResult']>): StepSnapshot => ({
+ completedAt: 3_000,
+ executionTimeMs: 2_000,
+ startedAt: 1_000,
+ stepIndex: 0,
+ stepType: 'call_tool',
+ toolsResult,
+ totalCost: 0,
+ totalTokens: 0,
+});
+
+const snapshotWith = (step: StepSnapshot): ExecutionSnapshot => ({
+ operationId: 'op_1',
+ startedAt: 1_000,
+ steps: [step],
+ totalCost: 0,
+ totalSteps: 1,
+ totalTokens: 0,
+ traceId: 'op_1',
+});
+
+// The renderer colourises; assertions read the text with escapes stripped.
+const plain = (s: string) => s.replaceAll(/\x1B\[\d+m/g, '');
+
+describe('tool timing in the trace viewer', () => {
+ it('splits a device call into work and transport', () => {
+ const out = plain(
+ renderSnapshot(
+ snapshotWith(
+ toolStep([
+ {
+ apiName: 'readFile',
+ deviceExecutionTimeMs: 40,
+ executionTimeMs: 1_950,
+ identifier: 'local-system',
+ isSuccess: true,
+ },
+ ]),
+ ),
+ ),
+ );
+
+ // 1950 observed βˆ’ 40 on the device = 1.9s that was pure dispatch.
+ expect(out).toContain('1.9s (device 40ms + transport 1.9s)');
+ });
+
+ it('shows the total alone when the device reported nothing', () => {
+ const out = plain(
+ renderSnapshot(
+ snapshotWith(
+ toolStep([
+ { apiName: 'search', executionTimeMs: 320, identifier: 'web', isSuccess: true },
+ ]),
+ ),
+ ),
+ );
+
+ expect(out).toContain('320ms');
+ expect(out).not.toContain('transport');
+ });
+
+ it('never reports negative transport when the clocks disagree', () => {
+ // Two machines, two clocks: the device can report marginally more than the
+ // server observed. Clamp rather than print a negative.
+ const out = plain(
+ renderSnapshot(
+ snapshotWith(
+ toolStep([
+ {
+ apiName: 'noop',
+ deviceExecutionTimeMs: 105,
+ executionTimeMs: 100,
+ identifier: 'local-system',
+ isSuccess: true,
+ },
+ ]),
+ ),
+ ),
+ );
+
+ expect(out).toContain('transport 0ms');
+ });
+
+ it('omits timing entirely for a step that recorded none', () => {
+ const out = plain(
+ renderSnapshot(
+ snapshotWith(toolStep([{ apiName: 'x', identifier: 'y', isSuccess: true }])),
+ ),
+ );
+
+ expect(out).toContain('Tool y ');
+ expect(out).not.toContain('device');
+ });
+});
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 8e96813d0e9..a087b8d11a5 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -62,6 +62,17 @@ export interface ToolCallResponseMessage {
result: {
content: string;
error?: string;
+ /**
+ * Wall time the tool actually took ON THE DEVICE, by the device's own
+ * clock. The server can only observe the whole dispatch round trip
+ * (publish β†’ gateway β†’ device β†’ callback β†’ redis), so without this number
+ * there is no way to tell a slow tool from slow transport β€” which is the
+ * entire question when deciding whether to move the agent loop local.
+ *
+ * Optional: an older device, or a gateway that does not forward the field,
+ * simply leaves it absent.
+ */
+ executionTimeMs?: number;
state?: unknown;
success: boolean;
};