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(T-76/T-68): der Audit-Zeiger traf die eine geschlossene Stelle — das Leck sass daneben
David4c7bf74851ad
diff --git a/src/api/mcp/__tests__/der-kill-weg-nimmt-den-baum.test.ts b/src/api/mcp/__tests__/der-kill-weg-nimmt-den-baum.test.tsnew file mode 100644index 00000000..f2e46bcb--- /dev/null+++ b/src/api/mcp/__tests__/der-kill-weg-nimmt-den-baum.test.ts@@ -0,0 +1,263 @@+/**+ * T-68, Nachzug im Frontend — "erst der Baum, dann gar nichts mehr".+ *+ * `tauri-plugin-shell`s `CommandChild::kill` (`src/process/mod.rs:78`) schickt+ * EIN Signal an das direkte Kind. Ein MCP-Server, der als `npx -y <paket>`+ * startet, ist damit nicht gemeint: das direkte Kind ist der Starter, der+ * eigentliche `node`-Server ist ein Enkel. `child.kill()` erlegte den Starter+ * und liess den Server laufen — und zwar unerreichbar, weil der JS-Handle+ * mit dem Starter verschwand.+ *+ * Seit `c5773322` gibt es dafür `kill_process_tree` auf der Rust-Seite. Der+ * Haken, den dieser Test festnagelt, ist die REIHENFOLGE: die Rust-Wache+ * (`may_kill_pid`) lässt nur pids aus dem eigenen Teilbaum durch, und genau+ * den zerstört der Tod des direkten Kindes — sobald der Starter weg ist,+ * hängen seine Kinder an init, sind keine Nachfahren dieser App mehr, und die+ * Wache verweigert zu Recht. `kill_process_tree` muss deshalb ANSTELLE von+ * `child.kill()` laufen, nie danach. Ein Kommentar hält das nicht; die Tests+ * unten tun es.+ *+ * Lauf: npx vitest run src/api/mcp/__tests__/der-kill-weg-nimmt-den-baum.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { MCPExternalClient } from '../external-client'+import type { MCPServerConfig } from '../types'++// ── ein Protokoll, das die Reihenfolge behält ──────────────────────────────+//+// Beide Wege schreiben in dieselbe Liste, damit "danach" ein Testfehler wird+// und nicht bloss eine andere Zählung.+let events: string[] = []++/** Was der Rust-Aufruf tun soll: auflegen, ablehnen, oder gar nicht da sein. */+type InvokeBehaviour = 'ok' | 'refused' | 'missing'+let invokeBehaviour: InvokeBehaviour = 'ok'++vi.mock('@tauri-apps/api/core', () => ({+ invoke: async (cmd: string, args?: Record<string, unknown>) => {+ // Sobald `isTauri()` wahr ist, geht auch der Logger durch diese IPC.+ // Protokolliert wird nur, worum es hier geht.+ if (cmd !== 'kill_process_tree') return undefined+ if (invokeBehaviour === 'missing') {+ // Was Tauri für ein unbekanntes Kommando meldet (ältere Rust-Seite).+ throw new Error(`Command ${cmd} not found`)+ }+ events.push(`${cmd}:${String(args?.pid)}`)+ if (invokeBehaviour === 'refused') {+ // Der Wortlaut von `may_kill_pid`, gekürzt.+ throw new Error(`refused: pid ${String(args?.pid)} is not a process this app started`)+ }+ return { killed: true, pid: args?.pid, processes: 2 }+ },+}))++// ── der Shell-Fake, gleiche Form wie in external-client.test.ts ────────────++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 { id?: number; method?: string }+type Responder = (req: FakeRequest) => string | null++let lastServer: FakeServer | null = null++/** Die pid, die der Plugin-Spawn zurückgibt — das ist der Starter, nicht der Server. */+const LAUNCHER_PID = 4242++/** Setzt ein Test, wenn auch der Rückfall scheitern soll (Prozess schon tot). */+let childKillThrows = false++class FakeChild {+ pid = LAUNCHER_PID+ private server: FakeServer+ constructor(server: FakeServer) { this.server = server }+ async write(data: string) { this.server.receive(data) }+ async kill() {+ events.push(`child.kill:${this.pid}`)+ if (childKillThrows) throw new Error('No such process')+ this.server.killed = true+ }+}++class FakeServer extends Emitter {+ stdout = new Emitter()+ stderr = new Emitter()+ killed = false+ written: string[] = []+ async spawn() { return new FakeChild(this) }+ receive(data: string) {+ this.written.push(data)+ for (const line of data.split('\n')) {+ if (!line.trim()) continue+ const out = responder(JSON.parse(line))+ if (out !== null) this.stdout.emit('data', out + '\n')+ }+ }+}++let responder: Responder = () => null++vi.mock('@tauri-apps/plugin-shell', () => ({+ Command: { create: () => (lastServer = new FakeServer()) },+}))++const config: MCPServerConfig = {+ id: 'srv-1', name: 'weather', command: 'npx', args: ['-y', 'weather-mcp'], enabled: true,+}++const goodServer: Responder = (req) => {+ 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: [] } })+ }+ return null+}++/** Ein Server, der den Handshake verweigert — der zweite Kill-Weg. */+const refusingServer: Responder = (req) => {+ if (req.method === 'initialize') {+ return JSON.stringify({ jsonrpc: '2.0', id: req.id, error: { code: -32000, message: 'nope' } })+ }+ return null+}++/**+ * Der Kill-Weg fragt die Rust-Seite nur, wenn es eine gibt: `isTauri()` prüft+ * `window.__TAURI_INTERNALS__`. Ohne das wäre der ganze Baum-Kill unter vitest+ * unerreichbar — und der Test würde nur beweisen, dass das direkte Kind noch+ * stirbt.+ */+function pretendTauri() {+ Object.defineProperty(globalThis, 'window', {+ value: { __TAURI_INTERNALS__: {} },+ writable: true,+ configurable: true,+ })+}++beforeEach(() => {+ responder = goodServer+ lastServer = null+ events = []+ invokeBehaviour = 'ok'+ childKillThrows = false+ pretendTauri()+})++afterEach(() => {+ Reflect.deleteProperty(globalThis, 'window')+})++describe('der Abbau nimmt den Prozessbaum', () => {+ it('disconnect ruft den Baum-Kill statt child.kill', async () => {+ const client = new MCPExternalClient(config)+ await client.connect()+ await client.disconnect()+ expect(events).toEqual([`kill_process_tree:${LAUNCHER_PID}`])+ })++ it('der Baum-Kill bekommt die pid des gespawnten Kindes', async () => {+ // Die pid ist das einzige Argument, und eine falsche pid wäre auf der+ // Rust-Seite entweder eine Ablehnung oder — schlimmer — ein Fremdkill.+ const client = new MCPExternalClient(config)+ await client.connect()+ await client.disconnect()+ expect(events[0]).toBe(`kill_process_tree:${LAUNCHER_PID}`)+ })++ it('ein gescheiterter Handshake nimmt denselben Weg', async () => {+ // Der Server läuft schon, wenn `initialize` scheitert; niemand ausser+ // connect() hält je einen Handle darauf.+ responder = refusingServer+ const client = new MCPExternalClient(config)+ await expect(client.connect()).rejects.toThrow(/Failed to connect/)+ expect(events).toEqual([`kill_process_tree:${LAUNCHER_PID}`])+ })++ it('zwei gleichzeitige disconnects schicken einen Kill, nicht zwei', async () => {+ // Die Abbau-Sichtung beim Seitenwechsel und ein Klick im Panel können+ // sich überholen, und ein Kill ist hier eine asynchrone IPC-Runde: wer+ // den Handle erst NACH dem await fallen lässt, schickt zwei. Eine+ // inzwischen neu vergebene pid wäre dann ein Fremdkill.+ // Deshalb wirklich nebenläufig, nicht nacheinander — sequenziell sähe+ // auch die kaputte Reihenfolge grün aus.+ const client = new MCPExternalClient(config)+ await client.connect()+ await Promise.all([client.disconnect(), client.disconnect()])+ expect(events).toEqual([`kill_process_tree:${LAUNCHER_PID}`])+ })+})++describe('lehnt der Baum-Kill ab, läuft der Server trotzdem nicht weiter', () => {+ it('die Ablehnung fällt auf das direkte Kind zurück', async () => {+ invokeBehaviour = 'refused'+ const client = new MCPExternalClient(config)+ await client.connect()+ await client.disconnect()+ expect(lastServer?.killed).toBe(true)+ })++ it('der Rückfall kommt NACH dem Baum-Kill, nie davor', async () => {+ // Das ist der ganze Witz: umgekehrt wäre der Baum-Kill garantiert+ // sinnlos, weil die Enkel dann schon an init hängen.+ invokeBehaviour = 'refused'+ const client = new MCPExternalClient(config)+ await client.connect()+ await client.disconnect()+ expect(events).toEqual([`kill_process_tree:${LAUNCHER_PID}`, `child.kill:${LAUNCHER_PID}`])+ })++ it('fehlt das Kommando ganz, greift derselbe Rückfall', async () => {+ // Eine Rust-Seite vor c5773322 kennt `kill_process_tree` nicht.+ invokeBehaviour = 'missing'+ const client = new MCPExternalClient(config)+ await client.connect()+ await client.disconnect()+ expect(events).toEqual([`child.kill:${LAUNCHER_PID}`])+ })++ it('scheitern beide Wege, meldet disconnect trotzdem nicht durch', async () => {+ // disconnect() hängt an einem Seiten-Unload; eine Ablehnung dort wäre+ // eine unbehandelte.+ invokeBehaviour = 'refused'+ childKillThrows = true+ const client = new MCPExternalClient(config)+ await client.connect()+ await expect(client.disconnect()).resolves.toBeUndefined()+ expect(events).toEqual([`kill_process_tree:${LAUNCHER_PID}`, `child.kill:${LAUNCHER_PID}`])+ })+})++describe('ohne Tauri gibt es keinen Baum-Kill zu holen', () => {+ it('der Browser-Lauf fragt gar nicht erst und nimmt direkt das Kind', async () => {+ // Unter reinem `npm run dev` gibt es keine IPC — und damit auch keinen+ // Server, weil der Spawn durch dieselbe IPC läuft. Ein Baum-Kill-Versuch+ // wäre dort eine Warnung über etwas, das niemand wollen konnte, und ein+ // dynamischer Import mitten im Seiten-Unload.+ const client = new MCPExternalClient(config)+ await client.connect()+ Reflect.deleteProperty(globalThis, 'window')+ await client.disconnect()+ expect(events).toEqual([`child.kill:${LAUNCHER_PID}`])+ })+})++describe('es gibt genau eine Stelle, die tötet', () => {+ it('external-client ruft child.kill() nur aus killServerProcess', () => {+ // Zwei Aufrufstellen waren der Ausgangszustand, und eine dritte würde+ // die Reihenfolge oben ohne einen roten Test verletzen können.+ const src = readFileSync(join(__dirname, '..', 'external-client.ts'), 'utf8')+ // Der Kommentarblock über `killServerProcess` erklärt `child.kill()` und+ // nennt es dabei mehrfach — gezählt wird der Code, nicht die Prosa.+ const code = src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')+ expect(code.match(/\bchild\.kill\(\)/g) ?? []).toHaveLength(1)+ expect(code).toMatch(/invoke\('kill_process_tree', \{ pid \}\)/)+ })+})diff --git a/src/api/mcp/external-client.ts b/src/api/mcp/external-client.tsindex 482c16c6..9ba7e400 100644--- a/src/api/mcp/external-client.ts+++ b/src/api/mcp/external-client.ts@@ -8,6 +8,7 @@import type { Child } from '@tauri-apps/plugin-shell'import type { MCPToolDefinition, MCPServerConfig, ToolArgs } from './types'import { log } from '../../lib/logger'+import { isTauri } from '../backend'import { isRecord, prop, asString, asNumber, asRecordArray, errorText } from '../../types/json-guards'// ── JSON-RPC message types ──────────────────────────────────────@@ -300,10 +301,7 @@ export class MCPExternalClient {// A failure after spawn (handshake refused, tools/list timed out) leaves// the server process running with nobody holding a handle to it — the// caller never gets a client it could disconnect. Take it down here.- if (this.child) {- try { await this.child.kill() } catch { /* already gone */ }- this.child = null- }+ await this.killServerProcess()liveClients.delete(this)throw new Error(`Failed to connect to MCP server "${this.config.name}": ${err instanceof Error ? err.message : String(err)}`)}@@ -336,13 +334,84 @@ export class MCPExternalClient {// inside the sweep must not be reachable a second time.liveClients.delete(this)this.rejectAllPending('Disconnecting')- if (this.child) {+ await this.killServerProcess()+ }++ /**+ * Take the server process down — the whole tree, not just the shim (T-68).+ *+ * The one place this client kills anything. Both callers (a failed handshake+ * in `connect()`, and `disconnect()`) used to run `this.child.kill()`+ * themselves, and that call is NOT a tree kill:+ * `tauri-plugin-shell`'s `CommandChild::kill` is one signal to the DIRECT+ * child (`src/process/mod.rs:78`). An MCP server started as `npx -y <pkg>`+ * — or `npx.cmd` through cmd.exe on Windows — has the launcher as that+ * direct child and the real `node` server as a GRANDCHILD. Killing the shim+ * reaped the launcher and left the server running for the rest of the+ * session, unreachable: the JS handle was gone with it.+ *+ * ── The ordering is the whole point ─────────────────────────────────────+ *+ * `kill_process_tree` is called INSTEAD of `child.kill()`, never after it.+ * The Rust guard (`may_kill_pid`) only allows pids inside this app's own+ * subtree, and that is exactly what the direct child's death destroys: the+ * moment the launcher exits, its children are reparented to init, stop being+ * our descendants, and the guard refuses — correctly, and too late. Kill the+ * shim first and the tree kill can no longer reach anything.+ *+ * The tree kill covers the direct child too (`kill_pid_tree`'s snapshot+ * includes the root), so nothing is left for a follow-up kill to do. Not+ * calling the plugin's own `kill` command also does not strand the pid in+ * its child map: the plugin removes an entry when it sees `Terminated`+ * (`src/commands.rs:259`), which is what the tree kill causes.+ *+ * ── When the command is not there or says no ────────────────────────────+ *+ * Two ways to land in the fallback, both real: a Rust side older than+ * `c5773322` has no such command, and the guard refuses a pid that is not+ * ours — which happens when the process already exited on its own, so its+ * pid is not in this app's subtree any more. In both the alternative to+ * `child.kill()` is leaving a server process running, i.e. exactly the+ * pre-T-53 bug; so we fall back and say so in the log. What the fallback+ * can lose is grandchildren — the leak this method exists to close — and+ * nothing beyond that.+ *+ * Outside Tauri there is no IPC to ask, and no MCP server either: the spawn+ * goes through the shell plugin, which needs the same IPC. The check is+ * synchronous on purpose, so the no-Tauri case does not pay for a dynamic+ * import (a page-unload sweep is counted in ticks) and does not log a+ * warning about a tree kill nobody could have wanted.+ *+ * Best-effort throughout: `disconnect()` is reached from a page-unload sweep+ * where a rejection is an unhandled one.+ */+ private async killServerProcess(): Promise<void> {+ const child = this.child+ if (!child) return+ // Dropped before the awaits: a second disconnect (the sweep racing a+ // panel click) must not issue a second kill for the same pid — by then it+ // may belong to somebody else.+ this.child = null+ const pid = child.pid++ if (isTauri()) {try {- await this.child.kill()- } catch {- // Process may already be dead+ const { invoke } = await import('@tauri-apps/api/core')+ await invoke('kill_process_tree', { pid })+ return+ } catch (err) {+ log.warn(+ `[MCP:${this.config.name}] no process-tree kill available — killing only the direct `+ + 'child, so a server that spawned its own processes may leave them running',+ { pid, err: errorText(err) },+ )}- this.child = null+ }++ try {+ await child.kill()+ } catch {+ // Process may already be dead}}diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsxindex 926b66d2..ffa9f8d3 100644--- a/src/components/create/experimental/SpecialIntentControls.tsx+++ b/src/components/create/experimental/SpecialIntentControls.tsx@@ -11,7 +11,7 @@ import { AnimatePresence, motion } from 'framer-motion'import {AudioLines, Download, Film, ImagePlus, Info, Mic, Music2, Trash2, Upload, Wand2, X,} from 'lucide-react'-import { useCreateStore, type CreateIntent, type MediaRef, type GalleryItem } from '../../../stores/createStore'+import { useCreateStore, type CreateIntent, type GalleryItem } from '../../../stores/createStore'import { useCloudCatalogStore, cloudModelById, modelForOp } from '../../../stores/cloudCatalogStore'import { listLoras, deleteLora, type CloudLora } from '../../../api/cloud/loras'import {@@ -24,6 +24,7 @@ import { getLoraModels } from '../../../api/comfyui'import { musicTakesLyrics, musicHowtoLines } from '../../../lib/render/music-ui'import { useCreateExp } from './CreateContext'import { loadImageRef } from './loadImage'+import { mediaRefFrom } from './mediaRef'import { fetchGalleryItemBlob } from './galleryUrl'import { Button } from '../ui/Button'import { Segmented } from '../ui/Segmented'@@ -43,17 +44,13 @@ export function SpecialControls({ intent }: { intent: CreateIntent }) {}// ── shared chip: a small labeled file slot (audio/video/image) ──────────────--/** A staged file plus a `blob:` preview URL for it.- *- * The URL's lifetime is closed in createStore's `setAudioInput` /- * `setVideoInput` (see `releaseReplacedMediaRef`): those two setters are the- * only way a slot is written, so replacing or clearing a pick always frees- * the file the previous pick pinned. Do NOT revoke here — the ref outlives- * this component, it lives in the store. */-function mediaRefFrom(file: File): MediaRef {- return { name: file.name, url: URL.createObjectURL(file), blob: file }-}+//+// `mediaRefFrom` used to be defined right here, and the training board in+// Stage.tsx had its own inline copy of the same two lines. Two mints, one+// release — and it was the copy without a release. Both now come from+// `./mediaRef`, whose counterpart in createStore is+// `releaseDroppedMediaRefs`. Do NOT revoke in this file: the ref outlives the+// component, it lives in the store.function FileChip({icon: Icon,diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxindex e0b1e25b..75907fae 100644--- a/src/components/create/experimental/Stage.tsx+++ b/src/components/create/experimental/Stage.tsx@@ -10,6 +10,7 @@ import { ICON_STROKE_MARK } from '../../ui/icon-size'import { Button } from '../ui/Button'import { cn } from '../ui/cn'import { loadImageRef } from './loadImage'+import { mediaRefFrom } from './mediaRef'import {subscribeInstallRuns, getInstallRun, startInstallRun, cancelInstallRun, clearInstallRun,} from '../../../lib/model-install-runs'@@ -591,9 +592,13 @@ function TrainSetBoard() {const inputRef = useRef<HTMLInputElement>(null)const addFiles = (files: FileList | File[]) => {+ // One mint, one release: `mediaRefFrom` is the only place a staged file+ // gets a blob: URL, and `addTrainImages` gives back every ref it does not+ // keep (a name duplicate, anything past the 30 cap). This used to be an+ // inline copy of those two lines with nothing on the other end.const imgs = Array.from(files).filter((f) => f.type.startsWith('image/'))- .map((f) => ({ name: f.name, url: URL.createObjectURL(f), blob: f as Blob }))+ .map(mediaRefFrom)if (imgs.length > 0) addTrainImages(imgs)}diff --git a/src/components/create/experimental/__tests__/das-trainingsset-gibt-seine-blobs-zurueck.test.ts b/src/components/create/experimental/__tests__/das-trainingsset-gibt-seine-blobs-zurueck.test.tsnew file mode 100644index 00000000..f93d41b8--- /dev/null+++ b/src/components/create/experimental/__tests__/das-trainingsset-gibt-seine-blobs-zurueck.test.ts@@ -0,0 +1,137 @@+/**+ * T-76 · "Create-Dateislots geben ihre Blob-URLs nie frei" — der Rest davon.+ *+ * Der Audit-Zeiger (SpecialIntentControls.tsx:48) trifft eine Stelle, die+ * bereits geschlossen IST: `mediaRefFrom` mintet eine `blob:` URL pro Pick,+ * und `setAudioInput` / `setVideoInput` geben die vorige über+ * `releaseReplacedMediaRef` zurück (bewiesen in+ * `src/api/__tests__/mlx-video-blob-lifetime.test.ts`).+ *+ * Ungedeckt blieb der DRITTE Slot derselben Familie: `trainImages`, ein+ * MediaRef[]. Er wird nicht ersetzt, sondern erweitert, gefiltert und+ * geleert — und keiner dieser drei Wege gab je etwas zurück:+ *+ * - `addTrainImages` wirft Namensdubletten weg und kappt bei 30,+ * - `removeTrainImage` filtert einen heraus,+ * - `clearTrainImages` leert alles (der Cloud-Trainingslauf ruft das nach+ * jedem Submit, `useCloudCreate.ts:367`).+ *+ * Jeder weggeworfene Eintrag hielt seine Datei bis zum Reload im Speicher —+ * bei 30 Fotos zu je einigen Megabyte ist das der ganze Trainingssatz.+ *+ * Lauf: npx vitest run src/components/create/experimental/__tests__/das-trainingsset-gibt-seine-blobs-zurueck.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { readFileSync, readdirSync } from 'node:fs'+import { join } from 'node:path'+import { useCreateStore } from '../../../../stores/createStore'+import { mediaRefFrom } from '../mediaRef'++// ── ein zählbarer Ersatz für die Blob-Tabelle des Renderers ────────────────+let minted = 0+const live = new Set<string>()++beforeEach(() => {+ minted = 0+ live.clear()+ globalThis.URL.createObjectURL = () => {+ const url = `blob:test/${++minted}`+ live.add(url)+ return url+ }+ globalThis.URL.revokeObjectURL = (url: string) => { live.delete(url) }+ useCreateStore.setState({ trainImages: [], audioInput: null, videoInput: null })+})++/** Eine Datei, wie der Dateidialog sie liefert. */+function file(name: string): File {+ return new File([new Uint8Array([1, 2, 3])], name, { type: 'image/png' })+}++/** Genau das, was `TrainSetBoard.addFiles` (Stage.tsx) mit einem Drop tut. */+function drop(...names: string[]) {+ useCreateStore.getState().addTrainImages(names.map((n) => mediaRefFrom(file(n))))+}++describe('das Trainingsset gibt seine Blob-URLs zurück', () => {+ it('ein entferntes Foto gibt seine Datei frei', () => {+ drop('a.png', 'b.png')+ expect(live.size).toBe(2)+ useCreateStore.getState().removeTrainImage('a.png')+ expect(live.size).toBe(1)+ })++ it('eine verworfene Dublette gibt ihre Datei frei', () => {+ // Zweimal denselben Ordner fallen lassen ist der Normalfall, nicht der+ // Sonderfall: der Nutzer sieht nicht, dass die Bilder schon drin sind.+ // Die Dublette bekommt in `addFiles` eine EIGENE, frische URL und wird+ // dann von der Namens-Dedupe weggeworfen — unerreichbar, aber gepinnt.+ drop('a.png')+ const kept = useCreateStore.getState().trainImages[0].url+ drop('a.png')+ expect(useCreateStore.getState().trainImages).toHaveLength(1)+ expect(live.has(kept)).toBe(true)+ expect(live.size).toBe(1)+ })++ it('was die 30er-Kappe abschneidet, gibt seine Datei frei', () => {+ // Diese Grenze hat gar keine UI: der Schnitt passiert still.+ drop(...Array.from({ length: 34 }, (_, i) => `f${i}.png`))+ expect(useCreateStore.getState().trainImages).toHaveLength(30)+ expect(live.size).toBe(30)+ })++ it('das Leeren des Sets gibt jede Datei zurück, die es hielt', () => {+ // `useCloudCreate` ruft clearTrainImages nach jedem abgeschickten+ // Trainingslauf — vorher blieb dabei der komplette Satz im Speicher.+ drop(...Array.from({ length: 12 }, (_, i) => `f${i}.png`))+ expect(live.size).toBe(12)+ useCreateStore.getState().clearTrainImages()+ expect(live.size).toBe(0)+ })++ it('was das Set behält, wird nicht widerrufen', () => {+ // Die Gegenprobe: ein Helfer, der zu viel freigibt, macht die Vorschau+ // im Board kaputt, und das sähe im Test oben genauso "grün" aus.+ drop('a.png', 'b.png', 'c.png')+ useCreateStore.getState().removeTrainImage('b.png')+ for (const img of useCreateStore.getState().trainImages) {+ expect(live.has(img.url)).toBe(true)+ }+ expect(live.size).toBe(2)+ })++ it('ein erneuter Anlauf desselben Sets stapelt nichts auf', () => {+ // Der gemessene Ablauf: 30 wählen, ersetzen (dieselben Namen nochmal),+ // eins entfernen, Ansicht wechseln (= Set leeren).+ drop(...Array.from({ length: 30 }, (_, i) => `f${i}.png`))+ drop(...Array.from({ length: 30 }, (_, i) => `f${i}.png`))+ useCreateStore.getState().removeTrainImage('f0.png')+ useCreateStore.getState().clearTrainImages()+ expect(minted).toBe(60)+ expect(live.size).toBe(0)+ })+})++describe('es gibt genau eine Stelle, die eine Slot-URL mintet', () => {+ it('kein Create-Modul baut sich seinen MediaRef selbst zusammen', () => {+ // Der eigentliche Befund war nicht "hier fehlt ein revoke", sondern+ // "der Mint ist kopiert und nur eine Kopie hat ein Gegenstück". Solange+ // jede Oberfläche ihren eigenen `{ name, url, blob }` bauen darf, kommt+ // der nächste Slot ohne Freigabe daneben. `mediaRef.ts` ist die eine+ // Stelle; sein Gegenstück ist `releaseDroppedMediaRefs` im Store.+ const root = join(__dirname, '..', '..')+ const files: string[] = []+ const walk = (dir: string) => {+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, e.name)+ if (e.isDirectory()) { if (e.name !== '__tests__') walk(full) }+ else if (/\.tsx?$/.test(e.name)) files.push(full)+ }+ }+ walk(root)+ const offenders = files.filter((f) =>+ /url:\s*URL\.createObjectURL/.test(readFileSync(f, 'utf8')))+ expect(offenders.map((f) => f.slice(root.length + 1))).toEqual(['experimental/mediaRef.ts'])+ })+})diff --git a/src/components/create/experimental/mediaRef.ts b/src/components/create/experimental/mediaRef.tsnew file mode 100644index 00000000..208931bf--- /dev/null+++ b/src/components/create/experimental/mediaRef.ts@@ -0,0 +1,25 @@+/**+ * Where a staged Create input file gets its `blob:` preview URL — and the only+ * place it does.+ *+ * A `blob:` URL pins its File in the renderer until somebody revokes it. This+ * module owns the BIRTH of such a URL; `createStore`'s `releaseDroppedMediaRefs`+ * owns its DEATH, and every slot that holds a `MediaRef` writes through a+ * setter that calls it. Two functions, one lifetime.+ *+ * That pairing is the point. Before T-76 the mint was copied inline into each+ * surface that needed one — SpecialIntentControls for the voice clip and the+ * driving video, Stage's training board for the photo set — and only the two+ * scalar slots had a release. The third surface leaked its whole set, and+ * nothing about the code said which of the three was the odd one out. Anyone+ * adding a fourth slot now finds a mint that has exactly one counterpart.+ *+ * Do NOT revoke here. The ref outlives the component that made it — it lives+ * in the store, and the store is what knows when it stops being reachable.+ */+import type { MediaRef } from '../../../stores/createStore'++/** A staged file plus the `blob:` preview URL that shows it. */+export function mediaRefFrom(file: File): MediaRef {+ return { name: file.name, url: URL.createObjectURL(file), blob: file }+}diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 5b43a68d..0c20a2bc 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -428,20 +428,42 @@ function releaseItemMedia(item: GalleryItem): void {}/**- * Replacing a staged input file must free the one it replaces.+ * A staged input file that stops being reachable must give its `blob:` URL back.*- * `mediaRefFrom` in SpecialIntentControls mints a fresh `blob:` URL for every- * pick, so re-choosing a driving video or a voice clip five times used to pin- * five files in the renderer with only the last one reachable. The lifetime is- * closed HERE rather than at the call site because these two setters are the- * only way a slot is ever written — a future caller cannot forget.+ * `mediaRefFrom` (`components/create/experimental/mediaRef.ts`) is the one place+ * such a URL is minted; this is the one place it dies. Everything a MediaRef+ * slot can do to a ref — replace it, clear it, drop it out of a set, refuse it+ * as a duplicate, cut it off past a cap — is the same event seen from a+ * different angle: it was in the slot before and it is not in the slot after.+ * So there is ONE rule, stated once, and every setter that writes a MediaRef+ * slot states its before and its after.+ *+ * The lifetime is closed HERE rather than at the call site because these+ * setters are the only way a slot is ever written — a future caller cannot+ * forget. That is what the previous, scalar-only version of this helper got+ * right for `audioInput` / `videoInput` and could not express for the third+ * slot, `trainImages`: an array whose members are dropped by a filter and by+ * a silent `.slice(0, 30)`, neither of which anybody was giving back.+ *+ * Membership is by URL, not by name: re-picking the same filename mints a+ * NEW URL, and the loser of that dedupe is exactly the one to revoke.** Only the preview URL is dropped; every consumer (local + cloud upload) reads- * `MediaRef.blob`, which is unaffected by revoking the URL.+ * `MediaRef.blob`, which is unaffected by revoking the URL. Non-`blob:` URLs+ * are left alone — they are not ours to revoke.*/+function releaseDroppedMediaRefs(previous: readonly MediaRef[], next: readonly MediaRef[]): void {+ if (previous.length === 0) return+ const kept = new Set(next.map((r) => r.url))+ for (const r of previous) {+ if (kept.has(r.url)) continue+ if (r.url.startsWith('blob:')) URL.revokeObjectURL(r.url)+ }+}++/** The same rule for a slot that holds at most one ref. */function releaseReplacedMediaRef(previous: MediaRef | null, next: MediaRef | null): void {- if (!previous || previous.url === next?.url) return- if (previous.url.startsWith('blob:')) URL.revokeObjectURL(previous.url)+ releaseDroppedMediaRefs(previous ? [previous] : [], next ? [next] : [])}export const useCreateStore = create<CreateState>()(@@ -695,13 +717,30 @@ export const useCreateStore = create<CreateState>()(setTargetResolution: (targetResolution) => set({ targetResolution }),setCharacterTab: (characterTab) => set({ characterTab }),// Cap at 30 (the server's image_paths limit) and de-dupe by filename so- // a re-drop of the same files doesn't double the set.- addTrainImages: (imgs) => set((s) => {- const have = new Set(s.trainImages.map((i) => i.name))- return { trainImages: [...s.trainImages, ...imgs.filter((i) => !have.has(i.name))].slice(0, 30) }- }),- removeTrainImage: (name) => set((s) => ({ trainImages: s.trainImages.filter((i) => i.name !== name) })),- clearTrainImages: () => set({ trainImages: [] }),+ // a re-drop of the same files doesn't double the set. Both of those+ // THROW REFS AWAY — the caller minted a blob: URL for every file it+ // handed over, including the ones landing in the dedupe and the ones+ // the cap cuts off, and neither is reachable from the store afterwards.+ // So "before" is everything in play, not just what was already staged.+ addTrainImages: (imgs) => {+ const before = get().trainImages+ const have = new Set(before.map((i) => i.name))+ const trainImages = [...before, ...imgs.filter((i) => !have.has(i.name))].slice(0, 30)+ releaseDroppedMediaRefs([...before, ...imgs], trainImages)+ set({ trainImages })+ },+ removeTrainImage: (name) => {+ const before = get().trainImages+ const trainImages = before.filter((i) => i.name !== name)+ releaseDroppedMediaRefs(before, trainImages)+ set({ trainImages })+ },+ // Called after every submitted training run (useCloudCreate.ts), which+ // is where the whole 30-photo set used to stay pinned for the session.+ clearTrainImages: () => {+ releaseDroppedMediaRefs(get().trainImages, [])+ set({ trainImages: [] })+ },setTriggerWord: (w) => set({ triggerWord: w.replace(/\s+/g, '').slice(0, 30) }),// Same clamp as the Rust command so the UI can never book a rejected run.setTrainSteps: (n) => set({ trainSteps: Math.max(100, Math.min(4000, Math.floor(n))) }),