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: View and Stop Background Tasks From the Chat Header (#16348)
Danny Avilae32e6b540ecd
diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.jsindex 0fdb419324..1498f62b0e 100644--- a/api/server/routes/__test-utils__/convos-route-mocks.js+++ b/api/server/routes/__test-utils__/convos-route-mocks.js@@ -123,6 +123,13 @@ module.exports = {}),createSubagentThreadViewHandler: jest.fn(() => (_req, res) => res.status(200).json({})),createSubagentControlHandler: jest.fn(() => (_req, res) => res.status(200).json({})),+ createBackgroundTaskIndexHandler: jest.fn(+ () => (_req, res) => res.status(200).json({ tasks: [] }),+ ),+ createBackgroundTaskPolicyMiddleware: jest.fn(() => (_req, _res, next) => next()),+ createBackgroundTaskCancelHandler: jest.fn(+ () => (_req, res) => res.status(200).json({ results: [] }),+ ),isValidSubagentControlRequest: jest.fn((body) => {if (body == null || typeof body !== 'object') return false;const commonKeys = ['taskId', 'invocationId', 'action'];diff --git a/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js b/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.jsindex e1e4280e3d..725e3c240c 100644--- a/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js+++ b/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js@@ -2,6 +2,7 @@ const express = require('express');const request = require('supertest');const MOCKS = '../__test-utils__/convos-route-mocks';+jest.mock('~/server/services/Config/app', () => ({ getAppConfig: jest.fn() }));jest.mock('@librechat/agents', () => require(MOCKS).agents());jest.mock('@librechat/api', () =>diff --git a/api/server/routes/__tests__/convos.spec.js b/api/server/routes/__tests__/convos.spec.jsindex b03940381b..b9302466a5 100644--- a/api/server/routes/__tests__/convos.spec.js+++ b/api/server/routes/__tests__/convos.spec.js@@ -2,6 +2,7 @@ const express = require('express');const request = require('supertest');const MOCKS = '../__test-utils__/convos-route-mocks';+jest.mock('~/server/services/Config/app', () => ({ getAppConfig: jest.fn() }));const {archiveAllHandler,generationJobManager,diff --git a/api/server/routes/convos.js b/api/server/routes/convos.jsindex dc45fd6a3b..96345a5efe 100644--- a/api/server/routes/convos.js+++ b/api/server/routes/convos.js@@ -16,6 +16,10 @@ const {isValidSubagentControlRequest,exemptAgentTriggerFromIpLimiter,createParentSubagentIndexHandler,+ createBackgroundTaskIndexHandler,+ createBackgroundTaskCancelHandler,+ createBackgroundTaskPolicyMiddleware,+ backgroundTaskRegistry,createSubagentThreadViewHandler,resolveImportMaxFileSize,restoreTenantContextFromReq,@@ -32,6 +36,7 @@ const {isStopConfirmed,} = require('@librechat/api');const { logger } = require('@librechat/data-schemas');+const { getAppConfig } = require('~/server/services/Config/app');const { CacheKeys, EModelEndpoint } = require('librechat-data-provider');const {createImportLimiters,@@ -144,6 +149,13 @@ const subagentControlHandler = createSubagentControlHandler({getSubagentTaskControlReceipt: db.getSubagentTaskControlReceipt,store: subagentThreadTaskStore,});+const backgroundTaskPolicy = createBackgroundTaskPolicyMiddleware({ getAppConfig });+const backgroundTaskIndexHandler = createBackgroundTaskIndexHandler({+ registry: backgroundTaskRegistry,+});+const backgroundTaskCancelHandler = createBackgroundTaskCancelHandler({+ registry: backgroundTaskRegistry,+});router.use(requireJwtAuth);const isValidProjectFilter = (projectId) =>@@ -207,6 +219,12 @@ router.post(subagentControlHandler,);router.get('/:parentConversationId/subagents', parentSubagentIndexHandler);+router.get('/:conversationId/background-tasks', backgroundTaskPolicy, backgroundTaskIndexHandler);+router.post(+ '/:conversationId/background-tasks/cancel',+ backgroundTaskPolicy,+ backgroundTaskCancelHandler,+);router.get('/:parentConversationId/subagents/:threadId', subagentThreadViewHandler);router.get('/:conversationId', async (req, res) => {diff --git a/client/src/components/Chat/BackgroundTasks/Button.tsx b/client/src/components/Chat/BackgroundTasks/Button.tsxnew file mode 100644index 0000000000..622fba5fc6--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/Button.tsx@@ -0,0 +1,202 @@+import { memo, useEffect, useRef, useState } from 'react';+import * as Ariakit from '@ariakit/react';+import { TooltipAnchor } from '@librechat/client';+import { ListTodo, Maximize2, Minimize2, Square, X } from 'lucide-react';+import { RECENT_SUBAGENT_WINDOW_MS } from './rows';+import useBackgroundTasks from './useTasks';+import { useLocalize } from '~/hooks';+import Section from './Section';+import TaskCard from './Card';+import { cn } from '~/utils';++const TICK_MS = 1_000;++const iconButtonClass =+ 'flex size-7 shrink-0 items-center justify-center rounded-md text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:pointer-events-none disabled:opacity-50';++/** Header control listing the conversation's background tools and subagents. */+function BackgroundTasksButton({+ conversationId,+ isSubmitting,+}: {+ conversationId: string;+ isSubmitting: boolean;+}) {+ const localize = useLocalize();+ const popover = Ariakit.usePopoverStore({ placement: 'bottom-end' });+ const open = Ariakit.useStoreState(popover, 'open');+ const disclosureRef = useRef<HTMLButtonElement>(null);+ const [now, setNow] = useState(() => Date.now());+ const [wide, setWide] = useState(false);+ const [popoverElement, setPopoverElement] = useState<HTMLDivElement | null>(null);+ const view = useBackgroundTasks({ conversationId, isSubmitting, now });+ const { rows, activeCount } = view;++ useEffect(() => {+ setNow(Date.now());+ if (!open || activeCount === 0) return;+ const timer = setInterval(() => setNow(Date.now()), TICK_MS);+ return () => clearInterval(timer);+ }, [open, activeCount]);++ const nextExpiry = rows.reduce(+ (next, row) =>+ row.settledAt != null && row.status !== 'running' && row.status !== 'stopping'+ ? Math.min(next, row.settledAt + RECENT_SUBAGENT_WINDOW_MS + 1)+ : next,+ Infinity,+ );+ useEffect(() => {+ if (!Number.isFinite(nextExpiry)) return;+ const timer = setTimeout(() => setNow(Date.now()), Math.max(0, nextExpiry - Date.now()));+ return () => clearTimeout(timer);+ }, [nextExpiry]);++ if (rows.length === 0 && !view.loadFailed) {+ return null;+ }++ const title = localize('com_ui_background_tasks');+ const triggerLabel =+ activeCount > 0 ? localize('com_ui_background_tasks_label', { 0: activeCount }) : title;+ const running = rows.filter((row) => row.status === 'running' || row.status === 'stopping');+ const finished = rows.filter((row) => row.status !== 'running' && row.status !== 'stopping');+ const anyStoppable = running.some(view.canStop);+ const partiallyStoppable = running.some((row) => row.status === 'running' && !view.canStop(row));+ let stopAllLabel = localize('com_ui_background_tasks_stop_all');+ if (!anyStoppable) {+ stopAllLabel = localize('com_ui_background_tasks_cancel_disabled');+ } else if (partiallyStoppable) {+ stopAllLabel = localize('com_ui_background_tasks_stop_available');+ }+ const card = (row: (typeof rows)[number]) => (+ <TaskCard+ key={row.id}+ row={row}+ now={now}+ canStop={view.canStop(row)}+ isStopping={view.isStopping}+ onStop={view.stop}+ portalElement={popoverElement}+ />+ );++ return (+ <>+ <TooltipAnchor+ description={triggerLabel}+ render={+ <Ariakit.PopoverDisclosure+ ref={disclosureRef}+ store={popover}+ aria-label={triggerLabel}+ data-testid="header-background-tasks-button"+ className="relative inline-flex size-9 flex-shrink-0 items-center justify-center rounded-xl border border-border-light bg-presentation text-text-primary transition-all ease-in-out hover:bg-surface-tertiary aria-expanded:bg-surface-tertiary"+ >+ <ListTodo className="icon-md" aria-hidden="true" />+ {activeCount > 0 && (+ <span+ aria-hidden="true"+ className="absolute -right-0.5 -top-0.5 size-2 animate-pulse rounded-full bg-status-info ring-2 ring-presentation motion-reduce:animate-none"+ />+ )}+ </Ariakit.PopoverDisclosure>+ }+ />+ <Ariakit.Popover+ ref={setPopoverElement}+ store={popover}+ gutter={8}+ portal+ unmountOnHide+ finalFocus={disclosureRef}+ aria-label={title}+ className={cn(+ 'z-[200] flex max-h-[min(36rem,calc(100vh-5rem))] max-w-[calc(100vw-2rem)] flex-col rounded-xl border border-border-medium bg-surface-secondary text-text-primary shadow-lg focus:outline-none',+ wide ? 'w-[36rem]' : 'w-80',+ )}+ >+ <div className="flex items-center gap-1 px-3 pb-2 pt-3">+ <Ariakit.PopoverHeading className="flex-1 text-sm font-semibold">+ {title}+ </Ariakit.PopoverHeading>+ <button+ type="button"+ aria-label={localize(wide ? 'com_ui_collapse' : 'com_ui_expand')}+ aria-pressed={wide}+ onClick={() => setWide((value) => !value)}+ className={cn(iconButtonClass, 'max-sm:hidden')}+ >+ {wide ? (+ <Minimize2 className="size-4" aria-hidden="true" />+ ) : (+ <Maximize2 className="size-4" aria-hidden="true" />+ )}+ </button>+ <Ariakit.PopoverDismiss aria-label={localize('com_ui_close')} className={iconButtonClass}>+ <X className="size-4" aria-hidden="true" />+ </Ariakit.PopoverDismiss>+ </div>+ <div className="space-y-4 overflow-y-auto px-3 pb-3">+ {view.loadFailed && (+ <div role="alert" className="text-sm text-status-error">+ <p>{localize('com_ui_background_tasks_load_failed')}</p>+ <button+ type="button"+ className="rounded px-2 py-1 text-text-primary underline focus-visible:ring-2 focus-visible:ring-ring-primary"+ onClick={() => void view.retry()}+ >+ {localize('com_ui_retry')}+ </button>+ </div>+ )}+ {running.length > 0 && (+ <Section+ label={localize('com_ui_background_tasks_running')}+ count={running.length}+ action={+ <TooltipAnchor+ description={stopAllLabel}+ portalElement={popoverElement}+ render={+ <span+ role={!anyStoppable ? 'group' : undefined}+ aria-label={!anyStoppable ? stopAllLabel : undefined}+ tabIndex={!anyStoppable ? 0 : undefined}+ className="inline-flex"+ >+ <button+ type="button"+ aria-label={stopAllLabel}+ disabled={!anyStoppable || view.isStopping}+ onClick={() => void view.stopAll()}+ data-testid="background-tasks-stop-all"+ className={cn(iconButtonClass, 'border border-border-medium')}+ >+ <Square className="size-3 fill-current" aria-hidden="true" />+ </button>+ </span>+ }+ />+ }+ >+ {running.map(card)}+ </Section>+ )}+ {finished.length > 0 && (+ <Section label={localize('com_ui_background_tasks_finished')} count={finished.length}>+ {finished.map(card)}+ </Section>+ )}+ {view.stopFailed && (+ <p role="alert" className="px-3 pb-3 text-sm text-status-error">+ {localize('com_ui_background_tasks_stop_failed')}+ </p>+ )}+ </div>+ </Ariakit.Popover>+ </>+ );+}++export default memo(BackgroundTasksButton);diff --git a/client/src/components/Chat/BackgroundTasks/Card.tsx b/client/src/components/Chat/BackgroundTasks/Card.tsxnew file mode 100644index 0000000000..3cf97129f8--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/Card.tsx@@ -0,0 +1,129 @@+import { memo, useId, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { ChevronDown, Square } from 'lucide-react';+import { Spinner, TooltipAnchor } from '@librechat/client';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { TaskRow, TaskRowStatus } from './rows';+import { getRunStepDurationLabels, getToolDisplayLabel, cn } from '~/utils';+import { useLocalize } from '~/hooks';++const STATUS_KEYS: Record<TaskRowStatus, TranslationKeys> = {+ running: 'com_ui_background_tasks_running',+ stopping: 'com_ui_background_tasks_stopping',+ completed: 'com_ui_background_tasks_completed',+ error: 'com_ui_failed',+ cancelled: 'com_ui_cancelled',+};++const STATUS_CLASSES: Partial<Record<TaskRowStatus, string>> = {+ error: 'text-status-error',+ cancelled: 'text-status-warning',+};++function TaskCard({+ row,+ now,+ canStop,+ isStopping,+ onStop,+ portalElement,+}: {+ row: TaskRow;+ now: number;+ canStop: boolean;+ isStopping: boolean;+ onStop: (row: TaskRow) => void;+ portalElement: HTMLElement | null;+}) {+ const localize = useLocalize();+ const { i18n } = useTranslation();+ const detailId = useId();+ const [open, setOpen] = useState(false);+ const active = row.status === 'running' || row.status === 'stopping';+ const kindLabel =+ row.kind === 'subagent'+ ? localize('com_ui_background_tasks_subagent')+ : getToolDisplayLabel(row.name, localize);+ const title = row.title ?? (row.kind === 'subagent' ? row.name : kindLabel);+ const end = active ? now : row.settledAt;+ const duration =+ row.startedAt != null && end != null+ ? getRunStepDurationLabels(Math.max(0, end - row.startedAt), i18n.language)+ : undefined;+ const stopLabel = localize('com_ui_background_tasks_stop');+ const expandable = row.detail != null;++ return (+ <li className="rounded-lg bg-surface-tertiary px-3 py-2" data-testid="background-task-row">+ <div className="flex items-start gap-2">+ <div className="min-w-0 flex-1">+ {expandable ? (+ <button+ type="button"+ aria-expanded={open}+ aria-controls={detailId}+ onClick={() => setOpen((value) => !value)}+ className="flex max-w-full items-start gap-1 rounded text-left text-sm text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <span className="line-clamp-2 break-words">{title}</span>+ <ChevronDown+ aria-hidden="true"+ className={cn(+ 'mt-1 size-3.5 shrink-0 text-text-secondary transition-transform motion-reduce:transition-none',+ open && 'rotate-180',+ )}+ />+ </button>+ ) : (+ <p className="line-clamp-2 break-words text-sm text-text-primary">{title}</p>+ )}+ <p className="mt-0.5 flex items-center gap-2 text-xs text-text-secondary">+ {title !== kindLabel && <span className="font-medium">{kindLabel}</span>}+ {active ? null : (+ <span className={STATUS_CLASSES[row.status]}>+ {localize(STATUS_KEYS[row.status])}+ </span>+ )}+ {row.status === 'stopping' && <span>{localize(STATUS_KEYS.stopping)}</span>}+ {duration != null && (+ <span+ className="tabular-nums"+ aria-label={localize(duration.announcedKey, duration.announcedValues)}+ >+ {localize(duration.key, duration.values)}+ </span>+ )}+ </p>+ </div>+ {row.status === 'running' && canStop && (+ <TooltipAnchor+ description={stopLabel}+ portalElement={portalElement}+ render={+ <button+ type="button"+ aria-label={`${stopLabel}: ${title}`}+ disabled={isStopping}+ onClick={() => onStop(row)}+ className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border-medium text-text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:opacity-50"+ >+ <Square className="size-3" aria-hidden="true" />+ </button>+ }+ />+ )}+ {row.status === 'stopping' && <Spinner className="size-4 shrink-0 text-text-secondary" />}+ </div>+ {expandable && open && (+ <pre+ id={detailId}+ className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-md bg-surface-primary p-2 font-mono text-xs text-text-primary"+ >+ {row.detail}+ </pre>+ )}+ </li>+ );+}++export default memo(TaskCard);diff --git a/client/src/components/Chat/BackgroundTasks/Section.tsx b/client/src/components/Chat/BackgroundTasks/Section.tsxnew file mode 100644index 0000000000..aa8527ed87--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/Section.tsx@@ -0,0 +1,50 @@+import { useId, useState } from 'react';+import { ChevronDown } from 'lucide-react';+import { cn } from '~/utils';++/** A labelled, collapsible group; `action` stays reachable while collapsed. */+export default function Section({+ label,+ count,+ action,+ defaultOpen = true,+ children,+}: {+ label: string;+ count: number;+ action?: React.ReactNode;+ defaultOpen?: boolean;+ children: React.ReactNode;+}) {+ const listId = useId();+ const [open, setOpen] = useState(defaultOpen);+ return (+ <section className="space-y-2">+ <div className="flex items-center gap-2">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={listId}+ onClick={() => setOpen((value) => !value)}+ className="flex min-w-0 flex-1 items-center gap-1 rounded text-sm text-text-secondary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <span>{label}</span>+ <span className="tabular-nums">{count}</span>+ <ChevronDown+ aria-hidden="true"+ className={cn(+ 'size-3.5 shrink-0 transition-transform motion-reduce:transition-none',+ !open && '-rotate-90',+ )}+ />+ </button>+ {action}+ </div>+ {open && (+ <ul id={listId} className="space-y-2">+ {children}+ </ul>+ )}+ </section>+ );+}diff --git a/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx b/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsxnew file mode 100644index 0000000000..3e6dd8dfdc--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx@@ -0,0 +1,466 @@+import React from 'react';+import { RecoilRoot } from 'recoil';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, render, screen, waitFor, within } from '@testing-library/react';+import { ContentTypes, QueryKeys, dataService } from 'librechat-data-provider';+import type { ParentSubagentSummary, BackgroundTaskIndex, TMessage } from 'librechat-data-provider';+import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider';+import BackgroundTasksButton from '../Button';++jest.mock('librechat-data-provider', () => {+ const actual =+ jest.requireActual<typeof import('librechat-data-provider')>('librechat-data-provider');+ return { ...actual, dataService: { ...actual.dataService } };+});++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++const conversationId = 'convo-1';+const startedAt = new Date(Date.now() - 30_000).toISOString();++const index = (overrides: Partial<BackgroundTaskIndex> = {}): BackgroundTaskIndex => ({+ conversationId,+ cancellable: true,+ tasks: [+ {+ taskId: 'task-running',+ toolName: 'bash_tool',+ toolCallId: 'call-running',+ status: 'running',+ cancellationRequested: false,+ startedAt,+ },+ {+ taskId: 'task-done',+ toolName: 'bash_tool',+ toolCallId: 'call-done',+ status: 'completed',+ cancellationRequested: false,+ startedAt,+ settledAt: new Date().toISOString(),+ },+ ],+ ...overrides,+});++const runningChild: ParentSubagentSummary = {+ threadId: 'thread-1',+ parentMessageId: 'parent-message',+ parentToolCallId: 'call-subagent',+ subagentType: 'researcher',+ subagentKind: 'agent',+ title: 'Research the API',+ origin: 'tool',+ status: 'running',+ latestTaskId: 'sub-task-1',+ tasks: [{ taskId: 'sub-task-1', status: 'running', createdAt: startedAt }],+ tasksTruncated: false,+};++const messages: TMessage[] = [+ {+ messageId: 'message-1',+ conversationId,+ parentMessageId: null,+ isCreatedByUser: false,+ text: '',+ content: [+ {+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ id: 'call-running',+ name: 'bash_tool',+ args: '{"intent":"Rerun the focused specs","command":"npx jest tasks.spec.ts"}',+ },+ },+ ],+ } as TMessage,+];++const renderButton = (children: ParentSubagentSummary[] = [], initialMessages = messages) => {+ jest.spyOn(dataService, 'getSubagentThread').mockImplementation(() => new Promise(() => {}));+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData([QueryKeys.messages, conversationId], initialMessages);+ jest.spyOn(dataService, 'getParentSubagents').mockResolvedValue({+ parentConversationId: conversationId,+ children,+ childrenTruncated: false,+ });+ const rendered = render(+ <RecoilRoot>+ <QueryClientProvider client={queryClient}>+ <ParentSubagentsProvider conversationId={conversationId} enabled>+ <BackgroundTasksButton conversationId={conversationId} isSubmitting={false} />+ </ParentSubagentsProvider>+ </QueryClientProvider>+ </RecoilRoot>,+ );+ return { ...rendered, queryClient };+};++afterEach(() => jest.restoreAllMocks());++describe('BackgroundTasksButton', () => {+ it('does not expose the previous conversation tasks while host context catches up to navigation', async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData([QueryKeys.parentSubagents, 'old-chat'], {+ parentConversationId: 'old-chat',+ children: [runningChild],+ childrenTruncated: false,+ });+ const getTasks = jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());+ jest.spyOn(dataService, 'getParentSubagents').mockResolvedValue({+ parentConversationId: 'old-chat',+ children: [runningChild],+ childrenTruncated: false,+ });+ const panel = (hostId: string) => (+ <RecoilRoot>+ <QueryClientProvider client={queryClient}>+ <ParentSubagentsProvider conversationId={hostId} enabled>+ <BackgroundTasksButton conversationId={conversationId} isSubmitting={false} />+ </ParentSubagentsProvider>+ </QueryClientProvider>+ </RecoilRoot>+ );+ const { rerender, container } = render(panel('old-chat'));+ await act(async () => {});+ expect(container).toBeEmptyDOMElement();+ expect(getTasks).not.toHaveBeenCalled();+ rerender(panel(conversationId));+ await waitFor(() => expect(getTasks).toHaveBeenCalledWith(conversationId));+ });++ it.each(['tool', 'subagent'])(+ 'ages out the last finished %s even while the panel is closed',+ async (kind) => {+ jest.useFakeTimers();+ try {+ const settledAt = new Date(Date.now() - 3_599_000).toISOString();+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(+ index({+ tasks:+ kind === 'tool'+ ? [+ {+ ...index().tasks[1],+ settledAt,+ },+ ]+ : [],+ }),+ );+ renderButton(+ kind === 'subagent'+ ? [+ {+ ...runningChild,+ status: 'completed',+ updatedAt: settledAt,+ },+ ]+ : [],+ );+ await act(async () => {+ await jest.advanceTimersByTimeAsync(100);+ });+ expect(screen.getByTestId('header-background-tasks-button')).toBeInTheDocument();+ await act(async () => {+ await jest.advanceTimersByTimeAsync(1_100);+ });+ expect(screen.queryByTestId('header-background-tasks-button')).toBeNull();+ } finally {+ jest.useRealTimers();+ }+ },+ );++ it('keeps an accepted cancellation pending through an observation failure, then reconciles failure', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));+ const cancel = jest+ .spyOn(dataService, 'controlSubagentTask')+ .mockImplementation(async (_parent, _thread, command) => ({+ receipt: {+ invocationId: command.invocationId,+ action: 'cancel',+ status: 'accepted',+ createdAt: startedAt,+ updatedAt: startedAt,+ },+ }));+ const { queryClient } = renderButton([runningChild]);+ jest+ .mocked(dataService.getSubagentThread)+ .mockRejectedValueOnce(new Error('receipt read unavailable'));+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ await user.click(await screen.findByRole('button', { name: /com_ui_background_tasks_stop:/ }));+ await waitFor(() => expect(cancel).toHaveBeenCalledTimes(1));+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'com_ui_background_tasks_load_failed',+ );+ expect(screen.queryByRole('button', { name: /com_ui_background_tasks_stop:/ })).toBeNull();+ const invocationId = cancel.mock.calls[0][2].invocationId;+ act(() => {+ queryClient.setQueryData(+ [+ QueryKeys.subagentThread,+ conversationId,+ runningChild.threadId,+ runningChild.latestTaskId,+ ],+ {+ controlReceipts: [{ invocationId, status: 'failed' }],+ },+ );+ });+ await waitFor(() =>+ expect(screen.getByRole('alert')).toHaveTextContent('com_ui_background_tasks_stop_failed'),+ );+ expect(+ await screen.findByRole('button', { name: /com_ui_background_tasks_stop:/ }),+ ).toBeEnabled();+ });++ it('shows an initial load failure and lets the user retry', async () => {+ const getTasks = jest+ .spyOn(dataService, 'getBackgroundTasks')+ .mockRejectedValueOnce(new Error('unavailable'))+ .mockResolvedValue(index());+ renderButton();+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'com_ui_background_tasks_load_failed',+ );+ await user.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ await waitFor(() => expect(getTasks).toHaveBeenCalledTimes(2));+ expect(await screen.findByText('Rerun the focused specs')).toBeVisible();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('fills in commands when restored messages arrive after the task index', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());+ const { queryClient } = renderButton([], []);+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ expect(screen.queryByText('Rerun the focused specs')).toBeNull();+ act(() => {+ queryClient.setQueryData([QueryKeys.messages, conversationId], messages);+ });+ expect(await screen.findByText('Rerun the focused specs')).toBeVisible();+ });++ it('does not carry stopping into a new task on the same child thread', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));+ jest.spyOn(dataService, 'controlSubagentTask').mockResolvedValue({+ receipt: {+ invocationId: 'cancel-a',+ action: 'cancel',+ status: 'accepted',+ createdAt: startedAt,+ updatedAt: startedAt,+ },+ });+ const { queryClient } = renderButton([runningChild]);+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ await user.click(await screen.findByRole('button', { name: /com_ui_background_tasks_stop:/ }));+ await waitFor(() =>+ expect(screen.queryByRole('button', { name: /com_ui_background_tasks_stop:/ })).toBeNull(),+ );+ act(() => {+ queryClient.setQueryData([QueryKeys.parentSubagents, conversationId], {+ parentConversationId: conversationId,+ childrenTruncated: false,+ children: [+ {+ ...runningChild,+ latestTaskId: 'sub-task-2',+ tasks: [+ ...runningChild.tasks,+ { taskId: 'sub-task-2', status: 'running', createdAt: new Date().toISOString() },+ ],+ },+ ],+ });+ });+ expect(+ await screen.findByRole('button', { name: /com_ui_background_tasks_stop:/ }),+ ).toBeEnabled();+ });+ it('renders nothing when the conversation has no background tasks', async () => {+ const getTasks = jest+ .spyOn(dataService, 'getBackgroundTasks')+ .mockResolvedValue(index({ tasks: [] }));+ const { container } = renderButton();+ await waitFor(() => expect(getTasks).toHaveBeenCalledWith(conversationId));+ expect(container).toBeEmptyDOMElement();+ });++ it('groups running and finished tasks and reveals the command on demand', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());+ renderButton();+ const user = userEvent.setup();++ await user.click(await screen.findByTestId('header-background-tasks-button'));+ const dialog = await screen.findByRole('dialog', { name: 'com_ui_background_tasks' });+ const title = within(dialog).getByRole('button', { name: 'Rerun the focused specs' });+ expect(within(dialog).getAllByTestId('background-task-row')).toHaveLength(2);+ expect(within(dialog).queryByText('npx jest tasks.spec.ts')).toBeNull();++ await user.click(title);+ expect(title).toHaveAttribute('aria-expanded', 'true');+ expect(within(dialog).getByText('npx jest tasks.spec.ts')).toBeInTheDocument();++ const finished = within(dialog).getByRole('button', {+ name: /com_ui_background_tasks_finished/,+ });+ await user.click(finished);+ expect(finished).toHaveAttribute('aria-expanded', 'false');+ expect(within(dialog).getAllByTestId('background-task-row')).toHaveLength(1);+ });++ it('stops every running tool and subagent from the running row, even when collapsed', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());+ const cancelTools = jest+ .spyOn(dataService, 'cancelBackgroundTasks')+ .mockResolvedValue({ results: [{ taskId: 'task-running', status: 'requested' }] });+ const cancelSubagent = jest.spyOn(dataService, 'controlSubagentTask').mockResolvedValue({+ receipt: {+ invocationId: 'invocation',+ action: 'cancel',+ status: 'accepted',+ createdAt: startedAt,+ updatedAt: startedAt,+ },+ });+ renderButton([runningChild]);+ const user = userEvent.setup();++ await user.click(await screen.findByTestId('header-background-tasks-button'));+ const dialog = await screen.findByRole('dialog', { name: 'com_ui_background_tasks' });+ await waitFor(() =>+ expect(within(dialog).getAllByTestId('background-task-row')).toHaveLength(3),+ );+ await user.click(+ within(dialog).getByRole('button', { name: /com_ui_background_tasks_running/ }),+ );+ await user.click(within(dialog).getByTestId('background-tasks-stop-all'));++ await waitFor(() =>+ expect(cancelTools).toHaveBeenCalledWith(conversationId, { taskIds: ['task-running'] }),+ );+ expect(cancelSubagent).toHaveBeenCalledWith(+ conversationId,+ 'thread-1',+ expect.objectContaining({ taskId: 'sub-task-1', action: 'cancel' }),+ );+ });++ it('keeps stop-all disabled when the server does not allow tool cancellation', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ cancellable: false }));+ const cancelTools = jest.spyOn(dataService, 'cancelBackgroundTasks');+ renderButton();+ const user = userEvent.setup();++ await user.click(await screen.findByTestId('header-background-tasks-button'));+ const stopAll = await screen.findByTestId('background-tasks-stop-all');+ expect(stopAll).toBeDisabled();+ expect(stopAll).toHaveAccessibleName('com_ui_background_tasks_cancel_disabled');+ const explanation = stopAll.parentElement!;+ expect(explanation).toHaveAttribute('tabindex', '0');+ expect(explanation).toHaveAttribute('aria-label', 'com_ui_background_tasks_cancel_disabled');+ act(() => explanation.focus());+ expect(explanation).toHaveFocus();+ expect(screen.queryByRole('button', { name: /com_ui_background_tasks_stop:/ })).toBeNull();+ expect(cancelTools).not.toHaveBeenCalled();+ });++ it('labels partial stop-all accurately when tool cancellation is disabled', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ cancellable: false }));+ const cancelTools = jest.spyOn(dataService, 'cancelBackgroundTasks');+ const cancelSubagent = jest.spyOn(dataService, 'controlSubagentTask').mockResolvedValue({+ receipt: {+ invocationId: 'invocation',+ action: 'cancel',+ status: 'accepted',+ createdAt: startedAt,+ updatedAt: startedAt,+ },+ });+ renderButton([runningChild]);+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ const dialog = screen.getByRole('dialog', { name: 'com_ui_background_tasks' });+ await waitFor(() =>+ expect(within(dialog).getAllByTestId('background-task-row')).toHaveLength(3),+ );+ const stopAll = within(dialog).getByTestId('background-tasks-stop-all');+ expect(stopAll).toHaveAccessibleName('com_ui_background_tasks_stop_available');+ await user.click(stopAll);+ expect(cancelTools).not.toHaveBeenCalled();+ expect(cancelSubagent).toHaveBeenCalledTimes(1);+ });++ it('shows failed cancellation and restores the retry control for a running subagent', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));+ const cancelSubagent = jest+ .spyOn(dataService, 'controlSubagentTask')+ .mockRejectedValueOnce(new Error('network unavailable'))+ .mockResolvedValue({+ receipt: {+ invocationId: 'invocation',+ action: 'cancel',+ status: 'accepted',+ createdAt: startedAt,+ updatedAt: startedAt,+ },+ });+ renderButton([runningChild]);+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ const dialog = screen.getByRole('dialog', { name: 'com_ui_background_tasks' });+ const stop = await within(dialog).findByRole('button', {+ name: /com_ui_background_tasks_stop:/,+ });+ await user.click(stop);+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(+ 'com_ui_background_tasks_stop_failed',+ );+ expect(+ within(dialog).getByRole('button', { name: /com_ui_background_tasks_stop:/ }),+ ).toBeEnabled();+ await user.click(within(dialog).getByRole('button', { name: /com_ui_background_tasks_stop:/ }));+ await waitFor(() => expect(cancelSubagent).toHaveBeenCalledTimes(2));+ });++ it('re-enables stopping after the server rejects a cancellation receipt', async () => {+ jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));+ jest.spyOn(dataService, 'controlSubagentTask').mockResolvedValue({+ receipt: {+ invocationId: 'invocation',+ action: 'cancel',+ status: 'rejected',+ createdAt: startedAt,+ updatedAt: startedAt,+ },+ });+ renderButton([runningChild]);+ const user = userEvent.setup();+ await user.click(await screen.findByTestId('header-background-tasks-button'));+ const dialog = screen.getByRole('dialog', { name: 'com_ui_background_tasks' });+ await user.click(+ await within(dialog).findByRole('button', { name: /com_ui_background_tasks_stop:/ }),+ );+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(+ 'com_ui_background_tasks_stop_failed',+ );+ expect(+ within(dialog).getByRole('button', { name: /com_ui_background_tasks_stop:/ }),+ ).toBeEnabled();+ });+});diff --git a/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts b/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.tsnew file mode 100644index 0000000000..b5ec2e072f--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts@@ -0,0 +1,151 @@+import { ContentTypes } from 'librechat-data-provider';+import type { ParentSubagentSummary, TMessage } from 'librechat-data-provider';+import {+ RECENT_SUBAGENT_WINDOW_MS,+ buildTaskRows,+ findToolCallArgs,+ subagentTaskKey,+} from '../rows';++const now = Date.parse('2026-09-24T12:00:00.000Z');+const iso = (offsetMs: number) => new Date(now - offsetMs).toISOString();++const child = (overrides: Partial<ParentSubagentSummary>): ParentSubagentSummary => ({+ threadId: 'thread',+ parentMessageId: 'message',+ subagentType: 'researcher',+ subagentKind: 'agent',+ title: 'Child',+ origin: 'tool',+ status: 'completed',+ latestTaskId: 'task',+ tasks: [{ taskId: 'task', status: 'completed', createdAt: iso(60_000) }],+ tasksTruncated: false,+ ...overrides,+});++describe('buildTaskRows', () => {+ it('orders active rows first and drops subagents settled past the retention window', () => {+ const rows = buildTaskRows({+ now,+ args: new Map(),+ describe: () => ({}),+ stoppingThreads: new Set([subagentTaskKey('running-child', 'task')]),+ tools: [+ {+ taskId: 'done',+ toolName: 'bash_tool',+ toolCallId: 'call-done',+ status: 'completed',+ cancellationRequested: false,+ startedAt: iso(1_000),+ settledAt: iso(500),+ },+ {+ taskId: 'stopping',+ toolName: 'bash_tool',+ toolCallId: 'call-stopping',+ status: 'running',+ cancellationRequested: true,+ startedAt: iso(90_000),+ },+ ],+ subagents: [+ child({ threadId: 'running-child', status: 'dispatched' }),+ child({ threadId: 'recent-child', status: 'failed', updatedAt: iso(10_000) }),+ child({ threadId: 'old-child', updatedAt: iso(RECENT_SUBAGENT_WINDOW_MS + 1) }),+ ],+ });++ expect(rows.map((row) => [row.id, row.status])).toEqual([+ ['subagent:running-child\u0000task', 'stopping'],+ ['tool:stopping', 'stopping'],+ ['tool:done', 'completed'],+ ['subagent:recent-child\u0000task', 'error'],+ ]);+ expect(rows[0].subagent).toEqual({ threadId: 'running-child', taskId: 'task' });+ expect(rows[3].subagent).toBeUndefined();+ });+});++describe('findToolCallArgs', () => {+ it('does not guess when a provider reuses a call id within one response', () => {+ const messages = [+ {+ messageId: 'm',+ content: ['first', 'second'].map((stepId) => ({+ type: ContentTypes.TOOL_CALL,+ tool_call: { id: 'call_0', stepId, args: { command: stepId } },+ })),+ },+ ] as unknown as TMessage[];+ expect(findToolCallArgs(messages, [{ messageId: 'm', toolCallId: 'call_0' }]).size).toBe(0);+ expect(+ findToolCallArgs(messages, [{ messageId: 'm', toolCallId: 'call_0', stepId: 'second' }]),+ ).toEqual(new Map([['m\u0000call_0\u0000second', { command: 'second' }]]));+ });+ it('resolves only the requested tool calls', () => {+ const messages = [+ {+ messageId: 'm1',+ content: [+ { type: ContentTypes.TEXT, text: 'hi' },+ {+ type: ContentTypes.TOOL_CALL,+ tool_call: { id: 'a', name: 'bash_tool', args: '{"command":"ls"}' },+ },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'b', name: 'bash_tool', args: '{}' } },+ ],+ },+ ] as unknown as TMessage[];+ expect(findToolCallArgs(messages, [{ messageId: 'm1', toolCallId: 'a' }])).toEqual(+ new Map([['m1\u0000a', '{"command":"ls"}']]),+ );+ expect(findToolCallArgs(undefined, [{ toolCallId: 'a' }]).size).toBe(0);+ });++ it('keeps separate commands for tasks whose call ids repeat in different messages', () => {+ const tools = [+ {+ taskId: 'older',+ messageId: 'm1',+ toolCallId: 'call_0',+ toolName: 'bash_tool',+ status: 'completed' as const,+ cancellationRequested: false,+ startedAt: iso(2_000),+ },+ {+ taskId: 'newer',+ messageId: 'm2',+ toolCallId: 'call_0',+ toolName: 'bash_tool',+ status: 'running' as const,+ cancellationRequested: false,+ startedAt: iso(1_000),+ },+ ];+ const messages = [+ {+ messageId: 'm1',+ content: [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'call_0', args: 'older' } }],+ },+ {+ messageId: 'm2',+ content: [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'call_0', args: 'newer' } }],+ },+ ] as unknown as TMessage[];+ const args = findToolCallArgs(messages, tools);+ const rows = buildTaskRows({+ now,+ args,+ tools,+ subagents: [],+ stoppingThreads: new Set(),+ describe: (value) => ({ detail: String(value) }),+ });+ expect(rows.find((row) => row.taskId === 'older')?.detail).toBe('older');+ expect(rows.find((row) => row.taskId === 'newer')?.detail).toBe('newer');+ expect(findToolCallArgs(messages, [{ toolCallId: 'call_0' }]).size).toBe(0);+ });+});diff --git a/client/src/components/Chat/BackgroundTasks/index.ts b/client/src/components/Chat/BackgroundTasks/index.tsnew file mode 100644index 0000000000..fa403f4320--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/index.ts@@ -0,0 +1 @@+export { default as BackgroundTasksButton } from './Button';diff --git a/client/src/components/Chat/BackgroundTasks/rows.ts b/client/src/components/Chat/BackgroundTasks/rows.tsnew file mode 100644index 0000000000..e982acfbca--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/rows.ts@@ -0,0 +1,160 @@+import { ContentTypes } from 'librechat-data-provider';+import type {+ TMessage,+ BackgroundTaskSummary,+ ParentSubagentSummary,+ SubagentThreadStatus,+} from 'librechat-data-provider';++export type TaskRowStatus = 'running' | 'stopping' | 'completed' | 'error' | 'cancelled';++export type TaskRow = {+ id: string;+ kind: 'tool' | 'subagent';+ /** Tool id for tool rows, thread title for subagent rows. */+ name: string;+ /** The call's model-authored intent, when its tool call is in the loaded messages. */+ title?: string;+ /** The command or code the call ran, for the expanded card. */+ detail?: string;+ /** Tool cancel target. */+ taskId?: string;+ status: TaskRowStatus;+ startedAt?: number;+ settledAt?: number;+ /** Subagent cancel target; present only while the child can still be stopped. */+ subagent?: { threadId: string; taskId: string };+};++/** Matches the server registry's settled-task retention, so both kinds age out together. */+export const RECENT_SUBAGENT_WINDOW_MS = 60 * 60 * 1000;++const time = (value?: string): number | undefined => {+ if (value == null) return undefined;+ const parsed = Date.parse(value);+ return Number.isFinite(parsed) ? parsed : undefined;+};++const subagentStatus = (status: SubagentThreadStatus): TaskRowStatus => {+ if (status === 'running' || status === 'dispatched') return 'running';+ if (status === 'failed' || status === 'interrupted') return 'error';+ return status;+};++export type ToolCallArgs = string | Record<string, unknown> | undefined;++/** Legacy identities are usable only when they resolve unambiguously. */+const toolCallKey = (messageId: string | undefined, toolCallId: string, stepId?: string): string =>+ `${messageId ?? ''}\u0000${toolCallId}${stepId == null ? '' : `\u0000${stepId}`}`;++export const subagentTaskKey = (threadId: string, taskId?: string): string =>+ `${threadId}\u0000${taskId ?? ''}`;++export function findToolCallArgs(+ messages: readonly TMessage[] | undefined,+ tasks: readonly Pick<BackgroundTaskSummary, 'messageId' | 'toolCallId' | 'stepId'>[],+): Map<string, ToolCallArgs> {+ const found = new Map<string, ToolCallArgs>();+ if (messages == null || tasks.length === 0) return found;+ const wanted = new Set(+ tasks.map((task) => toolCallKey(task.messageId, task.toolCallId, task.stepId)),+ );+ const ambiguous = new Set<string>();+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i];+ for (const part of message.content ?? []) {+ if (part?.type !== ContentTypes.TOOL_CALL) continue;+ const call = part[ContentTypes.TOOL_CALL] as+ | { id?: string; stepId?: string; args?: ToolCallArgs }+ | undefined;+ if (call?.id == null) continue;+ const keys = new Set([+ toolCallKey(message.messageId, call.id, call.stepId),+ toolCallKey(message.messageId, call.id),+ toolCallKey(undefined, call.id, call.stepId),+ toolCallKey(undefined, call.id),+ ]);+ for (const key of keys) {+ if (!wanted.has(key)) continue;+ if (found.has(key)) ambiguous.add(key);+ found.set(key, call.args);+ }+ }+ }+ for (const key of ambiguous) found.delete(key);+ return found;+}++export type ToolCallDescriber = (args: ToolCallArgs) => Pick<TaskRow, 'title' | 'detail'>;++const toolRow = (+ task: BackgroundTaskSummary,+ described: Pick<TaskRow, 'title' | 'detail'>,+): TaskRow => ({+ id: `tool:${task.taskId}`,+ kind: 'tool',+ name: task.toolName,+ taskId: task.taskId,+ ...described,+ status: task.status === 'running' && task.cancellationRequested ? 'stopping' : task.status,+ startedAt: time(task.startedAt),+ settledAt: time(task.settledAt),+});++const subagentRow = (child: ParentSubagentSummary, stopping: ReadonlySet<string>): TaskRow => {+ const status = subagentStatus(child.status);+ const running = status === 'running';+ const taskId = child.latestTaskId;+ return {+ id: `subagent:${subagentTaskKey(child.threadId, taskId)}`,+ kind: 'subagent',+ name: child.title,+ status: running && stopping.has(subagentTaskKey(child.threadId, taskId)) ? 'stopping' : status,+ startedAt: time(child.tasks.find((task) => task.taskId === taskId)?.createdAt),+ settledAt: running ? undefined : time(child.updatedAt),+ ...(running && taskId != null ? { subagent: { threadId: child.threadId, taskId } } : {}),+ };+};++const isActive = (row: TaskRow) => row.status === 'running' || row.status === 'stopping';++/**+ * One list across both background kinds: active rows first, then the most+ * recently started. Settled subagents older than the registry's retention are+ * dropped so a long conversation does not list its whole history. Apply the+ * same bound to cached tools after their terminal response stops polling.+ */+export function buildTaskRows({+ tools,+ subagents,+ stoppingThreads,+ now,+ describe,+ args,+}: {+ describe: ToolCallDescriber;+ args: ReadonlyMap<string, ToolCallArgs>;+ tools: readonly BackgroundTaskSummary[];+ subagents: readonly ParentSubagentSummary[];+ stoppingThreads: ReadonlySet<string>;+ now: number;+}): TaskRow[] {+ const rows = tools.map((task) =>+ toolRow(task, describe(args.get(toolCallKey(task.messageId, task.toolCallId, task.stepId)))),+ );+ for (const child of subagents) {+ const row = subagentRow(child, stoppingThreads);+ rows.push(row);+ }+ return rows+ .filter(+ (row) =>+ isActive(row) || row.settledAt == null || now - row.settledAt <= RECENT_SUBAGENT_WINDOW_MS,+ )+ .sort((left, right) => {+ const active = Number(isActive(right)) - Number(isActive(left));+ return active !== 0 ? active : (right.startedAt ?? 0) - (left.startedAt ?? 0);+ });+}++export const countActive = (rows: readonly TaskRow[]) => rows.filter(isActive).length;diff --git a/client/src/components/Chat/BackgroundTasks/useTasks.ts b/client/src/components/Chat/BackgroundTasks/useTasks.tsnew file mode 100644index 0000000000..575ed088e4--- /dev/null+++ b/client/src/components/Chat/BackgroundTasks/useTasks.ts@@ -0,0 +1,269 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import { v4 } from 'uuid';+import { useQuery, useQueries } from '@tanstack/react-query';+import { QueryKeys, dataService } from 'librechat-data-provider';+import type { TMessage, ParentSubagentSummary } from 'librechat-data-provider';+import type { TaskRow, ToolCallArgs } from './rows';+import {+ useBackgroundTasksQuery,+ useSubagentControlMutation,+ useCancelBackgroundTasksMutation,+} from '~/data-provider';+import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider';+import { buildTaskRows, countActive, findToolCallArgs, subagentTaskKey } from './rows';+import parseJsonField from '~/components/Chat/Messages/Content/Parts/parseJsonField';+import { getToolCallIntent } from '~/components/Chat/Messages/Content/Parts/intent';++const noThreads: ReadonlyMap<string, ParentSubagentSummary> = new Map();+const noRefresh = async () => undefined;++export type BackgroundTasksView = {+ rows: TaskRow[];+ activeCount: number;+ /** Whether the deployment lets users stop ordinary background tools. */+ toolsCancellable: boolean;+ isStopping: boolean;+ stopFailed: boolean;+ loadFailed: boolean;+ retry: () => Promise<void>;+ canStop: (row: TaskRow) => boolean;+ stop: (row: TaskRow) => Promise<void>;+ stopAll: () => Promise<void>;+};++const describeToolCall = (args: ToolCallArgs): Pick<TaskRow, 'title' | 'detail'> => {+ if (args == null) return {};+ const title = getToolCallIntent(args);+ const detail = parseJsonField(args, 'command') || parseJsonField(args, 'code');+ return {+ ...(title == null ? {} : { title }),+ ...(detail === '' ? {} : { detail }),+ };+};++/**+ * Joins ordinary background tools (process registry) with detached subagents+ * (durable index) for one conversation, and stops one or every running task.+ */+export default function useBackgroundTasks({+ conversationId,+ isSubmitting,+ now,+}: {+ conversationId: string;+ isSubmitting: boolean;+ now: number;+}): BackgroundTasksView {+ const parent = useParentSubagents();+ // The URL can advance before the host conversation context during navigation.+ const matchesConversation = parent.conversationId === conversationId;+ const byThreadId = matchesConversation ? parent.byThreadId : noThreads;+ const refresh = matchesConversation ? parent.refresh : noRefresh;+ const subagentsError = matchesConversation && parent.isError;+ const discoveryEnabled = matchesConversation && parent.discoveryEnabled;+ const { data, isError, refetch } = useBackgroundTasksQuery(+ conversationId,+ { enabled: discoveryEnabled },+ isSubmitting,+ );+ const { mutateAsync: cancelTools } = useCancelBackgroundTasksMutation();+ const { mutateAsync: controlSubagent } = useSubagentControlMutation();+ const [stoppingThreads, setStoppingThreads] = useState<ReadonlySet<string>>(() => new Set());+ const [isStopping, setIsStopping] = useState(false);+ const [stopFailed, setStopFailed] = useState(false);+ const [pendingControls, setPendingControls] = useState<+ Array<{+ threadId: string;+ taskId: string;+ invocationId: string;+ }>+ >([]);+ const controls = useQueries({+ queries: pendingControls.map((control) => ({+ queryKey: [QueryKeys.subagentThread, conversationId, control.threadId, control.taskId],+ queryFn: () =>+ dataService.getSubagentThread(conversationId, control.threadId, control.taskId),+ retry: false,+ refetchInterval: 2_000,+ select: (view: Awaited<ReturnType<typeof dataService.getSubagentThread>>) =>+ view.controlReceipts?.find((receipt) => receipt.invocationId === control.invocationId)+ ?.status,+ })),+ });+ // Receipt acceptance is not completion: a queued control can fail after POST returns.+ const controlStates = controls.map((result) => result.data).join(',');+ useEffect(() => {+ const statuses = controlStates.split(',');+ const finished = pendingControls.filter((control, index) => {+ const child = byThreadId.get(control.threadId);+ return (+ statuses[index] === 'failed' ||+ statuses[index] === 'rejected' ||+ statuses[index] === 'applied' ||+ child?.latestTaskId !== control.taskId ||+ (child.status !== 'running' && child.status !== 'dispatched')+ );+ });+ if (finished.length === 0) return;+ const failed = pendingControls.filter((_, index) =>+ ['failed', 'rejected'].includes(statuses[index]),+ );+ if (failed.length > 0) {+ setStopFailed(true);+ setStoppingThreads((current) => {+ const next = new Set(current);+ for (const control of failed)+ next.delete(subagentTaskKey(control.threadId, control.taskId));+ return next;+ });+ }+ setPendingControls((current) => current.filter((control) => !finished.includes(control)));+ }, [controlStates, pendingControls, byThreadId]);++ useEffect(() => {+ setStoppingThreads((current) => {+ const active = new Set(+ [...byThreadId.values()]+ .filter((child) => child.status === 'running' || child.status === 'dispatched')+ .map((child) => subagentTaskKey(child.threadId, child.latestTaskId)),+ );+ const settled = [...current].filter((key) => !active.has(key));+ if (settled.length === 0) return current;+ const remaining = new Set(current);+ for (const threadId of settled) remaining.delete(threadId);+ return remaining;+ });+ }, [byThreadId]);++ /** Observe existing message data without fetching. Structural sharing of the+ * selected record ignores unrelated streaming text but includes late restoration. */+ const selectArgs = useCallback(+ (messages: TMessage[]) => Object.fromEntries(findToolCallArgs(messages, data?.tasks ?? [])),+ [data?.tasks],+ );+ const { data: selectedArgs } = useQuery<TMessage[], unknown, Record<string, ToolCallArgs>>({+ queryKey: [QueryKeys.messages, conversationId],+ enabled: false,+ select: selectArgs,+ });+ const args = useMemo(() => new Map(Object.entries(selectedArgs ?? {})), [selectedArgs]);+ const retry = useCallback(async () => {+ await Promise.allSettled([+ refetch(),+ refresh(),+ ...controls.map((control) => control.refetch()),+ ]);+ }, [refetch, refresh, controls]);++ const rows = useMemo(+ () =>+ buildTaskRows({+ tools: data?.tasks ?? [],+ subagents: [...byThreadId.values()],+ stoppingThreads,+ now,+ args,+ describe: describeToolCall,+ }),+ [data?.tasks, byThreadId, stoppingThreads, now, args],+ );++ const toolsCancellable = data?.cancellable === true;+ const canStop = useCallback(+ (row: TaskRow) =>+ row.status === 'running' &&+ (row.subagent != null || (row.kind === 'tool' && toolsCancellable)),+ [toolsCancellable],+ );++ const stopRows = useCallback(+ async (targets: TaskRow[]) => {+ const toolIds = targets.flatMap((row) =>+ row.kind === 'tool' && row.taskId ? [row.taskId] : [],+ );+ const subagents = targets.flatMap((row) => (row.subagent == null ? [] : [row.subagent]));+ if (toolIds.length === 0 && subagents.length === 0) return;+ setIsStopping(true);+ setStopFailed(false);+ setStoppingThreads(+ (current) =>+ new Set([+ ...current,+ ...subagents.map((target) => subagentTaskKey(target.threadId, target.taskId)),+ ]),+ );+ const submittedAt = new Date().toISOString();+ const [toolFailed, subagentResults] = await Promise.all([+ toolIds.length > 0+ ? cancelTools({ conversationId, body: { taskIds: toolIds } })+ .then(({ results }) =>+ results.some(+ (result) =>+ !['requested', 'already_requested', 'settled'].includes(result.status),+ ),+ )+ .catch(() => true)+ : Promise.resolve(false),+ Promise.allSettled(+ subagents.map(async ({ threadId, taskId }) => {+ const invocationId = v4();+ const result = await controlSubagent({+ parentConversationId: conversationId,+ threadId,+ command: { taskId, invocationId, action: 'cancel' },+ submittedAt,+ });+ if (result.receipt.status === 'accepted') {+ setPendingControls((current) => [...current, { threadId, taskId, invocationId }]);+ }+ return result;+ }),+ ),+ ]);+ const failedThreads = subagents.flatMap(({ threadId, taskId }, index) => {+ const result = subagentResults[index];+ return result.status === 'rejected' ||+ (result.value.receipt.status !== 'accepted' && result.value.receipt.status !== 'applied')+ ? [subagentTaskKey(threadId, taskId)]+ : [];+ });+ if (failedThreads.length > 0) {+ setStoppingThreads((current) => {+ const remaining = new Set(current);+ for (const threadId of failedThreads) remaining.delete(threadId);+ return remaining;+ });+ }+ let failed = toolFailed || failedThreads.length > 0;+ if (subagents.length > 0) {+ try {+ await refresh();+ } catch {+ failed = true;+ }+ }+ if (failed) setStopFailed(true);+ setIsStopping(false);+ },+ [conversationId, cancelTools, controlSubagent, refresh],+ );++ const stop = useCallback(+ (row: TaskRow) => stopRows(canStop(row) ? [row] : []),+ [stopRows, canStop],+ );+ const stopAll = useCallback(() => stopRows(rows.filter(canStop)), [stopRows, rows, canStop]);++ return {+ rows,+ activeCount: countActive(rows),+ toolsCancellable,+ isStopping,+ stopFailed,+ loadFailed: isError || subagentsError || controls.some((control) => control.isError),+ retry,+ canStop,+ stop,+ stopAll,+ };+}diff --git a/client/src/components/Chat/Header.tsx b/client/src/components/Chat/Header.tsxindex fa09c8b187..1f1b9da3b2 100644--- a/client/src/components/Chat/Header.tsx+++ b/client/src/components/Chat/Header.tsx@@ -10,6 +10,7 @@ import {import { OpenSidebar, PresetsMenu, NewChat, HeaderMenu } from './Menus';import { TemporaryChat, TemporaryChatIndicator } from './TemporaryChat';import ModelSelector from './Menus/Endpoints/ModelSelector';+import { BackgroundTasksButton } from './BackgroundTasks';import { TraceButton, useTraceControl } from './Trace';import { useGetStartupConfig } from '~/data-provider';import ExportAndShareMenu from './ExportAndShareMenu';@@ -113,6 +114,13 @@ function Header({<div className={cn('flex flex-shrink-0 items-center gap-2', hiddenBehindNav)}>{hasAccessToTemporaryChat === true && <TemporaryChatIndicator />}{!isNewChat && <NewChat className="md:hidden" />}+ {!isNewChat && parentConversationId == null && (+ <BackgroundTasksButton+ key={routeConversationId}+ conversationId={routeConversationId}+ isSubmitting={isSubmitting}+ />+ )}<HeaderMenu startupConfig={startupConfig} trace={trace} className="md:hidden" /><div className="hidden items-center gap-2 md:flex">{trace.show && <TraceButton onClick={trace.open} />}diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsxindex 2d171b6202..a556ab7893 100644--- a/client/src/components/Chat/Presentation.test.tsx+++ b/client/src/components/Chat/Presentation.test.tsx@@ -2,6 +2,7 @@ import React from 'react';import { useSetAtom } from 'jotai';import { RecoilRoot, useSetRecoilState } from 'recoil';import { fireEvent, render, screen } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { TConversation } from 'librechat-data-provider';import type { Artifact } from '~/common';import { activeSubagentPanel } from '~/components/Chat/Subagents/state';@@ -9,6 +10,15 @@ import { ChatSurfaceHarness } from 'test/harness';import Presentation from './Presentation';import store from '~/store';+const renderPresentation = (element: React.ReactElement) => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(element, {+ wrapper: ({ children }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ ),+ });+};+const mockArtifactPanelLabel = 'Artifact panel loaded';const mockOpenArtifactLabel = 'Open Artifact';const mockChildPanelLabel = 'Child activity panel loaded';@@ -159,7 +169,7 @@ describe('Presentation Artifact loading', () => {presentationArtifactModuleEvaluations?: number;};- render(+ renderPresentation(<ChatSurfaceHarness><RecoilRoot><Presentation>@@ -179,7 +189,7 @@ describe('Presentation Artifact loading', () => {});it('loads the parent child index only for Agent conversations', () => {- render(+ renderPresentation(<ChatSurfaceHarness><RecoilRoot><Presentation>@@ -206,7 +216,7 @@ describe('Presentation Artifact loading', () => {});it('uses one panel slot and lets an opened artifact replace child activity', async () => {- render(+ renderPresentation(<ChatSurfaceHarness><RecoilRoot><Presentation>diff --git a/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsx b/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsxindex d722f4e432..58c5221b60 100644--- a/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsx+++ b/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsx@@ -1,10 +1,19 @@import React from 'react';-import { act, render } from '@testing-library/react';+import { QueryKeys } from 'librechat-data-provider';+import { act, render, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { ParentSubagentIndex, ParentSubagentSummary } from 'librechat-data-provider';import { ParentSubagentsProvider, useParentSubagents } from './ParentSubagentsProvider';const mockUseParentSubagentsQuery = jest.fn();+const renderProvider = (element: React.ReactElement, client = new QueryClient()) =>+ render(element, {+ wrapper: ({ children }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ ),+ });+jest.mock('~/data-provider', () => ({useParentSubagentsQuery: (...args: unknown[]) => mockUseParentSubagentsQuery(...args),}));@@ -52,7 +61,7 @@ describe('ParentSubagentsProvider', () => {return null;};- render(+ renderProvider(<ParentSubagentsProvider conversationId="parent-conversation" enabled><Probe /></ParentSubagentsProvider>,@@ -75,7 +84,7 @@ describe('ParentSubagentsProvider', () => {it('marks an active parent run for prompt discovery', () => {mockUseParentSubagentsQuery.mockReturnValue({ data: undefined, refetch: jest.fn() });- render(+ renderProvider(<ParentSubagentsProvider conversationId="parent-conversation" enabled isSubmitting><div /></ParentSubagentsProvider>,@@ -86,4 +95,104 @@ describe('ParentSubagentsProvider', () => {true,);});++ it('retains discovery on endpoint switches but resets for a different conversation', () => {+ mockUseParentSubagentsQuery.mockReturnValue({ data: undefined, refetch: jest.fn() });+ const { rerender } = renderProvider(+ <ParentSubagentsProvider conversationId="agent-chat" enabled>+ <div />+ </ParentSubagentsProvider>,+ );+ rerender(+ <ParentSubagentsProvider conversationId="agent-chat" enabled={false}>+ <div />+ </ParentSubagentsProvider>,+ );+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(+ 'agent-chat',+ { enabled: true },+ false,+ );+ rerender(+ <ParentSubagentsProvider conversationId="plain-chat" enabled={false}>+ <div />+ </ParentSubagentsProvider>,+ );+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(+ 'plain-chat',+ { enabled: false },+ false,+ );+ });++ it.each(['history', 'tools', 'subagents'])(+ 'restores discovery from cached %s after switching endpoints',+ (evidence) => {+ mockUseParentSubagentsQuery.mockReturnValue({ data: undefined, refetch: jest.fn() });+ const client = new QueryClient();+ if (evidence === 'history')+ client.setQueryData([QueryKeys.messages, 'restored'], [{ endpoint: 'agents' }]);+ if (evidence === 'tools')+ client.setQueryData([QueryKeys.backgroundTasks, 'restored'], { tasks: [{}] });+ if (evidence === 'subagents')+ client.setQueryData([QueryKeys.parentSubagents, 'restored'], { children: [eventChild] });+ renderProvider(+ <ParentSubagentsProvider conversationId="restored" enabled={false}>+ <div />+ </ParentSubagentsProvider>,+ client,+ );+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(+ 'restored',+ { enabled: true },+ false,+ );+ },+ );++ it('does not discover tasks for a new or genuinely non-agent conversation', () => {+ mockUseParentSubagentsQuery.mockReturnValue({ data: undefined, refetch: jest.fn() });+ const { rerender } = renderProvider(+ <ParentSubagentsProvider conversationId="plain" enabled={false}>+ <div />+ </ParentSubagentsProvider>,+ );+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(+ 'plain',+ { enabled: false },+ false,+ );+ rerender(+ <ParentSubagentsProvider conversationId="new" enabled>+ <div />+ </ParentSubagentsProvider>,+ );+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith('new', { enabled: false }, false);+ });++ it('starts discovery when agent history arrives after the initial render', async () => {+ mockUseParentSubagentsQuery.mockReturnValue({ data: undefined, refetch: jest.fn() });+ const client = new QueryClient();+ renderProvider(+ <ParentSubagentsProvider conversationId="restored" enabled={false}>+ <div />+ </ParentSubagentsProvider>,+ client,+ );+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(+ 'restored',+ { enabled: false },+ false,+ );+ await act(async () => {+ client.setQueryData([QueryKeys.messages, 'restored'], [{ endpoint: 'agents' }]);+ });+ await waitFor(() =>+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(+ 'restored',+ { enabled: true },+ false,+ ),+ );+ });});diff --git a/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsx b/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsxindex d04c75f252..4f7172aeef 100644--- a/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsx+++ b/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsx@@ -1,19 +1,32 @@-import { createContext, useCallback, useContext, useMemo } from 'react';-import type { ParentSubagentIndex, ParentSubagentSummary } from 'librechat-data-provider';+import { createContext, useCallback, useContext, useMemo, useState } from 'react';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { Constants, QueryKeys, EModelEndpoint } from 'librechat-data-provider';+import type {+ BackgroundTaskIndex,+ TMessage,+ ParentSubagentIndex,+ ParentSubagentSummary,+} from 'librechat-data-provider';import { useParentSubagentsQuery } from '~/data-provider';type ParentSubagentsContextValue = {+ conversationId: string;byMessageId: ReadonlyMap<string, ParentSubagentSummary[]>;byThreadId: ReadonlyMap<string, ParentSubagentSummary>;refresh: () => Promise<ParentSubagentIndex | undefined>;+ isError: boolean;+ discoveryEnabled: boolean;};const emptyMap = new Map<string, ParentSubagentSummary[]>();const emptyThreadMap = new Map<string, ParentSubagentSummary>();const defaultValue: ParentSubagentsContextValue = {+ conversationId: '',byMessageId: emptyMap,byThreadId: emptyThreadMap,refresh: async () => undefined,+ isError: false,+ discoveryEnabled: false,};const ParentSubagentsContext = createContext<ParentSubagentsContextValue>(defaultValue);@@ -29,7 +42,37 @@ export function ParentSubagentsProvider({isSubmitting?: boolean;children: React.ReactNode;}) {- const { data, refetch } = useParentSubagentsQuery(conversationId, { enabled }, isSubmitting);+ const queryClient = useQueryClient();+ // Observe already-loaded history without fetching it or rerendering on streamed text.+ const { data: hasAgentHistory = false } = useQuery<TMessage[], unknown, boolean>(+ [QueryKeys.messages, conversationId],+ {+ enabled: false,+ select: (messages) => messages.some((message) => message.endpoint === EModelEndpoint.agents),+ },+ );+ const hasCachedTasks =+ (queryClient.getQueryData<BackgroundTaskIndex>([QueryKeys.backgroundTasks, conversationId])+ ?.tasks.length ?? 0) > 0 ||+ (queryClient.getQueryData<ParentSubagentIndex>([QueryKeys.parentSubagents, conversationId])+ ?.children.length ?? 0) > 0;+ const evidence = enabled || hasAgentHistory || hasCachedTasks;+ const [discovery, setDiscovery] = useState({ conversationId, enabled: evidence });+ const observed = discovery.conversationId === conversationId && discovery.enabled;+ const discoveryEnabled =+ conversationId !== '' &&+ conversationId !== Constants.NEW_CONVO &&+ conversationId !== Constants.PENDING_CONVO &&+ (observed || evidence);+ // A model switch cannot revoke a conversation's task ownership. Reset only on navigation.+ if (discovery.conversationId !== conversationId || discovery.enabled !== discoveryEnabled) {+ setDiscovery({ conversationId, enabled: discoveryEnabled });+ }+ const { data, refetch, isError } = useParentSubagentsQuery(+ conversationId,+ { enabled: discoveryEnabled },+ isSubmitting,+ );const refresh = useCallback(async () => {const result = await refetch();return result.data;@@ -50,8 +93,8 @@ export function ParentSubagentsProvider({return updated === 0 ? left.threadId.localeCompare(right.threadId) : updated;});}- return { byMessageId, byThreadId, refresh };- }, [data, refresh]);+ return { conversationId, byMessageId, byThreadId, refresh, isError, discoveryEnabled };+ }, [conversationId, data, refresh, isError, discoveryEnabled]);return (<ParentSubagentsContext.Provider value={value}>{children}</ParentSubagentsContext.Provider>diff --git a/client/src/components/Chat/__tests__/Header.stacking.spec.tsx b/client/src/components/Chat/__tests__/Header.stacking.spec.tsxindex d573da116b..712f43ca7a 100644--- a/client/src/components/Chat/__tests__/Header.stacking.spec.tsx+++ b/client/src/components/Chat/__tests__/Header.stacking.spec.tsx@@ -1,15 +1,21 @@import React from 'react';import '@testing-library/jest-dom';-import { render } from '@testing-library/react';+import { render, screen } from '@testing-library/react';import Header from '../Header';+const mockEndpoint = { current: 'agents' };+jest.mock('react-router-dom', () => ({useParams: () => ({ conversationId: 'convo-1' }),}));-jest.mock('recoil', () => ({ useRecoilValue: () => false }));+jest.mock('recoil', () => ({+ useRecoilValue: (selector: string) =>+ selector === 'effectiveEndpoint' ? mockEndpoint.current : false,+}));jest.mock('librechat-data-provider', () => ({getConfigDefaults: () => ({ interface: {} }),Constants: { NEW_CONVO: 'new' },+ EModelEndpoint: { agents: 'agents' },PermissionTypes: { BOOKMARKS: 'bookmarks', MULTI_CONVO: 'multi_convo', TEMPORARY_CHAT: 'temp' },Permissions: { USE: 'use' },}));@@ -17,7 +23,11 @@ jest.mock('~/data-provider', () => ({ useGetStartupConfig: () => ({ data: undefijest.mock('~/hooks', () => ({ useHasAccess: () => false }));jest.mock('~/store', () => ({__esModule: true,- default: { sidebarExpanded: {}, isSubmittingFamily: () => ({}) },+ default: {+ sidebarExpanded: {},+ isSubmittingFamily: () => ({}),+ effectiveEndpointByIndex: () => 'effectiveEndpoint',+ },}));jest.mock('~/utils', () => ({cn: (...classes: Array<string | false | undefined>) => classes.filter(Boolean).join(' '),@@ -33,6 +43,9 @@ jest.mock('../TemporaryChat', () => ({TemporaryChatIndicator: () => null,}));jest.mock('../Trace', () => ({ useTraceControl: () => ({ show: false }) }));+jest.mock('../BackgroundTasks', () => ({+ BackgroundTasksButton: jest.fn(() => <div data-testid="conversation-tasks" />),+}));jest.mock('../Menus/Endpoints/ModelSelector', () => () => null);jest.mock('../ExportAndShareMenu', () => () => null);jest.mock('../SubagentThreadLink', () => () => null);@@ -40,9 +53,29 @@ jest.mock('../Menus/BookmarkMenu', () => () => null);jest.mock('../AddMultiConvo', () => () => null);describe('Header stacking', () => {+ const backgroundTasks = jest.requireMock('../BackgroundTasks').BackgroundTasksButton as jest.Mock;++ beforeEach(() => {+ backgroundTasks.mockClear();+ mockEndpoint.current = 'agents';+ });+test('keeps header controls above the z-10 composer approval review', () => {const { container } = render(<Header />);expect(container.firstElementChild).toHaveClass('absolute', 'top-0', 'z-20');+ expect(backgroundTasks).toHaveBeenCalled();+ });++ test('keeps conversation task controls mounted across endpoint switches', () => {+ const { rerender } = render(<Header />);+ mockEndpoint.current = 'openAI';+ rerender(<Header />);+ expect(screen.getByTestId('conversation-tasks')).toBeInTheDocument();+ });++ test('does not mount parent task controls on child threads', () => {+ render(<Header parentConversationId="parent" />);+ expect(backgroundTasks).not.toHaveBeenCalled();});});diff --git a/client/src/data-provider/BackgroundTasks/index.ts b/client/src/data-provider/BackgroundTasks/index.tsnew file mode 100644index 0000000000..3cf1ef310b--- /dev/null+++ b/client/src/data-provider/BackgroundTasks/index.ts@@ -0,0 +1 @@+export * from './queries';diff --git a/client/src/data-provider/BackgroundTasks/queries.polling.test.tsx b/client/src/data-provider/BackgroundTasks/queries.polling.test.tsxnew file mode 100644index 0000000000..50ef23a432--- /dev/null+++ b/client/src/data-provider/BackgroundTasks/queries.polling.test.tsx@@ -0,0 +1,121 @@+import React from 'react';+import { QueryKeys } from 'librechat-data-provider';+import { act, renderHook, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { BackgroundTaskIndex } from 'librechat-data-provider';+import { useBackgroundTasksQuery } from './queries';++const mockGetBackgroundTasks = jest.fn();++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getBackgroundTasks: (...args: unknown[]) => mockGetBackgroundTasks(...args),+ },+ };+});++const empty: BackgroundTaskIndex = {+ conversationId: 'convo-1',+ tasks: [],+ cancellable: true,+};++const setup = (submitting = false, enabled = true) => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const hook = renderHook(+ ({ isSubmitting }) => useBackgroundTasksQuery('convo-1', { enabled }, isSubmitting).data,+ { initialProps: { isSubmitting: submitting }, wrapper },+ );+ return { ...hook, client };+};++describe('background task discovery polling', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ mockGetBackgroundTasks.mockReset().mockResolvedValue(empty);+ });++ afterEach(() => jest.useRealTimers());++ it('does not fetch disabled conversations, including when their submission ends', async () => {+ const { rerender, client, unmount } = setup(true, false);+ rerender({ isSubmitting: false });+ await act(async () => jest.advanceTimersByTimeAsync(120_000));+ expect(mockGetBackgroundTasks).not.toHaveBeenCalled();+ unmount();+ client.clear();+ });++ it('refetches immediately at submit end and discovers tasks that appear afterward', async () => {+ mockGetBackgroundTasks.mockResolvedValueOnce(empty).mockResolvedValueOnce(empty);+ mockGetBackgroundTasks.mockResolvedValue({+ ...empty,+ tasks: [+ {+ taskId: 'late-task',+ toolName: 'bash_tool',+ toolCallId: 'call-1',+ status: 'running',+ cancellationRequested: false,+ startedAt: new Date().toISOString(),+ },+ ],+ });+ const { rerender, result, client, unmount } = setup(true);+ await act(async () => jest.advanceTimersByTimeAsync(0));+ expect(mockGetBackgroundTasks).toHaveBeenCalledTimes(1);+ await act(async () => jest.advanceTimersByTimeAsync(1_000));+ rerender({ isSubmitting: false });+ await act(async () => jest.advanceTimersByTimeAsync(0));+ expect(mockGetBackgroundTasks).toHaveBeenCalledTimes(2);+ await act(async () => jest.advanceTimersByTimeAsync(2_000));+ expect(mockGetBackgroundTasks).toHaveBeenCalledTimes(3);+ await waitFor(() =>+ expect(+ client.getQueryData<BackgroundTaskIndex>([QueryKeys.backgroundTasks, 'convo-1'])?.tasks[0]+ ?.taskId,+ ).toBe('late-task'),+ );+ await waitFor(() => expect(result.current?.tasks[0]?.taskId).toBe('late-task'));+ unmount();+ client.clear();+ });++ it('backs off to quiet discovery after the bounded fast discovery window', async () => {+ const { rerender, client, unmount } = setup(true);+ await act(async () => jest.advanceTimersByTimeAsync(0));+ rerender({ isSubmitting: false });+ await act(async () => jest.advanceTimersByTimeAsync(12_000));+ const calls = mockGetBackgroundTasks.mock.calls.length;+ expect(calls).toBeGreaterThan(1);+ await act(async () => jest.advanceTimersByTimeAsync(30_000));+ expect(mockGetBackgroundTasks).toHaveBeenCalledTimes(calls);+ await act(async () => jest.advanceTimersByTimeAsync(30_000));+ expect(mockGetBackgroundTasks).toHaveBeenCalledTimes(calls + 1);+ unmount();+ client.clear();+ });++ it('discovers server-started tasks without a browser submission', async () => {+ const { result, client, unmount } = setup();+ await act(async () => jest.advanceTimersByTimeAsync(0));+ mockGetBackgroundTasks.mockResolvedValue({+ ...empty,+ tasks: [{ taskId: 'server-task', toolName: 'bash_tool', status: 'running' }],+ });+ await act(async () => jest.advanceTimersByTimeAsync(60_000));+ await waitFor(() => expect(result.current?.tasks[0]?.taskId).toBe('server-task'));+ const calls = mockGetBackgroundTasks.mock.calls.length;+ await act(async () => jest.advanceTimersByTimeAsync(2_000));+ expect(mockGetBackgroundTasks).toHaveBeenCalledTimes(calls + 1);+ unmount();+ client.clear();+ });+});diff --git a/client/src/data-provider/BackgroundTasks/queries.ts b/client/src/data-provider/BackgroundTasks/queries.tsnew file mode 100644index 0000000000..69f771629d--- /dev/null+++ b/client/src/data-provider/BackgroundTasks/queries.ts@@ -0,0 +1,86 @@+import { useEffect, useRef, useState } from 'react';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { Constants, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';+import type {+ BackgroundTaskCancelResponse,+ BackgroundTaskCancelRequest,+ BackgroundTaskIndex,+} from 'librechat-data-provider';+import type { UseQueryOptions } from '@tanstack/react-query';++const RUNNING_REFRESH_MS = 2_000;+const SUBMITTING_REFRESH_MS = 5_000;+const POST_SUBMIT_DISCOVERY_MS = 10_000;+const QUIET_REFRESH_MS = 60_000;++/** Fast discovery around submissions, with a visible-tab fallback for server-started work. */+export const backgroundTasksRefetchInterval = (+ index: BackgroundTaskIndex | undefined,+ isSubmitting = false,+ discoveryDeadline = 0,+ now = Date.now(),+): number | false => {+ if (index?.tasks.some((task) => task.status === 'running') === true) {+ return RUNNING_REFRESH_MS;+ }+ if (now < discoveryDeadline) return RUNNING_REFRESH_MS;+ return isSubmitting ? SUBMITTING_REFRESH_MS : QUIET_REFRESH_MS;+};++export const useBackgroundTasksQuery = (+ conversationId: string,+ config?: UseQueryOptions<BackgroundTaskIndex>,+ isSubmitting = false,+) => {+ const previous = useRef({ conversationId, isSubmitting });+ const [discoveryDeadline, setDiscoveryDeadline] = useState(0);+ const query = useQuery<BackgroundTaskIndex>(+ [QueryKeys.backgroundTasks, conversationId],+ () => dataService.getBackgroundTasks(conversationId),+ {+ enabled:+ conversationId !== '' &&+ conversationId !== Constants.NEW_CONVO &&+ conversationId !== Constants.PENDING_CONVO,+ staleTime: 1_000,+ refetchOnWindowFocus: true,+ refetchInterval: (index) =>+ backgroundTasksRefetchInterval(index, isSubmitting, discoveryDeadline),+ refetchIntervalInBackground: false,+ ...config,+ },+ );++ const { refetch } = query;+ useEffect(() => {+ const last = previous.current;+ previous.current = { conversationId, isSubmitting };+ if (last.conversationId !== conversationId) {+ setDiscoveryDeadline(0);+ return;+ }+ if (last.isSubmitting && !isSubmitting && config?.enabled !== false) {+ setDiscoveryDeadline(Date.now() + POST_SUBMIT_DISCOVERY_MS);+ void refetch();+ }+ }, [conversationId, isSubmitting, refetch, config?.enabled]);++ return query;+};++export type CancelBackgroundTasksVariables = {+ conversationId: string;+ body: BackgroundTaskCancelRequest;+};++export const useCancelBackgroundTasksMutation = () => {+ const queryClient = useQueryClient();+ return useMutation<BackgroundTaskCancelResponse, Error, CancelBackgroundTasksVariables>(+ ({ conversationId, body }) => dataService.cancelBackgroundTasks(conversationId, body),+ {+ mutationKey: [MutationKeys.cancelBackgroundTasks],+ onSettled: (_data, _error, { conversationId }) =>+ queryClient.invalidateQueries([QueryKeys.backgroundTasks, conversationId]),+ },+ );+};diff --git a/client/src/data-provider/index.ts b/client/src/data-provider/index.tsindex ea2696ae8d..b554ae0de5 100644--- a/client/src/data-provider/index.ts+++ b/client/src/data-provider/index.ts@@ -13,6 +13,7 @@ export * from './Projects';/* Scheduled chats */export * from './Schedules';export * from './Subagents';+export * from './BackgroundTasks';export * from './Tools';export * from './Traces';export * from './connection';diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex a99faaf2dd..e6d28b9e67 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1,4 +1,17 @@{+ "com_ui_background_tasks": "Background tasks",+ "com_ui_background_tasks_cancel_disabled": "Stopping background tools is not enabled on this server",+ "com_ui_background_tasks_completed": "Completed",+ "com_ui_background_tasks_finished": "Finished",+ "com_ui_background_tasks_label": "Background tasks, {{0}} running",+ "com_ui_background_tasks_running": "Running",+ "com_ui_background_tasks_stop": "Stop task",+ "com_ui_background_tasks_stop_all": "Stop all running tasks",+ "com_ui_background_tasks_stop_available": "Stop available running tasks",+ "com_ui_background_tasks_stop_failed": "Could not stop some tasks. Try again.",+ "com_ui_background_tasks_load_failed": "Could not load all tasks. The list may be incomplete. Try again.",+ "com_ui_background_tasks_stopping": "Stopping…",+ "com_ui_background_tasks_subagent": "Subagent","com_ui_repository_instructions": "Repository instructions","com_ui_repository_instructions_prefer": "Prefer repository conventions","com_ui_repository_instructions_defer": "Prefer agent conventions",diff --git a/packages/api/src/agents/background.ts b/packages/api/src/agents/background.tsindex 22cab89ab9..c7de708268 100644--- a/packages/api/src/agents/background.ts+++ b/packages/api/src/agents/background.ts@@ -676,6 +676,7 @@ export interface BackgroundTask {completionPersistenceFailed?: boolean;createdAt: number;updatedAt: number;+ settledAt?: number;}interface TaskBucket {@@ -1387,6 +1388,7 @@ export class BackgroundTaskRegistryClass {const artifactChars = hasRetainedCapacity ? storedArtifact.chars : 0;const updated = this.update(userId, conversationId, taskId, {status: 'completed',+ settledAt: Date.now(),result: retainedContent,artifact,error: undefined,@@ -1560,6 +1562,7 @@ export class BackgroundTaskRegistryClass {const retainedError = hasRetainedCapacity ? storedError : undefined;const updated = this.update(userId, conversationId, taskId, {status: 'error',+ settledAt: Date.now(),error: retainedError,result: undefined,artifact: undefined,@@ -1593,6 +1596,7 @@ export class BackgroundTaskRegistryClass {const retainedError = hasRetainedCapacity ? storedError : undefined;const updated = this.update(userId, conversationId, taskId, {status: 'cancelled',+ settledAt: Date.now(),error: retainedError,result: undefined,artifact: undefined,@@ -1713,6 +1717,7 @@ export class BackgroundTaskRegistryClass {const retainedError = hasRetainedCapacity ? storedError : undefined;const updated = this.update(userId, conversationId, taskId, {status: 'error',+ settledAt: task.settledAt ?? Date.now(),error: retainedError,result: undefined,artifact: undefined,@@ -1787,7 +1792,8 @@ export class BackgroundTaskRegistryClass {}}-export const backgroundTaskRegistry = new BackgroundTaskRegistryClass();+export const backgroundTaskRegistry: BackgroundTaskRegistryClass =+ new BackgroundTaskRegistryClass();/** Content for the synthetic ToolMessage returned when a call is backgrounded. */export function buildBackgroundHandleContent(diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex b1a305fbfa..6b0cfc3a3c 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -82,6 +82,8 @@ export * from './activityLabels';export * from './activityPhases';export * from './subagentDelivery';export * from './view';+export * from './tasks';+export { backgroundTaskRegistry } from './background';export * from './workspace';export * from './reasoningLabels';export * from './refusal';diff --git a/packages/api/src/agents/tasks.spec.ts b/packages/api/src/agents/tasks.spec.tsnew file mode 100644index 0000000000..94de8f2cab--- /dev/null+++ b/packages/api/src/agents/tasks.spec.ts@@ -0,0 +1,194 @@+import type { Response } from 'express';+import type { ServerRequest } from '~/types';+import {+ createBackgroundTaskCancelHandler,+ createBackgroundTaskIndexHandler,+ createBackgroundTaskPolicyMiddleware,+} from './tasks';+import { BackgroundTaskRegistryClass } from './background';++const conversationId = 'convo-1';++const response = () => {+ const res = { status: jest.fn(), json: jest.fn() };+ res.status.mockReturnValue(res);+ return res as unknown as Response & { status: jest.Mock; json: jest.Mock };+};++const request = ({+ userId = 'user-1',+ cancellation = true,+ body,+}: {+ userId?: string;+ cancellation?: boolean;+ body?: unknown;+} = {}) =>+ ({+ user: { id: userId },+ params: { conversationId },+ body,+ config: {+ endpoints: { agents: { backgroundTasks: { ordinaryToolCancellation: cancellation } } },+ },+ }) as unknown as ServerRequest;++const createTask = (+ registry: BackgroundTaskRegistryClass,+ toolCallId: string,+ requestCancellation: () => boolean | void = jest.fn(),+) => {+ const created = registry.create({+ userId: 'user-1',+ conversationId,+ toolCallId,+ toolName: 'bash_tool',+ messageId: 'message-1',+ requestCancellation,+ });+ if ('atCapacity' in created) {+ throw new Error('unexpected capacity');+ }+ return created.task;+};++describe('background task routes', () => {+ it('loads effective policy without runtime workspace augmentation and fails closed', async () => {+ const req = request();+ const getAppConfig = jest.fn().mockResolvedValue(req.config);+ const next = jest.fn();+ const middleware = createBackgroundTaskPolicyMiddleware({ getAppConfig });+ await middleware(req, response(), next);+ expect(getAppConfig).toHaveBeenCalledWith(+ expect.objectContaining({+ userId: 'user-1',+ skipRuntimeAugmentation: true,+ failClosed: true,+ }),+ );+ expect(next).toHaveBeenCalledTimes(1);+ getAppConfig.mockRejectedValue(new Error('policy store unavailable'));+ const failed = response();+ await middleware(req, failed, next);+ expect(failed.status).toHaveBeenCalledWith(503);+ expect(next).toHaveBeenCalledTimes(1);+ });+ it('lists only the caller’s tasks without results', () => {+ const registry = new BackgroundTaskRegistryClass();+ const running = createTask(registry, 'call-1');+ const done = createTask(registry, 'call-2');+ registry.complete('user-1', conversationId, done.id, { content: 'secret output' });+ const handler = createBackgroundTaskIndexHandler({ registry });++ const res = response();+ handler(request(), res);+ const body = res.json.mock.calls[0][0];+ expect(res.status).toHaveBeenCalledWith(200);+ expect(body.cancellable).toBe(true);+ expect(body.tasks).toEqual([+ expect.objectContaining({+ taskId: running.id,+ toolName: 'bash_tool',+ toolCallId: 'call-1',+ messageId: 'message-1',+ status: 'running',+ cancellationRequested: false,+ }),+ expect.objectContaining({+ taskId: done.id,+ status: 'completed',+ settledAt: expect.any(String),+ }),+ ]);+ expect(body.tasks[0].settledAt).toBeUndefined();+ expect(body.tasks[1].settledAt).toBe(new Date(done.settledAt!).toISOString());+ const later = jest.spyOn(Date, 'now').mockReturnValue(done.settledAt! + 60_000);+ registry.markCompletionPersistenceFinished('user-1', conversationId, done.id);+ later.mockRestore();+ const afterPersistence = response();+ handler(request(), afterPersistence);+ expect(afterPersistence.json.mock.calls[0][0].tasks[1].settledAt).toBe(body.tasks[1].settledAt);+ expect(JSON.stringify(body)).not.toContain('secret output');++ const other = response();+ handler(request({ userId: 'user-2', cancellation: false }), other);+ expect(other.json).toHaveBeenCalledWith({ conversationId, tasks: [], cancellable: false });+ });++ it('cancels every running task when no ids are given', () => {+ const registry = new BackgroundTaskRegistryClass();+ const abortFirst = jest.fn();+ const abortSecond = jest.fn();+ const first = createTask(registry, 'call-1', abortFirst);+ const second = createTask(registry, 'call-2', abortSecond);+ const done = createTask(registry, 'call-3');+ registry.complete('user-1', conversationId, done.id, { content: 'ok' });+ const handler = createBackgroundTaskCancelHandler({ registry });++ const res = response();+ handler(request({ body: {} }), res);+ expect(res.json).toHaveBeenCalledWith({+ results: [+ { taskId: first.id, status: 'requested' },+ { taskId: second.id, status: 'requested' },+ ],+ });+ expect(abortFirst).toHaveBeenCalledTimes(1);+ expect(abortSecond).toHaveBeenCalledTimes(1);++ const again = response();+ handler(request({ body: { taskIds: [first.id, done.id, 'missing'] } }), again);+ expect(again.json).toHaveBeenCalledWith({+ results: [+ { taskId: first.id, status: 'already_requested' },+ { taskId: done.id, status: 'settled' },+ { taskId: 'missing', status: 'not_found' },+ ],+ });+ expect(abortFirst).toHaveBeenCalledTimes(1);+ });++ it('refuses cancellation when the deployment has not opted in', () => {+ const registry = new BackgroundTaskRegistryClass();+ const abort = jest.fn();+ createTask(registry, 'call-1', abort);+ const res = response();+ createBackgroundTaskCancelHandler({ registry })(request({ cancellation: false }), res);+ expect(res.status).toHaveBeenCalledWith(403);+ expect(abort).not.toHaveBeenCalled();+ });++ it('never reaches another user’s tasks', () => {+ const registry = new BackgroundTaskRegistryClass();+ const abort = jest.fn();+ const task = createTask(registry, 'call-1', abort);+ const res = response();+ createBackgroundTaskCancelHandler({ registry })(+ request({ userId: 'user-2', body: { taskIds: [task.id] } }),+ res,+ );+ expect(res.json).toHaveBeenCalledWith({ results: [{ taskId: task.id, status: 'not_found' }] });+ expect(abort).not.toHaveBeenCalled();+ });++ it('rejects malformed bodies without accidentally cancelling every task', () => {+ const registry = new BackgroundTaskRegistryClass();+ const abort = jest.fn();+ createTask(registry, 'call-1', abort);+ const handler = createBackgroundTaskCancelHandler({ registry });+ for (const body of [+ undefined,+ null,+ 'invalid',+ [],+ { taskIds: null },+ { taskIds: undefined },+ { taskIds: [1] },+ ]) {+ const res = response();+ handler(request({ body }), res);+ expect(res.status).toHaveBeenCalledWith(400);+ expect(abort).not.toHaveBeenCalled();+ }+ });+});diff --git a/packages/api/src/agents/tasks.ts b/packages/api/src/agents/tasks.tsnew file mode 100644index 0000000000..8f13e3d6d8--- /dev/null+++ b/packages/api/src/agents/tasks.ts@@ -0,0 +1,155 @@+import { EModelEndpoint } from 'librechat-data-provider';+import type {+ BackgroundTaskCancelResponse,+ BackgroundTaskSummary,+ BackgroundTaskIndex,+ TAgentsEndpoint,+} from 'librechat-data-provider';+import type { AppConfig } from '@librechat/data-schemas';+import type { Response, NextFunction } from 'express';+import type { BackgroundTask, BackgroundTaskRegistryClass } from './background';+import type { GetAppConfigOptions } from '~/app/service';+import type { ServerRequest } from '~/types';+import { getAppConfigOptionsFromUser } from '~/app/service';++/** The registry surface the user-facing task routes read and act on. */+export type BackgroundTaskRegistryView = Pick<+ BackgroundTaskRegistryClass,+ 'list' | 'requestCancellation'+>;++export interface BackgroundTaskRouteDependencies {+ registry: BackgroundTaskRegistryView;+}++/** Resolve effective cancellation policy without enumerating code environments. */+export function createBackgroundTaskPolicyMiddleware(deps: {+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig>;+}) {+ return async (req: ServerRequest, res: Response, next: NextFunction): Promise<void> => {+ try {+ req.config = await deps.getAppConfig({+ ...getAppConfigOptionsFromUser(req.user),+ skipRuntimeAugmentation: true,+ failClosed: true,+ });+ next();+ } catch {+ res.status(503).json({ error: 'Background task policy is temporarily unavailable' });+ }+ };+}++const MAX_CONVERSATION_ID_LENGTH = 256;+const MAX_CANCEL_TASK_IDS = 64;+const MAX_TASK_ID_LENGTH = 256;++const validConversationId = (value: string | undefined): value is string =>+ value != null && value.trim() !== '' && value.length <= MAX_CONVERSATION_ID_LENGTH;++const validTaskId = (value: unknown): value is string =>+ typeof value === 'string' && value.trim() !== '' && value.length <= MAX_TASK_ID_LENGTH;++/** User cancellation of ordinary tools shares the model tool's opt-in. */+export function ordinaryToolCancellationEnabled(config: TAgentsEndpoint | undefined): boolean {+ return config?.backgroundTasks?.ordinaryToolCancellation === true;+}++const agentsConfig = (req: ServerRequest): TAgentsEndpoint | undefined =>+ req.config?.endpoints?.[EModelEndpoint.agents] as TAgentsEndpoint | undefined;++/**+ * Projects a registry task for the client. Results, artifacts and errors stay+ * server-side, matching the model tool's metadata-only list path.+ */+export function toBackgroundTaskSummary(task: BackgroundTask): BackgroundTaskSummary {+ const settled = task.status !== 'running';+ return {+ taskId: task.id,+ toolName: task.toolName,+ toolCallId: task.toolCallId,+ ...(task.messageId == null ? {} : { messageId: task.messageId }),+ ...(task.stepId == null ? {} : { stepId: task.stepId }),+ status: task.status,+ cancellationRequested: task.cancellationRequestedAt != null,+ startedAt: new Date(task.createdAt).toISOString(),+ ...(settled && task.settledAt != null+ ? { settledAt: new Date(task.settledAt).toISOString() }+ : {}),+ };+}++/**+ * Lists the caller's background tool tasks for one conversation. The registry+ * is keyed by user and conversation, so another user's tasks are unreachable+ * without a database read; tasks owned by another replica are not visible.+ */+export function createBackgroundTaskIndexHandler(deps: BackgroundTaskRouteDependencies) {+ return (req: ServerRequest, res: Response): void => {+ const userId = req.user?.id;+ const { conversationId } = req.params as { conversationId?: string };+ if (!userId || !validConversationId(conversationId)) {+ res.status(404).json({ error: 'Conversation not found' });+ return;+ }+ const body: BackgroundTaskIndex = {+ conversationId,+ tasks: deps.registry.list(userId, conversationId).map(toBackgroundTaskSummary),+ cancellable: ordinaryToolCancellationEnabled(agentsConfig(req)),+ };+ res.status(200).json(body);+ };+}++/**+ * Requests cooperative cancellation of the caller's background tool tasks.+ * Without `taskIds` every running task in the conversation is targeted. Each+ * task reports the registry outcome; `unavailable` means the owning process+ * holds no cancellation handle for it.+ */+export function createBackgroundTaskCancelHandler(deps: BackgroundTaskRouteDependencies) {+ return (req: ServerRequest, res: Response): void => {+ const userId = req.user?.id;+ const { conversationId } = req.params as { conversationId?: string };+ if (!userId || !validConversationId(conversationId)) {+ res.status(404).json({ error: 'Conversation not found' });+ return;+ }+ if (!ordinaryToolCancellationEnabled(agentsConfig(req))) {+ res.status(403).json({ error: 'Background task cancellation is not enabled' });+ return;+ }++ const payload: unknown = req.body;+ if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {+ res.status(400).json({ error: 'Invalid background task cancellation request' });+ return;+ }+ const hasTaskIds = 'taskIds' in payload;+ const requested = hasTaskIds ? payload.taskIds : undefined;+ if (+ hasTaskIds &&+ (!Array.isArray(requested) ||+ requested.length > MAX_CANCEL_TASK_IDS ||+ !requested.every(validTaskId))+ ) {+ res.status(400).json({ error: 'Invalid background task cancellation request' });+ return;+ }++ const taskIds = hasTaskIds+ ? [...new Set(requested as string[])]+ : deps.registry+ .list(userId, conversationId)+ .filter((task) => task.status === 'running')+ .map((task) => task.id);++ const body: BackgroundTaskCancelResponse = {+ results: taskIds.map((taskId) => ({+ taskId,+ status: deps.registry.requestCancellation(userId, conversationId, taskId).status,+ })),+ };+ res.status(200).json(body);+ };+}diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 713389b186..bee6c01bad 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -141,6 +141,12 @@ export const subagentThread = (export const subagentControl = (parentConversationId: string, threadId: string) =>`${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents/${encodeURIComponent(threadId)}/control`;+export const backgroundTasks = (conversationId: string) =>+ `${conversationsRoot}/${encodeURIComponent(conversationId)}/background-tasks`;++export const backgroundTasksCancel = (conversationId: string) =>+ `${backgroundTasks(conversationId)}/cancel`;+export const genTitle = (conversationId: string) =>`${conversationsRoot}/gen_title/${encodeURIComponent(conversationId)}`;diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 4f158bfda2..47108dce2b 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1129,6 +1129,17 @@ export function controlSubagentTask(return request.post(endpoints.subagentControl(parentConversationId, threadId), body);}+export function getBackgroundTasks(conversationId: string): Promise<t.BackgroundTaskIndex> {+ return request.get(endpoints.backgroundTasks(conversationId));+}++export function cancelBackgroundTasks(+ conversationId: string,+ body: t.BackgroundTaskCancelRequest,+): Promise<t.BackgroundTaskCancelResponse> {+ return request.post(endpoints.backgroundTasksCancel(conversationId), body);+}+export function getPrompt(id: string): Promise<{ prompt: t.TPrompt }> {return request.get(endpoints.getPrompt(id));}diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 50b07a3ad2..92cb7a6cc8 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -44,6 +44,7 @@ export * from './types/graph';export * from './types/insights';export * from './types/traces';export * from './types/subagents';+export * from './types/background';export * from './types/queuedTurns';/* access permissions */export * from './accessPermissions';diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex d6e773d331..5e1e728807 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -98,6 +98,7 @@ export enum QueryKeys {schedule = 'schedule',parentSubagents = 'parentSubagents',subagentThread = 'subagentThread',+ backgroundTasks = 'backgroundTasks',codeEnvironments = 'codeEnvironments',agentQueuedTurns = 'agentQueuedTurns',/* Combined Pinned-section display order (favorites + pinned chats) */@@ -112,6 +113,7 @@ export const DynamicQueryKeys = {export enum MutationKeys {subagentControl = 'subagentControl',+ cancelBackgroundTasks = 'cancelBackgroundTasks',enqueueAgentQueuedTurn = 'enqueueAgentQueuedTurn',cancelAgentQueuedTurn = 'cancelAgentQueuedTurn',/** Whole-array favorites write, keyed so every hook instance's write isdiff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 9cd3f33cfa..f02fc87811 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -33,6 +33,7 @@ import type { Agent } from './types/agents';export * from './schemas';export * from './types/subagents';+export * from './types/background';export type TMessages = TMessage[];diff --git a/packages/data-provider/src/types/background.ts b/packages/data-provider/src/types/background.tsnew file mode 100644index 0000000000..1e50496b32--- /dev/null+++ b/packages/data-provider/src/types/background.ts@@ -0,0 +1,43 @@+export type BackgroundTaskStatus = 'running' | 'completed' | 'error' | 'cancelled';++/**+ * Public projection of one ordinary background tool task. Results, artifacts+ * and errors stay server-side; the list carries identity, status and timing.+ */+export type BackgroundTaskSummary = {+ taskId: string;+ toolName: string;+ toolCallId: string;+ messageId?: string;+ /** Distinguishes repeated provider call ids within one response. */+ stepId?: string;+ status: BackgroundTaskStatus;+ cancellationRequested: boolean;+ /** ISO-8601 dispatch time. */+ startedAt: string;+ /** ISO-8601 terminal time. Absent while the task is running. */+ settledAt?: string;+};++export type BackgroundTaskIndex = {+ conversationId: string;+ tasks: BackgroundTaskSummary[];+ /** Whether the deployment accepts user cancellation of ordinary tools. */+ cancellable: boolean;+};++export type BackgroundTaskCancelRequest = {+ /** Tasks to cancel; omitted cancels every running task in the conversation. */+ taskIds?: string[];+};++export type BackgroundTaskCancelOutcome =+ | 'not_found'+ | 'unavailable'+ | 'requested'+ | 'already_requested'+ | 'settled';++export type BackgroundTaskCancelResponse = {+ results: Array<{ taskId: string; status: BackgroundTaskCancelOutcome }>;+};diff --git a/packages/data-provider/src/types/index.ts b/packages/data-provider/src/types/index.tsindex 961463e2bd..7320b3a307 100644--- a/packages/data-provider/src/types/index.ts+++ b/packages/data-provider/src/types/index.ts@@ -1,4 +1,5 @@export * from './queries';export * from './mcpServers';export * from './subagents';+export * from './background';export * from './queuedTurns';