🤯 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(chat-input): Send now interrupts a run that is still taking the queued message (#22838)
Arvin Xuefd8d0dc5a26
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 129775f8a6e..fbbde4b4211 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1711,6 +1711,7 @@"inputQueue.queuedRunEndHint": "Sends when the current run finishes","inputQueue.queuedRunEndMergeHint": "Merged and sent when the current run finishes","inputQueue.sendNow": "Send now (interrupts current run)",+ "inputQueue.sendNowFailed": "Couldn’t interrupt the current run. Try again.","inputQueue.withdrawFailed": "Couldn’t take the message back. Try again.","intentUnderstanding.title": "Understanding your intent...","internalLink.agent.open": "Open agent",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 07bd24397fc..1ab169aee66 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1711,6 +1711,7 @@"inputQueue.queuedRunEndHint": "当前运行完成后发送","inputQueue.queuedRunEndMergeHint": "当前运行完成后合并发送","inputQueue.sendNow": "立即发送(中断当前运行)",+ "inputQueue.sendNowFailed": "没能中断当前运行,请重试","inputQueue.withdrawFailed": "没能撤回这条消息,请重试","intentUnderstanding.title": "正在理解你的意图…","internalLink.agent.open": "打开助理",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 2345c8b0883..9859d32af5f 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1051,6 +1051,7 @@ export default {'inputQueue.queuedRunEndHint': 'Sends when the current run finishes','inputQueue.queuedRunEndMergeHint': 'Merged and sent when the current run finishes','inputQueue.sendNow': 'Send now (interrupts current run)',+ 'inputQueue.sendNowFailed': 'Couldn’t interrupt the current run. Try again.','inputQueue.alreadyDelivered': 'Already sent to the agent','inputQueue.withdrawFailed': 'Couldn’t take the message back. Try again.','intentUnderstanding.title': 'Understanding your intent...',diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex 64b73b9266e..3b0d2986b70 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -2,7 +2,7 @@import { ActionIcon, createStaticStyles, Flexbox, Icon, Image, toast, Tooltip } from '@lobehub/ui';import { ArrowUp, Info, ListEnd, Pencil, Trash2 } from 'lucide-react';-import { memo, useCallback, useMemo } from 'react';+import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import FileIcon from '@/components/FileIcon';@@ -249,21 +249,35 @@ const QueueTray = memo(() => {// remaining queue (if any) stays in place — the new turn's onComplete drain// will pick them up after it finishes. Reads chatStore inline so we don't// re-subscribe the whole tray to the operations map.+ // The row shows it is on its way at once: stopping a CLI agent waits for the+ // device to confirm, which can take seconds.+ const [sendingId, setSendingId] = useState<string>();const handleSendNow = useCallback(async (msg: QueuedMessage) => {await sendNowGate- .run(() =>- sendQueuedMessageNow({- chat: useChatStore.getState(),- context,- contextKey,- msg,- withdraw,- }),- )- .catch((error) => console.error('[QueueTray] sendNow failed:', error));+ .run(async () => {+ setSendingId(msg.id);+ try {+ const outcome = await sendQueuedMessageNow({+ chat: useChatStore.getState(),+ context,+ contextKey,+ isQueued: (id) =>+ !!useChatStore.getState().queuedMessages[contextKey]?.some((q) => q.id === id),+ msg,+ withdraw: (queued) => withdrawQueuedMessage(contextKey, queued.id),+ });+ if (outcome === 'delivered') toast.info(t('inputQueue.alreadyDelivered'));+ } finally {+ setSendingId(undefined);+ }+ })+ .catch((error) => {+ console.error('[QueueTray] sendNow failed:', error);+ toast.error(t('inputQueue.sendNowFailed'));+ });},- [context, contextKey, sendNowGate, withdraw],+ [context, contextKey, sendNowGate, t, withdrawQueuedMessage],);if (queuedMessages.length === 0) return null;@@ -328,6 +342,7 @@ const QueueTray = memo(() => {<div style={{ flex: 1 }} /><ActionIconaria-label={t('inputQueue.edit')}+ disabled={sendingId === msg.id}icon={Pencil}size="small"title={t('inputQueue.edit')}@@ -335,13 +350,16 @@ const QueueTray = memo(() => {/><ActionIconaria-label={t('inputQueue.sendNow')}+ disabled={!!sendingId}icon={ArrowUp}+ loading={sendingId === msg.id}size="small"title={t('inputQueue.sendNow')}onClick={() => handleSendNow(msg)}/><ActionIconaria-label={t('inputQueue.delete')}+ disabled={sendingId === msg.id}icon={Trash2}size="small"title={t('inputQueue.delete')}diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.tsindex 9e5ce414571..af61e25e091 100644--- a/src/features/Conversation/ChatInput/utils.test.ts+++ b/src/features/Conversation/ChatInput/utils.test.ts@@ -370,6 +370,7 @@ describe('sendQueuedMessageNow', () => {chat,context,contextKey: messageMapKey(context),+ isQueued: () => true,msg,withdraw,});@@ -389,6 +390,7 @@ describe('sendQueuedMessageNow', () => {chat,context,contextKey: messageMapKey(context),+ isQueued: () => true,msg: { ...msg, forceRuntime: 'gateway' },withdraw: async () => true,});@@ -398,21 +400,94 @@ describe('sendQueuedMessageNow', () => {);});- it('stops nothing and sends nothing when the run already took it', async () => {+ it('stops nothing and sends nothing when the run already wrote it', async () => {const { chat } = chatWith(true);- await sendQueuedMessageNow({+ const outcome = await sendQueuedMessageNow({chat,context,contextKey: messageMapKey(context),+ isQueued: () => false,msg,withdraw: async () => false,});+ expect(outcome).toBe('delivered');expect(chat.cancelOperation).not.toHaveBeenCalled();expect(chat.sendMessage).not.toHaveBeenCalled();});+ // ROOT CAUSE:+ //+ // A CLI agent run takes a follow-up from the server but only writes it+ // between its own turns, so for minutes it stays "delivering". Send now read+ // that as already sent: it showed "Already sent to the agent" and neither+ // interrupted the run nor sent the message.+ //+ // Before: a refused withdrawal stopped nothing.+ // After: one still in the tray interrupts the run, which hands it back, and+ // is withdrawn again and sent.+ it('interrupts a run that took it but has not written it yet, then sends it', async () => {+ const { chat, order } = chatWith(true);+ let delivering = true;+ const withdraw = vi.fn(async () => {+ order.push('withdraw');+ return !delivering;+ });+ chat.cancelOperation.mockImplementation(async () => {+ order.push('cancel');+ delivering = false;+ return true;+ });++ const outcome = await sendQueuedMessageNow({+ chat,+ context,+ contextKey: messageMapKey(context),+ isQueued: () => true,+ msg,+ withdraw,+ });++ expect(outcome).toBe('sent');+ expect(order).toEqual(['withdraw', 'cancel', 'withdraw', 'send']);+ });++ it('sends nothing when the run wrote it before the interrupt landed', async () => {+ const { chat } = chatWith(true);++ const outcome = await sendQueuedMessageNow({+ chat,+ context,+ contextKey: messageMapKey(context),+ isQueued: () => true,+ msg,+ withdraw: async () => false,+ });++ expect(outcome).toBe('delivered');+ expect(chat.cancelOperation).toHaveBeenCalled();+ expect(chat.sendMessage).not.toHaveBeenCalled();+ });++ it('keeps an item the run holds in the tray when the interrupt fails', async () => {+ const { chat } = chatWith(false);++ await expect(+ sendQueuedMessageNow({+ chat,+ context,+ contextKey: messageMapKey(context),+ isQueued: () => true,+ msg,+ withdraw: async () => false,+ }),+ ).rejects.toThrow();++ expect(chat.restoreQueuedMessage).not.toHaveBeenCalled();+ expect(chat.sendMessage).not.toHaveBeenCalled();+ });+it.each([['unconfirmed', false],['failed', new Error('device unreachable')],@@ -424,6 +499,7 @@ describe('sendQueuedMessageNow', () => {chat,context,contextKey: messageMapKey(context),+ isQueued: () => true,msg,withdraw: async () => true,}),diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.tsindex 9c1a9c371ca..0e520557754 100644--- a/src/features/Conversation/ChatInput/utils.ts+++ b/src/features/Conversation/ChatInput/utils.ts@@ -188,33 +188,45 @@ export const toDisplayableSendErrorMessage = (message?: string): string | undefi* "Send now" for one queued message: take it out of the queue, stop every run* it waits behind, then send it as a steered turn.*- * Withdrawn first: interrupting a run that already took it from the server- * would leave that copy unanswered. `withdraw` resolving `false` means it is- * already on its way, so nothing is stopped or sent. Should the interrupt- * fail, it goes back to the tray, held by this client only.+ * Withdrawn first: interrupting a run that already wrote it into the+ * conversation would leave that copy unanswered. One the run took but has not+ * written yet (a CLI agent only reads it between its own turns) still+ * interrupts: the stop returns it to this tab, and it is withdrawn again and+ * sent. Should the interrupt fail, a withdrawn item goes back to the tray,+ * held by this client only.+ *+ * @returns `'delivered'` when the run already has it, so nothing was sent*/export const sendQueuedMessageNow = async ({chat,context,contextKey,+ isQueued,msg,withdraw,}: {chat: ChatStore;context: ConversationContext;contextKey: string;+ /** Reads the live queue: `chat` is a snapshot taken before any await. */+ isQueued: (id: string) => boolean;msg: QueuedMessage;+ /** Throws when the server cannot be asked; `false` means the run has it. */withdraw: (msg: QueuedMessage) => Promise<boolean>;-}): Promise<void> => {+}): Promise<'delivered' | 'sent'> => {const index = chat.queuedMessages[contextKey]?.findIndex((queued) => queued.id === msg.id) ?? -1;- if (!(await withdraw(msg))) return;+ const withdrawn = await withdraw(msg);+ // A `false` that leaves it in the tray means "taken, not yet written".+ if (!withdrawn && !isQueued(msg.id)) return 'delivered';// Back where it was, so the order the user queued in holds.- const putBack = () =>+ const putBack = () => {+ if (!withdrawn) return;chat.restoreQueuedMessage(contextKey,{ ...msg, serverDelivery: undefined, serverUnconfirmed: undefined },index < 0 ? Number.MAX_SAFE_INTEGER : index,);+ };// Cancel EVERY running blocker the item could be queued behind, not just the// first: matching one op would miss an interim blocker or the second of the@@ -234,6 +246,8 @@ export const sendQueuedMessageNow = async ({putBack();throw new Error('Running agent cancellation was not confirmed');}+ // The stop handed it back unless the run wrote it first.+ if (!withdrawn && !(await withdraw(msg))) return 'delivered';// Reconstruct UploadFileItem-shaped objects so the optimistic temp message// can rebuild imageList/videoList from the snapshotted preview metadata.@@ -252,6 +266,7 @@ export const sendQueuedMessageNow = async ({message: msg.content,metadata: { ...msg.metadata, steer: true },});+ return 'sent';};/**