diff --git a/.github/workflows/codegraph-select.yml b/.github/workflows/codegraph-select.yml index e74a86e270..d76d673a8a 100644 --- a/.github/workflows/codegraph-select.yml +++ b/.github/workflows/codegraph-select.yml @@ -59,7 +59,7 @@ jobs: RESP=$(curl -sS --fail-with-body -m 45 -H "Authorization: Bearer $TOKEN" \ -H 'content-type: application/json' --data-binary @body.json "$URL/v1/select"); RC=$? if [ "$RC" -ne 0 ] || [ -z "$RESP" ] || ! echo "$RESP" | jq -e .selected >/dev/null 2>&1; then - note "_codegraph unavailable (curl exit $RC: ${RESP:0:120}); skipped — full CI runs as always_" + note "_codegraph unavailable (curl exit $RC: ${RESP:0:120}); skipped, full CI runs as always_" exit 0 fi diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.js index 34bab04619..1d76042381 100644 --- a/api/server/controllers/agents/__tests__/callbacks.spec.js +++ b/api/server/controllers/agents/__tests__/callbacks.spec.js @@ -8,6 +8,7 @@ jest.mock('nanoid', () => ({ jest.mock('@librechat/api', () => ({ sendEvent: jest.fn(), writeAttachmentEvent: jest.fn(), + createOwnedToolEndHandler: jest.fn((callback) => ({ handle: callback })), GenerationJobManager: { emitChunk: jest.fn(), }, @@ -468,6 +469,73 @@ describe('createToolEndCallback', () => { artifactPromises = []; }); + it('preserves separate owners for final search artifacts with repeated tool-call IDs', async () => { + const toolEndCallback = createToolEndCallback({ req, res, artifactPromises }); + for (const agentId of ['agent-a', 'agent-b']) { + await toolEndCallback( + { + output: { + tool_call_id: 'call_0', + artifact: { + [Tools.web_search]: { + turn: 0, + organic: [{ link: `https://example.com/${agentId}` }], + }, + }, + }, + }, + { run_id: 'run456', thread_id: 'thread789', agent_id: agentId }, + ); + } + const results = await Promise.all(artifactPromises); + expect( + results.map((attachment) => ({ + owner: attachment.agentId, + link: attachment[Tools.web_search].organic[0].link, + })), + ).toEqual([ + { owner: 'agent-a', link: 'https://example.com/agent-a' }, + { owner: 'agent-b', link: 'https://example.com/agent-b' }, + ]); + }); + + it.each(['createToolEndCallback', 'createResponsesToolEndCallback'])( + '%s preserves memory payloads and their execution owner', + async (factoryName) => { + const toolEndCallback = require('../callbacks')[factoryName]({ req, res, artifactPromises }); + await toolEndCallback( + { + output: { + tool_call_id: 'call_0', + artifact: { + [Tools.memory]: { + key: 'project', + type: 'update', + value: 'owned', + }, + }, + }, + }, + { + run_id: 'run456', + thread_id: 'thread789', + agent_id: 'outer-agent', + executingAgentId: 'agent-a', + stepId: 'step-memory-1', + }, + ); + + const [attachment] = await Promise.all(artifactPromises); + expect(attachment).toMatchObject({ + type: Tools.memory, + toolCallId: 'call_0', + agentId: 'agent-a', + stepId: 'step-memory-1', + [Tools.memory]: { key: 'project', type: 'update', value: 'owned' }, + }); + }, + ); + describe('ui_resources artifact handling', () => { it('should process ui_resources artifact and return attachment when headers not sent', async () => { const toolEndCallback = createToolEndCallback({ req, res, artifactPromises }); diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js index 90fdabe516..8c8960b2d5 100644 --- a/api/server/controllers/agents/__tests__/openai.spec.js +++ b/api/server/controllers/agents/__tests__/openai.spec.js @@ -194,6 +194,9 @@ jest.mock('@librechat/api', () => ({ * export or the call throws before the assertions run. */ stripActivityLabelParts: jest.fn((payload) => payload), writeSSE: jest.fn(), + createOwnedToolEndHandler: jest.fn( + (...args) => new (require('@librechat/agents').ToolEndHandler)(...args), + ), createRun: jest.fn().mockResolvedValue({ processStream: mockProcessStream, }), diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js index 584b4c8e56..5ea0d8628a 100644 --- a/api/server/controllers/agents/__tests__/responses.unit.spec.js +++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js @@ -203,6 +203,9 @@ jest.mock('@librechat/api', () => ({ * before SDK formatting; the mock must expose it like any other used * export or the call throws before the assertions run. */ stripActivityLabelParts: jest.fn((payload) => payload), + createOwnedToolEndHandler: jest.fn( + (...args) => new (require('@librechat/agents').ToolEndHandler)(...args), + ), collectReachableAgents: (roots) => { const agents = []; const pending = [...roots]; diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.js index c97a196aad..89db7e4509 100644 --- a/api/server/controllers/agents/callbacks.js +++ b/api/server/controllers/agents/callbacks.js @@ -13,7 +13,6 @@ const { const { GraphEvents, GraphNodeKeys, - ToolEndHandler, createContentAggregator, summarizeEvent, } = require('@librechat/agents'); @@ -23,6 +22,7 @@ const { GenerationJobManager, writeAttachmentEvent, createToolExecuteHandler, + createOwnedToolEndHandler, createBackgroundCodeResultHandler: createCodeHarvestHandler, HOST_FILE_AUTHORING_ARTIFACT_KEY, isCodeSessionToolName, @@ -42,6 +42,15 @@ function isCodeArtifactToolOutput(output) { return isCodeSessionToolName(output.name) || isHostFileAuthoringArtifact(output.artifact); } +function getAttachmentOwnership(metadata) { + const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id; + const stepId = metadata?.stepId; + return { + ...(typeof agentId === 'string' && agentId.length > 0 ? { agentId } : {}), + ...(typeof stepId === 'string' && stepId.length > 0 ? { stepId } : {}), + }; +} + function addStatefulWorkspaceChange(attachment, artifact, executionProfile) { if (!attachment || executionProfile !== 'stateful' || !isHostFileAuthoringArtifact(artifact)) { return attachment; @@ -506,7 +515,7 @@ function getDefaultHandlers({ collectedThoughtSignatures, emitTokenUsage, ), - [GraphEvents.TOOL_END]: new ToolEndHandler(toolEndCallback, logger), + [GraphEvents.TOOL_END]: createOwnedToolEndHandler(toolEndCallback, logger), [GraphEvents.ON_RUN_STEP]: { /** * Handle ON_RUN_STEP event. @@ -785,6 +794,23 @@ function getDefaultHandlers({ handlers[GraphEvents.ON_SUMMARIZE_COMPLETE] = { handle: async (_event, data) => { aggregateContent({ event: GraphEvents.ON_SUMMARIZE_COMPLETE, data }); + /** + * Stamped onto the aggregated part for the same reason as + * `runStepStatus` above: an errored round keeps whatever deltas it + * already streamed, and the SDK's aggregator ignores a complete event + * that carries no `summary`, so nothing records the failure. Without + * this the flag exists only on the live client message and a reload + * re-renders the truncated text under "Conversation summarized". + * Resolved through `stepMap` only, so a missing step degrades to the + * old behavior rather than marking an unrelated part. + */ + if (data?.error && contentParts) { + const index = stepMap?.get(data?.id)?.index; + const part = typeof index === 'number' ? contentParts[index] : undefined; + if (part?.type === ContentTypes.SUMMARY) { + part.failed = true; + } + } await emitForJob({ event: GraphEvents.ON_SUMMARIZE_COMPLETE, data, @@ -987,6 +1013,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo (async () => { const attachment = { type: Tools.web_search, + ...getAttachmentOwnership(metadata), messageId: metadata.run_id, toolCallId: output.tool_call_id, conversationId: metadata.thread_id, @@ -1009,6 +1036,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo (async () => { const attachment = { type: Tools.memory, + ...getAttachmentOwnership(metadata), messageId: metadata.run_id, toolCallId: output.tool_call_id, conversationId: metadata.thread_id, @@ -1350,6 +1378,7 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises }) const attachment = { type: Tools.web_search, toolCallId: output.tool_call_id, + ...getAttachmentOwnership(metadata), [Tools.web_search]: { ...output.artifact[Tools.web_search] }, }; // For Responses API, always emit attachment during streaming @@ -1364,6 +1393,26 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises }) ); } + if (output.artifact[Tools.memory]) { + artifactPromises.push( + (async () => { + const attachment = { + type: Tools.memory, + toolCallId: output.tool_call_id, + ...getAttachmentOwnership(metadata), + [Tools.memory]: output.artifact[Tools.memory], + }; + if (res.headersSent && !res.writableEnded) { + writeResponsesAttachment(res, tracker, attachment, metadata); + } + return attachment; + })().catch((error) => { + logger.error('Error processing memory artifact content:', error); + return null; + }), + ); + } + if (output.artifact.content) { /** @type {FormattedContent[]} */ const content = output.artifact.content; diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js index b57cce7493..de275905ad 100644 --- a/api/server/controllers/agents/openai.js +++ b/api/server/controllers/agents/openai.js @@ -1,6 +1,6 @@ const { nanoid } = require('nanoid'); const { logger } = require('@librechat/data-schemas'); -const { Callback, ToolEndHandler, formatAgentMessages } = require('@librechat/agents'); +const { Callback, formatAgentMessages } = require('@librechat/agents'); const { EModelEndpoint, ResourceType, @@ -56,6 +56,7 @@ const { getUserFacingProviderError, getRemoteAgentPermissions, createToolExecuteHandler, + createOwnedToolEndHandler, buildNonStreamingResponse, createOpenAIStreamTracker, resolveAgentScopedSkillIds, @@ -1001,7 +1002,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { }, on_run_step_completed: createHandler(), // Use proper ToolEndHandler for processing artifacts (images, file citations, code output) - on_tool_end: new ToolEndHandler(toolEndCallback, logger), + on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger), on_chain_stream: createHandler(), on_chain_end: createHandler(), on_agent_update: createHandler(), diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js index 4903abf569..c3632f89c6 100644 --- a/api/server/controllers/agents/responses.js +++ b/api/server/controllers/agents/responses.js @@ -1,7 +1,7 @@ const { nanoid } = require('nanoid'); const { v4: uuidv4 } = require('uuid'); const { logger } = require('@librechat/data-schemas'); -const { Callback, ToolEndHandler, formatAgentMessages } = require('@librechat/agents'); +const { Callback, formatAgentMessages } = require('@librechat/agents'); const { EModelEndpoint, ResourceType, @@ -53,6 +53,7 @@ const { getSafeErrorMetadata, getUserFacingProviderError, createToolExecuteHandler, + createOwnedToolEndHandler, resolveRecursionLimit, getRemoteAgentPermissions, resolveAgentScopedSkillIds, @@ -1155,7 +1156,7 @@ const executeResponse = async (envelope, { req, res }) => { } }, }, - on_tool_end: new ToolEndHandler(toolEndCallback, logger), + on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger), on_run_step_completed: { handle: () => {} }, on_chain_stream: { handle: () => {} }, on_chain_end: { handle: () => {} }, @@ -1368,7 +1369,7 @@ const executeResponse = async (envelope, { req, res }) => { } }, }, - on_tool_end: new ToolEndHandler(toolEndCallback, logger), + on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger), on_run_step_completed: { handle: () => {} }, on_chain_stream: { handle: () => {} }, on_chain_end: { handle: () => {} }, diff --git a/api/server/routes/agents/__tests__/responses.spec.js b/api/server/routes/agents/__tests__/responses.spec.js index 4d83219b84..cddeaf95b7 100644 --- a/api/server/routes/agents/__tests__/responses.spec.js +++ b/api/server/routes/agents/__tests__/responses.spec.js @@ -4,6 +4,9 @@ * Tests the /v1/responses endpoint against the Open Responses specification * compliance tests. Uses real Anthropic API for LLM calls. * + * Run with: + * NODE_OPTIONS=--experimental-vm-modules RUN_RESPONSES_LIVE_TESTS=1 npx jest responses.spec --runInBand + * * @see https://openresponses.org/specification * @see https://github.com/openresponses/openresponses/blob/main/src/lib/compliance-tests.ts */ @@ -19,11 +22,10 @@ const originalEnv = { process.env.CREDS_KEY = '0123456789abcdef0123456789abcdef'; process.env.CREDS_IV = '0123456789abcdef'; -/** Skip tests if ANTHROPIC_API_KEY is not available */ -const SKIP_INTEGRATION_TESTS = !process.env.ANTHROPIC_API_KEY; -if (SKIP_INTEGRATION_TESTS) { - console.warn('ANTHROPIC_API_KEY not found - skipping integration tests'); -} +const shouldRunLive = + process.env.RUN_RESPONSES_LIVE_TESTS === '1' && + process.env.ANTHROPIC_API_KEY != null && + process.env.ANTHROPIC_API_KEY !== ''; jest.mock('meilisearch', () => ({ MeiliSearch: jest.fn().mockImplementation(() => ({ @@ -69,9 +71,13 @@ jest.mock('~/app/clients/tools', () => ({ jest.mock('~/config', () => ({ createMCPServersRegistry: jest.fn(), + getMCPServersRegistry: jest.fn().mockReturnValue({ + ensureConfigServers: jest.fn().mockResolvedValue({}), + }), createMCPManager: jest.fn().mockResolvedValue({ getAppToolFunctions: jest.fn().mockResolvedValue({}), }), + getMCPManager: jest.fn().mockReturnValue({}), })); const express = require('express'); @@ -369,9 +375,9 @@ async function createThinkingAgent(overrides = {}) { }); } -const describeWithApiKey = SKIP_INTEGRATION_TESTS ? describe.skip : describe; +const describeIfLive = shouldRunLive ? describe : describe.skip; -describeWithApiKey('Open Responses API Integration Tests', () => { +describeIfLive('Open Responses API Integration Tests', () => { // Increase timeout for real API calls jest.setTimeout(120000); diff --git a/api/server/services/Tools/search.js b/api/server/services/Tools/search.js index c6e031e9ee..e0ded1268b 100644 --- a/api/server/services/Tools/search.js +++ b/api/server/services/Tools/search.js @@ -34,6 +34,8 @@ function createOnSearchResults(res, streamId = null, jobCreatedAt) { sourceMap: new Map(), searchResultData: undefined, toolCallId: undefined, + agentId: undefined, + stepId: undefined, attachmentName: undefined, messageId: undefined, conversationId: undefined, @@ -83,6 +85,8 @@ function createOnSearchResults(res, streamId = null, jobCreatedAt) { } context.toolCallId = runnableConfig.toolCall.id; + context.agentId = runnableConfig.metadata.agent_id ?? runnableConfig.metadata.agentId; + context.stepId = runnableConfig.toolCall?.stepId; context.messageId = runnableConfig.metadata.run_id; context.conversationId = runnableConfig.metadata.thread_id; context.attachmentName = `${runnableConfig.toolCall.name}_${context.toolCallId}_${nanoid()}`; @@ -132,6 +136,8 @@ function buildAttachment(context) { return { messageId: context.messageId, toolCallId: context.toolCallId, + agentId: context.agentId, + stepId: context.stepId, conversationId: context.conversationId, name: context.attachmentName, type: Tools.web_search, diff --git a/api/server/services/Tools/search.spec.js b/api/server/services/Tools/search.spec.js index 8925d84062..adb864ab7b 100644 --- a/api/server/services/Tools/search.spec.js +++ b/api/server/services/Tools/search.spec.js @@ -28,6 +28,7 @@ describe('createOnSearchResults', () => { toolCall: { id: 'tool-call-1', name: 'web_search', + stepId: 'step-search-1', turn: 0, }, }; @@ -53,6 +54,7 @@ describe('createOnSearchResults', () => { data: expect.objectContaining({ messageId: 'response-1', toolCallId: 'tool-call-1', + stepId: 'step-search-1', conversationId: 'conversation-1', }), }, @@ -60,4 +62,35 @@ describe('createOnSearchResults', () => { ]); } }); + + it('keeps repeated search calls owned by their handoff agent through highlights', () => { + const snapshots = []; + const res = { + headersSent: true, + write: (event) => snapshots.push(JSON.parse(event.split('\ndata: ')[1])), + }; + for (const agentId of ['agent-a', 'agent-b']) { + const callbacks = createOnSearchResults(res); + callbacks.onSearchResults( + { + success: true, + data: { organic: [{ link: `https://example.com/${agentId}` }], topStories: [] }, + }, + { + metadata: { agent_id: agentId, run_id: 'response-1', thread_id: 'conversation-1' }, + toolCall: { id: 'call_0', name: 'web_search', turn: 0 }, + }, + ); + callbacks.onGetHighlights(`https://example.com/${agentId}`); + } + + expect(snapshots.map(({ agentId }) => agentId)).toEqual([ + 'agent-a', + 'agent-a', + 'agent-b', + 'agent-b', + ]); + expect(snapshots[1].web_search.organic[0].processed).toBe(true); + expect(snapshots[3].web_search.organic[0].processed).toBe(true); + }); }); diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx index c0bceec1b8..7647e99bea 100644 --- a/client/src/components/Chat/ChatView.tsx +++ b/client/src/components/Chat/ChatView.tsx @@ -17,6 +17,7 @@ import { import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers'; import ConversationStarters from './Input/ConversationStarters'; import { useGetMessagesByConvoId } from '~/data-provider'; +import { AskAnswerHostProvider } from './ask/state'; import MessagesView from './Messages/MessagesView'; import Presentation from './Presentation'; import ChatForm from './Input/ChatForm'; @@ -41,6 +42,7 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje const localize = useLocalize(); const rootSubmission = useRecoilValue(store.submissionByIndex(index)); const isSubmitting = useRecoilValue(store.isSubmittingFamily(index)); + const saveDrafts = useRecoilValue(store.saveDrafts); const centerFormOnLanding = useRecoilValue(store.centerFormOnLanding); const methods = useForm({ @@ -126,58 +128,65 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje const isSubagentThreadReadOnly = activeSubagentThread != null; return ( - - - - -
-

{pageHeading}

-
- <> -
- {content} + + + + + +
+

{pageHeading}

+
+ <>
- {isLandingPage && } - {isSubagentThreadReadOnly ? ( -
- {localize('com_ui_subagent_thread_read_only')} -
- ) : ( - - )} - {!isLandingPage &&
} + {content} + {/* Named + opaque so a view transition (the ask_user_question + popover ⇄ chat-card morph) paints the whole composer band + over the travelling card instead of letting it show + through below the composer. The background matches the + page, so normal rendering is unchanged. */} +
+ {isLandingPage && } + {isSubagentThreadReadOnly ? ( +
+ {localize('com_ui_subagent_thread_read_only')} +
+ ) : ( + + )} + {!isLandingPage &&
} +
-
- {isLandingPage &&
} - -
- - - - + {isLandingPage &&
} + +
+
+
+
+
+ ); } diff --git a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx index 66c73e2654..1c967d48d0 100644 --- a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx +++ b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx @@ -1,12 +1,12 @@ import { memo, useEffect, useRef } from 'react'; import { useWatch } from 'react-hook-form'; -import { Button } from '@librechat/client'; -import { Check, ChevronDown, CornerDownLeft, TriangleAlert, X } from 'lucide-react'; +import { Button, TooltipAnchor } from '@librechat/client'; +import { ChevronDown, CornerDownLeft, TriangleAlert } from 'lucide-react'; import AskUserQuestions from '~/components/Chat/Messages/Content/AskUserQuestions'; import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode'; +import AskOptions from '~/components/Chat/ask/options'; import { useChatFormContext } from '~/Providers'; import { useLocalize } from '~/hooks'; -import { cn } from '~/utils'; /** * Composer popover for a live `ask_user_question` pause. Single-select rows @@ -16,10 +16,10 @@ import { cn } from '~/utils'; * Submit confirms — * folding in any free-form text typed in the composer, exactly like Enter * would. The footer hint is a button that focuses the composer — the - * free-form answer box. Collapse (chevron) hides the popover but keeps - * answer mode live via the chat card; × dismisses it entirely. Pure - * rendering off {@link useAskAnswerMode}; disappears the moment an answer - * submits from any surface, and locks while one is in flight. + * free-form answer box. The chevron moves the question to the chat card and + * releases the composer (the card's chevron moves it back). Pure rendering + * off {@link useAskAnswerMode}; disappears the moment an answer submits from + * any surface, and locks while one is in flight. */ function AskUserQuestionPopoverContent({ conversationId, @@ -43,7 +43,7 @@ function AskUserQuestionPopoverContent({ function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType }) { const localize = useLocalize(); - const { liveAsk, collapse, dismiss } = ask; + const { liveAsk, collapse } = ask; const questions = liveAsk?.questions; if (liveAsk == null || questions == null || questions.length === 0) { return null; @@ -59,24 +59,21 @@ function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType -
- - -
+ +