AI media harness for planning, generating, and editing locally
TypeScript
Wire agent/export close; guard and queue running exports
Bitti57773666aabe
diff --git a/src/App.test.tsx b/src/App.test.tsxindex ad1487c..c165cc6 100644--- a/src/App.test.tsx+++ b/src/App.test.tsx@@ -236,6 +236,12 @@ describe("project library controls", () => {expect(screen.getByRole("textbox", { name: /Ask Slop about/ })).toBe(draft);expect(draft).toHaveValue("Keep this unfinished idea");await waitFor(() => expect(screen.getByRole("button", { name: "Settings" })).toHaveFocus());+ // The pane header's close button hides the pane and hands focus back to+ // the title-bar toggle.+ fireEvent.click(within(pane).getByRole("button", { name: "Close agent" }));+ expect(pane).not.toBeVisible();+ expect(screen.getByRole("button", { name: "Agent" })).toHaveAttribute("aria-pressed", "false");+ expect(screen.getByRole("button", { name: "Agent" })).toHaveFocus();});it("creates an empty project when the new-project form is left blank", async () => {diff --git a/src/App.tsx b/src/App.tsxindex 5f6613c..bb4a0ab 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -17,6 +17,7 @@ import { CommandBar, CommandBarButton, CommandBarSeparator, InfoBadge, InfoBar,import { AppUpdater } from "./lib/updater";import { useShortcut } from "./lib/commands";import { useGuardedShortcut } from "./lib/shellKeys";+import { useRunningExportName } from "./lib/exportJob";import { reportGenerationJobs, revealInExplorer, type GuardJob } from "./lib/nativeShell";import { describeDiagnosticError, errorContext, writeDiagnostic } from "./lib/diagnostics";import { chooseAndOpenProject, chooseNewProjectFolder, inspectNewProjectFolder, createProject, deleteProject, isTauri, listRecentProjects, saveProject, type NewProjectFolder } from "./lib/persistence";@@ -137,6 +138,10 @@ function App() {const guardJobs: GuardJob[] = workItems.filter((item) => item.kind !== "reference-icons" && isWorkActive(item)).map((item) => ({ title: `${item.title} · ${item.projectName}`, running: item.status !== "queued" }));+ /* An export keeps running when its tab (or its project) is left, and+ closing the window ends it just the same, so it is on the list too. */+ const exportingName = useRunningExportName();+ if (exportingName !== null) guardJobs.push({ title: exportingName ? `Export ${exportingName}` : "Export", running: true });const guardKey = JSON.stringify(guardJobs);useEffect(() => {void reportGenerationJobs(JSON.parse(guardKey) as GuardJob[]).catch(() => undefined);diff --git a/src/WorkQueue.integration.test.tsx b/src/WorkQueue.integration.test.tsxindex 8d2c98e..36b7466 100644--- a/src/WorkQueue.integration.test.tsx+++ b/src/WorkQueue.integration.test.tsx@@ -10,6 +10,7 @@ import { createProjectConfig, type ProjectRecord } from "./lib/project";import { enqueueSlopfabGeneration, type SlopfabStatus } from "./lib/runtime";import { loadReferenceIconAutomation } from "./lib/referenceIconSettings";import { reportGenerationJobs } from "./lib/nativeShell";+import { getExportJob, resetExportJobForTests, setExportJobForTests } from "./lib/exportJob";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(async () => undefined) }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));@@ -31,7 +32,7 @@ beforeEach(() => {vi.mocked(saveProject).mockImplementation(async (record) => record);vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/queued-result.mp4", bytes: 42, note: null });});-afterEach(() => { cleanup(); vi.restoreAllMocks(); });+afterEach(() => { cleanup(); vi.restoreAllMocks(); resetExportJobForTests(); });it("keeps icon confirmation available after returning to the library", async () => {const config = createProjectConfig({ name: "Icon project", prompt: "A quiet scene", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 });@@ -115,3 +116,28 @@ it("opens an empty queue from the library and closes it with Escape", async () =expect(screen.queryByRole("dialog", { name: "Work queue" })).toBeNull();expect(document.activeElement).toBe(trigger);});++it("guards the window for a running export and lists it in the queue with a Cancel action", async () => {+ vi.mocked(listRecentProjects).mockResolvedValue({ projects: [], unreadable: [] });+ render(<App />);+ expect(vi.mocked(reportGenerationJobs).mock.calls.every(([jobs]) => jobs.length === 0)).toBe(true);+ act(() => setExportJobForTests({+ folderPath: "C:/Film", projectName: "Film", destination: "C:/out/film.mp4",+ progress: { phase: "rendering", framesDone: 18, frameCount: 72, detail: "Rendering frame 18 of 72." },+ }));+ await waitFor(() => expect(reportGenerationJobs).toHaveBeenLastCalledWith([{ title: "Export Film", running: true }]));+ const trigger = screen.getByRole("button", { name: /^Work queue/ });+ fireEvent.click(trigger);+ const flyout = screen.getByRole("dialog", { name: "Work queue" });+ const region = within(flyout).getByRole("region", { name: "Export" });+ expect(region).toHaveTextContent("Export Film");+ expect(region).toHaveTextContent("25%");+ expect(within(region).getByRole("progressbar", { name: "Export Film progress" })).toBeInTheDocument();+ const cancel = within(region).getByRole("button", { name: "Cancel Export Film" });+ fireEvent.click(cancel);+ expect(getExportJob().cancelling).toBe(true);+ expect(cancel).toBeDisabled();+ act(() => setExportJobForTests({ progress: null, cancelling: false, outcome: { kind: "cancelled" } }));+ expect(within(flyout).queryByRole("region", { name: "Export" })).toBeNull();+ await waitFor(() => expect(reportGenerationJobs).toHaveBeenLastCalledWith([]));+});diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsxindex 8665ae0..391b5d0 100644--- a/src/components/ProjectWorkspace.tsx+++ b/src/components/ProjectWorkspace.tsx@@ -249,7 +249,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime ={view === "timeline" && <TimelineView config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} onChange={changeConfig} onMeasured={recordMeasurement} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView(imageProject ? "editor" : "generator"); }} />}{view === "generator" && <GeneratorView onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}{view === "references" && <ReferencesView config={config} folderPath={project.folderPath} onChange={changeConfig} onRegenerateIcon={(id) => queue.regenerateReferenceIcon(session, id)} onGenerateBuiltinIcons={() => queue.generateBuiltinReferenceIcons(session)} onRegenerateBuiltinIcon={(id) => queue.regenerateBuiltinReferenceIcon(session, id)} pendingBuiltinIconIds={queue.pendingBuiltinIconIds()} pendingIconIds={new Set(config.references.filter((reference) => queue.isReferenceIconPending(session, reference.id)).map((reference) => reference.id))} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}- {view === "export" && <ExportView config={config} folderPath={project.folderPath} />}+ {view === "export" && <ExportView config={config} folderPath={project.folderPath} onClose={() => setView("timeline")} />}</div>{agentOpen && <Splitter {...agentPane.splitterProps} reverse aria-label="Resize agent pane" aria-controls={`${panelId}-agent`} />}{/* Kept mounted while hidden, so a running turn and the conversation@@ -259,7 +259,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =context={view === "editor" ? "this image composition" : view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : view === "references" ? "project references" : "this export"}record={{ ...project, config }}providers={runtime?.providers ?? CHECKING_PROVIDERS}- expanded+ onClose={() => { setAgentOpen(false); agentToggle.current?.focus(); }}onPromptStart={() => { if (!agentOpen) setAgentOpen(true); }}/* The provider only proposes typed commands. Apply them to the session'slatest state—edits can continue while it thinks—as one undo step, thendiff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsxindex a944d50..45592af 100644--- a/src/components/WorkQueuePanel.tsx+++ b/src/components/WorkQueuePanel.tsx@@ -1,8 +1,9 @@-import { Check, Clock3, Download, ListTodo, TriangleAlert, X } from "lucide-react";+import { Check, Clock3, Download, Film, ListTodo, TriangleAlert, X } from "lucide-react";import { useState, useSyncExternalStore, type RefObject } from "react";import { GENERATION_FRAME_RATE } from "../lib/project";import { isWorkActive, type WorkItem, type WorkQueue } from "../lib/workQueue";import { loadGeneratorTemplateSettings } from "../lib/settings";+import { cancelExportJob, exportFraction, useExportJob } from "../lib/exportJob";import { cancelWeightDownload, retryWeightDownload, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";import { Flyout, ProgressBar, ProgressRing } from "./ui";@@ -36,6 +37,12 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onCloconst download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);const [downloadError, setDownloadError] = useState<string | null>(null);const downloadName = download ? download.name ?? loadGeneratorTemplateSettings().templates.find((template) => template.id === download.templateId)?.name ?? "Generator weights" : "";+ /* A running export lives in lib/exportJob.ts, not in the generation queue;+ it is shown here so it can be followed (and stopped) from anywhere. */+ const exportJob = useExportJob();+ const exporting = exportJob.progress;+ const exportTitle = exportJob.projectName ? `Export ${exportJob.projectName}` : "Export";+ const exportPercent = Math.floor(exportFraction(exporting) * 100);const current = items.filter((item) => isWorkActive(item) && item.status !== "queued");const upcoming = items.filter((item) => item.status === "queued").sort((a, b) => Number(a.kind === "reference-icons") - Number(b.kind === "reference-icons"));const finished = items.filter((item) => !isWorkActive(item)).slice().reverse();@@ -64,8 +71,17 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClo{finished.length > 0 && <button type="button" className="work-queue__link" onClick={() => queue.clearFinished()}>Clear finished</button>}</header><div className="work-queue__list">- {items.length === 0 && !download && <div className="work-queue__empty"><ListTodo size={32} aria-hidden="true" /><strong>No work yet</strong><span>Generated scenes and images show up here.</span></div>}+ {items.length === 0 && !download && !exporting && <div className="work-queue__empty"><ListTodo size={32} aria-hidden="true" /><strong>No work yet</strong><span>Generated scenes and images show up here.</span></div>}{current.length > 0 && <section aria-label="In progress"><ul>{current.map(row)}</ul></section>}+ {exporting && <section aria-label="Export"><ul><li className="work-queue__row">+ <span className="work-queue__state work-queue__state--preparing" aria-hidden="true"><Film size={16} /></span>+ <div className="work-queue__text">+ <span className="work-queue__title" data-tooltip={exportJob.destination ?? undefined}>{exportTitle}</span>+ <span className="work-queue__caption">{exporting.detail || "Exporting"} · {exportPercent}%</span>+ <ProgressBar value={exportPercent} aria-label={`${exportTitle} progress`} className="work-queue__progress" />+ </div>+ <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${exportTitle}`} data-tooltip="Cancel" disabled={exportJob.cancelling} onClick={cancelExportJob}><X size={16} /></button>+ </li></ul></section>}{download && <section aria-label="Weight downloads"><ul><li className="work-queue__row"><span className={`work-queue__state work-queue__state--${download.active ? "preparing" : download.error ? "failed" : "completed"}`} aria-hidden="true">{download.active ? <Download size={16} /> : download.error ? <TriangleAlert size={16} /> : <Check size={16} />}diff --git a/src/lib/exportJob.ts b/src/lib/exportJob.tsindex 27a0806..56d9df1 100644--- a/src/lib/exportJob.ts+++ b/src/lib/exportJob.ts@@ -25,15 +25,19 @@ export type ExportOutcome =export interface ExportJobState {/** The project folder the run (or its outcome) belongs to. */folderPath: string | null;+ /** The project's name, for the work queue and the exit guard. */+ projectName: string | null;destination: string | null;progress: ExportProgress | null;/** Milliseconds left, estimated from the frame rate so far. Null until* enough frames have been rendered to say. */remainingMs: number | null;outcome: ExportOutcome | null;+ /** Cancel was asked for and the run has not stopped yet. */+ cancelling: boolean;}-const IDLE: ExportJobState = { folderPath: null, destination: null, progress: null, remainingMs: null, outcome: null };+const IDLE: ExportJobState = { folderPath: null, projectName: null, destination: null, progress: null, remainingMs: null, outcome: null, cancelling: false };let state: ExportJobState = IDLE;let cancelRequested = false;@@ -59,6 +63,15 @@ export function useExportJob(): ExportJobState {export const isExportRunning = () => state.progress !== null;+const runningName = () => state.progress ? state.projectName ?? "" : null;++/** The running export's project name ("" when it has none), or null when+ * nothing is exporting. Unlike useExportJob it does not re-render on every+ * progress tick, so App can hold it for the exit guard and the badge. */+export function useRunningExportName(): string | null {+ return useSyncExternalStore(subscribeExportJob, runningName, runningName);+}+/** Fraction done, 0…1, for the bar and the taskbar. */export const exportFraction = (progress: ExportProgress | null) =>!progress || progress.frameCount === 0 ? 0 : Math.min(1, progress.framesDone / progress.frameCount);@@ -67,6 +80,7 @@ export const exportFraction = (progress: ExportProgress | null) =>* at any point before the end, so there is nothing to clean up. */export function cancelExportJob() {cancelRequested = true;+ if (state.progress && !state.cancelling) set({ cancelling: true });}/** Forgets a finished run's outcome (and clears a red taskbar button). */@@ -112,9 +126,11 @@ export async function startExportJob(options: StartExportOptions): Promise<void>};set({folderPath,+ projectName: config.name,destination,outcome: null,remainingMs: null,+ cancelling: false,progress: { phase: "preparing", framesDone: 0, frameCount: plan.frameCount, detail: "Starting…" },});void setTaskbarProgress(0).catch(() => undefined);@@ -137,6 +153,7 @@ export async function startExportJob(options: StartExportOptions): Promise<void>}} finally {cancelRequested = false;+ if (state.cancelling) set({ cancelling: false });}}