diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 58113a63a..9e3b366a4 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -151,7 +151,7 @@ def __init__(self, projects): def path(self, project_id: UUID, session: str | None = None) -> Path: with self.projects.local.transaction() as db: self.projects._recover() - directory, _, _ = self.projects._load(db, project_id) + directory, _ = self.projects._find(db, project_id) if session: self.projects._lease(db, project_id, directory, session, browser_only=True) return directory @@ -162,7 +162,7 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | finish_mono, finish_at = (_monotonic(), _utc_now()) if finish is not None else (None, None) with self.projects.local.transaction() as db: self.projects._recover() - directory, _, _ = self.projects._load(db, project_id) + directory, _ = self.projects._find(db, project_id) if session: self.projects._lease(db, project_id, directory, session, browser_only=True) folder = child(directory, 'agent-runs') @@ -383,7 +383,7 @@ def conversation_of(self, project_id: UUID, turn_id: UUID) -> str: def activate(self, project_id: UUID, conversation_id: UUID, session: str, *, create=False) -> dict: with self.projects.local.transaction() as db: self.projects._recover() - directory, _, _ = self.projects._load(db, project_id) + directory, _ = self.projects._find(db, project_id) self.projects._lease(db, project_id, directory, session, browser_only=True) folder = child(directory, 'agent-runs') folder.mkdir(exist_ok=True) diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index acf55b1e2..ba87b7ea0 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -100,6 +100,10 @@ English summary: a Job created by an Agent `generation.submit` records `agentRun Windows 上的 Codex 启动显式设置 `windows.sandbox="elevated"`,避免隔离启动忽略用户配置后,`workspace-write` 降为只读并拦截 Shell。保留沙箱约束,不绕过审批或沙箱。PowerShell 使用 `Get-Command opendirector` 发现 CLI,POSIX Shell 使用 `command -v opendirector`。 +OpenDirector 独立启动 Codex CLI 时不继承 Codex 桌面版的注册运行时标记。否则,即使模型能回复,独立 CLI 启动 PowerShell 时仍可能被注册运行时拒绝。此处理只作用于 Codex 子进程,仍使用 Windows 沙箱。 + +When launching the standalone Codex CLI, OpenDirector drops Desktop's registered-runtime markers from that child process. A model reply can succeed even when the inherited markers prevent PowerShell from starting. The Windows sandbox remains in use. + On Windows, Codex explicitly sets `windows.sandbox="elevated"` so ignoring user configuration does not downgrade `workspace-write` to read-only and block Shell execution. Sandbox restrictions remain enabled. Discover the CLI with `Get-Command opendirector` in PowerShell or `command -v opendirector` in POSIX shells. CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不使用连接令牌或凭据文件。网关继续校验工程范围、轮次生命周期及业务输入。 diff --git a/docs/development/lessons.md b/docs/development/lessons.md index f85aaae3c..03b556ee8 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -122,6 +122,13 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Four-view cropping:** A frozen face-emphasis prompt proves the setting reached the provider, while visual compliance still requires reviewing the generated image. Put the crop before appearance guidance and scope it to the first two columns. Specify a separate scale and headroom for the full back view. Check both a text-only subject and a reference with a less obvious neck. - **Reference medium:** Explicit photography wording corrected a photograph but turned an illustrated reference into a live-action portrait. Treat the layout as composition only and use medium-neutral framing language. Verify style changes against a photo and an illustration. +## History replay can block unrelated canvas reads + +- **Trigger:** Opening a canvas with hundreds of full-snapshot commits sends media, conversation, and update requests concurrently. +- **Evidence:** Media and assistant requests returned storage-lock timeouts on a Windows project with over 800 commits. All the referenced files were present, and reading the committed head resolved the failing media requests. +- **Check:** Read current media from the committed head and replay immutable history outside the catalog lock. Before publishing, recheck the head and rerun command validation if it changed. The asset and storage tests cover original bytes and a concurrent head change during replay. +- **Rename follow-up:** [PR #544](https://github.com/ThinkFlowLab/OpenDirector/pull/544) reproduced receipt and change-feed reads reporting corruption when a concurrent rename moved a valid commit directory. Resolve the project again after a failed replay and retry when its location or manifest changed. Keep the integrity error when the basis stayed the same. + ## An upstream response and a consumer finishing it are separate facts - **Trigger:** Forwarding streamed model responses through the loopback gateway. diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index b3e98f3c7..36cc3764d 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -45,8 +45,13 @@ def executable(runtime: str) -> str | None: _CODEX_ISOLATION: dict[tuple[str, ...], tuple[str, ...]] = {} -def codex_environment() -> dict[str, str]: - env = dict(os.environ) +def codex_environment(base: dict[str, str] | None = None) -> dict[str, str]: + env = dict(os.environ if base is None else base) + if sys.platform == 'win32': + # This is an independent CLI launch, not a registered Desktop Core child. + # Inheriting the registration selects a runner that cannot start this CLI's shell. + env.pop('CODEX_WINDOWS_REGISTERED_CORE', None) + env.pop('CODEX_WINDOWS_SANDBOX_PACKAGE_FAMILY', None) if sys.platform == 'win32' and not (env.get('HTTPS_PROXY') or env.get('ALL_PROXY')): # A Windows system proxy need not be exported to the CLI process. if proxy := getproxies().get('https'): @@ -94,8 +99,8 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None if bundled: runtime = 'opencode' env = cli_transport.environment(work, socket, bridge_env) - if runtime == 'codex' and (proxy := codex_environment().get('HTTPS_PROXY')): - env['HTTPS_PROXY'] = proxy + if runtime == 'codex': + env = codex_environment(env) if runtime == 'opencode': config = {'autoupdate': False, 'default_agent': 'opendirector', 'agent': {'opendirector': {'mode': 'primary', 'prompt': SYSTEM}}, diff --git a/packages/core/src/opendirector/application/creation_assets.py b/packages/core/src/opendirector/application/creation_assets.py index 6b5b6948b..4bc6bf5d6 100644 --- a/packages/core/src/opendirector/application/creation_assets.py +++ b/packages/core/src/opendirector/application/creation_assets.py @@ -209,15 +209,13 @@ def open_media(self, project_id, asset_id, *, snapshot=None): """ with self.projects.local.transaction() as db: self.projects._recover() + if snapshot is not None and snapshot.project.id != UUID(str(project_id)): + raise ProjectError('素材读取快照不属于当前工程。', 409) + path, manifest = self.projects._find(db, project_id) if snapshot is None: # A head whose chain was already proven needs no replay per read. - path, manifest = self.projects._find(db, project_id) record, validated = self.projects._current_record(db, project_id, path, manifest) snapshot = (record if validated else self.projects._load(db, project_id)[2][0]).snapshot - else: - if snapshot.project.id != UUID(str(project_id)): - raise ProjectError('素材读取快照不属于当前工程。', 409) - path, _ = self.projects._find(db, project_id) try: asset = self._asset(snapshot, asset_id) except ContractError: diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index cc826923b..8d817be3b 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -383,7 +383,8 @@ def used(kind, obj, ids=None, *, exclude_self=False): # Read independent tool ledgers once, retaining their deletion protection. asset_keys = {str(key): key for key in statuses} with self.projects.local.transaction() as db: - path, _, _ = self.projects._load(db, snapshot.project.id) + self.projects._recover() + path, _ = self.projects._find(db, snapshot.project.id) folder = gateway().child(path, 'tool-tasks') if folder.exists(): for entry in folder.glob('*.json'): diff --git a/packages/core/src/opendirector/domain/image_output.py b/packages/core/src/opendirector/domain/image_output.py index 516baafad..e059b16e1 100644 --- a/packages/core/src/opendirector/domain/image_output.py +++ b/packages/core/src/opendirector/domain/image_output.py @@ -17,6 +17,12 @@ def image_outputs(config, profile): ('16:9', '2720x1536'), ('9:16', '1536x2720'), ('3:2', '2496x1664'), ('2:3', '1664x2496'), ('21:9', '3136x1344'), ('9:21', '1344x3136'), ]] + if profile == 'vllm-omni-minimax-h3-image': + return [dict(aspectRatio=ratio, size=size) for ratio, size in [ + ('1:1', '1024x1024'), ('3:2', '1536x1024'), ('2:3', '1024x1536'), + ('4:3', '1600x1200'), ('3:4', '1200x1600'), + ('16:9', '1920x1080'), ('9:16', '1080x1920'), ('21:9', '2240x960'), + ]] if config.get('protocol') == 'volcengine': # This adapter only declares the existing automatic 2K request. Do not # promise a ratio without an explicit output contract for that service. diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index f0c160c61..ac5ada2e7 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -42,6 +42,11 @@ def _adapter_rules(config): rules.update(profile='minimax-h3-image', maxImages=16, imageBytes=64 * 1024 * 1024, requestBytes=64 * 1024 * 1024) return rules + if (kind == 'image' and config.get('protocol') == 'openai' + and config.get('connectionType') == 'self_hosted' + and model.rsplit('/', 1)[-1].lower() == 'minimax-h3-image'): + rules.update(profile='vllm-omni-minimax-h3-image') + return rules if is_moss_image(config): rules.update(profile='moss-image', allowedKinds=['text'], maxImages=0, maxPromptCharacters=MOSS_IMAGE_PROMPT_CHARACTERS) diff --git a/packages/core/src/opendirector/infrastructure/creation_commit_log.py b/packages/core/src/opendirector/infrastructure/creation_commit_log.py index dff7c067f..048c968b2 100644 --- a/packages/core/src/opendirector/infrastructure/creation_commit_log.py +++ b/packages/core/src/opendirector/infrastructure/creation_commit_log.py @@ -4,6 +4,7 @@ and by a bounded background warm, never by trusting a bare timestamp. """ import threading +from contextlib import contextmanager from hashlib import sha256 from opendirector.domain.projects import ProjectError @@ -310,6 +311,27 @@ def _read_manifest(self, project_id): self._recover() return self._find(db, project_id) + @contextmanager + def _write_basis(self, project_id): + while True: + path, manifest = self._read_manifest(project_id) + self._await_warm(project_id, manifest.head) + signature = _head_signature(path, manifest.head, self._verify_record_bytes) + try: + records = self._history(path, manifest) + except (OSError, ProjectError): + if (path, manifest) != self._read_manifest(project_id): + continue + raise + with self.local.transaction() as db: + self._recover() + if (path, manifest) != self._find(db, project_id): + continue + if signature is None or signature != _head_signature(path, manifest.head, self._verify_record_bytes): + raise ProjectError('工程提交身份不一致,原文件已保留。', 409, code='storage_unavailable') + yield db, path, manifest, records + return + def records(self, project_id): """Private commit records for read-only scans; callers must not mutate them. @@ -318,7 +340,18 @@ def records(self, project_id): megabytes for long histories, so they read the shared records directly. """ path, manifest = self._read_manifest(project_id) - return tuple(self._history(path, manifest)) + return tuple(self._read_history(project_id, path, manifest)) + + def _read_history(self, project_id, path, manifest): + while True: + try: + return self._history(path, manifest) + except (OSError, ProjectError): + # The immutable files can move together when a project is renamed. + current = self._read_manifest(project_id) + if current == (path, manifest): + raise + path, manifest = current def history(self, project_id): records = self.records(project_id) @@ -328,8 +361,7 @@ def history(self, project_id): def history_index(self, project_id): """Small detached event metadata; toolbar queries need no snapshots.""" - path, manifest = self._read_manifest(project_id) - records = self._history(path, manifest) + records = self.records(project_id) return records[0].snapshot.undoClearedThrough, tuple(dict( commandId=r.command.commandId, type=r.command.type, cursor=r.event.cursor, source=r.event.source, @@ -337,13 +369,11 @@ def history_index(self, project_id): ) for r in records if r.event is not None) def receipt(self, project_id, command_id): - with self.local.transaction() as db: - self._recover() - records = self._load(db, project_id)[2] - found = next((record.receipt for record in records if str(record.command.commandId) == str(command_id)), None) - if found is None: - raise ProjectError('没有该命令的已提交回执。', 404) - return found.model_copy(deep=True) + records = self.records(project_id) + found = next((record.receipt for record in records if str(record.command.commandId) == str(command_id)), None) + if found is None: + raise ProjectError('没有该命令的已提交回执。', 404) + return found.model_copy(deep=True) def changes(self, project_id, *, after=0, limit=100): if type(after) is not int or after < 0 or type(limit) is not int or not 1 <= limit <= 200: @@ -362,15 +392,13 @@ def changes(self, project_id, *, after=0, limit=100): cursor = head.snapshot.eventCursor if after > cursor: raise ProjectError('变更游标超出当前工程,请重新读取快照。', 409) - if after == cursor: - if not validated: - # A head served by the fast path has not proven its ancestry - # yet; the outbox is derived from the chain, so validate it - # before claiming there are no events. - self._history(path, manifest) - return dict(events=[], nextCursor=after, currentCursor=cursor, hasMore=False) - records = self._history(path, manifest) - events = [record.event for record in reversed(records) if record.event and record.event.cursor > after][:limit] - events = [event.model_copy(deep=True) for event in events] - return dict(events=events, nextCursor=events[-1].cursor if events else after, - currentCursor=cursor, hasMore=bool(events and events[-1].cursor < cursor)) + if after == cursor and validated: + return dict(events=[], nextCursor=after, currentCursor=cursor, hasMore=False) + records = self._read_history(project_id, path, manifest) + cursor = records[0].snapshot.eventCursor + if after > cursor: + raise ProjectError('变更游标超出当前工程,请重新读取快照。', 409) + events = [record.event for record in reversed(records) if record.event and record.event.cursor > after][:limit] + events = [event.model_copy(deep=True) for event in events] + return dict(events=events, nextCursor=events[-1].cursor if events else after, + currentCursor=cursor, hasMore=bool(events and events[-1].cursor < cursor)) diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index 5d015841e..3b14da792 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -37,19 +37,14 @@ def _replay(records, command): def replay(self, command): """Resolve an already committed command before reading upload handles.""" self._await_current_warm(command.projectId) - with self.local.transaction() as db: - self._recover() - return self._replay(self._load(db, command.projectId)[2], command) + return self._replay(self.records(command.projectId), command) def commit(self, command: Command, apply: Callable[[ProjectSnapshot], ProjectSnapshot] | Callable[[ProjectSnapshot, tuple[CommitRecord, ...]], ProjectSnapshot], *, session=None, source='ui', files=(), deletes=(), with_history=False): if source not in {'ui', 'agent', 'background', 'external'}: raise ProjectError('无效的命令来源。') - self._await_current_warm(command.projectId) - with self.local.transaction() as db: - self._recover() - path, manifest, records = self._load(db, command.projectId) + with self._write_basis(command.projectId) as (db, path, manifest, records): replay = self._replay(records, command) if replay: return replay diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index d1950f7aa..803de5aa1 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -119,10 +119,10 @@ def lock(self, project_id, handle): def _scope(self, db, project_id, session, trusted=False): self.projects._recover() - path, _, records = self.projects._load(db, project_id) + path, manifest = self.projects._find(db, project_id) if not trusted: self.projects._lease(db, project_id, path, session) - return records[0].snapshot + return self.projects._current(db, project_id, path, manifest).snapshot def _owner(self, folder, project_id, handle, session): try: diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 260a320e0..0910201d6 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -3,7 +3,8 @@ import { VoiceLibrary } from "./VoiceLibrary"; import { modelDescription } from "./modelDescriptions"; import { SearchableSelect } from "./SearchableSelect"; import { providerLabel } from "./providerPresets"; -import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { useEffect, useId, useLayoutEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; import { normalizeContent, presetOnlyContent, @@ -175,6 +176,13 @@ export function NodeComposer({ null, ); const [presetCopied, setPresetCopied] = useState(false); + /** Hover hint for the preset selector, anchored to its own rect. */ + const [presetHint, setPresetHint] = useState( + null, + ); + const presetHintId = useId(); + const presetHintElement = useRef(null); + const presetHintEnabled = selectedNode?.type === "image" && !running && !optimizing; const presetValue = selectedNode?.type === "image" ? selectedNode.data.settings?.imagePreset ?? "none" : "none"; @@ -198,6 +206,26 @@ export function NodeComposer({ useEffect(() => { setPanel(null); }, [selectedNode?.id, running]); + useEffect(() => { + setPresetHint(null); + }, [selectedNode?.id, presetHintEnabled]); + useLayoutEffect(() => { + const tip = presetHintElement.current; + if (!presetHintEnabled || !presetHint || !tip) return; + const anchor = presetHint.getBoundingClientRect(); + const { width, height } = tip.getBoundingClientRect(); + const left = anchor.left + (anchor.width - width) / 2; + const top = anchor.top - height - 8; + tip.style.left = `${Math.max(12, Math.min(innerWidth - width - 12, left))}px`; + tip.style.top = `${Math.max(12, Math.min(innerHeight - height - 12, top >= 12 ? top : anchor.bottom + 8))}px`; + const hide = () => setPresetHint(null); + window.addEventListener("resize", hide); + window.addEventListener("scroll", hide, true); + return () => { + window.removeEventListener("resize", hide); + window.removeEventListener("scroll", hide, true); + }; + }, [presetHint, presetHintEnabled, t]); useEffect(() => { setPresetPromptAnchor(null); setPresetTuneAnchor(null); @@ -982,10 +1010,26 @@ export function NodeComposer({
{mode === "image" && ( + { + if (event.pointerType === "touch" || event.buttons) return; + if (presetHintEnabled) setPresetHint(event.currentTarget); + }} + onPointerLeave={() => setPresetHint(null)} + onPointerDown={() => setPresetHint(null)} + > + )} {mode === "video" && ( + Math.ceil(time * fps - 1e-8); + export interface Mp4Options { canvas: HTMLCanvasElement; duration: number; @@ -72,7 +77,7 @@ export async function encodeMp4(options: Mp4Options): Promise { signal.addEventListener("abort", cancel, { once: true }); try { await output.start(); - const frames = Math.ceil(duration * fps); + const frames = Math.max(1, frameAtOrAfter(duration, fps)); let audioEnd = 0; for (let frame = 0; frame < frames; frame++) { signal.throwIfAborted(); diff --git a/src/canvas/nodes.css b/src/canvas/nodes.css index 45882d5c8..85af0c135 100644 --- a/src/canvas/nodes.css +++ b/src/canvas/nodes.css @@ -1109,6 +1109,12 @@ .cw-generation-mode-controls { display: contents; } + +.cw-preset-select { + display: inline-flex; + align-items: center; + min-width: 0; +} .cw-composer-options .cw-generation-mode-controls select, .cw-composer-options .cw-generation-mode-controls input { min-width: 0; diff --git a/src/canvas/timeline-editor.css b/src/canvas/timeline-editor.css index f7e9fcbc7..6a9804aa1 100644 --- a/src/canvas/timeline-editor.css +++ b/src/canvas/timeline-editor.css @@ -87,9 +87,31 @@ .cw-timeline-dialog { width: min(1370px, 100%); } +.cw-timeline-dialog .cw-domain-header { + padding: 10px 16px; +} +.cw-timeline-dialog .cw-domain-header p { + margin-top: 3px; + line-height: 1.4; +} .cw-timeline-dialog .cw-domain-body { padding: 0; } +.cw-timeline-dialog .cw-domain-footer { + gap: 8px 12px; + padding: 8px 14px; +} +.cw-timeline-dialog .cw-domain-footer > div { + flex-wrap: wrap; + gap: 6px; +} +.cw-timeline-dialog .cw-domain-footer > div:last-child { + flex-shrink: 0; +} +.cw-timeline-dialog .cw-domain-footer button, +.cw-timeline-dialog .cw-timeline-edit-toolbar button { + padding: 5px 8px; +} .cw-timeline-top { display: grid; grid-template-columns: 210px minmax(0, 1fr) 215px; @@ -125,7 +147,7 @@ flex-direction: column; align-items: center; justify-content: center; - padding: 22px 23px 16px; + padding: 10px 16px 5px; background: var(--cw-timeline-monitor); } .cw-timeline-screen { @@ -169,7 +191,7 @@ align-items: center; justify-content: center; gap: 10px; - margin-top: 18px; + margin-top: 6px; } .cw-timeline-transport button { padding: 6px 9px; @@ -203,8 +225,7 @@ } .cw-timeline-seek { width: 100%; - height: 14px; - margin-top: 15px; + margin-top: 0; accent-color: var(--cw-timeline-accent); cursor: pointer; } @@ -303,12 +324,20 @@ var(--cw-timeline-lane); } .cw-timeline-drag-status { - height: 24px; - padding: 0 20px; - overflow: hidden; + position: absolute; + z-index: 10; + inset-inline-end: 12px; + bottom: calc(100% + 4px); + max-width: calc(100% - 24px); color: var(--cw-timeline-text); font-size: 11px; - line-height: 24px; + pointer-events: none; +} +.cw-timeline-drag-status:not(:empty) { + padding: 4px 8px; + border: 1px solid var(--cw-timeline-border); + border-radius: 4px; + background: var(--cw-timeline-surface); } .cw-timeline-playhead { position: absolute; @@ -382,16 +411,28 @@ color: var(--cw-timeline-clip-muted); font-size: 9px; } -.cw-timeline-footnote { - padding: 0 22px 12px; +.cw-timeline-help { + padding: 0 14px; + color: var(--cw-timeline-muted); + font-size: 11px; +} +.cw-timeline-help summary { + width: fit-content; + padding: 4px 0; + cursor: pointer; +} +.cw-timeline-help summary:focus-visible { + outline: 2px solid var(--cw-timeline-accent); + outline-offset: 2px; +} +.cw-timeline-help .cw-domain-note { + margin: 0 0 6px; + line-height: 1.5; } @media (max-width: 1100px) { .cw-timeline-top { grid-template-columns: 175px minmax(0, 1fr) 185px; } - .cw-timeline-monitor { - padding: 18px 14px; - } .cw-timeline-transport { gap: 6px; } @@ -553,8 +594,10 @@ --cw-resizer-line: var(--cw-timeline-accent); } .cw-timeline-edit-toolbar { - flex-wrap: wrap; - padding: 12px 18px 0; + position: relative; + gap: 5px 8px; + margin: 0; + padding: 5px 14px 2px; } .cw-timeline-snap, .cw-timeline-zoom { @@ -633,8 +676,7 @@ } /* Short viewports shrink both areas before the body has to scroll. */ .cw-timeline-dialog .cw-timeline-top { - flex: 1 1 calc(590px - var(--cw-track-height, 260px)); - height: auto; + flex: 1 1 0; min-height: 180px; } .cw-timeline-dialog .cw-timeline-scroll { @@ -740,7 +782,6 @@ width: 100%; flex: 1; min-height: 100px; - max-height: 350px; } .cw-timeline-picture-area .cw-timeline-screen { flex: none; diff --git a/src/canvas/timelineRender.ts b/src/canvas/timelineRender.ts index c0c153dec..302feac80 100644 --- a/src/canvas/timelineRender.ts +++ b/src/canvas/timelineRender.ts @@ -15,7 +15,7 @@ import { timelineSegments, type TimelineSegment, } from "./timeline"; -import { encodeMp4 } from "./mp4Export"; +import { encodeMp4, frameAtOrAfter } from "./mp4Export"; import { prepareTimelineFonts, drawTimelineText, @@ -33,6 +33,13 @@ export async function renderTimelineMp4( if (error) throw new Error(error); const timeline = copyTimeline(value), segments = timelineSegments(timeline); + const visualSpans = segments + .filter(({ track }) => track.kind === "visual") + .map((segment) => ({ + segment, + first: frameAtOrAfter(segment.start, timeline.fps), + end: frameAtOrAfter(segment.end, timeline.fps), + })); const duration = timelineDuration(timeline); if (!duration) throw new Error(tNow("errors.render.timelineEmpty")); const canvas = document.createElement("canvas"); @@ -137,14 +144,14 @@ export async function renderTimelineMp4( fit: "contain", poolSize: 2, }); + const span = visualSpans.find((entry) => entry.segment === segment)!; function* times() { - for ( - let frame = Math.ceil(segment.start * timeline.fps); - frame / timeline.fps < segment.end; - frame++ - ) + for (let frame = span.first; frame < span.end; frame++) { + const offset = Math.max(0, frame / timeline.fps - segment.start); + // Sample on the current side of the source packet boundary. yield clip.inPoint + - (frame / timeline.fps - segment.start) * clip.speed; + offset * clip.speed + 1e-9; + } } videos.set(clip.id, sink.canvasesAtTimestamps(times())); } @@ -171,12 +178,9 @@ export async function renderTimelineMp4( draw: async (time, frameIndex) => { context.fillStyle = "#000000"; context.fillRect(0, 0, canvas.width, canvas.height); - const segment = segments.find( - (item) => - item.track.kind === "visual" && - time >= item.start && - time < item.end, - ); + const segment = visualSpans.find( + ({ first, end }) => frameIndex >= first && frameIndex < end, + )?.segment; if (segment) { const resource = segment.clip.resource; if (resource.kind === "image") { diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index 50f1ed309..948dc8969 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -29,6 +29,7 @@ export const generation = { "generation.imagePreset": "Image presets", "generation.videoMode": "Video mode", "generation.preset.none": "Free creation", + "generation.preset.hint": "Choose a preset image style", "generation.preset.productViews": "Product three views", "generation.preset.demo": "Local interaction demo", "generation.preset.audioWorkflow": "Local audio workflow", diff --git a/src/i18n/messages/en-US/timeline.ts b/src/i18n/messages/en-US/timeline.ts index ac450eacb..2ee232259 100644 --- a/src/i18n/messages/en-US/timeline.ts +++ b/src/i18n/messages/en-US/timeline.ts @@ -119,6 +119,7 @@ export const timeline = { "timeline.track.delete": "Delete {title}", "timeline.track.muted": "Muted", "timeline.track.audible": "Audible", + "timeline.track.help": "Editing and export help", "timeline.track.dragHint": "Drag visual clips to reorder them; drag audio to change its start or move it to another audio track. Press Esc to cancel and ⌘/Ctrl + Z to undo. MP4 renders in the browser and preserves order, trims, speed, volume, and multi-track mixing; the picture is scaled to fit with black bars. Speed changes also change pitch. ⌘/Ctrl + wheel zooms the timeline at the pointer; snapping aligns clip edges and the playhead. FCPXML is a standard editing interchange format, and the ZIP contains the original media; after extraction, keep the media directory's relative path. This is not a native CapCut project and compatibility with every editor version is not promised. The JSON remains editable in this project.", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index e02fa9cae..d7a1bc86a 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -27,6 +27,7 @@ export const generation = { "generation.imagePreset": "图片创作预设", "generation.videoMode": "视频创作模式", "generation.preset.none": "自由创作", + "generation.preset.hint": "选择预设图片样式", "generation.preset.productViews": "产品三视图", "generation.preset.demo": "本地交互演示", "generation.preset.audioWorkflow": "本地音频工作流", diff --git a/src/i18n/messages/zh-CN/timeline.ts b/src/i18n/messages/zh-CN/timeline.ts index a8ff7e702..c96ae3a39 100644 --- a/src/i18n/messages/zh-CN/timeline.ts +++ b/src/i18n/messages/zh-CN/timeline.ts @@ -111,6 +111,7 @@ export const timeline = { "timeline.track.delete": "删除{title}", "timeline.track.muted": "静音", "timeline.track.audible": "有声", + "timeline.track.help": "操作与导出说明", "timeline.track.dragHint": "拖动画面片段调整顺序;拖动音频调整起点或移至其他音轨。按 Esc 取消,⌘/Ctrl + Z 撤销。 MP4 在浏览器内合成,保留顺序、裁剪、倍速、音量和多轨混音;画面等比适配并补黑边。倍速会同时改变音调。⌘/Ctrl + 滚轮以指针位置缩放时间轴;自动吸附对齐片段边缘与播放头。 FCPXML 为标准剪辑交换格式,ZIP 含原媒体;解压后保持 media 目录相对位置。并非原生剪映工程,也不承诺所有剪辑软件版本兼容。JSON 可在本工程继续编辑。", diff --git a/tests/browser/reference_parity.mjs b/tests/browser/reference_parity.mjs index 41c097dd8..a672f4a35 100644 --- a/tests/browser/reference_parity.mjs +++ b/tests/browser/reference_parity.mjs @@ -273,9 +273,18 @@ try { .getAttribute("data-reference"), ); assert.ok(part.nodeId); - await page - .getByRole("combobox", { name: "图片创作预设", exact: true }) - .selectOption("four-view"); + const presetPicker = page.getByRole("combobox", { name: "图片创作预设", exact: true }); + const presetHint = page.getByRole("tooltip").filter({ hasText: "选择预设图片样式" }); + await presetPicker.hover(); + await presetHint.waitFor(); + await presetPicker.click(); + await presetHint.waitFor({ state: "hidden" }); + await page.keyboard.press("Escape"); + await presetPicker.press("Tab"); + await page.keyboard.press("Shift+Tab"); + await presetHint.waitFor(); + assert.equal(await presetPicker.getAttribute("aria-describedby"), await presetHint.getAttribute("id")); + await presetPicker.selectOption("four-view"); await page.locator('.cw-composer [data-preset="four-view"]').waitFor(); const copied = await page .getByRole("textbox", { name: "生成提示词", exact: true }) diff --git a/tests/test_creation_assets.py b/tests/test_creation_assets.py index 600880cf8..fbf289382 100644 --- a/tests/test_creation_assets.py +++ b/tests/test_creation_assets.py @@ -164,6 +164,17 @@ def fail(*args): assert len(projects.snapshot(project_id).assets) == 1 +def test_media_reads_use_the_committed_head_without_replaying_history(storage, monkeypatch): + projects, project_id, session = storage + info = upload(storage) + projects.execute(import_command(project_id, info), session=session) + monkeypatch.setattr(projects, '_history', lambda *args: pytest.fail('media read replayed history')) + stream, asset = CreationAssets(projects).open_media(project_id, upload_asset_id(project_id, info.id)) + with stream: + assert stream.read() == png() + assert asset.fingerprint == info.fingerprint + + def test_pending_or_corrupt_files_cannot_be_exposed_as_a_committed_asset(storage): projects, project_id, session = storage info = upload(storage) diff --git a/tests/test_creation_history_service.py b/tests/test_creation_history_service.py index f16a7b0e5..6b7c1a9e5 100644 --- a/tests/test_creation_history_service.py +++ b/tests/test_creation_history_service.py @@ -405,7 +405,7 @@ def reading(path): monkeypatch.setattr(gateway(), 'read_json', reading) service = CreationHistory(store) listing = service.asset_list(pid) - assert len(history_reads) == 1 and len(loads) == 1 + assert len(history_reads) == 1 and loads == [] assert ledger_reads == [ledger] assert listing['eventCursor'] == snapshot.eventCursor assert [row['asset'].id for row in listing['items']] == [unused.id, tool_input.id, material.id] diff --git a/tests/test_creation_storage.py b/tests/test_creation_storage.py index 6b68264e8..9ad51b9e8 100644 --- a/tests/test_creation_storage.py +++ b/tests/test_creation_storage.py @@ -946,6 +946,50 @@ def test_first_autosave_after_a_cold_open_reuses_the_warmed_chain(projects, monk assert decoded == [] # The warmed ancestors are trusted; only a new record is built. +def test_write_replays_outside_catalog_lock_and_rechecks_changed_head(projects, monkeypatch): + created = create(projects) + planned = rename(created, 'Final', revision=2) + intervening = rename(created, 'Intervening', revision=1) + history = projects._history + scanned = [] + + def advance(path, manifest): + assert not projects.local.lock.is_locked + records = history(path, manifest) + scanned.append(manifest.head) + if len(scanned) == 1: + assert projects.execute(intervening).status == 'applied' + return records + + monkeypatch.setattr(projects, '_history', advance) + assert projects.execute(planned).status == 'applied' + assert scanned == [created.commandId, created.commandId, intervening.commandId] + assert projects.snapshot(created.projectId).project.name == 'Final' + + +@pytest.mark.parametrize('read', ['receipt', 'changes']) +def test_commit_reads_retry_when_rename_moves_the_history(projects, monkeypatch, read): + created = create(projects) + moved = rename(created) + history = projects._history + scanned = [] + + def relocate(path, manifest): + scanned.append(path.name) + if len(scanned) == 1: + assert projects.execute(moved).status == 'applied' + return history(path, manifest) + + monkeypatch.setattr(projects, '_history', relocate) + if read == 'receipt': + assert projects.receipt(created.projectId, created.commandId).status == 'applied' + else: + changes = projects.changes(created.projectId) + assert changes['currentCursor'] == 2 + assert [event.commandId for event in changes['events']] == [created.commandId, moved.commandId] + assert scanned == ['Example', 'Example', 'Renamed'] + + def test_plain_snapshot_reads_do_not_warm_history_in_the_background(projects, monkeypatch): # Job scans call snapshot() for every project; that must not validate every # chain in the background the way opening a canvas does. diff --git a/tests/test_minimax_image.py b/tests/test_minimax_image.py index 10bfae5cf..410364cb5 100644 --- a/tests/test_minimax_image.py +++ b/tests/test_minimax_image.py @@ -2,6 +2,8 @@ import base64 import io import json +from email import policy +from email.parser import BytesParser from pathlib import Path from uuid import UUID, uuid4 @@ -9,6 +11,7 @@ import pytest from PIL import Image +from generation_helpers import command as generation_command from opendirector.domain.capabilities import ImageRequest from opendirector.domain.generation import GenerationError from opendirector.domain.projects import ProjectError @@ -37,6 +40,61 @@ def png(color): return buffer.getvalue() +def test_self_hosted_h3_aspect_ratios_are_frozen_and_sent(project): + projects, pid, session = project + configs = ModelConfigs(projects.local.repository) + url = 'http://gpu-box:18152/v1' + saved = configs.save('image', url, MODELS[0], 'fixture-key', protocol='openai', + connection_type='self_hosted', auth_mode='bearer') + sizes = { + '1:1': '1024x1024', '3:2': '1536x1024', '2:3': '1024x1536', + '4:3': '1600x1200', '3:4': '1200x1600', '16:9': '1920x1080', + '9:16': '1080x1920', '21:9': '2240x960', + } + rules = saved['inputRules'] + assert {output['aspectRatio']: output['size'] for output in rules['imageOutputs']} == sizes + image = png('blue') + asset, _, _ = import_asset(project, 'source.png', image) + calls = [] + + def respond(request): + assert request.headers['authorization'] == 'Bearer fixture-key' + if request.url.path == '/v1/images/edits': + message = BytesParser(policy=policy.default).parsebytes( + b'Content-Type: ' + request.headers['content-type'].encode() + b'\r\n\r\n' + request.content) + fields = {part.get_param('name', header='content-disposition'): part.get_payload(decode=True) + for part in message.iter_parts()} + assert fields['image'] == image + calls.append((request.url.path, fields['size'].decode())) + else: + calls.append((request.url.path, json.loads(request.content)['size'])) + return httpx.Response(200, json={'data': [{'b64_json': base64.b64encode(image).decode()}]}) + + async def run(): + runner = CreationGeneration(projects, configs) + runner.provider = GenerationProviders(runner.store, httpx.MockTransport(respond)) + try: + for ratio, size in sizes.items(): + edit = ratio == '9:16' + command = generation_command(project, saved, parameters={'aspectRatio': ratio}, + references=[asset.id] if edit else []) + source = 'agent' if edit else 'ui' + receipt = await runner.execute(command, session=session, source=source) + assert receipt.status == 'accepted', receipt + await asyncio.gather(*(worker.future for worker in list(runner.jobs.values()))) + job = runner.get_job(pid, receipt.jobIds[0]) + assert job.status == 'succeeded', (ratio, calls, job.errorDetails) + assert job.execution.size == size + assert calls[-1] == ('/v1/images/' + ('edits' if edit else 'generations'), size) + finally: + await runner.close() + + asyncio.run(run()) + assert len(calls) == len(sizes) + hosted = configs.save('image', url, MODELS[0], 'fixture-key', protocol='openai') + assert hosted['inputRules']['profile'] == 'compatible' + + @pytest.mark.parametrize('model', MODELS) def test_image_generation_and_ordered_edits(tmp_path, model): configs = ModelConfigs(tmp_path) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 9d44c9479..93f2035f0 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -265,6 +265,27 @@ def test_native_commands_keep_auth_and_restrict_tools(tmp_path, monkeypatch): assert 'title' not in config['agent'] +def test_codex_windows_launch_uses_standalone_sandbox_and_keeps_project_bridge(tmp_path, monkeypatch): + monkeypatch.setattr(native.sys, 'platform', 'win32') + monkeypatch.setattr(native, 'executable', lambda _: sys.executable) + monkeypatch.setattr(native, 'codex_isolation_flags', lambda _: ()) + monkeypatch.setenv('CODEX_WINDOWS_REGISTERED_CORE', '1') + monkeypatch.setenv('CODEX_WINDOWS_SANDBOX_PACKAGE_FAMILY', 'DesktopRegistration') + monkeypatch.setenv('HTTPS_PROXY', 'http://127.0.0.1:1080') + bridge = {'OPENDIRECTOR_AGENT_HOST': '127.0.0.1', 'OPENDIRECTOR_AGENT_PORT': '8001'} + + args, env = native.command('codex', tmp_path, '', 'token', None, '', [], bridge_env=bridge) + + assert 'CODEX_WINDOWS_REGISTERED_CORE' not in env + assert 'CODEX_WINDOWS_SANDBOX_PACKAGE_FAMILY' not in env + assert os.environ['CODEX_WINDOWS_REGISTERED_CORE'] == '1' + assert env['HTTPS_PROXY'] == 'http://127.0.0.1:1080' + assert all(env[key] == value for key, value in bridge.items()) + assert Path(env['PATH'].split(os.pathsep)[0]) == tmp_path / '.opendirector-bin' + assert args[args.index('--sandbox') + 1] == 'workspace-write' + assert 'windows.sandbox="elevated"' in args + + def test_codex_only_passes_supported_isolation_flags(tmp_path, monkeypatch): binary = str(tmp_path / 'codex') monkeypatch.setattr(native, 'executable', lambda _: binary)