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
fix(settings): Install- und Repair-Fortschritt ueberlebt den Bereichswechsel
purple23ab682fedc2
diff --git a/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts b/src/components/create/experimental/__tests__/comfy-env-selfheal.test.tsindex e9bbe59f..56675204 100644--- a/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts+++ b/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts@@ -19,6 +19,10 @@ import { fileURLToPath } from 'node:url'const hier = dirname(fileURLToPath(import.meta.url))const kontext = () => readFileSync(resolve(hier, '..', 'CreateContext.tsx'), 'utf8')const settings = () => readFileSync(resolve(hier, '..', '..', '..', 'settings', 'SettingsPage.tsx'), 'utf8')+// A13: der Lauf selbst wohnt seit dem Umbau im Store, damit ein Wechsel des+// Einstellungsbereichs den Fortschritt nicht mehr wegwirft. Der Knopf sitzt+// weiter in den Settings, das Kommando steht jetzt daneben.+const installStore = () => readFileSync(resolve(hier, '..', '..', '..', '..', 'stores', 'comfyInstallStore.ts'), 'utf8')describe('#98: die ComfyUI-Umgebung heilt sich selbst', () => {it('ein Absturz in der Wartschleife wird sofort erkannt, nicht als Timeout verbrannt', () => {@@ -40,8 +44,9 @@ describe('#98: die ComfyUI-Umgebung heilt sich selbst', () => {it('die Settings haben einen Repair-Knopf am selben Kommando', () => {const src = settings()- expect(src).toMatch(/repair_comfyui_env/)expect(src).toMatch(/Repair environment/)+ expect(src).toMatch(/runRepair\(\)/)+ expect(installStore()).toMatch(/backendCall\('repair_comfyui_env'\)/)})it('der Settings-Start meldet einen spaeten Absturz statt still auf Stopped zu kippen', () => {diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 32abd899..dcd324fc 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -53,6 +53,7 @@ import { ProviderSettings } from './ProviderConfig'import { BuiltinEngineSettings } from './BuiltinEngineSettings'import { MlxMediaSettings } from './MlxMediaSettings'import { useProviderStore } from '../../stores/providerStore'+import { useComfyInstallStore } from '../../stores/comfyInstallStore'import { PermissionSettings } from './PermissionSettings'import { MCPServerSettings } from './MCPServerSettings'import { WorkflowList } from '../agents/WorkflowList'@@ -479,15 +480,6 @@ function ImportLocalModels() {// ── ComfyUI Settings ────────────────────────────────────────────-// What the user is told once a cancelled run has really stopped. A cancel that-// leaves the panel blank reads as "nothing happened", and after a repair that-// is a lie: the venv is half rebuilt at that point.-export const COMFY_CANCEL_NOTICE = {- install: 'Install cancelled. ComfyUI is not set up yet, you can start the install again at any time.',- update: 'Update cancelled. ComfyUI may be updated only in part, so run Update ComfyUI again to finish it.',- repair: 'Repair cancelled. The environment is only half rebuilt, so run Repair environment again before you start ComfyUI.',-} as const-export function ComfyUISettings() {const [status, setStatus] = useState<{ running: boolean; found: boolean; complete?: boolean; path?: string; port?: number; host?: string; isLocal?: boolean; starting?: boolean; stalled?: boolean } | null>(null)// Why the last start attempt did not stick. The button used to swallow this@@ -505,17 +497,18 @@ export function ComfyUISettings() {const [customHost, setCustomHost] = useState('')const [hostError, setHostError] = useState('')const [hostSuccess, setHostSuccess] = useState(false)- // P14 Python install state for the Settings Install-ComfyUI flow.- const [installPhase, setInstallPhase] = useState<'idle' | 'python' | 'comfyui' | 'repair' | 'error'>('idle')- const [installLogs, setInstallLogs] = useState<string[]>([])- const [installErr, setInstallErr] = useState('')+ // A13 (Windows counter-check 2026-09-02): install, update and repair used to+ // keep their phase, their log lines and their byte counters in this+ // component. Switching to another settings section threw all of it away+ // while pip kept running, and coming back showed an empty panel. The run now+ // reports into a store that outlives the mount, and this panel is a reader.+ const installPhase = useComfyInstallStore((s) => s.phase)+ const installLogs = useComfyInstallStore((s) => s.logs)+ const installErr = useComfyInstallStore((s) => s.error)// #162: size, rate and remaining time in the bracket next to the spinner.- const [installDl, setInstallDl] = useState({ progress: 0, total: 0, speed: 0 })- // A13 (Windows counter-check 2026-09-02): Onboarding could stop a running- // install, Settings could not. A repair takes 20 minutes and pulls two- // gigabytes of PyTorch, and the only way out of it was killing the app.- const [cancelling, setCancelling] = useState(false)- const [installNotice, setInstallNotice] = useState('')+ const installDl = useComfyInstallStore((s) => s.dl)+ const cancelling = useComfyInstallStore((s) => s.cancelling)+ const installNotice = useComfyInstallStore((s) => s.notice)useEffect(() => {let cancelled = false@@ -568,61 +561,15 @@ export function ComfyUISettings() {// same status contract the installer uses, so the progress card just works.const handleRepair = async () => {setStartError('')- setInstallPhase('repair')- setInstallLogs(['Repairing the ComfyUI environment…'])- setInstallDl({ progress: 0, total: 0, speed: 0 })- setCancelling(false)- setInstallNotice('')- try {- const { backendCall } = await import('../../api/backend')- await backendCall('repair_comfyui_env')- const poll = setInterval(async () => {- try {- const data: any = await backendCall('install_comfyui_status')- setInstallLogs(data.logs || [])- setInstallDl({ progress: data.download_progress || 0, total: data.download_total || 0, speed: data.download_speed || 0 })- if (data.status === 'complete') {- clearInterval(poll)- setCancelling(false)- setInstallPhase('idle')- } else if (data.status === 'cancelled') {- // A cancel the user asked for is not a failure, and it must leave a- // sentence behind: the venv is half rebuilt at this point.- clearInterval(poll)- setCancelling(false)- setInstallPhase('idle')- setInstallNotice(COMFY_CANCEL_NOTICE.repair)- } else if (data.status === 'error') {- clearInterval(poll)- setCancelling(false)- const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string- setInstallErr(withInstallerOutput('Repairing the environment did not finish.', lastLog))- setInstallPhase('error')- }- } catch { /* keep polling */ }- }, 2000)- } catch (err) {- setInstallPhase('error')- setInstallErr(err instanceof Error ? err.message : 'Failed to start the repair')- }+ await useComfyInstallStore.getState().runRepair()}// One button for every long run this panel starts. Rust checks the same flag// in every step of the installer and of the repair, so the run stops at the// next step boundary; until it does, the panel says it is cancelling instead// of pretending the click did nothing.- const handleCancelInstall = async () => {- if (cancelling) return- setCancelling(true)- try {- const { backendCall } = await import('../../api/backend')- await backendCall('cancel_comfyui_install')- } catch (err) {- // The flag is the only thing that can stop the run. If setting it failed,- // a button stuck on "Cancelling…" would be the second lie in a row.- setCancelling(false)- setInstallErr(err instanceof Error ? err.message : 'Could not cancel the run')- }+ const handleCancelInstall = () => {+ void useComfyInstallStore.getState().cancel()}const handleStop = async () => {@@ -808,89 +755,13 @@ export function ComfyUISettings() {)}{(!status?.found || status?.complete === false) && installPhase === 'idle' && (<button- onClick={async () => {- const { backendCall } = await import('../../api/backend')- setInstallErr('')- setInstallLogs([])- setCancelling(false)- setInstallNotice('')-- // P14 pre-flight: ensure Python is on the box before- // pip-installing ComfyUI. The carcass case (status.complete- // === false) lands here too — Python may still be missing- // and the previous run died on the Microsoft Store stub.- let pythonOk = false- try {- const probe: any = await backendCall('python_check')- pythonOk = !!probe?.available- } catch { pythonOk = false }-- if (!pythonOk) {- setInstallPhase('python')- setInstallLogs(['Installing Python 3.12 via winget…'])- try {- await backendCall('install_python')- } catch (err) {- setInstallPhase('error')- setInstallErr(err instanceof Error ? err.message : 'Could not start Python install')- return- }- pythonOk = await new Promise<boolean>((resolve) => {- const poll = setInterval(async () => {- try {- const data: any = await backendCall('install_python_status')- setInstallLogs(data.logs || [])- if (data.status === 'complete' || data.status === 'already_installed') {- clearInterval(poll); resolve(true)- } else if (data.status === 'error') {- clearInterval(poll)- const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string- setInstallErr(withInstallerOutput('Installing Python did not finish.', lastLog))- resolve(false)- }- } catch { /* keep polling */ }- }, 2000)- })- if (!pythonOk) { setInstallPhase('error'); return }- }-- setInstallPhase('comfyui')- setInstallLogs(['Installing ComfyUI…'])- try {- // andy_38747 (Discord): let the Path field double as the install- // target so the multi-GB install can land on another drive.- // Empty field → backend default (~/ComfyUI). On a carcass- // re-install with no override, reuse the detected path so the- // repair happens where the broken install lives.- const installTarget = customPath.trim() || status?.path || ''- await backendCall('install_comfyui', installTarget ? { installPath: installTarget } : {})- const poll = setInterval(async () => {- try {- const data: any = await backendCall('install_comfyui_status')- setInstallLogs(data.logs || [])- setInstallDl({ progress: data.download_progress || 0, total: data.download_total || 0, speed: data.download_speed || 0 })- if (data.status === 'complete') {- clearInterval(poll)- setCancelling(false)- setInstallPhase('idle')- } else if (data.status === 'cancelled') {- clearInterval(poll)- setCancelling(false)- setInstallPhase('idle')- setInstallNotice(COMFY_CANCEL_NOTICE.install)- } else if (data.status === 'error') {- clearInterval(poll)- setCancelling(false)- const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string- setInstallErr(withInstallerOutput('Installing ComfyUI did not finish.', lastLog))- setInstallPhase('error')- }- } catch { /* keep polling */ }- }, 2000)- } catch (err) {- setInstallPhase('error')- setInstallErr(err instanceof Error ? err.message : 'Failed to start')- }+ onClick={() => {+ // andy_38747 (Discord): let the Path field double as the install+ // target so the multi-GB install can land on another drive.+ // Empty field means the backend default (~/ComfyUI). On a carcass+ // re-install with no override, reuse the detected path so the+ // repair happens where the broken install lives.+ void useComfyInstallStore.getState().runInstall(customPath.trim() || status?.path || '')}}className="px-2 py-1 rounded text-[0.6rem] bg-purple-500/10 text-purple-400 hover:bg-purple-500/20 transition-colors">@@ -903,42 +774,7 @@ export function ComfyUISettings() {// the one-click git pull + dependency refresh the lane errors point// to. Reuses the installer's status channel and log panel.<button- onClick={async () => {- setInstallPhase('comfyui')- setInstallErr('')- setInstallLogs(['Updating ComfyUI…'])- setCancelling(false)- setInstallNotice('')- try {- await backendCall('update_comfyui')- const poll = setInterval(async () => {- try {- const data: any = await backendCall('install_comfyui_status')- setInstallLogs(data.logs || [])- setInstallDl({ progress: data.download_progress || 0, total: data.download_total || 0, speed: data.download_speed || 0 })- if (data.status === 'complete') {- clearInterval(poll)- setCancelling(false)- setInstallPhase('idle')- } else if (data.status === 'cancelled') {- clearInterval(poll)- setCancelling(false)- setInstallPhase('idle')- setInstallNotice(COMFY_CANCEL_NOTICE.update)- } else if (data.status === 'error') {- clearInterval(poll)- setCancelling(false)- const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string- setInstallErr(withInstallerOutput('Updating ComfyUI did not finish.', lastLog))- setInstallPhase('error')- }- } catch { /* keep polling */ }- }, 2000)- } catch (err) {- setInstallPhase('error')- setInstallErr(err instanceof Error ? err.message : 'Failed to start the update')- }- }}+ onClick={() => { void useComfyInstallStore.getState().runUpdate() }}className="px-2 py-1 rounded text-[0.6rem] bg-white/5 text-gray-400 hover:text-gray-200 hover:bg-white/10 transition-colors">Update ComfyUIdiff --git a/src/components/settings/__tests__/comfy-install-cancel.test.ts b/src/components/settings/__tests__/comfy-install-cancel.test.tsindex 73a68ad9..53e204a7 100644--- a/src/components/settings/__tests__/comfy-install-cancel.test.ts+++ b/src/components/settings/__tests__/comfy-install-cancel.test.ts@@ -30,12 +30,15 @@ vi.mock('../../../api/backend', () => ({setComfyHost: vi.fn(),}))-const { ComfyUISettings, COMFY_CANCEL_NOTICE } = await import('../SettingsPage')+const { ComfyUISettings } = await import('../SettingsPage')+const { COMFY_CANCEL_NOTICE, useComfyInstallStore } = await import('../../../stores/comfyInstallStore')/** What `install_comfyui_status` answers next. */let installStatus: { status: string; logs: string[] } = { status: 'installing', logs: ['pip install torch'] }beforeEach(() => {+ // The run outlives the mount now, so it also outlives a test.+ useComfyInstallStore.getState().reset()installStatus = { status: 'installing', logs: ['pip install torch'] }backendCall.mockReset()backendCall.mockImplementation(async (cmd: string) => {@@ -46,7 +49,7 @@ beforeEach(() => {return {}})})-afterEach(() => { cleanup(); vi.useRealTimers() })+afterEach(() => { cleanup(); useComfyInstallStore.getState().reset(); vi.useRealTimers() })/** Mount the panel and get past the "Checking..." first status read. */async function mountPanel() {diff --git a/src/components/settings/__tests__/comfy-install-survives-remount.test.ts b/src/components/settings/__tests__/comfy-install-survives-remount.test.tsnew file mode 100644index 00000000..a30271f1--- /dev/null+++ b/src/components/settings/__tests__/comfy-install-survives-remount.test.ts@@ -0,0 +1,115 @@+/**+ * @vitest-environment jsdom+ *+ * A13, Windows counter-check 2026-09-02, side finding on the repair run:+ * "wer waehrend des Repairs den Einstellungsbereich wechselt, verliert den+ * Fortschrittstext; beim Zurueckkommen steht dort nichts mehr, obwohl pip+ * weiterlaeuft".+ *+ * The run was never in the component. What was in the component was the phase,+ * the log lines and the byte counters, so leaving the section threw away every+ * word about a twenty minute, two gigabyte rebuild that kept going in Rust.+ *+ * This mounts the panel, starts a repair, unmounts it the way the settings+ * navigation does, lets the poll tick while nothing is on screen, and mounts it+ * again.+ *+ * Run: npx vitest run src/components/settings/__tests__/comfy-install-survives-remount.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { createElement } from 'react'+import { render, screen, fireEvent, cleanup, act } from '@testing-library/react'++const backendCall = vi.fn()+vi.mock('../../../api/backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+ isTauri: () => true,+ isMacOS: () => false,+ openExternal: vi.fn(),+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),+ secretSet: vi.fn(),+ secretDelete: vi.fn(),+ setComfyPort: vi.fn(),+ setComfyHost: vi.fn(),+}))++const { ComfyUISettings } = await import('../SettingsPage')+const { useComfyInstallStore, comfyInstallPolling } = await import('../../../stores/comfyInstallStore')++let installStatus: { status: string; logs: string[]; download_progress?: number; download_total?: number } =+ { status: 'installing', logs: ['Step 1/4: Creating a fresh isolated venv...'] }++beforeEach(() => {+ useComfyInstallStore.getState().reset()+ installStatus = { status: 'installing', logs: ['Step 1/4: Creating a fresh isolated venv...'] }+ backendCall.mockReset()+ backendCall.mockImplementation(async (cmd: string) => {+ if (cmd === 'comfyui_status') return { running: false, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true }+ if (cmd === 'install_comfyui_status') return installStatus+ if (cmd === 'repair_comfyui_env') return { status: 'installing' }+ return {}+ })+})+afterEach(() => { cleanup(); useComfyInstallStore.getState().reset(); vi.useRealTimers() })++async function mountPanel() {+ const view = render(createElement(ComfyUISettings))+ await act(async () => { await Promise.resolve(); await Promise.resolve() })+ return view+}++describe('a repair started in Settings survives leaving the section', () => {+ it('shows the same phase and the newest log line after a remount', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ const first = await mountPanel()+ await act(async () => { fireEvent.click(screen.getByText('Repair environment')) })+ expect(screen.getByText(/Rebuilding the ComfyUI environment/)).toBeTruthy()++ // The user opens Providers: this panel goes away entirely.+ first.unmount()++ // pip does not care. Two more ticks arrive with nothing on screen.+ installStatus = {+ status: 'installing',+ logs: ['Step 2/4: Downloading PyTorch into the fresh venv (~2 GB).'],+ download_progress: 500_000_000,+ download_total: 2_000_000_000,+ }+ await act(async () => { await vi.advanceTimersByTimeAsync(4000) })+ expect(comfyInstallPolling()).toBe(true)++ // Back to AI Backends.+ await mountPanel()+ expect(screen.getByText(/Rebuilding the ComfyUI environment/)).toBeTruthy()+ expect(screen.getByText('Step 2/4: Downloading PyTorch into the fresh venv (~2 GB).')).toBeTruthy()+ // The download counters came along too, they are part of that line.+ expect(screen.getByText(/of 1.9 GB/)).toBeTruthy()+ })++ it('lets the remounted panel finish the run and stop the poll', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ const first = await mountPanel()+ await act(async () => { fireEvent.click(screen.getByText('Repair environment')) })+ first.unmount()++ installStatus = { status: 'complete', logs: ['Environment repaired.'] }+ await act(async () => { await vi.advanceTimersByTimeAsync(2000) })+ expect(comfyInstallPolling()).toBe(false)++ await mountPanel()+ expect(screen.getByText('Repair environment')).toBeTruthy()+ expect(screen.queryByText(/Rebuilding the ComfyUI environment/)).toBeNull()+ })++ it('starts no second poll when the panel is mounted twice', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ const first = await mountPanel()+ await act(async () => { fireEvent.click(screen.getByText('Repair environment')) })+ const before = backendCall.mock.calls.filter(([cmd]) => cmd === 'install_comfyui_status').length+ first.unmount()+ await mountPanel()+ await act(async () => { await vi.advanceTimersByTimeAsync(2000) })+ // One tick, one status read. A poll per mount would double this.+ expect(backendCall.mock.calls.filter(([cmd]) => cmd === 'install_comfyui_status').length).toBe(before + 1)+ })+})diff --git a/src/stores/comfyInstallStore.ts b/src/stores/comfyInstallStore.tsnew file mode 100644index 00000000..7ad276bb--- /dev/null+++ b/src/stores/comfyInstallStore.ts@@ -0,0 +1,248 @@+// A13, Windows counter-check 2026-09-02: "wer waehrend des Repairs den+// Einstellungsbereich wechselt, verliert den Fortschrittstext; beim+// Zurueckkommen steht dort nichts mehr, obwohl pip weiterlaeuft".+//+// The run itself was never the problem. It lives in Rust, and the poll is a+// plain setInterval that no unmount ever touched. What died was the STATE: the+// phase, the log lines and the download counters sat in useState inside the+// ComfyUI panel, so switching to Providers and back left a panel that knew+// nothing while a two gigabyte PyTorch download kept going.+//+// So the state moves here, next to the timer that feeds it. Runtime only, on+// purpose: an install that is over when the app restarts must not come back as+// a ghost on the next start, which is exactly what persisting it would do.++import { create } from 'zustand'+import { backendCall } from '../api/backend'+import { withInstallerOutput } from '../lib/error-text'++/** Which card the panel draws. `python` is the pre-flight winget step. */+export type ComfyInstallPhase = 'idle' | 'python' | 'comfyui' | 'repair' | 'error'++/** Which long run is in flight. Install and update share the `comfyui` phase,+ * and they need different sentences when they end. */+export type ComfyInstallKind = 'install' | 'update' | 'repair'++/** What the user is told once a cancelled run has really stopped. A cancel+ * that leaves the panel blank reads as "nothing happened", and after a repair+ * that is a lie: the venv is half rebuilt at that point. */+export const COMFY_CANCEL_NOTICE: Record<ComfyInstallKind, string> = {+ install: 'Install cancelled. ComfyUI is not set up yet, you can start the install again at any time.',+ update: 'Update cancelled. ComfyUI may be updated only in part, so run Update ComfyUI again to finish it.',+ repair: 'Repair cancelled. The environment is only half rebuilt, so run Repair environment again before you start ComfyUI.',+}++/** Headline of the failure text per run. The installer's own last log line is+ * appended to it, which is where the actual pip or git error shows up. */+const FAILED: Record<ComfyInstallKind, string> = {+ install: 'Installing ComfyUI did not finish.',+ update: 'Updating ComfyUI did not finish.',+ repair: 'Repairing the environment did not finish.',+}++const POLL_MS = 2000++/** The one poll in flight, module level so it outlives every mount. */+let timer: ReturnType<typeof setInterval> | null = null++function stopTimer() {+ if (timer) {+ clearInterval(timer)+ timer = null+ }+}++/** True while a poll is running. Tests read this to prove the loop is not tied+ * to a component. */+export function comfyInstallPolling(): boolean {+ return timer !== null+}++interface InstallStatusPayload {+ status?: string+ logs?: string[]+ download_progress?: number+ download_total?: number+ download_speed?: number+}++interface ComfyInstallState {+ phase: ComfyInstallPhase+ kind: ComfyInstallKind | null+ logs: string[]+ dl: { progress: number; total: number; speed: number }+ error: string+ /** Cancel requested, run not stopped yet. */+ cancelling: boolean+ /** The one line left behind after a cancelled run. */+ notice: string+ /** Install ComfyUI, installing Python first when the box has none. */+ runInstall: (installPath: string) => Promise<void>+ /** git pull plus a dependency refresh on an existing checkout. */+ runUpdate: () => Promise<void>+ /** Rebuild the venv from scratch. */+ runRepair: () => Promise<void>+ /** Ask Rust to stop whatever is running. */+ cancel: () => Promise<void>+ /** Back to a clean panel. Used by tests and by a fresh start. */+ reset: () => void+}++const IDLE = {+ phase: 'idle' as ComfyInstallPhase,+ kind: null,+ logs: [] as string[],+ dl: { progress: 0, total: 0, speed: 0 },+ error: '',+ cancelling: false,+ notice: '',+}++export const useComfyInstallStore = create<ComfyInstallState>()((set, get) => {+ /** Poll `install_comfyui_status` until the run reaches a terminal state.+ * Complete, cancelled and failed are three different answers, and the panel+ * says which one it was. */+ const watch = (kind: ComfyInstallKind) => {+ stopTimer()+ timer = setInterval(async () => {+ let data: InstallStatusPayload+ try {+ data = (await backendCall<InstallStatusPayload>('install_comfyui_status')) ?? {}+ } catch {+ return // transient, the next tick asks again+ }+ set({+ logs: data.logs ?? [],+ dl: {+ progress: data.download_progress || 0,+ total: data.download_total || 0,+ speed: data.download_speed || 0,+ },+ })+ if (data.status === 'complete') {+ stopTimer()+ set({ phase: 'idle', kind: null, cancelling: false })+ } else if (data.status === 'cancelled') {+ // A cancel the user asked for is not a failure.+ stopTimer()+ set({ phase: 'idle', kind: null, cancelling: false, notice: COMFY_CANCEL_NOTICE[kind] })+ } else if (data.status === 'error') {+ stopTimer()+ const lastLog = data.logs?.length ? String(data.logs[data.logs.length - 1]) : ''+ set({ phase: 'error', cancelling: false, error: withInstallerOutput(FAILED[kind], lastLog) })+ }+ }, POLL_MS)+ }++ const begin = (phase: ComfyInstallPhase, kind: ComfyInstallKind, firstLog: string) => {+ stopTimer()+ set({ ...IDLE, phase, kind, logs: firstLog ? [firstLog] : [] })+ }++ const fail = (message: string) => {+ stopTimer()+ set({ phase: 'error', cancelling: false, error: message })+ }++ return {+ ...IDLE,++ runInstall: async (installPath: string) => {+ begin('python', 'install', '')+ // Pre-flight: pip needs a Python before ComfyUI can be installed. The+ // carcass case lands here too, the previous run may have died on the+ // Microsoft Store stub.+ let pythonOk = false+ try {+ const probe = await backendCall<{ available?: boolean }>('python_check')+ pythonOk = !!probe?.available+ } catch {+ pythonOk = false+ }+ if (!pythonOk) {+ set({ logs: ['Installing Python 3.12 via winget…'] })+ try {+ await backendCall('install_python')+ } catch (err) {+ fail(err instanceof Error ? err.message : 'Could not start Python install')+ return+ }+ pythonOk = await new Promise<boolean>((resolve) => {+ stopTimer()+ timer = setInterval(async () => {+ let data: InstallStatusPayload+ try {+ data = (await backendCall<InstallStatusPayload>('install_python_status')) ?? {}+ } catch {+ return+ }+ set({ logs: data.logs ?? [] })+ if (data.status === 'complete' || data.status === 'already_installed') {+ stopTimer()+ resolve(true)+ } else if (data.status === 'error') {+ stopTimer()+ const lastLog = data.logs?.length ? String(data.logs[data.logs.length - 1]) : ''+ set({ error: withInstallerOutput('Installing Python did not finish.', lastLog) })+ resolve(false)+ }+ }, POLL_MS)+ })+ if (!pythonOk) {+ set({ phase: 'error', cancelling: false })+ return+ }+ }+ set({ phase: 'comfyui', logs: ['Installing ComfyUI…'] })+ try {+ await backendCall('install_comfyui', installPath ? { installPath } : {})+ } catch (err) {+ fail(err instanceof Error ? err.message : 'Failed to start')+ return+ }+ watch('install')+ },++ runUpdate: async () => {+ begin('comfyui', 'update', 'Updating ComfyUI…')+ try {+ await backendCall('update_comfyui')+ } catch (err) {+ fail(err instanceof Error ? err.message : 'Failed to start the update')+ return+ }+ watch('update')+ },++ runRepair: async () => {+ begin('repair', 'repair', 'Repairing the ComfyUI environment…')+ try {+ await backendCall('repair_comfyui_env')+ } catch (err) {+ fail(err instanceof Error ? err.message : 'Failed to start the repair')+ return+ }+ watch('repair')+ },++ // Rust checks the same flag in every step of the installer and of the+ // repair, so the run stops at the next step boundary. Until it does, the+ // panel says it is cancelling instead of pretending the click did nothing.+ cancel: async () => {+ if (get().cancelling) return+ set({ cancelling: true })+ try {+ await backendCall('cancel_comfyui_install')+ } catch (err) {+ // The flag is the only thing that can stop the run. If setting it+ // failed, a button stuck on "Cancelling…" would be the second lie.+ set({ cancelling: false, error: err instanceof Error ? err.message : 'Could not cancel the run' })+ }+ },++ reset: () => {+ stopTimer()+ set({ ...IDLE })+ },+ }+})