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(media): requestGenerationCancel je Unterhaltung statt app-weit

purplec70810a24dab
diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.ts
index 4ffbb10b..f456ae0a 100644
--- a/src/api/__tests__/vram-handoff.test.ts
+++ b/src/api/__tests__/vram-handoff.test.ts
@@ -858,6 +858,65 @@ describe('vramHandoffGenerate — Stop / cancel gating', () => {
// and never submitted a second workflow.
expect(submitWorkflow).toHaveBeenCalledTimes(1)
})
+
+ // Blocker 4 (review-lanes.md, 3.0.1 lanes Runde 3): requestGenerationCancel()
+ // used to know no conversation at all, so a Stop pressed in conversation B
+ // killed conversation A's still-running image/video, literally the B2
+ // "Abbrueche landen in der falschen Unterhaltung" failure case.
+ it('a Stop scoped to conversation B does NOT touch conversation A\'s still-running generation', async () => {
+ getActiveAgentModel.mockReturnValue({ name: 'gpt-4o', providerId: 'openai', remote: false })
+ getImageModels.mockResolvedValue([{ name: 'sdxl.safetensors', type: 'sdxl', source: 'checkpoint' }])
+ buildDynamicWorkflow.mockResolvedValue({})
+ submitWorkflow.mockResolvedValue('pid-conv-a')
+ getHistory.mockResolvedValue({ status: { completed: false } }) // sits polling, never finishes on its own
+
+ const genA = vramHandoffGenerate('image', { prompt: 'a cat' }, 'conv-a')
+ await vi.waitFor(() => expect(submitWorkflow).toHaveBeenCalled())
+
+ // Stop pressed in a DIFFERENT conversation.
+ requestGenerationCancel('conv-b')
+
+ // Conversation A's job is completely untouched: no abandon, no cancel.
+ expect(abandonPrompt).not.toHaveBeenCalled()
+ expect(cancelGeneration).not.toHaveBeenCalled()
+ expect(clearComfyQueue).not.toHaveBeenCalled()
+
+ // Now the real owner stops it, and THAT does reach ComfyUI.
+ requestGenerationCancel('conv-a')
+ const out = await genA
+ expect(abandonPrompt).toHaveBeenCalledWith('pid-conv-a')
+ expect(out).toMatch(/cancelled/i)
+ })
+
+ it('a Stop scoped to conversation A cancels its OWN queued generation behind B\'s running one, without touching B', async () => {
+ getActiveAgentModel.mockReturnValue({ name: 'gpt-4o', providerId: 'openai', remote: false })
+ getImageModels.mockResolvedValue([{ name: 'sdxl.safetensors', type: 'sdxl', source: 'checkpoint' }])
+ buildDynamicWorkflow.mockResolvedValue({})
+ submitWorkflow.mockResolvedValue('pid-conv-b')
+ getHistory.mockResolvedValue({ status: { completed: false } })
+
+ const genB = vramHandoffGenerate('image', { prompt: 'running' }, 'conv-b') // seq 1, runs
+ const genA = vramHandoffGenerate('image', { prompt: 'queued' }, 'conv-a') // seq 2, parks behind B
+ await vi.waitFor(() => expect(submitWorkflow).toHaveBeenCalledTimes(1))
+
+ // A cancels ITS OWN still-queued generation. B, currently running, is not
+ // the target and must be left alone.
+ requestGenerationCancel('conv-a')
+ expect(abandonPrompt).not.toHaveBeenCalled()
+
+ // Let B finish on its own terms.
+ getHistory.mockResolvedValue({
+ status: { completed: true },
+ outputs: { images: [{ filename: 'out.png', subfolder: '', type: 'output' }] },
+ })
+ const [outB, outA] = await Promise.all([genB, genA])
+
+ expect(outA).toMatch(/cancelled/i)
+ expect(outB).not.toMatch(/cancelled/i)
+ // The key regression assertion: A's queued generation bailed on dequeue
+ // and never reached submit; only B's one call did.
+ expect(submitWorkflow).toHaveBeenCalledTimes(1)
+ })
})
// ── Per-model auto-settings (David 2026-06-22: "setze die settings für jedes
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 75faa070..778e40e2 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1273,7 +1273,7 @@ async function executeScreenshot(): Promise<string> {
return JSON.stringify(data)
}
-async function executeImageGenerate(args: ToolArgs): Promise<string> {
+async function executeImageGenerate(args: ToolArgs, run?: AgentRunContext): Promise<string> {
// Feature EE (v2.5.0): the whole generation flow now goes through the VRAM
// hand-off orchestrator. It resolves the image model (args.model or first
// installed), decides whether the resident local text model has to be evicted
@@ -1301,10 +1301,13 @@ async function executeImageGenerate(args: ToolArgs): Promise<string> {
const picked = await pickModelForGeneration('image', merged)
if (picked) merged.model = picked
const { vramHandoffGenerate } = await import('../vram-handoff')
- return vramHandoffGenerate('image', merged)
+ // Blocker 4 (review-lanes.md): thread the owning conversation through so
+ // requestGenerationCancel(convId) can tell this generation apart from one
+ // a DIFFERENT conversation's agent started.
+ return vramHandoffGenerate('image', merged, run?.conversationId ?? null)
}
-async function executeVideoGenerate(args: ToolArgs): Promise<string> {
+async function executeVideoGenerate(args: ToolArgs, run?: AgentRunContext): Promise<string> {
// Feature EE (v2.5.0): text-to-video via the same hand-off orchestrator.
// Picks the first installed video model (or args.model), detects the video
// backend (Wan / AnimateDiff), evicts the local text model from VRAM if it
@@ -1333,7 +1336,8 @@ async function executeVideoGenerate(args: ToolArgs): Promise<string> {
const picked = await pickModelForGeneration('video', merged)
if (picked) merged.model = picked
const { vramHandoffGenerate } = await import('../vram-handoff')
- return vramHandoffGenerate('video', merged)
+ // Blocker 4 (review-lanes.md): see executeImageGenerate above.
+ return vramHandoffGenerate('video', merged, run?.conversationId ?? null)
}
// ── macOS MLX generation (hard rule: local image/video on Mac is MLX only,
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index 4129749c..9ebe3187 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -570,6 +570,27 @@ let _cancelSignal: Promise<typeof CANCELLED> = new Promise<typeof CANCELLED>(()
// dequeues — its per-run resetCancel() clears the flag, but the epoch persists.
let _genSeq = 0
let _cancelledThrough = 0
+
+/**
+ * Blocker 4 (review-lanes.md, 3.0.1 lanes Runde 3): every generation, queued
+ * or running, remembers the conversation that started it. Without this,
+ * `requestGenerationCancel()` had no way to tell "conversation A's still-
+ * running image" from "conversation B's just-pressed Stop" apart; a Stop in
+ * B killed A's render, literally the B2 "Abbrueche landen in der falschen
+ * Unterhaltung" failure case. `null` means "no conversation context" (a
+ * caller outside a chat, e.g. the Create tab); it still matches only other
+ * `null`-owned generations, never a real conversation's.
+ */
+const _genOwner = new Map<number, string | null>()
+/** Seqs cancelled by a conversation-scoped requestGenerationCancel(convId)
+ * call, as opposed to the app-wide `_cancelledThrough` epoch below (still
+ * used by callers that pass no conversation at all). Cleared per-seq once
+ * that generation's own runHandoff body has finished. */
+const _cancelledSeqs = new Set<number>()
+/** The conversation that owns the generation ACTUALLY executing right now
+ * (set at the top of runHandoff, cleared in its finally): generations are
+ * strictly serialised through `_inFlight`, so there is at most one. */
+let _currentGenConvId: string | null = null
/**
* The ComfyUI job THIS lane has in flight, or null.
*
@@ -602,28 +623,61 @@ function raceCancel<T>(p: Promise<T>): Promise<T | typeof CANCELLED> {
return Promise.race([p, _cancelSignal])
}
-export function requestGenerationCancel(): void {
- _genCancelRequested = true
- _cancelledThrough = _genSeq // cancel every gen created so far (running + queued)
- _cancelNotify?.() // wake every pending raceCancel immediately
- // Only touch ComfyUI when a chat-initiated generation is actually running.
- // A plain text-chat Stop must NOT reach ComfyUI at all.
- if (_activeHandoffs > 0 && _currentPromptId) {
- // OUR job, by id — never `/interrupt` + `clear: true`. Those took down the
- // Create tab's render and the user's own ComfyUI tab along with ours, and
- // still missed ours whenever it sat behind someone else's in the queue.
- void abandonPrompt(_currentPromptId)
+/**
+ * `conversationId` scopes the cancel (Blocker 4, review-lanes.md): passing
+ * it cancels only THAT conversation's own generations, running or still
+ * queued behind another conversation's, and leaves everyone else's alone.
+ * Omitting the argument entirely keeps the pre-3.0.1 app-wide behaviour
+ * (every generation, any conversation) for callers with no conversation
+ * context of their own (`ToolCallBlock`'s "nuke everything" Stop already
+ * iterates every conversation's aborter right after this call, so it is
+ * meant to be app-wide). Pass `null` for "no conversation, but scoped": it
+ * only ever matches another `null`-owned generation, never a real one.
+ */
+export function requestGenerationCancel(conversationId?: string | null): void {
+ if (conversationId === undefined) {
+ _genCancelRequested = true
+ _cancelledThrough = _genSeq // cancel every gen created so far (running + queued)
+ _cancelNotify?.() // wake every pending raceCancel immediately
+ if (_activeHandoffs > 0 && _currentPromptId) void abandonPrompt(_currentPromptId)
+ return
+ }
+ // Mark every STILL-PENDING generation (queued or running) that belongs to
+ // this conversation. runHandoff removes its own seq from `_genOwner` the
+ // moment it finishes, so this never touches a generation that already
+ // completed.
+ for (const [seq, owner] of _genOwner) {
+ if (owner === conversationId) _cancelledSeqs.add(seq)
+ }
+ // Only reach into ComfyUI / the live cancel channel when the ACTIVELY
+ // running generation is this conversation's own; otherwise this call
+ // owns nothing that is currently executing, and touching `_cancelNotify`
+ // or `abandonPrompt` would hit whichever OTHER conversation is running.
+ if (conversationId === _currentGenConvId) {
+ _genCancelRequested = true
+ _cancelNotify?.()
+ if (_activeHandoffs > 0 && _currentPromptId) {
+ // OUR job, by id, never `/interrupt` + `clear: true`. Those took down
+ // the Create tab's render and the user's own ComfyUI tab along with
+ // ours, and still missed ours whenever it sat behind someone else's in
+ // the queue.
+ void abandonPrompt(_currentPromptId)
+ }
}
// No prompt id yet means nothing was submitted; the pre-submit check in
// submitCancellable is what keeps it that way.
}
-/** Every generation created at or before the last Stop is cancelled — the flag
- * is per-run and cleared by resetCancel(), the epoch is not. An abandoned
- * promise from a cancelled run must consult THIS, not the flag, or the next
- * run's resetCancel() would quietly re-authorise it to submit. */
+/** Every generation created at or before the last app-wide Stop is
+ * cancelled via the epoch, every generation individually marked by a
+ * conversation-scoped Stop is cancelled via `_cancelledSeqs`, and the
+ * per-run flag (cleared by resetCancel(), unlike either of those) covers
+ * the generation currently executing when ITS OWN conversation was
+ * targeted. An abandoned promise from a cancelled run must consult THIS,
+ * not the flag, or the next run's resetCancel() would quietly
+ * re-authorise it to submit. */
function cancelledFor(seq: number): boolean {
- return _genCancelRequested || seq <= _cancelledThrough
+ return _genCancelRequested || seq <= _cancelledThrough || _cancelledSeqs.has(seq)
}
/**
@@ -676,6 +730,9 @@ export function __resetGenerationStateForTests(): void {
_genCancelRequested = false
_currentPromptId = null
_lastImageFilename = null
+ _genOwner.clear()
+ _cancelledSeqs.clear()
+ _currentGenConvId = null
}
// ── Public orchestrator ───────────────────────────────────────────
@@ -701,32 +758,59 @@ export interface VramHandoffArgs {
/**
* Orchestrate one image/video generation with VRAM hand-off. Always resolves to
* a result string (never rejects) so the agent loop gets a clean tool message.
+ *
+ * `conversationId` (Blocker 4, review-lanes.md) is the conversation this
+ * generation belongs to, or `null` when there is none (e.g. the Create tab).
+ * It is what lets `requestGenerationCancel(convId)` tell this generation
+ * apart from one running for a different conversation.
*/
-export async function vramHandoffGenerate(kind: 'image' | 'video', args: VramHandoffArgs): Promise<string> {
+export async function vramHandoffGenerate(
+ kind: 'image' | 'video', args: VramHandoffArgs, conversationId: string | null = null,
+): Promise<string> {
// Serialise. We park on the previous call's settled promise (success OR
// failure — `.catch` swallows so a prior error doesn't reject our chain),
// then run our own body and expose it as the new tail.
const seq = ++_genSeq
+ _genOwner.set(seq, conversationId)
const run = _inFlight
.catch(() => {})
- .then(() => runHandoff(kind, args, seq))
+ .then(() => runHandoff(kind, args, seq, conversationId))
// Defensive: runHandoff is written to always RETURN a string (the finally
// block never rethrows), but if anything unexpected slips through we still
// hand the agent a clean tool message instead of rejecting the chain.
.catch((e) => `${kind === 'video' ? 'Video' : 'Image'} generation failed: ${e instanceof Error ? e.message : String(e)}`)
+ // Centralised here rather than inside runHandoff's own try/finally:
+ // runHandoff has several early returns BEFORE that try (no model
+ // installed, ComfyUI unreachable, etc.), and every one of them needs
+ // this same cleanup or a finished generation would keep answering
+ // "yes" to `requestGenerationCancel`'s ownership checks forever.
+ .finally(() => {
+ _genOwner.delete(seq)
+ _cancelledSeqs.delete(seq)
+ if (_currentGenConvId === conversationId) _currentGenConvId = null
+ })
_inFlight = run.catch(() => {})
return run
}
-async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: number): Promise<string> {
+async function runHandoff(
+ kind: 'image' | 'video', args: VramHandoffArgs, seq: number, conversationId: string | null,
+): Promise<string> {
// Fresh run — re-arm the cancel channel (clears any flag/notify left over from
// a previous cancelled gen).
resetCancel()
// If Stop arrived while THIS gen was still queued behind another (its seq was
- // created at/before the cancel), bail now. resetCancel() above just cleared the
- // per-run flag, but the cancel epoch persists — without this, a back-to-back
- // gen survives the user's Stop.
- if (seq <= _cancelledThrough) return `${label(kind)} generation cancelled.`
+ // created at/before the cancel, app-wide epoch, or its OWN conversation
+ // cancelled it specifically), bail now. resetCancel() above just cleared the
+ // per-run flag, but neither the epoch nor a conversation-scoped mark persist
+ // past this check; without it, a back-to-back gen survives the user's Stop.
+ if (seq <= _cancelledThrough || _cancelledSeqs.has(seq)) {
+ return `${label(kind)} generation cancelled.`
+ }
+ // From here on, THIS conversation owns the actively-running generation;
+ // requestGenerationCancel(convId) reaches ComfyUI/the live cancel channel
+ // only when convId matches this.
+ _currentGenConvId = conversationId
// Robustness for small local models (gemma4:e4b live): they frequently emit a
// snake_case `input_image` alias and sometimes omit `prompt` on a video call.
// Normalize the alias so the I2V path still finds the source image.
diff --git a/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts b/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts
index 03b49133..b81dc6c7 100644
--- a/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts
+++ b/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts
@@ -10,7 +10,7 @@
* (`useAgentChat.ts`) und `codexLoopTimers` (`useCodex.ts`), und bisher
* loeschten nur `stopAgent`/`stopCodex` sie. Der faellige Rueckruf pruefte
* beim Feuern nur, ob DIESE Unterhaltung schon etwas generiert und ob sie die
- * sichtbare ist — nicht, ob der Nutzer den Lauf per Stop-Merker
+ * sichtbare ist, nicht, ob der Nutzer den Lauf per Stop-Merker
* (`lib/run-stop.ts`) beendet hat. Nach Abmelden, Fenster schliessen oder App
* beenden feuerte der Zeitgeber also trotzdem und schickte eine bezahlte
* Cloud-Anfrage in eine Sitzung, die die App dem Nutzer bereits als beendet
@@ -68,7 +68,7 @@ const sse = (payload: object) =>
status: 200, headers: { 'content-type': 'text/event-stream' },
})
// Never says the /loop magic-done word, so the driver always schedules
-// another pass — that is what gives Blocker 3 something real to prevent.
+// another pass, that is what gives Blocker 3 something real to prevent.
const textZug = () => sse({ choices: [{ delta: { content: 'weiter beim naechsten Mal' } }] })
function seed(): string {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index a921184a..2cad9828 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -780,8 +780,11 @@ export function useAgentChat() {
// Register so deleting/closing this chat stops the agent loop (Bug C).
// requestGenerationCancel too, so a ComfyUI gen the agent kicked off is
// interrupted when the chat is deleted mid-generation (gated to a no-op when
- // nothing is in flight).
- useGenerationStore.getState().registerAborter(convId, () => { abort.abort(); requestGenerationCancel() })
+ // nothing is in flight). Scoped to THIS conversation (Blocker 4,
+ // 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) })
// 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
@@ -2766,7 +2769,11 @@ export function useAgentChat() {
// Interrupt any in-flight ComfyUI gen too — the main Stop button only aborted
// the agent loop before, so a running image/video kept burning unless the user
// happened to click the small in-chat tool Stop. Now both Stops agree.
- requestGenerationCancel()
+ // Scoped to stoppedConvId (Blocker 4, review-lanes.md): a bare call used
+ // to cancel whichever generation happened to be running app-wide, so a
+ // Stop in conversation B killed conversation A's still-producing
+ // image/video.
+ requestGenerationCancel(stoppedConvId)
drainApprovals(stoppedConvId)
}, [])
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 48cb25b5..65dcc3ab 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -810,7 +810,11 @@ export function useChat() {
// review-lanes.md): Stop, then an immediate resend on the same
// conversation, can register a NEW aborter here before this run's
// `finally` executes, and the old run's cleanup must not reach past it.
- const myAborter = () => { abort.abort(); requestGenerationCancel() }
+ // Blocker 4 (review-lanes.md): scoped to THIS conversation. A bare call
+ // used to cancel whichever generation happened to be running app-wide,
+ // so Stop in one chat could kill an image/video another chat's agent
+ // was still producing.
+ const myAborter = () => { abort.abort(); requestGenerationCancel(convId) }
useGenerationStore.getState().registerAborter(convId, myAborter)
setIsGenerating(true)
// Bind the generating flag to THIS conversation so the typing indicator
@@ -1297,8 +1301,11 @@ export function useChat() {
useGenerationStore.getState().abortConversation(convId)
// Also interrupt an in-flight ComfyUI image/video gen, not just the JS loop —
// otherwise the main Stop button leaves ComfyUI burning (only the in-chat
- // tool Stop did this before; now both affordances agree).
- requestGenerationCancel()
+ // tool Stop did this before; now both affordances agree). Scoped to convId
+ // (Blocker 4, review-lanes.md): a bare call used to cancel whichever
+ // generation happened to be running app-wide, killing another
+ // conversation's still-producing image/video.
+ requestGenerationCancel(convId)
}, [stopAgent])
/**
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 1894904d..45f77c90 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -874,7 +874,12 @@ export function useCodex() {
// chat deletion both reach the real controller. Cleared in finally.
useGenerationStore.getState().registerAborter(convId, () => {
abort.abort()
- requestGenerationCancel()
+ // Blocker 4 (review-lanes.md): scoped to THIS conversation's own media
+ // generation. Passed bare (no arg) this used to cancel whichever
+ // generation happened to be running app-wide, so Stop in one Code
+ // conversation could kill an image/video another conversation's agent
+ // was still producing.
+ requestGenerationCancel(convId)
})
// Architect / RepoMap pre-pass (B8 + B9). Both inject into the