🤯 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
🐛 fix(task): send a run follow-up into the run's own topic (#20241)
Arvin Xuec624041f3a2
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 25def574ac9..9c9ec8b1f7a 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1905,6 +1905,7 @@"taskDetail.deleteConfirm.content": "This action cannot be undone.","taskDetail.deleteConfirm.ok": "Delete","taskDetail.deleteConfirm.title": "Delete this task?",+ "taskDetail.followUpFailed": "Couldn’t send the follow-up. Your message is kept — try again.","taskDetail.goalTimeline.hover.cost": "Cost","taskDetail.goalTimeline.hover.duration": "Duration","taskDetail.goalTimeline.hover.status": "Status",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 636eda27dc3..7418890615b 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1905,6 +1905,7 @@"taskDetail.deleteConfirm.content": "此操作不可撤销。","taskDetail.deleteConfirm.ok": "删除","taskDetail.deleteConfirm.title": "确认删除此任务?",+ "taskDetail.followUpFailed": "追问未发送成功,内容已保留,请重试。","taskDetail.goalTimeline.hover.cost": "成本","taskDetail.goalTimeline.hover.duration": "时长","taskDetail.goalTimeline.hover.status": "状态",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 9a0e148896b..1099b674d4d 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1720,6 +1720,7 @@ export default {'taskDetail.reportedByAgent': 'the agent','taskDetail.runFollowUp': 'Ask a follow-up','taskDetail.runFollowUpPlaceholder': 'Ask a follow-up about this run...',+ 'taskDetail.followUpFailed': 'Couldn’t send the follow-up. Your message is kept — try again.','taskDetail.collapseReply': 'Collapse','taskDetail.replyInThread': 'Reply in this thread','taskDetail.replyPlaceholder': 'Reply in this thread...',diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskRunReport.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskRunReport.tsxindex 99bd3e3bd62..c3fde0f2486 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskRunReport.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskRunReport.tsx@@ -9,9 +9,9 @@ import { useTranslation } from 'react-i18next';import { DEFAULT_AVATAR } from '@/const/meta';import { useTaskStore } from '@/store/task';-import { taskDetailSelectors } from '@/store/task/selectors';import RunReplyEditor from './RunReplyEditor';+import { resolveRunAgentId, useRunFollowUp } from './useRunFollowUp';/*** What the agent reported for this task, presented as a report.@@ -26,8 +26,10 @@ import RunReplyEditor from './RunReplyEditor';* different job from the avatar's job in a list row.** The two actions stay because reading a report is not the end of the job: you- * either ask the agent about it or leave a note for the next run. They sit under- * the report rather than inside it, so they never compete with the content.+ * either open the run's conversation or ask the agent about it. Both are doors+ * into that conversation — asking sends a user message there and opens the+ * drawer to show it arrive. They sit under the report rather than inside it, so+ * they never compete with the content.*/interface TaskRunReportProps {@@ -37,21 +39,16 @@ interface TaskRunReportProps {const TaskRunReport = memo<TaskRunReportProps>(({ activity }) => {const { t } = useTranslation('chat');const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);- const addComment = useTaskStore((s) => s.addComment);- const activeTaskId = useTaskStore(taskDetailSelectors.activeTaskId);+ const { canFollowUp, submitFollowUp } = useRunFollowUp(activity);const [commenting, setCommenting] = useState(false);- // A descendant run belongs to `sourceTaskId`, not the open parent.- const runTaskId = activity.sourceTaskId ?? activeTaskId;-const openConversation = useCallback(() => {if (!activity.id) return;openTopicDrawer(activity.id, {- agentId:- activity.author?.type === 'agent' ? activity.author.id : activity.agentId || undefined,+ agentId: resolveRunAgentId(activity),title: activity.title,});- }, [activity.agentId, activity.author, activity.id, activity.title, openTopicDrawer]);+ }, [activity, openTopicDrawer]);// Nothing was reported yet — the panel's own empty handling covers that case.const body = activity.content || activity.summary;@@ -73,9 +70,9 @@ const TaskRunReport = memo<TaskRunReportProps>(({ activity }) => {<RunReplyEditoronCancel={() => setCommenting(false)}onSubmit={async (text) => {- if (!runTaskId) return;- await addComment(runTaskId, text, { topicId: activity.id });- setCommenting(false);+ // Close the editor only once the message was accepted: a refused+ // send keeps the draft so it can be retried.+ if (await submitFollowUp(text)) setCommenting(false);}}/>) : (@@ -86,7 +83,7 @@ const TaskRunReport = memo<TaskRunReportProps>(({ activity }) => {title={t('taskDetail.openRunChat')}onClick={openConversation}/>- {!!runTaskId && (+ {canFollowUp && (<ActionIconicon={MessageCircle}size={'small'}diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsxindex 8b7583f29a1..d34111fd63c 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx@@ -9,6 +9,11 @@ import { describe, expect, it, vi } from 'vitest';import TopicCard from './TopicCard';+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ ...(await import('~base-ui-stubs')).baseUiStubs,+}));+vi.mock('@/store/task', () => ({useTaskStore: (selector: (state: any) => unknown) =>selector({@@ -30,6 +35,13 @@ vi.mock('./RunReplyEditor', () => ({ default: () => null }));vi.mock('./RunVerifyDetail', () => ({ default: () => null }));vi.mock('./RunVerifyTag', () => ({ default: () => null }));+// The follow-up's own behaviour lives in useRunFollowUp.test.ts; this file only+// covers the card's wiring to it.+vi.mock('./useRunFollowUp', () => ({+ resolveRunAgentId: () => 'agt_1',+ useRunFollowUp: () => ({ canFollowUp: true, submitting: false, submitFollowUp: vi.fn() }),+}));+vi.mock('@/features/AgentProfileCard/AgentProfilePopup', () => ({default: ({ children }: { children: ReactNode }) => <>{children}</>,}));@@ -56,4 +68,10 @@ describe('TopicCard', () => {// rule, which is exactly what a reader hit: a link that ignores the mouse.await expect(userEvent.click(link)).resolves.not.toThrow();});++ it('offers the follow-up affordance when the hook allows answering the run', () => {+ render(<TopicCard activity={activity} />);++ expect(screen.getByRole('button', { name: 'taskDetail.runFollowUp' })).toBeInTheDocument();+ });});diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsxindex 1ada30d8ede..68f31220913 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx@@ -32,7 +32,6 @@ import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';import { useActivityTime } from '@/hooks/useActivityTime';import { usePermission } from '@/hooks/usePermission';import { useTaskStore } from '@/store/task';-import { taskDetailSelectors } from '@/store/task/selectors';import { isForbiddenError } from '@/utils/forbiddenError';import { styles } from '../shared/style';@@ -41,6 +40,7 @@ import RunVerifyDetail from './RunVerifyDetail';import RunVerifyTag from './RunVerifyTag';import { shouldShowRunFollowUp } from './shouldShowRunFollowUp';import TopicStatusIcon from './TopicStatusIcon';+import { resolveRunAgentId, useRunFollowUp } from './useRunFollowUp';// The run's last message (`content`) is the raw assistant output — markdown, and// often long. Render it as rich text, but keep it a bounded preview in the feed:@@ -91,17 +91,12 @@ const TopicCard = memo<TopicCardProps>(({ activity, defaultExpanded = true, primconst openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);const cancelTopic = useTaskStore((s) => s.cancelTopic);const deleteTopic = useTaskStore((s) => s.deleteTopic);- const addComment = useTaskStore((s) => s.addComment);- const activeTaskId = useTaskStore(taskDetailSelectors.activeTaskId);+ const { canFollowUp, submitFollowUp } = useRunFollowUp(activity);const { allowed: canEditTask } = usePermission('create_content');const [commenting, setCommenting] = useState(false);const isRunning = activity.status === 'running';- // A descendant run shown in a parent detail belongs to `sourceTaskId`, not the- // currently open parent (`activeTaskId`) — file the follow-up on the task that- // owns the run so it appears where the run lives. Direct runs fall back to the- // active task.- const runTaskId = activity.sourceTaskId ?? activeTaskId;- const canFollowUp = canEditTask && !!runTaskId;+ // A run cannot be answered while it is still going: the follow-up is a turn+ // in the same conversation, so it would land mid-run.const showRunFollowUp = shouldShowRunFollowUp(canFollowUp, isRunning);const hasBody = Boolean(activity.summary || activity.content || showRunFollowUp || activity.verify?.total,@@ -130,11 +125,10 @@ const TopicCard = memo<TopicCardProps>(({ activity, defaultExpanded = true, primconst handleOpen = useCallback(() => {if (!activity.id) return;openTopicDrawer(activity.id, {- agentId:- activity.author?.type === 'agent' ? activity.author.id : activity.agentId || undefined,+ agentId: resolveRunAgentId(activity),title: activity.title,});- }, [activity.agentId, activity.author, activity.id, activity.title, openTopicDrawer]);+ }, [activity, openTopicDrawer]);const handleTitleKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {@@ -395,8 +389,9 @@ const TopicCard = memo<TopicCardProps>(({ activity, defaultExpanded = true, prim<RunReplyEditoronCancel={() => setCommenting(false)}onSubmit={async (text) => {- await addComment(runTaskId!, text, { topicId: activity.id });- setCommenting(false);+ // Close the editor only once the message was accepted: a+ // refused send keeps the draft so it can be retried.+ if (await submitFollowUp(text)) setCommenting(false);}}/></Flexbox>@@ -405,7 +400,8 @@ const TopicCard = memo<TopicCardProps>(({ activity, defaultExpanded = true, prim{/* The run's own conversation was reachable only by clicking thetitle, which said nothing about being a door. Asking theagent a follow-up is the natural next move after reading a- delivery, so it gets a real affordance. */}+ delivery, so it gets a real affordance — it sends into that+ conversation and opens it. */}<ActionIconicon={MessagesSquare}size={'small'}diff --git a/src/features/AgentTasks/AgentTaskDetail/useRunFollowUp.test.ts b/src/features/AgentTasks/AgentTaskDetail/useRunFollowUp.test.tsnew file mode 100644index 00000000000..60c0343e9ff--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/useRunFollowUp.test.ts@@ -0,0 +1,224 @@+/**+ * @vitest-environment happy-dom+ */+import type { TaskDetailActivity } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveRunAgentId, useRunFollowUp } from './useRunFollowUp';++const mocks = vi.hoisted(() => ({+ addComment: vi.fn(),+ canUseResource: true,+ openTopicDrawer: vi.fn(),+ prefetchMessages: vi.fn().mockResolvedValue(undefined),+ sendMessage: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: any) => unknown) =>+ selector({ prefetchMessages: mocks.prefetchMessages, sendMessage: mocks.sendMessage }),+}));++vi.mock('@/store/task', () => ({+ useTaskStore: (selector: (state: any) => unknown) =>+ selector({ addComment: mocks.addComment, openTopicDrawer: mocks.openTopicDrawer }),+}));++vi.mock('@/features/Conversation/hooks/useConversationResourceAccess', () => ({+ useConversationResourceAccessForTarget: () => ({+ canUseResource: mocks.canUseResource,+ isAccessLoading: false,+ isGroupContext: false,+ }),+}));++vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: mocks.toastError } }));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const run = {+ agentId: 'agt_1',+ author: { id: 'agt_1', name: 'Email Agent', type: 'agent' },+ id: 'topic-1',+ status: 'success',+ title: 'Email 通道: lobe.id 邮箱接入',+ type: 'topic',+} as unknown as TaskDetailActivity;++const context = {+ agentId: 'agt_1',+ isolatedTopic: true,+ scope: 'main',+ topicId: 'topic-1',+};++/** The happy path: the server takes ownership and reports acceptance. */+const acceptSend = () => {+ mocks.sendMessage.mockImplementation(async (params: any) => {+ params?.onMessageAccepted?.();+ return { assistantMessageId: 'msg_a', userMessageId: 'msg_u' };+ });+};++/**+ * A gateway/network refusal to start the run: `sendMessage` catches the failure+ * and resolves `undefined` without ever accepting the message.+ */+const refuseSend = () => {+ mocks.sendMessage.mockResolvedValue(undefined);+};++beforeEach(() => {+ mocks.canUseResource = true;+ mocks.prefetchMessages.mockClear();+ mocks.sendMessage.mockReset();+ mocks.openTopicDrawer.mockClear();+ mocks.addComment.mockClear();+ mocks.toastError.mockClear();+ acceptSend();+});++describe('resolveRunAgentId', () => {+ it('prefers the run author when the run reports an agent', () => {+ expect(+ resolveRunAgentId({ agentId: 'agt_owner', author: { id: 'agt_run', type: 'agent' } } as any),+ ).toBe('agt_run');+ });++ it('falls back to the activity agent for a non-agent author', () => {+ expect(+ resolveRunAgentId({ agentId: 'agt_owner', author: { id: 'usr_1', type: 'user' } } as any),+ ).toBe('agt_owner');+ });++ it('resolves nothing when the run carries no agent', () => {+ expect(resolveRunAgentId({ id: 'topic-1' } as any)).toBeUndefined();+ });+});++describe('useRunFollowUp', () => {+ it('sends the follow-up as a user message in the run topic', async () => {+ const { result } = renderHook(() => useRunFollowUp(run));++ let sent: boolean | undefined;+ await act(async () => {+ sent = await result.current.submitFollowUp('再补一下 email 通道的联调');+ });++ expect(mocks.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ context,+ forceRuntime: 'gateway',+ message: '再补一下 email 通道的联调',+ }),+ );+ expect(sent).toBe(true);+ });++ it('hydrates the topic before sending so the message threads onto its history', async () => {+ const { result } = renderHook(() => useRunFollowUp(run));++ await act(async () => {+ await result.current.submitFollowUp('hello');+ });++ expect(mocks.prefetchMessages).toHaveBeenCalledWith(context);+ expect(mocks.prefetchMessages.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.sendMessage.mock.invocationCallOrder[0],+ );+ });++ it('opens the conversation so the message can be seen where it landed', async () => {+ const { result } = renderHook(() => useRunFollowUp(run));++ await act(async () => {+ await result.current.submitFollowUp('hello');+ });++ expect(mocks.openTopicDrawer).toHaveBeenCalledWith('topic-1', {+ agentId: 'agt_1',+ title: 'Email 通道: lobe.id 邮箱接入',+ });+ });++ it('does not hand the send a composer editor to refill', async () => {+ const { result } = renderHook(() => useRunFollowUp(run));++ await act(async () => {+ await result.current.submitFollowUp('hello');+ });++ // An inline reply has no composer editor of its own. Without `null` the send+ // lifecycle falls back to ChatStore's global editor — a different surface —+ // and writes this message into it on failure.+ expect(mocks.sendMessage).toHaveBeenCalledWith(expect.objectContaining({ inputEditor: null }));+ });++ it('does not file the follow-up as a task comment', async () => {+ const { result } = renderHook(() => useRunFollowUp(run));++ await act(async () => {+ await result.current.submitFollowUp('hello');+ });++ // A comment is addressed to the task: it reaches the agent only on a later+ // task run and never enters the conversation it was written under.+ expect(mocks.addComment).not.toHaveBeenCalled();+ });++ it('reports failure and stays closed when the gateway refuses the send', async () => {+ // Regression: a refused start resolves `undefined`, so awaiting the send+ // looked like success — the drawer opened and both callers closed the reply+ // editor, discarding the draft the user had just typed.+ refuseSend();+ const { result } = renderHook(() => useRunFollowUp(run));++ let sent: boolean | undefined;+ await act(async () => {+ sent = await result.current.submitFollowUp('please follow up');+ });++ expect(sent).toBe(false);+ expect(mocks.openTopicDrawer).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalledWith('taskDetail.followUpFailed');+ });++ it('reports failure when the send throws', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.sendMessage.mockRejectedValue(new Error('network down'));+ const { result } = renderHook(() => useRunFollowUp(run));++ let sent: boolean | undefined;+ await act(async () => {+ sent = await result.current.submitFollowUp('please follow up');+ });++ expect(sent).toBe(false);+ expect(mocks.openTopicDrawer).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalledWith('taskDetail.followUpFailed');+ consoleError.mockRestore();+ });++ it('refuses to send when the member may only view the shared topic', async () => {+ mocks.canUseResource = false;+ const { result } = renderHook(() => useRunFollowUp(run));++ expect(result.current.canFollowUp).toBe(false);+ await act(async () => {+ await result.current.submitFollowUp('hello');+ });++ expect(mocks.sendMessage).not.toHaveBeenCalled();+ expect(mocks.openTopicDrawer).not.toHaveBeenCalled();+ });++ it('cannot follow up when the run carries no agent to send to', () => {+ const { result } = renderHook(() => useRunFollowUp({ id: 'topic-1' } as any));++ expect(result.current.canFollowUp).toBe(false);+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/useRunFollowUp.ts b/src/features/AgentTasks/AgentTaskDetail/useRunFollowUp.tsnew file mode 100644index 00000000000..76ed4e91289--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/useRunFollowUp.ts@@ -0,0 +1,123 @@+'use client';++import type { ConversationContext, TaskDetailActivity } from '@lobechat/types';+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useConversationResourceAccessForTarget } from '@/features/Conversation/hooks/useConversationResourceAccess';+import { useChatStore } from '@/store/chat';+import { useTaskStore } from '@/store/task';++/**+ * The agent a run was executed by. A descendant run reports its own author;+ * otherwise the activity carries the agent that owns the topic.+ */+export const resolveRunAgentId = (activity: TaskDetailActivity): string | undefined =>+ activity.author?.type === 'agent' ? activity.author.id : activity.agentId || undefined;++/**+ * Answering a run means continuing the conversation it ran in: the follow-up+ * becomes a user message in that run's topic, sent over the gateway runtime so+ * it takes the same server-side path as the `runTask` that spawned the topic.+ *+ * A follow-up used to be filed as a task comment instead. A comment is+ * addressed to the *task*, not the run: it renders in the task's activity feed+ * and reaches the agent only when the task runs again, folded into that run's+ * comment digest. The conversation the note was written under never received+ * it, so answering a run produced no reply in that run.+ */+export const useRunFollowUp = (activity: TaskDetailActivity) => {+ const { t } = useTranslation('chat');+ const topicId = activity.id;+ const agentId = resolveRunAgentId(activity);++ // Same gate as the drawer's composer: a workspace topic is shared, so a+ // view-only member can watch the run but must not be able to answer in it.+ const { canUseResource } = useConversationResourceAccessForTarget({ agentId });++ const prefetchMessages = useChatStore((s) => s.prefetchMessages);+ const sendMessage = useChatStore((s) => s.sendMessage);+ const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);++ // The send spans a network round trip; the composer stays busy until it lands.+ const [submitting, setSubmitting] = useState(false);++ const canFollowUp = canUseResource && !!agentId && !!topicId;++ /**+ * Send the follow-up into the run's topic. Resolves `true` only once the+ * message was accepted — the server owns it, so the drawer can be opened onto+ * it.+ *+ * Acceptance, not the await, is the success boundary: a gateway/network+ * refusal to start the run is caught inside `sendMessage` and resolved as+ * `undefined`, so a resolved await says nothing about whether the message+ * landed. The caller uses the result to keep its editor and draft open on a+ * refusal, and a failed send is surfaced so it can be retried.+ */+ const submitFollowUp = useCallback(+ async (text: string): Promise<boolean> => {+ if (!canFollowUp || !agentId || !topicId || submitting) return false;+ setSubmitting(true);+ let accepted = false;+ try {+ const context: ConversationContext = {+ agentId,+ isolatedTopic: true,+ scope: 'main',+ topicId,+ };+ // Hydrate the topic's history first: sending against an empty message+ // store orphans the reply, with no parent to thread it onto.+ await prefetchMessages(context);+ await sendMessage({+ context,+ forceRuntime: 'gateway',+ message: text,+ // This reply is owned by the inline editor, not the conversation+ // composer. `null` says so: on a refused send the lifecycle must not+ // fall back to — and refill — ChatStore's global editor, which belongs+ // to a sibling surface.+ inputEditor: null,+ // The only signal that the send actually took ownership of the+ // message; a refusal resolves without ever calling it.+ onMessageAccepted: () => {+ accepted = true;+ },+ });+ } catch (error) {+ console.error('[useRunFollowUp] failed to send follow-up:', error);+ } finally {+ setSubmitting(false);+ }++ if (!accepted) {+ toast.error(t('taskDetail.followUpFailed'));+ return false;+ }++ // The message lives in the run's conversation, and that is the only place+ // it can be read or watched — the report it was typed under is a static+ // panel that does not change when the run is answered. Opening the drawer+ // shows it landing and the agent picking it up. A run already in flight in+ // this tab keeps its own connection, so this attaches to it rather than+ // opening a second stream.+ openTopicDrawer(topicId, { agentId, title: activity.title });+ return true;+ },+ [+ activity.title,+ agentId,+ canFollowUp,+ openTopicDrawer,+ prefetchMessages,+ sendMessage,+ submitting,+ t,+ topicId,+ ],+ );++ return { canFollowUp, submitFollowUp, submitting };+};diff --git a/src/features/Conversation/hooks/useConversationResourceAccess.ts b/src/features/Conversation/hooks/useConversationResourceAccess.tsindex d807c1cb08b..b229a4c1ffe 100644--- a/src/features/Conversation/hooks/useConversationResourceAccess.ts+++ b/src/features/Conversation/hooks/useConversationResourceAccess.ts@@ -15,7 +15,14 @@ interface ConversationResourceTarget {groupId?: string | null;}-const useConversationResourceAccessForTarget = ({+/**+ * Resource gating for a conversation the caller names explicitly, for surfaces+ * that render beside the conversation instead of inside its+ * `ConversationProvider` — a task run's follow-up composer knows the run's+ * agent before any drawer is open, and must pass the same check the drawer's+ * own composer does.+ */+export const useConversationResourceAccessForTarget = ({agentId,groupId,}: ConversationResourceTarget) => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 056a25688ba..1acb7dd364e 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -622,6 +622,51 @@ describe('ConversationLifecycle actions', () => {expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeUndefined();});+ it('does not refill the global composer when a send names no editor of its own', async () => {+ // Regression: an embedded reply (a task run's inline follow-up) passes+ // `inputEditor: null` to say "no composer here". The lifecycle used to+ // treat that null as "unset" and fall back to ChatStore's global editor,+ // writing the failed message into a surface the send does not own.+ const { result } = renderHook(() => useChatStore());+ const setDocument = vi.fn();+ const setJSONState = vi.fn();+ const executeGatewayAgentSpy = vi+ .fn()+ .mockRejectedValue(+ new TRPCClientError('Topic tpc_test remained busy while starting operation'),+ );++ act(() => {+ useChatStore.setState({+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ mainInputEditor: {+ getJSONState: vi.fn().mockReturnValue({ root: { children: [], type: 'root' } }),+ setDocument,+ setJSONState,+ } as any,+ });+ });++ await act(async () => {+ await result.current.sendMessage({+ context: createTestContext(),+ inputEditor: null,+ message: 'Typed into an inline reply',+ });+ });++ const sendMessageOperation = Object.values(result.current.operations).find(+ (operation) => operation.type === 'sendMessage',+ );+ // Prove the gateway branch ran and failed before asserting the global+ // editor was left untouched.+ expect(executeGatewayAgentSpy).toHaveBeenCalled();+ expect(sendMessageOperation?.status).toBe('failed');+ expect(setDocument).not.toHaveBeenCalled();+ expect(setJSONState).not.toHaveBeenCalled();+ });+it('should send a snapshot of the tracked server runs with a gateway send', async () => {const context = { ...createTestContext(), topicId: TEST_IDS.TOPIC_ID };const contextKey = messageMapKey(context);diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 57f3ec8eaa9..a1f102d55df 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -140,7 +140,8 @@ export interface SendMessageWithContextParams extends SendMessageParams {/*** Editor owned by the calling ConversationProvider. Embedded conversations* must not fall back to ChatStore's global editor, which may belong to a- * sibling panel.+ * sibling panel. Pass `null` when the send is not backed by a composer editor+ * at all, so a failed send is not written into the global one.*/inputEditor?: ChatInputEditor | null;/** Restore composer-owned context when sending fails before a message owns it. */@@ -387,7 +388,12 @@ export class ConversationLifecycleActionImpl {let editorData = inputEditorData;const { executeClientAgent, mainInputEditor } = this.#get();- const targetInputEditor = inputEditor ?? mainInputEditor;+ // `inputEditor` names the editor that owns this send. An explicit `null`+ // means "this send has no composer editor": an embedded reply (a task run's+ // inline follow-up) must not fall back to ChatStore's global editor, which+ // belongs to a sibling surface and would be refilled with this send's text+ // when it fails. Only an omitted editor falls back to the global one.+ const targetInputEditor = inputEditor === undefined ? mainInputEditor : inputEditor;const ownerAgentId = context.agentId;const selectedSkills = parseSelectedSkillsFromEditorData(editorData);const selectedTools = parseSelectedToolsFromEditorData(editorData);