davinci-resolve-mcp 5.2.9 → 5.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  Release history for the DaVinci Resolve MCP Server. The latest release is summarized in the root README; older entries live here to keep the README focused.
4
4
 
5
+ ## What's New in v5.2.11 — A typo'd track index no longer grows a new timeline
6
+
7
+ From a follow-up on #370 by @willturner-maker.
8
+
9
+ ### Fixed
10
+
11
+ - **`create_timeline_from_clips` built as many tracks as a row named.** Since v5.2.9 it adds the tracks its `clip_infos` rows name, so a typo such as `track_index: 99` created a timeline with 98 empty tracks and answered success. A new timeline now gets at most 32 tracks of each type for its rows. A higher index is refused with `INVALID_TRACK_INDEX` before anything is created, and the message names the route for a build that needs more: create the timeline, add tracks with `timeline` `add_track`, then `append_to_timeline`, which checks rows against the tracks that exist. Same in the granular server. Both servers' docstrings now list `track_index` and `media_type` for this form.
12
+
13
+ ### Not verified here
14
+
15
+ - Offline tests only; no live Resolve run was made for this release.
16
+
17
+ ## What's New in v5.2.10 — Three writes are read back before they report success
18
+
19
+ From #373 by @youchengyangdu-pixel, adapted on landing.
20
+
21
+ ### Fixed
22
+
23
+ - **`timeline_markers.set_current_timecode` trusted the native `True`.** It now reads the playhead back, compared by frame and retried, and returns `requested`, `target`, `before`, `actual`, `api_success` and `verified`. A `True` that left the playhead elsewhere is `TIMECODE_READBACK_MISMATCH`. The shared seek check also accepts a read-back naming the same timecode label, so a drop-frame `;` or an unpadded hour no longer fails a seek that landed.
24
+ - **`media_pool.create_timeline_from_clips` (`clip_ids`) trusted the returned timeline.** It now confirms the timeline is in the project, holds items, and carries every ordinary clip's media-pool ID; a miss is `CREATE_TIMELINE_READBACK_FAILED`, with a note that the timeline may already exist. Subtitle and generator sources have no media-pool item on the timeline, so they are checked by SRT cue text and by name and bounds. Those two checks rest on behaviour not yet measured live, so a miss there is reported as `verified: false` with a warning on a successful result. A source SRT that is not UTF-8 falls back to the timeline's own cues.
25
+ - **Live subtitle preset and caption revisions** now check, after the write, that Resolve still has the same project, a database attached, the revision selected and readable target subtitle items. A failure reports `RESOLVE_DATABASE_UNHEALTHY` and asks for a manual restart; nothing is repaired automatically.
26
+
27
+ ### Changed on landing
28
+
29
+ - String comparison of timecodes replaced by the frame and label check above; the unmeasured subtitle and generator checks no longer fail the call; an unreadable SRT no longer fails the call; the clip IDs are resolved once instead of twice.
30
+
31
+ ### Not verified here
32
+
33
+ - Offline tests only; no live Resolve run was made for this release. The subtitle cue-text and generator `Type` assumptions and the database-health gate over the free-edition bridge are unmeasured.
34
+
5
35
  ## What's New in v5.2.9 — Bad track indexes and misplaced arguments are refused, not dropped
6
36
 
7
37
  From #370 and #372 by @willturner-maker, plus a Traditional Chinese README from #369 by @monarchsofchaos004-gif.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md)
4
4
 
5
- [![Version](https://img.shields.io/badge/version-5.2.9-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-5.2.11-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#server-modes)
package/README.zh-CN.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | 简体中文 | [繁體中文](README.zh-TW.md)
4
4
 
5
- [![Version](https://img.shields.io/badge/version-5.2.9-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-5.2.11-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#服务器模式)
@@ -12,7 +12,7 @@
12
12
  [![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/downloads/)
13
13
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
14
14
 
15
- > 本翻译对应 v5.2.9 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
15
+ > 本翻译对应 v5.2.11 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
16
16
 
17
17
  一个 Model Context Protocol (MCP) 服务器,让 AI 助手通过官方脚本 API 控制 DaVinci Resolve Studio(达芬奇)。它提供完整的 API 覆盖,外加带护栏的工作流助手,涵盖剪辑、媒体池整理、渲染设置、审阅标记、调色、Fusion、Fairlight、项目生命周期任务、扩展开发,以及不碰源媒体的媒体分析。
18
18
 
package/README.zh-TW.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | [简体中文](README.zh-CN.md) | 繁體中文
4
4
 
5
- [![Version](https://img.shields.io/badge/version-5.2.9-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-5.2.11-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#伺服器模式)
@@ -12,7 +12,7 @@
12
12
  [![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/downloads/)
13
13
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
14
14
 
15
- > 本翻譯對應 v5.2.9 版 README。如與英文原版有出入,以[英文原版](README.md)為準。
15
+ > 本翻譯對應 v5.2.11 版 README。如與英文原版有出入,以[英文原版](README.md)為準。
16
16
 
17
17
  一個 Model Context Protocol(MCP)伺服器,讓 AI 助理透過官方腳本 API 控制 DaVinci Resolve Studio。它提供完整的 API 覆蓋,並附上有防護機制的工作流程輔助工具,涵蓋剪輯、媒體池整理、算圖輸出設定、審閱標記、調色、Fusion、Fairlight、專案生命週期作業、擴充功能開發,以及不更動原始素材的媒體分析。
18
18
 
package/install.py CHANGED
@@ -37,7 +37,7 @@ from src.utils.update_check import (
37
37
 
38
38
  # ─── Version ──────────────────────────────────────────────────────────────────
39
39
 
40
- VERSION = "5.2.9"
40
+ VERSION = "5.2.11"
41
41
  # Only hard floor: mcp[cli] requires Python 3.10+. There is no upper bound —
42
42
  # Resolve's scripting bridge loads into newer interpreters on recent builds
43
43
  # (Python 3.14 verified against Resolve Studio 20.3.2). Older Resolve builds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "davinci-resolve-mcp",
3
- "version": "5.2.9",
3
+ "version": "5.2.11",
4
4
  "description": "NPM bootstrapper for the DaVinci Resolve MCP Server.",
5
5
  "license": "MIT",
6
6
  "author": "Samuel Gursky <samgursky@gmail.com>",
@@ -94,7 +94,7 @@ if not logging.getLogger().handlers:
94
94
  handlers=[logging.StreamHandler()],
95
95
  )
96
96
 
97
- VERSION = "5.2.9"
97
+ VERSION = "5.2.11"
98
98
  logger = logging.getLogger("davinci-resolve-mcp")
99
99
  logger.info(f"Starting DaVinci Resolve MCP Server v{VERSION}")
100
100
  logger.info(f"Detected platform: {get_platform()}")
@@ -1043,6 +1043,10 @@ def create_timeline_from_clips(
1043
1043
  media_pool_item_id), start_frame, end_frame, record_frame.
1044
1044
  record_frame is relative to the created timeline start frame by
1045
1045
  default; pass record_frame_mode="absolute" for raw Resolve values.
1046
+ Optional per row: track_index (1-based, default 1) and media_type
1047
+ (1 video, 2 audio). The new timeline gets the tracks the rows name,
1048
+ up to 32 of each type; a higher index is refused before anything
1049
+ is created.
1046
1050
  If both are None, uses the currently selected media pool clips.
1047
1051
  """
1048
1052
  project, mp, err = _get_mp()
package/src/server.py CHANGED
@@ -11,7 +11,7 @@ Usage:
11
11
  python src/server.py --full # Start the 377-tool granular server instead
12
12
  """
13
13
 
14
- VERSION = "5.2.9"
14
+ VERSION = "5.2.11"
15
15
 
16
16
  import base64
17
17
  import os
@@ -15759,6 +15759,225 @@ def _timeline_append_readback_snapshot(proj):
15759
15759
  }
15760
15760
 
15761
15761
 
15762
+ def _created_clip_property(clip, key):
15763
+ try:
15764
+ getter = getattr(clip, "GetClipProperty", None)
15765
+ value = getter(key) if callable(getter) else None
15766
+ return value if isinstance(value, str) else None
15767
+ except Exception:
15768
+ return None
15769
+
15770
+
15771
+ def _normalized_subtitle_text(value):
15772
+ return " ".join(str(value or "").split())
15773
+
15774
+
15775
+ def _read_srt_cue_texts(path):
15776
+ with open(path, "r", encoding="utf-8-sig") as handle:
15777
+ content = handle.read()
15778
+ cues = []
15779
+ for block in re.split(r"(?:\r?\n){2,}", content.strip()):
15780
+ lines = block.splitlines()
15781
+ timing_index = next(
15782
+ (index for index, line in enumerate(lines)
15783
+ if re.match(r"^\s*\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}\s*-->\s*"
15784
+ r"\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}(?:\s+.*)?$", line)),
15785
+ None,
15786
+ )
15787
+ if timing_index is None:
15788
+ raise ValueError("SRT cue has no valid timing line")
15789
+ text = _normalized_subtitle_text("\n".join(lines[timing_index + 1:]))
15790
+ if not text:
15791
+ raise ValueError("SRT cue has empty text")
15792
+ cues.append(text)
15793
+ if not cues:
15794
+ raise ValueError("SRT contains no cues")
15795
+ return cues
15796
+
15797
+
15798
+ def _created_timeline_readback(proj, created, clips):
15799
+ """Read back media IDs, subtitle cues, and source-less generator entries."""
15800
+ expected_ids, subtitle_ids, expected_generators = [], [], []
15801
+ subtitle_sources = []
15802
+ source_errors = []
15803
+ generator_warnings = []
15804
+ for clip in clips:
15805
+ clip_id = _safe_media_pool_item_id(clip)
15806
+ file_path = _created_clip_property(clip, "File Path")
15807
+ if (subtitle_append_guard.is_subtitle_item(clip)
15808
+ or (file_path and file_path.lower().endswith(".srt"))):
15809
+ if clip_id:
15810
+ subtitle_ids.append(clip_id)
15811
+ subtitle_sources.append(clip)
15812
+ continue
15813
+ clip_type = (_created_clip_property(clip, "Type") or "").strip().casefold()
15814
+ if clip_type in {"generator", "title", "fusion generator", "fusion composition"}:
15815
+ name = _safe_media_pool_item_name(clip)
15816
+ if name:
15817
+ expected_generators.append((clip_id, name))
15818
+ else:
15819
+ generator_warnings.append("Generator/title source has no readable name")
15820
+ elif clip_id:
15821
+ expected_ids.append(clip_id)
15822
+ else:
15823
+ name = _safe_media_pool_item_name(clip) or "<unnamed>"
15824
+ source_errors.append(f"Media source {name} has no readable unique ID")
15825
+ expected_ids = list(dict.fromkeys(expected_ids))
15826
+ subtitle_ids = list(dict.fromkeys(subtitle_ids))
15827
+ timeline_id = _safe_timeline_item_id(created)
15828
+ readback = {
15829
+ "timeline_id": timeline_id,
15830
+ "project_timeline_found": False,
15831
+ "item_count": 0,
15832
+ "media_pool_item_ids": [],
15833
+ "missing_clip_ids": list(expected_ids),
15834
+ "missing_generator_clip_ids": [clip_id for clip_id, _ in expected_generators if clip_id],
15835
+ "generator_item_names": [],
15836
+ "subtitle_readback": {
15837
+ "source_clip_ids": subtitle_ids,
15838
+ "sources": [],
15839
+ "mode": "source_srt" if subtitle_sources else None,
15840
+ "expected_cue_count": None,
15841
+ "cue_count": 0,
15842
+ "invalid_cue_count": 0,
15843
+ "text_mismatches": [],
15844
+ "verified": not subtitle_sources,
15845
+ },
15846
+ "errors": list(source_errors),
15847
+ "warnings": list(generator_warnings),
15848
+ "certain": False,
15849
+ "verified": False,
15850
+ }
15851
+ if not timeline_id:
15852
+ readback["errors"].append("Created timeline has no readable unique ID")
15853
+ return readback
15854
+ try:
15855
+ timeline_count = int(proj.GetTimelineCount() or 0)
15856
+ project_timeline = None
15857
+ for index in range(1, timeline_count + 1):
15858
+ candidate = proj.GetTimelineByIndex(index)
15859
+ if candidate and _safe_timeline_item_id(candidate) == timeline_id:
15860
+ project_timeline = candidate
15861
+ break
15862
+ except Exception as exc:
15863
+ readback["errors"].append(f"Project timeline enumeration failed: {exc}")
15864
+ return readback
15865
+ if project_timeline is None:
15866
+ readback["errors"].append("Created timeline unique ID is absent from the current project")
15867
+ return readback
15868
+ readback["project_timeline_found"] = True
15869
+
15870
+ observed_ids, generator_names, subtitle_texts = [], [], []
15871
+ for track_type in ("video", "audio", "subtitle"):
15872
+ try:
15873
+ track_count = int(project_timeline.GetTrackCount(track_type) or 0)
15874
+ except Exception as exc:
15875
+ readback["errors"].append(f"GetTrackCount({track_type}) failed: {exc}")
15876
+ continue
15877
+ for track_index in range(1, track_count + 1):
15878
+ try:
15879
+ items = project_timeline.GetItemListInTrack(track_type, track_index) or []
15880
+ except Exception as exc:
15881
+ readback["errors"].append(
15882
+ f"GetItemListInTrack({track_type}, {track_index}) failed: {exc}"
15883
+ )
15884
+ continue
15885
+ readback["item_count"] += len(items)
15886
+ for item in items:
15887
+ if track_type == "subtitle" and subtitle_sources:
15888
+ readback["subtitle_readback"]["cue_count"] += 1
15889
+ text = _normalized_subtitle_text(_safe_timeline_item_name(item))
15890
+ subtitle_texts.append(text)
15891
+ try:
15892
+ start, end = item.GetStart(), item.GetEnd()
15893
+ if not text or start is None or end is None or end <= start:
15894
+ readback["subtitle_readback"]["invalid_cue_count"] += 1
15895
+ except Exception:
15896
+ readback["subtitle_readback"]["invalid_cue_count"] += 1
15897
+ try:
15898
+ media_item = item.GetMediaPoolItem()
15899
+ media_id = _safe_media_pool_item_id(media_item)
15900
+ except Exception as exc:
15901
+ readback["errors"].append(f"Timeline item Media Pool readback failed: {exc}")
15902
+ continue
15903
+ if media_id and media_id not in observed_ids:
15904
+ observed_ids.append(media_id)
15905
+ if media_item is None and track_type != "subtitle" and expected_generators:
15906
+ try:
15907
+ name = item.GetName()
15908
+ start, end = item.GetStart(), item.GetEnd()
15909
+ if name and start is not None and end is not None and end > start:
15910
+ generator_names.append(name)
15911
+ except Exception:
15912
+ continue
15913
+ readback["media_pool_item_ids"] = observed_ids
15914
+ readback["missing_clip_ids"] = [clip_id for clip_id in expected_ids if clip_id not in observed_ids]
15915
+ readback["generator_item_names"] = list(dict.fromkeys(generator_names))
15916
+ readback["missing_generator_clip_ids"] = [
15917
+ clip_id for clip_id, name in expected_generators
15918
+ if clip_id and name not in generator_names
15919
+ ]
15920
+ subtitle_readback = readback["subtitle_readback"]
15921
+ expected_texts = []
15922
+ source_comparison = bool(subtitle_sources)
15923
+ for clip in subtitle_sources:
15924
+ path = _created_clip_property(clip, "File Path")
15925
+ source = {
15926
+ "name": _safe_media_pool_item_name(clip),
15927
+ "file_path": path,
15928
+ "cue_count": None,
15929
+ }
15930
+ subtitle_readback["sources"].append(source)
15931
+ if not path:
15932
+ source_comparison = False
15933
+ continue
15934
+ try:
15935
+ cue_texts = _read_srt_cue_texts(path)
15936
+ except (OSError, ValueError) as exc:
15937
+ # An SRT this parser cannot read (not UTF-8, unusual layout) says
15938
+ # nothing about the timeline: compare the timeline's own cues
15939
+ # instead of failing a create that worked (#373).
15940
+ source["read_error"] = f"{type(exc).__name__}: {exc}"
15941
+ source_comparison = False
15942
+ continue
15943
+ source["cue_count"] = len(cue_texts)
15944
+ expected_texts.extend(cue_texts)
15945
+ if source_comparison:
15946
+ subtitle_readback["expected_cue_count"] = len(expected_texts)
15947
+ subtitle_readback["text_mismatches"] = [
15948
+ {"index": index, "expected": expected, "observed": observed}
15949
+ for index, (expected, observed) in enumerate(zip(expected_texts, subtitle_texts))
15950
+ if expected != observed
15951
+ ]
15952
+ cue_count_matches = len(expected_texts) == len(subtitle_texts)
15953
+ else:
15954
+ subtitle_readback["mode"] = "timeline_cues" if subtitle_sources else None
15955
+ cue_count_matches = bool(subtitle_texts)
15956
+ subtitle_readback["verified"] = bool(
15957
+ not subtitle_sources
15958
+ or (subtitle_texts
15959
+ and cue_count_matches
15960
+ and not subtitle_readback["text_mismatches"]
15961
+ and subtitle_readback["invalid_cue_count"] == 0)
15962
+ )
15963
+ # Certain: the timeline is in the project, holds items, and every ordinary
15964
+ # media ID is on it. Heuristic: subtitle cue text (that GetName() equals
15965
+ # the cue text) and generator Type strings are not measured live, so a
15966
+ # miss there is reported, not turned into a failed call (#373).
15967
+ readback["certain"] = bool(
15968
+ (expected_ids or subtitle_sources or expected_generators)
15969
+ and not readback["missing_clip_ids"]
15970
+ and not readback["errors"]
15971
+ and readback["item_count"] > 0
15972
+ )
15973
+ readback["verified"] = bool(
15974
+ readback["certain"]
15975
+ and not readback["missing_generator_clip_ids"]
15976
+ and subtitle_readback["verified"]
15977
+ )
15978
+ return readback
15979
+
15980
+
15762
15981
  def _compare_timeline_append_readback(before, observed, expected_count: int):
15763
15982
  before_count = before.get("item_count") if isinstance(before, dict) and before.get("available") else None
15764
15983
  after_count = observed.get("item_count") if isinstance(observed, dict) and observed.get("available") else None
@@ -17184,14 +17403,32 @@ def _timeline_frame_of(tl, timecode) -> Optional[int]:
17184
17403
  return None if err else frame
17185
17404
 
17186
17405
 
17406
+ def _same_timecode_label(a, b) -> bool:
17407
+ """True when two timecodes name the same HH:MM:SS:FF label.
17408
+
17409
+ Separators and padding are ignored: Resolve reports a drop-frame
17410
+ timeline's playhead with ';' even when the seek was asked with ':', and
17411
+ the frame parser reads the two separators as different frame counts.
17412
+ """
17413
+ def parts(tc):
17414
+ if not isinstance(tc, str):
17415
+ return None
17416
+ fields = re.split(r"[:;.,]", tc.strip())
17417
+ if len(fields) != 4 or not all(f.isdigit() for f in fields):
17418
+ return None
17419
+ return tuple(int(f) for f in fields)
17420
+ pa = parts(a)
17421
+ return pa is not None and pa == parts(b)
17422
+
17423
+
17187
17424
  def _seek_and_confirm(tl, target: str, *, attempts: int = 8, delay: float = 0.1):
17188
17425
  """SetCurrentTimecode(target) and read the playhead back until it lands.
17189
17426
 
17190
17427
  Returns (landed_timecode, error). The return value of SetCurrentTimecode is
17191
17428
  not the evidence: a True that left the playhead where it was has been
17192
17429
  measured on Studio 19.1.3.7 straight after a page switch. The readback is
17193
- compared by FRAME, not by string, so a drop-frame ';' or a different
17194
- separator cannot fail a seek that landed.
17430
+ compared by FRAME, and by label with separators and padding ignored, so a
17431
+ drop-frame ';' or an unpadded hour cannot fail a seek that landed.
17195
17432
  """
17196
17433
  want = _timeline_frame_of(tl, target)
17197
17434
  try:
@@ -17211,7 +17448,7 @@ def _seek_and_confirm(tl, target: str, *, attempts: int = 8, delay: float = 0.1)
17211
17448
  landed = tl.GetCurrentTimecode()
17212
17449
  except Exception:
17213
17450
  landed = None
17214
- if want is None or _timeline_frame_of(tl, landed) == want:
17451
+ if want is None or _timeline_frame_of(tl, landed) == want or _same_timecode_label(target, landed):
17215
17452
  return landed, None
17216
17453
  if attempt < attempts - 1:
17217
17454
  time.sleep(delay)
@@ -23466,6 +23703,9 @@ def media_pool(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str
23466
23703
  start_frame & end_frame (or startFrame/endFrame), record_frame/recordFrame}.
23467
23704
  record_frame is relative to the created timeline start frame by default;
23468
23705
  pass record_frame_mode="absolute" for raw Resolve recordFrame values.
23706
+ Optional per row: track_index (1-based, default 1) and media_type (1 video,
23707
+ 2 audio). The new timeline gets the tracks the rows name, up to 32 of
23708
+ each type; a higher index is refused before anything is created.
23469
23709
  setup_multicam_timeline(name, clip_ids|angles, sync_mode?, include_audio?, dry_run?) -> {success}
23470
23710
  — creates a stacked multicam prep timeline: one angle per video track, optional
23471
23711
  matching audio tracks. Native multicam clip conversion remains a Resolve UI step.
@@ -23682,13 +23922,34 @@ def media_pool(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str
23682
23922
  if clips_err:
23683
23923
  return clips_err
23684
23924
  tl = mp.CreateTimelineFromClips(create_name, clips)
23925
+ if not tl:
23926
+ return _err("Failed to create timeline", code="CREATE_TIMELINE_FAILED")
23927
+ readback = _created_timeline_readback(proj, tl, clips)
23928
+ if not readback["certain"]:
23929
+ out = _err(
23930
+ "CreateTimelineFromClips returned a timeline, but its project or clip readback failed",
23931
+ code="CREATE_TIMELINE_READBACK_FAILED", category="resolve_api_failed",
23932
+ retryable=False,
23933
+ remediation=("Inspect the current project for the returned timeline ID before retrying; "
23934
+ "the native call may already have created a timeline."),
23935
+ state=readback,
23936
+ )
23937
+ out.update({"success": False, "verified": False, "readback": readback})
23938
+ return out
23685
23939
  return _ok(
23686
23940
  name=tl.GetName(),
23687
23941
  id=tl.GetUniqueId(),
23688
23942
  requested_name=p.get("name"),
23689
23943
  created_new=True,
23690
23944
  versioned_name=bool(existing and create_name != p.get("name")),
23691
- ) if tl else _err("Failed to create timeline")
23945
+ verified=readback["verified"],
23946
+ readback=readback,
23947
+ **({"warnings": readback["warnings"] + [
23948
+ "The timeline and its media were confirmed, but the subtitle-cue or "
23949
+ "generator read-back did not match. Those checks rest on behaviour "
23950
+ "not yet measured live; inspect the timeline."
23951
+ ]} if not readback["verified"] else {}),
23952
+ )
23692
23953
  elif action == "create_multicam_clip":
23693
23954
  missing = _requires_method(mp, "CreateMulticamClip", "21.1")
23694
23955
  if missing:
@@ -28804,7 +29065,7 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28804
29065
  delete_at_frame(frame|frame_id|frameId|timecode) -> {success}
28805
29066
  delete_by_custom_data(custom_data) -> {success}
28806
29067
  get_current_timecode() -> {timecode}
28807
- set_current_timecode(timecode) -> {success}
29068
+ set_current_timecode(timecode) -> {success, requested, target, before, actual, api_success, verified}
28808
29069
  get_current_video_item() -> {name, id}
28809
29070
  get_thumbnail() -> {thumbnail}
28810
29071
  get_thumbnail_image() -> MCP image content for the current Color-page frame
@@ -28905,7 +29166,49 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28905
29166
  elif action == "get_current_timecode":
28906
29167
  return {"timecode": tl.GetCurrentTimecode()}
28907
29168
  elif action == "set_current_timecode":
28908
- return {"success": bool(tl.SetCurrentTimecode(_playhead_absolute_timecode(tl, p["timecode"])))}
29169
+ # The read-back goes through _seek_and_confirm: it compares by FRAME
29170
+ # (a drop-frame ';' or an unpadded hour is the same playhead) and
29171
+ # retries, since a True that had not moved the playhead yet has been
29172
+ # measured straight after a page switch (#373).
29173
+ requested = p["timecode"]
29174
+ target = _playhead_absolute_timecode(tl, requested)
29175
+ try:
29176
+ before = tl.GetCurrentTimecode()
29177
+ except Exception:
29178
+ before = None
29179
+ landed, seek_err = _seek_and_confirm(tl, target)
29180
+ api_success = seek_err is None or seek_err["error"].get("code") == "SEEK_UNCONFIRMED"
29181
+ if seek_err is None:
29182
+ actual = landed
29183
+ else:
29184
+ try:
29185
+ actual = tl.GetCurrentTimecode()
29186
+ except Exception:
29187
+ actual = None
29188
+ result = {
29189
+ "success": seek_err is None,
29190
+ "requested": requested,
29191
+ "target": target,
29192
+ "before": before,
29193
+ "actual": actual,
29194
+ "api_success": api_success,
29195
+ "verified": seek_err is None,
29196
+ }
29197
+ if seek_err is not None:
29198
+ message = (
29199
+ f"SetCurrentTimecode returned True but the playhead reads {actual!r}, not {target!r}"
29200
+ if api_success else seek_err["error"]["message"]
29201
+ )
29202
+ error = _err(
29203
+ message,
29204
+ code="TIMECODE_READBACK_MISMATCH" if api_success else "SET_CURRENT_TIMECODE_FAILED",
29205
+ category="resolve_api_failed" if api_success else seek_err["error"].get("category", "api_error"),
29206
+ retryable=True,
29207
+ remediation=seek_err["error"].get("remediation"),
29208
+ state={key: value for key, value in result.items() if key != "success"},
29209
+ )
29210
+ result.update(error)
29211
+ return result
28909
29212
  elif action == "get_current_video_item":
28910
29213
  it = tl.GetCurrentVideoItem()
28911
29214
  return {"name": it.GetName(), "id": it.GetUniqueId()} if it else {"name": None, "id": None}
@@ -13,6 +13,14 @@ from typing import Any, Optional, Tuple
13
13
 
14
14
  MEDIA_TYPES = {1: "video", 2: "audio"}
15
15
 
16
+ #: Most tracks of one type a new timeline is given to satisfy its rows. A row
17
+ #: naming a higher index is far more often a typo (99 for 9) than a build
18
+ #: that needs it, and honouring it adds that many empty tracks with success
19
+ #: (reported on #370). A build that does need more creates the timeline, adds
20
+ #: tracks with timeline add_track, then appends; append_to_timeline checks
21
+ #: rows against the tracks that exist.
22
+ MAX_NEW_TIMELINE_TRACKS = 32
23
+
16
24
 
17
25
  def _as_int(value: Any) -> Optional[int]:
18
26
  """An int from an int, an integral float, or a digit string; else None."""
@@ -99,7 +107,8 @@ def needed_tracks(rows: Any) -> Tuple[Optional[dict], Optional[str]]:
99
107
 
100
108
  For building a new timeline from rows: each row's track_index (default 1)
101
109
  must be valid, and the timeline then needs that many tracks of the row's
102
- media type, or of both types when the row sets none.
110
+ media type, or of both types when the row sets none. An index above
111
+ MAX_NEW_TIMELINE_TRACKS is refused rather than growing the timeline to it.
103
112
  """
104
113
  needed = {"video": 1, "audio": 0}
105
114
  for i, ci in enumerate(rows if isinstance(rows, list) else []):
@@ -111,6 +120,13 @@ def needed_tracks(rows: Any) -> Tuple[Optional[dict], Optional[str]]:
111
120
  mt, err = coerce_media_type(ci.get("mediaType", ci.get("media_type")), i)
112
121
  if err:
113
122
  return None, err
123
+ if ti > MAX_NEW_TIMELINE_TRACKS:
124
+ return None, (
125
+ f"clip_infos[{i}] track_index {ti} would give the new timeline {ti} "
126
+ f"tracks, past the {MAX_NEW_TIMELINE_TRACKS} it adds for its rows; "
127
+ "nothing was created. If the index is intended, create the timeline, "
128
+ "add the tracks with timeline add_track, then use append_to_timeline."
129
+ )
114
130
  for track_type in ([MEDIA_TYPES[mt]] if mt else ["video", "audio"]):
115
131
  needed[track_type] = max(needed[track_type], ti)
116
132
  return needed, None
@@ -11,7 +11,7 @@ import shutil
11
11
  import subprocess
12
12
  import uuid
13
13
  from pathlib import Path
14
- from src.utils.resolve_writes import set_current_timeline, describe_switch_failure
14
+ from src.utils.resolve_writes import set_current_timeline, describe_switch_failure, unique_id
15
15
  from src.utils.title_library import find_subtitle_preset
16
16
 
17
17
  ROOT = Path(__file__).resolve().parents[2]
@@ -130,10 +130,97 @@ def _preflight(timeline, params):
130
130
  return node, dry_run, track
131
131
 
132
132
 
133
+ def _post_write_database_health(resolve, project_id, timeline, target_track):
134
+ """Check that a live subtitle write left the same project readable.
135
+
136
+ Guards against a native import or timeline switch that answers success
137
+ while Resolve has moved to another project or lost its database. That
138
+ state has not been measured on a build; the check is defensive (#373).
139
+ Never attempt a repair here: the safe remediation is a manual Resolve
140
+ restart.
141
+ """
142
+ health = {
143
+ "healthy": False,
144
+ "project_id_before": project_id,
145
+ "project_id_after": None,
146
+ "project_unchanged": False,
147
+ "database_attached": False,
148
+ "current_timeline_id": None,
149
+ "expected_timeline_id": unique_id(timeline),
150
+ "current_timeline_verified": False,
151
+ "target_track": target_track,
152
+ "target_item_count": None,
153
+ "target_items_healthy": False,
154
+ "errors": [],
155
+ }
156
+ try:
157
+ pm = resolve.GetProjectManager()
158
+ database = pm.GetCurrentDatabase() if pm else None
159
+ health["database_attached"] = bool(database)
160
+ if not database:
161
+ health["errors"].append("Resolve has no database attached")
162
+ current_project = pm.GetCurrentProject() if pm else None
163
+ except Exception as exc:
164
+ health["errors"].append(f"Project/database readback failed: {exc}")
165
+ return health
166
+
167
+ health["project_id_after"] = unique_id(current_project)
168
+ health["project_unchanged"] = bool(
169
+ project_id and health["project_id_after"] == project_id
170
+ )
171
+ if current_project is None:
172
+ health["errors"].append("Resolve returned no current project after the write")
173
+ elif not health["project_unchanged"]:
174
+ health["errors"].append("The current project unique ID changed during the write")
175
+
176
+ try:
177
+ current_timeline = current_project.GetCurrentTimeline() if current_project else None
178
+ health["current_timeline_id"] = unique_id(current_timeline)
179
+ health["current_timeline_verified"] = bool(
180
+ health["expected_timeline_id"]
181
+ and health["current_timeline_id"] == health["expected_timeline_id"]
182
+ )
183
+ if not health["current_timeline_verified"]:
184
+ health["errors"].append("The verified subtitle revision is not the current timeline")
185
+ except Exception as exc:
186
+ health["errors"].append(f"Current timeline readback failed: {exc}")
187
+ return health
188
+
189
+ if not health["current_timeline_verified"]:
190
+ return health
191
+ item_errors = []
192
+ try:
193
+ items = current_timeline.GetItemListInTrack("subtitle", target_track)
194
+ if items is None:
195
+ raise RuntimeError("GetItemListInTrack returned None")
196
+ health["target_item_count"] = len(items)
197
+ for item in items:
198
+ if not unique_id(item):
199
+ item_errors.append("A target subtitle item has no readable unique ID")
200
+ continue
201
+ start, end = item.GetStart(), item.GetEnd()
202
+ if start is None or end is None or end < start:
203
+ item_errors.append(f"Subtitle item {unique_id(item)} has invalid bounds")
204
+ except Exception as exc:
205
+ item_errors.append(f"Target subtitle item readback failed: {exc}")
206
+ health["target_items_healthy"] = not item_errors and health["target_item_count"] is not None
207
+ health["errors"].extend(item_errors)
208
+ health["healthy"] = bool(
209
+ health["database_attached"]
210
+ and health["project_unchanged"]
211
+ and health["current_timeline_verified"]
212
+ and health["target_items_healthy"]
213
+ and not health["errors"]
214
+ )
215
+ return health
216
+
217
+
133
218
  def _revise(resolve, project, timeline, params, safe_dir, *, dry_run, build, check, report, edited_track=None):
134
219
  """Export, build(source, output, staging) a patched DRT, import it as a selected
135
220
  revision and check(readback, patch) Resolve's re-export of it. The original is
136
221
  never modified and stays active on any failure or preview."""
222
+ project_id = unique_id(project)
223
+ database_health = None
137
224
  name = params.get("revision_name") or f"{timeline.GetName()} - subtitles {uuid.uuid4().hex[:8]}"
138
225
  if any(project.GetTimelineByIndex(i).GetName() == name for i in range(1, project.GetTimelineCount() + 1)):
139
226
  return {"success": False, "error": "revision_name already exists"}
@@ -179,17 +266,39 @@ def _revise(resolve, project, timeline, params, safe_dir, *, dry_run, build, che
179
266
  if original_timecode:
180
267
  if not imported.SetCurrentTimecode(original_timecode) or imported.GetCurrentTimecode() != original_timecode:
181
268
  warnings.append("Subtitle revision was selected, but its playhead could not be restored")
269
+ database_health = _post_write_database_health(
270
+ resolve, project_id, imported, params.get("track", 1)
271
+ )
272
+ if not database_health["healthy"]:
273
+ result = {
274
+ "success": False,
275
+ "error": "Resolve project/database health verification failed after the subtitle write",
276
+ "error_code": "RESOLVE_DATABASE_UNHEALTHY",
277
+ "restart_required": True,
278
+ "remediation": ("Quit and restart Resolve manually, then reopen and inspect the project before "
279
+ "retrying. This tool does not repair a detached Resolve database."),
280
+ "api_success": True,
281
+ "verified": False,
282
+ "database_health": database_health,
283
+ "original_export": str(source),
284
+ "failed_revision": imported.GetName(),
285
+ }
286
+ return result
182
287
  succeeded = True
183
288
  result = {"success": True, "restart_required": False, "original_timeline": timeline.GetName(),
184
289
  "timeline": imported.GetName(), "timeline_id": imported.GetUniqueId(),
185
- "patch": patch, **report, "render_verified": False}
290
+ "patch": patch, **report, "render_verified": False,
291
+ "api_success": True, "database_health": database_health, "verified": True}
186
292
  if warnings:
187
293
  result["warnings"] = warnings
188
294
  return result
189
295
  except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
190
296
  result = {"success": False, "error": str(exc), "restart_required": False,
297
+ "api_success": False, "verified": False,
191
298
  "original_export": str(source),
192
299
  "failed_revision": imported.GetName() if imported else None}
300
+ if database_health is not None:
301
+ result["database_health"] = database_health
193
302
  return result
194
303
  finally:
195
304
  # A failed or preview operation must leave the user's working timeline active.