Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat(web): queue messages typed while an agent is answering (#200)

Croffb480ae9e2229
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index 846f8e81..0722d2b4 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -87,6 +87,8 @@
"toolOutput": "المخرجات",
"thinking": "جارٍ التفكير…",
"waitingForRunner": "مستني الرانر…",
+ "waitingToSend": "في انتظار الإرسال",
+ "removePending": "حذف الرسالة",
"title": "محادثة مع {agent}",
"unreachable": "تعذّر الوصول إلى الوكيل. حاول مرة أخرى.",
"runnerOffline": "المنفّذ (runner) مش متصل",
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index a837a71f..7907adc2 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -87,6 +87,8 @@
"toolOutput": "Output",
"thinking": "Thinking…",
"waitingForRunner": "Waiting for the runner…",
+ "waitingToSend": "Waiting to send",
+ "removePending": "Remove message",
"title": "Chat with {agent}",
"unreachable": "Could not reach the agent. Try again.",
"runnerOffline": "Runner offline",
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index ed22aa00..2670ae45 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -87,6 +87,8 @@
"toolOutput": "Ответ",
"thinking": "Думает…",
"waitingForRunner": "Ждём раннер…",
+ "waitingToSend": "Ждёт отправки",
+ "removePending": "Удалить сообщение",
"title": "Чат с {agent}",
"unreachable": "Не удалось связаться с агентом. Попробуйте ещё раз.",
"runnerOffline": "Раннер не на связи",
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index 49c93d2c..0ed337de 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -87,6 +87,8 @@
"toolOutput": "Відповідь",
"thinking": "Думає…",
"waitingForRunner": "Чекаємо на раннер…",
+ "waitingToSend": "Чекає на надсилання",
+ "removePending": "Видалити повідомлення",
"title": "Чат з {agent}",
"unreachable": "Не вдалося зв'язатися з агентом. Спробуйте ще раз.",
"runnerOffline": "Раннер не на зв’язку",
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index abcf4a9f..ca9e3137 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -87,6 +87,8 @@
"toolOutput": "输出",
"thinking": "正在思考…",
"waitingForRunner": "正在等待运行器…",
+ "waitingToSend": "等待发送",
+ "removePending": "删除消息",
"title": "与 {agent} 对话",
"unreachable": "无法连接代理,请重试。",
"runnerOffline": "运行器未连接",
diff --git a/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx b/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
index 2e22269a..e1db31d6 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
@@ -1,9 +1,9 @@
'use client';
-import { useEffect, useRef, useState } from 'react';
+import { useState } from 'react';
import { ArrowUp, Bot, RotateCw } from 'lucide-react';
import type { AiAgent } from '@/lib/api';
-import type { ChatMessage, ChatStatus } from '@/hooks/useAgentChat';
+import type { ChatMessage, ChatStatus, PendingMessage } from '@/hooks/useAgentChat';
import { AgentChatTranscript } from './AgentChatTranscript';
import { AgentRunnerStatus } from './AgentRunnerStatus';
import { isRunnerOnline } from './runnerOnline';
@@ -31,7 +31,9 @@ export function AgentChatPanel({
messages,
status,
activeTool,
+ pending,
onSend,
+ onRemovePending,
onReset,
hasEarlierMessages,
isLoadingEarlier,
@@ -41,7 +43,9 @@ export function AgentChatPanel({
messages: ChatMessage[];
status: ChatStatus;
activeTool: string | null;
+ pending: PendingMessage[];
onSend: (prompt: string) => void;
+ onRemovePending: (id: string) => void;
onReset?: () => void;
hasEarlierMessages?: boolean;
isLoadingEarlier?: boolean;
@@ -51,22 +55,12 @@ export function AgentChatPanel({
const [input, setInput] = useState('');
// An external agent answers on its runner, so with none polling the message would sit
// in the queue with nothing to take it. The composer says so instead of accepting it.
+ // A message typed while the agent is answering is not refused — it waits its turn.
const runnerOffline = agent.kind === 'external' && !isRunnerOnline(agent);
- const isBusy = status !== 'ready';
- const canWrite = !isBusy && !runnerOffline;
-
- // The textarea is disabled while a reply is on its way, which drops focus. Restore
- // it once the reply ends so the user can keep typing without clicking back in.
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- const wasBusy = useRef(false);
- useEffect(() => {
- if (wasBusy.current && !isBusy) textareaRef.current?.focus();
- wasBusy.current = isBusy;
- }, [isBusy]);
function submit() {
const text = input.trim();
- if (!text || !canWrite) return;
+ if (!text || runnerOffline) return;
setInput('');
onSend(text);
}
@@ -75,7 +69,7 @@ export function AgentChatPanel({
<div className="flex h-full min-h-0 flex-col">
<MessageScrollerProvider>
<div className="min-h-0 flex-1 overflow-hidden">
- {messages.length === 0 ? (
+ {messages.length === 0 && pending.length === 0 ? (
<Empty className="h-full">
<EmptyHeader>
<EmptyMedia variant="icon">
@@ -90,6 +84,8 @@ export function AgentChatPanel({
messages={messages}
status={status}
activeTool={activeTool}
+ pending={pending}
+ onRemovePending={onRemovePending}
hasEarlierMessages={hasEarlierMessages}
isLoadingEarlier={isLoadingEarlier}
onLoadEarlier={onLoadEarlier}
@@ -113,7 +109,6 @@ export function AgentChatPanel({
>
<InputGroup className="rounded-xl">
<InputGroupTextarea
- ref={textareaRef}
// `auto` once there is something to read, so a message keeps the
// script it was typed in. An empty box has nothing to read from.
dir={input ? 'auto' : undefined}
@@ -131,7 +126,7 @@ export function AgentChatPanel({
? t('runnerOffline')
: t('messagePlaceholder', { agent: agent.name })
}
- disabled={!canWrite}
+ disabled={runnerOffline}
rows={1}
/>
<InputGroupAddon align="block-end">
@@ -142,7 +137,7 @@ export function AgentChatPanel({
size="icon-sm"
className="rounded-lg text-muted-foreground hover:text-foreground"
title={t('reset')}
- disabled={isBusy || messages.length === 0}
+ disabled={status !== 'ready' || messages.length === 0}
onClick={onReset}
>
<RotateCw />
@@ -154,7 +149,7 @@ export function AgentChatPanel({
variant="default"
size="icon-sm"
className="ml-auto rounded-lg"
- disabled={!input.trim() || !canWrite}
+ disabled={!input.trim() || runnerOffline}
>
<ArrowUp />
<span className="sr-only">{t('send')}</span>
diff --git a/apps/web/src/components/common/agent-chat/AgentChatPendingMessage.tsx b/apps/web/src/components/common/agent-chat/AgentChatPendingMessage.tsx
new file mode 100644
index 00000000..44543f26
--- /dev/null
+++ b/apps/web/src/components/common/agent-chat/AgentChatPendingMessage.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { X } from 'lucide-react';
+import type { PendingMessage } from '@/hooks/useAgentChat';
+import { Bubble, BubbleContent } from '@/components/ui/bubble';
+import { Button } from '@/components/ui/button';
+import { Message, MessageContent, MessageFooter } from '@/components/ui/message';
+import { MessageScrollerItem } from '@/components/ui/message-scroller';
+import { useTranslations } from 'next-intl';
+
+export default function AgentChatPendingMessage({
+ message,
+ onRemove,
+}: {
+ message: PendingMessage;
+ onRemove: (id: string) => void;
+}) {
+ const t = useTranslations('common.agentChat');
+
+ return (
+ <MessageScrollerItem
+ messageId={message.id}
+ className="motion-safe:animate-in motion-safe:duration-300 motion-safe:fade-in motion-safe:slide-in-from-bottom-1"
+ >
+ <Message align="end">
+ <MessageContent>
+ <Bubble variant="muted" className="gap-2 opacity-60">
+ <BubbleContent>
+ <span className="whitespace-pre-wrap" dir="auto">
+ {message.text}
+ </span>
+ </BubbleContent>
+ </Bubble>
+ <MessageFooter className="gap-1">
+ <span>{t('waitingToSend')}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-5 text-muted-foreground hover:text-foreground"
+ onClick={() => onRemove(message.id)}
+ >
+ <X className="size-3" />
+ <span className="sr-only">{t('removePending')}</span>
+ </Button>
+ </MessageFooter>
+ </MessageContent>
+ </Message>
+ </MessageScrollerItem>
+ );
+}
diff --git a/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx b/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
index 60e61547..d7a431ed 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
@@ -2,9 +2,10 @@
import { useEffect, useRef } from 'react';
import type { UIEvent, WheelEvent } from 'react';
-import type { ChatMessage, ChatStatus } from '@/hooks/useAgentChat';
+import type { ChatMessage, ChatStatus, PendingMessage } from '@/hooks/useAgentChat';
import { dayKey } from '@/utils/dates';
import AgentChatMessage from './AgentChatMessage';
+import AgentChatPendingMessage from './AgentChatPendingMessage';
import InitialScrollToEnd from './InitialScrollToEnd';
import { Marker, MarkerContent } from '@/components/ui/marker';
import {
@@ -22,6 +23,8 @@ export function AgentChatTranscript({
messages,
status,
activeTool,
+ pending,
+ onRemovePending,
hasEarlierMessages = false,
isLoadingEarlier = false,
onLoadEarlier,
@@ -29,6 +32,8 @@ export function AgentChatTranscript({
messages: ChatMessage[];
status: ChatStatus;
activeTool: string | null;
+ pending: PendingMessage[];
+ onRemovePending: (id: string) => void;
hasEarlierMessages?: boolean;
isLoadingEarlier?: boolean;
onLoadEarlier?: () => void;
@@ -104,6 +109,14 @@ export function AgentChatTranscript({
</Marker>
</MessageScrollerItem>
)}
+
+ {pending.map((message) => (
+ <AgentChatPendingMessage
+ key={message.id}
+ message={message}
+ onRemove={onRemovePending}
+ />
+ ))}
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
diff --git a/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx b/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx
index b0b9b2cd..59e2b22b 100644
--- a/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx
+++ b/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx
@@ -33,7 +33,9 @@ export function AiChatThread({
status,
activeTool,
threadId: activeThreadId,
+ pending,
send,
+ removePending,
loadThread,
prependHistory,
} = useAgentChat(projectKey, agent.id, agent.kind === 'external');
@@ -96,7 +98,9 @@ export function AiChatThread({
messages={messages}
status={status}
activeTool={activeTool}
+ pending={pending}
onSend={send}
+ onRemovePending={removePending}
hasEarlierMessages={messagesQuery.hasNextPage}
isLoadingEarlier={messagesQuery.isFetchingNextPage}
onLoadEarlier={() => void messagesQuery.fetchNextPage()}
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
index 5ef52b90..0f8790a6 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
@@ -133,7 +133,9 @@ function SheetBody({
messages={chat.messages}
status={chat.status}
activeTool={chat.activeTool}
+ pending={chat.pending}
onSend={chat.send}
+ onRemovePending={chat.removePending}
onReset={chat.newChat}
/>
</div>
diff --git a/apps/web/src/hooks/useAgentChat.ts b/apps/web/src/hooks/useAgentChat.ts
index cbb81ef7..127d550a 100644
--- a/apps/web/src/hooks/useAgentChat.ts
+++ b/apps/web/src/hooks/useAgentChat.ts
@@ -1,6 +1,6 @@
'use client';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { ApiError, streamAiAgentChat, streamAiAgentRun } from '@/lib/api';
import type { AiChatMessage, AiChatPart, AiChatToolPart } from '@/lib/api';
@@ -30,6 +30,9 @@ function updateToolPart(
// no runner has taken it yet, so nothing is being written.
export type ChatStatus = 'ready' | 'queued' | 'streaming';
+// A message typed while the agent was answering, waiting for its turn.
+export type PendingMessage = { id: string; text: string };
+
// Drives one conversation with an agent. Sends a prompt, streams the response over
// SSE, and exposes the running transcript, the stream status, and the tool the agent
// is currently using (for the status marker).
@@ -44,6 +47,11 @@ export type ChatStatus = 'ready' | 'queued' | 'streaming';
// and it is surfaced as `threadId` so the host can reflect the new thread in the
// history list. loadThread() restores a past conversation; newChat() starts a fresh
// one. threadId is null while a new conversation has not produced its first reply.
+//
+// A message sent while a reply is running is held in `pending` and sent on its own once
+// that reply ends, one at a time and in the order it was typed. A reply that failed
+// stops the queue: what is left waits until the next send, so a message is not thrown
+// at an agent that is not answering.
export function useAgentChat(projectKey: string, agentId: number, external: boolean) {
const t = useTranslations('common.agentChat');
const [messages, setMessages] = useState<ChatMessage[]>([]);
@@ -54,10 +62,20 @@ export function useAgentChat(projectKey: string, agentId: number, external: bool
// thread without re-creating the callback on every thread change.
const threadRef = useRef<string | null>(null);
- const send = useCallback(
- async (prompt: string) => {
- const text = prompt.trim();
- if (!text || status !== 'ready') return;
+ const [pending, setPending] = useState<PendingMessage[]>([]);
+ // A running turn is held twice: the ref so a second send in the same frame sees it
+ // before the re-render, the state so the end of a turn re-runs the drain effect.
+ // `status` cannot do that job — loadThread sets it to 'ready' while a turn it did
+ // not start is still streaming, and the end of that turn then changes nothing.
+ const runningRef = useRef(false);
+ const [running, setRunning] = useState(false);
+ const [stopped, setStopped] = useState(false);
+
+ const runTurn = useCallback(
+ async (text: string) => {
+ if (runningRef.current) return;
+ runningRef.current = true;
+ setRunning(true);
const assistantId = crypto.randomUUID();
const createdAt = new Date().toISOString();
@@ -128,12 +146,16 @@ export function useAgentChat(projectKey: string, agentId: number, external: bool
break;
case 'error':
toast.error(event.message);
+ setStopped(true);
break;
}
}
} catch (err) {
toast.error(err instanceof ApiError ? err.message : t('unreachable'));
+ setStopped(true);
} finally {
+ runningRef.current = false;
+ setRunning(false);
setStatus('ready');
setActiveTool(null);
// Drop the assistant placeholder if the agent never produced anything (an error
@@ -141,9 +163,35 @@ export function useAgentChat(projectKey: string, agentId: number, external: bool
setMessages((m) => m.filter((msg) => !(msg.id === assistantId && msg.parts.length === 0)));
}
},
- [projectKey, agentId, status, external, t],
+ [projectKey, agentId, external, t],
+ );
+
+ const send = useCallback(
+ (prompt: string) => {
+ const text = prompt.trim();
+ if (!text) return;
+ setStopped(false);
+ if (runningRef.current || pending.length > 0) {
+ setPending((queue) => [...queue, { id: crypto.randomUUID(), text }]);
+ return;
+ }
+ void runTurn(text);
+ },
+ [pending, runTurn],
);
+ const removePending = useCallback((id: string) => {
+ setPending((queue) => queue.filter((message) => message.id !== id));
+ }, []);
+
+ // Sends the next waiting message once the reply before it has ended.
+ useEffect(() => {
+ if (stopped || running || runningRef.current || pending.length === 0) return;
+ const [next] = pending;
+ setPending((queue) => queue.filter((message) => message.id !== next.id));
+ void runTurn(next.text);
+ }, [stopped, running, pending, runTurn]);
+
// Restores a past conversation: shows its transcript and continues its thread.
const loadThread = useCallback((id: string, history: AiChatMessage[]) => {
threadRef.current = id;
@@ -151,6 +199,8 @@ export function useAgentChat(projectKey: string, agentId: number, external: bool
setMessages(history);
setStatus('ready');
setActiveTool(null);
+ setPending([]);
+ setStopped(false);
}, []);
const prependHistory = useCallback((history: AiChatMessage[]) => {
@@ -167,7 +217,20 @@ export function useAgentChat(projectKey: string, agentId: number, external: bool
setMessages([]);
setStatus('ready');
setActiveTool(null);
+ setPending([]);
+ setStopped(false);
}, []);
- return { messages, status, activeTool, threadId, send, loadThread, prependHistory, newChat };
+ return {
+ messages,
+ status,
+ activeTool,
+ threadId,
+ pending,
+ send,
+ removePending,
+ loadThread,
+ prependHistory,
+ newChat,
+ };
}