π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(conversation): break image tool results out of the collapsed workflow (#19045)
Inneid3c812996ae1
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 7c8483e7021..f80473351aa 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -2000,6 +2000,46 @@ A stale version means the server needs a real process restart (PROJECT.md Β§6),reload. Gate the first evidence-bearing call on this row, not on the edit's timestamp βotherwise the round publishes new-prompt claims backed by old-prompt output.+#### The user's Vite serves a `node_modules` that a reinstall already replaced β every `.vite/deps` 504s, the page is black++**Situation:** the user's own `bun run dev` is up (Next answers, auth is green), but+the SPA never mounts: `#root` has 0 children, no console error, and every+`/node_modules/.vite/deps/*.js` request returns 504. `ls node_modules/.vite` shows no+`deps/` directory and a sibling `node_modules/.old_modules-<hash>/` exists.++**Doesn't work:** waiting for the optimizer, reloading, or blaming the change under+test. That Vite process predates a `pnpm install` that moved the old tree aside; its+dep cache is gone for good and HMR cannot recover it.++**Works:** leave the user's process alone and start an isolated SPA on a free port+against the same backend β `PORT=3010 SPA_PORT=<free> bun run dev:spa` from the repo+root. `localhost` cookies are port-agnostic, so the seeded `lobehub-dev` session is+already signed in there. Prove identity before capturing (fetch the changed module from+the new Vite origin and grep the change's marker), stop only that pid at teardown, and+tell the user to restart their `dev:spa`.++#### Every agent/topic read returns 500 `Failed query: select β¦ from "agents"` β the `.env` database is behind the repo's migrations++**Situation:** with the user's `.env` backend, opening a conversation shows+"Failed to load agent settings"; `agent.getBuiltinAgent` and `topic.queryTopics`+are 500 with a `Failed query` whose column list includes fields the table lacks.++**Doesn't work:** reading the error tail (the pg cause is not included) or assuming+the change under test broke the server.++**Works:** compare the database's migration count with the repo's:++```bash+docker exec -c 'echo $POSTGRES_USER $POSTGRES_DB' < pg-container > sh # never read .env for this+docker exec -U "select count(*) from drizzle.__drizzle_migrations" < pg-container > psql < user > -d < db > -Atc+ls packages/database/migrations | grep -c '\.sql$'+```++A gap means the running canary server expects columns the DB never got. This is the+user's database: surface it at the plan gate and run `bun run db:migrate` (it loads+`.env` itself) only with their authorization; the isolated alternative is a worktree+with a second Next against the managed `:5434` test DB.+#### Server-side reads of local S3 evidence are blocked by SSRF protection β private IPs must be allowed explicitly**Situation:** verifying any capability where the **server** reads back an uploadeddiff --git a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.tsindex 58b12af9978..22076773911 100644--- a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts+++ b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts@@ -136,6 +136,97 @@ describe('partitionAssistantGroupBlocks', () => {expect(segments.map(({ kind }) => kind)).toEqual(['workflow', 'answer']);});+ it('breaks a breakout tool out of the workflow as its own standalone segment', () => {+ const isBreakoutTool = (candidate: { id: string }) => candidate.id === 'read-image';+ const { segments } = partitionAssistantGroupBlocks(+ [+ block('step-1', 'Looking.', { tools: [tool('bash-1')] }),+ block('step-2', 'Checking the screenshot.', {+ reasoning: { content: 'thinking' },+ tools: [tool('bash-2'), tool('read-image'), tool('bash-3')],+ }),+ block('step-3', '', { tools: [tool('bash-4')] }),+ ],+ { isBreakoutTool, isGenerating: false },+ );++ expect(segments.map(({ kind }) => kind)).toEqual(['workflow', 'workflow', 'workflow']);+ expect(segments[0]).toMatchObject({+ blocks: [+ { id: 'step-1' },+ {+ content: 'Checking the screenshot.',+ id: 'step-2',+ projection: 'workflow',+ reasoning: { content: 'thinking' },+ tools: [expect.objectContaining({ id: 'bash-2' })],+ },+ ],+ kind: 'workflow',+ });+ expect(segments[1]).toMatchObject({+ blocks: [+ {+ content: '',+ id: 'step-2',+ projection: 'workflow',+ reasoning: undefined,+ tools: [expect.objectContaining({ id: 'read-image' })],+ },+ ],+ kind: 'workflow',+ standalone: true,+ });+ expect(segments[2]).toMatchObject({+ blocks: [+ {+ content: '',+ id: 'step-2',+ projection: 'workflow',+ tools: [expect.objectContaining({ id: 'bash-3' })],+ },+ { id: 'step-3' },+ ],+ kind: 'workflow',+ });+ expect(+ segments.flatMap((segment) =>+ segment.kind === 'workflow' ? segment.blocks.map((b) => b.projectionKey) : [],+ ),+ ).toEqual([undefined, 'step-2__bash-2', 'step-2__read-image', 'step-2__bash-3', undefined]);+ });++ it('keeps a workflow block carrying images standalone', () => {+ const { segments } = partitionAssistantGroupBlocks(+ [+ block('step-1', '', { tools: [tool('bash-1')] }),+ block('step-2', '', {+ imageList: [{ alt: 'img', id: 'img', url: 'https://x/img.png' }],+ tools: [tool('bash-2')],+ }),+ block('step-3', '', { tools: [tool('bash-3')] }),+ ],+ { isGenerating: false },+ );++ expect(segments.map((segment) => segment.kind === 'workflow' && !!segment.standalone)).toEqual([+ false,+ true,+ false,+ ]);+ });++ it('does not break out a breakout tool from a single-tool turn', () => {+ const { segments } = partitionAssistantGroupBlocks(+ [block('step-1', 'Reading.', { tools: [tool('read-image')] })],+ { isBreakoutTool: () => true, isGenerating: false },+ );++ expect(segments).toEqual([+ { blocks: [block('step-1', 'Reading.', { tools: [tool('read-image')] })], kind: 'workflow' },+ ]);+ });+it('keeps a short post-tool status in workflow while generating', () => {const { postToolTailPromoted, segments } = partitionAssistantGroupBlocks([diff --git a/packages/conversation-flow/src/assistantGroupContent.ts b/packages/conversation-flow/src/assistantGroupContent.tsindex 9662fda95e9..d81681c6c83 100644--- a/packages/conversation-flow/src/assistantGroupContent.ts+++ b/packages/conversation-flow/src/assistantGroupContent.ts@@ -1,5 +1,9 @@import { LOADING_FLAT } from '@lobechat/const';-import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';+import type {+ AssistantContentBlock,+ ChatToolPayloadWithResult,+ UIChatMessage,+} from '@lobechat/types';const ASSISTANT_GROUP_STATUS_TEXT_MAX_LENGTH = 100;const MARKDOWN_HEADING_MAX_LEVEL = 6;@@ -13,6 +17,8 @@ export type AssistantGroupBlockProjection = 'answer' | 'workflow';*/export interface AssistantGroupSemanticBlock extends AssistantContentBlock {projection?: AssistantGroupBlockProjection;+ /** Set when one block's tools are split into several workflow sub-blocks. */+ projectionKey?: string;}export interface AssistantGroupAnswerSegment<@@ -27,6 +33,8 @@ export interface AssistantGroupWorkflowSegment<> {blocks: Block[];kind: 'workflow';+ /** Rendered on its own between neighbouring workflow runs (e.g. an image result). */+ standalone?: boolean;}export type AssistantGroupSegment<@@ -34,6 +42,8 @@ export type AssistantGroupSegment<> = AssistantGroupAnswerSegment<Block> | AssistantGroupWorkflowSegment<Block>;export interface PartitionAssistantGroupOptions {+ /** Tools whose result should surface between collapsed workflow runs instead of inside one. */+ isBreakoutTool?: (tool: ChatToolPayloadWithResult) => boolean;isGenerating: boolean;/*** Whether all non-intervention tools have settled. Only used while generating@@ -74,7 +84,7 @@ const isTrailingReasoningCandidate = (block: AssistantContentBlock): boolean =>const createProjectedBlock = (block: AssistantContentBlock,projection: AssistantGroupBlockProjection,- overrides: Partial<AssistantContentBlock>,+ overrides: Partial<AssistantGroupSemanticBlock>,): AssistantGroupSemanticBlock => ({...block,...overrides,@@ -91,15 +101,53 @@ const appendAnswerBlock = (const appendWorkflowBlock = (segments: AssistantGroupSegment[],block: AssistantGroupSemanticBlock,+ standalone = false,) => {const lastSegment = segments.at(-1);- if (lastSegment?.kind === 'workflow') {+ if (lastSegment?.kind === 'workflow' && !lastSegment.standalone && !standalone) {lastSegment.blocks.push(block);return;}- segments.push({ blocks: [block], kind: 'workflow' });+ segments.push({ blocks: [block], kind: 'workflow', ...(standalone && { standalone }) });+};++const hasImages = (block: AssistantContentBlock): boolean => !!block.imageList?.length;++const appendWorkflowToolRuns = (+ segments: AssistantGroupSegment[],+ block: AssistantGroupSemanticBlock,+ isBreakoutTool: NonNullable<PartitionAssistantGroupOptions['isBreakoutTool']>,+) => {+ const tools = block.tools ?? [];+ if (!tools.some(isBreakoutTool)) {+ appendWorkflowBlock(segments, block, hasImages(block));+ return;+ }++ const runs: { standalone: boolean; tools: ChatToolPayloadWithResult[] }[] = [];+ for (const tool of tools) {+ const last = runs.at(-1);+ if (isBreakoutTool(tool)) runs.push({ standalone: true, tools: [tool] });+ else if (last && !last.standalone) last.tools.push(tool);+ else runs.push({ standalone: false, tools: [tool] });+ }++ runs.forEach((run, index) => {+ const head = index === 0;+ appendWorkflowBlock(+ segments,+ createProjectedBlock(block, 'workflow', {+ content: head ? block.content : '',+ imageList: head ? block.imageList : undefined,+ projectionKey: `${block.id}__${run.tools[0]!.id}`,+ reasoning: head ? block.reasoning : undefined,+ tools: run.tools,+ }),+ run.standalone || (head && hasImages(block)),+ );+ });};/**@@ -127,7 +175,13 @@ const appendWorkflowRangeBlock = (segments: AssistantGroupSegment[],block: AssistantContentBlock,collapsesIntoWorkflow: boolean,+ isBreakoutTool: PartitionAssistantGroupOptions['isBreakoutTool'],) => {+ const appendWorkflowRest = (rest: AssistantGroupSemanticBlock) => {+ if (!collapsesIntoWorkflow) appendWorkflowBlock(segments, rest);+ else appendWorkflowToolRuns(segments, rest, isBreakoutTool ?? (() => false));+ };+if (block.error) {if (hasTools(block)) {appendWorkflowBlock(@@ -161,8 +215,7 @@ const appendWorkflowRangeBlock = (tools: undefined,}),);- appendWorkflowBlock(- segments,+ appendWorkflowRest(createProjectedBlock(block, 'workflow', {content: '',imageList: undefined,@@ -172,7 +225,7 @@ const appendWorkflowRangeBlock = (return;}- appendWorkflowBlock(segments, block);+ appendWorkflowRest(block);};const appendPostToolBlocks = (@@ -274,7 +327,7 @@ export const partitionAssistantGroupBlocks = (const workflowEndIndex = answerSplitIndex ?? blocks.length;for (const block of blocks.slice(firstToolIndex, workflowEndIndex)) {- appendWorkflowRangeBlock(segments, block, totalToolCount > 1);+ appendWorkflowRangeBlock(segments, block, totalToolCount > 1, options.isBreakoutTool);}for (const block of blocks.slice(workflowEndIndex)) {@@ -288,7 +341,7 @@ export const partitionAssistantGroupBlocks = (}for (const block of blocks.slice(firstToolIndex, lastToolIndex + 1)) {- appendWorkflowRangeBlock(segments, block, totalToolCount > 1);+ appendWorkflowRangeBlock(segments, block, totalToolCount > 1, options.isBreakoutTool);}appendPostToolBlocks(segments, blocks.slice(lastToolIndex + 1));diff --git a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx b/src/features/Conversation/Messages/AssistantGroup/Tools.tsxindex abbb1228fd8..44d74663027 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx@@ -9,16 +9,19 @@ import { shouldRenderToolCall } from './toolRenderRules';interface ToolsRendererProps {disableEditing?: boolean;messageId: string;+ toolIds?: string[];}-export const Tools = memo<ToolsRendererProps>(({ disableEditing, messageId }) => {+export const Tools = memo<ToolsRendererProps>(({ disableEditing, messageId, toolIds }) => {// Subscribe only to the visible tool ids of this block. Streaming chunks that// change a single tool's args/result do not invalidate this string array, so// sibling Tool components stay isolated and only the changed one re-renders.const visibleToolCallIds = useConversationStore((s) => {const tools = dataSelectors.getToolsInBlock(messageId)(s);if (!tools || tools.length === 0) return [];- return tools.filter(shouldRenderToolCall).map((t) => t.id);+ return tools+ .filter((t) => shouldRenderToolCall(t) && (!toolIds || toolIds.includes(t.id)))+ .map((t) => t.id);}, isEqual);if (visibleToolCallIds.length === 0) return null;diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsxindex b93b1e055f2..581f0c2d4a7 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx@@ -31,6 +31,7 @@ const ContentBlock = memo<ContentBlockProps>(disableEditing,disableMarkdownStreaming,hasToolsOverride,+ projectionKey,}) => {const errorContent = useErrorContent(error);const showImageItems = !!imageList && imageList.length > 0;@@ -117,7 +118,11 @@ const ContentBlock = memo<ContentBlockProps>({hasTools && (<SafeBoundary>- <Tools disableEditing={disableEditing} messageId={id} />+ <Tools+ disableEditing={disableEditing}+ messageId={id}+ toolIds={projectionKey ? tools?.map((tool) => tool.id) : undefined}+ /></SafeBoundary>)}diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsxindex fe56578f533..45f35945f5c 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx@@ -346,6 +346,65 @@ describe('Group', () => {]);});+ it('breaks an image-bearing tool out between two workflow folds', () => {+ const { container } = render(+ <Group+ isLatestItem+ id="assistant-1"+ messageIndex={0}+ blocks={[+ blk({+ content: 'Inspecting.',+ id: 'block-1',+ tools: [+ { apiName: 'Bash', id: 'tool-0', identifier: 'claude-code' } as any,+ { apiName: 'Bash', id: 'tool-1', identifier: 'claude-code' } as any,+ {+ apiName: 'Read',+ id: 'tool-2',+ identifier: 'claude-code',+ result: {+ content: 'ok',+ id: 'r2',+ state: { images: [{ url: 'https://x/a.png' }] },+ },+ } as any,+ { apiName: 'Bash', id: 'tool-3', identifier: 'claude-code' } as any,+ ],+ }),+ blk({+ content: 'Continuing.',+ id: 'block-2',+ tools: [{ apiName: 'Bash', id: 'tool-4', identifier: 'claude-code' } as any],+ }),+ ]}+ />,+ );++ const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>+ node.getAttribute('data-testid'),+ );+ expect(sequence).toEqual(['workflow-segment', 'answer-segment', 'workflow-segment']);++ const [first, second] = screen+ .getAllByTestId('workflow-segment')+ .map((node) => JSON.parse(node.getAttribute('data-blocks') || '[]'));+ expect(first).toEqual([+ expect.objectContaining({+ contentOverride: 'Inspecting.',+ domId: 'block-1__tool-0__workflow',+ toolCount: 2,+ }),+ ]);+ expect(second).toEqual([+ expect.objectContaining({ domId: 'block-1__tool-3__workflow', toolCount: 1 }),+ expect.objectContaining({ content: 'Continuing.', toolCount: 1 }),+ ]);+ expect(parseAnswerSegment()).toEqual(+ expect.objectContaining({ domId: 'block-1__tool-2__workflow', id: 'block-1', toolCount: 1 }),+ );+ });+it('does not fold the latest process behind a non-renderable final answer placeholder', () => {render(<Groupdiff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsxindex d0bb3475db8..f25de0aeaaf 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx@@ -22,6 +22,7 @@ import { messageStateSelectors, useConversationStore } from '../../../store';import CouncilList from '../../AgentCouncil/components/CouncilList';import { MessageAggregationContext } from '../../Contexts/MessageAggregationContext';import { areWorkflowToolsComplete, formatReasoningDuration } from '../toolDisplayNames';+import { isImageBearingTool } from '../toolRenderRules';import { CollapsedMessage } from './CollapsedMessage';import GroupItem from './GroupItem';import ProcessFold from './ProcessFold';@@ -131,13 +132,14 @@ const toRenderableBlock = (block: AssistantGroupSemanticBlock): RenderableAssistif (!block.projection) return block;const suffix = block.projection === 'answer' ? ANSWER_DOM_ID_SUFFIX : WORKFLOW_DOM_ID_SUFFIX;+ const key = `${block.projectionKey ?? block.id}${suffix}`;return {...block,contentOverride: block.content,- domId: `${block.id}${suffix}`,+ domId: key,hasToolsOverride: !!block.tools?.length,- renderKey: `${block.id}${suffix}`,+ renderKey: key,};};@@ -145,7 +147,7 @@ const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegmentsegments.map((segment) =>segment.kind === 'answer'? { block: toRenderableBlock(segment.block), kind: 'answer' }- : { blocks: segment.blocks.map(toRenderableBlock), kind: 'workflow' },+ : { ...segment, blocks: segment.blocks.map(toRenderableBlock) },);const withMarkdownStreamingState = (@@ -231,6 +233,7 @@ const Group = memo<GroupChildrenProps>(const { segments, postToolTailPromoted } = useMemo(() => {const partitioned = partitionAssistantGroupBlocks(blocks, {+ isBreakoutTool: isImageBearingTool,isGenerating,toolsPhaseComplete: isGenerating? areWorkflowToolsComplete(blocks.flatMap((block) => block.tools ?? []))@@ -285,7 +288,7 @@ const Group = memo<GroupChildrenProps>(if (segment.kind === 'workflow') {if (segment.blocks.length === 0) return null;- if (shouldInlineWorkflowSegment(segment.blocks)) {+ if (segment.standalone || shouldInlineWorkflowSegment(segment.blocks)) {return segment.blocks.map((block, blockIndex) => {const item = withMarkdownStreamingState(block, lastBlockId);if (!isGenerating && isEmptyBlock(item)) return null;diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.tsindex 1cf9c274eed..2e6de10325c 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts@@ -4,7 +4,7 @@ import {} from '@lobechat/builtin-tool-web-onboarding';import { describe, expect, it } from 'vitest';-import { shouldRenderToolCall } from './toolRenderRules';+import { isImageBearingTool, shouldRenderToolCall } from './toolRenderRules';describe('shouldRenderToolCall', () => {it('hides the onboarding completion tool call', () => {@@ -34,3 +34,41 @@ describe('shouldRenderToolCall', () => {).toBe(true);});});++describe('isImageBearingTool', () => {+ const cc = (state?: unknown) =>+ ({+ apiName: 'Read',+ id: 't',+ identifier: 'claude-code',+ result: { content: 'x', id: 'r', state },+ }) as any;++ it('is true once a tool result carries an uploaded image', () => {+ expect(isImageBearingTool(cc({ images: [{ url: 'https://x/a.png' }] }))).toBe(true);+ });++ it('is false while the result is missing or the upload failed', () => {+ expect(isImageBearingTool(cc())).toBe(false);+ expect(isImageBearingTool(cc({ images: [{}] }))).toBe(false);+ });++ it('is true for a generateImage result with a finished asset', () => {+ expect(+ isImageBearingTool({+ apiName: 'generateImage',+ id: 't',+ identifier: 'lobe-image-generation',+ result: { content: 'x', id: 'r', state: { generations: [{ asset: { url: 'u' } }] } },+ } as any),+ ).toBe(true);+ expect(+ isImageBearingTool({+ apiName: 'generateImage',+ id: 't',+ identifier: 'lobe-image-generation',+ result: { content: 'x', id: 'r', state: { generations: [{ asset: null }] } },+ } as any),+ ).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.tsindex 7617f1fac2b..330969814b3 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts@@ -1,7 +1,12 @@+import {+ ImageGenerationApiName,+ ImageGenerationIdentifier,+} from '@lobechat/builtin-tool-image-generation';import {WebOnboardingApiName,WebOnboardingIdentifier,} from '@lobechat/builtin-tool-web-onboarding';+import type { ChatToolPayloadWithResult } from '@lobechat/types';interface ToolRenderRuleTarget {apiName: string;@@ -16,3 +21,24 @@ export const shouldRenderToolCall = ({ apiName, identifier }: ToolRenderRuleTargreturn true;};++const hasUploadedImages = (state: unknown): boolean =>+ !!(state as { images?: { url?: string }[] } | undefined)?.images?.some((image) => !!image.url);++const hasGeneratedImage = (state: unknown): boolean =>+ !!(state as { generations?: { asset?: unknown }[] } | undefined)?.generations?.some(+ (generation) => !!generation.asset,+ );++export const isImageBearingTool = (tool: ChatToolPayloadWithResult): boolean => {+ const state = tool.result?.state;+ if (!state) return false;++ if (+ tool.identifier === ImageGenerationIdentifier &&+ tool.apiName === ImageGenerationApiName.generateImage+ )+ return hasGeneratedImage(state);++ return hasUploadedImages(state);+};