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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
tech(M1/AS-08/T-53): eine Wahrheit fuer "laeuft etwas", und Aufraeumen am Ende
David9139ef6225ec
diff --git a/src/api/mcp/__tests__/mcp-trennt-beim-app-ende.test.ts b/src/api/mcp/__tests__/mcp-trennt-beim-app-ende.test.tsnew file mode 100644index 00000000..4b267224--- /dev/null+++ b/src/api/mcp/__tests__/mcp-trennt-beim-app-ende.test.ts@@ -0,0 +1,303 @@+/**+ * T-53, zweite Hälfte — nichts trennte die externen MCP-Server, wenn die App+ * (oder auch nur ihre Seite) verschwand. Die Kindprozesse blieben.+ *+ * Die Grenze zu Tauri ist hier dieselbe wie in `external-client.test.ts`:+ * `@tauri-apps/plugin-shell` braucht die Tauri-IPC und einen Rust-Host, beides+ * gibt es unter vitest nicht. Der Ersatz spiegelt die echte API genau —+ * `Command` trägt stdout/stderr/close, nur das `Child` aus `spawn()` hat+ * `write()` und `kill()`. Alles diesseits dieser Grenze ist der echte Code.+ *+ * `window` ist hier Nodes eigener `EventTarget`, keine nachgebaute+ * Ereignisschleife: der Aufräumpfad hängt an `pagehide`/`beforeunload`, und+ * genau diese Registrierung soll geprüft werden.+ *+ * Lauf: npx vitest run src/api/mcp/__tests__/mcp-trennt-beim-app-ende.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import {+ MCPExternalClient,+ disconnectAllExternalServers,+ liveExternalServerCount,+} from '../external-client'+import { installMcpShutdown, sweepMcpServers, __resetMcpShutdownForTests } from '../shutdown'+import type { MCPServerConfig } from '../types'++class Emitter {+ private handlers: Record<string, ((data: string) => void)[]> = {}+ on(event: string, fn: (data: string) => void) {+ ;(this.handlers[event] ||= []).push(fn)+ }+ emit(event: string, data = '') {+ for (const fn of this.handlers[event] || []) fn(data)+ }+}++interface FakeRequest {+ jsonrpc?: string+ id?: number+ method?: string+}++const spawned: FakeServer[] = []++class FakeChild {+ readonly server: FakeServer+ constructor(server: FakeServer) {+ this.server = server+ }+ async write(data: string) {+ this.server.receive(data)+ }+ async kill() {+ if (this.server.killThrows) throw new Error('kill refused')+ this.server.killed = true+ // The real plugin's close event follows the kill.+ this.server.emit('close')+ }+}++class FakeServer extends Emitter {+ stdout = new Emitter()+ stderr = new Emitter()+ killed = false+ killThrows = false+ /** Set `stdin` so any code reading it fails the way the real API would. */+ get stdin(): never {+ throw new Error('the real Command has no stdin — write() lives on the Child')+ }+ constructor() {+ super()+ spawned.push(this)+ }+ async spawn() {+ return new FakeChild(this)+ }+ receive(data: string) {+ for (const line of data.split('\n')) {+ if (!line.trim()) continue+ const out = respond(JSON.parse(line) as FakeRequest)+ if (out !== null) this.stdout.emit('data', out + '\n')+ }+ }+}++vi.mock('@tauri-apps/plugin-shell', () => ({+ Command: {+ create: (_cmd: string, _args?: string[], _opts?: unknown) => new FakeServer(),+ },+}))++/** A well-behaved MCP server: handshake plus one tool. */+function respond(req: FakeRequest): string | null {+ if (req.method === 'initialize') {+ return JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { protocolVersion: '2024-11-05' } })+ }+ if (req.method === 'tools/list') {+ return JSON.stringify({+ jsonrpc: '2.0',+ id: req.id,+ result: {+ tools: [{+ name: 'get_forecast',+ description: 'forecast',+ inputSchema: { type: 'object', properties: {} },+ }],+ },+ })+ }+ return null+}++const configFor = (id: string): MCPServerConfig => ({+ id,+ name: `server-${id}`,+ command: 'npx',+ args: ['-y', `${id}-mcp`],+ enabled: true,+})++async function connectOne(id: string) {+ const client = new MCPExternalClient(configFor(id))+ const tools = await client.connect()+ expect(tools).toHaveLength(1)+ return client+}++beforeEach(async () => {+ spawned.length = 0+ __resetMcpShutdownForTests()+ // The live set is module state shared with the rest of the suite; start+ // every test from an empty one.+ await disconnectAllExternalServers()+ spawned.length = 0+})++afterEach(async () => {+ await disconnectAllExternalServers()+ __resetMcpShutdownForTests()+ Reflect.deleteProperty(globalThis, 'window')+})++describe('die App weiß, welche Serverprozesse ihr gehören', () => {+ it('ein verbundener Server steht in der Liste', async () => {+ expect(liveExternalServerCount()).toBe(0)+ await connectOne('a')+ expect(liveExternalServerCount()).toBe(1)+ })++ it('GEGENPROBE: ein Server, der von selbst stirbt, steht nicht mehr drin', async () => {+ await connectOne('a')+ expect(liveExternalServerCount()).toBe(1)+ spawned[0].emit('close')+ expect(liveExternalServerCount()).toBe(0)+ })++ it('GEGENPROBE: ein einzeln getrennter Server ebenso', async () => {+ const client = await connectOne('a')+ await client.disconnect()+ expect(liveExternalServerCount()).toBe(0)+ })+})++describe('disconnectAllExternalServers', () => {+ it('nimmt jeden laufenden Server mit — nicht nur den ersten', async () => {+ await connectOne('a')+ await connectOne('b')+ await connectOne('c')+ expect(liveExternalServerCount()).toBe(3)++ const count = await disconnectAllExternalServers()++ expect(count).toBe(3)+ expect(spawned.map((s) => s.killed)).toEqual([true, true, true])+ expect(liveExternalServerCount()).toBe(0)+ })++ it('ein Server, dessen kill scheitert, hält die anderen nicht auf und bleibt nicht liegen', async () => {+ // Was hier bewiesen wird, ist die Schleife und die Buchführung, NICHT das+ // try/catch im Sweep: `disconnect()` schluckt seinen eigenen kill-Fehler+ // ("Process may already be dead"), der Sweep sieht ihn also gar nicht.+ // Das steht so auch an der Fundstelle; hier steht es, damit dieser Test+ // nicht mehr zu behaupten scheint, als er misst.+ await connectOne('a')+ await connectOne('b')+ spawned[0].killThrows = true++ await expect(disconnectAllExternalServers()).resolves.toBe(2)++ expect(spawned[0].killed).toBe(false)+ expect(spawned[1].killed).toBe(true)+ // Entscheidend: der widerspenstige Server ist trotzdem aus der Liste, sonst+ // liefe jeder weitere Sweep endlos auf denselben Prozess.+ expect(liveExternalServerCount()).toBe(0)+ })++ it('GEGENPROBE: ein zweiter Durchlauf tötet nichts noch einmal', async () => {+ await connectOne('a')+ await disconnectAllExternalServers()+ spawned[0].killed = false++ await expect(disconnectAllExternalServers()).resolves.toBe(0)++ expect(spawned[0].killed).toBe(false)+ })+})++describe('der Aufräumpfad hängt am Verschwinden der Seite', () => {+ /** Nodes eigener EventTarget als `window` — echte Listener-Semantik. */+ function installFakeWindow(): EventTarget {+ const target = new EventTarget()+ Object.defineProperty(globalThis, 'window', {+ value: target,+ writable: true,+ configurable: true,+ })+ return target+ }++ it('pagehide trennt die laufenden Server', async () => {+ const target = installFakeWindow()+ installMcpShutdown()+ await connectOne('a')++ target.dispatchEvent(new Event('pagehide'))+ // Der Handler kann nicht awaiten; der Kill ist eine Mikrotask weiter.+ await Promise.resolve()+ await Promise.resolve()++ expect(spawned[0].killed).toBe(true)+ expect(liveExternalServerCount()).toBe(0)+ })++ it('beforeunload ist derselbe Pfad, nicht ein zweiter', async () => {+ const target = installFakeWindow()+ installMcpShutdown()+ await connectOne('a')++ target.dispatchEvent(new Event('beforeunload'))+ await Promise.resolve()+ await Promise.resolve()++ expect(spawned[0].killed).toBe(true)+ })++ it('GEGENPROBE: zweimal verdrahten hängt keinen zweiten Listener an', async () => {+ const target = installFakeWindow()+ installMcpShutdown()+ installMcpShutdown()+ await connectOne('a')++ let sweeps = 0+ target.addEventListener('pagehide', () => sweeps++)+ target.dispatchEvent(new Event('pagehide'))++ expect(sweeps).toBe(1)+ await Promise.resolve()+ await Promise.resolve()+ expect(spawned[0].killed).toBe(true)+ })++ it('GEGENPROBE: ohne window fällt die Verdrahtung folgenlos aus', () => {+ Reflect.deleteProperty(globalThis, 'window')+ expect(() => installMcpShutdown()()).not.toThrow()+ })++ it('ein Durchlauf ohne Server meldet ehrlich null', async () => {+ await expect(sweepMcpServers()).resolves.toBe(0)+ })+})++describe('die bewusste Entscheidung ist im Code festgehalten', () => {+ const SRC = resolve(__dirname, '..', '..', '..')+ const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')++ it('main.tsx verdrahtet den Aufräumpfad wirklich', () => {+ const main = read('main.tsx')+ expect(main).toContain("from './api/mcp/shutdown'")+ expect(main).toContain('installMcpShutdown()')+ })++ it('NICHT an onCloseRequested — das X versteckt in die Tray, es beendet nicht', () => {+ // main.rs:549 ruft api.prevent_close() und versteckt das Fenster. Ein+ // Teardown an dieser Stelle würde jeden verbundenen Server killen, sobald+ // der Nutzer das Fenster schließt und die App weiterlaufen soll. Wer das+ // später "nachrüstet", soll hier auflaufen.+ const shutdown = read('api', 'mcp', 'shutdown.ts')+ const codeOnly = shutdown+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/(^|[^:])\/\/.*$/gm, '$1')+ expect(codeOnly).not.toContain('onCloseRequested')+ expect(codeOnly).not.toContain('getCurrentWindow')+ })++ it('ein Aufräumpfad, kein Pfad je Modus', () => {+ const shutdown = read('api', 'mcp', 'shutdown.ts')+ // Beide Trigger münden in dieselbe Funktion; es gibt genau einen Aufruf+ // der eigentlichen Implementierung.+ const calls = shutdown.match(/disconnectAllExternalServers\(\)/g) ?? []+ expect(calls).toHaveLength(1)+ })+})diff --git a/src/api/mcp/external-client.ts b/src/api/mcp/external-client.tsindex 18b45f54..482c16c6 100644--- a/src/api/mcp/external-client.ts+++ b/src/api/mcp/external-client.ts@@ -108,6 +108,55 @@ const EMPTY_INPUT_SCHEMA: MCPToolDefinition['inputSchema'] = {required: [],}+/**+ * Every client that currently owns a live server process (T-53).+ *+ * The only other place a connected client was ever held is a `Map` private to+ * `components/settings/MCPServerSettings.tsx:9`. That map dies with the module+ * — a webview reload empties it — and nothing outside that component could+ * ever reach it, so "disconnect everything" was not expressible anywhere in+ * the app. The set lives HERE, next to the spawn, on purpose: a client that+ * starts a process registers itself in the same method that starts it, so a+ * future second caller of `connect()` cannot forget to enrol. That is the+ * difference between one path and two.+ *+ * Membership is exactly "has a child process": added when `connect()` has a+ * spawned child, removed by `disconnect()`, by the process's own `close`+ * event, and on a failed handshake.+ */+const liveClients = new Set<MCPExternalClient>()++/** How many external MCP server processes this app currently owns. */+export function liveExternalServerCount(): number {+ return liveClients.size+}++/**+ * Disconnect every connected external MCP server. The ONE cleanup path —+ * `api/mcp/shutdown.ts` decides when it runs, this decides what it does.+ *+ * Resolves to the number of clients it took down. Never rejects: one server+ * that will not die must not stop the next one, and the caller is usually a+ * page-unload handler where a rejection is an unhandled one.+ *+ * The catch below is a guarantee, not a currently reachable branch —+ * `disconnect()` swallows its own `kill()` failure ("Process may already be+ * dead") and today has no other way to throw. It is here so that the contract+ * survives a future `disconnect()` that does, and no test claims to exercise+ * it.+ */+export async function disconnectAllExternalServers(): Promise<number> {+ const clients = [...liveClients]+ await Promise.all(clients.map(async (c) => {+ try {+ await c.disconnect()+ } catch (err) {+ log.warn('[MCP] a server did not disconnect cleanly', { err: String(err) })+ }+ }))+ return clients.length+}+export class MCPExternalClient {/*** The Child that spawn() hands back — owns stdin and kill(). The Command@@ -188,6 +237,8 @@ export class MCPExternalClient {const wasConnected = this.connectedthis.connected = falsethis.child = null+ // The process is gone: nothing left for a shutdown sweep to kill.+ liveClients.delete(this)this.rejectAllPending('Server process exited')// A crash, an OOM kill, a server that quits on a bad config: the// tools it registered are dead weight from this moment on, and the@@ -208,6 +259,11 @@ export class MCPExternalClient {}if (!this.child) throw spawnErrorthis.connected = true+ // Enrolled the moment a process exists, not once the handshake is+ // through: a server that spawns and then hangs in `initialize` is+ // exactly the one a shutdown has to be able to kill. The catch below+ // removes it again if the handshake fails outright.+ liveClients.add(this)// Initialize the MCP connectionawait this.sendRequest('initialize', {@@ -248,6 +304,7 @@ export class MCPExternalClient {try { await this.child.kill() } catch { /* already gone */ }this.child = null}+ liveClients.delete(this)throw new Error(`Failed to connect to MCP server "${this.config.name}": ${err instanceof Error ? err.message : String(err)}`)}}@@ -275,6 +332,9 @@ export class MCPExternalClient {async disconnect() {this.closingOnPurpose = truethis.connected = false+ // Out of the shutdown sweep first: a disconnect that is itself running+ // inside the sweep must not be reachable a second time.+ liveClients.delete(this)this.rejectAllPending('Disconnecting')if (this.child) {try {diff --git a/src/api/mcp/shutdown.ts b/src/api/mcp/shutdown.tsnew file mode 100644index 00000000..5335ad41--- /dev/null+++ b/src/api/mcp/shutdown.ts@@ -0,0 +1,111 @@+/**+ * T-53, second half — nothing disconnected the external MCP servers when the+ * app went away, so their child processes were left behind.+ *+ * ── What already cleans up, and what does not ────────────────────────────+ *+ * `AppState::shutdown_subprocesses()` (`src-tauri/src/state.rs:462`) kills the+ * children RUST spawned and tracks in AppState: Ollama, ComfyUI, the bundled+ * llama-server and embeddings server, the MLX video subprocess and image+ * sidecar, the LoRA trainer, the installer child trees, whisper. External MCP+ * servers are none of those — they are spawned from the frontend through+ * `@tauri-apps/plugin-shell`, land in the PLUGIN's child map, and never appear+ * in AppState. So this file does not duplicate that function; the two have an+ * empty intersection.+ *+ * The overlap that does exist is with the shell plugin itself:+ * `tauri-plugin-shell` 2.3.5 sweeps its own child map on `RunEvent::Exit`+ * (`src/lib.rs:132-143`) and kills every child. That covers the packaged app's+ * real quit paths — tray Quit, `exit_app`, Cmd+Q — and it is not double work,+ * because the JS `kill()` we issue below goes through the plugin's own+ * `kill` command, which REMOVES the pid from that same map before killing it+ * (`src/commands.rs:300-309`). Whoever gets there first takes the entry; the+ * other finds nothing. One registry, one kill.+ *+ * ── Why the trigger is page unload and NOT onCloseRequested ──────────────+ *+ * The obvious Tauri hook is the wrong one here. In this app the window's X+ * does not quit: `main.rs:549` calls `api.prevent_close()` and hides to the+ * tray, deliberately, and the window comes back with Show. Hanging the MCP+ * teardown off `onCloseRequested` would kill every connected server every time+ * the user pressed X and expected the app to keep standing.+ *+ * What no layer covers is the WEBVIEW going away without the process going+ * away: a `tauri dev` HMR full reload, a `location.reload()`, the recovery+ * path in `main.tsx`. The plugin's Exit sweep does not fire, and the JS side+ * loses the only handle to those processes (the client map is module state),+ * so they stay resident with nobody able to reach them for the rest of the+ * app's life. That is the orphan this file exists for.+ *+ * And it is ONE path, not one per mode. `pagehide` and `beforeunload` are two+ * TRIGGERS for the same single implementation+ * (`disconnectAllExternalServers`), registered identically whether the app is+ * running packaged or under `npm run dev`; both fire in a browser and in the+ * WKWebView/WebView2 the packaged app uses. Under plain `npm run dev` there is+ * no Tauri IPC, so no MCP server can have been spawned at all and the sweep+ * finds an empty set — the same code doing nothing, rather than a second code+ * path that only one mode has.+ *+ * ── What this cannot promise ─────────────────────────────────────────────+ *+ * `child.kill()` is an async IPC call. An unload handler cannot await, so the+ * request is posted and the page goes away; the Rust side normally receives it+ * because the post is synchronous, but nothing here can prove the process was+ * reaped. And the plugin's kill is a kill of the DIRECT child only — for+ * `npx -y some-mcp-server` (or `npx.cmd` on Windows) that is the launcher, and+ * the node process it forked is not in any tree walk. Closing that needs a+ * `kill_tree` on the Rust side, which is out of scope here.+ */+import { disconnectAllExternalServers } from './external-client'++/**+ * Set while a sweep is in flight, so the two triggers cannot double-fire.+ * Cleared when the sweep settles rather than latched for good: on a real+ * unload nothing gets that far, but a page that survives (a cancelled+ * navigation, a bfcache restore) must still be sweepable the next time.+ */+let sweeping = false+/** The listeners this module installed, so `installMcpShutdown` stays idempotent. */+let installed: (() => void) | null = null++/**+ * Run the teardown once. Exported for the test, which is the only place that+ * can drive it deterministically — an unload handler cannot be awaited.+ */+export function sweepMcpServers(): Promise<number> {+ if (sweeping) return Promise.resolve(0)+ sweeping = true+ return disconnectAllExternalServers().finally(() => { sweeping = false })+}++/**+ * Wire the teardown to the page going away. Idempotent: calling it twice+ * (React StrictMode, a re-entrant boot) installs one set of listeners.+ * Returns an uninstaller, which the app does not use — the hook is meant to+ * live for the whole session.+ */+export function installMcpShutdown(): () => void {+ if (installed) return installed+ if (typeof window === 'undefined') return () => {}++ const onGone = () => { void sweepMcpServers() }+ // Two triggers, one implementation. `pagehide` is the one that actually+ // fires on a reload in WebKit/WebView2; `beforeunload` is kept because it is+ // the earlier of the two and costs nothing when both arrive — `sweeping`+ // makes the second call a no-op.+ window.addEventListener('pagehide', onGone)+ window.addEventListener('beforeunload', onGone)++ installed = () => {+ window.removeEventListener('pagehide', onGone)+ window.removeEventListener('beforeunload', onGone)+ installed = null+ }+ return installed+}++/** Test-only: the latch and the listeners are process-lifetime state by design. */+export function __resetMcpShutdownForTests(): void {+ installed?.()+ sweeping = false+}diff --git a/src/lib/__tests__/eine-wahrheit-fuer-laeuft-etwas.test.ts b/src/lib/__tests__/eine-wahrheit-fuer-laeuft-etwas.test.tsnew file mode 100644index 00000000..48b4f944--- /dev/null+++ b/src/lib/__tests__/eine-wahrheit-fuer-laeuft-etwas.test.ts@@ -0,0 +1,168 @@+/**+ * AS-08 — "läuft gerade etwas?" hat zwei unabhängige Quellen.+ *+ * Zwei Dinge werden hier festgenagelt, und beide sind das Muster M1+ * (zwei Pfade, einer gepflegt):+ *+ * 1. Die Zustandsunion bildet ab, was der Lauf wirklich tut. Vorher war sie+ * `'idle' | 'running' | 'error'`, und `awaiting_approval`, `applying`,+ * `cancelling` — drei Zustände, in denen die App wirklich steht — fielen+ * an jeder Verzweigung in ein stilles `else`.+ * 2. Die Frage wird an EINER Stelle beantwortet. `run-idle.ts` versöhnt+ * `generationStore.generating` und `codexStore.threads[].status`; niemand+ * sonst darf die eine Hälfte für die Wahrheit halten.+ *+ * Lauf: npx vitest run src/lib/__tests__/eine-wahrheit-fuer-laeuft-etwas.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'++import {+ anyRunActive,+ runsActive,+ runStatusOf,+ isRunActive,+ whenRunsIdle,+} from '../run-idle'+import {+ CODEX_THREAD_STATUSES,+ isActiveCodexStatus,+ type CodexThreadStatus,+} from '../../types/codex'+import { beginRun, stopRun, __resetRunStopsForTests } from '../run-stop'+import { useGenerationStore } from '../../stores/generationStore'+import { useCodexStore } from '../../stores/codexStore'++beforeEach(() => {+ useGenerationStore.setState({ generating: {}, aborters: {} })+ useCodexStore.setState({ threads: {} })+ __resetRunStopsForTests()+})++describe('die Zustandsunion bildet den echten Lauf ab', () => {+ it('kennt die drei Zustände, die die App hat und der Typ nicht hatte', () => {+ // Nicht geraten: jeder dieser drei hat eine Fundstelle im Produktivcode,+ // sie steht im Kopf von types/codex.ts.+ expect(CODEX_THREAD_STATUSES).toContain('awaiting_approval')+ expect(CODEX_THREAD_STATUSES).toContain('applying')+ expect(CODEX_THREAD_STATUSES).toContain('cancelling')+ })++ it('jeder Zustand hat ein Urteil — kein stilles else', () => {+ // Die Urteilstabelle ist die Quelle der Liste. Ein siebter Zustand ohne+ // Eintrag ist ein Compilerfehler, kein `false`.+ for (const status of CODEX_THREAD_STATUSES) {+ expect(typeof isActiveCodexStatus(status)).toBe('boolean')+ }+ expect(CODEX_THREAD_STATUSES).toHaveLength(6)+ })++ it('warten auf Freigabe, Schreiben auf Platte und Abbrechen zählen als aktiv', () => {+ expect(isActiveCodexStatus('awaiting_approval')).toBe(true)+ expect(isActiveCodexStatus('applying')).toBe(true)+ expect(isActiveCodexStatus('cancelling')).toBe(true)+ })++ it('GEGENPROBE: idle und error sind es nicht', () => {+ expect(isActiveCodexStatus('idle')).toBe(false)+ expect(isActiveCodexStatus('error')).toBe(false)+ })+})++describe('anyRunActive über die volle Union', () => {+ const active: CodexThreadStatus[] = ['running', 'awaiting_approval', 'applying', 'cancelling']++ for (const status of active) {+ it(`ein Thread in '${status}' blockt`, () => {+ expect(anyRunActive({}, { 'conv-1': { status } })).toBe(true)+ })+ }++ it('GEGENPROBE: idle und error blocken nicht, ein generierender Chat schon', () => {+ expect(anyRunActive({}, { a: { status: 'idle' }, b: { status: 'error' } })).toBe(false)+ expect(anyRunActive({ 'conv-1': true }, {})).toBe(true)+ })+})++describe('eine Stelle beantwortet die Frage — für eine Konversation', () => {+ it('der Freigabedialog hält den Lauf am Leben, statt ihn als beendet zu melden', () => {+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'awaiting_approval')+ // generationStore weiß davon nichts — genau die halbe Wahrheit, die+ // CodexModeDropdown und PlanApprovalBar heute allein lesen.+ expect(useGenerationStore.getState().generating['conv-c']).toBeUndefined()+ expect(runStatusOf('conv-c')).toBe('awaiting_approval')+ expect(isRunActive('conv-c')).toBe(true)+ expect(runsActive()).toBe(true)+ })++ it('ein Chat ohne Coding-Thread wird über die andere Quelle beantwortet', () => {+ useGenerationStore.getState().setGenerating('conv-chat', true)+ expect(useCodexStore.getState().threads['conv-chat']).toBeUndefined()+ expect(runStatusOf('conv-chat')).toBe('running')+ expect(isRunActive('conv-chat')).toBe(true)+ })++ it('Stop gedrückt, Lauf läuft noch aus: das heißt cancelling, nicht idle', () => {+ // Der Zustand, in dem die beiden Quellen sich heute widersprechen:+ // stopCodex löscht generating[convId] sofort, der Thread steht bis zum+ // finally des abbrechenden Laufs weiter auf 'running'.+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'running')+ useGenerationStore.getState().setGenerating('conv-c', true)+ beginRun('conv-c')++ stopRun('conv-c')+ useGenerationStore.getState().abortConversation('conv-c')++ expect(useGenerationStore.getState().generating['conv-c']).toBeUndefined()+ expect(runStatusOf('conv-c')).toBe('cancelling')+ expect(isRunActive('conv-c')).toBe(true)+ })++ it('GEGENPROBE: der klebrige Stop-Merker allein macht keinen Lauf', () => {+ // run-stop bleibt bis zur nächsten Anweisung gesetzt. Ohne aktiven Lauf+ // darf daraus kein 'cancelling' werden, sonst stünde die Frage danach+ // für immer auf "läuft".+ stopRun('conv-c')+ expect(runStatusOf('conv-c')).toBe('idle')+ expect(isRunActive('conv-c')).toBe(false)+ expect(runsActive()).toBe(false)+ })++ it('GEGENPROBE: ein fehlgeschlagener Thread ist beendet, nicht beschäftigt', () => {+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'error')+ expect(runStatusOf('conv-c')).toBe('error')+ expect(isRunActive('conv-c')).toBe(false)+ })++ it('GEGENPROBE: ohne Konversation gibt es nichts zu beantworten', () => {+ expect(runStatusOf(null)).toBe('idle')+ expect(isRunActive(undefined)).toBe(false)+ })+})++describe('der aufgeschobene Dialog erbt die volle Union', () => {+ it('ein Lauf, der auf die Freigabe wartet, hält den Backend-Wähler zu', () => {+ // Vor AS-08 öffnete der Wähler hier: `status === 'running'` war falsch,+ // also galt der Lauf als beendet — und der Modal stand über dem+ // Freigabedialog, den der Nutzer gerade lesen soll.+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'awaiting_approval')+ let shown = 0+ whenRunsIdle(() => shown++)+ expect(shown).toBe(0)+ useCodexStore.getState().setThreadStatus('conv-c', 'idle')+ expect(shown).toBe(1)+ })++ it('ein Thread, der seine Änderungen schreibt, ebenso', () => {+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'applying')+ let shown = 0+ whenRunsIdle(() => shown++)+ expect(shown).toBe(0)+ useCodexStore.getState().setThreadStatus('conv-c', 'idle')+ expect(shown).toBe(1)+ })+})diff --git a/src/lib/run-idle.ts b/src/lib/run-idle.tsindex ec3c1e24..75271837 100644--- a/src/lib/run-idle.ts+++ b/src/lib/run-idle.ts@@ -1,34 +1,113 @@/**+ * "Is something running right now?" — asked and answered in ONE place.+ ** G25 (R17c witness 2026-08-07): backend detection resolves asynchronously a* few seconds after startup, so the "Multiple backends running" selector could* open MID RUN and stand over the chat for the rest of a 20 minute agent run.* Detection is a startup convenience; an active run is the one thing on screen* the user is actually watching. Any modal it wants to open waits here until* every surface is idle.+ *+ * ── AS-08 ────────────────────────────────────────────────────────────────+ * The app keeps the fact "a run is in flight" in two stores, and they are not+ * redundant copies of one another:+ *+ * 1. `generationStore.generating[convId]` — Chat, Agent AND the Coding Agent+ * all set it (`useChat.ts:639`, `useAgentChat.ts:599`, `useCodex.ts:756`).+ * It is the flag the Stop button and the typing indicator hang off.+ * 2. `codexStore.threads[convId].status` — only the Coding Agent has one, and+ * it is the only signal that can carry WHAT the run is doing rather than+ * just THAT it is running.+ *+ * Neither one alone is the truth, and they disagree in windows that are easy+ * to hit. `stopCodex` (`useCodex.ts:2605`) calls `abortConversation` at `:2614`,+ * which deletes `generating[convId]` synchronously, while the thread's status only+ * returns to 'idle' when the aborted run finishes unwinding in its `finally`+ * (`useCodex.ts:2517`) — a shell command that does not honour the signal+ * promptly stretches that window to seconds. During it, source 1 says idle and+ * source 2 says running. That window has a name now: `cancelling`.+ *+ * So the fix is not to pick a winner, it is to stop asking the question in+ * more than one place. This module reconciles both sources once and hands out+ * the verdict; `types/codex.ts` owns the classification of the states+ * themselves, as a total map, so a new state cannot slip through as a silent+ * `else`.+ *+ * STILL OPEN (locked files, reported rather than papered over):+ * - `components/chat/CodexModeDropdown.tsx:53` and+ * `components/chat/PlanApprovalBar.tsx:45` each compute their own+ * `generating[convId] === true` and never look at the thread. Both should+ * call `isRunActive(convId)`.+ * - `stores/chatStore.ts:59` (`dropConversationSideState`) sweeps four+ * stores when a chat is deleted and does not include `codexStore.threads`,+ * so a deleted coding chat leaves its thread behind — and its status keeps+ * voting in `anyRunActive` below.*/import { useGenerationStore } from '../stores/generationStore'import { useCodexStore } from '../stores/codexStore'+import { isRunStopped } from './run-stop'+import { isActiveCodexStatus, type CodexThreadStatus } from '../types/codex'/**- * Pure verdict over the two run signals: the per-conversation generating- * flags (Chat + Agent share them) and the Coding Agent's per-thread status.- * Exported for the unit tests.+ * Pure verdict over the two run signals, for the whole app: any generating+ * conversation, or any coding thread in a state that means work is in flight.+ *+ * The second half used to read `t.status === 'running'`, which answered "idle"+ * for a thread that was awaiting approval, applying its staged changes or+ * cancelling. The classification now lives with the union in `types/codex.ts`.+ * Exported for the unit tests and for callers that already hold both maps.*/export function anyRunActive(generating: Record<string, boolean>,- threads: Record<string, { status: string }>,+ threads: Record<string, { status: CodexThreadStatus }>,): boolean {if (Object.values(generating).some(Boolean)) return true- return Object.values(threads).some((t) => t.status === 'running')+ return Object.values(threads).some((t) => isActiveCodexStatus(t.status))}-function busy(): boolean {+/** Is ANY surface of the app busy right now? Reads both stores live. */+export function runsActive(): boolean {return anyRunActive(useGenerationStore.getState().generating,useCodexStore.getState().threads,)}+/**+ * What is this one conversation's run doing right now — the single verdict,+ * reconciled from both sources.+ *+ * Order matters and each step is a fact, not a guess:+ * - Not active by either source → `error` if the thread recorded one,+ * otherwise `idle`.+ * - Active and the user pressed Stop → `cancelling`. `run-stop.ts` is keyed+ * by conversation and is the one thing that knows this; the flag is sticky+ * after the run ends, which is why it is only read once the run is already+ * known to be active.+ * - Active with a thread that names its own state → that state+ * (`awaiting_approval` / `applying`), for whoever sets it.+ * - Active otherwise → `running`.+ */+export function runStatusOf(conversationId: string | null | undefined): CodexThreadStatus {+ if (!conversationId) return 'idle'+ const generating = useGenerationStore.getState().generating[conversationId] === true+ const thread = useCodexStore.getState().threads[conversationId]?.status+ const active = generating || (thread !== undefined && isActiveCodexStatus(thread))+ if (!active) return thread === 'error' ? 'error' : 'idle'+ if (isRunStopped(conversationId)) return 'cancelling'+ if (thread && thread !== 'running' && isActiveCodexStatus(thread)) return thread+ return 'running'+}++/**+ * Is a run in flight on this conversation? The question every per-conversation+ * caller should ask — never `generating[convId]` on its own, which is the half+ * of the truth that the Coding Agent's own Stop clears first.+ */+export function isRunActive(conversationId: string | null | undefined): boolean {+ return isActiveCodexStatus(runStatusOf(conversationId))+}+/*** Call `show` now when no run is active, otherwise the moment the last run* ends. Returns a cancel function that withdraws a still-deferred `show`@@ -38,14 +117,14 @@ function busy(): boolean {* never leave this waiting on a ghost run.*/export function whenRunsIdle(show: () => void): () => void {- if (!busy()) {+ if (!runsActive()) {show()return () => {}}let done = falseconst unsubs: (() => void)[] = []const check = () => {- if (done || busy()) return+ if (done || runsActive()) returndone = truefor (const u of unsubs) u()show()diff --git a/src/main.tsx b/src/main.tsxindex 4b991609..7a48d594 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -2,9 +2,19 @@ import './index.css'import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import { mountFatalError } from './lib/fatal-error'+import { installMcpShutdown } from './api/mcp/shutdown'const rootEl = document.getElementById('root')!+// T-53: external MCP servers are child processes this page owns, and nothing+// took them down when the page went away — a reload orphaned them for the rest+// of the app's life. Wired here, not in a component effect: the listeners+// belong to the page, not to a mount, and they must be standing before+// anything can connect a server. Cheap by construction — `external-client`+// imports the shell plugin lazily inside connect(), so this adds two listeners+// and no Tauri runtime to the boot chunk.+installMcpShutdown()+// Bug D (surfingbird1010): a throw while a persisted store hydrates from corrupt// data (D1 corrupt chat-settings / D2 migrate throw / D5 locked IndexedDB) fires// at module-import time — before the React ErrorBoundary can mount. With thediff --git a/src/stores/__tests__/delete-conversation-cascade.test.ts b/src/stores/__tests__/delete-conversation-cascade.test.tsindex 97d052c5..422f6a4f 100644--- a/src/stores/__tests__/delete-conversation-cascade.test.ts+++ b/src/stores/__tests__/delete-conversation-cascade.test.ts@@ -9,10 +9,43 @@* vectors are the expensive half — they kept being exported to* rag_chunks_backup.json every 30 s for the lifetime of the installation.*+ * AS-08 follow-up: the sweep documented FIVE stores and ran FOUR. codexStore+ * was the missing one, with five conversation-keyed maps of its own — and one+ * of them, `modeByConversation`, is persisted, so that leak outlived the+ * process. The threads map is the expensive one: an event ring of up to 500+ * entries, each an untruncated terminal result or a full unified diff, held+ * for a chat that no longer exists — and its status kept voting in+ * lib/run-idle.ts, so a chat deleted mid-run could defer every idle-gated+ * dialog for the rest of the session.+ ** Run: npx vitest run src/stores/__tests__/delete-conversation-cascade.test.ts*/import { describe, it, expect, vi, beforeEach } from 'vitest'+// zustand's persist middleware defaults to `window.localStorage` and RETURNS+// EARLY without attaching its `persist` API when that is missing+// (node_modules/zustand/esm/middleware.mjs:343). codexStore takes the default,+// so under vitest's node environment it would have no persist API at all and+// the test below could not ask the real middleware what it writes. Give it a+// real Storage — hoisted, because the store is created at import time. This is+// the platform, not a stand-in for anything under test.+vi.hoisted(() => {+ const mem = new Map<string, string>()+ const storage: Storage = {+ get length() { return mem.size },+ key: (i) => [...mem.keys()][i] ?? null,+ getItem: (k) => mem.get(k) ?? null,+ setItem: (k, v) => { mem.set(k, String(v)) },+ removeItem: (k) => { mem.delete(k) },+ clear: () => { mem.clear() },+ }+ Object.defineProperty(globalThis, 'window', {+ value: { localStorage: storage },+ writable: true,+ configurable: true,+ })+})+const deletedDocs: string[] = []vi.mock('../../lib/ragDB', () => ({saveChunks: vi.fn(async () => {}),@@ -25,6 +58,7 @@ import { useRAGStore } from '../ragStore'import { useTodoStore } from '../todoStore'import { usePermissionStore } from '../permissionStore'import { useStagedChangesStore } from '../stagedChangesStore'+import { useCodexStore } from '../codexStore'function seedSideState(id: string) {const docId = `doc-${id}`@@ -42,9 +76,33 @@ function seedSideState(id: string) {useStagedChangesStore.getState().stage(id, {path: 'main.py', oldContent: '', newContent: 'x', diff: '+x',})+ // All five codexStore maps, each through the store's own writers so the+ // seeding cannot drift from what the app really puts there.+ useCodexStore.getState().initThread(id, '/repo')+ useCodexStore.getState().addEvent(id, {+ id: `ev-${id}`, type: 'terminal_output', content: 'x'.repeat(4096), timestamp: 1,+ })+ useCodexStore.getState().setThreadStatus(id, 'running')+ useCodexStore.getState().chooseCodexMode(id, 'bypass', false)+ useCodexStore.getState().chooseCodexMode(id, 'plan', false) // fills prePlanModeByConversation+ useCodexStore.getState().chooseCodexMode(id, 'ask', true) // parks, run active+ useCodexStore.getState().setPlanApproval(id, { planText: 'p', messageId: 'm', createdAt: 1 })}-describe('deleteConversation sweeps the four dependent stores', () => {+/** The five maps codexStore keys by conversation id. */+function codexMapsHolding(id: string): string[] {+ const s = useCodexStore.getState()+ const maps: [string, Record<string, unknown>][] = [+ ['threads', s.threads],+ ['modeByConversation', s.modeByConversation],+ ['parkedModeByConversation', s.parkedModeByConversation],+ ['prePlanModeByConversation', s.prePlanModeByConversation],+ ['planApprovalByConversation', s.planApprovalByConversation],+ ]+ return maps.filter(([, m]) => id in m).map(([name]) => name)+}++describe('deleteConversation sweeps the five dependent stores', () => {beforeEach(() => {deletedDocs.length = 0useChatStore.setState({ conversations: [], activeConversationId: null })@@ -52,6 +110,13 @@ describe('deleteConversation sweeps the four dependent stores', () => {useTodoStore.setState({ byConversation: {}, updatedAt: {} })usePermissionStore.setState({ conversationOverrides: {} })useStagedChangesStore.setState({ byChat: {} })+ useCodexStore.setState({+ threads: {},+ modeByConversation: {},+ parkedModeByConversation: {},+ prePlanModeByConversation: {},+ planApprovalByConversation: {},+ })})it('leaves nothing keyed by the deleted conversation id', () => {@@ -67,6 +132,38 @@ describe('deleteConversation sweeps the four dependent stores', () => {expect(useTodoStore.getState().updatedAt).not.toHaveProperty(id)expect(usePermissionStore.getState().conversationOverrides).not.toHaveProperty(id)expect(useStagedChangesStore.getState().byChat).not.toHaveProperty(id)+ // The consequence, not the shape of the list: no codexStore map still+ // holds the id. A sweep that cleared only `threads` fails here.+ expect(codexMapsHolding(id)).toEqual([])+ })++ it('the seed really filled all five codex maps — otherwise the sweep proves nothing', () => {+ const id = useChatStore.getState().createConversation('llama3', '')+ seedSideState(id)+ expect(codexMapsHolding(id)).toEqual([+ 'threads',+ 'modeByConversation',+ 'parkedModeByConversation',+ 'prePlanModeByConversation',+ 'planApprovalByConversation',+ ])+ })++ it('the PERSISTED codex map is cleared — the difference between until-restart and forever', () => {+ const id = useChatStore.getState().createConversation('llama3', '')+ seedSideState(id)+ // partialize decides what actually reaches storage. Asked of the real+ // middleware, not read off the source, so a change to what is persisted+ // cannot leave this test claiming something that is no longer true.+ const partialize = useCodexStore.persist.getOptions().partialize+ const before = partialize?.(useCodexStore.getState()) ?? {}+ expect(JSON.stringify(before)).toContain(id)++ useChatStore.getState().deleteConversation(id)++ const after = partialize?.(useCodexStore.getState()) ?? {}+ expect(JSON.stringify(after)).not.toContain(id)+ expect(useCodexStore.getState().modeByConversation).not.toHaveProperty(id)})it('deletes the embedding vectors from ragDB, not just the document row', () => {@@ -92,9 +189,11 @@ describe('deleteConversation sweeps the four dependent stores', () => {expect(usePermissionStore.getState().conversationOverrides).toHaveProperty(keep)expect(useStagedChangesStore.getState().byChat).toHaveProperty(keep)expect(useRAGStore.getState().ragEnabled).toHaveProperty(keep)+ expect(codexMapsHolding(keep)).toHaveLength(5)+ expect(codexMapsHolding(drop)).toEqual([])})- it('one failing store does not stop the other three or the delete itself', () => {+ it('one failing store does not stop the other four or the delete itself', () => {const id = useChatStore.getState().createConversation('llama3', '')seedSideState(id)const boom = vi.spyOn(useRAGStore.getState(), 'removeConversation').mockImplementation(() => {@@ -107,6 +206,7 @@ describe('deleteConversation sweeps the four dependent stores', () => {expect(useTodoStore.getState().byConversation).not.toHaveProperty(id)expect(usePermissionStore.getState().conversationOverrides).not.toHaveProperty(id)expect(useStagedChangesStore.getState().byChat).not.toHaveProperty(id)+ expect(codexMapsHolding(id)).toEqual([])boom.mockRestore()})})diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex faa871c8..83662dbc 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -12,6 +12,7 @@ import { useRAGStore } from './ragStore'import { useTodoStore } from './todoStore'import { usePermissionStore } from './permissionStore'import { useStagedChangesStore } from './stagedChangesStore'+import { useCodexStore } from './codexStore'import { log } from '../lib/logger'import { isRecord, prop } from '../types/json-guards'@@ -47,9 +48,27 @@ export function migratePersistedChat(state: unknown): unknown {* Deleting a chat used to remove exactly one row — the one in `conversations` —* and leave five other stores holding that id forever. Nothing ever collects* them, because the id is the only thing that could prove they are orphans and- * the id is what was just thrown away. The RAG side is the expensive one: its- * 768-float embedding vectors stay in IndexedDB AND keep being exported to- * rag_chunks_backup.json every 30 s for the lifetime of the installation.+ * the id is what was just thrown away.+ *+ * Two of the five are expensive, for different reasons:+ *+ * - RAG: its 768-float embedding vectors stay in IndexedDB AND keep being+ * exported to rag_chunks_backup.json every 30 s for the lifetime of the+ * installation.+ * - codex: a Coding-Agent thread carries an event ring of up to 500 entries,+ * and each entry is either an UNTRUNCATED terminal result (the 60k cap in+ * useCodex applies to what goes back to the model, not to what is stored)+ * or a full unified diff — tens of megabytes for a chat that is gone. Its+ * status also keeps voting in `lib/run-idle.ts`, so a chat deleted mid-run+ * could leave a thread stuck at 'running' and defer every idle-gated dialog+ * for the rest of the session. And `codexStore.modeByConversation` is+ * PERSISTED, which is the difference between leaking until the next restart+ * and leaking for good.+ *+ * The list below ran with FOUR entries while this comment said five (and the+ * one below it said "the other four") — codex was the missing step, and the+ * mismatch between the two numbers was the only sign of it. Number and list+ * are now the same thing; keep them that way.** Each store is its own try/catch: one of them failing must not leave the other* four uncleaned, and none of them may stop the chat from being deleted.@@ -62,6 +81,7 @@ export function dropConversationSideState(id: string): void {['todos', () => useTodoStore.getState().clearTodos(id)],['permissions', () => usePermissionStore.getState().clearConversationOverrides(id)],['staged-changes', () => useStagedChangesStore.getState().clear(id)],+ ['codex', () => useCodexStore.getState().dropConversation(id)],]for (const [what, run] of steps) {try { run() } catch (err) {diff --git a/src/stores/codexStore.ts b/src/stores/codexStore.tsindex 4c9469ae..089568c4 100644--- a/src/stores/codexStore.ts+++ b/src/stores/codexStore.ts@@ -84,6 +84,13 @@ interface CodexState {initThread: (conversationId: string, workingDir: string) => stringaddEvent: (conversationId: string, event: CodexEvent) => voidsetThreadStatus: (conversationId: string, status: CodexThread['status']) => void+ /**+ * Everything this store holds under one conversation id, dropped in one+ * `set()`. Called by `chatStore.dropConversationSideState` when the chat is+ * deleted — see the comment on the implementation for why all FIVE maps go+ * and not just `threads`.+ */+ dropConversation: (conversationId: string) => void}/** Drop one key from a record without leaving an undefined hole behind. */@@ -212,6 +219,39 @@ export const useCodexStore = create<CodexState>()(},}}),++ /**+ * The chat is gone; so is everything this store filed under its id.+ *+ * FIVE maps, not one. `threads` is the expensive one — a thread carries+ * an event ring of up to CODEX_EVENT_LOG_MAX entries, and each entry is+ * either an UNTRUNCATED terminal result (the 60k cap in useCodex applies+ * to what goes back to the model, not to what is stored here) or a full+ * unified diff. That is tens of megabytes held for a chat that no longer+ * exists, and no id left to prove it is an orphan.+ *+ * The other four maps are small, and one of them is the reason this is+ * not merely bookkeeping: `modeByConversation` is the ONE part of the+ * mode slice that is persisted (see `partialize` below), so a deleted+ * chat's Ask/Bypass/Plan pick used to survive every restart from then on.+ * That is the difference between leaking until the next start and leaking+ * for good. `threads` has its own second cost: its status keeps voting in+ * `lib/run-idle.ts` for as long as the entry exists, so a chat deleted+ * mid-run could leave a thread at 'running' and defer every idle-gated+ * dialog for the rest of the session.+ *+ * One `set()` so a subscriber can never observe the conversation half+ * removed, and `omit` returns the same object when the key is absent, so+ * deleting a chat that never touched the Coding Agent is free.+ */+ dropConversation: (conversationId) =>+ set((state) => ({+ threads: omit(state.threads, conversationId),+ modeByConversation: omit(state.modeByConversation, conversationId),+ parkedModeByConversation: omit(state.parkedModeByConversation, conversationId),+ prePlanModeByConversation: omit(state.prePlanModeByConversation, conversationId),+ planApprovalByConversation: omit(state.planApprovalByConversation, conversationId),+ })),}),{// Persist key kept as 'locally-uncensored-codex' for storagediff --git a/src/types/codex.ts b/src/types/codex.tsindex 5d51ea5c..16f24c0c 100644--- a/src/types/codex.ts+++ b/src/types/codex.ts@@ -16,11 +16,88 @@ export interface CodexEvent {diff?: string}+/**+ * The lifecycle of one Coding-Agent run, as the app actually runs it.+ *+ * AS-08. The union used to be `'idle' | 'running' | 'error'` — three states for+ * a lifecycle that has six. The missing three are not hypothetical; each one is+ * a place the app really parks in, it just parked there under a different+ * name, in a different module, out of reach of anything that asks "is a run in+ * flight?":+ *+ * - `awaiting_approval` — the run is blocked on the shell/code approval card.+ * `stores/codexConfirmStore.ts` parks the resolver, `hooks/useCodex.ts:2088`+ * (`awaitApproval: knobs.confirmExec`) awaits it. The run is not doing+ * anything and is not finished either.+ * - `applying` — staged changes are being written to disk.+ * `hooks/useCodex.ts:2371` (`await applyAllStagedChanges(convId)`) on the+ * run's own exit path, and `components/chat/StagedChangesPanel.tsx:36`+ * (a local `applying` Set) when the user presses Apply by hand.+ * - `cancelling` — Stop was pressed and the tail of the run has not unwound+ * yet. `lib/run-stop.ts` holds that fact per conversation, deliberately+ * sticky, because "a stopped run's tail work … must all see the stop".+ *+ * The reason this matters is the one the audit names: a state the app has but+ * its type does not becomes a silent `else` at every branch. `run-idle.ts`+ * asked `status === 'running'` and answered "idle" for all three.+ *+ * `error` is kept and is honest about itself: it is declared, it is exercised+ * by `stores/__tests__/sessionStores.test.ts`, and **no production code sets+ * it** — `setThreadStatus` has exactly two callers, `useCodex.ts:752`+ * ('running') and `useCodex.ts:2517` ('idle'). That is the mirror image of the+ * bug above and it is written down here rather than quietly dropped.+ */+export type CodexThreadStatus =+ | 'idle'+ | 'running'+ | 'awaiting_approval'+ | 'applying'+ | 'cancelling'+ | 'error'++/**+ * Does this state mean a run is in flight?+ *+ * The verdict lives next to the union on purpose, and as a total+ * `Record<CodexThreadStatus, …>` rather than a list or a comparison: adding a+ * seventh state without deciding what it means to "is something running?" is a+ * compile error, not a silent `false`. That is the whole defence against the+ * pattern that produced AS-08 in the first place.+ *+ * `awaiting_approval`, `applying` and `cancelling` are all ACTIVE. A run+ * waiting on the user's approval still owns the conversation, still holds its+ * abort controller, and a modal that opens over it is the G25 regression all+ * over again. A run writing files to disk is the last moment you want to be+ * told the app is idle. And a cancelling run is not a finished run — that is+ * exactly the distinction T-28 / T-51 had to be taught.+ */+const RUN_ACTIVE_BY_STATUS: Record<CodexThreadStatus, boolean> = {+ idle: false,+ running: true,+ awaiting_approval: true,+ applying: true,+ cancelling: true,+ // Terminal. The run is over; the thread carries the reason, not the work.+ error: false,+}++/** Every state in the union, derived from the verdict map so the two cannot drift. */+export const CODEX_THREAD_STATUSES = Object.keys(RUN_ACTIVE_BY_STATUS) as CodexThreadStatus[]++/**+ * The single classification of a thread status. Everything that wants to know+ * whether a coding run is in flight goes through here — see `lib/run-idle.ts`,+ * which is the one place that answers the question for the whole app.+ */+export function isActiveCodexStatus(status: CodexThreadStatus): boolean {+ return RUN_ACTIVE_BY_STATUS[status]+}+export interface CodexThread {id: stringconversationId: stringevents: CodexEvent[]- status: 'idle' | 'running' | 'error'+ status: CodexThreadStatusworkingDirectory: string}