AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(chat): deep research with one researcher per subject (#16171)
Hazem Adel97c181f2c886
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.mdindex 82231fff95d..9984e53c695 100644--- a/brain/knowledge/flows-execution/chat.md+++ b/brain/knowledge/flows-execution/chat.md@@ -57,6 +57,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **Read-only checks don't belong in `BUILD_ONLY_TOOL_NAMES`.** `ap_validate_flow` was in it, so "check that this solution fits together" never saw the tool. The agent inspected flows by hand instead and misread a Call Flow `flowId` (an externalId) as a mismatch with the flow's id. It now stays visible in discovery, like `ap_flow_structure`.- **A dynamic property only runs with a saved schema.** The engine processes a `DYNAMIC` prop's sub-fields (JSON parse, numbers, arrays) only from `propertySettings[prop].schema`, which the builder saves when it resolves the prop. Chat tools used to save `propertySettings: {}`, so an advanced-mode Call Flow payload reached the subflow as one string and a live run saved empty fields. `mcpUtils.resolveDynamicPropertySettings` now resolves and saves it on build, add and update.- **Focused goals run as task sub-agents.** `ap_run_task` (`task-subagent-tools.ts`) runs a second `runAgentTurn` with a fresh context and the main's tools, minus anything that talks to the user, nests, tests, publishes or flips flow status. The prompt is `task-subagent-prompt.md`. Tasks start in the build phase with their own `ap_set_phase`: any tool whose closure holds run state must be rebuilt per task, because reusing the main's copy flipped the main's phase. A task must end with `updateTaskStatus`. If it's cut off it continues (up to 2 times), and if it forgets to report it gets one forced report step, so `failed` is rare and the main retries it. Histories live in `agent_task`, so `taskId` resumes the same sub-agent. Approvals inside a task carry `taskTitle` (via `AsyncLocalStorage`). Flat-billed calls come back as `billedToolCalls`, and `toModelOutput` keeps the card data out of the main's context. Delegation happens only when it buys something: multi-flow solutions build in dependency waves, one task per flow; single flows stay with the main.+- **Research goes through `ap_deep_research`, not prompt rules.** Prompt rules alone got research delegated in 3 of 8 runs, because the model reaches for the quick `ap_web_search`. A dedicated tool whose name matches the intent fixed it. It runs one task per subject under progress ids `toolCallId:index`, and the web expands it into one row per subject. Its timeline (statuses, searches, page reads) streams into the right-side task panel (`task-panel.tsx`), which opens on its own on the first search.- **Capability notes are built where `discoveryOnly` is not known, so a prompt can promise tools the worker has stripped.** `getAgentConfig` composes the system prompt in the api, while `discoveryOnly` rides on the job data; before Aug 2026 it never crossed that boundary. Meanwhile the worker strips image tools, email tools and the agent tools on such a run, so the notes claimed all three. Two of the three had been wrong since long before anyone noticed, because each note computed its own availability term. The flag now travels with the config request and the three notes read one shared `actingRun = !dryRun && !discoveryOnly`. Whenever a tool group is gated on a run mode in the worker, the note that advertises it has to be gated on the same term, in one place.- **Tool output can't be trusted to waive a charge.** A user's own MCP server or `ap_run_code` controls its output's top-level keys, and they reach the persisted part unchanged. Chat billing only honours `billedAtCost` from `ap_web_search` and `ap_generate_image`; a new built-in tool that bills at cost must be added to `TOOLS_THAT_BILL_AT_COST` in `chatBilling`.- **Credits are checked after every step, not just before the turn.** `runAgentTurn` asks the API (`agentHasCredits`) after each tool step, sending what the turn has used so far (`chatBilling.creditsForTurn`, the same rule end-of-turn billing uses), and stops once the remaining balance no longer covers it. Flat credits are only charged when the turn ends, so without that pending count the balance never moves mid-turn. The check fails open if the RPC errors.diff --git a/bun.lock b/bun.lockindex 6994b83862f..0d5bdaa41e8 100644--- a/bun.lock+++ b/bun.lock@@ -167,7 +167,7 @@},"packages/core/shared": {"name": "@activepieces/shared",- "version": "0.201.2",+ "version": "0.201.3","dependencies": {"@activepieces/core-execution": "workspace:*","@activepieces/core-formula": "workspace:*",diff --git a/packages/core/execution/src/lib/workers/agent-events.ts b/packages/core/execution/src/lib/workers/agent-events.tsindex bc1746da513..fc55ad7332f 100644--- a/packages/core/execution/src/lib/workers/agent-events.ts+++ b/packages/core/execution/src/lib/workers/agent-events.ts@@ -93,7 +93,15 @@ export type BuildPlanEvent = {updatedAt: string}-export type SubagentTimelineEntry = { kind: 'status', text: string, failed?: boolean }+export type SubagentLink = {+ url: string+ title?: string+}++export type SubagentTimelineEntry =+ | { kind: 'status', text: string, failed?: boolean }+ | { kind: 'search', query: string, results: SubagentLink[] }+ | { kind: 'read', url: string, title?: string }export type SubagentActivity = {taskId?: string@@ -110,6 +118,11 @@ export type SubagentActivity = {durationMs?: number}+export const subagentProgressId = {+ forSubject: ({ toolCallId, index }: { toolCallId: string, index: number }): string => `${toolCallId}:${index}`,+ baseOf: (progressId: string): string => progressId.split(':')[0],+}+export type SubagentProgressEvent = {toolCallId: stringdata: SubagentActivitydiff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex 51138b7f32f..74df801e327 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.201.2",+ "version": "0.201.3","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/ee/agent/tool-skills.ts b/packages/core/shared/src/lib/ee/agent/tool-skills.tsindex ebdf22aa1b0..714d39f909b 100644--- a/packages/core/shared/src/lib/ee/agent/tool-skills.ts+++ b/packages/core/shared/src/lib/ee/agent/tool-skills.ts@@ -187,7 +187,7 @@ const AGENT_SKILLS: readonly AgentSkill[] = [loadWhen: 'before searching the web, reading a web page, scraping a site, generating an image or sending an email',guideTopic: 'web_research',entersBuildPhase: false,- toolNames: ['ap_web_search', 'ap_fetch_url', 'ap_scrape_url', 'ap_generate_image', 'ap_send_email'],+ toolNames: ['ap_web_search', 'ap_fetch_url', 'ap_scrape_url', 'ap_deep_research', 'ap_generate_image', 'ap_send_email'],},{name: 'interaction',diff --git a/packages/core/shared/test/ee/agent-tool-skills.test.ts b/packages/core/shared/test/ee/agent-tool-skills.test.tsindex 0836b1327f8..e9d62677a8e 100644--- a/packages/core/shared/test/ee/agent-tool-skills.test.ts+++ b/packages/core/shared/test/ee/agent-tool-skills.test.ts@@ -67,6 +67,10 @@ describe('agentToolSkills', () => {expect(CORE_TOOL_NAMES.CHAT).toContain('ap_run_task')})+ it('ships deep research with the web research guide, so its schema arrives with the guide', () => {+ expect(agentToolSkills.findSkill({ name: 'web_and_media' })?.toolNames).toContain('ap_deep_research')+ })+it('renders a sorted one-line catalog', () => {const catalog = agentToolSkills.renderToolCatalog({ tools: [{ name: 'b_tool', description: 'Does b. More text.' }, { name: 'a_tool' }] })expect(catalog).toBe('- a_tool — \n- b_tool — Does b.')diff --git a/packages/server/api/src/app/ee/agent/chat-tool-billing.ts b/packages/server/api/src/app/ee/agent/chat-tool-billing.tsindex ed9d2944bbd..e734543b9cf 100644--- a/packages/server/api/src/app/ee/agent/chat-tool-billing.ts+++ b/packages/server/api/src/app/ee/agent/chat-tool-billing.ts@@ -14,7 +14,7 @@ function latestTurnToolCalls({ messages }: { messages: PersistedAgentMessage[] }const turn = lastUserIndex === -1 ? messages : messages.slice(lastUserIndex + 1)return turn.flatMap((message) => message.parts.flatMap((part) =>part.type === PersistedAgentPartType.TOOL_CALL && part.status === PersistedToolCallStatus.COMPLETED- ? [{ toolName: part.toolName, output: part.output }, ...(part.toolName === TASK_TOOL_NAME ? taskToolCalls(part.output) : [])]+ ? [{ toolName: part.toolName, output: part.output }, ...(SUB_AGENT_TOOLS.includes(part.toolName) ? taskToolCalls(part.output) : [])]: [],))}@@ -106,4 +106,4 @@ type ChargeForLatestTurnParams = {log: FastifyBaseLogger}-const TASK_TOOL_NAME = 'ap_run_task'+const SUB_AGENT_TOOLS = ['ap_run_task', 'ap_deep_research']diff --git a/packages/server/api/src/app/ee/agent/prompt/agent-prompt.ts b/packages/server/api/src/app/ee/agent/prompt/agent-prompt.tsindex e02ce5665bf..3a4833eb271 100644--- a/packages/server/api/src/app/ee/agent/prompt/agent-prompt.ts+++ b/packages/server/api/src/app/ee/agent/prompt/agent-prompt.ts@@ -23,6 +23,7 @@ const GUIDES: Record<string, string> = Object.fromEntries(const TASK_TEMPLATE = loadPromptTemplate('task-subagent-prompt.md')const SUBAGENTS_NOTE = loadPromptTemplate('chat-subagents-note.md').trim()+const RESEARCH_NOTE = loadPromptTemplate('chat-research-note.md').trim()function sanitizeProjectName(name: string): string {return name.replace(/[^a-zA-Z0-9 \-_.]/g, '').slice(0, 64)@@ -108,6 +109,7 @@ export const agentPrompt = {buildTaskSystemPrompt,guides: GUIDES,subagentsNote: SUBAGENTS_NOTE,+ researchNote: RESEARCH_NOTE,projectDisplayName,sources: {...PROMPT_TEMPLATES,diff --git a/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.ts b/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.tsindex 65331083e56..f7759cb83a1 100644--- a/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.ts+++ b/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.ts@@ -36,6 +36,7 @@ function buildRunNotes({ source, currentDate, searchAvailable, fetchAvailable, s})+ (isChat && agentsAvailable ? AGENTS_NOTE : '')+ (isChat && tasksAvailable ? `\n\n${agentPrompt.subagentsNote}` : '')+ + (isChat && tasksAvailable && searchAvailable && readsTheWeb ? `\n\n${agentPrompt.researchNote}` : '')+ (isChat && tasksAvailable && !isNil(tasks) && tasks.length > 0 ? buildTasksNote(tasks) : '')+ (isChat && !isNil(connections) ? buildConnectionInventoryNote(connections) : '')+ (isChat ? buildMemoryNote(memory) : '')diff --git a/packages/server/api/src/assets/prompts/chat-research-note.md b/packages/server/api/src/assets/prompts/chat-research-note.mdnew file mode 100644index 00000000000..92a84b2b113--- /dev/null+++ b/packages/server/api/src/assets/prompts/chat-research-note.md@@ -0,0 +1,2 @@+## Research in depth+When the answer needs facts read from real pages (pricing, plans, reviews, complaints, competitors, docs), call `ap_deep_research` with one subject per thing to compare. It runs a researcher per subject in parallel and returns sourced briefs. Compare them and do the final step yourself (the recommendation, the image, the build). A quick fact that one search answers you look up yourself.diff --git a/packages/server/api/src/assets/prompts/chat-system-prompt.md b/packages/server/api/src/assets/prompts/chat-system-prompt.mdindex c12177fdca3..78f5ab7db2b 100644--- a/packages/server/api/src/assets/prompts/chat-system-prompt.md+++ b/packages/server/api/src/assets/prompts/chat-system-prompt.md@@ -27,7 +27,7 @@ A sharp, friendly operator who loves this work: warm, confident, genuinely excit### Tool UX: thinking status vs. tool titlesThe thinking status and the tool's pill label are shown together, so they must never say the same thing.- **Thinking status** (`ap_update_thinking_status`): one warm, personal sentence about the goal ("I'll put it all together for you"), never the "-ing" form and never a tool, app or action name. Send one before every new unit of work, including the first tool of a turn, in the same step as that work's tool calls. A retry or continuation of the same goal gets none; rewording a goal you already stated is repetition. `ap_load_skill`, `ap_get_tool_schema` and `ap_set_build_plan` are silent and need none.-- **Reads in parallel, writes one by one:** independent read-only lookups share one status and go out together in a single step. Anything that writes, changes state or needs approval gets its own status and its own step.+- **Reads in parallel, writes one by one:** independent read-only lookups share one status and go out together in a single step. Anything that writes, changes state or needs approval gets its own status and its own step. Search results are only snippets: when the answer needs facts read from the pages themselves (pricing, plans, reviews, complaints, API docs) and `ap_deep_research` is available, use it instead of searching yourself.- **Pill labels on every call except the thinking status:** `title` (2-4 words), `activeTitle` (present continuous, while it runs), `doneTitle` (same label, past tense). Under 40 characters, specific to the user's thing ("Digging through your Gmail" → "Dug through your Gmail"), never generic or jargon. For `ap_execute_action` and `ap_generate_image` the `activeTitle` labels the loading card, so make it specific. Through `ap_lazy_tool`, put the labels on that call.</persona>diff --git a/packages/server/api/src/assets/prompts/task-subagent-prompt.md b/packages/server/api/src/assets/prompts/task-subagent-prompt.mdindex aae7e6556de..47cae30909c 100644--- a/packages/server/api/src/assets/prompts/task-subagent-prompt.md+++ b/packages/server/api/src/assets/prompts/task-subagent-prompt.md@@ -16,6 +16,7 @@ Projects you can reach:- Every step costs the same whether it does a lot or a little. Send independent calls together in one step, and never spend a step on a call that does no work.- You cannot ask the user anything. Risky actions still show the user an approval card, and you wait for it like the assistant would. If you need something only the user can give (a connection, a choice you cannot infer, a missing permission), stop and finish as blocked, saying exactly what you need.- When the user cancels an approval, that is their answer, not a block. Do not try that action again. Finish as done with what you did, and say the user cancelled it.+- For research, never stop at search snippets: open the pages that hold the facts (`ap_fetch_url`, or `ap_scrape_url` for pages that need a browser), search again when something is missing, and put the source links in your summary.- If the brief turns out to be several separate goals, do the first and say so in your summary.## Finishingdiff --git a/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.ts b/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.tsindex 11671d01f49..7a1d2097907 100644--- a/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.ts+++ b/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.ts@@ -78,6 +78,14 @@ describe('what each surface is told it can do', () => {expect(notesFor(AgentRunSource.AGENT)).not.toContain('Saved agents')})+ it('only points the chat at deep research when it can search the web', () => {+ const withSearch = agentSurfaceNotes.buildRunNotes({ source: AgentRunSource.CHAT, currentDate: 'Tuesday, August 18, 2026', ...EVERYTHING_AVAILABLE, userEmail: '[email protected]', memory: { instructions: '', memories: [] } })+ const withoutSearch = agentSurfaceNotes.buildRunNotes({ source: AgentRunSource.CHAT, currentDate: 'Tuesday, August 18, 2026', ...EVERYTHING_AVAILABLE, searchAvailable: false, userEmail: '[email protected]', memory: { instructions: '', memories: [] } })++ expect(withSearch).toContain('ap_deep_research')+ expect(withoutSearch).not.toContain('ap_deep_research')+ })+it('tells a chat run about everything it has', () => {const notes = notesFor(AgentRunSource.CHAT)diff --git a/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.ts b/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.tsindex 362457049de..69557395cca 100644--- a/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.ts+++ b/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.ts@@ -80,6 +80,20 @@ describe('chatToolBilling.countBillableToolCallsInLatestTurn', () => {expect(chatToolBilling.countBillableToolCallsInLatestTurn({ messages })).toBe(2)})+ it('bills the paid calls every researcher made inside deep research', () => {+ const researchPart: PersistedAgentPart = {+ type: PersistedAgentPartType.TOOL_CALL,+ toolCallId: 'research-1',+ toolName: 'ap_deep_research',+ input: {},+ status: PersistedToolCallStatus.COMPLETED,+ output: { tasks: [], billedToolCalls: [{ toolName: 'ap_scrape_url', output: {} }, { toolName: 'ap_scrape_url', output: {} }, { toolName: 'ap_fetch_url', output: {} }] },+ }+ const messages = [user('compare them'), assistant([researchPart])]++ expect(chatToolBilling.countBillableToolCallsInLatestTurn({ messages })).toBe(2)+ })+it('never bills inner calls reported by a tool that is not a task', () => {const connectedPart: PersistedAgentPart = {type: PersistedAgentPartType.TOOL_CALL,diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.tsindex 89f8c66d99f..5d9e6f5976e 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts@@ -266,7 +266,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForgerun: (stepMcpToolSet) => {const baseTools = { ...allTools, ...agentWorkerTools.wrapToolsWithTaint({ tools: stepMcpToolSet, taintState }) }const taskTools = createTaskSubagentTools({- tools: baseTools, guides: config.guides, models: turnModels, tier: config.tier,+ tools: baseTools, guides: config.guides, models: turnModels, researchModels: isNil(fastTurnModel) ? turnModels : [fastTurnModel], tier: config.tier,taskPrompt: config.taskSystemPrompt, creditsLeftFor, eventEmitter, abortSignal: abortController.signal, log,beginTask: (input) => ctx.apiClient.beginAgentTask({ platformId, conversationId, ...input }),finishTask: (input) => ctx.apiClient.finishAgentTask({ platformId, conversationId, ...input }),diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.tsindex 54e0dfa44cf..13788c66a38 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts@@ -1,10 +1,11 @@-import { isNil, isObject, omit, tryCatch } from '@activepieces/core-utils'-import { AGENT_SURFACE_TOOLS, AgentPhase, BeginAgentTaskResponse, chatBilling, FinishAgentTaskRequest, PersistedAgentPart, PersistedAgentPartType, PersistedToolCallStatus, SkillSurface, SubagentActivity, SubagentTaskArtifact, SubagentTimelineEntry, TASK_COMPLETION_TOOL_NAME } from '@activepieces/shared'+import { isNil, isObject, omit, parseToJsonIfPossible, spreadIfDefined, tryCatch } from '@activepieces/core-utils'+import { AGENT_SURFACE_TOOLS, AgentPhase, BeginAgentTaskResponse, chatBilling, FinishAgentTaskRequest, PersistedAgentPart, PersistedAgentPartType, PersistedToolCallStatus, SkillSurface, SubagentActivity, SubagentLink, subagentProgressId, SubagentTaskArtifact, SubagentTimelineEntry, TASK_COMPLETION_TOOL_NAME } from '@activepieces/shared'import { hasToolCall, isLoopFinished, ModelMessage, tool, ToolSet } from 'ai'+import pLimit from 'p-limit'import { z } from 'zod'import { AgentTurnResult, runAgentTurn, RunAgentTurnParams } from '../run-agent-turn'import { taskContext } from './task-context'-import { AgentEventEmitter } from './tool-primitives'+import { AgentEventEmitter, extractResultText } from './tool-primitives'export function createTaskSubagentTools({ tools, taskPrompt, ...rest }: Omit<TaskDeps, 'workerTools' | 'taskPrompt'> & {tools: ToolSet@@ -18,6 +19,7 @@ export function createTaskSubagentTools({ tools, taskPrompt, ...rest }: Omit<TastaskPrompt,workerTools: Object.fromEntries(Object.entries(tools).filter(([name]) => !NOT_FOR_TASKS.includes(name))),}+ const searchAvailable = Object.hasOwn(tools, WEB_SEARCH_TOOL)return {[TASK_TOOL_NAME]: tool({description: 'Hand one self-contained goal to a focused sub-agent with its own fresh context and the same tools you have (read, search, build, update, execute; risky actions still ask the user for approval). Use it when it buys something: independent goals that can run in parallel (several calls in one step run at once), or noisy preparation with a short answer (going through many records or runs, investigating a failure). Build flows yourself, even several at once, and make small edits yourself. It cannot ask the user anything: when it needs something only the user can give it finishes as blocked and says what; ask the user for it in your own words, then pass their answer back. Pass taskId to continue a task you started earlier in this conversation (after a block, or for a follow-up on what it built).',@@ -25,17 +27,36 @@ export function createTaskSubagentTools({ tools, taskPrompt, ...rest }: Omit<TastoModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify(omit(output, ['activity', 'billedToolCalls'])) }),execute: async ({ title, brief, taskId }, { toolCallId }) => runTask({ deps, title, brief, taskId, progressId: toolCallId }),}),+ ...(searchAvailable ? {+ [RESEARCH_TOOL_NAME]: tool({+ description: 'Research one or more subjects in depth on the live web. One sub-agent per subject runs in parallel: it searches, reads the actual pages and returns a short sourced brief, and the user watches the research live. Use it whenever the answer needs facts from real pages, such as comparing tools or vendors, pricing and plans, reviews and complaints, competitors, or API docs. Prefer it over several ap_web_search calls. Use ap_web_search only for one quick fact. Compare the briefs and do the final step yourself (the recommendation, the image, the build).',+ inputSchema: researchInput,+ toModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify({ tasks: output.tasks.map((task: TaskRunOutput) => omit(task, ['activity', 'billedToolCalls'])) }) }),+ execute: async ({ question, subjects, context }, { toolCallId }) => {+ const researchSlot = pLimit(RESEARCHERS_AT_ONCE)+ const tasks = await Promise.all(subjects.map((subject, index) => researchSlot(() => runTask({+ deps,+ title: subject,+ brief: [question, `Subject: ${subject}`, ...(isNil(context) ? [] : [context])].join('\n\n'),+ progressId: subagentProgressId.forSubject({ toolCallId, index }),+ kind: 'research',+ }))))+ return { tasks, billedToolCalls: tasks.flatMap((task) => task.billedToolCalls ?? []) }+ },+ }),+ } : {}),}}-async function runTask({ deps, title, brief, taskId, progressId }: {+async function runTask({ deps, title, brief, taskId, progressId, kind = 'task' }: {deps: TaskDepstitle: stringbrief: stringtaskId?: stringprogressId: string+ kind?: TaskKind}): Promise<TaskRunOutput> {- const { workerTools, guides, models, tier, taskPrompt, creditsLeftFor, beginTask, finishTask, eventEmitter, abortSignal, log } = deps+ const { tier, taskPrompt, creditsLeftFor, beginTask, finishTask, eventEmitter, abortSignal, log } = depsif (abortSignal.aborted) {return { status: 'failed', summary: 'Stopped before it started.' }}@@ -50,12 +71,13 @@ async function runTask({ deps, title, brief, taskId, progressId }: {const priorMessages = begun.messages.filter(isModelMessage)const messages: ModelMessage[] = [...priorMessages, { role: 'user', content: brief }]const phaseState: { phase: AgentPhase } = { phase: 'build' }+ const profile = TASK_PROFILES[kind](deps)const taskTools = {- ...workerTools,+ ...profile.tools,...finishTool(finish),}const turnParams: RunAgentTurnParams = {- models,+ models: profile.models,systemPrompt: taskPrompt,messages,tools: taskTools,@@ -66,7 +88,7 @@ async function runTask({ deps, title, brief, taskId, progressId }: {log,creditsLeft: creditsLeftFor(progressId),stopWhen: [isLoopFinished(), hasToolCall(TASK_COMPLETION_TOOL_NAME)],- skills: { surface: TASK_SKILL_SURFACE, guides },+ ...spreadIfDefined('skills', profile.skills),sinks: {drainStream: async (result) => {await result.consumeStream()@@ -221,11 +243,11 @@ function fallbackResult(turn: AgentTurnResult): TaskResult {function runningActivity({ title, uiParts, startedAt }: { title: string, uiParts: PersistedAgentPart[], startedAt: Date }): SubagentActivity {const timeline = timelineFrom(uiParts)- const statuses = timeline.flatMap((entry) => entry.kind === 'status' ? [entry.text] : [])+ const latest = timeline.at(-1)return {title,status: 'running',- statusLine: statuses[statuses.length - 1],+ statusLine: isNil(latest) ? undefined : timelineLine(latest),timeline,stepCount: uiParts.filter((part) => part.type === PersistedAgentPartType.TOOL_CALL).length,pieces: piecesFrom(uiParts),@@ -244,20 +266,103 @@ function finalActivity({ title, turn, result, startedAt }: { title: string, turn}}+function researchTools(workerTools: ToolSet): ToolSet {+ return Object.fromEntries(Object.entries(workerTools)+ .filter(([name]) => RESEARCH_TOOLS.includes(name))+ .map(([name, researchTool]) => [name, PAGE_READ_TOOLS.includes(name) ? withPageBudget(researchTool) : researchTool]))+}++function withPageBudget(pageTool: ToolSet[string]): ToolSet[string] {+ const execute = pageTool.execute+ if (isNil(execute)) {+ return pageTool+ }+ return { ...pageTool, execute: async (input, options) => capPageText(await execute(input, options)) }+}++function capPageText(result: unknown): unknown {+ if (!isObject(result)) {+ return result+ }+ return Object.fromEntries(Object.entries(result).map(([key, value]) => {+ const isLongPageText = PAGE_TEXT_KEYS.includes(key) && typeof value === 'string' && value.length > RESEARCH_PAGE_CHARS+ return isLongPageText ? [key, `${value.slice(0, RESEARCH_PAGE_CHARS)}\n…[page cut at ${RESEARCH_PAGE_CHARS} characters]`] : [key, value]+ }))+}+function isTitledToolCall(part: PersistedAgentPart): part is Extract<PersistedAgentPart, { type: PersistedAgentPartType.TOOL_CALL }> & { title: string } {return part.type === PersistedAgentPartType.TOOL_CALL && !isNil(part.title) && part.title.trim().length > 0}+function timelineLine(entry: SubagentTimelineEntry): string {+ switch (entry.kind) {+ case 'status':+ return entry.text+ case 'search':+ return entry.query+ case 'read':+ return entry.title ?? entry.url+ }+}+function timelineFrom(parts: PersistedAgentPart[]): SubagentTimelineEntry[] {- return parts.flatMap((part): SubagentTimelineEntry[] => {- if (isTitledToolCall(part)) {- return [{ kind: 'status', text: part.title.trim(), failed: part.status === PersistedToolCallStatus.ERROR }]+ const entries = parts.flatMap((part): SubagentTimelineEntry[] => {+ if (part.type === PersistedAgentPartType.THINKING_STATUS) {+ const text = part.text.trim()+ return text.length > 0 ? [{ kind: 'status', text }] : []}- if (part.type !== PersistedAgentPartType.THINKING_STATUS) {+ if (part.type !== PersistedAgentPartType.TOOL_CALL || !isObject(part.input)) {return []}- const text = part.text.trim()- return text.length > 0 ? [{ kind: 'status', text }] : []+ const query = part.input['query']+ if (part.toolName === WEB_SEARCH_TOOL && typeof query === 'string') {+ return [{ kind: 'search', query, results: searchResults(part.output) }]+ }+ const url = part.input['url']+ const pageWasRead = PAGE_READ_TOOLS.includes(part.toolName) && typeof url === 'string' && part.status === PersistedToolCallStatus.COMPLETED && returnedPage(part.output)+ if (pageWasRead) {+ return [{ kind: 'read', url }]+ }+ return isTitledToolCall(part) ? [{ kind: 'status', text: part.title.trim(), failed: part.status === PersistedToolCallStatus.ERROR }] : []+ })+ const titles = new Map(entries.flatMap((entry) => entry.kind === 'search' ? entry.results : []).map((link) => [link.url, link.title]))+ return entries.map((entry) => {+ const title = entry.kind === 'read' ? titles.get(entry.url) : undefined+ return isNil(title) ? entry : { ...entry, title }+ })+}++function unwrapLargeResponse(value: unknown): unknown {+ if (isNil(value)) {+ return value+ }+ const text = extractResultText(value)+ if (!text.startsWith(LARGE_RESPONSE_MARKER)) {+ return value+ }+ return parseToJsonIfPossible(text.slice(text.indexOf('\n\n') + 2))+}++function returnedPage(output: unknown): boolean {+ if (isNil(output)) {+ return false+ }+ const parsed = parseToJsonIfPossible(output)+ const hasPageText = isObject(parsed) && (typeof parsed['content'] === 'string' || typeof parsed['markdown'] === 'string')+ return hasPageText || extractResultText(parsed).startsWith(LARGE_RESPONSE_MARKER)+}++function searchResults(output: unknown): SubagentLink[] {+ const parsed = unwrapLargeResponse(parseToJsonIfPossible(output))+ if (!isObject(parsed) || !Array.isArray(parsed['results'])) {+ return []+ }+ return parsed['results'].flatMap((result): SubagentLink[] => {+ if (!isObject(result) || typeof result['url'] !== 'string' || result['url'].length === 0) {+ return []+ }+ const title = typeof result['title'] === 'string' && result['title'].length > 0 ? result['title'] : undefined+ return [{ url: result['url'], ...(isNil(title) ? {} : { title }) }]})}@@ -301,6 +406,12 @@ const taskInput = z.object({taskId: z.string().optional().describe('Continue a task from earlier in this conversation instead of starting a new one'),})+const researchInput = z.object({+ question: z.string().min(1).describe('What to find out, with the details that matter (team size, budget, region, what to compare)'),+ subjects: z.array(z.string().min(1)).min(1).describe('One entry per thing to research, e.g. ["Asana", "ClickUp", "Monday.com"]. Each gets its own sub-agent.'),+ context: z.string().optional().describe('Anything else the researchers should know'),+})+const taskResult = z.object({status: z.enum(['done', 'blocked', 'failed']),summary: z.string().describe('A few plain sentences: what you did and what the main assistant should tell the user'),@@ -315,15 +426,29 @@ const STATUS_BY_RESULT: Record<TaskResult['status'], FinishAgentTaskRequest['sta}const TASK_TOOL_NAME = 'ap_run_task'+const RESEARCH_TOOL_NAME = 'ap_deep_research'+const RESEARCHERS_AT_ONCE = 4const TASK_SKILL_SURFACE: SkillSurface = 'CHAT'const REPORT_REQUEST = `You stopped without reporting. Call ${TASK_COMPLETION_TOOL_NAME} now with your result.`const CONTINUE_REQUEST = 'You were cut off. Continue from where you stopped.'const MAX_CONTINUATIONS = 2const REPORT_STEPS = 2+const WEB_SEARCH_TOOL = 'ap_web_search'+const PAGE_READ_TOOLS = ['ap_fetch_url', 'ap_scrape_url']+const RESEARCH_TOOLS = [WEB_SEARCH_TOOL, ...PAGE_READ_TOOLS]+const RESEARCH_PAGE_CHARS = 32_000+const PAGE_TEXT_KEYS = ['content', 'markdown']+const LARGE_RESPONSE_MARKER = '[LARGE RESPONSE'++const TASK_PROFILES: Record<TaskKind, (deps: TaskDeps) => TaskProfile> = {+ task: ({ workerTools, models, guides }) => ({ tools: workerTools, models, skills: { surface: TASK_SKILL_SURFACE, guides } }),+ research: ({ workerTools, researchModels }) => ({ tools: researchTools(workerTools), models: researchModels }),+}const NOT_FOR_TASKS = [TASK_TOOL_NAME,'ap_retry_run',+ RESEARCH_TOOL_NAME,...AGENT_SURFACE_TOOLS,'ap_update_thinking_status','ap_send_email',@@ -351,6 +476,7 @@ type TaskDeps = {workerTools: ToolSetguides: Record<string, string>models: RunAgentTurnParams['models']+ researchModels: RunAgentTurnParams['models']tier: RunAgentTurnParams['tier']taskPrompt: stringcreditsLeftFor: (runKey: string) => RunAgentTurnParams['creditsLeft']@@ -361,6 +487,14 @@ type TaskDeps = {log: RunAgentTurnParams['log']}+type TaskKind = 'task' | 'research'++type TaskProfile = {+ tools: ToolSet+ models: RunAgentTurnParams['models']+ skills?: RunAgentTurnParams['skills']+}+type TaskRunOutput = {taskId?: stringstatus: TaskResult['status']diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.tsindex 2a9b9bef3e1..5ca2d0e3cae 100644--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts@@ -101,26 +101,99 @@ describe('createTaskSubagentTools', () => {])})- it('streams its status steps as a timeline', async () => {+ it('streams its searches and page reads in order', async () => {runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {- await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Built.', artifacts: [] }, EXECUTION_OPTIONS)+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Found it.', artifacts: [] }, EXECUTION_OPTIONS)+ return reportedTurn()+ })+ const reportedTurn = (): Record<string, unknown> => ({+ ...turnResult(),+ uiParts: [+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 's1', toolName: 'ap_web_search', input: { query: 'blue bottle' }, status: PersistedToolCallStatus.COMPLETED, output: { results: [{ title: 'Blue Bottle plans', url: 'https://bluebottle.com/plans' }, { title: 'Reddit thread', url: 'https://reddit.com/r/coffee/1' }] } },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f1', toolName: 'ap_fetch_url', input: { url: 'https://bluebottle.com/plans' }, status: PersistedToolCallStatus.COMPLETED, output: { url: 'https://bluebottle.com/plans', content: 'Plans and pricing' } },+ ],+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ activity: { timeline: [+ { kind: 'search', query: 'blue bottle', results: [{ url: 'https://bluebottle.com/plans', title: 'Blue Bottle plans' }, { url: 'https://reddit.com/r/coffee/1', title: 'Reddit thread' }] },+ { kind: 'read', url: 'https://bluebottle.com/plans', title: 'Blue Bottle plans' },+ ] } })+ })++ it('labels a researcher with its latest search or page read', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Found it.', artifacts: [] }, EXECUTION_OPTIONS)return {...turnResult(),uiParts: [- { type: PersistedAgentPartType.THINKING_STATUS, text: 'Looking at your Leads table' },- { type: PersistedAgentPartType.THINKING_STATUS, text: ' ' },- { type: PersistedAgentPartType.THINKING_STATUS, text: 'Checking the flow works' },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 's1', toolName: 'ap_web_search', input: { query: 'asana pricing' }, status: PersistedToolCallStatus.COMPLETED, output: { results: [{ title: 'Asana plans', url: 'https://asana.com/pricing' }] } },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f1', toolName: 'ap_fetch_url', input: { url: 'https://asana.com/pricing' }, status: PersistedToolCallStatus.COMPLETED, output: { url: 'https://asana.com/pricing', content: 'Plans' } },],}})- const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })- const result = await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)+ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)- expect(result).toMatchObject({ activity: { statusLine: 'Checking the flow works', timeline: [- { kind: 'status', text: 'Looking at your Leads table' },- { kind: 'status', text: 'Checking the flow works' },- ] } })+ expect(result).toMatchObject({ activity: { statusLine: 'Asana plans' } })+ })++ it('keeps the links of a search too large to return in full', async () => {+ const truncated = JSON.stringify({ query: 'pricing', results: [{ title: 'Plans', url: 'https://ok.com/plans' }] })+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Found it.', artifacts: [] }, EXECUTION_OPTIONS)+ return {+ ...turnResult(),+ uiParts: [+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 's1', toolName: 'ap_web_search', input: { query: 'pricing' }, status: PersistedToolCallStatus.COMPLETED, output: { content: [{ type: 'text', text: `[LARGE RESPONSE — long values were truncated to fit, structure preserved] The full response was 80KB.\n\n${truncated}` }] } },+ ],+ }+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ activity: { timeline: [{ kind: 'search', query: 'pricing', results: [{ url: 'https://ok.com/plans', title: 'Plans' }] }] } })+ })++ it('keeps reporting progress when a search or page read failed with no output', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet, sinks: { onProgress: (progress: { uiParts: unknown[] }) => void } }) => {+ const failed = [+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 's1', toolName: 'ap_web_search', input: { query: 'pricing' }, status: PersistedToolCallStatus.ERROR, output: undefined },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f1', toolName: 'ap_fetch_url', input: { url: 'https://down.com' }, status: PersistedToolCallStatus.COMPLETED, output: undefined },+ ]+ params.sinks.onProgress({ uiParts: failed })+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Recovered.', artifacts: [] }, EXECUTION_OPTIONS)+ return { ...turnResult(), uiParts: failed }+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ status: 'done', activity: { timeline: [{ kind: 'search', query: 'pricing', results: [] }] } })+ })++ it('counts only pages that were actually read', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Found it.', artifacts: [] }, EXECUTION_OPTIONS)+ return {+ ...turnResult(),+ uiParts: [+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f1', toolName: 'ap_fetch_url', input: { url: 'https://ok.com' }, status: PersistedToolCallStatus.COMPLETED, output: { url: 'https://ok.com', content: 'Pricing' } },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f2', toolName: 'ap_fetch_url', input: { url: 'https://down.com' }, status: PersistedToolCallStatus.COMPLETED, output: { content: [{ type: 'text', text: 'Failed to fetch https://down.com: timeout' }] } },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f3', toolName: 'ap_scrape_url', input: { url: 'https://broken.com' }, status: PersistedToolCallStatus.ERROR, output: null },+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'f4', toolName: 'ap_scrape_url', input: { url: 'https://big.com' }, status: PersistedToolCallStatus.COMPLETED, output: { content: [{ type: 'text', text: '[LARGE RESPONSE — long values were truncated to fit, structure preserved] {}' }] } },+ ],+ }+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ activity: { timeline: [{ kind: 'read', url: 'https://ok.com' }, { kind: 'read', url: 'https://big.com' }] } })})it('keeps the card details out of what the main model reads', async () => {@@ -241,15 +314,53 @@ describe('createTaskSubagentTools', () => {expect(runAgentTurn).not.toHaveBeenCalled()})- it('starts nothing once the run is stopped', async () => {+ it('researches every subject in its own task, in parallel, with its own live card', async () => {+ beginTask.mockImplementation(async ({ title }: { title: string }) => ({ taskId: `task-${title}`, claimId: `claim-${title}`, messages: [] }))+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet, messages: { content: string }[] }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: `Brief for ${params.messages[0].content.split('Subject: ')[1]}`, artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_deep_research'].execute?.({ question: 'Pricing for 12 seats', subjects: ['Asana', 'ClickUp'] }, EXECUTION_OPTIONS)++ expect(runAgentTurn).toHaveBeenCalledTimes(2)+ expect(Object.keys(runAgentTurn.mock.calls[0][0].tools)).not.toContain('ap_deep_research')+ expect(new Set(emitSubagentProgress.mock.calls.map(([event]) => event.toolCallId))).toEqual(new Set(['call-1:0', 'call-1:1']))+ expect(result).toMatchObject({ tasks: [{ taskId: 'task-Asana', status: 'done', summary: 'Brief for Asana' }, { taskId: 'task-ClickUp', status: 'done', summary: 'Brief for ClickUp' }] })+ expect(result).toMatchObject({ billedToolCalls: [{ toolName: 'ap_web_search' }, { toolName: 'ap_web_search' }] })+ })++ it('runs a long list of subjects a few at a time', async () => {+ const inFlight = { now: 0, peak: 0 }+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ inFlight.now += 1+ inFlight.peak = Math.max(inFlight.peak, inFlight.now)+ await new Promise((resolve) => setTimeout(resolve, 5))+ inFlight.now -= 1+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_deep_research'].execute?.({ question: 'Compare', subjects: ['a', 'b', 'c', 'd', 'e', 'f'] }, EXECUTION_OPTIONS)++ expect(inFlight.peak).toBe(4)+ expect(result).toMatchObject({ tasks: [{}, {}, {}, {}, {}, {}] })+ })++ it('starts no more researchers once the run is stopped', async () => {const controller = new AbortController()- controller.abort()- const tasks = createTaskSubagentTools({ ...BASE_PARAMS, abortSignal: controller.signal, tools: toolSet(['ap_build_flow']) })+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ controller.abort()+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, abortSignal: controller.signal, tools: toolSet(['ap_web_search']) })- const result = await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)+ await tasks['ap_deep_research'].execute?.({ question: 'Compare', subjects: ['a', 'b', 'c', 'd', 'e', 'f'] }, EXECUTION_OPTIONS)- expect(beginTask).not.toHaveBeenCalled()- expect(result).toMatchObject({ status: 'failed' })+ expect(beginTask).toHaveBeenCalledTimes(4)})it('keeps the result when saving it fails once', async () => {@@ -296,6 +407,38 @@ describe('createTaskSubagentTools', () => {expect(Object.keys(runAgentTurn.mock.calls[0][0].tools)).not.toContain('ap_retry_run')})+ it('gives researchers only the search and page tools, on the research models, with no skills', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search', 'ap_fetch_url', 'ap_scrape_url', 'ap_build_flow', 'ap_execute_action']) })++ await tasks['ap_deep_research'].execute?.({ question: 'Pricing', subjects: ['Asana'] }, EXECUTION_OPTIONS)++ const params = runAgentTurn.mock.calls[0][0]+ expect(Object.keys(params.tools).sort()).toEqual(['ap_fetch_url', 'ap_scrape_url', 'ap_web_search', TASK_COMPLETION_TOOL_NAME].sort())+ expect(params.models).toBe(RESEARCH_MODELS)+ expect(params.skills).toBeUndefined()+ })++ it('cuts a page a researcher reads down to a small budget', async () => {+ let pageSize = 0+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ const page = await params.tools['ap_fetch_url'].execute?.({}, EXECUTION_OPTIONS)+ pageSize = JSON.stringify(page).length+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const bigPage = tool({ description: 'fetch', inputSchema: z.object({}), execute: async () => ({ url: 'https://big.com', content: 'x'.repeat(200 * 1024) }) })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: { ...toolSet(['ap_web_search']), ap_fetch_url: bigPage } })++ await tasks['ap_deep_research'].execute?.({ question: 'Pricing', subjects: ['Asana'] }, EXECUTION_OPTIONS)++ expect(pageSize).toBeGreaterThan(30_000)+ expect(pageSize).toBeLessThan(40 * 1024)+ })+it('shows the latest step title on the card when the task sends no status', async () => {runAgentTurn.mockImplementation(async (params: { tools: ToolSet, sinks: { onProgress: (progress: { uiParts: unknown[] }) => void } }) => {params.sinks.onProgress({ uiParts: [{ type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'b1', toolName: 'ap_build_flow', title: 'Building your intake flow', input: {}, status: PersistedToolCallStatus.COMPLETED }] })@@ -323,6 +466,10 @@ describe('createTaskSubagentTools', () => {expect(Object.keys(runAgentTurn.mock.calls[0][0].tools).filter((name) => name.includes('agent'))).toEqual([])})+ it('offers research only when web search is available', () => {+ expect(createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })).not.toHaveProperty('ap_deep_research')+ })+it('offers no task tool without a task prompt', () => {expect(createTaskSubagentTools({ ...BASE_PARAMS, taskPrompt: undefined, tools: toolSet(['ap_build_flow']) })).toEqual({})})@@ -352,9 +499,12 @@ const finishTask = vi.fn()const MODELS: RunAgentTurnParams['models'] = [{ model: 'test-model', provider: AIProviderName.OPENAI, modelId: 'm', thinkingBudget: 0 }]+const RESEARCH_MODELS: RunAgentTurnParams['models'] = [{ model: 'fast-model', provider: AIProviderName.OPENAI, modelId: 'fast', thinkingBudget: 0 }]+const BASE_PARAMS = {guides: { build_flow: 'BUILD FLOW GUIDE' },models: MODELS,+ researchModels: RESEARCH_MODELS,tier: { id: 'smart', thinkingBudget: 0, modelId: 'm' },taskPrompt: 'TASK PROMPT',creditsLeftFor: () => undefined,diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 6981845db0e..d28c7ba9a07 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -3284,5 +3284,8 @@"Exit full screen": "Exit full screen","Full screen": "Full screen","Findings": "Findings",- "Made": "Made"+ "Made": "Made",+ "{count, plural, =1 {1 source} other {# sources}}": "{count, plural, =1 {1 source} other {# sources}}",+ "Read {page}": "Read {page}",+ "Searched “{query}”": "Searched “{query}”"}diff --git a/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsx b/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsxindex 62bd068c773..ee5606a72b7 100644--- a/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsx@@ -8,13 +8,15 @@ import { createPortal } from 'react-dom';import { TextWithTooltip } from '@/components/custom/text-with-tooltip';import { ToolCallMeta } from '@/features/chat/lib/chat-store';import { useChatStoreContext } from '@/features/chat/lib/chat-store-context';-import { AnyToolPart, chatPartUtils } from '@/features/chat/lib/chat-types';import { cn } from '@/lib/utils';+import { TaskRow } from '../lib/message-blocks';+import {AppLogos,Duration,LiveLine,+ ReadFavicons,StatusMark,} from './subagent-primitives';import { TaskPanel, TaskPanelSlotContext } from './task-panel';@@ -24,7 +26,7 @@ export function SubagentGroup({toolCallMeta,isStreaming,}: {- tasks: { toolCallId: string; part: AnyToolPart }[];+ tasks: TaskRow[];toolCallMeta: Record<string, ToolCallMeta>;isStreaming: boolean;}) {@@ -32,11 +34,11 @@ export function SubagentGroup({const openTaskPanel = useChatStoreContext((s) => s.openTaskPanel);const closeTaskPanel = useChatStoreContext((s) => s.closeTaskPanel);const panelSlot = useContext(TaskPanelSlotContext);- const activities = tasks.map(({ toolCallId, part }) => ({- toolCallId,+ const activities = tasks.map((task) => ({+ toolCallId: task.toolCallId,activity: resolveActivity({- live: toolCallMeta[toolCallId]?.subagent,- part,+ live: toolCallMeta[task.toolCallId]?.subagent,+ task,isStreaming,}),}));@@ -119,6 +121,7 @@ function SubagentRow({<LiveLine activity={activity} /></div><AppLogos pieces={activity.pieces ?? []} />+ <ReadFavicons timeline={activity.timeline ?? []} /><Duration activity={activity} /></button></div>@@ -127,32 +130,32 @@ function SubagentRow({function resolveActivity({live,- part,+ task,isStreaming,}: {live: SubagentActivity | undefined;- part: AnyToolPart;+ task: TaskRow;isStreaming: boolean;}): SubagentActivity {- const saved = activityFromOutput(part);+ const saved = activityFromOutput(task);if (saved) return saved;if (live) {const stoppedMidRun = live.status === 'running' && !isStreaming;return stoppedMidRun ? { ...live, status: 'failed' } : live;}- const input = isObject(part.input) ? part.input : {};+ const input = isObject(task.part.input) ? task.part.input : {};+ const inputTitle =+ typeof input['title'] === 'string' ? input['title'] : undefined;return {- title: typeof input['title'] === 'string' ? input['title'] : t('Task'),+ title: task.subject ?? inputTitle ?? t('Task'),status: isStreaming ? 'running' : 'failed',stepCount: 0,startedAt: '',};}-function activityFromOutput(part: AnyToolPart): SubagentActivity | null {- const parsed = chatPartUtils.parseToolOutput(part);- if (parsed.state !== 'success' || !isObject(parsed.data)) return null;- const activity = parsed.data['activity'];+function activityFromOutput(task: TaskRow): SubagentActivity | null {+ const activity = isObject(task.output) ? task.output['activity'] : undefined;return isSubagentActivity(activity) ? activity : null;}diff --git a/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsx b/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsxindex e2d752e27ef..7c5e8302e0f 100644--- a/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsx@@ -1,9 +1,10 @@-import { SubagentActivity } from '@activepieces/shared';+import { SubagentActivity, SubagentTimelineEntry } from '@activepieces/shared';import { t } from 'i18next';import { Check, Hand, Loader2, Minus } from 'lucide-react';import { AnimatePresence, motion } from 'motion/react';import { useEffect, useState } from 'react';+import { FaviconOrGlobe } from '@/components/prompt-kit/source';import { TextShimmer } from '@/components/ui/text-shimmer';import { PieceIcon } from '@/features/pieces/components/piece-icon';import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';@@ -79,14 +80,40 @@ export function AppLogos({ pieces }: { pieces: string[] }) {const apps = pieces.filter((pieceName) => !PLUMBING_PIECES.includes(pieceName),);- if (apps.length === 0) return null;- const shown = apps.slice(0, MAX_LOGOS);- const extra = apps.length - shown.length;return (- <div className="flex shrink-0 items-center gap-1">- {shown.map((pieceName) => (+ <LogoStack+ items={apps.map((pieceName) => (<AppLogo key={pieceName} pieceName={pieceName} />))}+ />+ );+}++export function ReadFavicons({+ timeline,+}: {+ timeline: SubagentTimelineEntry[];+}) {+ return (+ <LogoStack+ items={readPages(timeline).map((page) => (+ <span+ key={page.url}+ className="flex size-5 items-center justify-center rounded-full bg-panel"+ >+ <FaviconOrGlobe url={page.url} size="sm" />+ </span>+ ))}+ />+ );+}++function LogoStack({ items }: { items: React.ReactNode[] }) {+ if (items.length === 0) return null;+ const extra = items.length - MAX_LOGOS;+ return (+ <div className="flex shrink-0 items-center gap-1">+ {items.slice(0, MAX_LOGOS)}{extra > 0 && (<span className="text-xs text-gray-11 tabular-nums">+{extra}</span>)}@@ -144,5 +171,19 @@ function AppLogo({ pieceName }: { pieceName: string }) {);}+function readPages(+ timeline: SubagentTimelineEntry[],+): { url: string; title?: string }[] {+ const pages = timeline.flatMap((entry) =>+ entry.kind === 'read' ? [{ url: entry.url, title: entry.title }] : [],+ );+ return pages.filter(+ (page, index) =>+ pages.findIndex((other) => other.url === page.url) === index,+ );+}++export const subagentTimelineUtils = { readPages };+const MAX_LOGOS = 3;const PLUMBING_PIECES = ['@activepieces/piece-subflows'];diff --git a/packages/web/src/app/routes/chat-with-ai/components/task-panel.tsx b/packages/web/src/app/routes/chat-with-ai/components/task-panel.tsxindex 2af7a4464ce..f858ee89ce9 100644--- a/packages/web/src/app/routes/chat-with-ai/components/task-panel.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/task-panel.tsx@@ -1,6 +1,6 @@-import { SubagentActivity } from '@activepieces/shared';+import { SubagentActivity, SubagentTimelineEntry } from '@activepieces/shared';import { t } from 'i18next';-import { Check, Loader2, Maximize2, Minimize2, X } from 'lucide-react';+import { Check, Loader2, Maximize2, Minimize2, Search, X } from 'lucide-react';import { motion } from 'motion/react';import { createContext, useEffect, useRef, useState } from 'react';@@ -9,6 +9,11 @@ import {ChatContainerRoot,} from '@/components/prompt-kit/chat-container';import { Markdown } from '@/components/prompt-kit/markdown';+import {+ FaviconOrGlobe,+ getDomain,+ Source,+} from '@/components/prompt-kit/source';import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';import { chatStoreSelectors } from '@/features/chat/lib/chat-store';import { useChatStoreContext } from '@/features/chat/lib/chat-store-context';@@ -16,7 +21,12 @@ import { useElementSize } from '@/hooks/use-element-size';import { cn } from '@/lib/utils';import { PreviewIconButton } from './previews/preview-card';-import { Duration, LiveLine, StatusMark } from './subagent-primitives';+import {+ Duration,+ LiveLine,+ StatusMark,+ subagentTimelineUtils,+} from './subagent-primitives';export function TaskPanel({tasks,@@ -153,6 +163,7 @@ function TaskDetails({}) {const timeline = activity.timeline ?? [];const artifacts = activity.artifacts ?? [];+ const pages = subagentTimelineUtils.readPages(timeline);const running = activity.status === 'running';return (@@ -172,9 +183,8 @@ function TaskDetails({<ol className="mt-5 flex flex-col gap-3">{timeline.map((entry, index) => (<TimelineItem- key={`${index}-${entry.text}`}- text={entry.text}- failed={entry.failed ?? false}+ key={`${index}-${entry.kind}`}+ entry={entry}active={running && index === timeline.length - 1}/>))}@@ -203,18 +213,35 @@ function TaskDetails({</div></Section>)}++ {pages.length > 0 && (+ <Section+ title={t('{count, plural, =1 {1 source} other {# sources}}', {+ count: pages.length,+ })}+ >+ <div+ className={cn(+ 'grid grid-cols-1 gap-2',+ wide ? 'sm:grid-cols-3' : 'sm:grid-cols-2',+ )}+ >+ {pages.map((page) => (+ <SourceCard key={page.url} url={page.url} title={page.title} />+ ))}+ </div>+ </Section>+ )}</ChatContainerContent></ChatContainerRoot>);}function TimelineItem({- text,- failed,+ entry,active,}: {- text: string;- failed: boolean;+ entry: SubagentTimelineEntry;active: boolean;}) {return (@@ -225,19 +252,93 @@ function TimelineItem({className="flex gap-3"><span className="flex size-5 shrink-0 items-center justify-center">- {failed ? (- <X className="size-3.5 text-danger-11" strokeWidth={2.5} />- ) : active ? (- <Loader2 className="size-3.5 animate-spin text-accent-10 motion-reduce:animate-none" />- ) : (- <Check className="size-3.5 text-success-10" strokeWidth={2.5} />- )}+ <TimelineIcon entry={entry} active={active} /></span>- <p className="min-w-0 flex-1 text-sm text-gray-12">{text}</p>+ <div className="min-w-0 flex-1 text-sm text-gray-12">+ {entry.kind === 'status' && <p>{entry.text}</p>}+ {entry.kind === 'search' && <SearchEntry entry={entry} />}+ {entry.kind === 'read' && (+ <a+ href={entry.url}+ target="_blank"+ rel="noopener noreferrer"+ className="block truncate hover:underline"+ >+ {t('Read {page}', { page: entry.title ?? getDomain(entry.url) })}+ </a>+ )}+ </div></motion.li>);}+function TimelineIcon({+ entry,+ active,+}: {+ entry: SubagentTimelineEntry;+ active: boolean;+}) {+ if (entry.kind === 'status' && entry.failed) {+ return <X className="size-3.5 text-danger-11" strokeWidth={2.5} />;+ }+ if (active) {+ return (+ <Loader2 className="size-3.5 animate-spin text-accent-10 motion-reduce:animate-none" />+ );+ }+ if (entry.kind === 'search') {+ return <Search className="size-3.5 text-gray-11" />;+ }+ if (entry.kind === 'read') {+ return <FaviconOrGlobe url={entry.url} size="sm" />;+ }+ return <Check className="size-3.5 text-success-10" strokeWidth={2.5} />;+}++function SearchEntry({+ entry,+}: {+ entry: Extract<SubagentTimelineEntry, { kind: 'search' }>;+}) {+ const shown = entry.results.slice(0, MAX_SEARCH_RESULTS);+ const extra = entry.results.length - shown.length;+ return (+ <div>+ <p className="truncate">+ {t('Searched “{query}”', { query: entry.query })}+ </p>+ {shown.length > 0 && (+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5">+ {shown.map((result) => (+ <Source key={result.url} href={result.url} title={result.title} />+ ))}+ {extra > 0 && (+ <span className="text-xs text-gray-11 tabular-nums">+{extra}</span>+ )}+ </div>+ )}+ </div>+ );+}++function SourceCard({ url, title }: { url: string; title?: string }) {+ return (+ <a+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ className="flex flex-col gap-1.5 rounded-lg border p-3 transition-colors hover:bg-gray-3"+ >+ <span className="flex items-center gap-1.5 text-xs text-gray-11">+ <FaviconOrGlobe url={url} size="sm" />+ <span className="truncate">{getDomain(url)}</span>+ </span>+ <span className="line-clamp-2 text-sm text-gray-12">{title ?? url}</span>+ </a>+ );+}+function Section({title,children,@@ -254,3 +355,5 @@ function Section({}export const TaskPanelSlotContext = createContext<HTMLElement | null>(null);++const MAX_SEARCH_RESULTS = 4;diff --git a/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts b/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.tsindex 8491d3924d6..4348ceedcd1 100644--- a/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts+++ b/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts@@ -1,5 +1,5 @@import { isObject, parseToJsonIfPossible } from '@activepieces/core-utils';-import { BatchProgressData } from '@activepieces/shared';+import { BatchProgressData, subagentProgressId } from '@activepieces/shared';import { ToolCallMeta } from '@/features/chat/lib/chat-store';import {@@ -190,14 +190,14 @@ export function buildMessageBlocks({}continue;}- if (toolName === 'ap_run_task') {+ if (toolName === 'ap_run_task' || toolName === 'ap_deep_research') {endSegment();- const task = { toolCallId: chatPartUtils.getToolCallId(p), part: p };+ const tasks = taskRows({ part: p, toolName });const previous = result[result.length - 1];if (previous?.kind === 'tasks') {- previous.tasks.push(task);+ previous.tasks.push(...tasks);} else {- result.push({ kind: 'tasks', tasks: [task] });+ result.push({ kind: 'tasks', tasks });}continue;}@@ -256,6 +256,35 @@ export function buildMessageBlocks({};}+function taskRows({+ part,+ toolName,+}: {+ part: AnyToolPart;+ toolName: string;+}): TaskRow[] {+ const toolCallId = chatPartUtils.getToolCallId(part);+ const parsed = chatPartUtils.parseToolOutput(part);+ const output = parsed.state === 'success' ? parsed.data : undefined;+ if (toolName !== 'ap_deep_research') {+ return [{ toolCallId, part, output }];+ }+ const input = isObject(part.input) ? part.input : {};+ const subjects = Array.isArray(input['subjects'])+ ? input['subjects'].filter(+ (subject): subject is string => typeof subject === 'string',+ )+ : [];+ const outputs =+ isObject(output) && Array.isArray(output['tasks']) ? output['tasks'] : [];+ return subjects.map((subject, index) => ({+ toolCallId: subagentProgressId.forSubject({ toolCallId, index }),+ part,+ output: outputs[index],+ subject,+ }));+}+// Several genuine outcomes in a row (e.g. a handful of individual writes) would// otherwise stack as N full-width cards. Coalesce an adjacent run of 2+ outcome// cards into one collapsed `card-group` so the timeline stays calm; a lone card@@ -390,7 +419,7 @@ export type MessageBlock =| { kind: 'batch-progress'; data: BatchProgressData }| {kind: 'tasks';- tasks: { toolCallId: string; part: AnyToolPart }[];+ tasks: TaskRow[];}| OutcomeCardBlock| { kind: 'card-group'; cards: OutcomeCardBlock[] }@@ -414,4 +443,11 @@ export type OutcomeCardBlock =| { kind: 'image'; toolCallId: string }| { kind: 'files'; toolCallId: string };+export type TaskRow = {+ toolCallId: string;+ part: AnyToolPart;+ output: unknown;+ subject?: string;+};+export type SourceItem = { key: string; href?: string; title?: string };diff --git a/packages/web/src/components/prompt-kit/source.tsx b/packages/web/src/components/prompt-kit/source.tsxindex 62d98701e19..e06302c8996 100644--- a/packages/web/src/components/prompt-kit/source.tsx+++ b/packages/web/src/components/prompt-kit/source.tsx@@ -10,7 +10,7 @@ import { cn } from '@/lib/utils';function getDomain(url: string): string {try {- return new URL(url).hostname.replace('www.', '');+ return new URL(url).hostname.replace(/^www\./, '');} catch {return url;}@@ -84,7 +84,7 @@ function Source({ href, title, className }: SourceProps) {);}-export { Source };+export { FaviconOrGlobe, getDomain, Source };export type SourceProps = {href: string;diff --git a/packages/web/src/features/chat/lib/chat-store.ts b/packages/web/src/features/chat/lib/chat-store.tsindex 45b01a8874b..6b2c5fb1775 100644--- a/packages/web/src/features/chat/lib/chat-store.ts+++ b/packages/web/src/features/chat/lib/chat-store.ts@@ -64,6 +64,7 @@ export type ChatStoreState = {dismissedGateIds: Record<string, true>;lastDismissedFormId: string | null;taskPanelToolCallId: string | null;+ taskPanelAutoOpen: boolean;chatAreaWidth: number;setConversationId: (conversationId: string | null) => void;@@ -100,6 +101,7 @@ export const createChatStore = () =>dismissedGateIds: {},lastDismissedFormId: null,taskPanelToolCallId: null,+ taskPanelAutoOpen: true,chatAreaWidth: 0,approveGate: (gateId: string, payload?: Record<string, unknown>) => {@@ -117,7 +119,11 @@ export const createChatStore = () =>set({ lastDismissedFormId: messageId });},setConversationId: (conversationId: string | null) => {- set({ conversationId });+ set((prev) =>+ prev.conversationId === conversationId+ ? { conversationId }+ : { conversationId, taskPanelAutoOpen: true },+ );},resetInteractions: () => {set({@@ -136,7 +142,7 @@ export const createChatStore = () =>set({ taskPanelToolCallId: toolCallId });},closeTaskPanel: () => {- set({ taskPanelToolCallId: null });+ set({ taskPanelToolCallId: null, taskPanelAutoOpen: false });},setChatAreaWidth: (width: number) => {set({ chatAreaWidth: width });diff --git a/packages/web/src/features/chat/lib/chat-utils.ts b/packages/web/src/features/chat/lib/chat-utils.tsindex bfa2f0bd975..4c2a9c98d27 100644--- a/packages/web/src/features/chat/lib/chat-utils.ts+++ b/packages/web/src/features/chat/lib/chat-utils.ts@@ -53,6 +53,7 @@ const TOOL_LABELS: Record<string, { active: string; done: string }> = {},ap_build_flow: { active: 'Building automation', done: 'Built automation' },ap_run_task: { active: 'Working on a task', done: 'Finished a task' },+ ap_deep_research: { active: 'Researching', done: 'Researched' },ap_create_flow: { active: 'Creating automation', done: 'Created automation' },ap_validate_step_config: {active: 'Validating setup',diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.tsindex 7ee210c6dc3..8836c98fbae 100644--- a/packages/web/src/features/chat/lib/use-chat.ts+++ b/packages/web/src/features/chat/lib/use-chat.ts@@ -13,6 +13,7 @@ import {ToolProgressEvent,AgentMessageSource,SubagentActivity,+ subagentProgressId,SubagentProgressEvent,} from '@activepieces/shared';import { useQuery } from '@tanstack/react-query';@@ -229,10 +230,13 @@ function appendTrailingPart({messages: ChatUIMessage[];part: ReturnType<typeof buildGatePart>;}): ChatUIMessage[] {+ const baseToolCallId = subagentProgressId.baseOf(part.toolCallId);const alreadyAnchored = messages.some((m) =>m.parts.some((existing) =>- 'toolCallId' in existing && existing.toolCallId === part.toolCallId,+ 'toolCallId' in existing &&+ (existing.toolCallId === part.toolCallId ||+ existing.toolCallId === baseToolCallId),),);if (alreadyAnchored) return messages;@@ -421,6 +425,11 @@ export function useAgentChat({if (isStale) {return prev;}+ const opensPanel =+ prev.taskPanelAutoOpen &&+ prev.taskPanelToolCallId === null &&+ chatStoreSelectors.taskPanelDocks(prev) &&+ (event.data.timeline ?? []).some((entry) => entry.kind === 'search');return {toolCallMeta: {...prev.toolCallMeta,@@ -429,6 +438,7 @@ export function useAgentChat({subagent: event.data,},},+ ...(opensPanel ? { taskPanelToolCallId: event.toolCallId } : {}),};});},diff --git a/packages/web/test/features/chat/lib/chat-store.test.ts b/packages/web/test/features/chat/lib/chat-store.test.tsindex c13a4daa0d5..0dd20fd56fa 100644--- a/packages/web/test/features/chat/lib/chat-store.test.ts+++ b/packages/web/test/features/chat/lib/chat-store.test.ts@@ -21,17 +21,26 @@ function event(override: Partial<BuildPlanEvent>): BuildPlanEvent {describe('chatBuildUtils.mergeBuildPlan', () => {it('inserts a new build', () => {- const merged = chatBuildUtils.mergeBuildPlan({ builds: {}, event: event({}) });+ const merged = chatBuildUtils.mergeBuildPlan({+ builds: {},+ event: event({}),+ });expect(merged['build_1'].phase).toBe('building');});it('ignores stale events with an older updatedAt', () => {const builds: Record<string, BuildState> = {- build_1: { ...event({ phase: 'done' }), updatedAt: '2026-01-01T00:05:00.000Z' },+ build_1: {+ ...event({ phase: 'done' }),+ updatedAt: '2026-01-01T00:05:00.000Z',+ },};const merged = chatBuildUtils.mergeBuildPlan({builds,- event: event({ phase: 'building', updatedAt: '2026-01-01T00:01:00.000Z' }),+ event: event({+ phase: 'building',+ updatedAt: '2026-01-01T00:01:00.000Z',+ }),});expect(merged).toBe(builds);expect(merged['build_1'].phase).toBe('done');@@ -43,7 +52,11 @@ describe('chatBuildUtils.mergeBuildPlan', () => {};const merged = chatBuildUtils.mergeBuildPlan({builds,- event: event({ phase: 'done', flowId: 'flow_42', updatedAt: '2026-01-01T00:05:00.000Z' }),+ event: event({+ phase: 'done',+ flowId: 'flow_42',+ updatedAt: '2026-01-01T00:05:00.000Z',+ }),});expect(merged['build_1'].phase).toBe('done');expect(merged['build_1'].flowId).toBe('flow_42');@@ -65,3 +78,26 @@ describe('chat store build state', () => {expect(store.getState().builds).toEqual({});});});++describe('task panel auto-open', () => {+ it('stays off for the rest of the conversation once the user closes the panel', () => {+ const store = createChatStore();+ store.getState().setConversationId('conv_1');+ store.getState().closeTaskPanel();++ store.getState().resetInteractions();+ store.getState().setConversationId('conv_1');++ expect(store.getState().taskPanelAutoOpen).toBe(false);+ });++ it('comes back for a different conversation', () => {+ const store = createChatStore();+ store.getState().setConversationId('conv_1');+ store.getState().closeTaskPanel();++ store.getState().setConversationId('conv_2');++ expect(store.getState().taskPanelAutoOpen).toBe(true);+ });+});