Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
⏲️ feat: Report a Background Task's Start, Settlement and Elapsed Time (#16193)
lia-by-librechat[bot]fb0a03f38281
diff --git a/packages/api/src/agents/background.spec.ts b/packages/api/src/agents/background.spec.tsindex 65873abc2f..5418fdeb3f 100644--- a/packages/api/src/agents/background.spec.ts+++ b/packages/api/src/agents/background.spec.ts@@ -2310,6 +2310,76 @@ describe('runCheckBackgroundTask (singleton)', () => {);});+ it('reports ISO dispatch and settlement stamps with the elapsed span', async () => {+ const nowSpy = jest.spyOn(Date, 'now');+ try {+ const created = backgroundTaskRegistry.create({+ userId: 'timing_user',+ conversationId: 'timing_convo',+ toolCallId: 'call_timing',+ toolName: 'search_mcp_docs',+ });+ if ('atCapacity' in created) {+ throw new Error('unexpected capacity');+ }+ /** The dispatch stamp is monotonic per process, so it is whatever the registry+ * assigned rather than the clock at this instant; drive the clock from it. */+ const dispatchedAt = created.task.createdAt;++ nowSpy.mockReturnValue(dispatchedAt + 90_000);+ const running = JSON.parse(+ await runCheckBackgroundTask({+ userId: 'timing_user',+ conversationId: 'timing_convo',+ args: { background_task_id: created.task.id },+ }),+ );+ expect(running).toMatchObject({+ status: 'running',+ started_at: new Date(dispatchedAt).toISOString(),+ elapsed_ms: 90_000,+ });+ /** A running task has not settled, so it must not claim a terminal stamp. */+ expect(running.settled_at).toBeUndefined();++ nowSpy.mockReturnValue(dispatchedAt + 120_000);+ backgroundTaskRegistry.complete('timing_user', 'timing_convo', created.task.id, {+ content: 'RESULT',+ });++ nowSpy.mockReturnValue(dispatchedAt + 600_000);+ const settled = JSON.parse(+ await runCheckBackgroundTask({+ userId: 'timing_user',+ conversationId: 'timing_convo',+ args: { background_task_id: created.task.id },+ }),+ );+ /** The span freezes at settlement instead of growing with every later poll. */+ expect(settled).toMatchObject({+ status: 'completed',+ started_at: new Date(dispatchedAt).toISOString(),+ settled_at: new Date(dispatchedAt + 120_000).toISOString(),+ elapsed_ms: 120_000,+ });++ const listed = JSON.parse(+ await runCheckBackgroundTask({+ userId: 'timing_user',+ conversationId: 'timing_convo',+ args: {},+ }),+ );+ expect(listed.tasks[0]).toMatchObject({+ started_at: new Date(dispatchedAt).toISOString(),+ settled_at: new Date(dispatchedAt + 120_000).toISOString(),+ elapsed_ms: 120_000,+ });+ } finally {+ nowSpy.mockRestore();+ }+ });+it('lets a later-generation poll collect a receipt without inheriting an abandoned local claim', async () => {const created = backgroundTaskRegistry.create({userId: 'claim_user',@@ -2566,6 +2636,7 @@ describe('runCheckBackgroundTask (singleton)', () => {{ status: 'completed' as const, field: 'result', output: 'RECOVERED RESULT' },{ status: 'error' as const, field: 'error', output: 'RECOVERED FAILURE' },])('recovers a durable $status receipt after process-local state is lost', async (terminal) => {+ const settledAt = new Date('2026-09-22T09:00:00.000Z');const claimBackgroundToolResult = jest.fn(async () => ({status: 'acquired' as const,messageId: 'response-recovered',@@ -2576,6 +2647,7 @@ describe('runCheckBackgroundTask (singleton)', () => {toolName: 'slow_tool',status: terminal.status,output: terminal.output,+ settledAt,},],}));@@ -2595,7 +2667,11 @@ describe('runCheckBackgroundTask (singleton)', () => {status: terminal.status,background_task_id: 'task-recovered',[terminal.field]: terminal.output,+ /** The receipt records settlement only, so a recovered poll reports no span. */+ settled_at: settledAt.toISOString(),});+ expect(result.started_at).toBeUndefined();+ expect(result.elapsed_ms).toBeUndefined();expect(claimBackgroundToolResult).toHaveBeenCalledWith(expect.not.objectContaining({ messageId: expect.anything() }),);@@ -2915,6 +2991,13 @@ describe('runCheckBackgroundTask (singleton)', () => {expect(second).toEqual(expect.objectContaining({ status: 'claimed', result_claimed: true }));expect(second.result).toBeUndefined();expect(claimBackgroundToolResult).not.toHaveBeenCalled();++ /** A subagent task reports the same timings as an ordinary one. */+ for (const polled of [first, second]) {+ expect(Number.isNaN(Date.parse(polled.started_at))).toBe(false);+ expect(Date.parse(polled.settled_at)).toBeGreaterThanOrEqual(Date.parse(polled.started_at));+ expect(polled.elapsed_ms).toBe(Date.parse(polled.settled_at) - Date.parse(polled.started_at));+ }});it('falls through cleanly when neither background store recognizes a poll id', async () => {diff --git a/packages/api/src/agents/background.ts b/packages/api/src/agents/background.tsindex adc187943a..2c9b744ee4 100644--- a/packages/api/src/agents/background.ts+++ b/packages/api/src/agents/background.ts@@ -1831,6 +1831,12 @@ interface SerializedBackgroundTask {/** Coarse 0..1: no intermediate progress exists, only running vs settled. */progress: number;cancellation_requested?: boolean;+ /** ISO-8601 dispatch time, the app's serialization for every timestamp. */+ started_at?: string;+ /** ISO-8601 terminal time. Absent while the task is still running. */+ settled_at?: string;+ /** Dispatch to settlement, or dispatch to this poll while still running. */+ elapsed_ms?: number;result?: string;result_available?: boolean;result_chars?: number;@@ -1838,6 +1844,32 @@ interface SerializedBackgroundTask {error?: string;}+/**+ * Model-facing task timings. The registry keeps epoch milliseconds; everything the+ * app serializes carries ISO-8601 (`toISOString`), so the poll payload does too.+ * `elapsed_ms` is served alongside them because a polling model has no clock of its+ * own: without it, "running" carries no age and a caller cannot tell a task that+ * started seconds ago from one stuck for an hour.+ *+ * `createdAt` is the strictly-increasing dispatch stamp, so a same-millisecond+ * dispatch can read a few milliseconds after its real start and, for an instantly+ * settled task, after `updatedAt`; clamping keeps `settled_at` from preceding+ * `started_at` and `elapsed_ms` from going negative.+ */+function taskTimings(task: {+ status: string;+ createdAt: number;+ updatedAt: number;+}): Pick<SerializedBackgroundTask, 'started_at' | 'settled_at' | 'elapsed_ms'> {+ const settled = task.status !== 'running';+ const settledAt = Math.max(task.updatedAt, task.createdAt);+ return {+ started_at: new Date(task.createdAt).toISOString(),+ ...(settled ? { settled_at: new Date(settledAt).toISOString() } : {}),+ elapsed_ms: Math.max(0, (settled ? settledAt : Date.now()) - task.createdAt),+ };+}+function resultFields(task: BackgroundTask,includeResult: boolean,@@ -1880,18 +1912,25 @@ function serializeTask(...(task.status === 'running' && task.cancellationRequestedAt != null? { cancellation_requested: true }: {}),+ ...taskTimings(task),...resultFields(task, includeResult),...taskNote(task),...(task.error !== undefined ? { error: task.error } : {}),};}+/**+ * A durable receipt is what a poll sees once process-local state is gone (another+ * replica, or after a restart). It records when the task settled but not when it was+ * dispatched, so it carries `settled_at` alone: no start, hence no elapsed span.+ */function serializeDurableTask(task: BackgroundToolResultRecord): SerializedBackgroundTask {return {background_task_id: task.taskId,tool: task.toolName,status: task.status,progress: 1,+ ...(task.settledAt == null ? {} : { settled_at: task.settledAt.toISOString() }),...(task.status === 'completed' ? { result: task.output } : { error: task.output }),};}@@ -1904,6 +1943,9 @@ interface SerializedSubagentTask {status: string;progress: number;progress_detail?: SubagentTaskSnapshot['progress'];+ started_at?: string;+ settled_at?: string;+ elapsed_ms?: number;result?: string;result_available?: boolean;result_claimed?: boolean;@@ -1930,6 +1972,8 @@ function serializeSubagentSnapshot(status: options.status ?? task.status,progress: task.status === 'running' ? 0 : 1,...(task.progress == null ? {} : { progress_detail: task.progress }),+ /** Timings follow the task's own lifecycle, never a control receipt's status. */+ ...taskTimings(task),...(options.includeResult == null ? {} : { result: options.includeResult }),...(task.resultAvailable ? { result_available: true } : {}),...(task.resultClaimed ? { result_claimed: true } : {}),diff --git a/packages/data-schemas/src/methods/message.spec.ts b/packages/data-schemas/src/methods/message.spec.tsindex 83751e49e9..8460b85dcf 100644--- a/packages/data-schemas/src/methods/message.spec.ts+++ b/packages/data-schemas/src/methods/message.spec.ts@@ -1200,6 +1200,7 @@ describe('Message Operations', () => {});it('lets a same-generation manual poll claim an anchored terminal receipt', async () => {+ const settledAt = new Date('2026-09-22T09:00:00.000Z');await saveMessage(mockCtx, {...mockMessageData,unfinished: true,@@ -1216,7 +1217,7 @@ describe('Message Operations', () => {taskId: 'task-same-generation',toolName: 'slow_tool',status: 'completed',- settledAt: new Date(),+ settledAt,completionWakeup: true,},},@@ -1264,6 +1265,8 @@ describe('Message Operations', () => {status: 'completed',output: 'settled output',agentId: 'agent-a',+ /** Carried through so a poll can report when the task settled. */+ settledAt,},],});@@ -1388,6 +1391,7 @@ describe('Message Operations', () => {status: 'completed',output: 'durable result',agentId: 'agent-a',+ settledAt: expect.any(Date),},],};@@ -1597,6 +1601,7 @@ describe('Message Operations', () => {toolName: 'bash_tool',status: 'cancelled',output: 'Background task cancellation requested',+ settledAt: expect.any(Date),},],});@@ -1643,6 +1648,7 @@ describe('Message Operations', () => {status: 'completed',output: 'one',agentId: 'agent-a',+ settledAt: expect.any(Date),},{taskId: 'task-2',@@ -1651,6 +1657,7 @@ describe('Message Operations', () => {status: 'completed',output: 'two',agentId: 'agent-a',+ settledAt: expect.any(Date),},],});@@ -1954,6 +1961,7 @@ describe('Message Operations', () => {status: 'completed',output: 'a',agentId: 'agent-a',+ settledAt: expect.any(Date),},],});diff --git a/packages/data-schemas/src/methods/message.ts b/packages/data-schemas/src/methods/message.tsindex 49f2958449..8b85d82d61 100644--- a/packages/data-schemas/src/methods/message.ts+++ b/packages/data-schemas/src/methods/message.ts@@ -497,6 +497,9 @@ export interface BackgroundToolResultRecord {status: 'completed' | 'error' | 'cancelled';output: string;agentId?: string;+ /** When the task reached this terminal status. Absent on rows written before+ * the stamp existed, so a consumer must treat it as optional. */+ settledAt?: Date;}export type BackgroundToolResultClaim =@@ -626,6 +629,22 @@ export interface ConversationTraceRefs {sampledMessages: SampledTraceMessage[];}+/**+ * Reads a stored terminal stamp defensively: rows written before the stamp existed+ * omit it, and a document can reach here from a raw read where the date is still a+ * string, so an unusable value is reported as absent rather than as `Invalid Date`.+ */+function toSettledAt(value: unknown): Date | undefined {+ if (value instanceof Date) {+ return Number.isNaN(value.getTime()) ? undefined : value;+ }+ if (typeof value === 'string' || typeof value === 'number') {+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;+ }+ return undefined;+}+export interface MessageMethods {saveMessage(ctx: {@@ -1493,6 +1512,7 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): MessatoolName?: unknown;status?: unknown;cancelled?: unknown;+ settledAt?: unknown;resultClaim?: { kind?: unknown; claimId?: unknown };};};@@ -1515,6 +1535,7 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): Messa} else if (typeof toolCall.agentId === 'string') {resultAgentId = toolCall.agentId;}+ const settledAt = toSettledAt(task.settledAt);results.push({taskId: task.taskId,toolCallId: toolCall.id,@@ -1522,6 +1543,7 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): Messastatus: task.cancelled === true ? 'cancelled' : task.status,output: typeof toolCall.output === 'string' ? toolCall.output : '',...(resultAgentId == null ? {} : { agentId: resultAgentId }),+ ...(settledAt == null ? {} : { settledAt }),});}return results;