diff --git a/apps/docs/content/docs/integrations/slack.mdx b/apps/docs/content/docs/integrations/slack.mdx index ac7bcb76873..d97664d897d 100644 --- a/apps/docs/content/docs/integrations/slack.mdx +++ b/apps/docs/content/docs/integrations/slack.mdx @@ -31,6 +31,9 @@ Custom-bot Slack triggers can stream workflow outputs directly back into the con - Loop and parallel invocations each create their own Slack response. - The response status label defaults to `Running` and can be customized in the trigger's advanced settings. - Optional thinking and tool-call updates appear as Slack tasks in a timeline or plan. +- **Show progress from** (`streamTimelineSources`) shows an Agent's tool steps, and its thinking when enabled, without posting its text. Use it when an Agent's output is reviewed or reformatted by a later block: the steps and the first streamed answer share one Slack reply. Agents in child workflows can be selected. A block cannot be both an output to stream and a progress source. +- **Tool step labels** (`streamToolLabels`) renames tool steps by tool name, for example `lc_cur` → `Reading AWS cost data`. Unlisted tools use a generated name. Steps never show tool arguments. +- With PII block-output redaction on, Agent output is not streamed live, so no progress steps appear; selected outputs are still sent when their block completes. - Slack Agent Sessions remain in processing state for the run, return to active when it finishes, and the native Slack stop button cancels active workflow executions. Automatic trigger responses require a custom bot created by the Slack setup wizard. They are not available with the shared Sim Slack app. Where the deployment enables shared-app triggers, the Sim app can receive its subscribed event subset without automatic streaming. @@ -3867,6 +3870,8 @@ Trigger from Slack events, interactions, and slash commands | `threads` | string | No | Include thread replies, exclude them \(top-level only\), or fire only on thread replies. | | `streamResponse` | boolean | No | Create a Slack agent session and stream selected workflow outputs into the conversation that started this run. Custom bots only. | | `streamOutputs` | workflow-output-selector | No | Use `<blockName>.<outputPath>` for this workflow or `<childWorkflowId>.<blockName>.<outputPath>` for a child workflow. Selecting a child workflow applies to every invocation of it. Agent outputs stream live; other outputs are sent when the block completes. | +| `streamTimelineSources` | workflow-output-selector | No | Agent blocks, including ones in child workflows, whose tool steps appear in the reply while they run. Their text is never posted. No steps appear when PII block-output redaction is on. | +| `streamToolLabels` | table | No | Optional names for tool steps, keyed by tool name \(an MCP tool by its own name, like lc_cur\). Unlisted tools use a generated name. | | `streamTaskTitle` | string | No | Optional status Slack shows while each selected response is being produced. Leave empty to use Running. | | `streamTaskDisplayMode` | string | No | Choose how Slack displays thinking and tool progress. | | `streamIncludeThinking` | boolean | No | Show agent thinking as Slack task updates while the response is generated. | diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/chat/components/output-select/output-select.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/chat/components/output-select/output-select.tsx index 60b730175ab..cdcb9f1b350 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/chat/components/output-select/output-select.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/chat/components/output-select/output-select.tsx @@ -15,6 +15,7 @@ import { buildWorkflowOutputMenu, buildWorkflowOutputOptions, collectReferencedWorkflowIds, + selectBlockPathOptions, type WorkflowOutputMenuNode, type WorkflowOutputOption, } from '@/lib/workflows/streaming/nested-output-options' @@ -42,6 +43,8 @@ interface OutputSelectProps { disabled?: boolean /** Placeholder text when no outputs are selected */ placeholder?: string + /** Offers one option per block of this type, selecting this output path */ + outputFilter?: { blockType: string; path: string } /** Whether to emit internal IDs, display labels, or public dot selectors */ valueMode?: 'id' | 'label' | 'public' /** Alignment of the dropdown relative to the trigger */ @@ -127,6 +130,7 @@ function OutputSelectContent({ onOutputSelect, disabled = false, placeholder = 'Select outputs', + outputFilter, valueMode = 'id', align = 'start', maxHeight = 200, @@ -206,7 +210,7 @@ function OutputSelectContent({ const thirdLevelStates = useWorkflowStates(thirdLevelWorkflowIds) const workflowStates = new Map([...firstLevelStates, ...secondLevelStates, ...thirdLevelStates]) - const workflowOutputs = workflowId + const allWorkflowOutputs = workflowId ? buildWorkflowOutputOptions({ rootWorkflowId: workflowId, rootState, @@ -214,6 +218,9 @@ function OutputSelectContent({ maxChildDepth: DEFAULTS.MAX_SSE_CHILD_DEPTH, }) : [] + const workflowOutputs = outputFilter + ? selectBlockPathOptions(allWorkflowOutputs, outputFilter.blockType, outputFilter.path) + : allWorkflowOutputs const outputMenu = buildWorkflowOutputMenu(workflowOutputs) const outputMenuRevision = JSON.stringify([ workflowId, diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx index bbe921224b8..a611f6302f5 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx @@ -11,6 +11,7 @@ interface WorkflowOutputSelectorProps { previewValue?: string[] | null disabled?: boolean placeholder?: string + outputFilter?: { blockType: string; path: string } } export function WorkflowOutputSelector({ @@ -20,6 +21,7 @@ export function WorkflowOutputSelector({ previewValue, disabled = false, placeholder, + outputFilter, }: WorkflowOutputSelectorProps) { const workflowId = useWorkflowRegistry((state) => state.activeWorkflowId) const [storedValue, setStoredValue] = useSubBlockValue(blockId, subBlockId) @@ -34,6 +36,7 @@ export function WorkflowOutputSelector({ onOutputSelect={setStoredValue} disabled={disabled || isPreview} placeholder={placeholder} + outputFilter={outputFilter} valueMode='public' size='md' className='w-full' diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx index 9607c3b70a5..59658cb5ee4 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx @@ -1152,6 +1152,7 @@ function SubBlockComponent({ previewValue={previewValue as string[] | null | undefined} disabled={isDisabled} placeholder={config.placeholder} + outputFilter={config.outputFilter} /> ) diff --git a/apps/sim/blocks/blocks/slack.ts b/apps/sim/blocks/blocks/slack.ts index 5ff889943bf..b7d9502124a 100644 --- a/apps/sim/blocks/blocks/slack.ts +++ b/apps/sim/blocks/blocks/slack.ts @@ -3551,6 +3551,7 @@ export const SlackV2Block: BlockConfig = { 'Build Slack workflows with messages, conversations, files, reactions, pins, bookmarks, user groups, profiles, Lists, canvases, and Agent Sessions. Operations that need additional app scopes use custom Slack bots. Lists require lists:read/lists:write and a paid Slack plan. Native Sim connections retain their existing permissions. Page through list outputs explicitly.', bestPractices: `${SlackBlock.bestPractices} Native agent-session streaming uses a custom Slack bot and a supported trigger event. Enable streamResponse and select the intended outputs in streamOutputs; Sim Chat (mothership) streams its content output. The trigger owns the streamed reply, so another send needs a separate purpose. +To show an Agent's tool steps without posting its text (for example an analyst whose output a later block reviews), list that Agent in streamTimelineSources while streamOutputs keeps the block that posts the answer (a block cannot be in both), and optionally name its tools in streamToolLabels. The custom-bot manifest's baseline agent scopes are ${SLACK_AGENT_SCOPES.join(', ')}. Selected capabilities add their required scopes and event subscriptions. Verify the installed app's grants, resource access and event configuration; a saved credential or edited manifest alone does not prove access. streamIncludeToolCalls displays tool activity; it does not authorize tool execution. Configure Sim Chat's selected operations and their credentials separately. Choose streamIncludeThinking deliberately for the destination audience. Block Kit messages can contain buttons, selects and forms, but interactions require the app's interactivity request URL and the corresponding interaction trigger. Treat message events, button/select callbacks and modal submissions as separate paths. A control's action_id/value correlates work; runtime actor and state checks authorize it.`, diff --git a/apps/sim/blocks/types.ts b/apps/sim/blocks/types.ts index 0ff743d9594..54efa034522 100644 --- a/apps/sim/blocks/types.ts +++ b/apps/sim/blocks/types.ts @@ -393,6 +393,8 @@ export interface SubBlockConfig { min?: number max?: number columns?: string[] + /** Limits a `workflow-output-selector` to blocks of one type, each selecting `path`. */ + outputFilter?: { blockType: string; path: string } placeholder?: string /** * Conceals the stored value in the editor until the field is focused. diff --git a/apps/sim/lib/mothership/tools/display.ts b/apps/sim/lib/mothership/tools/display.ts index 52f2f52ada0..8f47aa93c93 100644 --- a/apps/sim/lib/mothership/tools/display.ts +++ b/apps/sim/lib/mothership/tools/display.ts @@ -1497,7 +1497,9 @@ export function getToolDisplayTitle(name: string, args?: Record } } - return TOOL_TITLES[name] ?? CLI_TOOL_TITLES[name] ?? humanizeToolName(name) + if (Object.hasOwn(TOOL_TITLES, name)) return TOOL_TITLES[name] + if (Object.hasOwn(CLI_TOOL_TITLES, name)) return CLI_TOOL_TITLES[name] + return humanizeToolName(name) } /** First positional after the synthetic CLI command path; shared by resource and operation labels. */ diff --git a/apps/sim/lib/webhooks/slack-execution-stream.test.ts b/apps/sim/lib/webhooks/slack-execution-stream.test.ts index 765d088719b..bd41a57a64f 100644 --- a/apps/sim/lib/webhooks/slack-execution-stream.test.ts +++ b/apps/sim/lib/webhooks/slack-execution-stream.test.ts @@ -49,6 +49,8 @@ const BASE_CONFIG: SlackStreamResponseConfig = { includeToolCalls: true, taskTitle: 'Running', taskDisplayMode: 'plan', + timelineSources: [], + toolLabels: {}, } function createLoggingSession() { @@ -729,6 +731,213 @@ describe('SlackExecutionStreamController', () => { controller.assertSucceeded() }) + describe('timeline sources', () => { + const TIMELINE_CONFIG: SlackStreamResponseConfig = { + ...BASE_CONFIG, + outputConfigs: [{ blockId: 'reply', path: 'result' }], + timelineSources: [{ workflowId: 'child-workflow', blockId: 'analyst' }], + toolLabels: { lc_cur: 'Reading AWS cost data' }, + } + const TIMELINE_EVENTS: AgentStreamEvent[] = [ + { type: 'tool_call_start', id: 'tool-1', name: 'mcp-6da535c1-lc_cur' }, + { type: 'tool_call_end', id: 'tool-1', name: 'mcp-6da535c1-lc_cur', status: 'success' }, + { type: 'tool_call_start', id: 'tool-2', name: 'mcp-6da535c1-lc_other' }, + { type: 'tool_call_end', id: 'tool-2', name: 'mcp-6da535c1-lc_other', status: 'success' }, + { type: 'text_delta', text: '{"secret":"analyst json"}', turn: 'pending' }, + { type: 'turn_end', turn: 'final' }, + ] + + async function streamTimeline( + controller: SlackExecutionStreamController, + events: AgentStreamEvent[] = TIMELINE_EVENTS + ) { + await controller.callbacks.onStream?.({ + blockId: 'child-workflow.analyst', + childWorkflowInstanceId: 'child-instance-1', + executionOrder: 2, + stream: createByteStream('{"secret":"analyst json"}'), + execution: { success: true, output: {} }, + clientStreamTransformed: false, + subscribe: ({ onEvent }) => { + for (const event of events) void onEvent(event) + return vi.fn() + }, + }) + } + + function allChunks(): SlackStreamChunk[] { + return [ + ...mockStartSlackAgentStream.mock.calls.flatMap((call) => call[2]), + ...mockAppendSlackAgentStream.mock.calls.flatMap((call) => call[3]), + ...mockStopSlackAgentStream.mock.calls.flatMap((call) => call[6] ?? []), + ] + } + + it('streams the source as a block selector so the executor streams it', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + expect(controller.selectedOutputs).toEqual(['reply_result', 'child-workflow.analyst_content']) + }) + + it('shows tool steps without the source text and posts the answer in the same message', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + await streamTimeline(controller) + await controller.callbacks.onBlockComplete?.('reply', 'Reply', 'function', { + output: { result: 'Reviewed answer' }, + executionOrder: 3, + executionTime: 1, + startedAt: '2026-11-24T00:00:00Z', + endedAt: '2026-11-24T00:00:01Z', + }) + await controller.finalize({ success: true, status: 'completed', output: {} }) + + controller.assertSucceeded() + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream).toHaveBeenCalledTimes(1) + const text = allChunks() + .filter((chunk) => chunk.type === 'markdown_text') + .map((chunk) => (chunk.type === 'markdown_text' ? chunk.text : '')) + .join('') + expect(text).toBe('Reviewed answer') + const toolTitles = allChunks().flatMap((chunk) => + chunk.type === 'task_update' && chunk.id.includes('-tool-') ? [chunk.title] : [] + ) + expect(new Set(toolTitles)).toEqual(new Set(['Reading AWS cost data', 'Lc Other'])) + expect(mockStopSlackAgentStream.mock.calls[0][3]).toBe('processing') + }) + + it('stops a timeline-only message once with an error status when the run fails', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + await streamTimeline(controller, [ + { type: 'tool_call_start', id: 'tool-1', name: 'mcp-6da535c1-lc_cur' }, + ]) + await controller.finalize({ success: false, output: {} }) + + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream.mock.calls[0][3]).toBe('suspended') + expect(mockStopSlackAgentStream.mock.calls[0][6]).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: 'task_update', title: 'Running', status: 'error' }), + expect.objectContaining({ + type: 'task_update', + id: expect.stringContaining('-tool-tool-1'), + status: 'error', + }), + ]) + ) + }) + + it('never overlaps appends from the timeline and the answer on the shared message', async () => { + let inFlight = 0 + let maxInFlight = 0 + mockAppendSlackAgentStream.mockImplementation(async () => { + inFlight++ + maxInFlight = Math.max(maxInFlight, inFlight) + for (let tick = 0; tick < 20; tick++) await Promise.resolve() + inFlight-- + }) + const { controller } = await createController({ + ...TIMELINE_CONFIG, + outputConfigs: [{ blockId: 'reply', path: 'content' }], + }) + await Promise.all([ + streamTimeline(controller), + controller.callbacks.onStream?.({ + blockId: 'reply', + executionOrder: 3, + stream: createByteStream(), + execution: { success: true, output: {} }, + clientStreamTransformed: false, + subscribe: ({ onEvent }) => { + void onEvent({ type: 'text_delta', text: 'Reviewed answer. ', turn: 'pending' }) + void onEvent({ type: 'turn_end', turn: 'final' }) + return vi.fn() + }, + }), + ]) + + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockAppendSlackAgentStream.mock.calls.length).toBeGreaterThan(1) + expect(maxInFlight).toBe(1) + }) + + it('still rejects a stream from a block in neither list', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + await expect( + controller.callbacks.onStream?.({ + blockId: 'other', + executionOrder: 1, + stream: createByteStream(), + execution: { success: true, output: {} }, + }) + ).rejects.toThrow('unselected block') + }) + }) + + describe('per-invocation outcomes', () => { + const unfinishedTool: AgentStreamEvent[] = [ + { type: 'tool_call_start', id: 'tool-1', name: 'read_file' }, + ] + + function streamEvents( + controller: SlackExecutionStreamController, + executionOrder: number, + events: AgentStreamEvent[] + ) { + return controller.callbacks.onStream?.({ + blockId: 'agent', + executionOrder, + stream: createByteStream(), + execution: { success: true, output: {} }, + clientStreamTransformed: false, + subscribe: ({ onEvent }) => { + for (const event of events) void onEvent(event) + return vi.fn() + }, + }) + } + + it('does not mark an earlier answer failed when a later one fails', async () => { + mockStartSlackAgentStream + .mockResolvedValueOnce({ channel: 'C123', ts: 'first' }) + .mockResolvedValueOnce({ channel: 'C123', ts: 'second' }) + const { controller } = await createController() + await streamEvents(controller, 1, [ + { type: 'text_delta', text: 'First answer', turn: 'pending' }, + { type: 'turn_end', turn: 'final' }, + ]) + await streamEvents(controller, 2, unfinishedTool) + await controller.finalize({ success: true, status: 'completed', output: {} }) + + const statusByTs = Object.fromEntries( + mockStopSlackAgentStream.mock.calls.map((call) => [call[2], call[3]]) + ) + expect(statusByTs).toEqual({ first: 'processing', second: 'suspended' }) + }) + + it('posts no empty reply for a later invocation after an earlier one failed', async () => { + const { controller } = await createController() + await streamEvents(controller, 1, unfinishedTool) + await streamEvents(controller, 2, []) + await controller.finalize({ success: true, status: 'completed', output: {} }) + + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream).toHaveBeenCalledTimes(1) + }) + + it('titles a tool whose name is an object property', async () => { + const { controller } = await createController({ ...BASE_CONFIG, toolLabels: {} }) + await streamEvents(controller, 1, [ + { type: 'tool_call_start', id: 'tool-1', name: 'toString' }, + { type: 'tool_call_end', id: 'tool-1', name: 'toString', status: 'success' }, + ]) + const toolChunk = mockAppendSlackAgentStream.mock.calls + .flatMap((call) => call[3] as SlackStreamChunk[]) + .find((chunk) => chunk.type === 'task_update' && chunk.id.includes('-tool-')) + expect(toolChunk).toMatchObject({ title: expect.any(String) }) + }) + }) + it('rejects credentials that do not belong to the workflow workspace', async () => { mockGetSlackBotCredential.mockResolvedValue({ botToken: 'xoxb-token', diff --git a/apps/sim/lib/webhooks/slack-execution-stream.ts b/apps/sim/lib/webhooks/slack-execution-stream.ts index d69be842105..2ea742ee0a7 100644 --- a/apps/sim/lib/webhooks/slack-execution-stream.ts +++ b/apps/sim/lib/webhooks/slack-execution-stream.ts @@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger' import { getValueAtPath, isRecordLike } from '@sim/utils/object' import { truncate } from '@sim/utils/string' import type { LoggingSession } from '@/lib/logs/execution/logging-session' +import { parseMcpToolTarget } from '@/lib/mcp/utils' import { getToolDisplayTitle } from '@/lib/mothership/tools/display' import { getSlackBotCredential } from '@/lib/oauth/credential-service' import { @@ -13,9 +14,10 @@ import { stopSlackAgentStream, } from '@/lib/webhooks/slack-agent-api' import { SlackDeliveryError } from '@/lib/webhooks/slack-delivery-error' -import type { - SlackStreamOutputConfig, - SlackStreamResponseConfig, +import { + SLACK_TIMELINE_SOURCE_PATH, + type SlackStreamBlockRef, + type SlackStreamResponseConfig, } from '@/lib/webhooks/slack-stream-config' import { registerSlackStreamSession, @@ -23,6 +25,7 @@ import { unregisterSlackStreamSession, } from '@/lib/webhooks/slack-stream-sessions' import { formatOutputSelector, scopeOutputBlockId } from '@/lib/workflows/streaming/output-selector' +import { isMcpTool } from '@/executor/constants' import type { BlockCompletionCallbackData, ExecutionCallbacks } from '@/executor/execution/types' import type { ExecutionResult, StreamingExecution } from '@/executor/types' import type { AgentStreamEvent } from '@/providers/stream-events' @@ -40,6 +43,8 @@ interface SlackMessageStream { textLength: number textComplete: boolean stopped: boolean + /** Settles after this message's latest append, so writers sharing it append in order. */ + writes: Promise } /** Prefer a nearby paragraph/sentence, then a whole word; only oversized words need hard cuts. */ @@ -126,6 +131,98 @@ export function resolveSlackReplyTarget(triggerInput: Record): } } +/** An MCP tool's label may be keyed by its own name rather than the server-scoped one. */ +function mcpToolName(name: string): string | undefined { + if (!isMcpTool(name)) return undefined + try { + return parseMcpToolTarget(name).toolName + } catch { + return undefined + } +} + +function toolTitle(name: string, labels: Record): string { + const ownName = Object.hasOwn(labels, name) ? name : mcpToolName(name) + const label = ownName !== undefined && Object.hasOwn(labels, ownName) ? labels[ownName] : '' + return truncate(label || getToolDisplayTitle(name), TASK_TEXT_LIMIT) +} + +/** Matches a configured block against the scoped block ID the executor reports. */ +function isBlock(blockId: string): (ref: SlackStreamBlockRef) => boolean { + return (ref) => + (ref.workflowId ? scopeOutputBlockId(ref.workflowId, ref.blockId) : ref.blockId) === blockId +} + +function markdownLength(chunks: SlackStreamChunk[]): number { + return chunks.reduce( + (length, chunk) => length + (chunk.type === 'markdown_text' ? chunk.text.length : 0), + 0 + ) +} + +async function openSlackMessage( + token: string, + target: SlackReplyTarget, + config: SlackStreamResponseConfig, + chunks: SlackStreamChunk[], + taskId: string | undefined, + signal?: AbortSignal +): Promise { + const started = await startSlackAgentStream(token, target, chunks, config.taskDisplayMode, signal) + return { + ...started, + taskId, + textLength: markdownLength(chunks), + textComplete: false, + stopped: false, + writes: Promise.resolve(), + } +} + +/** Stops one message, settling its task. Cleanup has its own deadline, so no abort signal. */ +async function stopMessage( + token: string, + message: SlackMessageStream, + title: string, + failed: boolean, + chunks: SlackStreamChunk[] +): Promise { + await stopSlackAgentStream( + token, + message.channel, + message.ts, + failed ? 'suspended' : 'processing', + undefined, + undefined, + message.taskId + ? [ + ...chunks, + { type: 'task_update', id: message.taskId, title, status: failed ? 'error' : 'complete' }, + ] + : chunks + ) + message.stopped = true +} + +/** + * The first message of an execution, owned and stopped by the controller. Timeline sources write + * their steps into it and the first answer invocation writes its text there too, so steps and + * answer read as one reply. A later answer starts its own message so two answers never interleave. + */ +interface SharedMessage { + message: Promise + hasAnswer: boolean + /** Only these invocations' outcomes decide how the shared message settles. */ + writers: Set +} + +/** Returns the shared message, or undefined when another answer already writes to it. */ +type AcquireSharedMessage = ( + writer: SlackInvocationStream, + forAnswer: boolean, + start: () => Promise +) => Promise | undefined + function formatOutput(value: unknown): string { if (typeof value === 'string') return value const serialized = JSON.stringify(value, null, 2) @@ -134,7 +231,10 @@ function formatOutput(value: unknown): string { } class SlackInvocationStream { + /** Every message this invocation writes to. */ private readonly messages: SlackMessageStream[] = [] + /** The messages this invocation started, and so stops. */ + private readonly ownedMessages = new Set() private answerBuffer = '' private acknowledgedAnswer = '' private thinking = '' @@ -155,8 +255,10 @@ class SlackInvocationStream { private readonly target: SlackReplyTarget, private readonly config: SlackStreamResponseConfig, private readonly taskId: string, - private readonly title: string, private readonly projectLiveText: (text: string) => Promise, + private readonly acquireSharedMessage: AcquireSharedMessage, + /** Shows tool steps and thinking only; the source's text never reaches Slack. */ + private readonly timelineOnly: boolean, private readonly signal?: AbortSignal ) {} @@ -171,40 +273,52 @@ class SlackInvocationStream { private async ensureStarted(): Promise { const current = this.messages.at(-1) if (current) return current - return this.startMessage( - [{ type: 'task_update', id: this.taskId, title: this.title, status: 'in_progress' }], - this.taskId - ) + const start = () => + openSlackMessage( + this.token, + this.target, + this.config, + [ + { + type: 'task_update', + id: this.taskId, + title: this.config.taskTitle, + status: 'in_progress', + }, + ], + this.taskId, + this.signal + ) + const shared = this.acquireSharedMessage(this, !this.timelineOnly, start) + const message = shared ? await shared : await start() + if (!shared) this.ownedMessages.add(message) + this.messages.push(message) + return message } - private async startMessage( - chunks: SlackStreamChunk[], - taskId?: string - ): Promise { - const started = await startSlackAgentStream( + private async startMessage(chunks: SlackStreamChunk[]): Promise { + const message = await openSlackMessage( this.token, this.target, + this.config, chunks, - this.config.taskDisplayMode, + undefined, this.signal ) - const textLength = chunks.reduce( - (length, chunk) => length + (chunk.type === 'markdown_text' ? chunk.text.length : 0), - 0 - ) - const message = { ...started, taskId, textLength, textComplete: false, stopped: false } + this.ownedMessages.add(message) this.messages.push(message) return message } private async append(chunks: SlackStreamChunk[], message?: SlackMessageStream): Promise { const target = message ?? (await this.ensureStarted()) - const textLength = chunks.reduce( - (length, chunk) => length + (chunk.type === 'markdown_text' ? chunk.text.length : 0), - 0 - ) + const textLength = markdownLength(chunks) try { - await appendSlackAgentStream(this.token, target.channel, target.ts, chunks, this.signal) + const write = target.writes.then(() => + appendSlackAgentStream(this.token, target.channel, target.ts, chunks, this.signal) + ) + target.writes = write.catch(() => {}) + await write target.textLength += textLength } catch (error) { logger.warn('Slack stream append failed', { @@ -366,7 +480,7 @@ class SlackInvocationStream { return { type: 'task_update', id: `${this.taskId}-tool-${id}`, - title: truncate(getToolDisplayTitle(tool.name), TASK_TEXT_LIMIT), + title: toolTitle(tool.name, this.config.toolLabels), status: tool.status, } } @@ -399,11 +513,25 @@ class SlackInvocationStream { this.failure ??= formatSlackApiFailure(error) } - finish(success: boolean): Promise { + get failed(): boolean { + return Boolean(this.failure) + } + + /** Error steps for this invocation's tools still running on `message`. */ + unfinishedToolChunks(message: SlackMessageStream): SlackStreamChunk[] { + return [...this.tools].flatMap(([id, tool]) => + tool.message === message && (tool.status === 'pending' || tool.status === 'in_progress') + ? [this.toolChunk(id, { ...tool, status: 'error' })] + : [] + ) + } + + /** Readies this response to stop: a successful empty answer still shows its settled task. */ + settle(success: boolean): Promise { return this.enqueue(async () => { if (this.stopAttempted) return if (this.messages.length === 0) { - if (this.failure || !success) return + if (this.failure || !success || this.timelineOnly) return await this.ensureStarted() } if ( @@ -414,34 +542,23 @@ class SlackInvocationStream { ) { this.failure ??= new Error('Slack delivery ended with unfinished tool calls') } + }) + } + + /** Stops the messages this invocation started; the controller stops the shared one. */ + stop(success: boolean): Promise { + return this.enqueue(async () => { + if (this.stopAttempted) return this.stopAttempted = true - for (const message of this.messages) { - const failed = Boolean(this.failure) || !success - const chunks: SlackStreamChunk[] = [...this.tools].flatMap(([id, tool]) => - tool.message === message && (tool.status === 'pending' || tool.status === 'in_progress') - ? [this.toolChunk(id, { ...tool, status: 'error' })] - : [] - ) - if (message.taskId) { - chunks.push({ - type: 'task_update', - id: message.taskId, - title: this.title, - status: failed ? 'error' : 'complete', - }) - } + for (const message of this.ownedMessages) { try { - /** Cleanup has its own deadline and attempts every part even if an earlier stop failed. */ - await stopSlackAgentStream( + await stopMessage( this.token, - message.channel, - message.ts, - failed ? 'suspended' : 'processing', - undefined, - undefined, - chunks + message, + this.config.taskTitle, + Boolean(this.failure) || !success, + this.unfinishedToolChunks(message) ) - message.stopped = true } catch (error) { this.recordFailure(error) } @@ -451,7 +568,7 @@ class SlackInvocationStream { assertSucceeded(): void { if (this.failure) throw this.failure - if (this.messages.some((message) => !message.stopped)) { + if ([...this.ownedMessages].some((message) => !message.stopped)) { throw new Error('Slack response stream was not stopped') } } @@ -465,6 +582,7 @@ export class SlackExecutionStreamController { private readonly target: SlackReplyTarget private readonly token: string private readonly invocations = new Map() + private sharedMessage?: SharedMessage private finalization?: Promise private finalized = false @@ -475,9 +593,14 @@ export class SlackExecutionStreamController { ) { this.token = token this.target = target - this.selectedOutputs = options.config.outputConfigs.map((output) => - formatOutputSelector(output.blockId, output.path, output.workflowId) - ) + this.selectedOutputs = [ + ...options.config.outputConfigs.map((output) => + formatOutputSelector(output.blockId, output.path, output.workflowId) + ), + ...options.config.timelineSources.map((source) => + formatOutputSelector(source.blockId, SLACK_TIMELINE_SOURCE_PATH, source.workflowId) + ), + ] this.callbacks = { onStream: (stream) => this.onStream(stream), onBlockComplete: (blockId, _blockName, _blockType, data) => @@ -514,13 +637,35 @@ export class SlackExecutionStreamController { return controller } - private selectedForBlock(blockId: string): SlackStreamOutputConfig[] { - return this.options.config.outputConfigs.filter((output) => { - const selectedBlockId = output.workflowId - ? scopeOutputBlockId(output.workflowId, output.blockId) - : output.blockId - return selectedBlockId === blockId - }) + private readonly acquireSharedMessage: AcquireSharedMessage = (writer, forAnswer, start) => { + if (!this.sharedMessage) { + this.sharedMessage = { message: start(), hasAnswer: forAnswer, writers: new Set([writer]) } + return this.sharedMessage.message + } + if (forAnswer) { + if (this.sharedMessage.hasAnswer) return undefined + this.sharedMessage.hasAnswer = true + } + this.sharedMessage.writers.add(writer) + return this.sharedMessage.message + } + + private createInvocation( + executionOrder: number, + childWorkflowInstanceId: string | undefined, + projectLiveText: (text: string) => Promise, + timelineOnly: boolean + ): SlackInvocationStream { + return new SlackInvocationStream( + this.token, + this.target, + this.options.config, + this.taskId(executionOrder, childWorkflowInstanceId), + projectLiveText, + this.acquireSharedMessage, + timelineOnly, + this.options.abortSignal + ) } private invocationKey( @@ -531,8 +676,12 @@ export class SlackExecutionStreamController { return `${blockId}:${childWorkflowInstanceId ?? executionOrder}` } + /** Unique per invocation: blocks of one child workflow instance share the shared message. */ private taskId(executionOrder: number, childWorkflowInstanceId?: string): string { - return `sim-${this.options.executionId}-${childWorkflowInstanceId ?? executionOrder}` + const invocation = childWorkflowInstanceId + ? `${childWorkflowInstanceId}-${executionOrder}` + : executionOrder + return `sim-${this.options.executionId}-${invocation}` } private recordFailure(error: unknown): Error { @@ -558,7 +707,9 @@ export class SlackExecutionStreamController { if (!stream.blockId || stream.executionOrder === undefined) { throw new Error('Slack streaming received a stream without invocation metadata') } - if (this.selectedForBlock(stream.blockId).length === 0) { + const { outputConfigs, timelineSources } = this.options.config + const timelineOnly = !outputConfigs.some(isBlock(stream.blockId)) + if (timelineOnly && !timelineSources.some(isBlock(stream.blockId))) { throw new Error(`Slack streaming received an unselected block: ${stream.blockId}`) } const key = this.invocationKey( @@ -569,18 +720,18 @@ export class SlackExecutionStreamController { if (this.invocations.has(key)) { throw new Error(`Duplicate Slack stream invocation: ${key}`) } - const invocation = new SlackInvocationStream( - this.token, - this.target, - this.options.config, - this.taskId(stream.executionOrder, stream.childWorkflowInstanceId), - this.options.config.taskTitle, + const invocation = this.createInvocation( + stream.executionOrder, + stream.childWorkflowInstanceId, (text) => this.projectLiveText(text, stream.displayResolvedSecretTraceProvenance), - this.options.abortSignal + timelineOnly ) this.invocations.set(key, invocation) - const answerFromEventSink = Boolean(stream.subscribe) && !stream.clientStreamTransformed + // A timeline source's text is drained for the executor but never read into Slack. + const answerFromEventSink = + !timelineOnly && Boolean(stream.subscribe) && !stream.clientStreamTransformed + const answerFromBytes = !timelineOnly && !answerFromEventSink const unsubscribe = stream.subscribe?.({ onEvent: async (event) => { if (!answerFromEventSink && event.type === 'text_delta') return @@ -593,11 +744,11 @@ export class SlackExecutionStreamController { while (true) { const { done, value } = await reader.read() if (done) break - if (!answerFromEventSink) { + if (answerFromBytes) { await invocation.appendProjectedBytes(decoder.decode(value, { stream: true })) } } - if (!answerFromEventSink) { + if (answerFromBytes) { const remainder = decoder.decode() if (remainder) await invocation.appendProjectedBytes(remainder) } @@ -617,7 +768,7 @@ export class SlackExecutionStreamController { private async onBlockComplete(blockId: string, data: BlockCompletionCallbackData): Promise { try { const selectedOutputBlockId = data.outputBlockId ?? blockId - const selected = this.selectedForBlock(selectedOutputBlockId) + const selected = this.options.config.outputConfigs.filter(isBlock(selectedOutputBlockId)) if (selected.length === 0) return const key = this.invocationKey( selectedOutputBlockId, @@ -641,14 +792,11 @@ export class SlackExecutionStreamController { : values.map(({ path, value }) => `*${path}*\n${formatOutput(value)}`).join('\n\n') const invocation = this.invocations.get(key) ?? - new SlackInvocationStream( - this.token, - this.target, - this.options.config, - this.taskId(data.executionOrder, data.childWorkflowInstanceId), - this.options.config.taskTitle, + this.createInvocation( + data.executionOrder, + data.childWorkflowInstanceId, async (value) => value, - this.options.abortSignal + false ) this.invocations.set(key, invocation) await invocation.reconcileSettledOutput(text) @@ -663,13 +811,22 @@ export class SlackExecutionStreamController { } private async finalizeOnce(result: ExecutionResult): Promise { - for (const invocation of this.invocations.values()) { - await invocation.finish( - !this.failure && - result.success && - result.status !== 'cancelled' && - result.status !== 'paused' - ) + const succeeded = () => + !this.failure && result.success && result.status !== 'cancelled' && result.status !== 'paused' + const invocations = [...this.invocations.values()] + // An invocation succeeds only if every one before it did, as when each settled in turn. + const successes = new Map() + let earlierFailed = false + for (const invocation of invocations) { + const success = succeeded() && !earlierFailed + successes.set(invocation, success) + await invocation.settle(success) + earlierFailed ||= invocation.failed + } + // The shared message is the reply's first, so it settles before any continuation. + await this.stopSharedMessage(invocations, successes) + for (const invocation of invocations) { + await invocation.stop(successes.get(invocation) === true) try { invocation.assertSucceeded() } catch (error) { @@ -698,6 +855,27 @@ export class SlackExecutionStreamController { this.finalized = true } + private async stopSharedMessage( + invocations: SlackInvocationStream[], + successes: ReadonlyMap + ): Promise { + if (!this.sharedMessage) return + try { + const message = await this.sharedMessage.message + await stopMessage( + this.token, + message, + this.options.config.taskTitle, + [...this.sharedMessage.writers].some( + (writer) => writer.failed || successes.get(writer) !== true + ), + invocations.flatMap((invocation) => invocation.unfinishedToolChunks(message)) + ) + } catch (error) { + this.recordFailure(error) + } + } + assertSucceeded(): void { if (this.failure) throw this.failure if (!this.finalized) throw new Error('Slack delivery has not been finalized') diff --git a/apps/sim/lib/webhooks/slack-stream-config.test.ts b/apps/sim/lib/webhooks/slack-stream-config.test.ts index 978fb43f8d9..6b1d7987b73 100644 --- a/apps/sim/lib/webhooks/slack-stream-config.test.ts +++ b/apps/sim/lib/webhooks/slack-stream-config.test.ts @@ -33,6 +33,8 @@ describe('Slack stream response config', () => { includeToolCalls: false, taskTitle: 'Working', taskDisplayMode: 'plan', + timelineSources: [], + toolLabels: {}, }) expect(readSlackStreamResponseConfig(providerConfig)).toEqual(normalized) expect(providerConfig.streamResponse).toBeUndefined() @@ -91,4 +93,91 @@ describe('Slack stream response config', () => { ).toThrow('Invalid Slack stream output selector') } ) + + describe('timeline sources', () => { + const blocks = { + 'agent-1': { id: 'agent-1', name: 'Analyst', type: 'agent' }, + 'fn-1': { id: 'fn-1', name: 'Format Answer', type: 'function' }, + } + + it('normalizes block-level sources and tool labels, and reads them back', () => { + const providerConfig: Record = { + eventType: 'message', + streamResponse: true, + streamOutputs: ['formatanswer.result'], + streamTimelineSources: ['analyst.content', `${CHILD_WORKFLOW_ID}.analyst`], + streamToolLabels: [ + { id: 'r1', cells: { Tool: ' lc_cur ', Label: ' Reading AWS cost data ' } }, + { id: 'r2', cells: { Tool: '', Label: 'ignored' } }, + ], + } + const normalized = normalizeSlackStreamResponseConfig(providerConfig, blocks) + replaceSlackStreamAuthoringConfig(providerConfig, normalized) + + expect(normalized?.timelineSources).toEqual([ + { blockId: 'agent-1' }, + { workflowId: CHILD_WORKFLOW_ID, blockId: 'analyst' }, + ]) + expect(normalized?.toolLabels).toEqual({ lc_cur: 'Reading AWS cost data' }) + expect(readSlackStreamResponseConfig(providerConfig)).toEqual(normalized) + expect(providerConfig.streamTimelineSources).toBeUndefined() + expect(providerConfig.streamToolLabels).toBeUndefined() + }) + + it('reads configs deployed before timeline sources existed', () => { + const config = readSlackStreamResponseConfig({ + streamResponseConfig: { + enabled: true, + outputConfigs: [{ blockId: 'block', path: 'content' }], + includeThinking: false, + includeToolCalls: true, + taskDisplayMode: 'timeline', + }, + }) + expect(config?.timelineSources).toEqual([]) + expect(config?.toolLabels).toEqual({}) + }) + + it('rejects a block that is both an answer output and a timeline source', () => { + expect(() => + normalizeSlackStreamResponseConfig( + { + eventType: 'message', + streamResponse: true, + streamOutputs: ['analyst.content'], + streamTimelineSources: ['analyst'], + }, + blocks + ) + ).toThrow('both') + }) + + it('rejects a timeline source that is not an Agent block', () => { + expect(() => + normalizeSlackStreamResponseConfig( + { + eventType: 'message', + streamResponse: true, + streamOutputs: ['analyst.content'], + streamTimelineSources: ['formatanswer'], + }, + blocks + ) + ).toThrow('must be an Agent block') + }) + + it('rejects a timeline source path other than the Agent content', () => { + expect(() => + normalizeSlackStreamResponseConfig( + { + eventType: 'message', + streamResponse: true, + streamOutputs: ['formatanswer.result'], + streamTimelineSources: ['analyst.model'], + }, + blocks + ) + ).toThrow('timeline source') + }) + }) }) diff --git a/apps/sim/lib/webhooks/slack-stream-config.ts b/apps/sim/lib/webhooks/slack-stream-config.ts index 175435902ed..a907646dfd0 100644 --- a/apps/sim/lib/webhooks/slack-stream-config.ts +++ b/apps/sim/lib/webhooks/slack-stream-config.ts @@ -1,4 +1,4 @@ -import { isRecordLike } from '@sim/utils/object' +import { isRecordLike, toRecordOrNull } from '@sim/utils/object' import { formatInternalOutputSelector, parsePublicOutputSelector, @@ -7,9 +7,7 @@ import { import { normalizeName } from '@/executor/constants' import { SLACK_STREAM_RESPONSE_EVENTS } from '@/triggers/slack/shared' -export interface SlackStreamOutputConfig { - workflowId?: string - blockId: string +interface SlackStreamOutputConfig extends SlackStreamBlockRef { path: string } @@ -20,9 +18,24 @@ export interface SlackStreamResponseConfig { includeToolCalls: boolean taskTitle: string taskDisplayMode: 'timeline' | 'plan' + /** Agent blocks whose tool steps (and thinking, when enabled) are shown without their text. */ + timelineSources: SlackStreamBlockRef[] + /** Display titles for tool steps, keyed by tool name (an MCP tool by its own name). */ + toolLabels: Record +} + +/** A block of the triggered workflow, or of a child workflow when `workflowId` is set. */ +export interface SlackStreamBlockRef { + workflowId?: string + blockId: string } +type SlackStreamAuthoringBlocks = Record + const SLACK_TASK_TITLE_LIMIT = 256 +/** A timeline source streams through its Agent's answer output, which is never posted. */ +export const SLACK_TIMELINE_SOURCE_PATH = 'content' +const SLACK_TIMELINE_SOURCE_BLOCK_TYPE = 'agent' function parseSlackOutputSelector( selector: string, @@ -39,10 +52,56 @@ function parseSlackOutputSelector( return { ...parsed, blockId } } +/** Accepts `` or `.`, with or without the `.content` the picker adds. */ +function parseSlackTimelineSource( + selector: string, + blocks: SlackStreamAuthoringBlocks, + currentBlockRefs: ReadonlySet +): SlackStreamBlockRef { + const suffix = `.${SLACK_TIMELINE_SOURCE_PATH}` + const parsed = parsePublicOutputSelector( + selector.endsWith(suffix) ? selector : `${selector}${suffix}`, + { currentBlockRefs } + ) + if (parsed.path !== SLACK_TIMELINE_SOURCE_PATH) { + throw new Error(`Slack timeline source must select an Agent block: ${selector}`) + } + if (parsed.workflowId) return { workflowId: parsed.workflowId, blockId: parsed.blockId } + const blockId = resolveOutputBlockRef(parsed.blockId, blocks) + if (blocks[blockId]?.type !== SLACK_TIMELINE_SOURCE_BLOCK_TYPE) { + throw new Error(`Slack timeline source must be an Agent block: ${selector}`) + } + return { blockId } +} + +function sameBlock(a: SlackStreamBlockRef, b: SlackStreamBlockRef): boolean { + return a.blockId === b.blockId && a.workflowId === b.workflowId +} + +/** Reads the editor's Tool/Label table, skipping incomplete rows. */ +function parseSlackToolLabels(value: unknown): Record { + if (value === undefined || value === null || value === '') return {} + if (!Array.isArray(value)) throw new Error('Slack tool step labels must be a table') + const labels: Record = {} + for (const row of value) { + const cells = isRecordLike(row) ? toRecordOrNull(row.cells) : null + const tool = typeof cells?.Tool === 'string' ? cells.Tool.trim() : '' + const label = typeof cells?.Label === 'string' ? cells.Label.trim() : '' + if (!tool || !label) continue + if (label.length > SLACK_TASK_TITLE_LIMIT) { + throw new Error( + `Slack tool step label for ${tool} must be ${SLACK_TASK_TITLE_LIMIT} characters or fewer` + ) + } + labels[tool] = label + } + return labels +} + /** Converts trigger authoring fields into the durable Slack streaming contract. */ export function normalizeSlackStreamResponseConfig( providerConfig: Record, - blocks: Record + blocks: SlackStreamAuthoringBlocks ): SlackStreamResponseConfig | null { if (providerConfig.streamResponse !== true) return null @@ -83,16 +142,63 @@ export function normalizeSlackStreamResponseConfig( if (block.name) currentBlockRefs.add(normalizeName(block.name)) } + const rawTimelineSources = providerConfig.streamTimelineSources ?? [] + if (!Array.isArray(rawTimelineSources)) { + throw new Error('Slack timeline sources must be a list of Agent blocks') + } + const outputConfigs = selectors.map((selector) => + parseSlackOutputSelector(selector, blocks, currentBlockRefs) + ) + const timelineSources = rawTimelineSources.map((value) => { + if (typeof value !== 'string' || !value) { + throw new Error('Slack timeline sources must be non-empty strings') + } + const source = parseSlackTimelineSource(value, blocks, currentBlockRefs) + if (outputConfigs.some((output) => sameBlock(output, source))) { + throw new Error(`A block cannot be both a streamed output and a timeline source: ${value}`) + } + return source + }) + return { enabled: true, - outputConfigs: selectors.map((selector) => - parseSlackOutputSelector(selector, blocks, currentBlockRefs) - ), + outputConfigs, includeThinking: providerConfig.streamIncludeThinking === true, includeToolCalls: providerConfig.streamIncludeToolCalls !== false, taskTitle, taskDisplayMode, + timelineSources, + toolLabels: parseSlackToolLabels(providerConfig.streamToolLabels), + } +} + +/** Validates a persisted block reference; `kind` names it in errors. */ +function readBlockRef(value: unknown, kind: string): SlackStreamBlockRef { + if (!isRecordLike(value) || typeof value.blockId !== 'string' || !value.blockId) { + throw new Error(`Persisted Slack ${kind} is missing a block ID`) } + if (value.workflowId === undefined) return { blockId: value.blockId } + if (typeof value.workflowId !== 'string' || !value.workflowId) { + throw new Error(`Persisted Slack ${kind} has an invalid workflow ID`) + } + return { workflowId: value.workflowId, blockId: value.blockId } +} + +function readTimelineSources(value: unknown): SlackStreamBlockRef[] { + if (value === undefined) return [] + if (!Array.isArray(value)) throw new Error('Persisted Slack timeline sources are invalid') + return value.map((source) => readBlockRef(source, 'timeline source')) +} + +function readToolLabels(value: unknown): Record { + if (value === undefined) return {} + if (!isRecordLike(value)) throw new Error('Persisted Slack tool step labels are invalid') + return Object.fromEntries( + Object.entries(value).map(([tool, label]) => { + if (typeof label !== 'string') throw new Error('Persisted Slack tool step labels are invalid') + return [tool, label] + }) + ) } /** Reads and validates the normalized config stored on a deployed webhook. */ @@ -108,28 +214,13 @@ export function readSlackStreamResponseConfig( throw new Error('Persisted Slack stream configuration has no outputs') } const outputConfigs = value.outputConfigs.map((output) => { - if (!isRecordLike(output) || typeof output.blockId !== 'string' || !output.blockId) { - throw new Error('Persisted Slack stream output is missing a block ID') - } - if (typeof output.path !== 'string' || !output.path) { + const ref = readBlockRef(output, 'stream output') + const path = isRecordLike(output) ? output.path : undefined + if (typeof path !== 'string' || !path) { throw new Error('Persisted Slack stream output is missing an output path') } - if ( - output.workflowId !== undefined && - (typeof output.workflowId !== 'string' || !output.workflowId) - ) { - throw new Error('Persisted Slack stream output has an invalid workflow ID') - } - formatInternalOutputSelector( - output.blockId, - output.path, - typeof output.workflowId === 'string' ? output.workflowId : undefined - ) - return { - ...(typeof output.workflowId === 'string' ? { workflowId: output.workflowId } : {}), - blockId: output.blockId, - path: output.path, - } + formatInternalOutputSelector(ref.blockId, path, ref.workflowId) + return { ...ref, path } }) if (typeof value.includeThinking !== 'boolean' || typeof value.includeToolCalls !== 'boolean') { throw new Error('Persisted Slack stream visibility settings are invalid') @@ -151,6 +242,8 @@ export function readSlackStreamResponseConfig( includeToolCalls: value.includeToolCalls, taskTitle, taskDisplayMode: value.taskDisplayMode, + timelineSources: readTimelineSources(value.timelineSources), + toolLabels: readToolLabels(value.toolLabels), } } @@ -175,4 +268,6 @@ export function replaceSlackStreamAuthoringConfig( providerConfig.streamIncludeToolCalls = undefined providerConfig.streamTaskTitle = undefined providerConfig.streamTaskDisplayMode = undefined + providerConfig.streamTimelineSources = undefined + providerConfig.streamToolLabels = undefined } diff --git a/apps/sim/lib/workflows/streaming/nested-output-options.test.ts b/apps/sim/lib/workflows/streaming/nested-output-options.test.ts index 8010fc1547f..f8d571f4e5f 100644 --- a/apps/sim/lib/workflows/streaming/nested-output-options.test.ts +++ b/apps/sim/lib/workflows/streaming/nested-output-options.test.ts @@ -17,6 +17,7 @@ import { buildWorkflowOutputOptions, collectReferencedWorkflowIds, getWorkflowInvocationTarget, + selectBlockPathOptions, } from '@/lib/workflows/streaming/nested-output-options' function block(id: string, type: string, name: string, subBlocks = {}, data = {}) { @@ -105,4 +106,38 @@ describe('nested workflow output options', () => { }, ]) }) + + it('offers an Agent whose response format replaces its content output', () => { + const option = (blockId: string, blockType: string, path: string, workflowId?: string) => ({ + id: `${blockId}_${path}`, + label: `${blockId}.${path}`, + workflowId, + blockId, + blockName: blockId === 'a1' ? 'Analyst' : 'Formatter', + blockType, + groupKey: workflowId ? `invoke/${blockId}` : blockId, + groupLabel: blockId, + path, + menuPath: [], + }) + const options = [ + option('a1', 'agent', 'verdict', 'child-workflow'), + option('a1', 'agent', 'reasons', 'child-workflow'), + option('f1', 'function', 'result'), + ] + + expect( + selectBlockPathOptions(options, 'agent', 'content').map(({ id, label, path }) => ({ + id, + label, + path, + })) + ).toEqual([ + { + id: 'child-workflow.a1_content', + label: 'child-workflow.analyst.content', + path: 'content', + }, + ]) + }) }) diff --git a/apps/sim/lib/workflows/streaming/nested-output-options.ts b/apps/sim/lib/workflows/streaming/nested-output-options.ts index 1ec3ef71908..0ea7e086f71 100644 --- a/apps/sim/lib/workflows/streaming/nested-output-options.ts +++ b/apps/sim/lib/workflows/streaming/nested-output-options.ts @@ -184,3 +184,27 @@ export function buildWorkflowOutputMenu( return roots } + +/** + * One option per block of `blockType`, selecting `path` even when the block does not list it. + * An Agent with a response format lists its schema fields instead of `content`, yet still streams + * through `content`. + */ +export function selectBlockPathOptions( + options: readonly WorkflowOutputOption[], + blockType: string, + path: string +): WorkflowOutputOption[] { + const byBlock = new Map() + for (const option of options) { + if (option.blockType !== blockType || byBlock.has(option.groupKey)) continue + const blockName = normalizeName(option.blockName || `block-${option.blockId}`) + byBlock.set(option.groupKey, { + ...option, + id: formatInternalOutputSelector(option.blockId, path, option.workflowId), + label: formatPublicOutputSelector(blockName, path, option.workflowId), + path, + }) + } + return [...byBlock.values()] +} diff --git a/apps/sim/triggers/slack/oauth.ts b/apps/sim/triggers/slack/oauth.ts index d043d329a1f..74ce6dd8d02 100644 --- a/apps/sim/triggers/slack/oauth.ts +++ b/apps/sim/triggers/slack/oauth.ts @@ -204,6 +204,39 @@ export const slackOAuthTrigger: TriggerConfig = { }, reactiveCondition: CUSTOM_BOT_REACTIVE_CONDITION, }, + { + id: 'streamTimelineSources', + title: 'Show progress from', + type: 'workflow-output-selector', + placeholder: 'Select Agent blocks', + outputFilter: { blockType: 'agent', path: 'content' }, + description: + 'Agent blocks, including ones in child workflows, whose tool steps appear in the reply while they run. Their text is never posted. No steps appear when PII block-output redaction is on.', + required: false, + mode: 'trigger', + condition: { + field: 'streamResponse', + value: true, + and: { field: 'eventType', value: SLACK_STREAM_RESPONSE_EVENTS }, + }, + reactiveCondition: CUSTOM_BOT_REACTIVE_CONDITION, + }, + { + id: 'streamToolLabels', + title: 'Tool step labels', + type: 'table', + columns: ['Tool', 'Label'], + description: + 'Optional names for tool steps, keyed by tool name (an MCP tool by its own name, like lc_cur). Unlisted tools use a generated name.', + required: false, + mode: 'trigger', + condition: { + field: 'streamResponse', + value: true, + and: { field: 'eventType', value: SLACK_STREAM_RESPONSE_EVENTS }, + }, + reactiveCondition: CUSTOM_BOT_REACTIVE_CONDITION, + }, { id: 'streamTaskTitle', title: 'Response status label', diff --git a/packages/workflow-sdk/test/fixtures/catalog.json b/packages/workflow-sdk/test/fixtures/catalog.json index e4edcebb700..c6508bcec59 100644 --- a/packages/workflow-sdk/test/fixtures/catalog.json +++ b/packages/workflow-sdk/test/fixtures/catalog.json @@ -30206,6 +30206,54 @@ } } }, + { + "id": "streamTimelineSources", + "type": "workflow-output-selector", + "valueKind": "array", + "storage": "native", + "title": "Show progress from", + "mode": "trigger", + "surface": "trigger", + "condition": { + "field": "streamResponse", + "value": true, + "and": { + "field": "eventType", + "value": [ + "message", + "app_mention" + ] + } + }, + "required": false + }, + { + "id": "streamToolLabels", + "type": "table", + "valueKind": "array", + "storage": "native", + "structured": "tableRows", + "title": "Tool step labels", + "mode": "trigger", + "surface": "trigger", + "condition": { + "field": "streamResponse", + "value": true, + "and": { + "field": "eventType", + "value": [ + "message", + "app_mention" + ] + } + }, + "required": false, + "valueShape": "json", + "columns": [ + "Tool", + "Label" + ] + }, { "id": "streamTaskTitle", "type": "short-input", @@ -33323,6 +33371,52 @@ } } }, + { + "id": "streamTimelineSources", + "type": "workflow-output-selector", + "valueKind": "array", + "storage": "native", + "title": "Show progress from", + "mode": "trigger", + "condition": { + "field": "streamResponse", + "value": true, + "and": { + "field": "eventType", + "value": [ + "message", + "app_mention" + ] + } + }, + "required": false + }, + { + "id": "streamToolLabels", + "type": "table", + "valueKind": "array", + "storage": "native", + "structured": "tableRows", + "title": "Tool step labels", + "mode": "trigger", + "condition": { + "field": "streamResponse", + "value": true, + "and": { + "field": "eventType", + "value": [ + "message", + "app_mention" + ] + } + }, + "required": false, + "valueShape": "json", + "columns": [ + "Tool", + "Label" + ] + }, { "id": "streamTaskTitle", "type": "short-input",