Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(agent): steer a running task, and a clean end at the limit (CA U2, U6)

purple5ae6e67e888a
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 91619e81..ad982c45 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -111,6 +111,12 @@ interface Props {
* yet, and the list says so (hooks/useMentionRoot.ts).
*/
mentionRoot?: MentionRoot | null
+ /** CA U2: set while a run of this chat can take a message mid-run. Enter
+ * then queues the text instead of doing nothing. */
+ onSteer?: (text: string) => void
+ /** Messages waiting to be read by the run, shown above the field. */
+ steerQueue?: readonly { id: string; text: string }[]
+ onUnsteer?: (id: string) => void
}
/**
@@ -155,7 +161,7 @@ interface SendLock {
message: string
}
-export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pendingApproval, onApprove, onReject, disabled, modelReady, slashCommands, composerModel, composerActions, composerAbove, filesReachTools = false, draftScope = 'chat', mentionRoot }: Props) {
+export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pendingApproval, onApprove, onReject, disabled, modelReady, slashCommands, composerModel, composerActions, composerAbove, filesReachTools = false, draftScope = 'chat', mentionRoot, onSteer, steerQueue, onUnsteer }: Props) {
// What this composer held when its view closed last (lib/chat-drafts.ts):
// the draft of the open chat goes straight into the field, the rest into
// `entwuerfe` below. Read once, on mount.
@@ -616,6 +622,14 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const handleSend = () => {
// Enter ends the last word as a space would, so an emoticon there turns.
const trimmed = (emojiOn ? turnOnSend(input) : input).trim()
+ // CA U2: during a run, a plain message waits for the run to read it after
+ // its current step. Attachments and commands still wait for the run's end.
+ if (isGenerating && onSteer && trimmed && !trimmed.startsWith('/') && images.length === 0 && files.length === 0 && media.length === 0 && !disabled) {
+ onSteer(trimmed)
+ setInput('')
+ setMention(null)
+ return
+ }
if (imageJob.current.busy || fileJob.current.busy || (!trimmed && images.length === 0 && files.length === 0 && media.length === 0) || isGenerating || waitingForLocalLane || disabled) return
// No chat model to answer: the send handlers return without a word in that
// case, and the lines below would then empty the field and the chips for a
@@ -967,6 +981,29 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
instruction that steers every turn is never invisible. */}
{composerAbove}
+ {/* CA U2: what the user wrote during the run, until the run reads it. */}
+ {steerQueue && steerQueue.length > 0 && (
+ <div className="px-2.5 pt-2 space-y-1" data-testid="steer-queue">
+ {steerQueue.map((m) => (
+ <div key={m.id} className="flex items-start gap-2 rounded-md bg-gray-100 dark:bg-white/[0.05] px-2 py-1">
+ <span className="t-micro text-gray-500 dark:text-gray-400 shrink-0 pt-0.5">Next step reads</span>
+ <span className="t-control text-gray-700 dark:text-gray-200 flex-1 min-w-0 break-words line-clamp-3">{m.text}</span>
+ {onUnsteer && (
+ <button
+ type="button"
+ onClick={() => onUnsteer(m.id)}
+ aria-label="Take this message back"
+ title="Take this message back"
+ className="shrink-0 p-0.5 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-black/5 dark:hover:bg-white/10"
+ >
+ <X size={12} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
{/* G31: the run is STOPPED until this is answered, so the answer has to
be where the user's eyes already are. The inline buttons on the tool
block are still there and still the nicer place to decide from, but
@@ -1089,7 +1126,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
onKeyDown={handleKeyDown}
onBlur={() => setTimeout(() => { setCmdMenu([]); setMention(null) }, 120)}
onPaste={handlePaste}
- placeholder={disabled ? "Unavailable" : isDragOver ? "Drop files here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : composerPlaceholder(enterMode, isMacOS())}
+ placeholder={disabled ? "Unavailable" : isGenerating && onSteer ? "Add to the task, the agent reads it after this step…" : isDragOver ? "Drop files here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : composerPlaceholder(enterMode, isMacOS())}
disabled={disabled}
rows={1}
className="lu-fokus-am-kasten w-full bg-transparent resize-none text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none text-[12px] leading-relaxed max-h-[200px] disabled:opacity-50 scrollbar-thin"
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 50b9d605..0b1742f4 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -9,6 +9,7 @@ import { useAgentModeStore } from '../../stores/agentModeStore'
import { AgentPanel } from './AgentPanel'
import { MessageList } from './MessageList'
import { ChatInput } from './ChatInput'
+import { useSteerQueue } from '../../hooks/useSteerQueue'
import { COMPOSER_MAX_W } from './composer-width'
import { RAGPanel } from './RAGPanel'
import { DocsButton } from './DocsButton'
@@ -197,6 +198,9 @@ export function ChatView() {
// `@` file mentions (U8): Agent mode reads its working folder, plain chat
// only a real folder pinned on the chat or set as default.
const mentionRoot = useMentionRoot(isAgentActive ? 'agent' : 'chat')
+ // CA U2: in Agent mode, typing during a run queues the message for the
+ // run's next step; plain chat keeps its one-answer-at-a-time rule.
+ const steering = useSteerQueue(activeConversationId, busy.thisChat, isAgentActive, (text) => sendMessage(text))
// Remote-chat state: show a reactivate banner when the user is viewing a
// Remote conversation whose server has been stopped.
@@ -849,6 +853,9 @@ export function ChatView() {
// plain chat hands the model a summary of them.
filesReachTools={isAgentActive}
mentionRoot={mentionRoot}
+ onSteer={steering.steer}
+ steerQueue={steering.queue}
+ onUnsteer={steering.unsteer}
composerModel={
/* What this chat's answers were written by rides on the
picker itself now, as a dot plus a tooltip, instead of a
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 221bd06e..638dbbee 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -9,6 +9,8 @@ import { useComputerStore } from '../../stores/computerStore'
import { useBackgroundAgentWake } from '../../hooks/useBackgroundAgentWake'
import { useGenerationStore } from '../../stores/generationStore'
import { ChatInput } from './ChatInput'
+import { SteerNote } from './SteerNote'
+import { useSteerQueue } from '../../hooks/useSteerQueue'
import { ChatFileChip } from './ChatFileChip'
import { FILE_ONLY_TEXT } from '../../lib/chat-files'
import { ToolCallBlock } from './ToolCallBlock'
@@ -124,6 +126,8 @@ export function CodexView() {
// refs); the visual bits below read this conversation-scoped flag instead.
const generatingMap = useGenerationStore((s) => s.generating)
const codexGenerating = !!activeConversationId && !!generatingMap[activeConversationId]
+ // CA U2: typing during a run queues the message for the run's next step.
+ const steering = useSteerQueue(activeConversationId, isRunning || codexGenerating, true, (text) => sendInstruction(text, { shownMode }))
const pendingConfirm = useCodexConfirmStore((s) => s.pending)
// The question of the first use of computer control is open in this conversation.
const chatAsked = useComputerStore((s) => !!s.chatAsk && !s.chatAsk.voice && (s.chatAsk.conversationId === null || s.chatAsk.conversationId === activeConversationId))
@@ -505,7 +509,9 @@ export function CodexView() {
const shown = (text: string) => (running ? closeOpenMarkdown(text) : text)
const hasBlocks = !!(msg.role === 'assistant' && msg.agentBlocks && msg.agentBlocks.length > 0)
const stepCount = msg.agentBlocks?.filter((b) => b.phase === 'tool_call' && b.toolCall).length ?? 0
- const hasAnswerBlock = !!(msg.agentBlocks && msg.agentBlocks.some((b) => b.phase === 'answer' && b.content.trim()))
+ // A message the user wrote during the run (CA U2) needs
+ // the chronological layout to sit where it was read.
+ const hasAnswerBlock = !!(msg.agentBlocks && msg.agentBlocks.some((b) => (b.phase === 'answer' && b.content.trim()) || b.steer))
// Reflection blocks (Architect plan, RepoMap context) ,
// shown above the tool calls so the user sees what context
@@ -513,7 +519,7 @@ export function CodexView() {
const reflection = hasBlocks ? (
<div className="space-y-1">
{msg.agentBlocks!
- .filter((b) => b.phase === 'reflection' && b.content)
+ .filter((b) => b.phase === 'reflection' && b.content && !b.steer)
.map((block) => (
<div
key={block.id}
@@ -542,6 +548,7 @@ export function CodexView() {
(b) =>
(b.phase === 'tool_call' && b.toolCall) ||
(b.phase === 'answer' && stripChannelTags(b.content)) ||
+ (b.steer && b.content.trim()) ||
// G21-2: per-round thoughts, chronological
(b.phase === 'thinking' && b.content.trim()),
)
@@ -588,6 +595,7 @@ export function CodexView() {
)
}
const block = group.block
+ if (block.steer) return <SteerNote key={block.id} text={block.content} />
if (block.phase === 'thinking') {
// Trailing thought before the final
// answer, in its collapsed G14-7 bubble.
@@ -799,6 +807,9 @@ export function CodexView() {
// the header next to New, so this row carries ONE view-specific
// control and stays a single quiet line in both states.
composerActions={<CodexModeDropdown openUpward />}
+ onSteer={steering.steer}
+ steerQueue={steering.queue}
+ onUnsteer={steering.unsteer}
/>
</div>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index f0b1a753..8ce793d4 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -10,6 +10,7 @@ import { closeOpenMarkdown } from '../../lib/streaming-markdown'
import { ThinkingBlock } from './ThinkingBlock'
import { ToolCallBand } from './ToolCallBand'
import { ReflectionBlock } from './ReflectionBlock'
+import { SteerNote } from './SteerNote'
import { groupAgentBlocks } from '../../lib/tool-call-groups'
import { VramSwitchCard } from './VramSwitchCard'
import { SpeakerButton } from './SpeakerButton'
@@ -445,6 +446,9 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, p
// answer) in its G14-7 bubble, collapsed, chronological.
return <ThinkingBlock key={block.id} thinking={block.content} />
}
+ if (block.phase === 'reflection' && block.steer) {
+ return <SteerNote key={block.id} text={block.content} />
+ }
if (block.phase === 'reflection') {
return <ReflectionBlock key={block.id} content={block.content} />
}
diff --git a/src/components/chat/SteerNote.tsx b/src/components/chat/SteerNote.tsx
new file mode 100644
index 00000000..8eaac225
--- /dev/null
+++ b/src/components/chat/SteerNote.tsx
@@ -0,0 +1,14 @@
+/**
+ * A message the user wrote while the run was going, drawn where the run read
+ * it (CA U2). Right-aligned and small: the user's voice inside the agent's turn.
+ */
+export function SteerNote({ text }: { text: string }) {
+ return (
+ <div className="flex justify-end py-1" data-testid="steer-note">
+ <div className="max-w-[80%] rounded-lg bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08] px-2.5 py-1.5">
+ <div className="t-micro text-gray-500 dark:text-gray-400">You, during the run</div>
+ <div className="t-control leading-relaxed text-gray-800 dark:text-gray-100 whitespace-pre-wrap break-words">{text}</div>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/chat/__tests__/composer-steers-a-running-task.test.tsx b/src/components/chat/__tests__/composer-steers-a-running-task.test.tsx
new file mode 100644
index 00000000..d85cde4f
--- /dev/null
+++ b/src/components/chat/__tests__/composer-steers-a-running-task.test.tsx
@@ -0,0 +1,56 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * CA U2: Enter during an agent run queues the message for the next step.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, renderHook } from '@testing-library/react'
+import { ChatInput } from '../ChatInput'
+import { useSteerQueue } from '../../../hooks/useSteerQueue'
+import { useSteerStore } from '../../../stores/steerStore'
+
+afterEach(() => { cleanup(); useSteerStore.setState({ queue: {} }) })
+
+describe('typing while the agent works (CA U2)', () => {
+ it('Enter queues the message instead of doing nothing', () => {
+ const onSend = vi.fn()
+ const onSteer = vi.fn()
+ const view = render(<ChatInput onSend={onSend} onStop={() => {}} isGenerating modelReady={() => true} onSteer={onSteer} />)
+ const box = view.container.querySelector('textarea')!
+ expect(box.getAttribute('placeholder')).toMatch(/reads it after this step/)
+ fireEvent.change(box, { target: { value: 'use vitest' } })
+ fireEvent.keyDown(box, { key: 'Enter' })
+ expect(onSteer).toHaveBeenCalledWith('use vitest')
+ expect(onSend).not.toHaveBeenCalled()
+ expect(box.value).toBe('')
+ })
+
+ it('shows what waits, and a message can be taken back', () => {
+ const onUnsteer = vi.fn()
+ const view = render(
+ <ChatInput onSend={() => {}} onStop={() => {}} isGenerating modelReady={() => true} onSteer={() => {}} steerQueue={[{ id: 's1', text: 'keep the old name' }]} onUnsteer={onUnsteer} />,
+ )
+ expect(view.getByTestId('steer-queue').textContent).toContain('keep the old name')
+ fireEvent.click(view.getByRole('button', { name: 'Take this message back' }))
+ expect(onUnsteer).toHaveBeenCalledWith('s1')
+ })
+
+ it('without steering (plain chat) Enter during a run still sends nothing', () => {
+ const onSend = vi.fn()
+ const view = render(<ChatInput onSend={onSend} onStop={() => {}} isGenerating modelReady={() => true} />)
+ const box = view.container.querySelector('textarea')!
+ fireEvent.change(box, { target: { value: 'hello' } })
+ fireEvent.keyDown(box, { key: 'Enter' })
+ expect(onSend).not.toHaveBeenCalled()
+ expect(box.value).toBe('hello')
+ })
+
+ it('what the run did not read goes out as the next message when it ends', () => {
+ const send = vi.fn()
+ const { rerender } = renderHook(({ running }) => useSteerQueue('c1', running, true, send), { initialProps: { running: true } })
+ act(() => { useSteerStore.getState().add('c1', 'one more thing'); useSteerStore.getState().add('c1', 'and this') })
+ rerender({ running: false })
+ expect(send).toHaveBeenCalledWith('one more thing\n\nand this')
+ expect(useSteerStore.getState().queue.c1).toEqual([])
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 188778dc..d98921f4 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -123,6 +123,9 @@ import {
} from '../lib/agent-fanout'
import { setExplicitFanout, buildSubAgentGates } from '../api/agents/sub-agent'
import { appendTaskReport } from '../lib/agent-task-report'
+import { appendSteers } from '../lib/agent-core/steer'
+import { finishWithoutTools, finishSection } from '../lib/agent-core/finish'
+import { useSteerStore } from '../stores/steerStore'
import { useAgentTaskStore } from '../stores/agentTaskStore'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { endLoopUnlessRearmed, useAgentLoopStore } from '../stores/agentLoopStore'
@@ -1754,6 +1757,12 @@ export function useAgentChat() {
() => useAgentTaskStore.getState().takeUnreported(convId),
Date.now(),
)
+ // CA U2: what the user wrote while the run was going, read here, at
+ // the same seam and as the same kind of material as the report above.
+ for (const steer of appendSteers(agentMessages, () => useSteerStore.getState().take(convId), (content) => ({ role: 'user' as const, content }))) {
+ addBlock(runState, convId, assistantMessage.id, { id: uuid(), phase: 'reflection', content: steer.text, steer: true, timestamp: Date.now() })
+ log.info('agent.steer_read', { chars: steer.text.length })
+ }
// One card, and a render from the chat has the chat model off it
// (3.0.8, A2): wait for it here, visibly, instead of inside the
// provider without a word.
@@ -1765,6 +1774,11 @@ export function useAgentChat() {
runState.content =
(runState.content ? runState.content + '\n\n' : '') + budget.haltMessage()
scheduleUIUpdate()
+ // CA U6: one pass without tools says what is done and what is open.
+ {
+ const summary = await finishWithoutTools({ provider, model: modelToUse, messages: agentMessages, signal: abort.signal })
+ if (summary) { runState.content += finishSection(summary); scheduleUIUpdate() }
+ }
break
}
let toolCalls: ToolCall[] = []
@@ -2996,6 +3010,11 @@ export function useAgentChat() {
(runState.content ? runState.content + '\n\n' : '') +
`_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step tasks, or rephrase the instruction.)_`
scheduleUIUpdate()
+ // CA U6: one pass without tools says what is done and what is open.
+ {
+ const summary = await finishWithoutTools({ provider, model: modelToUse, messages: agentMessages, signal: abort.signal })
+ if (summary) { runState.content += finishSection(summary); scheduleUIUpdate() }
+ }
addBlock(runState, convId!, assistantMessage.id, {
id: uuid(),
phase: 'reflection',
@@ -3504,6 +3523,11 @@ export function useAgentChat() {
(runState.content ? runState.content + '\n\n' : '') +
`_(halted: ${failVerdict.reason}. The model is looping. Try a stronger model for multi-step tasks, or rephrase the instruction.)_`
scheduleUIUpdate()
+ // CA U6: one pass without tools says what is done and what is open.
+ {
+ const summary = await finishWithoutTools({ provider, model: modelToUse, messages: agentMessages, signal: abort.signal })
+ if (summary) { runState.content += finishSection(summary); scheduleUIUpdate() }
+ }
break
}
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 1a9a4d82..180500b9 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -28,6 +28,9 @@ import {
} from '../lib/agent-fanout'
import { setExplicitFanout } from '../api/agents/sub-agent'
import { appendTaskReport } from '../lib/agent-task-report'
+import { finishWithoutTools, finishSection } from '../lib/agent-core/finish'
+import { appendSteers } from '../lib/agent-core/steer'
+import { useSteerStore } from '../stores/steerStore'
import { useAgentTaskStore } from '../stores/agentTaskStore'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { endLoopUnlessRearmed, useAgentLoopStore } from '../stores/agentLoopStore'
@@ -1322,15 +1325,20 @@ export function useCodex() {
() => useAgentTaskStore.getState().takeUnreported(convId!),
Date.now(),
)
+ // CA U2: what the user wrote while the run was going (same seam).
+ for (const steer of appendSteers(messages, () => useSteerStore.getState().take(convId!), (content) => ({ role: 'user' as const, content }))) {
+ addBlock({ id: uuid(), phase: 'reflection', content: steer.text, steer: true, timestamp: Date.now() })
+ diagLog('steer-read', { chars: steer.text.length })
+ }
budget.addIteration()
const bx = budget.exceeded()
if (bx.kind !== 'none') {
diagLog('budget-halt', { iter: i, kind: bx.kind })
- useChatStore.getState().updateMessageContent(
- convId!,
- assistantMsg.id,
- (fullContent ? fullContent + '\n\n' : '') + budget.haltMessage()
- )
+ const halted = (fullContent ? fullContent + '\n\n' : '') + budget.haltMessage()
+ useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, halted)
+ // CA U6: one pass without tools says what is done and what is open.
+ const summary = await finishWithoutTools({ provider, model: modelToUse, messages, signal: abort.signal })
+ if (summary) useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, halted + finishSection(summary))
break
}
let toolCalls: ToolCall[] = []
@@ -2257,6 +2265,10 @@ export function useCodex() {
diagLog('loop-guard-halt', { iter: i, reason: batchVerdict.reason })
const msg = `\n\n_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)
+ {
+ const summary = await finishWithoutTools({ provider, model: modelToUse, messages, signal: abort.signal })
+ if (summary) useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg + finishSection(summary))
+ }
// A halt has to be visible in the thread itself, not only as a
// suffix on the answer: support cannot otherwise tell a loop halt
// apart from a model that simply stopped (plan A1, SICHTBARKEIT).
@@ -2720,6 +2732,10 @@ export function useCodex() {
if (failVerdict.action === 'halt') {
const msg = `\n\n_(halted: ${failVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)
+ {
+ const summary = await finishWithoutTools({ provider, model: modelToUse, messages, signal: abort.signal })
+ if (summary) useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg + finishSection(summary))
+ }
addBlock({
id: uuid(),
phase: 'reflection',
diff --git a/src/hooks/useSteerQueue.ts b/src/hooks/useSteerQueue.ts
new file mode 100644
index 00000000..e804c64d
--- /dev/null
+++ b/src/hooks/useSteerQueue.ts
@@ -0,0 +1,38 @@
+/**
+ * The composer's side of steering a run (CA U2).
+ *
+ * While a run goes, Enter queues the message (stores/steerStore); the loop
+ * reads it after the current tool step. A run that ends before it read them
+ * (the model answered without another tool) sends what is left as the next
+ * message, so nothing the user wrote is lost.
+ */
+import { useEffect, useRef } from 'react'
+import { useSteerStore, type QueuedSteer } from '../stores/steerStore'
+
+const EMPTY: QueuedSteer[] = []
+
+export function useSteerQueue(
+ convId: string | null,
+ running: boolean,
+ enabled: boolean,
+ sendNext: (text: string) => void,
+): { queue: QueuedSteer[]; steer?: (text: string) => void; unsteer: (id: string) => void } {
+ const queue = useSteerStore((s) => (convId ? s.queue[convId] ?? EMPTY : EMPTY))
+ const wasRunning = useRef(running)
+ const send = useRef(sendNext)
+ useEffect(() => { send.current = sendNext })
+
+ useEffect(() => {
+ const ended = wasRunning.current && !running
+ wasRunning.current = running
+ if (!ended || !convId) return
+ const left = useSteerStore.getState().take(convId)
+ if (left.length) send.current(left.map((m) => m.text).join('\n\n'))
+ }, [running, convId])
+
+ return {
+ queue,
+ steer: enabled && convId ? (text: string) => useSteerStore.getState().add(convId, text) : undefined,
+ unsteer: (id: string) => { if (convId) useSteerStore.getState().remove(convId, id) },
+ }
+}
diff --git a/src/lib/__tests__/file-mentions.test.ts b/src/lib/__tests__/file-mentions.test.ts
index ac9cddeb..7bab9f99 100644
--- a/src/lib/__tests__/file-mentions.test.ts
+++ b/src/lib/__tests__/file-mentions.test.ts
@@ -55,7 +55,7 @@ describe('the trigger', () => {
expect(mentionAt('@', 1)).toEqual({ start: 0, query: '' })
expect(mentionAt('look at @src/ma', 15)).toEqual({ start: 8, query: 'src/ma' })
expect(mentionAt('(@mat', 5)).toEqual({ start: 1, query: 'mat' })
- expect(mentionAt('mail [email protected]', 16)).toBeNull()
+ expect(mentionAt('mail name@host', 14)).toBeNull()
expect(mentionAt('@src/math.ts done', 17)).toBeNull()
expect(mentionAt('plain text', 10)).toBeNull()
})
diff --git a/src/lib/agent-core/__tests__/finish.test.ts b/src/lib/agent-core/__tests__/finish.test.ts
new file mode 100644
index 00000000..45989289
--- /dev/null
+++ b/src/lib/agent-core/__tests__/finish.test.ts
@@ -0,0 +1,38 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { describe, expect, it, vi } from 'vitest'
+import { FINISH_PROMPT, finishSection, finishWithoutTools } from '../finish'
+
+describe('a clean end at the limit (CA U6)', () => {
+ it('asks once without tools and returns the summary', async () => {
+ const chatWithTools = vi.fn(async () => ({ content: '<think>hm</think>Done: median. Open: docs. Next: run lint.' }))
+ const out = await finishWithoutTools({ provider: { chatWithTools }, model: 'm', messages: [{ role: 'user', content: 'task' }] })
+ expect(out).toBe('Done: median. Open: docs. Next: run lint.')
+ const [, msgs, tools] = chatWithTools.mock.calls[0] as unknown as [string, { content: string }[], unknown[]]
+ expect(tools).toEqual([])
+ expect(msgs[msgs.length - 1].content).toBe(FINISH_PROMPT)
+ })
+
+ it('gives up quietly: an error, an empty answer, a stop, a timeout', async () => {
+ expect(await finishWithoutTools({ provider: { chatWithTools: async () => { throw new Error('400') } }, model: 'm', messages: [] })).toBeNull()
+ expect(await finishWithoutTools({ provider: { chatWithTools: async () => ({ content: ' ' }) }, model: 'm', messages: [] })).toBeNull()
+ const stopped = new AbortController(); stopped.abort()
+ expect(await finishWithoutTools({ provider: { chatWithTools: vi.fn() }, model: 'm', messages: [], signal: stopped.signal })).toBeNull()
+ const hang = { chatWithTools: (_m: string, _x: unknown, _t: unknown, o?: { signal?: AbortSignal }) => new Promise((_, rej) => o?.signal?.addEventListener('abort', () => rej(new Error('aborted')))) }
+ expect(await finishWithoutTools({ provider: hang, model: 'm', messages: [], timeoutMs: 20 })).toBeNull()
+ })
+
+ it('appends under the halt line only when there is something to say', () => {
+ expect(finishSection(null)).toBe('')
+ expect(finishSection('x')).toContain('Where it stopped')
+ })
+
+ it('both loops run it at the budget and loop-guard halts, never at the cost brake', () => {
+ const src = (p: string) => readFileSync(resolve(__dirname, '../../..', p), 'utf8')
+ for (const f of ['hooks/useAgentChat.ts', 'hooks/useCodex.ts']) {
+ expect(src(f).match(/finishWithoutTools\(/g)?.length).toBe(3)
+ const brake = src(f).indexOf("if (brake.action === 'halt')")
+ expect(src(f).slice(brake, brake + 500)).not.toContain('finishWithoutTools')
+ }
+ })
+})
diff --git a/src/lib/agent-core/__tests__/steer.test.ts b/src/lib/agent-core/__tests__/steer.test.ts
new file mode 100644
index 00000000..cd302ceb
--- /dev/null
+++ b/src/lib/agent-core/__tests__/steer.test.ts
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { appendSteers, steerMessage } from '../steer'
+import { useSteerStore } from '../../../stores/steerStore'
+
+type M = { role: string; content?: unknown; tool_calls?: unknown }
+const make = (content: string): M => ({ role: 'user', content })
+
+describe('a message written during a run (CA U2)', () => {
+ beforeEach(() => useSteerStore.setState({ queue: {} }))
+
+ it('enters the history as user material, oldest first, and leaves the queue', () => {
+ useSteerStore.getState().add('c1', 'use vitest, not jest')
+ useSteerStore.getState().add('c1', 'and keep the old name')
+ const messages: M[] = [{ role: 'user', content: 'task' }, { role: 'tool', content: 'ok' }]
+ const taken = appendSteers(messages, () => useSteerStore.getState().take('c1'), make)
+ expect(taken.map((t) => t.text)).toEqual(['use vitest, not jest', 'and keep the old name'])
+ expect(messages.slice(2).map((m) => m.content)).toEqual([steerMessage('use vitest, not jest'), steerMessage('and keep the old name')])
+ expect(useSteerStore.getState().queue.c1).toEqual([])
+ })
+
+ it('never lands between a call and its results; it waits for the next round', () => {
+ useSteerStore.getState().add('c1', 'stop after the tests')
+ const messages: M[] = [{ role: 'assistant', content: '', tool_calls: [{ id: 'x' }] }]
+ expect(appendSteers(messages, () => useSteerStore.getState().take('c1'), make)).toEqual([])
+ expect(messages).toHaveLength(1)
+ expect(useSteerStore.getState().queue.c1).toHaveLength(1)
+ })
+
+ it('keeps chats apart and can take one back', () => {
+ const st = useSteerStore.getState()
+ st.add('a', 'one'); st.add('b', 'two')
+ const id = useSteerStore.getState().queue.a[0].id
+ useSteerStore.getState().remove('a', id)
+ expect(useSteerStore.getState().take('a')).toEqual([])
+ expect(useSteerStore.getState().take('b').map((m) => m.text)).toEqual(['two'])
+ })
+
+ it('both loops read the queue at the top of an iteration, next to the task report', () => {
+ const src = (p: string) => readFileSync(resolve(__dirname, '../../..', p), 'utf8')
+ for (const f of ['hooks/useAgentChat.ts', 'hooks/useCodex.ts']) {
+ const s = src(f)
+ const report = s.indexOf('appendTaskReport(\n')
+ const steer = s.indexOf('appendSteers(', report)
+ expect(report).toBeGreaterThan(0)
+ expect(steer - report).toBeLessThan(600)
+ }
+ })
+})
diff --git a/src/lib/agent-core/finish.ts b/src/lib/agent-core/finish.ts
new file mode 100644
index 00000000..aa77dc03
--- /dev/null
+++ b/src/lib/agent-core/finish.ts
@@ -0,0 +1,67 @@
+/**
+ * A clean end when a run has to stop (CA U6, C59's open L2).
+ *
+ * At the step budget or a loop-guard halt LU used to end on a bracketed line
+ * ("[Agent halted: …]") and the user had to work out from the tool rows what
+ * had been done. Hermes and OpenClaw run one last pass without tools that says
+ * what was done, what is open and what comes next. This is that pass: one call,
+ * no tools, a short answer, and on any failure the old line stays alone.
+ *
+ * Not used for the cost brake (another paid call is the opposite of braking)
+ * or for Stop (the user asked for silence).
+ */
+import type { ChatMessage } from '../../api/providers/types'
+import { settleThinking } from '../thinking-stripper'
+import { stripToolCallTags } from '../../api/hermes-tool-calling'
+
+export const FINISH_PROMPT =
+ 'Stop here: this run has reached its limit, and no more tools can be called. ' +
+ 'In at most six short lines, in the language the user wrote in, say what is done, what is still open, ' +
+ 'and the one next step you would take. No tool calls, no code blocks.'
+
+export const FINISH_TIMEOUT_MS = 90_000
+
+interface Chatty {
+ chatWithTools(
+ model: string,
+ messages: ChatMessage[],
+ tools: never[],
+ options?: { signal?: AbortSignal; maxTokens?: number },
+ ): Promise<{ content: string }>
+}
+
+/** The summary, or null when the pass failed, timed out or said nothing. */
+export async function finishWithoutTools(opts: {
+ provider: unknown
+ model: string
+ messages: ChatMessage[]
+ signal?: AbortSignal
+ timeoutMs?: number
+}): Promise<string | null> {
+ if (opts.signal?.aborted) return null
+ const ctrl = new AbortController()
+ const onAbort = () => ctrl.abort()
+ opts.signal?.addEventListener('abort', onAbort, { once: true })
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? FINISH_TIMEOUT_MS)
+ try {
+ const provider = opts.provider as Chatty
+ const turn = await provider.chatWithTools(
+ opts.model,
+ [...opts.messages, { role: 'user', content: FINISH_PROMPT }],
+ [],
+ { signal: ctrl.signal, maxTokens: 600 },
+ )
+ const text = stripToolCallTags(settleThinking(turn?.content || '', '', false).content).trim()
+ return text || null
+ } catch {
+ return null
+ } finally {
+ clearTimeout(timer)
+ opts.signal?.removeEventListener('abort', onAbort)
+ }
+}
+
+/** How the summary is appended under the halt line. */
+export function finishSection(summary: string | null): string {
+ return summary ? `\n\n**Where it stopped**\n\n${summary}` : ''
+}
diff --git a/src/lib/agent-core/steer.ts b/src/lib/agent-core/steer.ts
new file mode 100644
index 00000000..216eba66
--- /dev/null
+++ b/src/lib/agent-core/steer.ts
@@ -0,0 +1,36 @@
+/**
+ * Where a message written during a run enters the run (CA U2).
+ *
+ * The same place and the same channel as a finished background agent's report
+ * (lib/agent-task-report.ts): user material, at the top of an iteration, never
+ * between an assistant message with tool_calls and their results. A round that
+ * still waits for results keeps the messages for the next one.
+ */
+import { awaitingToolResults } from '../agent-task-report'
+import type { QueuedSteer } from '../../stores/steerStore'
+
+interface Turn {
+ role: string
+ content?: unknown
+ tool_calls?: unknown
+}
+
+/** What the model reads. Short, and clear that the task is still the same run. */
+export function steerMessage(text: string): string {
+ return `The user adds this while you work. Take it into account from now on, then go on:\n${text}`
+}
+
+/**
+ * Appends the waiting messages to the history and returns them, so the loop
+ * can show them in the transcript. Nothing is taken while results are missing.
+ */
+export function appendSteers<T extends Turn>(
+ messages: T[],
+ take: () => QueuedSteer[],
+ make: (content: string) => T,
+): QueuedSteer[] {
+ if (awaitingToolResults(messages)) return []
+ const items = take()
+ for (const item of items) messages.push(make(steerMessage(item.text)))
+ return items
+}
diff --git a/src/lib/file-mentions.ts b/src/lib/file-mentions.ts
index 670366f3..5a452db5 100644
--- a/src/lib/file-mentions.ts
+++ b/src/lib/file-mentions.ts
@@ -102,7 +102,7 @@ export interface MentionQuery {
/**
* The mention the caret is in, or null. An `@` counts at the start of the
- * text or after whitespace or an opening bracket, so `[email protected]` never
+ * text or after whitespace or an opening bracket, so `name@host` never
* opens the list. The query ends at the caret and holds no whitespace.
*/
export function mentionAt(text: string, caret: number | null | undefined): MentionQuery | null {
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.ts
index 4f358f1e..b6fb64af 100644
--- a/src/lib/store-backup.ts
+++ b/src/lib/store-backup.ts
@@ -32,6 +32,8 @@ export const STORE_KEYS = [
'chat-conversations', 'chat-settings', 'chat-models', 'lu-providers',
'create-store', 'locally-uncensored-codex',
'locally-uncensored-permissions', 'locally-uncensored-mcp-servers',
+ // CA K4: the commands the user allowed per folder (stores/commandRulesStore).
+ 'locally-uncensored-command-rules',
'locally-uncensored-agent-mode', 'locally-uncensored-memory',
'locally-uncensored-agent-workflows', 'locally-uncensored-agent',
'locally-uncensored-voice', 'lu-benchmark-store', 'lu-update-checker-v2',
diff --git a/src/lib/tool-call-groups.ts b/src/lib/tool-call-groups.ts
index 93d45887..4807719b 100644
--- a/src/lib/tool-call-groups.ts
+++ b/src/lib/tool-call-groups.ts
@@ -68,6 +68,8 @@ export function groupAgentBlocks(blocks: AgentBlock[]): AgentBlockGroup[] {
groups.push({ kind: 'tools', blocks: [block], calls: [block.toolCall], notes: [] })
}
} else if (
+ // A message from the user is never folded into a band (CA U2).
+ !block.steer &&
INTERIOR_NOTE_PHASES.has(block.phase) &&
i < lastCallAt &&
last &&
diff --git a/src/stores/steerStore.ts b/src/stores/steerStore.ts
new file mode 100644
index 00000000..18c985df
--- /dev/null
+++ b/src/stores/steerStore.ts
@@ -0,0 +1,42 @@
+/**
+ * Messages the user writes while a run is going (CA U2).
+ *
+ * Claude Code, Codex and Cursor let the user keep typing while the agent
+ * works: the message waits and is read after the current tool step, inside the
+ * same run. In LU an Enter during a run did nothing and the text sat in the
+ * composer. Not persisted: a queued message belongs to the run that is going.
+ */
+import { create } from 'zustand'
+
+export interface QueuedSteer {
+ id: string
+ text: string
+ at: number
+}
+
+interface SteerState {
+ queue: Record<string, QueuedSteer[]>
+ add: (convId: string, text: string) => void
+ remove: (convId: string, id: string) => void
+ /** Takes every waiting message of this chat, oldest first. */
+ take: (convId: string) => QueuedSteer[]
+}
+
+let seq = 0
+
+export const useSteerStore = create<SteerState>((set, get) => ({
+ queue: {},
+ add: (convId, text) => {
+ const t = text.trim()
+ if (!convId || !t) return
+ const item = { id: `steer-${Date.now()}-${++seq}`, text: t, at: Date.now() }
+ set((s) => ({ queue: { ...s.queue, [convId]: [...(s.queue[convId] ?? []), item] } }))
+ },
+ remove: (convId, id) =>
+ set((s) => ({ queue: { ...s.queue, [convId]: (s.queue[convId] ?? []).filter((m) => m.id !== id) } })),
+ take: (convId) => {
+ const items = get().queue[convId] ?? []
+ if (items.length) set((s) => ({ queue: { ...s.queue, [convId]: [] } }))
+ return items
+ },
+}))
diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.ts
index c631afee..1476fc08 100644
--- a/src/types/agent-mode.ts
+++ b/src/types/agent-mode.ts
@@ -160,6 +160,10 @@ export interface AgentBlock {
* 'reflection' and `content` carries the sentence, so a reader that does
* not know the field still shows something true. */
compaction?: { before: number; after: number; replaced: number }
+ /** A message the user wrote while the run was going (CA U2). Phase
+ * 'reflection', `content` is the user's own text; the transcript draws it as
+ * a small user note at the point where the run read it. */
+ steer?: true
}
// Sandbox configuration