๐คฏ 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
โก๏ธ perf: show input loading instantly for approve/retry actions (#16864)
YuTengjing647c30ead596
diff --git a/AGENTS.md b/AGENTS.mdindex 0c2a8ab15f1..1a3d9550beb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,6 @@# LobeHub Development Guidelines-Guidelines for using AI coding agents in this LobeHub repository.+Guidelines for using AI coding agents in this opensource LobeHub repository.## Tech Stack@@ -68,7 +68,7 @@ When adding or changing SPA routes:3. In route files, use `import { X } from '@/features/<Domain>'` (or `import Y from '@/features/<Domain>/...'`). Do not add new `features/` folders inside `src/routes/`.4. **Register the desktop route tree in both configs:** `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` must stay in sync (same paths and nesting). Updating only one can cause **blank screens** if the other build path expects the route. `desktopRouter.sync.test.tsx` guards this invariant โ keep it passing.-See the **spa-routes** skill (`.agents/skills/spa-routes/SKILL.md`) for the full convention and file-division rules.+See the **spa-routes** skill for the full convention and file-division rules.## Development@@ -107,23 +107,20 @@ Open this URL to develop locally against the production backend (app.lobehub.com### Quality Check```bash-# Lint (with autofix) + related tests for changed files, or explicit paths-bun run check [files...] [--lint] [--test] [--type]+bun run check [changed-files...]```-- `--lint` / `--test` / `--type` are composable selectors; no selector = lint + test. Default files = all working-tree changes (staged + unstaged + untracked); explicit paths override.-- Tests are auto-routed to the nearest owning vitest config (e.g. `packages/database`) โ no need to `cd` into packages. `--type` runs the full type-check.-- NEVER run `bun run test` โ the full suite takes \~10 minutes.-- Prefer `vi.spyOn` over `vi.mock`-- Manual fallback when you need unusual flags or a single tool: `bunx vitest run --silent='passed-only' '[file-path]'` from the owning package directory, `bun run type-check` for types.-- The implementation lives in `.agents/scripts/check/` as a reusable engine. A superproject that vendors this repo as a submodule can ship its own `check` entry that mounts this repo's pipelines; when this repo is checked out as such a submodule, `bun run check` here detects that and delegates to the superproject's entry automatically.+- No selector = **lint + test in a single pass** โ run it once; don't fire a separate pass per selector. `--lint` / `--test` / `--type` narrow scope and are composable within one run. Default files = all working-tree changes (staged + unstaged + untracked); explicit paths override.+- `--lint` auto-fixes the given files and prints the applied fixes as a diff, so you can review what changed.+- `--test` auto-discovers the related tests for the given source files and runs them under the nearest owning vitest config (e.g. `packages/database`) โ no need to `cd` into packages.+- `--type` runs the full type-check. NEVER run `bun run test` โ the full suite takes \~10 minutes.+- To run tests manually (e.g. a single file or unusual flags), `cd` into the owning package first: `cd packages/database && bunx vitest run --silent='passed-only' '[file-path]'`.### i18n- Add keys to a namespace file under `src/locales/default/` (e.g. `agent.ts`, `auth.ts`)-- Ship en-US and zh-CN by hand in the same PR: write the English source in `src/locales/default/*.ts` and mirror it to `locales/en-US/`; hand-translate `locales/zh-CN/`. Leave all other locales to CI.-- Don't run `pnpm i18n` manually by default โ a daily CI workflow (`auto-i18n.yml`) runs it and opens an automated translation PR for any missing keys.-- Run `pnpm i18n` manually only when your branch needs the translated locales immediately, instead of waiting for the daily job (slow; requires `OPENAI_API_KEY`). Note it only fills keys missing from other locales โ value-only edits never need it.+- Hand-write en-US + zh-CN for dev preview: author the English source in `src/locales/default/*.ts`, mirror it to `locales/en-US/`, and hand-translate `locales/zh-CN/`.+- Before opening the PR, run `bun run i18n` (slow) to fill the remaining locales with the script โ don't hand-translate those.### Code Style@@ -131,16 +128,6 @@ bun run check [files...] [--lint] [--test] [--type]### Code Review-Before reviewing a PR / diff / branch change, read the **deep-review** skill (`.agents/skills/deep-review/SKILL.md`). Ordinary review requests use its light mode (inline review against the dimension quick checklists); the full multi-subagent deep mode runs only on explicit invocation.+Before reviewing a PR / diff / branch change, read the **deep-review** skill. Ordinary review requests use its light mode (inline review against the dimension quick checklists); the full multi-subagent deep mode runs only on explicit invocation.When designing or reviewing user-facing flows (empty/loading/error states, confirmations, async feedback, button hierarchy, lists at scale, pickers), follow LobeHub's design values in [`DESIGN.md`](./DESIGN.md) โ Natural / Meaningful / Certainty / Growth (่ช็ถ / ๆไนๆ / ็กฎๅฎๆง / ๆ้ฟ).--<!-- BEGIN:nextjs-agent-rules -->--# This is NOT the Next.js you know--This version has breaking changes โ APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.--**Keep this block, including in commits.** It is part of the project's agent setup, maintained by `next dev` for every agent that works here. If it appears as an uncommitted change, that is intentional โ commit it as-is. Do not remove it to clean up a diff; it will be regenerated.--<!-- END:nextjs-agent-rules -->diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex b7834f57b60..3515934e742 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -10,7 +10,6 @@ import FileIcon from '@/components/FileIcon';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';import {- AI_RUNTIME_OPERATION_TYPES,type QueuedFile,type QueuedMessage,reconstructUploadFilesFromQueue,@@ -128,14 +127,34 @@ const QueueTray = memo(() => {const { t } = useTranslation('chat');const context = useConversationStore((s) => s.context);+ // Key off the FULL context (threadId / scope / documentId / ...) so remove /+ // edit / send-now target the same bucket the queue is stored under and+ // getQueuedMessages reads from. A reduced agentId/groupId/topicId key would+ // operate on the wrong bucket for thread / page / group_agent conversations.+ // Pass the fields explicitly (not the `context` object, which may be a fresh+ // ref each render) so the memo deps stay stable primitives.const contextKey = useMemo(() =>messageMapKey({agentId: context.agentId,+ documentId: context.documentId,groupId: context.groupId,+ isNew: context.isNew,+ scope: context.scope,+ subAgentId: context.subAgentId,+ threadId: context.threadId,topicId: context.topicId,}),- [context.agentId, context.groupId, context.topicId],+ [+ context.agentId,+ context.documentId,+ context.groupId,+ context.isNew,+ context.scope,+ context.subAgentId,+ context.threadId,+ context.topicId,+ ],);const queuedMessages = useChatStore((s) => operationSelectors.getQueuedMessages(context)(s));@@ -168,11 +187,15 @@ const QueueTray = memo(() => {const handleSendNow = useCallback((msg: QueuedMessage) => {const chat = useChatStore.getState();- const runningOpId = chat.operationsByContext[contextKey]?.find((id) => {- const op = chat.operations[id];- return op && AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running';- });- if (runningOpId) chat.cancelOperation(runningOpId, 'send_now');+ // 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+ // two concurrent `regenerate` ops a delAndRegenerate/delAndResendThread+ // retry runs (outer wrapper + inner regenerateUserMessage). Leaving any+ // blocker running would make the sendMessage below re-enqueue the item, so+ // "Send now" becomes a no-op. The selector shares the queue-blocking+ // predicate with the enqueue check.+ const runningOpIds = operationSelectors.getRunningQueueBlockingOperationIds(context)(chat);+ for (const id of runningOpIds) chat.cancelOperation(id, 'send_now');removeQueuedMessage(contextKey, msg.id);// Reconstruct UploadFileItem-shaped objects so the optimistic temp messagediff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 1043649041f..0dfaae8d3e1 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -608,6 +608,119 @@ describe('Generation Actions', () => {expect(mockStartOperation).not.toHaveBeenCalled();expect(mockDeleteMessage).not.toHaveBeenCalled();});++ it('completes the retry even if a Stop cancels the outer op during delete (best-effort Stop)', async () => {+ const { useChatStore } = await import('@/store/chat');+ // The outer op is whitelisted (shows Stop); simulate a Stop landing while+ // deleteMessage is in flight by flipping the op to cancelled inside it.+ // The old message is already deleted, so bailing here would be destructive+ // data loss โ regeneration must proceed regardless (Stop is best-effort in+ // this sub-second window and applies to the fresh run instead).+ const chatState: any = {+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ cancelOperations: mockCancelOperations,+ cancelOperation: mockCancelOperation,+ regenerateUserMessage: mockRegenerateUserMessage,+ switchMessageBranch: mockSwitchMessageBranch,+ startOperation: mockStartOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ };+ chatState.deleteMessage = vi.fn().mockImplementation(async () => {+ chatState.operations = { 'test-op-id': { id: 'test-op-id', status: 'cancelled' } };+ });+ vi.mocked(useChatStore.getState).mockReturnValue(chatState);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ groupId: 'group-1',+ };++ const store = createStore({ context });++ act(() => {+ store.setState({+ displayMessages: [+ { id: 'msg-1', role: 'user', content: 'Hello' },+ { id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },+ ],+ } as any);+ });++ // delAndRegenerate calls the slice's OWN regenerateUserMessage (via get()),+ // not the useChatStore mock โ spy on it to assert (and short-circuit) it.+ const regenSpy = vi+ .spyOn(store.getState(), 'regenerateUserMessage')+ .mockResolvedValue(undefined);++ await act(async () => {+ await store.getState().delAndRegenerateMessage('msg-2');+ });++ // Delete ran, and regeneration completes atomically despite the cancelled+ // outer op โ no orphaned deletion.+ expect(chatState.deleteMessage).toHaveBeenCalledWith('msg-2', { operationId: 'test-op-id' });+ expect(regenSpy).toHaveBeenCalledWith('msg-1');+ expect(mockCompleteOperation).toHaveBeenCalled();+ });++ it('settles the wrapper op via failOperation when regeneration throws (no stuck loading)', async () => {+ const { useChatStore } = await import('@/store/chat');+ const chatState: any = {+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ cancelOperations: mockCancelOperations,+ cancelOperation: mockCancelOperation,+ deleteMessage: vi.fn().mockResolvedValue(undefined),+ switchMessageBranch: mockSwitchMessageBranch,+ startOperation: mockStartOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ };+ vi.mocked(useChatStore.getState).mockReturnValue(chatState);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ groupId: 'group-1',+ };++ const store = createStore({ context });++ act(() => {+ store.setState({+ displayMessages: [+ { id: 'msg-1', role: 'user', content: 'Hello' },+ { id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },+ ],+ } as any);+ });++ // Regeneration blows up mid-retry. Because `regenerate` now drives input+ // loading + queue blocking, the wrapper op MUST be settled โ otherwise the+ // input wedges in loading forever and future sends queue behind it.+ vi.spyOn(store.getState(), 'regenerateUserMessage').mockRejectedValue(new Error('boom'));++ await act(async () => {+ await expect(store.getState().delAndRegenerateMessage('msg-2')).rejects.toThrow('boom');+ });++ expect(mockFailOperation).toHaveBeenCalledWith(+ 'test-op-id',+ expect.objectContaining({ type: 'RegenerateError' }),+ );+ expect(mockCompleteOperation).not.toHaveBeenCalled();+ });});describe('delAndResendThreadMessage', () => {@@ -772,6 +885,104 @@ describe('Generation Actions', () => {);});+ it('should bail out if the interim op was cancelled during preflight (Stop pressed)', async () => {+ const { useChatStore } = await import('@/store/chat');+ vi.mocked(useChatStore.getState).mockReturnValue({+ messagesMap: {},+ // Simulate the user hitting Stop during the preflight awaits: stopGenerating+ // has already flipped the interim regenerate op to 'cancelled'.+ operations: { 'test-op-id': { id: 'test-op-id', status: 'cancelled' } },+ operationsByMessage: {},++ cancelOperations: mockCancelOperations,+ cancelOperation: mockCancelOperation,+ deleteMessage: mockDeleteMessage,+ switchMessageBranch: mockSwitchMessageBranch,+ startOperation: mockStartOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ };++ const store = createStore({ context });++ act(() => {+ store.setState({+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],+ } as any);+ });++ await act(async () => {+ await store.getState().regenerateUserMessage('msg-1');+ });++ // The interim op is still created up front (so the input shows loading+ // instantly)...+ expect(mockStartOperation).toHaveBeenCalledWith({+ context: { ...context, messageId: 'msg-1' },+ type: 'regenerate',+ });+ // ...but because Stop cancelled it during preflight, the run must NOT start.+ expect(mockSwitchMessageBranch).not.toHaveBeenCalled();+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ });++ it('should bail out if the interim op was cancelled during switchMessageBranch (Stop pressed)', async () => {+ const { useChatStore } = await import('@/store/chat');+ // The op passes the preflight guard as 'running', then a Stop lands while+ // switchMessageBranch is awaiting โ flip it to cancelled inside the mock.+ const chatState: any = {+ messagesMap: {},+ operations: { 'test-op-id': { id: 'test-op-id', status: 'running' } },+ operationsByMessage: {},+ dbMessages: [],+ cancelOperations: mockCancelOperations,+ cancelOperation: mockCancelOperation,+ deleteMessage: mockDeleteMessage,+ startOperation: mockStartOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ executeGatewayAgent: mockExecuteGatewayAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ };+ chatState.switchMessageBranch = vi.fn().mockImplementation(async () => {+ chatState.operations = { 'test-op-id': { id: 'test-op-id', status: 'cancelled' } };+ });+ vi.mocked(useChatStore.getState).mockReturnValue(chatState);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ };++ const store = createStore({ context });++ act(() => {+ store.setState({+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],+ } as any);+ });++ await act(async () => {+ await store.getState().regenerateUserMessage('msg-1');+ });++ // The branch switch ran (preflight passed), but the Stop during it must+ // stop the runtime from starting.+ expect(chatState.switchMessageBranch).toHaveBeenCalled();+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ expect(mockExecuteGatewayAgent).not.toHaveBeenCalled();+ });+it('should restore mention-based initialContext when regenerating a user message', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 434904f7284..d7d152627b9 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -459,13 +459,30 @@ export const generationSlice: StateCreator<type: 'regenerate',});- // IMPORTANT: Delete first, then regenerate- // If we regenerate first, it switches to a new branch, causing the original- // message to no longer appear in displayMessages. Then deleteMessage cannot- // find the message and fails silently.- await chatStore.deleteMessage(messageId, { operationId });- await get().regenerateUserMessage(userId);- chatStore.completeOperation(operationId);+ try {+ // IMPORTANT: Delete first, then regenerate+ // If we regenerate first, it switches to a new branch, causing the original+ // message to no longer appear in displayMessages. Then deleteMessage cannot+ // find the message and fails silently.+ await chatStore.deleteMessage(messageId, { operationId });++ // NOTE: intentionally do NOT bail on Stop here. The old assistant message is+ // already deleted above; returning early would leave the turn deleted with+ // nothing regenerated โ destructive data loss. Stop pressed in this+ // sub-second window is best-effort; complete the retry atomically and honor+ // the next Stop (on the fresh run) normally.+ await get().regenerateUserMessage(userId);+ chatStore.completeOperation(operationId);+ } catch (error) {+ // Settle the wrapper op on failure. `regenerate` now drives input-loading ++ // queue-blocking, so a never-settled op would wedge the input in loading+ // forever and queue every future send behind it.+ chatStore.failOperation(operationId, {+ message: error instanceof Error ? error.message : String(error),+ type: 'RegenerateError',+ });+ throw error;+ }},delAndResendThreadMessage: async (messageId: string) => {@@ -478,10 +495,28 @@ export const generationSlice: StateCreator<type: 'regenerate',});- // Resend then delete- await get().resendThreadMessage(messageId);- await chatStore.deleteMessage(messageId, { operationId });- chatStore.completeOperation(operationId);+ try {+ // Resend then delete+ await get().resendThreadMessage(messageId);++ // Honor a Stop pressed during the resend: the whitelisted outer op gets+ // cancelled by stopGenerating, so skip the follow-up delete and leave the+ // original message intact rather than mutating state after Stop. The+ // cancelled op is no longer `running`, so it stops driving loading โ no+ // need to settle it here.+ const outerOp = operationSelectors.getOperationById(operationId)(useChatStore.getState());+ if (outerOp && outerOp.status !== 'running') return;++ await chatStore.deleteMessage(messageId, { operationId });+ chatStore.completeOperation(operationId);+ } catch (error) {+ // Settle the wrapper op on failure โ see delAndRegenerateMessage.+ chatStore.failOperation(operationId, {+ message: error instanceof Error ? error.message : String(error),+ type: 'RegenerateError',+ });+ throw error;+ }},openThreadCreator: (messageId: string) => {@@ -601,28 +636,48 @@ export const generationSlice: StateCreator<const currentIndex = displayMessages.findIndex((c) => c.id === messageId);const item = displayMessages[currentIndex];if (!item) return;- const initialContext = mergeAgentRuntimeInitialContexts(- await resolveActiveTopicDocumentInitialContext(context),- buildRetryInitialContext(item.editorData),- );-- // Get context messages up to and including the target message- const contextMessages = displayMessages.slice(0, currentIndex + 1);- if (contextMessages.length <= 0) return;-- // ===== Hook: onBeforeRegenerate =====- if (hooks.onBeforeRegenerate) {- const shouldProceed = await hooks.onBeforeRegenerate(messageId);- if (shouldProceed === false) return;- }-- // Create regenerate operation with context+ // Start the interim regenerate op BEFORE the async preflight below+ // (document-context resolve + onBeforeRegenerate hook). In page / bound-+ // document contexts those reads are real round trips, so creating the op+ // afterwards would leave the input/Stop state dead during exactly the+ // pre-generation window the INPUT_LOADING_OPERATION_TYPES whitelist covers.+ // Complete it if any preflight guard bails out before generation starts.const { operationId } = chatStore.startOperation({context: { ...context, messageId },type: 'regenerate',});try {+ const initialContext = mergeAgentRuntimeInitialContexts(+ await resolveActiveTopicDocumentInitialContext(context),+ buildRetryInitialContext(item.editorData),+ );++ // Get context messages up to and including the target message+ const contextMessages = displayMessages.slice(0, currentIndex + 1);+ if (contextMessages.length <= 0) {+ chatStore.completeOperation(operationId);+ return;+ }++ // ===== Hook: onBeforeRegenerate =====+ if (hooks.onBeforeRegenerate) {+ const shouldProceed = await hooks.onBeforeRegenerate(messageId);+ if (shouldProceed === false) {+ chatStore.completeOperation(operationId);+ return;+ }+ }++ // If the user hit Stop during the preflight awaits above, stopGenerating has+ // already cancelled this interim op (cancelOperation flips its status but+ // keeps the record). Bail out before switching branches or starting a run โ+ // otherwise the Stop is swallowed and a new assistant turn starts anyway. No+ // child runtime exists yet, so cancelOperation had nothing to propagate to;+ // this is the only place that can honour the Stop.+ const preflightOp = operationSelectors.getOperationById(operationId)(useChatStore.getState());+ if (preflightOp && preflightOp.status !== 'running') return;+// Calculate next branch index by counting children of this user message// We need to count how many assistant messages have this user message as parentconst { dbMessages } = get();@@ -635,6 +690,15 @@ export const generationSlice: StateCreator<operationId,});+ // Re-check after switchMessageBranch: it is another await round-trip, so a+ // Stop pressed during it lands *after* the preflight guard above. Bail+ // before starting the runtime so the Stop isn't swallowed. The branch is+ // already switched, which is harmless โ no assistant turn has started yet.+ const postSwitchOp = operationSelectors.getOperationById(operationId)(+ useChatStore.getState(),+ );+ if (postSwitchOp && postSwitchOp.status !== 'running') return;+const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.tsindex ede9152d4d5..778b0ba5859 100644--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts@@ -32,7 +32,10 @@ vi.mock('@/store/chat/utils/activeTopicDocumentContext', () => ({}));vi.mock('@/store/chat/slices/operation/selectors', () => ({- operationSelectors: { isMessageProcessing: () => () => false },+ operationSelectors: {+ getOperationById: () => () => undefined,+ isMessageProcessing: () => () => false,+ },}));vi.mock('@/services/message', () => ({diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex 0f06c3a1d43..6b627bf584e 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -640,6 +640,58 @@ describe('ConversationControl actions', () => {expect(executeClientAgentSpy).not.toHaveBeenCalled();});+ it('completes the approval even if a Stop lands mid optimistic write (best-effort Stop)', async () => {+ const { result } = renderHook(() => useChatStore());++ const agentId = 'global-agent';+ const topicId = 'global-topic';++ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },+ });++ const globalKey = messageMapKey({ agentId, topicId });++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [globalKey]: [toolMessage] },+ messagesMap: { [globalKey]: [toolMessage] },+ });+ });++ // Simulate a Stop pressed while the optimistic update is in flight: cancel+ // the just-created interim op from inside the awaited optimistic write.+ // `intervention: approved` is already persisted, so bailing here would+ // leave the tool approved-but-never-executed (stuck). The approval must+ // complete atomically โ Stop is best-effort in this sub-second window.+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockImplementation(+ async (_id, _value, ctx) => {+ if (ctx?.operationId) result.current.cancelOperation(ctx.operationId);+ },+ );+ // Stub the runtime setup so the assertion targets "did we reach the run?",+ // not the full agent-config resolution.+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ state: {},+ context: {},+ } as any);+ const executeClientAgentSpy = vi+ .spyOn(result.current, 'executeClientAgent')+ .mockResolvedValue(undefined);++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-1', 'group-1');+ });++ // The run proceeds despite the cancelled op โ no stuck approval.+ expect(executeClientAgentSpy).toHaveBeenCalled();+ });+describe('server-mode branch', () => {it('should start a new Gateway op with resumeApproval.decision=approved and NOT run local runtime', async () => {const { result } = renderHook(() => useChatStore());@@ -1629,6 +1681,47 @@ describe('ConversationControl actions', () => {executeGatewayAgentSpy.mockRestore();});});++ it('should bail before running if a Stop cancels the interim op during synthetic message creation', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'global-agent';+ const topicId = 'global-topic';+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },+ });+ const globalKey = messageMapKey({ agentId, topicId });+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [globalKey]: [toolMessage] },+ messagesMap: { [globalKey]: [toolMessage] },+ });+ });++ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ // Stop lands while the synthetic user message is being created โ a later+ // await than the guard before it.+ vi.spyOn(result.current, 'optimisticCreateMessage').mockImplementation(async (_msg, ctx) => {+ if (ctx?.operationId) result.current.cancelOperation(ctx.operationId);+ return { id: 'submitted-user-msg', messages: [] } as any;+ });+ const internal_createAgentStateSpy = vi.spyOn(result.current, 'internal_createAgentState');+ const executeClientAgentSpy = vi+ .spyOn(result.current, 'executeClientAgent')+ .mockResolvedValue(undefined);++ await act(async () => {+ await result.current.submitToolInteraction('tool-msg-1', { answer: 'blue' });+ });++ expect(internal_createAgentStateSpy).not.toHaveBeenCalled();+ expect(executeClientAgentSpy).not.toHaveBeenCalled();+ });});describe('skipToolInteraction', () => {@@ -1870,6 +1963,47 @@ describe('ConversationControl actions', () => {}),);});++ it('should bail before running if a Stop cancels the interim op during synthetic message creation', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'global-agent';+ const topicId = 'global-topic';+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },+ });+ const globalKey = messageMapKey({ agentId, topicId });+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [globalKey]: [toolMessage] },+ messagesMap: { [globalKey]: [toolMessage] },+ });+ });++ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ // Stop lands while the synthetic user message is being created โ a later+ // await than the guard before it.+ vi.spyOn(result.current, 'optimisticCreateMessage').mockImplementation(async (_msg, ctx) => {+ if (ctx?.operationId) result.current.cancelOperation(ctx.operationId);+ return { id: 'skipped-user-msg', messages: [] } as any;+ });+ const internal_createAgentStateSpy = vi.spyOn(result.current, 'internal_createAgentState');+ const executeClientAgentSpy = vi+ .spyOn(result.current, 'executeClientAgent')+ .mockResolvedValue(undefined);++ await act(async () => {+ await result.current.skipToolInteraction('tool-msg-1', 'not needed');+ });++ expect(internal_createAgentStateSpy).not.toHaveBeenCalled();+ expect(executeClientAgentSpy).not.toHaveBeenCalled();+ });});describe('rejectAndContinueToolCalling', () => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex edc45a3dc1f..af0708cb7b5 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -1251,6 +1251,57 @@ describe('ConversationLifecycle actions', () => {);});+ it('should enqueue behind a running interim approve/retry op (preflight window)', async () => {+ // Interim ops (approve/submit/skip/regenerate) show input loading the+ // instant the user clicks, but the real runtime op is only created 2โ4+ // tRPC round-trips later. A fast follow-up Enter in that window must+ // queue behind the interim op โ not fire a concurrent sendMessage that+ // interleaves with the approve/retry flow. Guards QUEUE_BLOCKING staying+ // in sync with INPUT_LOADING for INTERIM_LOADING_OPERATION_TYPES.+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-regenerate': {+ childOperationIds: [],+ context,+ id: 'op-regenerate',+ metadata: {},+ status: 'running',+ type: 'regenerate',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-regenerate'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');+ const sendMessageInServerSpy = vi.spyOn(aiChatService, 'sendMessageInServer');++ await act(async () => {+ await result.current.sendMessage({+ context,+ message: 'follow-up during regenerate preflight',+ });+ });++ expect(enqueueMessageSpy).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({+ content: 'follow-up during regenerate preflight',+ interruptMode: 'soft',+ }),+ 'op-regenerate',+ );+ // Must queue, not start a concurrent send.+ expect(sendMessageInServerSpy).not.toHaveBeenCalled();+ });+it('should enqueue while the first new-topic message is still being persisted', async () => {const { result } = renderHook(() => useChatStore());const context = createTestContext();diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex e18f16fb904..5a8c3da5d54 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -281,6 +281,20 @@ export class ConversationControlActionImpl {});};+ /**+ * Honor a Stop pressed during the optimistic-write window. Interim ops+ * (approve / submit / skip) are created synchronously, but their optimistic+ * updates await, so a Stop landing in that gap cancels the op via+ * `stopGenerating` โ `cancelOperations`. Detect the cancelled/terminal op and+ * bail before starting the run instead of resurrecting a stopped conversation.+ * `cancelOperation` flips status but keeps the record, so a real Stop always+ * leaves the op present here. Mirrors regenerateUserMessage's preflight guard.+ */+ #wasInterimOpStopped = (operationId: string): boolean => {+ const op = this.#get().operations[operationId];+ return !!op && op.status !== 'running';+ };+approveToolCalling = async (toolMessageId: string,_assistantGroupId: string,@@ -305,11 +319,13 @@ export class ConversationControlActionImpl {// This ensures optimistic updates use the correct agentId/topicIdconst { operationId } = startOperation({type: 'approveToolCalling',+ // Carry the full effective context (groupId / documentId / scope / โฆ) so the+ // interim op lands in the same messageMapKey bucket the UI queries. A cherry-+ // picked context without groupId would bucket group conversations under+ // `main_<agentId>` while the UI reads `group_<groupId>`, so the input-loading+ // whitelist never matches there. Mirrors execServerAgentRuntime's execContext.context: {- agentId,- topicId: topicId ?? undefined,- threadId: threadId ?? undefined,- scope,+ ...effectiveContext,messageId: toolMessageId,},});@@ -332,6 +348,12 @@ export class ConversationControlActionImpl {{ intervention: { status: 'approved' } },optimisticContext,);++ // NOTE: intentionally do NOT bail on Stop here. `intervention: approved` is+ // already persisted above; returning early would leave the tool marked+ // approved but never executed โ a stuck conversation. Stop pressed in this+ // sub-second window is best-effort (the paused run can't be aborted yet);+ // let the approval complete atomically and honor the next Stop normally.const requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);// 2.5. Server-mode: start a **new** Gateway op carrying the approval@@ -458,11 +480,12 @@ export class ConversationControlActionImpl {const { operationId } = startOperation({type: 'submitToolInteraction',+ // Carry the full effective context so the interim op is bucketed under the+ // same messageMapKey the UI queries (group / page need groupId / documentId,+ // not just agentId) โ otherwise the input-loading whitelist never matches+ // there. Mirrors execServerAgentRuntime's execContext.context: {- agentId,- topicId: topicId ?? undefined,- threadId: threadId ?? undefined,- scope,+ ...effectiveContext,messageId: toolMessageId,},});@@ -503,6 +526,12 @@ export class ConversationControlActionImpl {);}+ // NOTE: intentionally do NOT bail on Stop here. `intervention: approved`+ // and the tool result are already persisted above; returning early would+ // leave the submission recorded but never resumed โ a stuck conversation.+ // Same best-effort rationale as approveToolCalling: complete atomically and+ // honor the next Stop normally.+// 1.5. Server-mode: start a **new** Gateway op carrying the human answer as// the tool result via `resumeToolResult`. The server writes the answer as// the pending tool message's content, marks intervention approved, and@@ -634,6 +663,12 @@ export class ConversationControlActionImpl {return;}+ // Bail if a Stop landed while the synthetic user message was being created:+ // optimisticCreateMessage above is another await round-trip after the earlier+ // guard, and executeClientAgent would otherwise start a fresh child run that+ // wasn't present when the cancellation propagated.+ if (this.#wasInterimOpStopped(operationId)) return;+// 3. Resume agent from user message (not tool re-execution)const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());@@ -688,11 +723,12 @@ export class ConversationControlActionImpl {const { operationId } = startOperation({type: 'skipToolInteraction',+ // Carry the full effective context so the interim op is bucketed under the+ // same messageMapKey the UI queries (group / page need groupId / documentId,+ // not just agentId) โ otherwise the input-loading whitelist never matches+ // there. Mirrors execServerAgentRuntime's execContext.context: {- agentId,- topicId: topicId ?? undefined,- threadId: threadId ?? undefined,- scope,+ ...effectiveContext,messageId: toolMessageId,},});@@ -723,6 +759,10 @@ export class ConversationControlActionImpl {optimisticContext,);+ // Bail if a Stop landed while the optimistic updates above were in flight,+ // before creating the synthetic user message so Stop leaves no dangling turn.+ if (this.#wasInterimOpStopped(operationId)) return;+// 2. Create a user message indicating the skipconst chatKey = messageMapKey({ agentId, topicId, threadId, scope });const requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);@@ -749,6 +789,12 @@ export class ConversationControlActionImpl {return;}+ // Bail if a Stop landed while the synthetic user message was being created:+ // optimisticCreateMessage above is another await round-trip after the guard+ // before it, and executeClientAgent would otherwise start a fresh child run+ // that wasn't present when the cancellation propagated.+ if (this.#wasInterimOpStopped(operationId)) return;+// 3. Resume agent from user messageconst currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 250565fd955..6f6fbe11858 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -52,7 +52,7 @@ import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecyclimport type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';import { resolveHeteroResume } from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';import type { OperationType, QueuedFile } from '@/store/chat/slices/operation/types';-import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import { QUEUE_BLOCKING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';import { type ChatStore } from '@/store/chat/store';@@ -151,10 +151,7 @@ const isAbortError = (error: unknown, abortController?: AbortController) =>const createAbortError = () =>Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });-const QUEUE_BLOCKING_OPERATION_TYPES = new Set<OperationType>([- ...AI_RUNTIME_OPERATION_TYPES,- 'sendMessage',-]);+const QUEUE_BLOCKING_OPERATION_TYPE_SET = new Set<OperationType>(QUEUE_BLOCKING_OPERATION_TYPES);const attachSendTimeMetadataToUserMessage = (messages: UIChatMessage[],@@ -425,7 +422,9 @@ export class ConversationLifecycleActionImpl {const contextOpIds = this.#get().operationsByContext[currentContextKey] || [];const runningQueueBlockingOp = contextOpIds.map((id) => this.#get().operations[id])- .find((op) => op && QUEUE_BLOCKING_OPERATION_TYPES.has(op.type) && op.status === 'running');+ .find(+ (op) => op && QUEUE_BLOCKING_OPERATION_TYPE_SET.has(op.type) && op.status === 'running',+ );if (runningQueueBlockingOp) {// Snapshot file previews so the tray can render thumbnails AND thediff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.tsindex 8c6b117adab..18222325fd8 100644--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts@@ -2,14 +2,75 @@ import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it } from 'vitest';import { useChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { operationSelectors } from '../selectors';+import {+ INPUT_LOADING_OPERATION_TYPES,+ INTERIM_LOADING_OPERATION_TYPES,+ QUEUE_BLOCKING_OPERATION_TYPES,+} from '../types';describe('Operation Selectors', () => {beforeEach(() => {useChatStore.setState(useChatStore.getInitialState());});+ // Coherence invariant: interim approve/submit/skip/regenerate ops must live in+ // BOTH whitelists. If the input shows loading for an op (INPUT_LOADING), a+ // follow-up must queue behind it and "Send now" must be able to cancel it+ // (QUEUE_BLOCKING). Dropping them from either set silently reintroduces the+ // interleave / stuck-queue / no-op-send-now bugs.+ describe('operation-type set invariants', () => {+ it('keeps interim ops in both INPUT_LOADING and QUEUE_BLOCKING', () => {+ for (const type of INTERIM_LOADING_OPERATION_TYPES) {+ expect(INPUT_LOADING_OPERATION_TYPES).toContain(type);+ expect(QUEUE_BLOCKING_OPERATION_TYPES).toContain(type);+ }+ });+ });++ describe('getRunningQueueBlockingOperationIds', () => {+ it('returns every running queue-blocking op, not just the first', () => {+ // A delAndRegenerate/delAndResendThread retry runs two concurrent+ // `regenerate` ops (outer wrapper + inner regenerateUserMessage). "Send now"+ // must cancel BOTH โ returning only the first would leave the queue blocked.+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };+ let outerId = '';+ let innerId = '';++ act(() => {+ outerId = result.current.startOperation({ type: 'regenerate', context }).operationId;+ innerId = result.current.startOperation({ type: 'regenerate', context }).operationId;+ });++ const ids = operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current);+ expect(ids).toHaveLength(2);+ expect(ids).toEqual(expect.arrayContaining([outerId, innerId]));+ });++ it('excludes non-running and non-blocking ops', () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };+ let runningId = '';++ act(() => {+ runningId = result.current.startOperation({ type: 'regenerate', context }).operationId;+ // Different queue-blocking op, but completed โ excluded.+ const doneId = result.current.startOperation({+ type: 'execAgentRuntime',+ context,+ }).operationId;+ result.current.completeOperation(doneId);+ });++ expect(+ operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current),+ ).toEqual([runningId]);+ });+ });+describe('getOperationsByType', () => {it('should return operations of specific type', () => {const { result } = renderHook(() => useChatStore());@@ -41,6 +102,49 @@ describe('Operation Selectors', () => {});});+ describe('getRunningQueueBlockingOperationIds', () => {+ it('returns every running queue blocker for send-now in the same context', () => {+ const { result } = renderHook(() => useChatStore());++ let outerRegenerate: string;+ let innerRegenerate: string;++ act(() => {+ outerRegenerate = result.current.startOperation({+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ type: 'regenerate',+ }).operationId;+ innerRegenerate = result.current.startOperation({+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ type: 'regenerate',+ }).operationId;+ const completedRegenerate = result.current.startOperation({+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ type: 'regenerate',+ }).operationId;+ result.current.startOperation({+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ type: 'toolCalling',+ });+ result.current.startOperation({+ context: { agentId: 'agent-2', topicId: 'topic-2' },+ type: 'regenerate',+ });+ result.current.completeOperation(completedRegenerate);+ });++ // Regression: delAndRegenerate/delAndResendThread can leave both an outer+ // wrapper regenerate and an inner regenerateUserMessage running. Send-now+ // must cancel both; cancelling only the first makes it re-queue.+ expect(+ operationSelectors.getRunningQueueBlockingOperationIds({+ agentId: 'agent-1',+ topicId: 'topic-1',+ })(result.current),+ ).toEqual([outerRegenerate!, innerRegenerate!]);+ });+ });+describe('getCurrentContextOperations', () => {it('should return operations for current active session/topic', () => {const { result } = renderHook(() => useChatStore());@@ -612,6 +716,128 @@ describe('Operation Selectors', () => {).toBeUndefined();});+ it('should keep visible loading when a queued message waits behind a visibly-done op', () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };++ act(() => {+ useChatStore.setState({ activeAgentId: 'agent1', activeTopicId: 'topic1' });++ // Prior op has finished its visible output but hasn't reached its+ // terminal end yet (visibleLoadingDone), so it is not visibly running.+ result.current.startOperation({+ type: 'execAgentRuntime',+ context,+ metadata: { startTime: 1000, visibleLoadingDone: true },+ });+ });++ // Sanity: without a queued message the input reads idle in this window.+ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(+ false,+ );++ // User sends a follow-up while the op is still running: it queues without+ // its own op. The visible loading must stay on so the input doesn't look idle.+ act(() => {+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'follow-up',+ createdAt: 1200,+ id: 'queued-1',+ interruptMode: 'soft',+ });+ });++ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(true);+ });++ it('should not pin visible loading on a stale queue once the op is no longer running', () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };++ let opId!: string;+ act(() => {+ useChatStore.setState({ activeAgentId: 'agent1', activeTopicId: 'topic1' });+ opId = result.current.startOperation({+ type: 'execAgentRuntime',+ context,+ metadata: { startTime: 1000, visibleLoadingDone: true },+ }).operationId;+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'follow-up',+ createdAt: 1200,+ id: 'queued-1',+ interruptMode: 'soft',+ });+ });++ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(true);++ // A cancelled/errored run never drains its queue; with no running op left,+ // the leftover queue must not keep the indicator pinned on.+ act(() => {+ result.current.cancelOperation(opId);+ });++ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(+ false,+ );+ });++ it('should find a queued follow-up in a thread-scope context (full context key)', () => {+ const { result } = renderHook(() => useChatStore());+ // Thread scope keys on threadId/scope; a reduced agentId/topicId key would+ // collapse to the main-scope bucket and miss the queue.+ const context = {+ agentId: 'agent1',+ scope: 'thread' as const,+ threadId: 'thread1',+ topicId: 'topic1',+ };++ act(() => {+ useChatStore.setState({ activeAgentId: 'agent1', activeTopicId: 'topic1' });+ result.current.startOperation({+ type: 'execAgentRuntime',+ context,+ metadata: { startTime: 1000, visibleLoadingDone: true },+ });+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'follow-up',+ createdAt: 1200,+ id: 'queued-1',+ interruptMode: 'soft',+ });+ });++ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(true);+ });++ it('should count a queued follow-up in a thread-scope context (QueueTray mounts)', () => {+ const { result } = renderHook(() => useChatStore());+ // queuedMessageCount gates whether QueueTray mounts. It must key off the+ // same full context as getQueuedMessages/enqueue โ a reduced+ // agentId/topicId key would report 0 here and hide the tray even though a+ // real queued message is pinning the input loading.+ const context = {+ agentId: 'agent1',+ scope: 'thread' as const,+ threadId: 'thread1',+ topicId: 'topic1',+ };++ act(() => {+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'follow-up',+ createdAt: 1200,+ id: 'queued-1',+ interruptMode: 'soft',+ });+ });++ expect(operationSelectors.queuedMessageCount(context)(result.current)).toBe(1);+ });+it('should keep visible loading for a normal running runtime operation', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex 95f19e55097..f04c0d29831 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -3,7 +3,11 @@ import { messageMapKey, type MessageMapKeyInput } from '@/store/chat/utils/messaimport { topicMapKey } from '@/store/chat/utils/topicMapKey';import { type Operation, type OperationType } from './types';-import { AI_RUNTIME_OPERATION_TYPES, INPUT_LOADING_OPERATION_TYPES } from './types';+import {+ AI_RUNTIME_OPERATION_TYPES,+ INPUT_LOADING_OPERATION_TYPES,+ QUEUE_BLOCKING_OPERATION_TYPES,+} from './types';// === Basic Queries ===/**@@ -244,6 +248,23 @@ const isAgentRuntimeVisiblyRunningByContext =);};+/**+ * All running queue-blocking operation ids in a context (see+ * QUEUE_BLOCKING_OPERATION_TYPES). "Send now" cancels every one of them, not just+ * the first: a retry via delAndRegenerate/delAndResendThread runs an outer+ * wrapper `regenerate` op AND an inner regenerateUserMessage `regenerate` op at+ * once, so cancelling only one would leave the queue blocked and make "Send now"+ * a no-op during that retry window.+ */+const getRunningQueueBlockingOperationIds =+ (context: MessageMapKeyInput) =>+ (s: ChatStoreState): string[] => {+ if (!context.agentId) return [];+ return getOperationsByContext(context)(s)+ .filter((op) => QUEUE_BLOCKING_OPERATION_TYPES.includes(op.type) && op.status === 'running')+ .map((op) => op.id);+ };+/*** Get the earliest start time for a running agent runtime operation in a* specific context. This anchors visible elapsed-time UI to the top-level@@ -330,9 +351,24 @@ const isInputVisiblyLoadingByContext =const operations = getOperationsByContext(context)(s);- return operations.some(+ const hasVisiblyRunning = operations.some((op) => INPUT_LOADING_OPERATION_TYPES.includes(op.type) && isVisiblyRunningOperation(op),);+ if (hasVisiblyRunning) return true;++ // A queued message is a follow-up the user already sent while a prior op was+ // running; it gets no op of its own until that op ends and the queue drains.+ // In the window where the prior op has finished its *visible* output+ // (visibleLoadingDone) but hasn't reached its terminal end yet, there is no+ // visibly-running op and no op for the queued message, so the input would+ // look idle even though a send is pending. Keep the visible loading on while+ // some INPUT_LOADING op is still running to absorb the queue. Gate on a+ // still-running op so a stale queue left by a cancelled/errored run (which+ // never drains) doesn't pin the indicator on forever.+ const hasRunning = operations.some(+ (op) => INPUT_LOADING_OPERATION_TYPES.includes(op.type) && isRunningOperation(op),+ );+ return hasRunning && getQueuedMessages(context)(s).length > 0;};// === Backward Compatibility ===@@ -747,31 +783,28 @@ const unreadCompletedCountForTopics =* Get queued messages count for a context*/const queuedMessageCount =- (context: { agentId?: string; groupId?: string; topicId?: string | null }) =>- (s: ChatStoreState): number => {- if (!context.agentId) return 0;- const contextKey = messageMapKey({- agentId: context.agentId,- groupId: context.groupId,- topicId: context.topicId,- });- return s.queuedMessages[contextKey]?.length ?? 0;- };+ (context: MessageMapKeyInput) =>+ (s: ChatStoreState): number =>+ // Delegate to getQueuedMessages so the count keys off the SAME full context+ // (threadId / scope / documentId / ...) the queue is stored under. A reduced+ // agentId/groupId/topicId key here would report 0 for thread / page /+ // group_agent follow-ups, so QueueTray would never mount even though the+ // input is pinned loading by a real queued message.+ getQueuedMessages(context)(s).length;/*** Get all queued messages for a context*/-const getQueuedMessages =- (context: { agentId?: string; groupId?: string; topicId?: string | null }) =>- (s: ChatStoreState) => {- if (!context.agentId) return [];- const contextKey = messageMapKey({- agentId: context.agentId,- groupId: context.groupId,- topicId: context.topicId,- });- return s.queuedMessages[contextKey] ?? [];- };+const getQueuedMessages = (context: MessageMapKeyInput) => (s: ChatStoreState) => {+ if (!context.agentId) return [];+ // Build the key from the FULL context (threadId / scope / subAgentId /+ // documentId), matching both the enqueue side (`messageMapKey(operationContext)`+ // in conversationLifecycle) and getOperationsByContext. A reduced+ // agentId/groupId/topicId key collapses thread / page / group_agent+ // conversations onto the main-scope bucket, so their queued follow-ups would+ // never be found.+ return s.queuedMessages[messageMapKey(context)] ?? [];+};/*** Operation Selectors@@ -793,6 +826,7 @@ export const operationSelectors = {getOperationsByMessage,getOperationsByType,getRunningOperations,+ getRunningQueueBlockingOperationIds,getRunningToolCallStartTime,hasAnyRunningOperation,hasRunningOperationByContext,diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 1ae8e1f734a..a8a7124412d 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -408,6 +408,29 @@ export const AI_RUNTIME_OPERATION_TYPES: OperationType[] = ['execServerAgentRuntime',];+/**+ * Interim operations that approve / submit / skip / regenerate each start+ * synchronously on click, before the whitelisted `execServerAgentRuntime` op is+ * created 2โ4 serial tRPC round-trips later. The interim op stays running until+ * `executeGatewayAgent` spins up the runtime op, so it bridges the pre-generation+ * window seamlessly.+ *+ * Shared by two whitelists so the whole window behaves consistently:+ * - INPUT_LOADING_OPERATION_TYPES โ show input loading/Stop the instant the user clicks.+ * - QUEUE_BLOCKING_OPERATION_TYPES โ a fast follow-up Enter queues behind the interim+ * op instead of starting a concurrent `sendMessage` that interleaves with the+ * approve/retry flow before the real runtime op exists.+ *+ * Kept out of AI_RUNTIME_OPERATION_TYPES on purpose to avoid flipping+ * isAgentRuntimeRunning / isMessageGenerating and their gating logic.+ */+export const INTERIM_LOADING_OPERATION_TYPES: OperationType[] = [+ 'approveToolCalling',+ 'submitToolInteraction',+ 'skipToolInteraction',+ 'regenerate',+];+/*** Operation types that should block input and show loading state* Superset of AI_RUNTIME_OPERATION_TYPES, also includes sendMessage@@ -419,4 +442,32 @@ export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [// The auto-retry waiting period is part of the same in-progress turn โ keep// the input in loading state (and let Stop target it) across the countdown.'autoRetryPending',+ // Interim approve/submit/skip/regenerate ops light up the input the instant+ // the user clicks, mirroring how `sendMessage` already does โ instead of only+ // after the round-trips. See INTERIM_LOADING_OPERATION_TYPES for the bridge+ // semantics and why they stay out of AI_RUNTIME_OPERATION_TYPES.+ //+ // Known limitation (accepted): this also makes Stop appear during the pre-+ // generation window. Because these gateway branches don't forward+ // `parentOperationId` to `executeGatewayAgent`, hitting Stop in that narrow+ // window doesn't actually abort the in-flight request (loading briefly+ // flickers, generation proceeds). No stuck state; wiring the abort handoff+ // through these branches is deferred.+ ...INTERIM_LOADING_OPERATION_TYPES,+];++/**+ * Operation types that block a fresh `sendMessage`: a send fired while one of+ * these runs enqueues behind it instead of starting a concurrent run.+ *+ * Single source of truth shared by the enqueue check (conversationLifecycle) and+ * the QueueTray "Send now" cancel path โ so both agree on what a follow-up is+ * queued behind. Kept in sync with INPUT_LOADING via the shared+ * INTERIM_LOADING_OPERATION_TYPES: if the input shows loading for an op, a+ * follow-up must queue behind it, and "Send now" must be able to cancel it.+ */+export const QUEUE_BLOCKING_OPERATION_TYPES: OperationType[] = [+ ...AI_RUNTIME_OPERATION_TYPES,+ 'sendMessage',+ ...INTERIM_LOADING_OPERATION_TYPES,];