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.

fix(agent): Stop right after Send ends the run on the first press

purple2f849d7aae6b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d1fd80f5..1a02215e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,7 +34,8 @@ cloud catalogue.
call has arrived, for example "Preparing file_write 3 kB", as soon as the
first piece is in. A run that waits for your approval says so in the
chat too, and Stop before the first word leaves a short note instead of an
- empty answer.
+ empty answer. Stop pressed right after Send ends the run on the first
+ press; before, the run could keep going or hang on "Working".
- **Code conversations stay in the Code tab.** After a restart the last Code
conversation opened in the Chat tab, where the agent was off and a
"continue" ran without tools. The app now starts on an empty chat, and the
diff --git a/src/components/chat/CodexModeDropdown.tsx b/src/components/chat/CodexModeDropdown.tsx
index 4f441548..660a85dc 100644
--- a/src/components/chat/CodexModeDropdown.tsx
+++ b/src/components/chat/CodexModeDropdown.tsx
@@ -119,7 +119,11 @@ export function CodexModeDropdown({ openUpward = false }: { openUpward?: boolean
{open && (
<>
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
- <div className={`absolute right-0 z-50 w-60 rounded-lg lu-elevated py-1.5 ${openUpward ? 'bottom-full mb-1' : 'top-full mt-1'}`}>
+ {/* left-0: the trigger sits at the LEFT of the composer row, so a
+ menu hung off its right edge ran 240px to the left and the panel
+ cut off the first letters ("ypass permissions", Gegenprobe
+ 01.10.2026). The room is to the right. */}
+ <div className={`absolute left-0 z-50 w-60 rounded-lg lu-elevated py-1.5 ${openUpward ? 'bottom-full mb-1' : 'top-full mt-1'}`}>
{!activeConvId ? (
<p className="px-3 py-1.5 text-[0.5rem] text-gray-400">
Open a coding chat first, the mode lives on the conversation.
diff --git a/src/hooks/__tests__/a-stop-right-after-send-ends-the-run.test.ts b/src/hooks/__tests__/a-stop-right-after-send-ends-the-run.test.ts
new file mode 100644
index 00000000..2d8df536
--- /dev/null
+++ b/src/hooks/__tests__/a-stop-right-after-send-ends-the-run.test.ts
@@ -0,0 +1,142 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Gegenprobe on the real Windows build, 01.10.2026: Stop pressed in the same
+ * moment as Send, while the run was still preparing (before its first model
+ * request). The Stop was taken, then the run's own start wiped it and marked
+ * itself generating again: "Working" counted past a minute with nothing
+ * behind it, only a second Stop ended it, and the answer read "rephrase, or
+ * turn off Think". The same gap in the Code tab let the whole run go ahead.
+ *
+ * The preparing window is held open here by the workspace lookup every run
+ * awaits before its first request.
+ *
+ * Run: npx vitest run src/hooks/__tests__/a-stop-right-after-send-ends-the-run.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act, waitFor } from '@testing-library/react'
+
+const gate = vi.hoisted(() => ({ held: null as null | { reached: boolean; release: () => void } }))
+
+vi.mock('../../api/workspace-slug', async (importOriginal) => {
+ const real = await importOriginal<typeof import('../../api/workspace-slug')>()
+ return {
+ ...real,
+ resolveChatWorkspaceSlug: async (...args: Parameters<typeof real.resolveChatWorkspaceSlug>) => {
+ const g = gate.held
+ if (g) {
+ g.reached = true
+ await new Promise<void>((r) => { g.release = r })
+ }
+ return real.resolveChatWorkspaceSlug(...args)
+ },
+ }
+})
+vi.mock('../../api/cloud/supabase', () => ({
+ getAccessToken: async () => 'session-token-abc',
+}))
+vi.mock('../../api/rag', () => ({
+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),
+ generateEmbeddings: async () => [[0.1, 0.2]],
+}))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+
+import { useAgentChat } from '../useAgentChat'
+import { useCodex } from '../useCodex'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useAgentTaskStore } from '../../stores/agentTaskStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useTodoStore } from '../../stores/todoStore'
+import { useToolAuditStore } from '../../stores/toolAuditStore'
+import { useRunActivityStore } from '../../stores/runActivityStore'
+import { STOPPED_NOTE } from '../../lib/stopped-note'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+import { __resetRunStopsForTests } from '../../lib/run-stop'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+
+const MODEL = 'lu-cloud::zai-org/GLM-5.3'
+
+let modelRequests = 0
+beforeEach(() => {
+ registerBuiltinTools(toolRegistry)
+ __resetRunStopsForTests()
+ gate.held = { reached: false, release: () => {} }
+ modelRequests = 0
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ if (String(input).includes('/chat/completions')) modelRequests++
+ return new Response('{}', { status: 200 })
+ })
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useAgentTaskStore.setState({ byConv: {} })
+ useAgentLoopStore.setState({ loops: {} })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useAgentModeStore.setState({ agentModeActive: {} })
+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })
+ useToolAuditStore.setState({ entries: {} })
+ useRunActivityStore.setState({ activity: {} })
+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off' } })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } },
+ }))
+ useModelStore.setState({ models: [], activeModel: MODEL })
+})
+afterEach(() => {
+ gate.held = null
+ vi.restoreAllMocks()
+})
+
+const answer = (convId: string) =>
+ useChatStore.getState().conversations.find((c) => c.id === convId)!.messages.filter((m) => m.role === 'assistant').at(-1)
+
+function settled(convId: string) {
+ const g = useGenerationStore.getState()
+ return { generating: !!g.generating[convId], aborter: !!g.aborters[convId] }
+}
+
+describe('Stop pressed while the run is still preparing', () => {
+ it('Agent: the run ends, nothing keeps "Working" alive, the answer says it stopped', async () => {
+ const { result } = renderHook(() => useAgentChat())
+ const convId = useChatStore.getState().createConversation(MODEL, '')
+ useChatStore.getState().setActiveConversation(convId)
+ useAgentModeStore.getState().setAgentModeActive(convId, true)
+ let run!: Promise<void>
+ act(() => { run = result.current.sendAgentMessage('write a poem') })
+ await waitFor(() => expect(gate.held!.reached).toBe(true))
+ expect(result.current.isAgentRunning).toBe(true)
+
+ act(() => result.current.stopAgent(convId))
+ await act(async () => { gate.held!.release(); await run })
+
+ expect(settled(convId)).toEqual({ generating: false, aborter: false })
+ expect(result.current.isAgentRunning).toBe(false)
+ expect(modelRequests).toBe(0)
+ expect(answer(convId)?.content).toBe(STOPPED_NOTE)
+ })
+
+ it('Code: the Stop is not wiped by the run starting, no request goes out', async () => {
+ const { result } = renderHook(() => useCodex())
+ const convId = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convId)
+ let run!: Promise<unknown>
+ act(() => { run = result.current.sendInstruction('create notes.md') })
+ await waitFor(() => expect(gate.held!.reached).toBe(true))
+
+ act(() => result.current.stopCodex(convId))
+ await act(async () => { gate.held!.release(); await run })
+
+ expect(settled(convId)).toEqual({ generating: false, aborter: false })
+ expect(result.current.isRunning).toBe(false)
+ expect(modelRequests).toBe(0)
+ expect(answer(convId)?.content).toBe(STOPPED_NOTE)
+ })
+})
diff --git a/src/hooks/__tests__/a-stopped-run-says-so.test.ts b/src/hooks/__tests__/a-stopped-run-says-so.test.ts
index 447bbba5..00e92904 100644
--- a/src/hooks/__tests__/a-stopped-run-says-so.test.ts
+++ b/src/hooks/__tests__/a-stopped-run-says-so.test.ts
@@ -100,6 +100,9 @@ describe('a stopped run says so', () => {
await waitFor(() => expect(s.ready()).toBe(true))
await act(async () => { result.current.stopAgent(); await run() })
expect(answer(convId).content).toBe(STOPPED_NOTE)
+ // The step's "Analyzing..." placeholder does not stay behind as a
+ // "Thinking" chip above the note.
+ expect((answer(convId).agentBlocks ?? []).filter((b) => b.phase === 'thinking')).toEqual([])
})
it('Stop after text arrived: the text stays, no note on top', async () => {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 9a7027df..2e1c48db 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -740,6 +740,12 @@ export function useAgentChat() {
const abort = new AbortController()
const runState: AgentRunState = { convId, content: '', thinking: '', blocks: [], abort }
activeAgentRuns.set(convId, runState)
+ // A brand-new instruction clears a previous stop; a /loop pass inherits it,
+ // which is what makes Stop end the LOOP and not just the pass in flight.
+ // Cleared HERE, in the same beat as the claim, because the Stop button is
+ // live from the next line on: cleared after the awaits below, it wiped a
+ // Stop pressed right after Send and the run went on (Gegenprobe 01.10.2026).
+ if (!opts?.loop) beginRun(convId)
// Flip the INPUT gate true in the SAME synchronous beat as the claim
// above (David 2026-06-16, bug A). The input shows Send vs Stop off
// `isAgentRunning`, which used to flip true only ~80 lines down, AFTER
@@ -781,11 +787,6 @@ export function useAgentChat() {
} catch { /* run with whatever the engine has */ }
const memoryScope = store.conversations.find(c => c.id === convId)?.memoryScope
- // A brand-new instruction clears a previous stop; a /loop pass inherits it,
- // which is what makes Stop end the LOOP and not just the pass in flight.
- // The old per-instance ref was set by stopAgent and never cleared anywhere,
- // so after one Stop every later /loop ran exactly one pass, in silence.
- if (!opts?.loop) beginRun(convId)
// Publish a HUMAN-READABLE slug ("create-an-index-7f2c3d") so
// built-in tools land in `~/agent-workspace/<slug>/`. Previously
@@ -1148,7 +1149,13 @@ export function useAgentChat() {
run.heldLocalLane = heldLocalLane
// Bind the generating flag to THIS conversation so the typing indicator
// shows only in the chat whose turn is in flight (David 2026-06-12).
- useGenerationStore.getState().setGenerating(convId, true)
+ // A Stop that landed before this point already released the slot, so the
+ // finally below will not clear what is set here: marking the run as
+ // generating now left "Working" counting with nothing behind it until a
+ // second Stop (Gegenprobe 01.10.2026). The loop below sees the aborted
+ // signal and ends without a request.
+ const stoppedBeforeStart = abort.signal.aborted
+ if (!stoppedBeforeStart) useGenerationStore.getState().setGenerating(convId, true)
// A run that threw mid-call left its label behind; this run starts clean.
useRunActivityStore.getState().setActivity(convId, null)
// Register so deleting/closing this chat stops the agent loop (Bug C).
@@ -1158,7 +1165,7 @@ export function useAgentChat() {
// review-lanes.md): passed bare this used to cancel whichever generation
// happened to be running app-wide, so Stop in conversation B could kill an
// image/video conversation A's agent was still producing.
- useGenerationStore.getState().registerAborter(convId, () => { abort.abort(); requestGenerationCancel(convId) })
+ if (!stoppedBeforeStart) useGenerationStore.getState().registerAborter(convId, () => { abort.abort(); requestGenerationCancel(convId) })
// A refusal no retry can fix has to end the loop as well. `return` in the
// catch does not skip the finally, so without this the driver fires the
// next pass into the same refusal and the credits dialog reopens every
@@ -1332,6 +1339,10 @@ export function useAgentChat() {
// Step number for the decay audit trail. The loop is a while, so it has
// no index of its own.
let stepNo = 0
+ // The "Analyzing..." placeholder of the step in flight. A Stop mid-request
+ // never reaches the code that drops it, and it stayed as a "Thinking" chip
+ // above the stop note (Gegenprobe 01.10.2026); the finally takes it out.
+ let placeholderId: string | null = null
try {
// ── Agent Loop ──────────────────────────────────────────
// A separate running flag used to be checked here too; it was only
@@ -1533,6 +1544,7 @@ export function useAgentChat() {
if (strategy === 'native') {
// Show thinking indicator while model processes
const thinkingBlockId = uuid()
+ placeholderId = thinkingBlockId
addBlock(runState, convId!, assistantMessage.id, {
id: thinkingBlockId, phase: 'thinking', content: 'Analyzing...',
timestamp: Date.now(),
@@ -2846,7 +2858,9 @@ export function useAgentChat() {
// tool-call rows but no closing line. Build a concise summary
// from the actually-completed blocks so there is always a final
// answer at the bottom of the bubble.
- if (!runState.content.trim()) {
+ // A stopped run gets the stop note in the finally instead: "rephrase, or
+ // turn off Think" blamed the prompt for the user's own Stop.
+ if (!runState.content.trim() && !abort.signal.aborted) {
// Closing line when the model said nothing itself. Pure logic lives in
// summarizeTurn so the D#81 rules (a failed picture is not a completed
// task, and its reason gets shown) are locked by tests.
@@ -3002,7 +3016,12 @@ export function useAgentChat() {
// unstoppable through generationStore (Stop button, sign-out, window
// close, app quit) even though activeAgentRuns still pointed at it.
// A Stop before anything was written leaves a line, not an empty bubble.
- if (abort.signal.aborted || isRunStopped(convId)) noteStoppedIfEmpty(convId, assistantMessage.id)
+ if (abort.signal.aborted || isRunStopped(convId)) {
+ if (placeholderId && runState.blocks.some((b) => b.id === placeholderId)) {
+ removeBlock(runState, convId, assistantMessage.id, placeholderId)
+ }
+ noteStoppedIfEmpty(convId, assistantMessage.id)
+ }
const stillOwnsSlot = activeAgentRuns.get(convId) === runState
if (stillOwnsSlot) {
useGenerationStore.getState().clearAborter(convId)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 36a64190..5bbe367c 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -412,6 +412,12 @@ export function useCodex() {
}
const runToken = Symbol('codex-run')
activeCodexRuns.set(convId, runToken)
+ // A brand-new instruction clears a previous stop; a /loop pass inherits it,
+ // which is what makes Stop end the LOOP and not just the pass in flight.
+ // Cleared HERE, in the same beat as the claim: cleared after the awaits
+ // below, it wiped a Stop pressed right after Send and the run went on as if
+ // nothing had been pressed (Gegenprobe 01.10.2026).
+ if (!opts?.loop) beginRun(convId)
// A wrapping try/catch, not just the identity-checked cleanup deep in the
// body's own finally (below): the body has many awaited calls BEFORE that
// inner try (resolveChatWorkspaceSlug, runCompactForConversation,
@@ -440,9 +446,6 @@ export function useCodex() {
async (heldLocalLane) => {
const memoryScope = store.conversations.find(c => c.id === convId)?.memoryScope
- // A brand-new instruction clears a previous stop; a /loop pass inherits it,
- // which is what makes Stop end the LOOP and not just the pass in flight.
- if (!opts?.loop) beginRun(convId)
// Mode of THIS conversation (plan 2.6.6, C1). A pick made while the
// previous run was still going has been parked; a send is where it takes
@@ -966,12 +969,21 @@ export function useCodex() {
// delegate_task threads this straight back into runInLane instead of
// guessing it holds the lane.
run.heldLocalLane = heldLocalLane
- setIsRunning(true)
- codexStore.setThreadStatus(convId, 'running')
- // Bind the generating flag to THIS conversation so the typing indicator +
- // realtime counter show only in the coding chat that's actually running,
- // not in every chat the user switches to (David 2026-06-12). Cleared below.
- useGenerationStore.getState().setGenerating(convId, true)
+ // A Stop that landed before this controller existed had nothing to abort
+ // and already released the slot, so the finally below will not undo what
+ // is set here: marking the run as running now left "Working" counting with
+ // nothing behind it. The stop is recorded, so the run ends here without a
+ // request (Gegenprobe 01.10.2026).
+ const stoppedBeforeStart = isRunStopped(convId) || activeCodexRuns.get(convId) !== runToken
+ if (stoppedBeforeStart) abort.abort()
+ if (!stoppedBeforeStart) {
+ setIsRunning(true)
+ codexStore.setThreadStatus(convId, 'running')
+ // Bind the generating flag to THIS conversation so the typing indicator +
+ // realtime counter show only in the coding chat that's actually running,
+ // not in every chat the user switches to (David 2026-06-12). Cleared below.
+ useGenerationStore.getState().setGenerating(convId, true)
+ }
// A run that threw mid-call left its label behind; this run starts clean.
useRunActivityStore.getState().setActivity(convId, null)
// Register the abort in the STORE, not just in hook refs (audit A2). The
@@ -980,7 +992,7 @@ export function useCodex() {
// Stop button and a second instruction could start a parallel loop on the
// same conversation. With the store aborter, stopCodex (any instance) and
// chat deletion both reach the real controller. Cleared in finally.
- useGenerationStore.getState().registerAborter(convId, () => {
+ if (!stoppedBeforeStart) useGenerationStore.getState().registerAborter(convId, () => {
abort.abort()
// Blocker 4 (review-lanes.md): scoped to THIS conversation's own media
// generation. Passed bare (no arg) this used to cancel whichever
diff --git a/src/lib/release-notes.ts b/src/lib/release-notes.ts
index 1209c721..5e521297 100644
--- a/src/lib/release-notes.ts
+++ b/src/lib/release-notes.ts
@@ -172,7 +172,7 @@ export const RELEASE_NOTES: ReleaseNote[] = [
},
{
title: 'The run says which tool the model is writing.',
- detail: 'A model writing a long file sends the call in pieces for many seconds, and the run said only "Working" the whole time. It now shows the tool\'s name and how much of the call has arrived as soon as the first piece is in. A run waiting for your approval says so in the chat too, and Stop before the first word leaves a note instead of an empty answer.',
+ detail: 'A model writing a long file sends the call in pieces for many seconds, and the run said only "Working" the whole time. It now shows the tool\'s name and how much of the call has arrived as soon as the first piece is in. A run waiting for your approval says so in the chat too, and Stop before the first word leaves a note instead of an empty answer. Stop pressed right after Send ends the run on the first press; before, the run could keep going or hang on "Working".',
},
{
title: 'Code conversations stay in the Code tab.',