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 really stops background delegate_task work

purple4c9cb5e4a4f0
diff --git a/src/api/agents/__tests__/sub-agent.test.ts b/src/api/agents/__tests__/sub-agent.test.ts
index 45291685..77cf16f2 100644
--- a/src/api/agents/__tests__/sub-agent.test.ts
+++ b/src/api/agents/__tests__/sub-agent.test.ts
@@ -419,6 +419,21 @@ describe('sub-agent — abort signal (AGT-1)', () => {
expect(chatWithTools).not.toHaveBeenCalled()
expect(out).toMatch(/stopped by the user/)
})
+
+ // B1 (3.0.1): before this fix, the abort signal was checked ONLY at the top
+ // of the next loop iteration and never handed to the provider itself, so a
+ // Stop pressed mid-request left the fetch running to completion on its own
+ // (T4: a 25.2s cloud request still finished with status 200, 13.4s after
+ // Stop). The provider call must receive the SAME signal the tool gates use,
+ // so an in-flight request actually aborts instead of billing to the end.
+ it('threads the abort signal into the chatWithTools call itself', async () => {
+ const ctrl = new AbortController()
+ chatWithTools.mockResolvedValueOnce({ content: 'done', toolCalls: [] })
+ await runSub(makeRun({ abortSignal: ctrl.signal }))
+ expect(chatWithTools).toHaveBeenCalledOnce()
+ const options = chatWithTools.mock.calls[0][3]
+ expect(options?.signal).toBe(ctrl.signal)
+ })
})
// ── Eine Ankuendigung ist keine Antwort (Persona B2) ─────────────────────
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index 9dacbc7d..4dc532ad 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -564,7 +564,14 @@ export async function defaultSubAgentRunner(
const material = finalContent || gesammeltesMaterial(messages)
return `${options.budget.haltMessage()} ${material || '(no partial answer)'}`
}
- const turn = await provider.chatWithTools(modelId, messages, llmTools, {})
+ // B1 (3.0.1): `gates.abortSignal` was only checked at the TOP of the next
+ // iteration, never handed to the provider call itself. A Stop pressed
+ // mid-request left the fetch running to completion on its own — T4
+ // measured a 25.2s cloud request finishing with status 200, 13.4s after
+ // the user stopped, and that is paid compute the product promised would
+ // not happen ("Stop means stop"). Threading the same signal the tool
+ // gates already use into the request makes the abort reach the wire.
+ const turn = await provider.chatWithTools(modelId, messages, llmTools, { signal: gates.abortSignal })
// What a sub-agent returns becomes a TOOL RESULT in the parent's context,
// so leaked reasoning floods the run it was supposed to shorten (2.6.7
// Denk-Audit, Loch 11). Same settlement as every visible surface.
diff --git a/src/components/chat/AgentPanel.tsx b/src/components/chat/AgentPanel.tsx
index 97743b02..a8aeba02 100644
--- a/src/components/chat/AgentPanel.tsx
+++ b/src/components/chat/AgentPanel.tsx
@@ -89,9 +89,51 @@ function TaskRow({ task, now }: { task: AgentTask; now: number }) {
)
}
+/**
+ * B1 (3.0.1, Orchestrator-Entscheid): Unterhaltung wechseln beendet einen
+ * Hintergrundauftrag NICHT — der Kunde darf ihn bewusst weiterlaufen lassen.
+ * Aber wenn dieses Panel unten nur an `activeConversationId` haengt, zeigt es
+ * beim Wechsel in eine andere Unterhaltung GAR NICHTS mehr, obwohl anderswo
+ * noch etwas laeuft und Credits kostet. Diese Leiste ist die sichtbare
+ * Ausnahme: sie zaehlt laufende Aufgaben in JEDER ANDEREN Unterhaltung und
+ * bietet denselben Stop-all-Griff wie das Panel selbst.
+ */
+function ElsewhereBar({ byConv, activeConvId }: {
+ byConv: Record<string, AgentTask[]>
+ activeConvId: string | null
+}) {
+ const cancelAll = useAgentTaskStore((s) => s.cancelAll)
+ const elsewhere = Object.entries(byConv).filter(([id]) => id !== activeConvId)
+ const laufend = elsewhere.reduce(
+ (n, [, list]) => n + list.filter((t) => t.status === 'running').length,
+ 0,
+ )
+ if (laufend === 0) return null
+ return (
+ <div
+ data-testid="agent-panel-elsewhere-bar"
+ className="flex items-center gap-1.5 px-2 py-1 border-b border-gray-200 dark:border-white/[0.04] bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400"
+ >
+ <Loader2 size={10} className="animate-spin shrink-0" />
+ <span className="t-micro flex-1">
+ {laufend} background {laufend === 1 ? 'agent' : 'agents'} running in {elsewhere.length === 1 ? 'another chat' : 'other chats'} · costs credits
+ </span>
+ <button
+ onClick={() => { for (const [id] of elsewhere) cancelAll(id) }}
+ title="Stop every running agent in other chats"
+ data-testid="agent-panel-elsewhere-stop-all"
+ className="p-1 rounded hover:bg-amber-100 dark:hover:bg-amber-500/20 transition-colors shrink-0"
+ >
+ <Square size={9} />
+ </button>
+ </div>
+ )
+}
+
export function AgentPanel() {
const convId = useChatStore((s) => s.activeConversationId)
- const tasks = useAgentTaskStore((s) => (convId ? s.byConv[convId] : undefined))
+ const byConv = useAgentTaskStore((s) => s.byConv)
+ const tasks = convId ? byConv[convId] : undefined
const cancelAll = useAgentTaskStore((s) => s.cancelAll)
const width = useUIStore((s) => s.agentPanelWidth)
const collapsed = useUIStore((s) => s.agentPanelCollapsed)
@@ -103,6 +145,13 @@ export function AgentPanel() {
// Sekunde für eine Zahl, die sich nicht mehr ändert.
const laufend = (tasks ?? []).filter((t) => t.status === 'running').length
const gescheitert = (tasks ?? []).filter((t) => t.status === 'failed').length
+ // B1: laufende Aufgaben in JEDER ANDEREN Unterhaltung, unabhaengig davon,
+ // ob diese hier selbst welche hat. Entscheidet, ob das Panel ueberhaupt
+ // sichtbar bleibt, wenn die aktive Unterhaltung leer ist.
+ const anderswoLaufend = Object.entries(byConv).reduce(
+ (n, [id, list]) => (id === convId ? n : n + list.filter((t) => t.status === 'running').length),
+ 0,
+ )
// ── Eine NEUE Aufgabe klappt das Panel auf ─────────────────────────────
//
@@ -135,7 +184,7 @@ export function AgentPanel() {
return () => clearInterval(id)
}, [laufend])
- if (!convId || !tasks?.length) return null
+ if (!convId || (!tasks?.length && anderswoLaufend === 0)) return null
if (collapsed) {
return (
@@ -148,6 +197,20 @@ export function AgentPanel() {
>
<PanelRightOpen size={12} />
</button>
+ {/* B1: auch zugeklappt und auch wenn die aktive Unterhaltung selbst
+ still ist, muss sichtbar bleiben, dass ANDERSWO noch Credits
+ verbrannt werden. */}
+ {anderswoLaufend > 0 && (
+ <button
+ onClick={() => setCollapsed(false)}
+ title={`${anderswoLaufend} running in other chats · costs credits`}
+ data-testid="agent-panel-elsewhere-badge"
+ className="mt-1 flex flex-col items-center text-amber-500"
+ >
+ <Loader2 size={10} className="animate-spin" />
+ <span className="t-mono">{anderswoLaufend}</span>
+ </button>
+ )}
{/* Auch zugeklappt muss "es läuft etwas" sichtbar bleiben — sonst
versteckt ein Klick die einzige Spur eines Agenten, der gerade
Werkzeuge auf der Maschine des Nutzers fährt. */}
@@ -231,10 +294,12 @@ export function AgentPanel() {
</button>
</div>
+ <ElsewhereBar byConv={byConv} activeConvId={convId} />
+
<div className="flex-1 overflow-y-auto scrollbar-thin min-h-0">
{/* Neueste oben: das Panel beantwortet "was läuft gerade", nicht
"was lief zuerst". */}
- {[...tasks].reverse().map((t) => (
+ {[...(tasks ?? [])].reverse().map((t) => (
<TaskRow key={t.id} task={t} now={now} />
))}
</div>
diff --git a/src/components/chat/__tests__/agent-panel-elsewhere.test.tsx b/src/components/chat/__tests__/agent-panel-elsewhere.test.tsx
new file mode 100644
index 00000000..5e2cb554
--- /dev/null
+++ b/src/components/chat/__tests__/agent-panel-elsewhere.test.tsx
@@ -0,0 +1,70 @@
+// @vitest-environment jsdom
+/**
+ * B1 (3.0.1, Orchestrator-Entscheid): "Unterhaltung wechseln beendet NICHT"
+ * einen Hintergrundauftrag, der Kunde darf ihn bewusst weiterlaufen lassen.
+ * Vorher haengte das ganze Panel an `activeConversationId` — beim Wechsel in
+ * eine andere Unterhaltung verschwand jede Spur, obwohl anderswo noch etwas
+ * lief und Credits kostete. Diese Tests fahren den echten agentTaskStore und
+ * das echte AgentPanel, keine Attrappe.
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { AgentPanel } from '../AgentPanel'
+import { useAgentTaskStore } from '../../../stores/agentTaskStore'
+import { useChatStore } from '../../../stores/chatStore'
+import { useUIStore } from '../../../stores/uiStore'
+
+const HERE = 'conv-here'
+const THERE = 'conv-there'
+
+function starte(id: string, convId: string, controller = new AbortController()) {
+ useAgentTaskStore.getState().start({
+ id,
+ convId,
+ goal: 'goal ' + id,
+ context: '',
+ background: true,
+ startedAt: Date.now(),
+ controller,
+ })
+ return controller
+}
+
+beforeEach(() => {
+ cleanup()
+ useAgentTaskStore.setState({ byConv: {} })
+ useChatStore.setState({ activeConversationId: HERE })
+ useUIStore.getState().setAgentPanelCollapsed(false)
+})
+
+describe('AgentPanel — background work in another chat stays visible', () => {
+ it('shows nothing when no conversation has a background task', () => {
+ render(<AgentPanel />)
+ expect(screen.queryByTestId('agent-panel')).toBeNull()
+ expect(screen.queryByTestId('agent-panel-elsewhere-bar')).toBeNull()
+ })
+
+ it('the active chat has none, but another chat is still running — the panel says so', () => {
+ starte('t1', THERE)
+ render(<AgentPanel />)
+ expect(screen.getByTestId('agent-panel-elsewhere-bar')).toBeTruthy()
+ expect(screen.getByText(/1 background agent running in another chat/)).toBeTruthy()
+ expect(screen.getByText(/costs credits/)).toBeTruthy()
+ })
+
+ it('Stop all in the elsewhere bar cancels the OTHER conversation, not the active one', () => {
+ const hereCtrl = starte('t-here', HERE)
+ const thereCtrl = starte('t-there', THERE)
+ render(<AgentPanel />)
+ fireEvent.click(screen.getByTestId('agent-panel-elsewhere-stop-all'))
+ expect(thereCtrl.signal.aborted).toBe(true)
+ expect(hereCtrl.signal.aborted).toBe(false)
+ })
+
+ it('stays visible even collapsed, as an amber badge distinct from the own-chat one', () => {
+ starte('t2', THERE)
+ useUIStore.getState().setAgentPanelCollapsed(true)
+ render(<AgentPanel />)
+ expect(screen.getByTestId('agent-panel-elsewhere-badge')).toBeTruthy()
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 831359ee..45173955 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2610,6 +2610,14 @@ export function useAgentChat() {
// rest of the session.
const stoppedConvId = useChatStore.getState().activeConversationId
stopRun(stoppedConvId)
+ // B1 (3.0.1, Orchestrator-Entscheid): "Stop means stop" gilt auch fuer
+ // Hintergrundauftraege dieser Unterhaltung, die per delegate_task
+ // background gestartet wurden. Vorher endete Stop nur die Hauptantwort,
+ // ein laufender Unteragent kostete unbemerkt weiter Rechenzeit, bis er von
+ // selbst fertig wurde. cancelAll bricht jeden `running`-Eintrag dieser
+ // Unterhaltung ab (siehe agentTaskStore.ts), derselbe Griff wie der
+ // "Stop all"-Knopf im Aufgabenpanel.
+ useAgentTaskStore.getState().cancelAll(stoppedConvId ?? '')
if (agentLoopTimer) {
clearTimeout(agentLoopTimer)
agentLoopTimer = null
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 075f958c..266edb88 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2567,6 +2567,10 @@ export function useCodex() {
// and the module-scoped stop is readable from its loop driver's finally,
// which lives in that instance's closure and can read no ref of this one.
stopRun(stoppedConvId)
+ // B1 (3.0.1): siehe useAgentChat.ts stopAgent, derselbe Griff fuer den
+ // Code-Tab. Ein per delegate_task background gestarteter Unteragent
+ // dieser Unterhaltung lief bisher nach Stop unbemerkt weiter.
+ useAgentTaskStore.getState().cancelAll(stoppedConvId ?? '')
useGenerationStore.getState().abortConversation(stoppedConvId)
if (codexLoopTimer) {
clearTimeout(codexLoopTimer)
diff --git a/src/lib/__tests__/run-stop.test.ts b/src/lib/__tests__/run-stop.test.ts
index 179e9fa5..854b09b2 100644
--- a/src/lib/__tests__/run-stop.test.ts
+++ b/src/lib/__tests__/run-stop.test.ts
@@ -111,6 +111,15 @@ describe('run-stop — both loop surfaces are wired to it', () => {
}
})
+ it('B1 (3.0.1): both stop buttons also cancel background delegate_task agents of the conversation', () => {
+ // Before this fix, a `delegate_task background: true` run kept billing
+ // compute after Stop — the main answer ended, the sub-agent did not, and
+ // the Orchestrator's decision is that Stop means stop for both.
+ for (const src of [codex, agent]) {
+ expect(src).toContain('useAgentTaskStore.getState().cancelAll(stoppedConvId')
+ }
+ })
+
it('Codex also refuses to auto-apply staged changes after a Stop', () => {
// The auto-apply sits on the loop's NORMAL exit path (the for-loop condition
// includes !abort.signal.aborted, so a Stop leaves through it), which meant a