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(shutdown): Reichweite, Netzabbruch und Karenzzeit fuer den X-Klick

purpleb73b834e179d
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 5195c3a7..45856cd0 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -1,6 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Header } from './Header'
import { StaleModelsBanner } from './StaleModelsBanner'
+import { BackgroundShutdownBanner } from './BackgroundShutdownBanner'
import { StorageQuotaToast } from './StorageQuotaToast'
import { Sidebar } from './Sidebar'
import { ChatView } from '../chat/ChatView'
@@ -1077,6 +1078,7 @@ export function AppShell() {
<Titlebar />
<Header />
<StaleModelsBanner />
+ <BackgroundShutdownBanner />
{restoreError && (
<div className="mx-2 mt-2 flex items-start gap-2 rounded-lg border border-red-500/20 bg-red-500/[0.06] px-3 py-2">
<p role="alert" className="flex-1 text-[0.65rem] leading-snug text-red-500 dark:text-red-400 whitespace-pre-line">
diff --git a/src/components/layout/BackgroundShutdownBanner.tsx b/src/components/layout/BackgroundShutdownBanner.tsx
new file mode 100644
index 00000000..199a68ce
--- /dev/null
+++ b/src/components/layout/BackgroundShutdownBanner.tsx
@@ -0,0 +1,35 @@
+import { X } from 'lucide-react'
+import { useBackgroundShutdownStore } from '../../stores/backgroundShutdownStore'
+import { HINWEIS_TEXT, HINWEIS_ZEILE } from '../../lib/hinweis'
+
+/**
+ * B1 Runde 2, Punkt 1 und 4. The one visible line for what
+ * `lib/background-shutdown.ts` did without the user watching — see that
+ * module's doc comment for the two triggers.
+ *
+ * Same quiet-row form as StaleModelsBanner: nothing crashed, so no filled
+ * warning colour, `role="status"` so a screen reader is not interrupted.
+ */
+export function BackgroundShutdownBanner() {
+ const { notice, dismiss } = useBackgroundShutdownStore()
+
+ if (!notice) return null
+
+ const text = notice.kind === 'offline'
+ ? 'Connection lost. Running work is waiting or will retry once you are back online.'
+ : 'Closing the window stopped background agent work so nothing kept running unseen. Send a new message to continue.'
+
+ return (
+ <div role="status" className={`${HINWEIS_ZEILE} ${HINWEIS_TEXT.ruhig} px-3 py-1`}>
+ <span className="flex-1 min-w-0 self-center">{text}</span>
+ <button
+ onClick={dismiss}
+ className="self-center shrink-0 rounded p-[1px] opacity-70 hover:opacity-100 transition-opacity"
+ aria-label="Dismiss"
+ title="Dismiss"
+ >
+ <X size={11} />
+ </button>
+ </div>
+ )
+}
diff --git a/src/components/layout/__tests__/background-shutdown-banner.test.tsx b/src/components/layout/__tests__/background-shutdown-banner.test.tsx
new file mode 100644
index 00000000..db301553
--- /dev/null
+++ b/src/components/layout/__tests__/background-shutdown-banner.test.tsx
@@ -0,0 +1,47 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * B1 Runde 2, Punkt 1 und 4: the visible half of `lib/background-shutdown.ts`.
+ * Stopping work without saying so is the same complaint that opened this
+ * whole Nachbesserung — a stop the user cannot see is not a stop they can
+ * act on.
+ *
+ * Run: npx vitest run src/components/layout/__tests__/background-shutdown-banner.test.tsx
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { cleanup, render, screen, fireEvent } from '@testing-library/react'
+import { BackgroundShutdownBanner } from '../BackgroundShutdownBanner'
+import { useBackgroundShutdownStore } from '../../../stores/backgroundShutdownStore'
+
+beforeEach(() => useBackgroundShutdownStore.setState({ notice: null }))
+afterEach(() => cleanup())
+
+describe('BackgroundShutdownBanner', () => {
+ it('shows nothing when there is no notice', () => {
+ render(<BackgroundShutdownBanner />)
+ expect(screen.queryByRole('status')).toBeNull()
+ })
+
+ it('says the connection is down, in English, without claiming work stopped', () => {
+ useBackgroundShutdownStore.setState({ notice: { kind: 'offline' } })
+ render(<BackgroundShutdownBanner />)
+ const line = screen.getByRole('status')
+ expect(line.textContent).toContain('Connection lost')
+ expect(line.textContent).not.toContain('stopped')
+ })
+
+ it('says background work was actually stopped, after the window was closed', () => {
+ useBackgroundShutdownStore.setState({ notice: { kind: 'hidden-stopped', at: Date.now() } })
+ render(<BackgroundShutdownBanner />)
+ const line = screen.getByRole('status')
+ expect(line.textContent).toContain('Closing the window stopped background agent work')
+ expect(line.textContent).toContain('Send a new message')
+ })
+
+ it('dismiss clears the notice', () => {
+ useBackgroundShutdownStore.setState({ notice: { kind: 'offline' } })
+ render(<BackgroundShutdownBanner />)
+ fireEvent.click(screen.getByLabelText('Dismiss'))
+ expect(useBackgroundShutdownStore.getState().notice).toBeNull()
+ })
+})
diff --git a/src/lib/__tests__/background-shutdown.test.ts b/src/lib/__tests__/background-shutdown.test.ts
index c2ecef52..1c465672 100644
--- a/src/lib/__tests__/background-shutdown.test.ts
+++ b/src/lib/__tests__/background-shutdown.test.ts
@@ -9,6 +9,12 @@
* hooks/__tests__/signing-out-must-not-lie.test.ts, weil es dort schon die
* ganze Sign-out-Vertragspruefung gibt). Je Ausloeser ein Fall.
*
+ * Runde 2 (Final Verifier, 18.09.) fand zwei Blocker hier, beide unten
+ * nachgezogen: die Reichweite war auf `delegate_task`-Hintergrundlaeufe
+ * verengt (ein normaler Agent oder `/loop` OHNE Unteraufgabe entkam), und
+ * `offline` toetete mit dem klebrigen `stopRun`-Merker jede Agentenarbeit
+ * schon bei einem kurzen WLAN-Wackler.
+ *
* Lauf: npx vitest run src/lib/__tests__/background-shutdown.test.ts
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
@@ -17,6 +23,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
const listeners: Record<string, ((e: unknown) => void)[]> = {}
const unlisten = vi.fn()
let tauriOn = false
+let windowVisible = false
vi.mock('../../api/backend', () => ({
isTauri: () => tauriOn,
@@ -27,9 +34,17 @@ vi.mock('@tauri-apps/api/event', () => ({
return unlisten
},
}))
+vi.mock('@tauri-apps/api/window', () => ({
+ getCurrentWindow: () => ({
+ isVisible: async () => windowVisible,
+ }),
+}))
import { useAgentTaskStore } from '../../stores/agentTaskStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
import { isRunStopped, __resetRunStopsForTests } from '../run-stop'
+import { useBackgroundShutdownStore } from '../../stores/backgroundShutdownStore'
import {
stopAllBackgroundWork,
installBackgroundShutdown,
@@ -44,19 +59,41 @@ function laufendeAufgabe(id: string, convId: string): AbortController {
return controller
}
+/** A normal agent/chat stream mid-flight, with NO delegate_task sub-agent —
+ * the shape Runde 2 found byConv could not see at all. */
+function laufenderStrom(convId: string): { aborted: () => boolean } {
+ let aborted = false
+ useGenerationStore.getState().registerAborter(convId, () => { aborted = true })
+ useGenerationStore.getState().setGenerating(convId, true)
+ return { aborted: () => aborted }
+}
+
+/** A /loop pass parked between two runs — nothing is "generating", so only
+ * the loop store knows this conversation still has work pending. */
+function wartenderLoopPass(convId: string): void {
+ useAgentLoopStore.getState().start({
+ conversationId: convId, pass: 2, cap: 0, task: 'weiter', intervalMs: 1000, nextAt: Date.now() + 1000,
+ })
+}
+
beforeEach(() => {
useAgentTaskStore.setState({ byConv: {} })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useAgentLoopStore.setState({ loop: null })
+ useBackgroundShutdownStore.setState({ notice: null })
__resetRunStopsForTests()
__resetBackgroundShutdownForTests()
tauriOn = false
+ windowVisible = false
for (const k of Object.keys(listeners)) delete listeners[k]
unlisten.mockClear()
})
afterEach(() => {
__resetBackgroundShutdownForTests()
+ vi.useRealTimers()
})
-describe('stopAllBackgroundWork', () => {
+describe('stopAllBackgroundWork: reach (Runde 2, Blocker 2)', () => {
it('cancels every running task in every conversation, not just the visible one', () => {
const a = laufendeAufgabe('task-a', 'conv-A')
const b = laufendeAufgabe('task-b', 'conv-B')
@@ -85,6 +122,40 @@ describe('stopAllBackgroundWork', () => {
expect(c.signal.aborted).toBe(false)
expect(isRunStopped('conv-1')).toBe(true)
})
+
+ it('reaches a normal agent/chat stream that never started a delegate_task sub-agent', () => {
+ // The gap Runde 2 named as unclosed: byConv alone never sees this.
+ const strom = laufenderStrom('conv-plain')
+
+ stopAllBackgroundWork()
+
+ expect(strom.aborted()).toBe(true)
+ expect(isRunStopped('conv-plain')).toBe(true)
+ })
+
+ it('reaches a /loop pass waiting out its interval, which generates nothing right now', () => {
+ wartenderLoopPass('conv-loop')
+
+ stopAllBackgroundWork()
+
+ expect(useAgentLoopStore.getState().loop).toBeNull()
+ expect(isRunStopped('conv-loop')).toBe(true)
+ })
+
+ it('reaches all three shapes at once, none crowding out another', () => {
+ const task = laufendeAufgabe('task-x', 'conv-task')
+ const strom = laufenderStrom('conv-stream')
+ wartenderLoopPass('conv-loop')
+
+ stopAllBackgroundWork()
+
+ expect(task.signal.aborted).toBe(true)
+ expect(strom.aborted()).toBe(true)
+ expect(useAgentLoopStore.getState().loop).toBeNull()
+ expect(isRunStopped('conv-task')).toBe(true)
+ expect(isRunStopped('conv-stream')).toBe(true)
+ expect(isRunStopped('conv-loop')).toBe(true)
+ })
})
describe('installBackgroundShutdown: App beenden (pagehide + beforeunload)', () => {
@@ -108,41 +179,90 @@ describe('installBackgroundShutdown: App beenden (pagehide + beforeunload)', ()
})
})
-describe('installBackgroundShutdown: Netzabbruch (offline)', () => {
- it('a dropped connection stops every running background task', () => {
+describe('installBackgroundShutdown: Netzabbruch (Runde 2, Blocker 1 — offline stoppt nichts mehr)', () => {
+ it('a dropped connection leaves running work running: retry.ts is built for exactly this', () => {
installBackgroundShutdown()
const c = laufendeAufgabe('task-z', 'conv-1')
window.dispatchEvent(new Event('offline'))
- expect(c.signal.aborted).toBe(true)
- expect(isRunStopped('conv-1')).toBe(true)
+ expect(c.signal.aborted).toBe(false)
+ expect(isRunStopped('conv-1')).toBe(false)
+ })
+
+ it('shows a visible notice instead', () => {
+ installBackgroundShutdown()
+ window.dispatchEvent(new Event('offline'))
+ expect(useBackgroundShutdownStore.getState().notice).toEqual({ kind: 'offline' })
+ })
+
+ it('reconnecting clears the notice on its own, no user action needed', () => {
+ installBackgroundShutdown()
+ window.dispatchEvent(new Event('offline'))
+ expect(useBackgroundShutdownStore.getState().notice?.kind).toBe('offline')
+
+ window.dispatchEvent(new Event('online'))
+ expect(useBackgroundShutdownStore.getState().notice).toBeNull()
+ })
+
+ it('COUNTER-CHECK: a two-second wobble and reconnect never touches a running task', () => {
+ // The exact scenario Runde 2 named: WLAN wobble, VPN switch, sleep/wake.
+ installBackgroundShutdown()
+ const c = laufendeAufgabe('task-wobble', 'conv-1')
+
+ window.dispatchEvent(new Event('offline'))
+ window.dispatchEvent(new Event('online'))
+
+ expect(c.signal.aborted).toBe(false)
+ expect(isRunStopped('conv-1')).toBe(false)
})
})
-describe('installBackgroundShutdown: Fenster schliessen (app:hidden, nicht onCloseRequested)', () => {
+describe('installBackgroundShutdown: Fenster schliessen (app:hidden IST onCloseRequested)', () => {
/**
- * main.rs intercepts CloseRequested with api.prevent_close() and hides to
- * the tray, the window's X does not quit this app. A JS onCloseRequested
- * listener would fire on that exact same click and stop every background
- * agent on a plain tray-hide, which is not what "Fenster schliessen" as a
- * Stop trigger should mean here. main.rs already relays that moment to the
- * frontend as `app:hidden` (useVoice.ts listens to it for the identical
- * reason, mic/playback must not keep running behind a hidden window), so
- * this module reuses that signal instead of registering a second listener
- * for the same event.
+ * main.rs sendet `app:hidden` an GENAU EINER Stelle: im `CloseRequested`-
+ * Arm, direkt bevor es das Fenster in den Tray versteckt. Ein Horcher auf
+ * dieses Ereignis ist also derselbe X-Klick, nicht ein zweiter, getrennter
+ * Moment — mit derselben Karenzzeit, die main.rs fuer den lokalen-Modelle-
+ * Offload nach demselben Klick schon anwendet.
*/
- it('reacts to app:hidden and stops every running background task', async () => {
+ it('reacts to app:hidden and, after the grace period, stops every running background task', async () => {
tauriOn = true
+ vi.useFakeTimers()
installBackgroundShutdown()
- await new Promise((r) => setTimeout(r, 0))
+ await vi.advanceTimersByTimeAsync(0)
expect(listeners['app:hidden']).toBeDefined()
const c = laufendeAufgabe('task-w', 'conv-1')
+ windowVisible = false
for (const cb of listeners['app:hidden']) cb(undefined)
+ // Not yet — the mis-click grace period has not elapsed.
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(c.signal.aborted).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(30_000)
expect(c.signal.aborted).toBe(true)
expect(isRunStopped('conv-1')).toBe(true)
+ expect(useBackgroundShutdownStore.getState().notice).toEqual({ kind: 'hidden-stopped', at: expect.any(Number) })
+ })
+
+ it('a reopen inside the grace period cancels the stop entirely (the mis-click case)', async () => {
+ tauriOn = true
+ vi.useFakeTimers()
+ installBackgroundShutdown()
+ await vi.advanceTimersByTimeAsync(0)
+
+ const c = laufendeAufgabe('task-w2', 'conv-1')
+ for (const cb of listeners['app:hidden']) cb(undefined)
+
+ // The user re-opened the window well within the grace period.
+ windowVisible = true
+ await vi.advanceTimersByTimeAsync(30_000)
+
+ expect(c.signal.aborted).toBe(false)
+ expect(isRunStopped('conv-1')).toBe(false)
+ expect(useBackgroundShutdownStore.getState().notice).toBeNull()
})
it('does not register app:hidden outside Tauri (browser-dev / web build)', async () => {
diff --git a/src/lib/background-shutdown.ts b/src/lib/background-shutdown.ts
index 60ce3e63..c46c19f2 100644
--- a/src/lib/background-shutdown.ts
+++ b/src/lib/background-shutdown.ts
@@ -2,45 +2,131 @@
* B1 Nachbesserung 1 (Opus-Review, 3.0.1) - der Orchestrator-Entscheid "Stop
* heisst Stop" galt von Anfang an fuer fuenf Ausloeser: der Stop-Knopf,
* Abmelden, Fenster schliessen, App beenden, Netzabbruch. Gebaut war nur der
- * erste. Ohne die anderen vier feuert ein delegate_task-Hintergrundagent
- * weiter, nachdem der Nutzer sich abgemeldet hat - mit einem Konto, das er
- * gerade verlassen hat glaubt. Das ist die teuerste der vier Luecken.
+ * erste. Ohne die anderen vier feuert ein Hintergrundagent weiter, nachdem
+ * der Nutzer sich abgemeldet hat - mit einem Konto, das er gerade verlassen
+ * hat glaubt. Das ist die teuerste der vier Luecken.
*
- * `stopAllBackgroundWork()` ist die eine Stelle: sie laeuft ueber jede
- * Konversation im Aufgaben-Store und wendet dasselbe Paar an, das der
- * Stop-Knopf selbst benutzt (useAgentTaskStore.cancelAll + lib/run-stop's
- * stopRun) - kein neuer Mechanismus, nur derselbe an vier weiteren Stellen.
- * `stopRun` ist wichtig und nicht nur `cancelAll`: ohne den klebrigen Merker
- * wuerde ein Hintergrundagent, der GENAU IN DEM MOMENT gestartet wird (siehe
- * die Wettlauf-Nachbesserung in api/agents/sub-agent.ts), den Ausloeser
- * verpassen.
+ * `stopAllBackgroundWork()` ist die eine Stelle: sie laeuft ueber JEDEN
+ * laufenden Lauf, egal welcher der drei Sendewege ihn gestartet hat, und
+ * wendet dasselbe Paar an, das der Stop-Knopf selbst benutzt
+ * (generationStore.abortConversation + lib/run-stop's stopRun) - kein neuer
+ * Mechanismus, nur derselbe an mehr Stellen.
+ *
+ * ── Runde 2 (Final Verifier, 18.09.): zwei Blocker in dieser Datei ─────────
+ *
+ * BLOCKER Reichweite: diese Funktion lief bis heute nur ueber
+ * `useAgentTaskStore.byConv`, also nur ueber Konversationen, die je eine
+ * `delegate_task`-Unteraufgabe gestartet haben. Eine normale Agenten- oder
+ * `/loop`-Schleife OHNE Unteraufgabe lief nach Abmelden, Schliessen und
+ * Netzabbruch ungebremst weiter. Jetzt: die Vereinigung aus drei Quellen,
+ * keine davon eine Kopie einer anderen -
+ * `agentTaskStore.byConv` delegate_task-Hintergrundlaeufe.
+ * `generationStore.generating` JEDER Strom, der gerade Token zieht:
+ * Chat, Agent, Codex, egal welcher Hook.
+ * `agentLoopStore.loop` ein `/loop`-Pass, der zwischen zwei
+ * Durchgaengen auf seinen Zeitgeber wartet -
+ * generiert nichts, `generating` sieht ihn
+ * also nicht, aber er feuert die naechste
+ * Cloud-Anfrage trotzdem.
+ *
+ * BLOCKER Netzabbruch: `offline` rief bis heute `stopAllBackgroundWork()`
+ * selbst, mit dem KLEBRIGEN `stopRun`-Merker. Ein zwei Sekunden langer
+ * WLAN-Wackler, ein VPN-Wechsel, ein Sleep/Wake toetete damit unwiderruflich
+ * jede Agentenarbeit in jeder Konversation - genau die Faelle, fuer die
+ * `providers/retry.ts` Netzfehler bewusst wie 429/503 wiederholt. `offline`
+ * stoppt jetzt nichts mehr: es zeigt nur einen sichtbaren Hinweis
+ * (`backgroundShutdownStore`), dass die Verbindung weg ist und laufende
+ * Arbeit wartet bzw. beim naechsten Versuch wiederholt. Ein Wackler kostet
+ * damit hoechstens eine verzoegerte Antwort, nie den ganzen Lauf.
*/
import { useAgentTaskStore } from '../stores/agentTaskStore'
+import { useGenerationStore } from '../stores/generationStore'
+import { useAgentLoopStore } from '../stores/agentLoopStore'
import { stopRun } from './run-stop'
import { isTauri } from '../api/backend'
+import { useBackgroundShutdownStore } from '../stores/backgroundShutdownStore'
/**
- * Bricht jede laufende Hintergrundaufgabe in jeder Konversation ab und setzt
- * den Stop-Merker fuer jede von ihnen - unabhaengig davon, welche
- * Konversation gerade sichtbar ist. Kein Ausloeser hier kennt "die aktive
- * Konversation": das Abmelden, das Schliessen und der Netzabbruch treffen
- * die ganze Sitzung, nicht nur den gerade offenen Tab.
+ * Bricht jeden laufenden Lauf in jeder Konversation ab und setzt den
+ * Stop-Merker fuer jede von ihnen - unabhaengig davon, welche Konversation
+ * gerade sichtbar ist und ueber welchen der drei Sendewege der Lauf lief.
+ * Kein Ausloeser hier kennt "die aktive Konversation": das Abmelden, das
+ * Schliessen und das App-Beenden treffen die ganze Sitzung, nicht nur den
+ * gerade offenen Tab.
*/
export function stopAllBackgroundWork(): void {
- const byConv = useAgentTaskStore.getState().byConv
- for (const convId of Object.keys(byConv)) {
+ const ids = new Set<string>()
+ for (const convId of Object.keys(useAgentTaskStore.getState().byConv)) ids.add(convId)
+ for (const convId of Object.keys(useGenerationStore.getState().generating)) ids.add(convId)
+ const loopConvId = useAgentLoopStore.getState().loop?.conversationId
+ if (loopConvId) ids.add(loopConvId)
+
+ for (const convId of ids) {
useAgentTaskStore.getState().cancelAll(convId)
+ useGenerationStore.getState().abortConversation(convId)
stopRun(convId)
}
+ // Der Zeitgeber eines wartenden /loop-Passes haengt nicht an einer
+ // Konversation im Speicher, sondern am globalen Store (bis B2 Commit 3
+ // dieser Zweigarbeit ihn je Konversation fuehrt) - darum eigens geraeumt,
+ // nicht durch die Schleife oben erfasst.
+ if (loopConvId) useAgentLoopStore.getState().clear()
+}
+
+/**
+ * Wie lange nach dem Verschwinden ins Tray gewartet wird, bevor
+ * Hintergrundarbeit wirklich beendet wird. Dieselbe Frist und derselbe
+ * Beweggrund wie `HIDE_OFFLOAD_GRACE` in main.rs, das nach dem gleichen X-
+ * Klick die lokalen Modelle aus dem VRAM raeumt: ein Fehlklick plus sofortiges
+ * Wiederoeffnen kostet nichts, ein Fenster, das der Nutzer fuer weg haelt,
+ * bezahlt keine unsichtbare Rechenzeit.
+ */
+const HIDDEN_STOP_GRACE_MS = 30_000
+
+/**
+ * Zaehlt jedes `app:hidden` hoch. Ein Verstecken-Zeigen-Verstecken laesst den
+ * AELTEREN Zeitgeber stehen, und der darf NICHT die Arbeit der neueren
+ * Sitzung beenden - dieselbe Generationslogik wie `hide_gen`/
+ * `should_offload_after_hide` in main.rs, nur diesseits der Grenze.
+ */
+let hideGeneration = 0
+
+/**
+ * Nach der Karenzzeit: noch immer versteckt? Dann wirklich stoppen und den
+ * Nutzer beim naechsten Wiedersehen des Fensters darueber informieren. Ein
+ * Wiederoeffnen INNERHALB der Frist - erkannt an einer neueren Generation
+ * ODER, als zweite Sicherung, direkt an der Fenstersichtbarkeit - sagt nichts
+ * und stoppt nichts, genau wie beim VRAM-Offload nebenan.
+ */
+async function scheduleHiddenStop(): Promise<void> {
+ hideGeneration += 1
+ const generation = hideGeneration
+ await new Promise((resolve) => setTimeout(resolve, HIDDEN_STOP_GRACE_MS))
+ if (generation !== hideGeneration) return // ein neueres Verstecken (oder ein Reset fuer Tests) besitzt die Entscheidung jetzt
+
+ if (isTauri()) {
+ try {
+ const { getCurrentWindow } = await import('@tauri-apps/api/window')
+ if (await getCurrentWindow().isVisible()) return
+ } catch {
+ // Sichtbarkeit nicht zu ermitteln: im Zweifel stoppen, dieselbe
+ // Abwaegung wie das main.rs-Pendant (ein zaehlender Prozess ohne
+ // Beweis, dass der Nutzer zurueck ist, wird beendet).
+ }
+ }
+
+ stopAllBackgroundWork()
+ useBackgroundShutdownStore.getState().setNotice({ kind: 'hidden-stopped', at: Date.now() })
}
/** Die von `installBackgroundShutdown` gesetzten Horcher, fuer Idempotenz. */
let installed: (() => void) | null = null
/**
- * Haengt `stopAllBackgroundWork` an die drei Ausloeser, die kein Knopf im UI
- * sind: App beenden, Fenster schliessen, Netzabbruch (Abmelden ruft die
- * Funktion direkt aus `signOutAccount`, siehe hooks/useCloudAuth.ts).
+ * Haengt `stopAllBackgroundWork` an die Ausloeser, die kein Knopf im UI
+ * sind: App beenden, Fenster schliessen (mit Karenzzeit), Netzabbruch (nur
+ * noch als Hinweis, siehe Kopf der Datei; Abmelden ruft die Funktion direkt
+ * aus `signOutAccount`, siehe hooks/useCloudAuth.ts).
*
* ── App beenden ─────────────────────────────────────────────────────────
* `pagehide` + `beforeunload`, exakt das Paar aus api/mcp/shutdown.ts und
@@ -50,29 +136,24 @@ let installed: (() => void) | null = null
* kostet nichts extra, weil `stopAllBackgroundWork` mehrfach aufzurufen
* harmlos ist (cancelAll auf einer bereits leeren/abgebrochenen Liste tut
* nichts). Im Browser-Dev-Build ist das dasselbe Ereignis wie ein
- * Tab-Schliessen - genau der in Punkt 1 verlangte Rueckfall.
+ * Tab-Schliessen. Beide Ausloeser sind der Prozess, der wirklich verschwindet
+ * - keine Karenzzeit, es gibt niemanden mehr, der einen Hinweis noch saehe.
*
* ── Fenster schliessen ──────────────────────────────────────────────────
- * BEWUSST NICHT an Tauris `onCloseRequested` gehaengt, obwohl der
- * Nachbesserungs-Auftrag genau das nennt. Grund: in main.rs (Zeile ~760)
- * ruft der Rust-Handler bei jedem X-Klick `api.prevent_close()` und
- * versteckt das Fenster in den Tray, statt die App zu beenden - das X
- * schliesst hier nichts, es minimiert. Ein `onCloseRequested`-Horcher in
- * diesem Modul wuerde bei JEDEM Klick auf das X feuern, also auch beim
- * blossen Wegklicken in den Tray, und braeche damit genau die
- * Hintergrundagenten ab, die der Sinn des Tray-Verhaltens sind ("die App
- * arbeitet weiter, waehrend das Fenster weg ist"). main.rs sendet fuer
- * exakt diesen Moment bereits ein eigenes Ereignis an die Oberflaeche,
- * `app:hidden` - useVoice.ts hoert bereits darauf, um Mikro und Wiedergabe
- * zu stoppen, aus derselben Ueberlegung ("die Webview lebt weiter, obwohl
- * der Nutzer glaubt, das Fenster sei weg"). Dieses Modul hoert auf dasselbe
- * Ereignis, statt ein zweites fuer denselben Augenblick zu registrieren.
+ * `app:hidden` IST `onCloseRequested`: main.rs sendet das Ereignis an GENAU
+ * EINER Stelle, im `CloseRequested`-Arm, unmittelbar bevor es das Fenster in
+ * den Tray versteckt (`w.hide()`). Ein eigener `onCloseRequested`-Horcher
+ * hier waere also derselbe Klick ein zweites Mal beobachtet, nicht ein
+ * anderer Moment. Die App lebt im Tray absichtlich weiter (Tray-Menue,
+ * schnelles Show), aber nicht fuer unsichtbare bezahlte Rechenzeit: dieselbe
+ * main.rs-Stelle raeumt seit dem 30.08. aus demselben Grund die lokalen
+ * Modelle aus dem VRAM, mit derselben Karenzzeit gegen den Fehlklick. Diese
+ * Datei zieht mit `scheduleHiddenStop` nach, statt ohne Frist abzubrechen.
*
* ── Netzabbruch ─────────────────────────────────────────────────────────
- * `window.addEventListener('offline', ...)` - ein abgebrochener
- * Hintergrundagent, der sowieso nicht mehr senden kann, feuert wenigstens
- * das Panel und den Merker korrekt, statt still auf eine Verbindung zu
- * warten, die nicht wiederkommt, ohne dass der Nutzer es sehen kann.
+ * `window.addEventListener('offline'/'online', ...)` - stoppt nichts mehr
+ * (siehe Kopf der Datei), zeigt nur den Hinweis und nimmt ihn bei
+ * Wiederverbindung zurueck.
*
* Idempotent wie installMcpShutdown: mehrfacher Aufruf installiert nur einen
* Satz Horcher.
@@ -84,27 +165,39 @@ export function installBackgroundShutdown(): () => void {
const onGone = () => stopAllBackgroundWork()
window.addEventListener('pagehide', onGone)
window.addEventListener('beforeunload', onGone)
- window.addEventListener('offline', onGone)
+
+ const onOffline = () => useBackgroundShutdownStore.getState().setNotice({ kind: 'offline' })
+ const onOnline = () => {
+ const notice = useBackgroundShutdownStore.getState().notice
+ if (notice?.kind === 'offline') useBackgroundShutdownStore.getState().dismiss()
+ }
+ window.addEventListener('offline', onOffline)
+ window.addEventListener('online', onOnline)
+
+ const onHidden = () => { void scheduleHiddenStop() }
let unlistenHidden: (() => void) | undefined
if (isTauri()) {
void (async () => {
const { listen } = await import('@tauri-apps/api/event')
- unlistenHidden = await listen('app:hidden', onGone)
+ unlistenHidden = await listen('app:hidden', onHidden)
})()
}
installed = () => {
window.removeEventListener('pagehide', onGone)
window.removeEventListener('beforeunload', onGone)
- window.removeEventListener('offline', onGone)
+ window.removeEventListener('offline', onOffline)
+ window.removeEventListener('online', onOnline)
unlistenHidden?.()
installed = null
}
return installed
}
-/** Test-only: die Horcher sind Modulzustand fuer die ganze Sitzung, mit Absicht. */
+/** Test-only: die Horcher und die Generation sind Modulzustand fuer die
+ * ganze Sitzung, mit Absicht. */
export function __resetBackgroundShutdownForTests(): void {
installed?.()
+ hideGeneration += 1 // entwertet jeden noch laufenden scheduleHiddenStop-Zeitgeber
}
diff --git a/src/stores/backgroundShutdownStore.ts b/src/stores/backgroundShutdownStore.ts
new file mode 100644
index 00000000..21b10894
--- /dev/null
+++ b/src/stores/backgroundShutdownStore.ts
@@ -0,0 +1,39 @@
+import { create } from 'zustand'
+
+/**
+ * The one visible line for what `lib/background-shutdown.ts` did without the
+ * user watching. Runtime only, never persisted: a notice about something
+ * that happened last session is not a notice, it is a stale claim.
+ *
+ * ── B1 Runde 2, Punkt 1 und 4 ────────────────────────────────────────────
+ *
+ * Two DIFFERENT things this module needs to say, never conflated into one:
+ *
+ * `'offline'` the network dropped. Nothing was stopped — retry.ts already
+ * retries a dropped connection on purpose, so a two-second
+ * WLAN wobble must not read as "your work is gone". This
+ * notice says the connection is down and running work is
+ * waiting or retrying, and clears itself the moment `online`
+ * fires again.
+ *
+ * `'hidden-stopped'` the window was closed (to the tray) and, after the
+ * grace period a reopen would have cancelled, background
+ * agent work was actually stopped — the same trade the local
+ * model offload in main.rs already makes for the same click.
+ * This one does NOT self-clear: the user has to see it once,
+ * because credits stopped accruing and a new message is what
+ * starts the next one.
+ */
+export type BackgroundNotice = { kind: 'offline' } | { kind: 'hidden-stopped'; at: number }
+
+interface BackgroundShutdownState {
+ notice: BackgroundNotice | null
+ setNotice: (notice: BackgroundNotice | null) => void
+ dismiss: () => void
+}
+
+export const useBackgroundShutdownStore = create<BackgroundShutdownState>((set) => ({
+ notice: null,
+ setNotice: (notice) => set({ notice }),
+ dismiss: () => set({ notice: null }),
+}))