diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index d2a685de4..e694d3261 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -5,6 +5,8 @@ from hashlib import sha256 from io import BytesIO import asyncio +from fastapi.encoders import jsonable_encoder +from fastapi.responses import JSONResponse import json import re from urllib.parse import quote, unquote @@ -13,7 +15,7 @@ from pydantic import BaseModel, Field from fastapi.responses import FileResponse, Response, StreamingResponse from filelock import Timeout -from starlette.background import BackgroundTask +from starlette.background import BackgroundTask, BackgroundTasks from starlette.concurrency import run_in_threadpool from opendirector.application.creation_assets import CreationAssets @@ -81,6 +83,7 @@ async def disconnected(): def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None): router = APIRouter(prefix='/api/creation', tags=['Unified creation projects']) + reference_checks = asyncio.Semaphore(2) assets = CreationAssets(projects) canvas = CreationCanvas(projects) history = CreationHistory(projects, assets=assets) @@ -109,8 +112,8 @@ async def optimize_prompt(project_id: UUID, item_id: UUID, value: PromptOptimiza value.preferredModelId, value.assistantModel)) @router.get('/projects') - def list_projects(): - return projects.list_projects() + def list_projects(navigation: bool = False): + return projects.list_projects(navigation=navigation) @router.post('/projects/cleanup') def cleanup_unreadable_projects(): @@ -134,21 +137,58 @@ def open_project(project_id: UUID, x_opendirector_session: UUID = Header(), return projects.open(project_id, str(x_opendirector_session)) @router.post('/projects/{project_id}/open-canvas') - def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header(), - x_opendirector_allow_preview: bool = Header(default=False)): - # The canvas needs its reference edges and text on first render too. Reuse the - # single snapshot this open read already published instead of making the - # page read the same project again through GET /canvas. The no-flag - # route above still returns a bare ProjectSnapshot. - session = str(x_opendirector_session) - editing = {} - if x_opendirector_allow_preview: - snapshot, state = projects.open_canvas(project_id, session, allow_preview=True) - editing['editing'] = state - else: - snapshot = projects.open(project_id, session) - return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot), - 'texts': canvas.text_contents(snapshot), **editing} + async def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header(), + x_opendirector_allow_preview: bool = Header(default=False), + x_opendirector_defer_reference_checks: bool = Header(default=False), + x_opendirector_defer_texts: bool = Header(default=False), + x_opendirector_view_client: UUID | None = Header(default=None)): + def open_canvas(): + session = str(x_opendirector_session) + background = BackgroundTasks() + editing = {} + resolved: list[Path] = [] + if x_opendirector_allow_preview: + snapshot, state = projects.open_canvas( + project_id, session, allow_preview=True, after_response=background.add_task, + on_resolved=resolved.append, copy_snapshot=False) + editing['editing'] = state + else: + snapshot = projects.open(project_id, session) + defer_checks = x_opendirector_defer_reference_checks and any(ref.active for ref in snapshot.references) + edges = ([{'referenceId': ref.id, 'state': 'unknown'} for ref in snapshot.references if ref.active] + if defer_checks else canvas.reference_edges(project_id, snapshot)) + texts = {} if x_opendirector_defer_texts else canvas.text_contents(snapshot, resolved_path=resolved[0] if resolved else None) + if x_opendirector_view_client is not None: + view = projects.view(project_id, x_opendirector_view_client, missing_ok=True, + resolved_path=resolved[0] if resolved else None) + editing['view'] = view.model_dump(mode='json') if view is not None else None + encoded = dict( + snapshot=snapshot.model_dump(mode='json'), + edges=jsonable_encoder(edges), + referenceChecksDeferred=defer_checks, + texts=texts, + textsDeferred=x_opendirector_defer_texts, + **editing, + ) + return JSONResponse(encoded, background=background) + return await run_in_threadpool(open_canvas) + + @router.get('/projects/{project_id}/canvas-texts') + def canvas_texts(project_id: UUID, cursor: int = Query(ge=1)): + snapshot, folder = projects.canvas_read_basis(project_id) + return {'cursor': snapshot.eventCursor, 'texts': ( + canvas.text_contents(snapshot, resolved_path=folder) + if snapshot.eventCursor == cursor else {})} + + @router.get('/projects/{project_id}/reference-evidence') + async def reference_evidence(project_id: UUID, cursor: int = Query(ge=1)): + def read(): + snapshot = projects.snapshot(project_id) + return {'cursor': snapshot.eventCursor, 'edges': ( + canvas.reference_edges(project_id, snapshot) if cursor == snapshot.eventCursor else [])} + + async with reference_checks: + return await run_in_threadpool(read) @router.get('/projects/{project_id}/edit-session') def edit_session(project_id: UUID, x_opendirector_session: UUID = Header()): diff --git a/packages/core/src/opendirector/application/creation_assets.py b/packages/core/src/opendirector/application/creation_assets.py index 4bc6bf5d6..eded85e95 100644 --- a/packages/core/src/opendirector/application/creation_assets.py +++ b/packages/core/src/opendirector/application/creation_assets.py @@ -50,6 +50,10 @@ def stage_copy(self, project_id, handle, session, source_project_id, source_asse def reference_available(self, project_id, asset_id, *, snapshot=None): stream, asset = self.open_media(project_id, asset_id, snapshot=snapshot) + return self.check_reference_media(stream, asset) + + @staticmethod + def check_reference_media(stream, asset): with stream: if asset.kind == 'text' and not stream.read().decode('utf-8-sig').strip(): raise ContractError('reference_invalid', '空白文本不能作为参考。', asset.id) @@ -201,30 +205,51 @@ def get(self, project_id, asset_id): raise ProjectError('素材不在当前工程中。', 404) from None def open_media(self, project_id, asset_id, *, snapshot=None): - """Pin the descriptor under the catalog lock, then verify outside it. + """Pin and verify bytes against a checked, immutable snapshot. Trusted queries may reuse a snapshot verified earlier in the same read. - Resolve the current path under the lock even then: a project rename must - never retarget media. No HTTP parameter can supply this read basis. """ - with self.projects.local.transaction() as db: - self.projects._recover() - if snapshot is not None and snapshot.project.id != UUID(str(project_id)): + if snapshot is not None: + if 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. - 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 - try: - asset = self._asset(snapshot, asset_id) - except ContractError: - raise ProjectError('素材不在当前工程中。', 404) from None - file = gateway().child(gateway().directory(gateway().child(path, 'assets')), str(asset.id)) - try: - stream = os.fdopen(os.open(file, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)), 'rb') - except FileNotFoundError: - raise ProjectError('素材文件缺失,元信息与历史已保留,请恢复文件。', 409, code='storage_unavailable') from None + return self.snapshot_media_reader(snapshot)(asset_id) + path, manifest = self.projects._published_manifest(project_id) + record, validated = self.projects._current_record(None, project_id, path, manifest) + if not validated: + record = self.projects._read_history(project_id, path, manifest)[0] + try: + asset = self._asset(record.snapshot, asset_id) + except ContractError: + raise ProjectError('素材不在当前工程中。', 404) from None + # A rename can move the project while its immutable history is read. + # Retry path resolution only if the file has actually moved. + try: + stream = self._pin_asset_file(path, asset) + except (OSError, ProjectError): + current_path, _ = self.projects._published_manifest(project_id) + if current_path == path: + raise + stream = self._pin_asset_file(current_path, asset) + return self._verify_media(stream, asset) + + def snapshot_media_reader(self, snapshot, *, resolved_path=None): + """Resolve the project directory once for a batch of display reads.""" + path = resolved_path + if path is None: + path, _ = self.projects._published_manifest(snapshot.project.id) + folder = gateway().directory(gateway().child(path, 'assets')) + assets = {asset.id: asset for asset in snapshot.assets} + + def read(asset_id): + asset = assets.get(UUID(str(asset_id))) + if asset is None: + raise ProjectError('素材不在当前工程中。', 404) + stream = self._open_asset_file(folder, asset) + return self._verify_media(stream, asset) + + return read + + def _verify_media(self, stream, asset): try: def signature(): stat = os.fstat(stream.fileno()) @@ -246,6 +271,19 @@ def signature(): stream.close() raise + @staticmethod + def _pin_asset_file(path, asset): + folder = gateway().directory(gateway().child(path, 'assets')) + return CreationAssets._open_asset_file(folder, asset) + + @staticmethod + def _open_asset_file(folder, asset): + file = gateway().child(folder, str(asset.id)) + try: + return os.fdopen(os.open(file, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)), 'rb') + except FileNotFoundError: + raise ProjectError('素材文件缺失,元信息与历史已保留,请恢复文件。', 409, code='storage_unavailable') from None + def preview(self, project_id: UUID, asset_id: UUID, target: Path) -> dict: stream, asset = self.open_media(project_id, asset_id) with stream: diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index f97c6af96..817c3e91c 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -824,12 +824,15 @@ def _asset_checker(self, snapshot): A projection shares one checker across reference edges and capabilities. """ availability = {} + read = None def check_asset(asset): + nonlocal read if asset.id not in availability: try: - availability[asset.id] = self.assets.reference_available( - asset.projectId, asset.id, snapshot=snapshot) + if read is None: + read = self.assets.snapshot_media_reader(snapshot) + availability[asset.id] = self.assets.check_reference_media(*read(asset.id)) except (ContractError, ProjectError, OSError) as error: availability[asset.id] = error value = availability[asset.id] @@ -839,18 +842,21 @@ def check_asset(asset): return check_asset - def text_contents(self, snapshot): + def text_contents(self, snapshot, *, resolved_path=None): """Text shown by canvas items, read with the snapshot that opens the canvas. An unreadable body is left out so only that item reports it. """ contents = {} + read = None for item in snapshot.canvasItems: asset = current_asset(snapshot, item) if asset is None or asset.kind != 'text' or str(asset.id) in contents: continue try: - stream, _ = self.assets.open_media(asset.projectId, asset.id, snapshot=snapshot) + if read is None: + read = self.assets.snapshot_media_reader(snapshot, resolved_path=resolved_path) + stream, _ = read(asset.id) with stream: contents[str(asset.id)] = stream.read().decode('utf-8-sig', 'replace') except (ContractError, ProjectError, OSError): diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index 8d817be3b..1690d370b 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -106,8 +106,9 @@ def _entry_states(cleared, entries): return states def reference_catalog(self, project_id): - snapshot = self.projects.snapshot(project_id) - current, _, historical = self._inventory(snapshot) + records, path = self.projects.records_with_path(project_id) + snapshot = records[0].snapshot + current, _, historical = self._inventory(snapshot, records=records) listed = {a.id for a in snapshot.assets if a.id not in historical or a.id in current} owners = {} for item in snapshot.canvasItems: @@ -120,12 +121,14 @@ def reference_catalog(self, project_id): if ref: owners.setdefault(ref.assetId, []).append(dict(nodeId=str(item.id), nodeTitle=item.title, sourceRole=role)) from opendirector.application.creation_assets import CreationAssets - service = CreationAssets(self.projects) + service = self.assets or CreationAssets(self.projects) + reader = service.snapshot_media_reader(snapshot, resolved_path=path) result = [] for asset in snapshot.assets: file_available = True try: - service.reference_available(project_id, asset.id, snapshot=snapshot) + stream, checked = reader(asset.id) + service.check_reference_media(stream, checked) except (ContractError, ProjectError, OSError, ValueError): file_available = False available = file_available and (asset.id in listed or asset.id in owners) @@ -142,12 +145,12 @@ def operations(self, project_id): for key in reversed(states)] def versions(self, project_id, spec_id): - snapshot = self.projects.snapshot(project_id) + records = self.projects.records(project_id) + snapshot = records[0].snapshot spec = next((s for s in snapshot.generationSpecs if str(s.id) == str(spec_id)), None) if spec is None: raise ContractError('missing_object', '生成配置不存在。', UUID(str(spec_id))) configurations, last = [], None - records = self.projects.history(project_id) accepted = {job_id: record.command.commandId for record in records for job_id in record.receipt.jobIds} for record in reversed(records): value = next((s for s in record.snapshot.generationSpecs if s.id == spec.id), None) @@ -156,12 +159,12 @@ def versions(self, project_id, spec_id): identity = dict(spec=value.model_dump(exclude={'revision', 'currentResultId'}), references=[r.model_dump(exclude={'revision'}) for r in refs]) if identity != last: - configurations.append(dict(commandId=record.command.commandId, spec=value, - references=refs)) + configurations.append(dict(commandId=record.command.commandId, spec=value.model_copy(deep=True), + references=[r.model_copy(deep=True) for r in refs])) last = identity - return dict(spec=spec, configurations=list(reversed(configurations)), - jobs=[dict(job=j, configurationCommandId=accepted.get(j.id)) for j in snapshot.jobs if j.inputSnapshot.spec.id == spec.id], - results=[dict(result=r, job=next(j for j in snapshot.jobs if j.id == r.jobId), configurationCommandId=accepted.get(r.jobId)) + return dict(spec=spec.model_copy(deep=True), configurations=list(reversed(configurations)), + jobs=[dict(job=j.model_copy(deep=True), configurationCommandId=accepted.get(j.id)) for j in snapshot.jobs if j.inputSnapshot.spec.id == spec.id], + results=[dict(result=r.model_copy(deep=True), job=next(j for j in snapshot.jobs if j.id == r.jobId).model_copy(deep=True), configurationCommandId=accepted.get(r.jobId)) for r in reversed(snapshot.results) if r.specId == spec.id]) def execute(self, command, *, session=None, source='ui'): @@ -393,7 +396,7 @@ def used(kind, obj, ids=None, *, exclude_self=False): *(output['id'] for output in task.get('outputs', []))} for key in ids & asset_keys.keys(): statuses[asset_keys[key]]['reasons'].append(dict(type='tool_task', id=task['id'])) - records = self.projects.history(snapshot.project.id) if records is None else records + records = self.projects.records(snapshot.project.id) if records is None else records historical_pins = {} for record in records: for ref in record.snapshot.references: @@ -477,7 +480,7 @@ def _inventory(self, snapshot, *, records=None): historical.update(source.assetId for asset in snapshot.assets for source in asset.provenance.sources) # Every adopted manual/uploaded sibling is a version, including a newer # sibling after applying an older version. Hidden current owners stay live. - for record in self.projects.history(snapshot.project.id) if records is None else records: + for record in self.projects.records(snapshot.project.id) if records is None else records: historical.update(asset.id for item in record.snapshot.canvasItems if (asset := current_asset(record.snapshot, item)) is not None) for doc in record.snapshot.editorDocuments: if doc.kind == 'subject': @@ -491,7 +494,7 @@ def _inventory(self, snapshot, *, records=None): return current, current_results, historical def asset_list(self, project_id, *, text='', usage='all', visibility='all', category='all', offset=0, limit=100): - records = self.projects.history(project_id) + records = self.projects.records(project_id) snapshot = records[0].snapshot current, current_results, historical = self._inventory(snapshot, records=records) visible = visible_item_ids(snapshot) diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 68f483efa..42b2b3ef8 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -183,8 +183,13 @@ def _directory(self, project_id, session=None): self.projects._lease(db, project_id, path, session) return path + def _read_directory(self, project_id): + path, manifest = self.projects._published_manifest(project_id) + self.projects._current(None, project_id, path, manifest) + return path + def list(self, project_id): - folder = self._folder(self._directory(project_id), create=False) + folder = self._folder(self._read_directory(project_id), create=False) tasks = [self._read_task(project_id, gateway().child(folder, path.name)) for path in folder.glob('*.json')] return sorted(tasks, key=lambda task: (task['createdAt'], task['id']), reverse=True) @@ -223,7 +228,9 @@ def _write(self, directory, task): def get(self, project_id, task_id, session=None): identifier(project_id) identifier(task_id) - path = gateway().child(self._folder(self._directory(project_id, session), create=False), task_id + '.json') + directory = (self._read_directory(project_id) if session is None + else self._directory(project_id, session)) + path = gateway().child(self._folder(directory, create=False), task_id + '.json') return self._read_task(project_id, path, session) def _read_task(self, project_id, path, session=None): diff --git a/packages/core/src/opendirector/infrastructure/creation_catalog.py b/packages/core/src/opendirector/infrastructure/creation_catalog.py index 7140cf34a..a3b3e88c8 100644 --- a/packages/core/src/opendirector/infrastructure/creation_catalog.py +++ b/packages/core/src/opendirector/infrastructure/creation_catalog.py @@ -1,7 +1,11 @@ """Project directory scan, catalog listing, and unreadable-folder cleanup.""" +import os +import stat import time from pathlib import Path +from filelock import Timeout + from opendirector.domain.projects import ProjectError, identifier, project_name from opendirector.infrastructure import recycle from opendirector.infrastructure.creation_records import Manifest @@ -31,38 +35,97 @@ def _manifest(cls, path): def _scan(self): self.local._check_root() grouped, manifests, unsupported, warnings = {}, {}, set(), list(self._warnings) - self._invalid = [] - if self.root.is_dir(): - for path in sorted(self.root.iterdir()): - if path.is_symlink() or not path.is_dir() or path.name.startswith('.opendirector-'): - continue - manifest_path = path / 'project.json' - if not manifest_path.exists() and not manifest_path.is_symlink(): - continue - try: - project_name(path.name) - raw = read_json(child(path, 'project.json')) - project_id = identifier(raw['id']) - grouped.setdefault(project_id, []).append(path) - if raw.get('format') != 'opendirector-project' or raw.get('formatVersion') != 2: - unsupported.add(project_id) - else: - # Parsed once per scan; callers never reread project.json. - manifests[project_id] = raw - except (OSError, ValueError, TypeError, KeyError, ProjectError): - warning = f'工程“{path.name}”的清单无法读取,原文件已保留。' - warnings.append(warning) - self._invalid.append((path, warning)) + invalid = [] + previous = self._manifest_cache + scanned = {} + try: + with os.scandir(self.root) as entries: + folders = sorted( + (entry for entry in entries if not entry.name.startswith('.opendirector-') + and entry.is_dir(follow_symlinks=False)), + key=lambda entry: entry.name, + ) + except FileNotFoundError: + folders = [] + for folder in folders: + path = Path(folder.path) + file = path / 'project.json' + try: + metadata = file.stat(follow_symlinks=False) + except FileNotFoundError: + continue + except OSError: + metadata = None + try: + project_name(folder.name) + if metadata is None or not stat.S_ISREG(metadata.st_mode): + raise ValueError('Invalid project manifest file') + signature = (metadata.st_dev, metadata.st_ino, metadata.st_size, + metadata.st_mtime_ns, metadata.st_ctime_ns) + cached = previous.get(file) + # Windows ctime does not detect an external rewrite with restored mtime. + if os.name != 'nt' and cached and cached[0] == signature: + raw = cached[1] + else: + raw = read_json(file) + scanned[file] = (signature, raw) + project_id = identifier(raw['id']) + grouped.setdefault(project_id, []).append(path) + if raw.get('format') != 'opendirector-project' or raw.get('formatVersion') != 2: + unsupported.add(project_id) + else: + # Parsed once per scan; callers never reread project.json. + manifests[project_id] = raw + except (OSError, ValueError, TypeError, KeyError, ProjectError): + warning = f'工程“{path.name}”的清单无法读取,原文件已保留。' + warnings.append(warning) + invalid.append((path, warning)) conflicts = {key for key, paths in grouped.items() if len(paths) > 1} for key in sorted(conflicts): warnings.append(f'工程标识重复:{key};请移走重复目录后重试。') - return grouped, manifests, unsupported, conflicts, warnings + self._manifest_cache = scanned + return grouped, manifests, unsupported, conflicts, warnings, invalid + + def _directory_version(self): + try: + info = self.root.stat() + return info.st_dev, info.st_ino, info.st_mtime_ns, info.st_ctime_ns + except FileNotFoundError: + return None + + def _navigation_basis(self, project_id): + key = identifier(str(project_id)) + while True: + version = self._directory_version() + index = self._navigation_index + if index is None or index[0] != version or time.monotonic() - index[1] > 10: + grouped, _, _, _, _, _ = self._scan() + if self._directory_version() != version: + continue + index = (version, time.monotonic(), grouped) + self._navigation_index = index + paths = index[2].get(key, ()) + if len(paths) != 1: + return self._find(None, key), version + try: + manifest = self._manifest(paths[0]) + except (OSError, ProjectError): + self._navigation_index = None + return self._find(None, key), version + if str(manifest.id) == key: + return (paths[0], manifest), version + self._navigation_index = None def _find(self, db, project_id): project_id = identifier(str(project_id)) if project_id in self._blocked: raise ProjectError('工程提交需要恢复;请检查磁盘及工程文件后重试。', 409, code='storage_unavailable') - grouped, manifests, unsupported, conflicts, _ = self._scan() + if db is not None and self._journal(project_id).exists(): + # An incomplete intent cannot be used as a writable basis. + # The publication lock must never be awaited under catalog.lock. + with self._publication_lock(project_id).acquire(timeout=0): + pass + grouped, manifests, unsupported, conflicts, _, _ = self._scan() if project_id in conflicts: raise ProjectError('projects 中存在同标识工程,请移走重复目录后重试。', 409) if project_id in unsupported: @@ -80,11 +143,13 @@ def _find(self, db, project_id): def _unreadable_item(path, reason, project_id=None): return dict(id=project_id, name=path.name, path=str(path), reason=reason) - def _catalog(self, db): + def _catalog(self, *, navigation=False): # One directory scan for the whole listing: resolving each project with # _find() reread every project.json once per project (O(N^2)). - grouped, manifests, unsupported, conflicts, warnings = self._scan() - invalid = list(self._invalid) + version = self._directory_version() + grouped, manifests, unsupported, conflicts, warnings, invalid = self._scan() + if version == self._directory_version(): + self._navigation_index = (version, time.monotonic(), grouped) projects = [] unreadable = [self._unreadable_item(path, reason) for path, reason in invalid] for project_id in sorted(grouped): @@ -105,6 +170,10 @@ def _catalog(self, db): path = paths[0] raw = manifests.get(project_id) manifest = self._manifest(path) if raw is None else self._parse_manifest(raw) + if navigation: + # Opening a row validates the authoritative head before granting a lease. + projects.append(dict(id=project_id, name=manifest.name, path=str(path))) + continue # Parsing the head alone proves the project still opens, and the # manifest already carries the name it must agree with; a full # chain replay just to list a name cost about a second. @@ -123,10 +192,39 @@ def _catalog(self, db): unreadable.sort(key=lambda item: (item['name'].casefold(), item['name'])) return dict(projects=projects, unreadable=unreadable, warnings=warnings) - def list_projects(self): + def list_projects(self, *, navigation=False): + # Head records are immutable. Catalogue validation must not hold storage + # coordination for the time it takes to decode every project's head. + directory(self.intents) + if not navigation and (self._warnings or next(self.intents.glob('*.json'), None) is not None): + with self.local.transaction(): + self._recover() + return self._catalog(navigation=navigation) + + def _published_manifest(self, project_id): + project_id = identifier(str(project_id)) + journal = self._journal(project_id) + if not journal.exists() and project_id not in self._blocked: + try: + current = self._find(None, project_id) + except ProjectError as error: + # A rename can briefly hide a directory during publication. + if not journal.exists() and error.status != 404: + raise + else: + if not journal.exists(): + return current + if journal.exists() and project_id not in self._blocked: + try: + with self._publication_lock(project_id).acquire(timeout=0): + pass + except Timeout: + # Ordinary publication leaves the directory in place. Its + # atomic manifest still names a complete immutable commit. + return self._find(None, project_id) with self.local.transaction() as db: self._recover() - return self._catalog(db) + return self._find(db, project_id) @staticmethod def _cleanup_blocker(db, project_id, path): @@ -151,12 +249,12 @@ def cleanup_unreadable(self): """Remove only directories that a fresh catalog read still cannot open.""" with self.local.transaction() as db: self._recover() - candidates = self._catalog(db)['unreadable'] + candidates = self._catalog()['unreadable'] removed, failed = [], [] for candidate in candidates: with self.local.transaction() as db: self._recover() - current = next((item for item in self._catalog(db)['unreadable'] + current = next((item for item in self._catalog()['unreadable'] if item['path'] == candidate['path']), None) if current is None: continue @@ -187,4 +285,6 @@ def cleanup_unreadable(self): db.execute('DELETE FROM sessions WHERE project_id=?', (current['id'],)) if removed: sync_directory(self.root) + with self.local.transaction(): + self._recover() return dict(removed=removed, failed=failed) diff --git a/packages/core/src/opendirector/infrastructure/creation_commit_log.py b/packages/core/src/opendirector/infrastructure/creation_commit_log.py index 048c968b2..a6f7a3876 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 +import time from contextlib import contextmanager from hashlib import sha256 @@ -18,7 +19,7 @@ # that, each read reparses every record from disk and holds the catalog lock # long enough to expire sessions and interrupt running jobs. RECORD_CACHE_ENTRIES = 4096 -RECORD_CACHE_BYTES = 512 * 1024 * 1024 +RECORD_CACHE_BYTES = 1024 * 1024 * 1024 # Only the validated head of each open project is kept, so this stays small. CURRENT_CACHE_ENTRIES = 16 # A head served without replaying its ancestry is validated in the background @@ -78,19 +79,20 @@ def _record(self, path, head): if content != cached[2]: raise ValueError('Commit content changed') return cached[1] - raw = file.read_bytes() if self._verify_record_bytes else None - content = sha256(raw).digest() if raw is not None else None - if raw is not None and _file_signature(file) != before: + raw = file.read_bytes() + content = sha256(raw).digest() if self._verify_record_bytes else None + if self._verify_record_bytes and _file_signature(file) != before: raise ValueError('Commit changed during read') - if cached and cached[0] == before and cached[2] == content: - self._records_cache.move_to_end(file) + if cached and cached[0] == before and self._verify_record_bytes and cached[2] == content: + with self._cache_lock: + self._records_cache.move_to_end(file) return cached[1] if cached: with self._cache_lock: removed = self._records_cache.pop(file, None) if removed is not None: self._records_cache_bytes -= removed[0][2] - record = CommitRecord.model_validate_json(raw) if raw is not None else CommitRecord.model_validate(read_json(file)) + record = CommitRecord.model_validate_json(raw) if _file_signature(file) != before: raise ValueError('Commit changed during read') if before[2] <= 8 * 1024 * 1024: @@ -112,6 +114,7 @@ def _record(self, path, head): def _history(self, path, manifest): records, seen, head = [], set(), manifest.head + last_yield = time.perf_counter() while head is not None: if head in seen: raise ProjectError('工程提交历史存在循环,原文件已保留。', 409, code='storage_unavailable') @@ -125,6 +128,12 @@ def _history(self, path, manifest): raise ProjectError('工程变更游标不连续,原文件已保留。', 409, code='storage_unavailable') records.append(record) head = record.previousHead + now = time.perf_counter() + if now - last_yield >= 0.025: + # Periodically release the GIL during long cold-history parses so + # the ASGI event loop can keep serving static assets and opens. + time.sleep(0.001) + last_yield = time.perf_counter() if (not records or records[-1].command.type != 'project.create' or records[-1].snapshot.eventCursor != 1 or records[0].snapshot.project.name != manifest.name): raise ProjectError('工程提交历史与清单不一致,原文件已保留。', 409, code='storage_unavailable') @@ -211,7 +220,7 @@ def _await_current_warm(self, project_id, timeout=30): if not inflight: return try: - head = self.head(project_id) + head = self._published_manifest(project_id)[1].head except ProjectError: return self._await_warm(project_id, head, timeout) @@ -286,10 +295,16 @@ def _current(self, db, project_id, path, manifest): return self._current_record(db, project_id, path, manifest)[0] def snapshot(self, project_id): - with self.local.transaction() as db: - self._recover() - path, manifest = self._find(db, project_id) - return self._current(db, project_id, path, manifest).snapshot.model_copy(deep=True) + path, manifest = self._published_manifest(project_id) + while True: + try: + record, _ = self._current_record(None, project_id, path, manifest) + return record.snapshot.model_copy(deep=True) + except (OSError, ProjectError): + current = self._published_manifest(project_id) + if current == (path, manifest): + raise + path, manifest = current def head(self, project_id): """The current head commit, cheap enough to gate content-addressed caches. @@ -332,6 +347,11 @@ def _write_basis(self, project_id): yield db, path, manifest, records return + def records_with_path(self, project_id): + """Private commit records plus the resolved project directory for read-only scans.""" + path, manifest = self._published_manifest(project_id) + return self._read_history_with_path(project_id, path, manifest) + def records(self, project_id): """Private commit records for read-only scans; callers must not mutate them. @@ -339,19 +359,38 @@ def records(self, project_id): around. Scans that only count versions or owners would copy hundreds of megabytes for long histories, so they read the shared records directly. """ - path, manifest = self._read_manifest(project_id) - return tuple(self._read_history(project_id, path, manifest)) + return self.records_with_path(project_id)[0] - def _read_history(self, project_id, path, manifest): + def _read_history_with_path(self, project_id, path, manifest): while True: + self._await_warm(project_id, manifest.head) + key = (str(path), str(manifest.head)) + leader = False + with self._warm_lock: + inflight = self._history_inflight.get(key) + if inflight is None: + inflight = threading.Event() + self._history_inflight[key] = inflight + leader = True + if not leader: + inflight.wait(30) try: - return self._history(path, manifest) + return tuple(self._history(path, manifest)), path except (OSError, ProjectError): # The immutable files can move together when a project is renamed. - current = self._read_manifest(project_id) + current = self._published_manifest(project_id) if current == (path, manifest): raise path, manifest = current + finally: + if leader: + with self._warm_lock: + if self._history_inflight.get(key) is inflight: + self._history_inflight.pop(key, None) + inflight.set() + + def _read_history(self, project_id, path, manifest): + return list(self._read_history_with_path(project_id, path, manifest)[0]) def history(self, project_id): records = self.records(project_id) @@ -382,16 +421,11 @@ def changes(self, project_id, *, after=0, limit=100): # catalog lock keeps a caught-up subscriber from replaying the same # chain while the lock is held. self._await_current_warm(project_id) - with self.local.transaction() as db: - self._recover() - path, manifest = self._find(db, project_id) - # A subscriber that is already caught up is the common polling - # path. Replaying the commit chain here held the catalog lock for - # about a second per poll on Windows and starved saves/heartbeats. - head, validated = self._current_record(db, project_id, path, manifest) - cursor = head.snapshot.eventCursor - if after > cursor: - raise ProjectError('变更游标超出当前工程,请重新读取快照。', 409) + path, manifest = self._published_manifest(project_id) + head, validated = self._current_record(None, project_id, path, manifest) + cursor = head.snapshot.eventCursor + if after > cursor: + raise ProjectError('变更游标超出当前工程,请重新读取快照。', 409) if after == cursor and validated: return dict(events=[], nextCursor=after, currentCursor=cursor, hasMore=False) records = self._read_history(project_id, path, manifest) diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index 4c5a45ff8..ec6d7572a 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -1,9 +1,10 @@ """File-authoritative creation projects, using LocalProjects coordination. An immutable commit contains the snapshot, command receipt and outbox event. -A durable intent precedes every filesystem mutation. Publishing project.json -is the commit point; reads first finish pending intents under the catalog lock. -SQLite coordinates leases only and is never used to roll back file writes. +A durable intent precedes every filesystem mutation. Project publication +atomically replaces project.json. Reads can use that complete version while +a live writer holds a project lock. Recovery completes abandoned intents. +SQLite coordinates leases and is never used to roll back file writes. Catalog scans, commit history, and publication live in sibling modules. Command dispatch lives in ``application.creation_commands``. ``execute`` delegates @@ -13,6 +14,9 @@ import threading import time from collections import OrderedDict +from collections.abc import Callable +from functools import partial +from pathlib import Path from uuid import UUID from opendirector.domain.creation.base import digest @@ -57,7 +61,10 @@ def __init__(self, local: LocalProjects): self.intents = directory(child(self.state_dir, 'creation-commits')) self._blocked = {} self._warnings = [] - self._invalid = [] + self._manifest_cache = {} + self._navigation_index = None + self._publication_locks = {} + self._publication_locks_guard = threading.Lock() self._records_cache = OrderedDict() self._records_cache_bytes = 0 # Windows ctime is creation time. Verify bytes there before reusing a @@ -71,6 +78,9 @@ def __init__(self, local: LocalProjects): self._warm_lock = threading.Lock() # (project id, head) -> Event. A save waits only for the head it will read. self._warming = {} + # (path, head) -> Event. Concurrent cold history reads coalesce instead of + # parsing the same commit chain in parallel and starving the GIL. + self._history_inflight = {} # (project id, head) -> True after that head's ancestry was proved. # A failed attempt is absent so the next open can try again. self._warmed = OrderedDict() @@ -103,46 +113,92 @@ def _closed(self, db, project_id, snapshot, verb='重命名'): if tools.exists() and any(read_json(child(tools, item.name)).get('status') in {'queued', 'running'} for item in tools.glob('*.json')): raise ProjectError(f'工程仍有工具任务,请等待或取消任务后再{verb}。', 409) - def view(self, project_id, client_id, value=None, *, session=None, missing_ok=False): - with self.local.transaction() as db: - self._recover() - path, _ = self._find(db, project_id) - folder = directory(child(path, 'views')) - file = child(folder, f'{UUID(str(client_id))}.json') - if value is not None: + def view(self, project_id, client_id, value=None, *, session=None, missing_ok=False, resolved_path=None): + filename = f'{UUID(str(client_id))}.json' + if value is None: + path = resolved_path + if path is None: + path, _ = self._published_manifest(project_id) + file = child(directory(child(path, 'views')), filename) + try: + stored = read_json(file) + except FileNotFoundError: + return None if missing_ok else ViewState(projectId=project_id, clientId=client_id) + view = ViewState.model_validate(stored) + if view.projectId != UUID(str(project_id)) or view.clientId != UUID(str(client_id)): + raise ProjectError('视图不属于当前工程或客户端。') + return view + value = ViewState.model_validate(value) + if str(value.projectId) != str(project_id) or str(value.clientId) != str(client_id): + raise ProjectError('视图不属于当前工程或客户端。') + if self._journal(project_id).exists() or str(project_id) in self._blocked: + with self.local.transaction(): + self._recover() + while True: + (path, manifest), version = self._navigation_basis(project_id) + with self.local.transaction() as db: + self._recover() + if version != self._directory_version() or self._manifest(path) != manifest: + self._navigation_index = None + continue + if str(project_id) in self._blocked or self._journal(project_id).exists(): + path, _ = self._find(db, project_id) self._lease(db, project_id, path, session) - value = ViewState.model_validate(value) - if str(value.projectId) != str(project_id) or str(value.clientId) != str(client_id): - raise ProjectError('视图不属于当前工程或客户端。') + folder = directory(child(path, 'views')) folder.mkdir(exist_ok=True) - durable_json(file, value.model_dump(mode='json')) + durable_json(child(folder, filename), value.model_dump(mode='json')) return value - if file.exists(): - return ViewState.model_validate(read_json(file)) - return None if missing_ok else ViewState(projectId=project_id, clientId=client_id) + + def canvas_read_basis(self, project_id): + # A background canvas read uses the same published project identity + # as navigation. Pending recovery still follows the normal read path. + if self._journal(project_id).exists() or str(project_id) in self._blocked: + path, manifest = self._published_manifest(project_id) + else: + (path, manifest), _ = self._navigation_basis(project_id) + record, _ = self._current_record(None, project_id, path, manifest) + return record.snapshot, path def open_canvas( self, project_id: UUID | str, session: str, *, allow_preview: bool, persistent: bool = False, + after_response: Callable[[Callable[[], None]], None] | None = None, + on_resolved: Callable[[Path], None] | None = None, + copy_snapshot: bool = True, ) -> tuple[ProjectSnapshot, dict[str, str | None]]: - with self.local.transaction() as db: - self._recover() - path, manifest = self._find(db, project_id) - project = dict(id=str(project_id), path=str(path)) - if allow_preview: - editor = self.local.editor(db, str(project_id)) - if editor and editor['id'] != session: - db.execute("DELETE FROM sessions WHERE id=?", (session,)) - else: - self.local.acquire_edit_lease(db, project, session, persistent=True) + if self._journal(project_id).exists(): + with self.local.transaction(): + self._recover() + while True: + (path, manifest), version = self._navigation_basis(project_id) + with self.local.transaction() as db: + self._recover() + if version != self._directory_version(): + continue + if str(project_id) in self._blocked or self._journal(project_id).exists(): + with self._publication_lock(project_id).acquire(timeout=0): + if str(project_id) in self._blocked: + raise ProjectError('工程提交需要恢复;请检查磁盘及工程文件后重试。', 409, code='storage_unavailable') + if self._manifest(path) != manifest: + self._navigation_index = None + continue + project = dict(id=str(project_id), path=str(path)) + editing = self.local.acquire_edit_lease( + db, project, session, persistent=allow_preview or persistent, + allow_preview=allow_preview, + ) + state = {"mode": "edit" if editing else "preview"} + record, validated = self._current_record(db, project_id, path, manifest) + break + if on_resolved is not None: + on_resolved(path) + if not validated: + warm = partial(self._schedule_warm, path, manifest) + if after_response is None: + warm() else: - self.local.acquire_edit_lease(db, project, session, persistent=persistent) - state = self.local.editing_state(db, str(project_id), session) - record, validated = self._current_record(db, project_id, path, manifest) - if not validated: - # The canvas is open now; prove the ancestry in the background - # so the first autosave does not replay it under the lock. - self._schedule_warm(path, manifest) - return record.snapshot.model_copy(deep=True), state + after_response(warm) + snapshot = record.snapshot.model_copy(deep=True) if copy_snapshot else record.snapshot + return snapshot, state def open(self, project_id: UUID | str, session: str, *, persistent=False) -> ProjectSnapshot: snapshot, _ = self.open_canvas(project_id, session, allow_preview=False, persistent=persistent) @@ -168,7 +224,7 @@ def _create(self, command, source): name = project_name(command.payload.name) with self.local.transaction() as db: self._recover() - grouped, _, _, _, _ = self._scan() + grouped, _, _, _, _, _ = self._scan() if str(command.projectId) in self._blocked: self._find(db, command.projectId) if str(command.projectId) in grouped: diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index 3b14da792..8b016f528 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -1,10 +1,14 @@ """Publish one already-decided commit and finish a pending journal on read. The journal is written before any project file changes. ``project.json`` is the -commit point. Recovery finishes that intent; it does not choose a new command. +commit point. Ordinary commits publish under a project lock. Recovery finishes +abandoned intents, and directory-changing commands keep catalog coordination. """ from collections.abc import Callable +import os +from uuid import UUID +from filelock import FileLock, Timeout from pydantic import ValidationError from opendirector.domain.creation.base import digest @@ -44,6 +48,12 @@ def commit(self, command: Command, session=None, source='ui', files=(), deletes=(), with_history=False): if source not in {'ui', 'agent', 'background', 'external'}: raise ProjectError('无效的命令来源。') + if command.type in {'project.rename', 'project.trash'}: + return self._commit(command, apply, session, source, files, deletes, with_history) + with self._publication_lock(command.projectId): + return self._commit(command, apply, session, source, files, deletes, with_history) + + def _commit(self, command, apply, session, source, files, deletes, with_history): with self._write_basis(command.projectId) as (db, path, manifest, records): replay = self._replay(records, command) if replay: @@ -96,9 +106,16 @@ def commit(self, command: Command, snapshot = ProjectSnapshot.model_validate({**snapshot.model_dump(), 'eventCursor': before.eventCursor + 1}) record = self._make_record(command, manifest.head, snapshot, changed, source, issue) to_name = snapshot.project.name if command.type == 'project.rename' and changed else path.name - return self._publish(CommitIntent(fromName=path.name, toName=to_name, - beforeFingerprint=digest(before), record=record, files=files if changed and issue is None else (), - deletes=deletes if changed and issue is None else ()), validated_history=True) + intent = CommitIntent( + fromName=path.name, toName=to_name, beforeFingerprint=digest(before), + record=record, files=files if changed and issue is None else (), + deletes=deletes if changed and issue is None else ()) + if command.type in {'project.rename', 'project.trash'}: + return self._publish(intent, validated_history=True) + # The current version and editor were checked while coordination + # was held. The durable intent fences further work on this project. + self._write_intent(intent) + return self._publish_intent(intent, validated_history=True) @staticmethod def _make_record(command, head, snapshot, changed, source, issue=None): @@ -112,7 +129,24 @@ def _make_record(command, head, snapshot, changed, source, issue=None): return CommitRecord(command=command, previousHead=head, snapshot=snapshot, receipt=receipt, event=event) def _journal(self, project_id): - return child(directory(self.intents), f'{project_id}.json') + base = directory(self.intents).resolve() + filename = f'{UUID(str(project_id))}.json' + path = child(base, filename) + normalized = os.path.normpath(str(path)) + if not normalized.startswith(os.path.normpath(str(base)) + os.sep): + raise ProjectError('工程标识无效。', 400) + return path + + def _publication_lock(self, project_id): + key = identifier(str(project_id)) + with self._publication_locks_guard: + lock = self._publication_locks.get(key) + if lock is None: + folder = directory(child(self.state_dir, 'creation-publication-locks')) + folder.mkdir(exist_ok=True) + lock = FileLock(child(folder, f'{key}.lock'), timeout=15) + self._publication_locks[key] = lock + return lock def _temporary(self, intent): # Compact UUIDs retain both identities while keeping Windows staging @@ -120,6 +154,10 @@ def _temporary(self, intent): return child(self.root, f'.opendirector-creation-{intent.record.command.projectId.hex}-{intent.record.command.commandId.hex}') def _publish(self, intent, *, validated_history=False): + self._write_intent(intent) + return self._publish_intent(intent, validated_history=validated_history) + + def _write_intent(self, intent): self.intents.mkdir(exist_ok=True) sync_directory(self.state_dir) temporary = self._temporary(intent) @@ -129,6 +167,8 @@ def _publish(self, intent, *, validated_history=False): if journal.exists(): raise ProjectError('工程已有待恢复的提交。', 409, code='storage_unavailable') durable_json(journal, intent.model_dump(mode='json')) + + def _publish_intent(self, intent, *, validated_history): self._checkpoint('journaled') self._finish(intent, validated_history=validated_history) return intent.record.receipt @@ -248,10 +288,17 @@ def _recover(self): self._warnings.append('发现无法识别的提交日志,文件已保留。') continue try: - intent = CommitIntent.model_validate(read_json(child(self.intents, file.name))) - if str(intent.record.command.projectId) != project_id: - raise ValueError('Journal filename differs from its project') - self._finish(intent) + # An active writer owns only its project. Never wait for it + # while holding the catalog lock, including across processes. + with self._publication_lock(project_id).acquire(timeout=0): + if not file.exists(): + continue + intent = CommitIntent.model_validate(read_json(child(self.intents, file.name))) + if str(intent.record.command.projectId) != project_id: + raise ValueError('Journal filename differs from its project') + self._finish(intent) + except Timeout: + continue except (OSError, ValueError, TypeError, KeyError, ProjectError): self._blocked[project_id] = True self._warnings.append(f'工程 {project_id} 的提交需要恢复,相关文件已保留。') diff --git a/packages/core/src/opendirector/infrastructure/local_projects.py b/packages/core/src/opendirector/infrastructure/local_projects.py index 3777bc550..9d15bb1a3 100644 --- a/packages/core/src/opendirector/infrastructure/local_projects.py +++ b/packages/core/src/opendirector/infrastructure/local_projects.py @@ -89,6 +89,7 @@ def __init__(self, repository: Path): id TEXT PRIMARY KEY, project_id TEXT NOT NULL, expires REAL NOT NULL, path TEXT NOT NULL DEFAULT '' ); + CREATE INDEX IF NOT EXISTS sessions_project ON sessions(project_id); """) db.execute("DELETE FROM sessions WHERE expires<=?", (time.time(),)) @@ -122,22 +123,32 @@ def _conflict(parent: Path, name: str, source: Path | None = None): raise ProjectError("该位置已有同名文件或文件夹,请使用其他名称。", 409) - def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str, *, persistent=False) -> None: + def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str, *, + persistent=False, allow_preview=False) -> bool: identifier(session) - project_id = project["id"] - if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND id NOT LIKE ? AND expires>?", - (project_id, session, self._AGENT_SESSION_PREFIX + "%", time.time())).fetchone(): - raise ProjectError("该项目正在其他窗口中打开,请先关闭后再试。", 409, code="project_open_elsewhere") - lease = db.execute("SELECT path, expires FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone() - if lease and lease["path"] != project["path"]: - raise ProjectError("项目目录已在应用外改名或移动,请复制未保存内容并刷新页面。", 409) - expires = float("inf") if persistent or (lease and lease["expires"] == float("inf")) else time.time() + self.LEASE_SECONDS - db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, expires, project["path"])) - + now = time.time() + editor = self.editor(db, project["id"], now=now) + if editor and editor["id"] != session: + if not allow_preview: + raise ProjectError("该项目正在其他窗口中打开,请先关闭后再试。", 409, code="project_open_elsewhere") + db.execute("DELETE FROM sessions WHERE id=?", (session,)) + return False + if editor: + if editor["path"] != project["path"]: + raise ProjectError("项目目录已在应用外改名或移动,请复制未保存内容并刷新页面。", 409) + if editor["expires"] == float("inf"): + return True + expires = float("inf") if persistent else now + self.LEASE_SECONDS + db.execute( + "INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) " + "ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", + (session, project["id"], expires, project["path"]), + ) + return True def editor(self, db, project_id, *, now=None): return db.execute( - "SELECT id FROM sessions WHERE project_id=? AND id NOT LIKE ? AND expires>?", + "SELECT id, path, expires FROM sessions WHERE project_id=? AND id NOT LIKE ? AND expires>? LIMIT 1", (project_id, self._AGENT_SESSION_PREFIX + "%", time.time() if now is None else now), ).fetchone() diff --git a/src/backend/api.ts b/src/backend/api.ts index 0f19b2551..b6e7d9d91 100644 --- a/src/backend/api.ts +++ b/src/backend/api.ts @@ -1,3 +1,4 @@ +import { PriorityLimiter } from "./priorityLimiter.ts"; /** Requests to the local OpenDirector API started by scripts/opendirector.py. */ import { detectLocale } from "../i18n/locale.ts"; import type { Locale } from "../i18n/types.ts"; @@ -96,7 +97,22 @@ export function setLeaseRecovery(recover: LeaseRecovery | undefined) { const PROJECT_PATH = /^\/creation\/projects\/([^/?]+)\//; -export async function request( +// Leave connection capacity for opening projects and accepting commands. +const backgroundReads = new PriorityLimiter(2); +export function backgroundRead(task: () => Promise, signal?: AbortSignal) { + return backgroundReads.run(task, { signal }); +} + +const BACKGROUND_PROJECT_READ = /^\/creation\/projects\/[^/]+\/(?:assistant(?:\/[^?]*)?|reference-catalog|reference-evidence|canvas-texts|history|version-counts)(?:\?|$)/; + +export function request(path: string, options: RequestInit = {}, leaseRenewed = false): Promise { + const run = () => requestNow(path, options, leaseRenewed); + if ((options.method === undefined || options.method === "GET") && BACKGROUND_PROJECT_READ.test(path)) + return backgroundRead(run, options.signal ?? undefined); + return run(); +} + +async function requestNow( path: string, options: RequestInit = {}, leaseRenewed = false, @@ -126,7 +142,7 @@ export async function request( !options.signal?.aborted && (await leaseRecovery(projectId).catch(() => false)) ) { - if (requestedSession === sessionId) return request(path, options, true); + if (requestedSession === sessionId) return requestNow(path, options, true); } throw error; } diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 60c53678b..4e5c8b467 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -15,6 +15,7 @@ import type { } from "../contracts/generated.ts"; import { ApiError, + backgroundRead, headers, json, reloadedTab, @@ -68,6 +69,11 @@ export class CreationCommandError extends Error { } } +type ReferenceEdgeEvidence = { + referenceId: string; + state: "used" | "pending" | "unknown" | "unavailable"; +}; + /** One server snapshot and one command queue per open project. No writable * business graph, browser result ownership or generation history is persisted. */ export class CreationClient { @@ -83,6 +89,9 @@ export class CreationClient { }; private listeners = new Set<(snapshot: ProjectSnapshot) => void>(); private subscription: AbortController | undefined; + private textRead?: AbortController; + private deferredTexts?: { cursor: number; contents?: Record }; + private referenceCheck: AbortController | undefined; private media = new Map>(); private sourceAssets = new Map(); /** Bytes behind each object URL. The desktop CSP does not allow fetching blob URLs. */ @@ -136,22 +145,19 @@ export class CreationClient { } } async open() { - this.viewState = undefined; - this.viewPersisted = false; - this.viewRead = undefined; + // The view belongs to this project and browser tab across switches. this.historyRead = undefined; + this.textRead?.abort(); + this.referenceCheck?.abort(); this.referenceStates = new Map(); - // The saved viewport is independent of the snapshot; prefetch it so the - // first render does not wait for a separate serial round trip. - void this.view().catch(() => {}); let canvas: | { snapshot: ProjectSnapshot; - edges: { - referenceId: string; - state: "used" | "pending" | "unknown" | "unavailable"; - }[]; + edges: ReferenceEdgeEvidence[]; + referenceChecksDeferred?: boolean; texts?: Record; + textsDeferred?: boolean; + view?: ViewState | null; } | undefined; for (let attempt = 0; ; attempt++) { @@ -160,16 +166,22 @@ export class CreationClient { | ProjectSnapshot | { snapshot: ProjectSnapshot; - edges: { - referenceId: string; - state: "used" | "pending" | "unknown" | "unavailable"; - }[]; + edges: ReferenceEdgeEvidence[]; + referenceChecksDeferred?: boolean; texts?: Record; + textsDeferred?: boolean; + view?: ViewState | null; editing?: unknown; } >(`${creationPath(this.id)}/open-canvas`, { method: "POST", - headers: { "X-OpenDirector-Allow-Preview": "true" }, + priority: "high", + headers: { + "X-OpenDirector-Allow-Preview": "true", + "X-OpenDirector-Defer-Texts": "true", + "X-OpenDirector-View-Client": viewClientId, + "X-OpenDirector-Defer-Reference-Checks": "true", + }, }); // The open-canvas response carries the one authoritative snapshot plus // the reference evidence the canvas draws; a bare snapshot response is @@ -189,6 +201,12 @@ export class CreationClient { // waits for a separate read per node. for (const [assetId, text] of Object.entries(canvas?.texts ?? {})) this.text.set(assetId, Promise.resolve(text)); + if (canvas && "view" in canvas) { + if (!this.viewState) this.installView(canvas.view ?? undefined); + } else { + void this.view().catch(() => {}); + } + this.deferredTexts = canvas?.textsDeferred ? { cursor: canvas.snapshot.eventCursor } : undefined; this.install(canvas ? canvas.snapshot : (opened as ProjectSnapshot)); break; } catch (error) { @@ -210,6 +228,8 @@ export class CreationClient { } } if (!canvas) await this.refresh(); + if (canvas?.textsDeferred) this.readDeferredTexts(); + if (canvas?.referenceChecksDeferred) this.checkReferences(canvas.snapshot); this.subscribe(); return this.snapshot; } @@ -218,16 +238,69 @@ export class CreationClient { throw new Error(tNow("errors.backend.snapshotMismatch")); if (this.snapshot && snapshot.eventCursor < this.snapshot.eventCursor) return; + const changed = this.snapshot && this.snapshot.eventCursor !== snapshot.eventCursor; this.snapshot = snapshot; + if (changed && this.deferredTexts && !this.deferredTexts.contents) this.readDeferredTexts(); for (const listener of this.listeners) listener(snapshot); } + projectedText(assetId: string) { + if (!this.deferredTexts) return; + const { contents } = this.deferredTexts; + if (!contents) return { state: "loading" as const }; + const text = contents[assetId]; + if (text === undefined) + return this.deferredTexts.cursor === this.snapshot.eventCursor ? { state: "missing" as const } : undefined; + return { state: "ready" as const, text }; + } + private readDeferredTexts() { + const pending = this.deferredTexts; + if (!pending || pending.contents) return; + this.textRead?.abort(); + const controller = new AbortController(); + this.textRead = controller; + const cursor = this.snapshot.eventCursor; + void storageRequest<{ cursor: number; texts: Record }>( + `${creationPath(this.id)}/canvas-texts?cursor=${cursor}`, + { signal: controller.signal }, + ).then((result) => { + if (controller.signal.aborted || this.deferredTexts !== pending) return; + if (result.cursor !== cursor || this.snapshot.eventCursor !== cursor) return; + pending.cursor = cursor; + pending.contents = result.texts; + for (const [id, text] of Object.entries(result.texts)) + this.text.set(id, Promise.resolve(text)); + for (const listener of this.mediaListeners) listener(); + }).catch(() => { + if (controller.signal.aborted || this.deferredTexts !== pending) return; + pending.contents = {}; + for (const listener of this.mediaListeners) listener(); + }); + } + private checkReferences(snapshot: ProjectSnapshot) { + const controller = new AbortController(); + this.referenceCheck = controller; + const cursor = snapshot.eventCursor; + const timer = setTimeout(() => { + void storageRequest<{ cursor: number; edges: ReferenceEdgeEvidence[] }>( + `${creationPath(this.id)}/reference-evidence?cursor=${cursor}`, + { signal: controller.signal }, + ).then((result) => { + if (controller.signal.aborted || this.snapshot !== snapshot || result.cursor !== cursor) + return; + this.referenceStates = new Map( + result.edges.map((edge) => [edge.referenceId, edge.state]), + ); + this.install(snapshot); + }).catch(() => { + // A later refresh can recover evidence independently of opening. + }); + }, 500); + controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true }); + } async refresh() { const projection = await storageRequest<{ snapshot: ProjectSnapshot; - edges: { - referenceId: string; - state: "used" | "pending" | "unknown" | "unavailable"; - }[]; + edges: ReferenceEdgeEvidence[]; }>(`${creationPath(this.id)}/canvas`); if ( !this.snapshot || @@ -407,19 +480,19 @@ export class CreationClient { options.browserImage && (mime === "image/heic" || mime === "image/heif") ? "browser-image" : "content"; - return this.mediaReader.run( - () => - resilientRead( + const read = () => resilientRead( async (signal) => { const response = await fetch( `/api${creationPath(this.id)}/assets/${assetId}/${representation}`, - { headers, signal }, + { headers, signal, priority: options.priority === MEDIA_PRIORITY.visible ? "low" : "auto" }, ); if (!response.ok) throw await responseError(response); return response.blob(); }, { timeoutMs: 120_000, attempts: 3, ...options }, - ), + ); + return this.mediaReader.run( + () => options.priority === MEDIA_PRIORITY.visible ? backgroundRead(read, options.signal) : read(), { priority: options.priority ?? MEDIA_PRIORITY.action, key: options.readKey, @@ -790,12 +863,12 @@ export class CreationClient { ], ); } - history() { + history(signal?: AbortSignal) { const cursor = this.snapshot.eventCursor; if (this.historyRead?.cursor === cursor) return this.historyRead.promise; const promise = storageRequest< { commandId: string; state: "applied" | "undone" }[] - >(`${creationPath(this.id)}/history`).catch((error) => { + >(`${creationPath(this.id)}/history`, { signal }).catch((error) => { if (this.historyRead?.promise === promise) this.historyRead = undefined; throw error; }); @@ -843,18 +916,7 @@ export class CreationClient { const path = `${creationPath(this.id)}/views/${viewClientId}`; const pending = storageRequest(path).then( (stored) => { - // A 204 means this client has never saved a viewport for this project. - this.viewPersisted = stored !== undefined; - this.viewState = stored ?? { - projectId: this.id, - clientId: viewClientId, - viewport: { x: 0, y: 0, zoom: 1 }, - selectedItemIds: [], - activeEditorId: null, - playheads: [], - generationCounts: {}, - }; - return this.viewState; + return this.installView(stored); }, ); this.viewRead = pending; @@ -866,6 +928,19 @@ export class CreationClient { } return this.viewRead; } + private installView(stored?: ViewState) { + this.viewPersisted = stored !== undefined; + this.viewState = stored ?? { + projectId: this.id, + clientId: viewClientId, + viewport: { x: 0, y: 0, zoom: 1 }, + selectedItemIds: [], + activeEditorId: null, + playheads: [], + generationCounts: {}, + }; + return this.viewState; + } async view(value?: Partial) { const path = `${creationPath(this.id)}/views/${viewClientId}`; if (!this.viewState) await this.loadViewState(); @@ -883,7 +958,25 @@ export class CreationClient { } return this.viewState!; } + pauseDisplayReads() { + this.referenceCheck?.abort(); + this.textRead?.abort(); + this.subscription?.abort(); + for (const read of this.mediaReads.values()) { + if (!read.retained) read.controller.abort(); + } + } + resumeDisplayReads() { + if (this.snapshot) { + this.subscribe(); + this.readDeferredTexts(); + if ([...this.referenceStates.values()].includes("unknown")) this.checkReferences(this.snapshot); + } + } close() { + this.textRead?.abort(); + this.deferredTexts = undefined; + this.referenceCheck?.abort(); this.subscription?.abort(); for (const read of this.mediaReads.values()) read.controller.abort(); this.mediaReads.clear(); diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index b161441c5..0d5153c4b 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -15,6 +15,7 @@ import type { ProjectSnapshot, ReferenceInput, TimelineResource, + ViewState, } from "../contracts/generated.ts"; import { AUDIO_CARD_SIZE, @@ -574,6 +575,12 @@ export class CreationProjection { const update = (nodes: CanvasNode[]) => { let changed = false; const next = nodes.map((node) => { + if (node.type === "text" && node.data.assetState === "loading" && node.data.backendAssetId) { + const body = this.client.projectedText(node.data.backendAssetId); + if (!body || body.state === "loading") return node; + changed = true; + return { ...node, data: { ...node.data, text: body.text, assetState: body.state } }; + } if ( !node.data.backendAssetId || !["image", "video", "audio"].includes(node.type) @@ -617,9 +624,14 @@ export class CreationProjection { id: snapshot.project.id, defaultNameIndex: snapshot.project.defaultNameIndex, }; - const view = await this.client.view(); + const savedView = await this.client.view(); + const draft = this.pendingView; + const view = draft ? { + ...savedView, ...draft, + generationCounts: { ...savedView.generationCounts, ...draft.generationCounts }, + } : savedView; document.viewport = view.viewport; - document.viewPersisted = this.client.hasPersistedView(); + document.viewPersisted = Boolean(draft) || this.client.hasPersistedView(); const visible = visibleItems(snapshot); // Canvas visibility changes the projection, never the accepted business inputs. const currentReferences = snapshot.references.filter((ref) => ref.active); @@ -646,12 +658,16 @@ export class CreationProjection { const asset = currentAsset(snapshot, item); if (asset) { try { - if (asset.kind === "text") - node.data.text = await this.client.textContent(asset.id); - else node.data.src = assetSource(snapshot.project.id, asset.id); - node.data.assetState = this.client.mediaUnavailable(asset.id) - ? "missing" - : "ready"; + const deferred = asset.kind === "text" ? this.client.projectedText(asset.id) : undefined; + if (deferred) { + node.data.text = deferred.text; + node.data.assetState = deferred.state; + } else { + if (asset.kind === "text") + node.data.text = await this.client.textContent(asset.id); + else node.data.src = assetSource(snapshot.project.id, asset.id); + node.data.assetState = this.client.mediaUnavailable(asset.id) ? "missing" : "ready"; + } } catch { node.data.assetState = "missing"; } @@ -2184,7 +2200,7 @@ export class CreationProjection { } // Business acknowledgement cannot be undone by a view preference failure. this.basis = this.client.snapshot; - this.baseline = document; + this.baseline = this.withMediaAvailability(document); this.pendingSpecIds.clear(); if (options.saveView === false) return operations.length > 0; await this.saveView(document); @@ -2192,32 +2208,38 @@ export class CreationProjection { } /** View state is independent of the business commit; panning only needs this. */ - async saveView(document: CanvasDocument) { - this.viewError = ""; - try { - const view = await this.client.view(); - const generationCounts = { - ...view.generationCounts, - ...Object.fromEntries( - document.nodes - .filter((node) => node.data.settings) - .map((node) => [node.id, node.data.settings!.count ?? 1]), - ), - }; - // Autosave, switch flushes and open all end here. Rewriting an unchanged - // viewport delays the next document without persisting any new fact. - const unchangedCounts = - Object.keys(view.generationCounts).length === + private viewWrites = Promise.resolve(); + private pendingView?: Pick; + + saveView(document: CanvasDocument) { + const draft = { + viewport: document.viewport, + generationCounts: Object.fromEntries( + document.nodes + .filter((node) => node.data.settings) + .map((node) => [node.id, node.data.settings?.count ?? 1]), + ), + }; + this.pendingView = draft; + const write = this.viewWrites.then(async () => { + if (this.pendingView !== draft) return; + this.viewError = ""; + try { + const view = await this.client.view(); + const generationCounts = { ...view.generationCounts, ...draft.generationCounts }; + const unchangedCounts = Object.keys(view.generationCounts).length === Object.keys(generationCounts).length && - same( - Object.entries(view.generationCounts).sort(), - Object.entries(generationCounts).sort(), - ); - if (same(view.viewport, document.viewport) && unchangedCounts) return; - await this.client.view({ viewport: document.viewport, generationCounts }); - } catch (error) { - this.viewError = error instanceof Error ? error.message : String(error); - } + Object.entries(generationCounts).every(([id, count]) => view.generationCounts[id] === count); + if (!same(view.viewport, draft.viewport) || !unchangedCounts) + await this.client.view({ viewport: draft.viewport, generationCounts }); + if (this.pendingView === draft) this.pendingView = undefined; + } catch (error) { + if (this.pendingView === draft) + this.viewError = error instanceof Error ? error.message : String(error); + } + }); + this.viewWrites = write; + return write; } } diff --git a/src/backend/workspace.ts b/src/backend/workspace.ts index 0bedc730a..8aab65bde 100644 --- a/src/backend/workspace.ts +++ b/src/backend/workspace.ts @@ -1,4 +1,3 @@ -import { getEditingState } from "./editSession.ts"; import { type CanvasDocument } from "../canvas/model.ts"; import type { CommandReceipt, @@ -61,6 +60,7 @@ export interface WorkspaceCleanupResult { const lastKey = "opendirector.lastUnifiedFilesystemProject"; /** The project selector opens and closes often; the list is cheap to reuse. */ const PROJECTS_KEY = "workspace:projects"; +const NAVIGATION_KEY = "workspace:projects:navigation"; const projectCatalogChanges = new EventTarget(); export function subscribeWorkspaceProjects(onChange: () => void) { @@ -76,18 +76,24 @@ function invalidateWorkspaceProjects() { export const listWorkspaceProjects = (read: { fresh?: boolean } = {}) => cachedRequest( PROJECTS_KEY, - () => request("/creation/projects"), + () => request("/creation/projects", { priority: "high" }), read, ); -/** Rows already fetched for this page, for a selector that opens instantly. */ +const readWorkspaceNavigation = () => + request("/creation/projects?navigation=true", { priority: "high" }); + +export const listWorkspaceNavigation = () => { + const catalog = peekCached(PROJECTS_KEY); + return catalog ? Promise.resolve(catalog) : cachedRequest(NAVIGATION_KEY, readWorkspaceNavigation); +}; + export const peekWorkspaceProjects = () => - peekCached(PROJECTS_KEY); + peekCached(PROJECTS_KEY) ?? + peekCached(NAVIGATION_KEY); export function prefetchWorkspaceProjects() { - prefetchRequest(PROJECTS_KEY, () => - request("/creation/projects"), - ); + prefetchRequest(NAVIGATION_KEY, readWorkspaceNavigation); } export const cleanupUnreadableWorkspaceProjects = () => @@ -99,11 +105,11 @@ export const cleanupUnreadableWorkspaceProjects = () => export const projectDeleteMode = () => request<{ projectDelete: "recycle_bin" | "permanent" }>("/creation/storage"); -export async function readWorkspaceDocument(project: WorkspaceProject) { +export async function readWorkspaceDocument(project: Pick) { return workspaceProjection(project.id).open(); } -export async function openWorkspaceProject(project: WorkspaceProject) { +export async function openWorkspaceProject(project: Pick) { // Read first: invalid content cannot take the lease away from the old project. // The read itself acquires the session lease, so no second open is needed. const document = await openBackendProjectCanvas(project.id, () => @@ -229,27 +235,36 @@ export function openExampleWorkspaceProject( return pending; } +let routedOpening: Promise | undefined; + +export function primeRoutedWorkspace() { + const project = window.location.pathname.split("/ai-canvas/")[1]; + if (!project || routedOpening) return; + routedOpening = Promise.resolve().then(() => + openWorkspaceProject({ id: decodeURIComponent(project) }), + ); + void routedOpening.catch(() => {}); +} + let initialization: Promise | undefined; export function initializeWorkspace() { // StrictMode's concurrent mount effects share in-flight work. A later mount // must reread the current project, not reinstall the first empty document. initialization ??= (async () => { + const routeProject = window.location.pathname.split("/ai-canvas/")[1]; + if (routeProject) { + primeRoutedWorkspace(); + const opened = routedOpening!; + routedOpening = undefined; + return opened; + } let { projects } = await listWorkspaceProjects(); - let selected: string | undefined = - window.location.pathname.split("/ai-canvas/")[1]; - if (selected) { - selected = decodeURIComponent(selected); - if (!projects.some((project) => project.id === selected)) { - // Ask the authoritative store for the precise missing/unsupported-format error. - await request(creationPath(selected)); - throw new Error(tNow("errors.backend.projectNotOpen")); - } - } else - try { - selected = localStorage.getItem(lastKey) ?? undefined; - } catch { - /* Optional hint. */ - } + let selected: string | undefined; + try { + selected = localStorage.getItem(lastKey) ?? undefined; + } catch { + /* Optional hint. */ + } if (!projects.length) { const id = crypto.randomUUID(); try { @@ -281,7 +296,6 @@ export function initializeWorkspace() { const document = await openWorkspaceProject( projects.find((project) => project.id === selected) ?? projects[0]!, ); - if (getEditingState(document.id)?.mode !== "preview") await saveWorkspaceDocument(document); return document; })().finally(() => { initialization = undefined; diff --git a/src/canvas/CanvasNodeView.tsx b/src/canvas/CanvasNodeView.tsx index a09fd9029..fa81b37c4 100644 --- a/src/canvas/CanvasNodeView.tsx +++ b/src/canvas/CanvasNodeView.tsx @@ -52,9 +52,10 @@ function CanvasNodeContents({ id, data, selected }: NodeProps) { const kind = data.kind; const hasAsset = Boolean(data.src) && data.assetState !== "missing"; const [viewportProbe, inViewport] = useInViewport(); + const mediaEnabled = useContext(AssetMediaActive) && inViewport; const media = useAssetMedia( ["image", "video", "audio"].includes(kind) ? data.src : undefined, - inViewport, + mediaEnabled, ); const mediaPending = Boolean(data.src) && media.state !== "ready"; const locked = Boolean(actions?.isLocked(id)); @@ -72,7 +73,7 @@ function CanvasNodeContents({ id, data, selected }: NodeProps) { if (data.timelineOutput) return ; return ( - + ) { ) : ["timeline", "stack", "tool", "external"].includes(kind) ? ( ) : kind === "text" ? ( - actions?.isTextEditing(id) ? ( + data.assetState === "loading" ? ( +
+ {t("canvasNodes.media.loading")} +
+ ) : data.assetState === "missing" && data.backendAssetId ? ( +
+ {t("canvasNodes.media.failed")} +
+ ) : actions?.isTextEditing(id) ? ( >({}); useEffect(() => { + if (!enabled) return; const client = creationClient(projectId); let key = "", active = true, + loaded = false, ticket = 0; let timer: ReturnType; const abort = new AbortController(); @@ -64,12 +66,15 @@ export function useNodeVersionCounts(projectId: string) { { signal: abort.signal }, ) .then((value) => { - if (active && sequence === ticket) setCounts(value.counts); + if (active && sequence === ticket) { + loaded = true; + setCounts(value.counts); + } }) .catch(() => { if (active && sequence === ticket) key = ""; }); - }, 180); + }, loaded ? 180 : 1500); }; const unsubscribe = client.listen(update); if (client.snapshot) update(client.snapshot); @@ -79,7 +84,7 @@ export function useNodeVersionCounts(projectId: string) { clearTimeout(timer); unsubscribe(); }; - }, [projectId]); + }, [projectId, enabled]); return counts; } diff --git a/src/canvas/ProjectSelector.tsx b/src/canvas/ProjectSelector.tsx index 0be86c4cd..bb6c9d9de 100644 --- a/src/canvas/ProjectSelector.tsx +++ b/src/canvas/ProjectSelector.tsx @@ -6,6 +6,8 @@ import { ProjectNameDialog } from "./ProjectNameDialog"; import { cleanupUnreadableWorkspaceProjects, listWorkspaceProjects, + listWorkspaceNavigation, + peekWorkspaceProjects, projectDeleteMode, type UnreadableWorkspaceProject, type WorkspaceProject, @@ -113,6 +115,19 @@ export function ProjectSelector({ return null; }); }, []); + useEffect(() => { + if (!deleteTarget && !cleanupOpen) return; + let active = true; + void projectDeleteMode() + .then((mode) => { + if (active) setRecycleBin(mode.projectDelete === "recycle_bin"); + }) + .catch(() => { + // The prompt stays on the permanent wording when the mode is unknown. + if (active) setRecycleBin(false); + }); + return () => { active = false; }; + }, [deleteTarget, cleanupOpen]); const loadProjects = useCallback(async () => { const result = await listWorkspaceProjects(); setProjects(result.projects); @@ -172,18 +187,15 @@ export function ProjectSelector({ useEffect(() => { if (!open) return; let active = true; - setLoading(true); + const cached = peekWorkspaceProjects(); + if (cached) { + setProjects(cached.projects); + setUnreadable(cached.unreadable); + } + setLoading(!cached); setError(""); setNotice(""); - void projectDeleteMode() - .then((mode) => { - if (active) setRecycleBin(mode.projectDelete === "recycle_bin"); - }) - .catch(() => { - // The prompt stays on the permanent wording when the mode is unknown. - if (active) setRecycleBin(false); - }); - void listWorkspaceProjects() + void listWorkspaceNavigation() .then((result) => { if (active) { setProjects(result.projects); @@ -399,7 +411,7 @@ export function ProjectSelector({ aria-busy={loading || busy} onScroll={() => closeActions(false)} > - {loading ? ( + {loading && projects.length === 0 ? (

{t("canvas.project.loading")}

diff --git a/src/canvas/model.ts b/src/canvas/model.ts index fecc3e30f..82068db8e 100644 --- a/src/canvas/model.ts +++ b/src/canvas/model.ts @@ -216,7 +216,7 @@ export interface CanvasNodeData extends Record { src?: string; mimeType?: string; text?: string; - assetState?: "ready" | "missing"; + assetState?: "ready" | "missing" | "loading"; /** Imported/derived assets have editing controls, not an automatic generator. * Omitted in older documents; keep their existing generator behavior. */ mediaRole?: "asset" | "generation"; diff --git a/src/canvas/useAssetMedia.tsx b/src/canvas/useAssetMedia.tsx index f5b2ac64c..0f77d1849 100644 --- a/src/canvas/useAssetMedia.tsx +++ b/src/canvas/useAssetMedia.tsx @@ -54,7 +54,7 @@ export function useAssetMedia( active?: boolean, ): { src?: string; state: AssetMediaState; retry: () => void } { const inherited = useContext(AssetMediaActive); - const enabled = active ?? inherited; + const enabled = inherited && (active ?? true); const asset = parseAssetSource(source); const [loaded, setLoaded] = useState<{ source: string; @@ -74,8 +74,9 @@ export function useAssetMedia( .then((src) => { if (!controller.signal.aborted) setLoaded({ source: source!, src }); }) - .catch(() => { - if (!controller.signal.aborted) setLoaded({ source: source! }); + .catch((error) => { + if (!controller.signal.aborted && !(error instanceof DOMException && error.name === "AbortError")) + setLoaded({ source: source! }); }); return () => controller.abort(); }, [source, projectId, assetId, enabled, attempt]); diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index bcf373c62..3cfad9772 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -37,6 +37,7 @@ import { exampleFailureText, examplePercent } from "./example/exampleFailure.ts" import { useExampleImport } from "./example/useExampleImport.ts"; import { AssistantPanel } from "../AssistantPanel"; +import { AssetMediaActive } from "../useAssetMedia.tsx"; import { CanvasActionsContext } from "../CanvasActionsContext"; import { CanvasConnectionLine, CanvasConnectionPreview, CanvasInteractionOverlay } from "../CanvasConnections"; @@ -747,6 +748,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { } > + entry.id === node.id); if (item) void openEditor(item); @@ -1064,6 +1067,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { ))} + @@ -1668,7 +1672,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { ) } onEdit={(mode) => { - if (single.type === "text") setTextEditingId(single.id); + if (single.type === "text" && (!single.data.backendAssetId || single.data.assetState === "ready")) setTextEditingId(single.id); else if (single.type === "video") { if (mode === "extract-audio") void runQuickAction( @@ -1719,7 +1723,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { } onAssistant={showAssistant} onExpand={ - single.type === "text" + single.type === "text" && (!single.data.backendAssetId || single.data.assetState === "ready") ? () => setTextWindowId(single.id) : undefined } diff --git a/src/canvas/workspace/useWorkspaceDocument.ts b/src/canvas/workspace/useWorkspaceDocument.ts index 68a032b0c..e5aa18ac8 100644 --- a/src/canvas/workspace/useWorkspaceDocument.ts +++ b/src/canvas/workspace/useWorkspaceDocument.ts @@ -201,24 +201,18 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { try { if (getEditingState(snapshot.id)?.mode === "preview") return false; const projection = workspaceProjection(snapshot.id); - // A preceding write can change the baseline while this save waits. - if ( - saveView && - projection.baseline && - sameCanvasContent(snapshot, projection.baseline) - ) { - await projection.saveView(snapshot); - } else { - await saveWorkspaceDocument(snapshot, { saveView }); - } + // Business saves share a barrier with navigation. View saves carry + // tab preferences and can finish independently of that barrier. + if (!projection.baseline || !sameCanvasContent(snapshot, projection.baseline)) + await saveWorkspaceDocument(snapshot, { saveView: false }); saveError.current = ""; - if (historyRef.current.present === snapshot) { - const warning = workspaceProjection(snapshot.id).viewError; - setSaveStatus( - warning - ? { state: "savedViewFailed", warning } - : { state: "saved" }, - ); + if (historyRef.current.present === snapshot) + setSaveStatus({ state: "saved" }); + if (saveView) { + void projection.saveView(snapshot).then(() => { + if (historyRef.current.present !== snapshot || !projection.viewError) return; + setSaveStatus({ state: "savedViewFailed", warning: projection.viewError }); + }); } return true; } catch (error) { @@ -295,6 +289,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { uploadTarget.current = null; setArrivingNodes(new Set()); setHistory(createHistory(next)); + setSaveStatus({ state: "saved" }); setMeasurements({}); setSelected([]); setComposerNodeId(null); @@ -327,7 +322,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { ); } }, - [flow], + [flow, setSaveStatus], ); const switchDocument = useCallback( @@ -339,6 +334,9 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { if (switchPending.current) return false; switchPending.current = true; setSwitching(true); + const source = creationClient(historyRef.current.present.id); + source.pauseDisplayReads(); + let installed = false; // The workspace is inert until saving and loading finish, so later edits cannot be lost. importAbort.current?.abort(); try { @@ -354,6 +352,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { } const next = await read(); installDocument(next, fit); + installed = true; return true; } catch (error) { try { @@ -371,6 +370,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { notify(error instanceof Error ? error.message : t("canvas.workspace.error.openCanvasFailed")); return false; } finally { + if (!installed) source.resumeDisplayReads(); switchPending.current = false; setSwitching(false); } @@ -622,7 +622,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { useEffect(() => { if (!ready) return; const projection = workspaceProjection(doc.id); - return creationClient(doc.id).listenMedia(() => { + const updateMedia = () => { if (projection.baseline) projection.baseline = projection.withMediaAvailability(projection.baseline); const apply = (document: CanvasDocument) => @@ -634,32 +634,45 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { future: history.future.map(apply), transaction: history.transaction ? apply(history.transaction) : null, })); - }); + }; + const unsubscribe = creationClient(doc.id).listenMedia(updateMedia); + updateMedia(); + return unsubscribe; }, [doc.id, ready]); useEffect(() => { - if (!ready) return; + if (!ready || switching) return; + const abort = new AbortController(); + let timer: ReturnType; let active = true, + loaded = false, sequence = 0; const refresh = () => { const ticket = ++sequence; - void creationClient(doc.id) - .history() - .then((entries) => { - if (active && sequence === ticket) - setBusinessHistory({ - undo: entries.some((entry) => entry.state === "applied"), - redo: entries.some((entry) => entry.state === "undone"), - }); - }) - .catch((error) => active && notify(errorMessage(error))); + clearTimeout(timer); + timer = setTimeout(() => { + void creationClient(doc.id) + .history(abort.signal) + .then((entries) => { + if (active && sequence === ticket) { + loaded = true; + setBusinessHistory({ + undo: entries.some((entry) => entry.state === "applied"), + redo: entries.some((entry) => entry.state === "undone"), + }); + } + }) + .catch((error) => active && notify(errorMessage(error))); + }, loaded ? 0 : 1500); }; const unsubscribe = creationClient(doc.id).listen(refresh); refresh(); return () => { active = false; + clearTimeout(timer); + abort.abort(); unsubscribe(); }; - }, [doc.id, ready, notify]); + }, [doc.id, ready, switching, notify]); useEffect(() => { const epoch = autosaveEpoch.current; const canPersist = !editorSaving.current; diff --git a/src/canvas/workspace/useWorkspaceEditor.ts b/src/canvas/workspace/useWorkspaceEditor.ts index dbd3b8190..37c20a4d8 100644 --- a/src/canvas/workspace/useWorkspaceEditor.ts +++ b/src/canvas/workspace/useWorkspaceEditor.ts @@ -81,6 +81,7 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) { [doc.nodes], ); const openEditor = async (node: CanvasNode, mode: EditorMode = "default") => { + if (node.type === "text" && node.data.backendAssetId && node.data.assetState !== "ready") return; if (readOnly) { if (node.type === "timeline") { setEditorMode("default"); diff --git a/src/canvas/workspace/useWorkspaceInteraction.tsx b/src/canvas/workspace/useWorkspaceInteraction.tsx index 9edfc6de5..833147a94 100644 --- a/src/canvas/workspace/useWorkspaceInteraction.tsx +++ b/src/canvas/workspace/useWorkspaceInteraction.tsx @@ -903,7 +903,7 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean) if (action.type === "edit-text" || action.type === "nudge") event.stopPropagation(); if (action.type === "edit-text") { - if (single?.type === "text") setTextEditingId(single.id); + if (single?.type === "text" && (!single.data.backendAssetId || single.data.assetState === "ready")) setTextEditingId(single.id); } else if (action.type === "history") replayHistory(action.forward); else if (action.type === "select-all") setSelected(canvasSelectAllIds(doc.nodes)); diff --git a/src/canvas/workspace/useWorkspaceRuntime.ts b/src/canvas/workspace/useWorkspaceRuntime.ts index a8ef71ce0..b223eb3c5 100644 --- a/src/canvas/workspace/useWorkspaceRuntime.ts +++ b/src/canvas/workspace/useWorkspaceRuntime.ts @@ -83,7 +83,7 @@ export function useWorkspaceRuntime(): WorkspaceRuntime { () => ({ projectId: doc.id, sources: liveCanvasSources(doc) }), [doc], ); - const versionCounts = useNodeVersionCounts(doc.id); + const versionCounts = useNodeVersionCounts(doc.id, ready && !store.switching); const switchPending = useRef(false); const revealCreatedNodes = useRef<(nodes: CanvasNode[], allNodes: CanvasNode[]) => void>(() => {}); const viewportMoving = useRef(false); @@ -243,7 +243,7 @@ export function useWorkspaceRuntime(): WorkspaceRuntime { () => incomingNodes(doc, composerNodeId), [doc.nodes, doc.hiddenNodes, doc.edges, composerNodeId], ); - const referenceAssets = useProjectMentionAssets(doc.id, ready); + const referenceAssets = useProjectMentionAssets(doc.id, ready && Boolean(composerNodeId)); const actionSource = actionSession ? validateNodeActionSource(doc, actionSession) : null; diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts index 8b9936219..94c83ff89 100644 --- a/src/canvas/workspace/useWorkspaceTransfer.ts +++ b/src/canvas/workspace/useWorkspaceTransfer.ts @@ -14,7 +14,7 @@ import { backUpLibrarySubject, copyLibrarySubjects, } from "../../backend/subjectLibrary.ts"; -import { importWorkspaceDocument, workspaceProjection } from "../../backend/workspace"; +import { importWorkspaceDocument, prefetchWorkspaceProjects, workspaceProjection } from "../../backend/workspace"; import { downloadFile, downloadFilename } from "../assets"; import { referenceIssueText, referenceIssue } from "../connectionPolicy"; @@ -71,6 +71,7 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { importAbort, lockedIds, notify, + panel, pasteCount, pasting, persist, @@ -98,10 +99,11 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { } = rt; useEffect(() => { - // Warm the library and the project selector after this canvas settles, so - // both open from cache; switching projects warms the next one the same way. - if (ready) prefetchLibrary(doc.id); - }, [ready, doc.id]); + if (ready) prefetchWorkspaceProjects(); + }, [ready]); + useEffect(() => { + if (ready && panel === "assets") prefetchLibrary(doc.id); + }, [ready, panel, doc.id]); /** Copies a picked resource onto the current canvas as independent nodes. */ const importCanvasResource = async (resource: CanvasResource) => { diff --git a/src/main.tsx b/src/main.tsx index 71ea872c5..0359f45d6 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,12 +1,14 @@ import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; +import { primeRoutedWorkspace } from "./backend/workspace"; import AssistantTracePage from "./canvas/AssistantTracePage"; import { I18nProvider } from "./i18n/I18nProvider"; const root = document.getElementById("root"); if (!root) throw new Error("Missing application root"); const params = new URLSearchParams(window.location.search); +if (!params.has("traceProject")) primeRoutedWorkspace(); ReactDOM.createRoot(root).render( diff --git a/tests/backendWorkspace.test.ts b/tests/backendWorkspace.test.ts index 05d7e0396..377d53746 100644 --- a/tests/backendWorkspace.test.ts +++ b/tests/backendWorkspace.test.ts @@ -13,6 +13,7 @@ import { initializeWorkspace, openExampleWorkspaceProject, openWorkspaceProject, + primeRoutedWorkspace, saveWorkspaceDocument, trashWorkspaceProject, type WorkspaceProject, @@ -64,8 +65,9 @@ function fixture(t: TestContext) { }); CreationProjection.prototype.open = async function () { // CreationClient.open() acquires the project lease with the same read. + const doc = documents.get(this.client.id); + if (!doc) throw new Error("不支持该工程格式"); lease = this.client.id; - const doc = documents.get(this.client.id)!; this.baseline = structuredClone(doc); return structuredClone(doc); }; @@ -80,7 +82,7 @@ function fixture(t: TestContext) { const body = options?.body ? JSON.parse(String(options.body)) : undefined; calls.push({ path, method, body }); assert.ok(path.startsWith("/api/creation/"), `Legacy request: ${path}`); - if (path === "/api/creation/projects") + if (path === "/api/creation/projects" || path === "/api/creation/projects?navigation=true") return Response.json({ projects: [...projects.values()], unreadable: occupied @@ -228,13 +230,31 @@ test("plain entry shares concurrent initialization, then rereads the saved proje ); }); +test("an explicit canvas link reuses its bootstrap open without requesting the catalog", async (t) => { + const f = fixture(t); + const initial = await initializeWorkspace(); + f.calls.length = 0; + f.location.pathname = `/ai-tool/ai-canvas/${initial.id}`; + let opens = 0; + const open = CreationProjection.prototype.open; + CreationProjection.prototype.open = async function () { + opens++; + return open.call(this); + }; + primeRoutedWorkspace(); + primeRoutedWorkspace(); + assert.equal((await initializeWorkspace()).id, initial.id); + assert.equal(opens, 1); + assert.deepEqual(f.calls, []); +}); + test("explicit unsupported project links reject instead of creating or opening another project", async (t) => { const f = fixture(t); await initializeWorkspace(); f.calls.length = 0; f.location.pathname = `/ai-tool/ai-canvas/${crypto.randomUUID()}`; await assert.rejects(initializeWorkspace(), /不支持该工程格式/); - assert.ok(f.calls.every((call) => call.method === "GET")); + assert.ok(f.calls.every((call) => !call.path.endsWith("/commands"))); assert.equal(f.projects.size, 1); }); diff --git a/tests/creationClient.test.ts b/tests/creationClient.test.ts index f4dd7322d..f1df4f3f1 100644 --- a/tests/creationClient.test.ts +++ b/tests/creationClient.test.ts @@ -1385,6 +1385,38 @@ test("a viewport-only save skips business preparation and batching", async () => assert.equal(projection.viewError, ""); }); +test("a pending or rejected tab view remains available when projecting the canvas", async () => { + const original = globalThis.fetch; + const snapshot = empty(); + const client = new CreationClient(snapshot.project.id); + client.install(snapshot); + const projection = new CreationProjection(client); + const viewport = { x: 42, y: 17, zoom: 1.5 }; + let started!: () => void; + let respond!: (response: Response) => void; + const startedWrite = new Promise((resolve) => { started = resolve; }); + const reply = new Promise((resolve) => { respond = resolve; }); + globalThis.fetch = async (url, options) => { + assert.match(String(url), /\/views\//); + if (options?.method === "PUT") { + started(); + return reply; + } + return new Response(null, { status: 204 }); + }; + try { + const write = projection.saveView({ ...createDocument(), id: client.id, viewport }); + await startedWrite; + assert.deepEqual((await projection.read()).viewport, viewport); + respond(Response.json({ code: "session_expired", detail: "Canvas switched" }, { status: 409 })); + await write; + assert.match(projection.viewError, /Canvas switched/); + assert.deepEqual((await projection.read()).viewport, viewport); + } finally { + globalThis.fetch = original; + } +}); + test("clean business flush skips preparation and preserves the basis of unseen changes", async () => { const snapshot = empty(); const client = new CreationClient(snapshot.project.id); @@ -1718,6 +1750,51 @@ test("opening a canvas keeps text with the snapshot and reads originals by asset } }); +test("a deferred text body leaves the canvas available and hydrates its original binding", async () => { + const original = globalThis.fetch; + const { snapshot } = mediaFixture(); + const text = snapshot.assets.find((asset) => asset.kind === "text")!; + const identifier = snapshot.project.id; + let finish!: (value: Response) => void; + const response = new Promise((resolve) => { finish = resolve; }); + const requests: string[] = []; + globalThis.fetch = async (url) => { + const path = String(url); + requests.push(path); + if (path.endsWith("/open-canvas")) + return Response.json({ snapshot, edges: [], textsDeferred: true, view: null }); + if (path.includes("/canvas-texts")) return response; + if (path.includes("/subscribe")) return new Response(new ReadableStream({ start() {} })); + throw new Error(`Unexpected request ${path}`); + }; + const client = new CreationClient(identifier); + const projection = new CreationProjection(client); + try { + const document = await projection.open(); + assert.equal(document.nodes.find((node) => node.data.backendAssetId === text.id)?.data.assetState, "loading"); + const moved = { + ...document, + nodes: document.nodes.map((node) => node.data.backendAssetId === text.id + ? { ...node, position: { ...node.position, x: node.position.x + 20 } } + : node), + }; + const queued = await projection.prepare(moved); + assert.ok(!requests.some((path) => path.endsWith("/commands"))); + assert.ok(queued.operations.length > 0); + let hydrated!: () => void; + const ready = new Promise((resolve) => { hydrated = resolve; }); + client.listenMedia(hydrated); + finish(Response.json({ cursor: snapshot.eventCursor, texts: { [text.id]: "original body" } })); + await ready; + const loaded = projection.withMediaAvailability(document).nodes.find((node) => node.data.backendAssetId === text.id); + assert.equal(loaded?.data.text, "original body"); + assert.equal(loaded?.data.assetState, "ready"); + } finally { + client.close(); + globalThis.fetch = original; + } +}); + test("an upload rejected for a lapsed lease is renewed and resent with the same file", async () => { const { setLeaseRecovery } = await import("../src/backend/api.ts"); const snapshot = empty(); diff --git a/tests/test_creation_api.py b/tests/test_creation_api.py index 0500c892b..2b0f74615 100644 --- a/tests/test_creation_api.py +++ b/tests/test_creation_api.py @@ -103,17 +103,40 @@ def test_storage_reports_how_a_deleted_project_leaves_the_disk(api): assert response.json()['projectDelete'] in {'recycle_bin', 'permanent'} +def test_navigation_catalog_defers_commit_checks_to_open(api): + client, local = api + path, command, _ = create(client) + head = local.root / 'New project' / 'commits' / f"{command['commandId']}.json" + head.unlink() + navigation = client.get('/api/creation/projects', params={'navigation': 'true'}) + assert navigation.is_success + assert [row['id'] for row in navigation.json()['projects']] == [command['projectId']] + assert client.post(path + '/open-canvas').status_code == 409 + full = client.get('/api/creation/projects').json() + assert full['projects'] == [] + assert full['unreadable'][0]['id'] == command['projectId'] + + + def test_lock_timeout_has_a_retryable_code_without_hiding_other_conflicts(api, monkeypatch): from filelock import FileLock client, local = api path = local.state_dir / 'catalog.lock' monkeypatch.setattr(local, 'lock', FileLock(path, timeout=.05)) + project_id = str(uuid4()) + project = f'/api/creation/projects/{project_id}' + command = dict(type='project.create', commandId=str(uuid4()), projectId=project_id, + payload=dict(name='Read during publication')) + assert client.post(project + '/commands', json=command).is_success with FileLock(path): - response = client.get('/api/creation/projects') + assert client.get('/api/creation/projects').status_code == 200 + assert client.get(project).json()['project']['id'] == project_id + assert client.get(project + f'/views/{uuid4()}').status_code == 204 + response = client.post(project + '/open-canvas') assert response.status_code == 409 assert response.json()['code'] == 'storage_busy' assert response.headers['retry-after'] == '1' - assert client.get('/api/creation/projects').status_code == 200 + assert client.post(project + '/open-canvas').status_code == 200 def test_unknown_and_legacy_projects_are_not_reinitialized(api): @@ -302,6 +325,32 @@ def counting_snapshot(self, project_id_value): assert body['edges'] == [dict(referenceId=reference['id'], sourceItemId=source_item, targetSpecId=target_spec, state='pending')] assert body['texts'] == {asset['id']: 'v1'} + deferred = client.post(path + '/open-canvas', + headers={'x-opendirector-defer-reference-checks': 'true'}).json() + assert deferred['snapshot'] == body['snapshot'] + assert deferred['texts'] == body['texts'] + assert deferred['referenceChecksDeferred'] + assert deferred['edges'] == [{'referenceId': reference['id'], 'state': 'unknown'}] + cursor = body['snapshot']['eventCursor'] + lazy = client.post(path + '/open-canvas', headers={ + 'x-opendirector-allow-preview': 'true', + 'x-opendirector-defer-texts': 'true', + 'x-opendirector-view-client': str(uuid4()), + }).json() + assert lazy['snapshot'] == body['snapshot'] + assert lazy['textsDeferred'] and lazy['texts'] == {} and lazy['view'] is None + assert client.get(path + '/canvas-texts', params={'cursor': cursor}).json() == { + 'cursor': cursor, 'texts': body['texts'], + } + assert client.get(path + '/canvas-texts', params={'cursor': cursor + 1}).json() == { + 'cursor': cursor, 'texts': {}, + } + assert client.get(path + '/reference-evidence', params={'cursor': cursor}).json() == { + 'cursor': cursor, 'edges': body['edges'], + } + assert client.get(path + '/reference-evidence', params={'cursor': cursor + 1}).json() == { + 'cursor': cursor, 'edges': [], + } # The no-flag open keeps its established bare snapshot response. plain = client.post(path + '/open').json() assert plain == body['snapshot'] diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index e7f6385f7..f2a48253f 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -91,16 +91,16 @@ def test_projection_reuses_read_basis_checks_each_asset_once_and_rechecks_change reference=dict(id=uuid4(), projectId=pid, binding='follow_current', source=dict(id=source.id), targetSpecId=spec.id)).status == 'applied' canvas = CreationCanvas(store) loads, checks = [], [] - load, check = store._load, canvas.assets.reference_available + load, check = store._load, canvas.assets.check_reference_media def loading(*args, **kwargs): loads.append(1) return load(*args, **kwargs) - def checking(project_id, asset_id, **kwargs): - checks.append(asset_id) - assert kwargs['snapshot'].project.id == pid - return check(project_id, asset_id, **kwargs) + def checking(stream, asset): + checks.append(asset.id) + assert asset.projectId == pid + return check(stream, asset) monkeypatch.setattr(store, '_load', loading) - monkeypatch.setattr(canvas.assets, 'reference_available', checking) + monkeypatch.setattr(canvas.assets, 'check_reference_media', checking) projection = canvas.projection(pid) # The command above just published this head, so it may already be in hand; # the invariant is that a projection never loads the project more than once. diff --git a/tests/test_creation_history_service.py b/tests/test_creation_history_service.py index 6b7c1a9e5..a6407a692 100644 --- a/tests/test_creation_history_service.py +++ b/tests/test_creation_history_service.py @@ -121,12 +121,12 @@ def tracking(): cleared, entries = store.history_index(pid) # Reading hundreds of immutable commits used to hold the catalog lock for # longer than the 15 s contention budget, so unrelated saves were reported - # as "storage busy"; only the head lookup may take it now. - assert len(locks) == 1 + # as "storage busy"; reads must take it at most once to resolve the head. + assert len(locks) <= 1 assert cleared == 0 and len(entries) >= 4 locks.clear() records = store.history(pid) - assert len(locks) == 1 and len(records) >= 4 + assert len(locks) <= 1 and len(records) >= 4 def test_redo_follows_undo_order_and_new_edit_discards_redo_branch(project): @@ -390,18 +390,18 @@ def test_asset_list_batches_history_and_tool_dependencies_without_stale_usage(pr ledger = folder / f'{task_id}.json' durable_json(ledger, dict(id=task_id, sourceAssetIds=[str(tool_input.id)], outputs=[])) loads, history_reads, ledger_reads = [], [], [] - load, history, read = store._load, store.history, gateway().read_json + load, records_fn, read = store._load, store.records, gateway().read_json def loading(*args, **kwargs): loads.append(1) return load(*args, **kwargs) def records(*args, **kwargs): history_reads.append(1) - return history(*args, **kwargs) + return records_fn(*args, **kwargs) def reading(path): ledger_reads.append(path) return read(path) monkeypatch.setattr(store, '_load', loading) - monkeypatch.setattr(store, 'history', records) + monkeypatch.setattr(store, 'records', records) monkeypatch.setattr(gateway(), 'read_json', reading) service = CreationHistory(store) listing = service.asset_list(pid) @@ -557,10 +557,17 @@ def test_reference_catalog_checks_files_against_its_one_snapshot(project, monkey store, pid, _ = project text_material(project, title='First') text_material(project, title='Second') - loads = [] - original = store._load - monkeypatch.setattr(store, '_load', lambda *args: (loads.append(args), original(*args))[1]) + loads, deep_copies, resolves = [], [], [] + original_load = store._load + original_history = store.history + original_manifest = store._published_manifest + monkeypatch.setattr(store, '_load', lambda *args: (loads.append(args), original_load(*args))[1]) + monkeypatch.setattr(store, 'history', lambda *args: (deep_copies.append(args), original_history(*args))[1]) + monkeypatch.setattr(store, '_published_manifest', lambda *args: (resolves.append(args), original_manifest(*args))[1]) rows = CreationHistory(store).reference_catalog(pid) assert len(rows) == 2 and all(row['fileAvailable'] for row in rows) - # Replaying the commit chain per asset held the catalog lock across a whole switch. + # Replaying the commit chain per asset held the catalog lock across a whole switch, + # deep-copying history stalled the GIL, and per-asset path resolution scaled with asset count. assert loads == [] + assert deep_copies == [] + assert len(resolves) == 1 diff --git a/tests/test_creation_storage.py b/tests/test_creation_storage.py index 9ad51b9e8..22198bbf7 100644 --- a/tests/test_creation_storage.py +++ b/tests/test_creation_storage.py @@ -213,6 +213,41 @@ def test_leases_expiry_external_moves_and_closed_rename_guards(projects): assert projects.snapshot(created.projectId).project.name == 'Renamed' +def test_reopening_a_persistent_editor_reuses_the_lease(projects): + created = create(projects) + session = str(uuid4()) + projects.open(created.projectId, session, persistent=True) + with projects.local.transaction() as db: + project = dict(id=str(created.projectId), path=str(projects.root / 'Example')) + assert projects.local.acquire_edit_lease(db, project, session, persistent=True) + assert db.total_changes == 0 + _, state = projects.open_canvas(created.projectId, str(uuid4()), allow_preview=True) + assert state == {"mode": "preview"} + assert projects.editing_state(created.projectId, session) == {"mode": "edit"} + + +def test_navigation_reuses_index_and_rechecks_external_directory_changes(projects, monkeypatch): + created = create(projects, 'Indexed') + projects.list_projects(navigation=True) + original = projects._scan + scans = [] + + def scan(): + scans.append(True) + return original() + + monkeypatch.setattr(projects, '_scan', scan) + session = str(uuid4()) + opened, _ = projects.open_canvas(created.projectId, session, allow_preview=True) + assert opened.project.id == created.projectId and scans == [] + copy = projects.root / 'External copy' + copy.mkdir() + shutil.copyfile(projects.root / 'Indexed' / 'project.json', copy / 'project.json') + with pytest.raises(ProjectError) as conflict: + projects.open_canvas(created.projectId, session, allow_preview=True) + assert conflict.value.status == 409 and scans + + def test_duplicate_ids_unknown_projects_and_legacy_formats_are_rejected(projects): legacy = legacy_project(projects.local) legacy_before = (Path(legacy['path']) / 'project.json').read_bytes() @@ -788,14 +823,89 @@ def reading(path): monkeypatch.setattr(creation_projects.CreationProjects, '_scan', scanning) monkeypatch.setattr(creation_catalog, 'read_json', reading) - first = projects.list_projects() + cold = restarted(projects) + first = cold.list_projects() assert len(first['projects']) == 8 - # One directory scan and one manifest read per project, never per project pair. assert len(scans) == 1 and len(manifests) == 8 scans.clear(), manifests.clear() - second = projects.list_projects() - assert len(second['projects']) == 8 - assert len(scans) == 1 and len(manifests) == 8 + assert cold.list_projects() == first + assert len(scans) == 1 and len(manifests) == (8 if os.name == 'nt' else 0) + + +def test_unrelated_canvas_reads_during_journaled_commit(projects, monkeypatch): + from threading import Event + + writing = create(projects, 'Writing') + reading = create(projects, 'Reading') + journaled, resume = Event(), Event() + + def pause(stage): + if stage == 'journaled': + journaled.set() + assert resume.wait(10) + + monkeypatch.setattr(projects, '_checkpoint', pause) + with ThreadPoolExecutor(max_workers=2) as pool: + change = pool.submit(projects.execute, rename(writing, 'After publication')) + try: + assert journaled.wait(5) + snapshot = pool.submit(projects.snapshot, reading.projectId).result(timeout=2) + assert snapshot.project.name == 'Reading' and snapshot.eventCursor == 1 + view = pool.submit(projects.view, reading.projectId, uuid4()).result(timeout=2) + assert view.projectId == reading.projectId + finally: + resume.set() + assert change.result(timeout=5).status == 'applied' + assert projects.snapshot(writing.projectId).project.name == 'After publication' + + +def test_publication_pause_allows_another_process_to_open_and_save(projects, monkeypatch): + from filelock import Timeout + from threading import Event + + writing = create(projects, 'Writing') + reading = create(projects, 'Reading') + other = restarted(projects) + session_a, session_b = str(uuid4()), str(uuid4()) + projects.open(writing.projectId, session_a) + + def show(project): + return request(project.projectId, 'canvas.show', item=dict( + id=uuid4(), projectId=project.projectId, kind='text', + title='Saved', binding=dict(role='empty'))) + + command_a, command_b = show(writing), show(reading) + journaled, resume = Event(), Event() + + def pause(stage): + if stage == 'bundle_written': + journaled.set() + assert resume.wait(10) + + monkeypatch.setattr(projects, '_checkpoint', pause) + with ThreadPoolExecutor(max_workers=2) as pool: + change = pool.submit(projects.execute, command_a, session=session_a) + try: + assert journaled.wait(5) + assert not change.done() + assert other._manifest(projects.root / 'Writing').head == writing.commandId + opened, state = other.open_canvas(reading.projectId, session_b, allow_preview=True) + assert state['mode'] == 'edit' and opened.eventCursor == 1 + assert other.execute(command_b, session=session_b).status == 'applied' + assert other.snapshot(reading.projectId).canvasItems[0].title == 'Saved' + assert not change.done() + + stable = other.snapshot(writing.projectId) + assert stable.eventCursor == 1 and not stable.canvasItems + with pytest.raises(Timeout): + other.open_canvas(writing.projectId, session_b, allow_preview=True) + finally: + resume.set() + receipt = change.result(timeout=5) + + assert receipt.status == 'applied' + assert other.snapshot(writing.projectId).canvasItems[0].title == 'Saved' + assert other.execute(command_a, session=session_a) == receipt def test_list_projects_still_checks_the_manifest_name_against_the_head(projects): diff --git a/tests/test_video_capability_acceptance.py b/tests/test_video_capability_acceptance.py index 35fd8d00d..23241075f 100644 --- a/tests/test_video_capability_acceptance.py +++ b/tests/test_video_capability_acceptance.py @@ -3,7 +3,7 @@ from contextlib import contextmanager import json from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from threading import Thread +from threading import Event, Thread import time from uuid import uuid4 @@ -263,7 +263,7 @@ def test_first_frame_minimum_rejects_before_task_or_http_generation(project, cli ('complete', True), ('reference_only', True), ('h3_unknown', True), ('mask_denied', False), ('h3_old', False), ('task_denied', False), ('frames_denied', False), ]) -def test_video_edits_check_actual_uploads_before_acceptance(project, clip, entry, mode, accepted): +def test_video_edits_check_actual_uploads_before_acceptance(project, clip, entry, mode, accepted, monkeypatch): store, pid, session = project with video_service(clip, mode) as (url, state): configs = ModelConfigs(store.local.repository) @@ -276,15 +276,40 @@ def test_video_edits_check_actual_uploads_before_acceptance(project, clip, entry # conftest disables accidental discovery; explicitly enable loopback HTTP. probe = CapabilityProbe(transport=httpx.HTTPTransport()) if entry == 'http': + pause_publication = mode == 'reference_only' + publishing, resume = Event(), Event() + if pause_publication: + publish = type(store)._publish_intent + + def pause(projects, intent, *, validated_history): + if intent.record.event and intent.record.event.source == 'background': + publishing.set() + assert resume.wait(10) + return publish(projects, intent, validated_history=validated_history) + + monkeypatch.setattr(type(store), '_publish_intent', pause) with TestClient(create_app(store.local, capability_probe=probe), headers={'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': session, 'Accept-Language': 'en-US'}) as client: path = f'/api/creation/projects/{pid}/tool-tasks' response = client.post(path, json=value) assert response.status_code == (202 if accepted else 409), response.text if accepted: + if pause_publication: + try: + assert publishing.wait(5) + in_flight = client.get(path + '/' + value['id']) + assert in_flight.status_code == 200, in_flight.text + assert in_flight.json()['status'] == 'running' + listed = client.get(path) + assert listed.status_code == 200, listed.text + assert [task['id'] for task in listed.json()['tasks']] == [value['id']] + finally: + resume.set() deadline = time.monotonic() + 20 while time.monotonic() < deadline: - task = client.get(path + '/' + value['id']).json() + polled = client.get(path + '/' + value['id']) + assert polled.status_code == 200, polled.text + task = polled.json() if task['status'] in {'succeeded', 'failed'}: break time.sleep(.02)