diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index e65932e51..5e23d068d 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -178,6 +178,7 @@ Select a node, then choose an action from its toolbar. - **Images**: Crop, rotate, flip, adjust colors, work with layers, add text, shapes, or annotations, and edit selections. - **Video and audio**: Extract frames, trim, extract audio tracks, and process clips. + Use the version button at the top right of a node to apply an earlier version. If a generation job blocks the change, choose **Stop blocking jobs** in the history panel, then apply the version. Previously generated results remain available. When trimming a video, choose WebM (the default) or MP4 under **Output format**. Choose MP4 if your model requires MP4 reference video. - **AI tools**: Extend images, erase content, remove backgrounds, edit images with AI, upscale, and more. Availability depends on the connected models. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index f6dc6a095..4a582659d 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -178,6 +178,7 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制 - **图片**:裁剪、旋转、翻转、调色、图层、文字、形状、标注和选区编辑。 - **视频与音频**:取帧、裁剪、音轨提取和片段处理。 + 从节点右上角的历史版本按钮可以应用旧版本。如果生成任务阻塞切换,请先在历史版本面板点击「停止阻塞任务」,再应用版本。之前生成的结果仍可使用。 使用「时长修剪」时,可在「保存格式」中选择 WebM(默认)或 MP4。如果模型要求参考视频为 MP4,请选择 MP4。 - **AI 工具**:扩图、消除、抠图、智能改图、超清等,是否可用取决于已接入模型。 diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 61e75cdff..4a9f82c95 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -517,7 +517,8 @@ def control(before): job = self.get_job(command.projectId, command.payload.jobId) if job is None: raise ContractError('missing_object', '任务不存在。', command.payload.jobId) - if command.type == 'job.cancel' and job.status not in {'succeeded', 'cancelled'}: + if (command.type == 'job.cancel' and not job.cancelRequested and job.status != 'succeeded' + and (job.status != 'cancelled' or job.resumeAllowed or job.recovery == 'review')): job = job.model_copy(update={'cancelRequested': True, 'revision': job.revision + 1}) return before.model_copy(update={'jobs': tuple(job if j.id == job.id else j for j in before.jobs)}) return before diff --git a/packages/core/src/opendirector/application/creation_node_versions.py b/packages/core/src/opendirector/application/creation_node_versions.py index e0c0c3388..386fca371 100644 --- a/packages/core/src/opendirector/application/creation_node_versions.py +++ b/packages/core/src/opendirector/application/creation_node_versions.py @@ -20,6 +20,19 @@ from opendirector.ports.gateway import gateway +def blocking_version_jobs(snapshot, item): + binding = item.binding + owner = binding.objectRef if binding.role == 'generation' else binding.draftSpec if binding.role == 'empty' else None + # Once a local stop completes, cancel intent fences off automatic adoption. + # Remote uncertainty remains recorded on the job for later reconciliation. + return [ + job.id for job in snapshot.jobs + if (job.originItemId == item.id or (owner and job.inputSnapshot.spec.id == owner.id)) + and (job.status in {'queued', 'running'} + or (not job.cancelRequested and (job.resumeAllowed or job.recovery == 'review'))) + ] + + def available_model(projects, frozen): """A removed or repurposed model remains evidence, never an implicit fallback.""" try: @@ -122,6 +135,7 @@ def node_versions(projects, project_id, item_id, *, assets=None): currentReferencesDiffer=current_references_differ(snapshot, job.inputSnapshot) if job else False)) current = current_asset(snapshot, item) return deepcopy(dict(item=item, versions=rows, currentAssetId=current.id if current else None, + blockingJobIds=blocking_version_jobs(snapshot, item), eventCursor=snapshot.eventCursor, expectedVersions=[dict(objectType=kind, id=obj.id, revision=obj.revision) for (kind, _), obj in object_index(snapshot).items()])) @@ -142,8 +156,7 @@ def apply_node_version(history, before, command): data = before.model_dump(mode='json') target = CreationCanvas._editable(data, item.id) current_spec_id = item.binding.objectRef.id if item.binding.role == 'generation' else item.binding.draftSpec.id if item.binding.role == 'empty' and item.binding.draftSpec else None - if any((j.originItemId == item.id or j.inputSnapshot.spec.id == current_spec_id) and - (j.status in {'queued', 'running'} or j.resumeAllowed or j.recovery == 'review') for j in before.jobs): + if blocking_version_jobs(before, item): raise ContractError('revision_conflict', '节点有未结束或待确认任务,请先处理任务。', item.id) job = evidence.get('job') if job is None: diff --git a/src/canvas/NodeVersionHistory.tsx b/src/canvas/NodeVersionHistory.tsx index d2c131a47..51cd2787b 100644 --- a/src/canvas/NodeVersionHistory.tsx +++ b/src/canvas/NodeVersionHistory.tsx @@ -9,6 +9,7 @@ import type { import { assetReference, creationClient, + CreationCommandError, creationPath, } from "../backend/creationClient.ts"; import { errorMessage, request } from "../backend/api.ts"; @@ -32,10 +33,20 @@ interface VersionListing { item: CanvasItem; versions: NodeVersion[]; currentAssetId: string | null; + blockingJobIds: string[]; expectedVersions: ObjectVersion[]; eventCursor: number; } +async function readVersions(projectId: string, itemId: string, signal?: AbortSignal) { + const value = await request( + `${creationPath(projectId)}/items/${itemId}/versions`, + { signal }, + ); + // The service lists newest first. Keep the display in creation order. + return { ...value, versions: [...value.versions].reverse() }; +} + /** One inventory request per content change, never per node or pointer movement. */ export function useNodeVersionCounts(projectId: string, enabled: boolean) { const [counts, setCounts] = useState>({}); @@ -224,7 +235,9 @@ export function NodeVersionHistory({ const [preparing, setPreparing] = useState(true); const [selected, setSelected] = useState(""); const [error, setError] = useState(""); - const [busy, setBusy] = useState(false); + const [operation, setOperation] = useState<"apply" | "stop" | null>(null); + const busy = operation !== null; + const blockingJobIds = listing?.blockingJobIds ?? []; const [stale, setStale] = useState(false); const pending = useRef(false); const alive = useRef(true); @@ -249,21 +262,15 @@ export function NodeVersionHistory({ .then(() => { abort.signal.throwIfAborted(); setPreparing(false); - return request( - `${creationPath(projectId)}/items/${itemId}/versions`, - { signal: abort.signal }, - ); + return readVersions(projectId, itemId, abort.signal); }) .then((value) => { if (abort.signal.aborted) return; - // The service lists newest assets first; display creation order, - // independent of which result is currently adopted. - const versions = [...value.versions].reverse(); - setListing({ ...value, versions }); + setListing(value); setSelected((id) => - versions.some((version) => version.asset.id === id) + value.versions.some((version) => version.asset.id === id) ? id - : (versions[0]?.asset.id ?? ""), + : (value.versions[0]?.asset.id ?? ""), ); }) .catch((reason) => { @@ -273,9 +280,9 @@ export function NodeVersionHistory({ }, [projectId, itemId, preparation]); const apply = async () => { const version = listing?.versions.find((row) => row.asset.id === selected); - if (!listing || !version || pending.current || stale) return; + if (!listing || !version || pending.current || stale || blockingJobIds.length) return; pending.current = true; - setBusy(true); + setOperation("apply"); setError(""); try { await creationClient(projectId).command( @@ -290,14 +297,54 @@ export function NodeVersionHistory({ if (alive.current) onApplied(version.currentReferencesDiffer); } catch (reason) { if (alive.current) { - setError( - t("canvasNodes.version.reopen", { message: errorMessage(reason) }), - ); - setStale(true); + // A task may have started after the version list was read. + const latest = reason instanceof CreationCommandError && + reason.receipt.issues.some((issue) => issue.code === "revision_conflict") + ? await readVersions(projectId, itemId).catch(() => undefined) + : undefined; + if (!alive.current) return; + if (latest?.blockingJobIds?.length) setListing(latest); + else { + setError(t("canvasNodes.version.reopen", { message: errorMessage(reason) })); + setStale(true); + } } } finally { pending.current = false; - if (alive.current) setBusy(false); + if (alive.current) setOperation(null); + } + }; + const stopBlockingJobs = async () => { + if (pending.current || !blockingJobIds.length || readOnly || listing?.item.locked) return; + pending.current = true; + setOperation("stop"); + setError(""); + try { + const client = creationClient(projectId); + for (const jobId of blockingJobIds) { + if (!alive.current) return; + await client.control(jobId, "cancel"); + } + } catch (reason) { + if (alive.current) setError(errorMessage(reason)); + } finally { + if (alive.current) { + try { + const latest = await readVersions(projectId, itemId); + if (alive.current) { + setListing(latest); + setStale(false); + } + } catch (reason) { + if (alive.current) { + setError(t("canvasNodes.version.reopen", { message: errorMessage(reason) })); + setStale(true); + } + } finally { + if (alive.current) setOperation(null); + } + } + pending.current = false; } }; const close = () => { @@ -407,22 +454,33 @@ export function NodeVersionHistory({ ); })} - {error && ( + {(error || blockingJobIds.length > 0) && (

- {error} + {error || t("canvasNodes.version.blockingJobs")}

)}