@morshoto/framekit 0.1.13 → 0.1.16

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.
Files changed (30) hide show
  1. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +28 -0
  2. package/dist-package/adapters/final-cut/typescript/src/canonical.js +144 -35
  3. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +36 -7
  4. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -0
  5. package/dist-package/adapters/final-cut/typescript/src/live.js +56 -1
  6. package/dist-package/adapters/final-cut/typescript/src/native.js +311 -20
  7. package/dist-package/adapters/final-cut/typescript/src/pasteboard-snapshot.js +312 -0
  8. package/dist-package/adapters/final-cut/typescript/src/publisher.js +68 -8
  9. package/dist-package/adapters/final-cut/typescript/src/sqlite-wal-observation.js +263 -0
  10. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +75 -3
  11. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.js +62 -0
  12. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +443 -0
  13. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +181 -0
  14. package/dist-package/adapters/headless/typescript/src/index.js +3 -0
  15. package/dist-package/apps/mcp-server/src/headless-projects.js +139 -0
  16. package/dist-package/apps/mcp-server/src/headless-sessions.js +3 -0
  17. package/dist-package/apps/mcp-server/src/main.js +22 -1
  18. package/dist-package/apps/mcp-server/src/materialization-jobs.js +233 -4
  19. package/dist-package/apps/mcp-server/src/readback-policy.js +26 -0
  20. package/dist-package/apps/mcp-server/src/routing.js +134 -5
  21. package/dist-package/apps/mcp-server/src/server.js +214 -31
  22. package/dist-package/packages/runtime/src/application/local-media.js +157 -0
  23. package/dist-package/packages/runtime/src/application/project-store.js +234 -0
  24. package/dist-package/packages/runtime/src/application/project-transactions.js +227 -0
  25. package/dist-package/packages/runtime/src/index.js +6 -0
  26. package/dist-package/packages/runtime/src/render/render-and-verify.js +126 -0
  27. package/dist-package/packages/runtime/src/render/render-contract.js +143 -0
  28. package/dist-package/packages/runtime/src/timeline/editing-session.js +277 -9
  29. package/dist-package/packages/runtime/src/timeline/fast-observation.js +141 -0
  30. package/package.json +2 -1
@@ -74,6 +74,7 @@ export class FinalCutNativeAutomationAdapter {
74
74
  enabled;
75
75
  titleDiscoveryAvailable;
76
76
  executor;
77
+ nativeMouseExecutor;
77
78
  canDriveNativeMouse;
78
79
  liveState;
79
80
  nativeOperationLease;
@@ -106,6 +107,7 @@ export class FinalCutNativeAutomationAdapter {
106
107
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
107
108
  this.titleDiscoveryAvailable = this.enabled;
108
109
  this.executor = options.executor ?? runAppleScript;
110
+ this.nativeMouseExecutor = options.nativeMouseExecutor;
109
111
  this.canDriveNativeMouse = options.executor === undefined;
110
112
  this.liveState = options.liveState;
111
113
  this.nativeOperationLease = options.nativeOperationLease;
@@ -286,7 +288,12 @@ export class FinalCutNativeAutomationAdapter {
286
288
  const command = commandName(operation);
287
289
  const requiresPlayhead = operation.type === "trim-selected-clip-to-playhead" || operation.type === "add-marker-at-playhead";
288
290
  try {
289
- await this.executeNativeCommand(editScript(operation), (recovered) => this.assertRetryContext(before, recovered, requiresPlayhead));
291
+ if (operation.type === "rename-selected-clip" && (this.canDriveNativeMouse || this.nativeMouseExecutor)) {
292
+ await this.executeNativeMouseScript(nativeRenameSource(operation.name));
293
+ }
294
+ else {
295
+ await this.executeNativeCommand(editScript(operation), (recovered) => this.assertRetryContext(before, recovered, requiresPlayhead));
296
+ }
290
297
  }
291
298
  catch (error) {
292
299
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
@@ -713,6 +720,12 @@ export class FinalCutNativeAutomationAdapter {
713
720
  async locateOccurrence(mediaHandle, options = {}) {
714
721
  return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle), options.signal);
715
722
  }
723
+ async selectOccurrence(occurrenceHandle, options = {}) {
724
+ return this.withNativeUi(() => this.selectOccurrenceNative(occurrenceHandle), options.signal);
725
+ }
726
+ async selectCanonicalOccurrence(name, occurrenceIndex, options = {}) {
727
+ return this.withNativeUi(() => this.selectCanonicalOccurrenceNative(name, occurrenceIndex), options.signal);
728
+ }
716
729
  async targetMedia(query, options = {}) {
717
730
  return this.withNativeUi(() => this.targetMediaNative(query), options.signal);
718
731
  }
@@ -839,6 +852,45 @@ export class FinalCutNativeAutomationAdapter {
839
852
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
840
853
  }
841
854
  }
855
+ async selectOccurrenceNative(occurrenceHandle) {
856
+ this.assertEnabled();
857
+ const occurrence = this.occurrenceHandles.get(occurrenceHandle);
858
+ if (!occurrence)
859
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown occurrence handle ${occurrenceHandle}`);
860
+ await this.validateOccurrenceBinding(occurrence);
861
+ if (occurrence.timelineOffset === undefined) {
862
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: occurrence has no selectable timeline position");
863
+ }
864
+ await this.selectTimelineOccurrence(occurrence.timelineOffset);
865
+ const context = await this.requireTimelineContext();
866
+ if (context.target.kind !== "selected-clip") {
867
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_SELECTION_UNAVAILABLE: Final Cut did not expose the selected occurrence");
868
+ }
869
+ if (context.target.identity)
870
+ occurrence.nativeIdentity = context.target.identity;
871
+ return context;
872
+ }
873
+ async selectCanonicalOccurrenceNative(name, occurrenceIndex) {
874
+ this.assertEnabled();
875
+ if (!name.trim() || !Number.isInteger(occurrenceIndex) || occurrenceIndex < 1) {
876
+ throw new Error("INVALID_OPERATION: canonical native occurrence name and positive occurrence index are required");
877
+ }
878
+ const coordinates = (await this.executeNativeScript(canonicalTimelineSelectionScript(name, occurrenceIndex)))
879
+ .split("|").map(Number);
880
+ const [x, y] = coordinates;
881
+ if (![x, y].every(Number.isFinite)) {
882
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: canonical timeline occurrence has no selectable position");
883
+ }
884
+ await this.executeNativeMouseScript(nativeMouseSelectionSource(Math.round(x), Math.round(y)));
885
+ const context = await this.requireTimelineContext();
886
+ if (context.target.kind !== "selected-clip" || context.target.name !== name) {
887
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_SELECTION_UNAVAILABLE: selected timeline occurrence does not match the canonical target");
888
+ }
889
+ if (context.target.occurrenceIndex !== undefined && context.target.occurrenceIndex !== occurrenceIndex) {
890
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_SELECTION_UNAVAILABLE: selected timeline occurrence index does not match the canonical target");
891
+ }
892
+ return context;
893
+ }
842
894
  async previewBlade(occurrenceHandle, options = {}) {
843
895
  return this.withNativeUi(() => this.previewBladeNative(occurrenceHandle), options.signal);
844
896
  }
@@ -2139,17 +2191,25 @@ export class FinalCutNativeAutomationAdapter {
2139
2191
  }
2140
2192
  }
2141
2193
  async prepareNativeRetry() {
2142
- return this.attachLiveState(await this.ensureTimelineReady());
2194
+ await this.ensureTimelineReady();
2195
+ const recovered = await this.inspectRawNative();
2196
+ if (!recovered.available) {
2197
+ throw new Error(`${recovered.error?.code ?? "FINAL_CUT_NATIVE_UNAVAILABLE"}: ${recovered.error?.message ?? "native retry context unavailable"}`);
2198
+ }
2199
+ return recovered;
2143
2200
  }
2144
2201
  assertRetryContext(expected, recovered, requirePlayhead = false) {
2145
2202
  const targetChanged = expected.target.kind !== recovered.target.kind
2146
2203
  || expected.target.name !== recovered.target.name
2147
2204
  || expected.target.role !== recovered.target.role;
2148
2205
  const occurrenceChanged = expected.target.kind === "selected-clip" && recovered.target.kind === "selected-clip"
2149
- && (!expected.target.identity || !recovered.target.identity || expected.target.identity !== recovered.target.identity);
2206
+ && (expected.target.identity && recovered.target.identity
2207
+ ? expected.target.identity !== recovered.target.identity
2208
+ : expected.target.occurrenceIndex !== undefined && recovered.target.occurrenceIndex !== undefined
2209
+ ? expected.target.occurrenceIndex !== recovered.target.occurrenceIndex
2210
+ : true);
2150
2211
  const playheadChanged = requirePlayhead
2151
- ? !expected.playheadTime || !recovered.playheadTime || expected.playheadTime !== recovered.playheadTime
2152
- : expected.playheadTime !== recovered.playheadTime;
2212
+ && (!expected.playheadTime || !recovered.playheadTime || expected.playheadTime !== recovered.playheadTime);
2153
2213
  if (targetChanged || occurrenceChanged || playheadChanged) {
2154
2214
  throw new Error("FINAL_CUT_NATIVE_RETRY_TARGET_CHANGED: Final Cut selection or playhead changed during focus recovery");
2155
2215
  }
@@ -2523,6 +2583,10 @@ export class FinalCutNativeAutomationAdapter {
2523
2583
  }
2524
2584
  }
2525
2585
  async executeNativeMouseScript(source) {
2586
+ if (this.nativeMouseExecutor) {
2587
+ await this.nativeMouseExecutor(source);
2588
+ return;
2589
+ }
2526
2590
  const requestSignal = this.requestContext.getStore()?.signal;
2527
2591
  const effectiveDeadline = this.now() + this.nativePreflightTimeoutMs;
2528
2592
  if (requestSignal?.aborted)
@@ -2641,8 +2705,10 @@ function nativeRollbackEvidence(record) {
2641
2705
  && (beforeTargetIdentity && afterTargetIdentity
2642
2706
  ? beforeTargetIdentity === afterTargetIdentity
2643
2707
  : !beforeTargetIdentity && !afterTargetIdentity
2644
- && record.before.target.kind !== "selected-clip"
2645
- && (record.before.target.kind === "playhead" || record.before.target.name === record.after.target.name));
2708
+ && (record.before.target.occurrenceIndex !== undefined && record.after.target.occurrenceIndex !== undefined
2709
+ ? record.before.target.occurrenceIndex === record.after.target.occurrenceIndex
2710
+ : record.before.target.kind !== "selected-clip"
2711
+ && (record.before.target.kind === "playhead" || record.before.target.name === record.after.target.name)));
2646
2712
  const insertedTargetBound = (record.kind === "title-placement"
2647
2713
  || record.kind === "picture-in-picture"
2648
2714
  || record.kind === "transition-placement")
@@ -2676,7 +2742,23 @@ function nativeRollbackEvidence(record) {
2676
2742
  };
2677
2743
  }
2678
2744
  function verifyNativeUndo(operation, after, afterLive) {
2679
- if (operation.afterLive && (!afterLive || afterLive.revision.id === operation.afterLive.revision.id)) {
2745
+ const liveRevisionAdvanced = Boolean(operation.afterLive
2746
+ && afterLive
2747
+ && afterLive.revision.id !== operation.afterLive.revision.id);
2748
+ const selectedTargetRestored = operation.kind === "selection"
2749
+ && operation.before.target.kind === "selected-clip"
2750
+ && after.target.kind === "selected-clip"
2751
+ && operation.before.target.name === after.target.name;
2752
+ // Final Cut can undo clip metadata without advancing the workflow-extension
2753
+ // live revision, and its Undo action can clear the timeline selection. In
2754
+ // that case the consumed Undo command is the native UI proof; disposable
2755
+ // workflows still require canonical read-after-Undo digest equality.
2756
+ const nativeUndoConsumed = operation.kind === "selection"
2757
+ && operation.undoCommand !== undefined
2758
+ && after.undoCommand !== operation.undoCommand
2759
+ && (after.target.kind !== "selected-clip" || selectedTargetRestored);
2760
+ const selectionClearedAfterConsumedUndo = nativeUndoConsumed && after.target.kind !== "selected-clip";
2761
+ if (operation.afterLive && !liveRevisionAdvanced && !selectedTargetRestored && !nativeUndoConsumed) {
2680
2762
  return { verified: false, detail: "Final Cut did not expose a new revision after Undo" };
2681
2763
  }
2682
2764
  if (operation.beforeDuration) {
@@ -2685,10 +2767,10 @@ function verifyNativeUndo(operation, after, afterLive) {
2685
2767
  if (!detail.verified)
2686
2768
  return detail;
2687
2769
  }
2688
- if (operation.before.target.identity && after.target.identity !== operation.before.target.identity) {
2770
+ if (operation.before.target.identity && after.target.identity !== operation.before.target.identity && !selectionClearedAfterConsumedUndo) {
2689
2771
  return { verified: false, detail: "native target identity changed during Undo" };
2690
2772
  }
2691
- if (operation.kind === "selection" && operation.before.target.name !== after.target.name) {
2773
+ if (operation.kind === "selection" && operation.before.target.name !== after.target.name && !selectionClearedAfterConsumedUndo) {
2692
2774
  return {
2693
2775
  verified: false,
2694
2776
  detail: `expected selected target ${operation.before.target.name ?? "<unnamed>"}, observed ${after.target.name ?? "<unnamed>"}`,
@@ -3213,6 +3295,22 @@ using terms from application "System Events"
3213
3295
  end repeat
3214
3296
  return ""
3215
3297
  end selectedTimelineItem
3298
+
3299
+ on selectedTimelineOccurrenceIndex(timelineArea)
3300
+ set occurrenceIndex to 0
3301
+ repeat with candidateRef in UI elements of timelineArea
3302
+ try
3303
+ set candidate to contents of candidateRef
3304
+ if (role of candidate as text) is "AXLayoutItem" then
3305
+ set occurrenceIndex to occurrenceIndex + 1
3306
+ if (selected of candidate) is true then return occurrenceIndex as text
3307
+ end if
3308
+ on error
3309
+ -- Ignore inaccessible descendants and continue the bounded scan.
3310
+ end try
3311
+ end repeat
3312
+ return ""
3313
+ end selectedTimelineOccurrenceIndex
3216
3314
  end using terms from
3217
3315
 
3218
3316
  on preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, undoEnabled, bladeEnabled, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, undoCommand, selectedIdentity)
@@ -3237,8 +3335,8 @@ tell application "System Events"
3237
3335
  set mainOrigin to {0, 0}
3238
3336
  set mainSize to {0, 0}
3239
3337
  try
3240
- if (count of windows) > 0 then
3241
- set frontWindow to front window
3338
+ if exists window "Final Cut Pro" then
3339
+ set frontWindow to window "Final Cut Pro"
3242
3340
  set frontWindowName to name of frontWindow as text
3243
3341
  set timelineWindowAvailable to true
3244
3342
  set mainOrigin to position of frontWindow
@@ -3249,11 +3347,13 @@ tell application "System Events"
3249
3347
  set selectedName to ""
3250
3348
  set selectedRole to ""
3251
3349
  set selectedIdentity to ""
3350
+ set selectedOccurrenceIndex to ""
3252
3351
  set selectionLookupAvailable to false
3253
3352
  try
3254
- set timelineArea to UI element 1 of UI element 8 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
3353
+ set timelineArea to UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
3255
3354
  set selectionLookupAvailable to true
3256
3355
  set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
3356
+ set selectedOccurrenceIndex to my selectedTimelineOccurrenceIndex(timelineArea)
3257
3357
  if selectedRecord is not "" then
3258
3358
  set selectedFields to my splitText(selectedRecord, ASCII character 31)
3259
3359
  set selectedName to item 1 of selectedFields
@@ -3316,7 +3416,7 @@ tell application "System Events"
3316
3416
  end try
3317
3417
  set focusTarget to my focusTargetFor(focusedRole, focusedDescription, focusedName)
3318
3418
  set timelineFocused to processFrontmost is "true" and focusTarget is "timeline"
3319
- return my preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, undoEnabled, bladeEnabled, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, 0, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, undoCommand, selectedIdentity)
3419
+ return (my preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, undoEnabled, bladeEnabled, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, 0, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, undoCommand, selectedIdentity)) & (ASCII character 31) & selectedOccurrenceIndex
3320
3420
  end tell
3321
3421
  end tell`;
3322
3422
  }
@@ -3647,6 +3747,68 @@ function inspectScript() {
3647
3747
  end repeat
3648
3748
  return ""
3649
3749
  end selectedTimelineItem
3750
+
3751
+ on selectedTimelineOccurrenceIndex(timelineArea)
3752
+ set occurrenceIndex to 0
3753
+ repeat with candidateRef in UI elements of timelineArea
3754
+ try
3755
+ set candidate to contents of candidateRef
3756
+ if (role of candidate as text) is "AXLayoutItem" then
3757
+ set occurrenceIndex to occurrenceIndex + 1
3758
+ if (selected of candidate) is true then return occurrenceIndex as text
3759
+ end if
3760
+ on error
3761
+ -- Ignore inaccessible descendants and continue the bounded scan.
3762
+ end try
3763
+ end repeat
3764
+ return ""
3765
+ end selectedTimelineOccurrenceIndex
3766
+
3767
+ on findInspectorName(containerItem, depth)
3768
+ if depth > 10 then return ""
3769
+ try
3770
+ if (role of containerItem as text) is "AXScrollArea" then
3771
+ if (description of containerItem as text) is "metadata inspector" then
3772
+ repeat with childRef in UI elements of containerItem
3773
+ set child to contents of childRef
3774
+ try
3775
+ if (role of child as text) is "AXTextField" and (description of child as text) is "name" then
3776
+ return value of child as text
3777
+ end if
3778
+ on error
3779
+ -- Ignore inaccessible inspector fields.
3780
+ end try
3781
+ end repeat
3782
+ return ""
3783
+ end if
3784
+ end if
3785
+ on error
3786
+ -- Ignore inaccessible inspector containers.
3787
+ end try
3788
+ try
3789
+ repeat with candidateRef in UI elements of containerItem
3790
+ set candidate to contents of candidateRef
3791
+ set candidateRole to ""
3792
+ set candidateDescription to ""
3793
+ try
3794
+ set candidateRole to role of candidate as text
3795
+ set candidateDescription to description of candidate as text
3796
+ on error
3797
+ -- Ignore inaccessible nodes and continue the bounded search.
3798
+ end try
3799
+ if candidateRole is "AXScrollArea" and candidateDescription is "metadata inspector" then
3800
+ set foundName to my findInspectorName(candidate, depth + 1)
3801
+ if foundName is not "" then return foundName
3802
+ else if candidateRole is "AXGroup" or candidateRole is "AXSplitGroup" or candidateRole is "AXWindow" then
3803
+ set foundName to my findInspectorName(candidate, depth + 1)
3804
+ if foundName is not "" then return foundName
3805
+ end if
3806
+ end repeat
3807
+ on error
3808
+ -- Ignore inaccessible containers and continue the bounded search.
3809
+ end try
3810
+ return ""
3811
+ end findInspectorName
3650
3812
  end using terms from
3651
3813
 
3652
3814
  tell application "System Events"
@@ -3659,15 +3821,17 @@ function inspectScript() {
3659
3821
  set selectedName to ""
3660
3822
  set selectedRole to ""
3661
3823
  set selectedIdentity to ""
3824
+ set selectedOccurrenceIndex to ""
3662
3825
  set selectedCount to 0
3663
3826
  set selectedRecord to ""
3664
3827
  set selectionLookupAvailable to false
3665
3828
  -- Final Cut exposes the Project Timeline as a stable bounded AX node.
3666
3829
  -- Start there instead of traversing Browser and Effects Library trees.
3667
3830
  try
3668
- set timelineArea to UI element 1 of UI element 8 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
3831
+ set timelineArea to UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
3669
3832
  set selectionLookupAvailable to true
3670
3833
  set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
3834
+ set selectedOccurrenceIndex to my selectedTimelineOccurrenceIndex(timelineArea)
3671
3835
  end try
3672
3836
  if selectedRecord is not "" then
3673
3837
  set selectedFields to my splitText(selectedRecord, ASCII character 31)
@@ -3676,6 +3840,8 @@ function inspectScript() {
3676
3840
  set selectedIdentity to item 3 of selectedFields
3677
3841
  set selectedCount to 1
3678
3842
  end if
3843
+ set inspectorName to my findInspectorName(frontWindow, 0)
3844
+ if inspectorName is not "" and selectedCount is 1 then set selectedName to inspectorName
3679
3845
  if not selectionLookupAvailable then set selectedCount to -1
3680
3846
  set undoEnabled to false
3681
3847
  set undoCommand to ""
@@ -3707,7 +3873,7 @@ function inspectScript() {
3707
3873
  set focusedDescription to description of focusedElement as text
3708
3874
  end try
3709
3875
  set frontState to frontmost as text
3710
- return frontState & (ASCII character 31) & frontWindowName & (ASCII character 31) & selectedCount & (ASCII character 31) & selectedName & (ASCII character 31) & selectedRole & (ASCII character 31) & undoEnabled & (ASCII character 31) & bladeEnabled & (ASCII character 31) & focusedName & (ASCII character 31) & focusedRole & (ASCII character 31) & focusedDescription & (ASCII character 31) & "true" & (ASCII character 31) & "true" & (ASCII character 31) & "timeline" & (ASCII character 31) & "0" & (ASCII character 31) & "false" & (ASCII character 31) & "true" & (ASCII character 31) & frontWindowName & (ASCII character 31) & "false" & (ASCII character 31) & undoCommand & (ASCII character 31) & selectedIdentity
3876
+ return (frontState & (ASCII character 31) & frontWindowName & (ASCII character 31) & selectedCount & (ASCII character 31) & selectedName & (ASCII character 31) & selectedRole & (ASCII character 31) & undoEnabled & (ASCII character 31) & bladeEnabled & (ASCII character 31) & focusedName & (ASCII character 31) & focusedRole & (ASCII character 31) & focusedDescription & (ASCII character 31) & "true" & (ASCII character 31) & "true" & (ASCII character 31) & "timeline" & (ASCII character 31) & "0" & (ASCII character 31) & "false" & (ASCII character 31) & "true" & (ASCII character 31) & frontWindowName & (ASCII character 31) & "false" & (ASCII character 31) & undoCommand & (ASCII character 31) & selectedIdentity) & (ASCII character 31) & selectedOccurrenceIndex
3711
3877
  end tell
3712
3878
  end tell`;
3713
3879
  }
@@ -4646,6 +4812,35 @@ tell application "System Events"
4646
4812
  end tell
4647
4813
  end tell`;
4648
4814
  }
4815
+ function canonicalTimelineSelectionScript(name, occurrenceIndex) {
4816
+ return `
4817
+ tell application "System Events"
4818
+ tell process "Final Cut Pro"
4819
+ ${requireFrontmostAppleScript()}
4820
+ set mainWindow to window "Final Cut Pro"
4821
+ set timelineArea to UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of mainWindow
4822
+ set targetName to ${appleScriptString(name)}
4823
+ set currentIndex to 0
4824
+ repeat with candidateRef in UI elements of timelineArea
4825
+ try
4826
+ set candidate to contents of candidateRef
4827
+ if (role of candidate as text) is "AXLayoutItem" then
4828
+ set currentIndex to currentIndex + 1
4829
+ set candidateDescription to description of candidate as text
4830
+ if currentIndex is ${occurrenceIndex} and candidateDescription contains ("Video-Clip:" & targetName) then
4831
+ set candidatePosition to position of candidate
4832
+ set candidateSize to size of candidate
4833
+ return ((item 1 of candidatePosition) + ((item 1 of candidateSize) / 2)) as text & "|" & ((item 2 of candidatePosition) + ((item 2 of candidateSize) / 2)) as text
4834
+ end if
4835
+ end if
4836
+ on error
4837
+ -- Ignore inaccessible timeline nodes and continue the bounded scan.
4838
+ end try
4839
+ end repeat
4840
+ error "FINAL_CUT_NATIVE_OCCURRENCE_NOT_FOUND: canonical timeline occurrence was not exposed"
4841
+ end tell
4842
+ end tell`;
4843
+ }
4649
4844
  function timelineInsertionCoordinatesScript() {
4650
4845
  return `
4651
4846
  tell application "System Events"
@@ -4695,6 +4890,95 @@ pressKey(115)
4695
4890
  for _ in 0..<30 { pressKey(124) }
4696
4891
  `;
4697
4892
  }
4893
+ function nativeRenameSource(name) {
4894
+ const units = Array.from({ length: name.length }, (_, index) => name.charCodeAt(index)).join(", ");
4895
+ return `
4896
+ import AppKit
4897
+ import ApplicationServices
4898
+ import CoreGraphics
4899
+ import Foundation
4900
+
4901
+ let finalCutPid = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.FinalCut").first!.processIdentifier
4902
+ let application = AXUIElementCreateApplication(finalCutPid)
4903
+
4904
+ func attribute(_ element: AXUIElement, _ key: String) -> Any? {
4905
+ var value: CFTypeRef?
4906
+ let result = AXUIElementCopyAttributeValue(element, key as CFString, &value)
4907
+ return result == .success ? value : nil
4908
+ }
4909
+
4910
+ func text(_ element: AXUIElement, _ key: String) -> String {
4911
+ String(describing: attribute(element, key) ?? "")
4912
+ }
4913
+
4914
+ func isSelected(_ element: AXUIElement) -> Bool {
4915
+ let value = text(element, "AXSelected")
4916
+ return value == "1" || value == "true"
4917
+ }
4918
+
4919
+ func findSelectedTimelineItem(_ element: AXUIElement) -> AXUIElement? {
4920
+ if text(element, "AXRole") == "AXLayoutItem" && isSelected(element) { return element }
4921
+ if let children = attribute(element, "AXChildren") as? [AXUIElement] {
4922
+ for child in children {
4923
+ if let result = findSelectedTimelineItem(child) { return result }
4924
+ }
4925
+ }
4926
+ return nil
4927
+ }
4928
+
4929
+ func findRenameMenuItem(_ element: AXUIElement) -> AXUIElement? {
4930
+ if text(element, "AXRole") == "AXMenuItem" && text(element, "AXTitle") == "Rename Clip" { return element }
4931
+ if let children = attribute(element, "AXChildren") as? [AXUIElement] {
4932
+ for child in children {
4933
+ if let result = findRenameMenuItem(child) { return result }
4934
+ }
4935
+ }
4936
+ return nil
4937
+ }
4938
+
4939
+ guard let selectedItem = findSelectedTimelineItem(application) else {
4940
+ fatalError("FINAL_CUT_NATIVE_SELECTION_REQUIRED: selected timeline item was not exposed")
4941
+ }
4942
+ _ = AXUIElementPerformAction(selectedItem, kAXShowMenuAction as CFString)
4943
+ var renameMenuItem: AXUIElement?
4944
+ for _ in 0..<20 {
4945
+ if let item = findRenameMenuItem(application) {
4946
+ renameMenuItem = item
4947
+ break
4948
+ }
4949
+ usleep(50_000)
4950
+ }
4951
+ guard let renameMenuItem else {
4952
+ fatalError("FINAL_CUT_NATIVE_RENAME_MENU_UNAVAILABLE: Final Cut did not expose Rename Clip")
4953
+ }
4954
+ guard AXUIElementPerformAction(renameMenuItem, kAXPressAction as CFString) == .success else {
4955
+ fatalError("FINAL_CUT_NATIVE_RENAME_MENU_FAILED: Final Cut did not activate Rename Clip")
4956
+ }
4957
+ usleep(250_000)
4958
+
4959
+ let units: [UniChar] = [${units}]
4960
+ if !units.isEmpty {
4961
+ let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true)!
4962
+ units.withUnsafeBufferPointer { buffer in
4963
+ keyDown.keyboardSetUnicodeString(stringLength: buffer.count, unicodeString: buffer.baseAddress)
4964
+ }
4965
+ keyDown.post(tap: .cghidEventTap)
4966
+ usleep(100_000)
4967
+ let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)!
4968
+ units.withUnsafeBufferPointer { buffer in
4969
+ keyUp.keyboardSetUnicodeString(stringLength: buffer.count, unicodeString: buffer.baseAddress)
4970
+ }
4971
+ keyUp.post(tap: .cghidEventTap)
4972
+ }
4973
+ usleep(150_000)
4974
+ let returnDown = CGEvent(keyboardEventSource: nil, virtualKey: 36, keyDown: true)!
4975
+ returnDown.post(tap: .cghidEventTap)
4976
+ usleep(50_000)
4977
+ let returnUp = CGEvent(keyboardEventSource: nil, virtualKey: 36, keyDown: false)!
4978
+ returnUp.post(tap: .cghidEventTap)
4979
+ usleep(300_000)
4980
+ `;
4981
+ }
4698
4982
  function bladeScript() {
4699
4983
  return `
4700
4984
  tell application "System Events"
@@ -5587,13 +5871,16 @@ end tell`;
5587
5871
  }
5588
5872
  function editScript(operation) {
5589
5873
  const action = operation.type === "rename-selected-clip"
5590
- ? `click menu item "Apply Custom Name" of menu "Modify" of menu bar 1\n delay 0.2\n set value of first text field of front window to ${appleScriptString(operation.name)}\n key code 36`
5874
+ ? `-- Apply Custom Name through the selected timeline clip's Info Inspector Name field\n set frontWindow to window "Final Cut Pro"\n set inspectorToggle to missing value\n try\n set inspectorToggle to first checkbox of toolbar 1 of frontWindow whose description is "Show or hide the Inspector"\n if (value of inspectorToggle as text) is "0" then\n perform action "AXPress" of inspectorToggle\n delay 0.3\n end if\n on error\n -- The Inspector may already be visible without exposing its toolbar toggle.\n end try\n set nameField to my findInspectorNameField(frontWindow, 0)\n if nameField is missing value then error "FINAL_CUT_NATIVE_SELECTION_REQUIRED: Final Cut Inspector Name field was not exposed"\n set value of attribute "AXValue" of nameField to ${appleScriptString(operation.name)}\n key code 36`
5591
5875
  : operation.type === "trim-selected-clip-to-playhead"
5592
5876
  ? `click menu item "Trim ${operation.edge === "start" ? "Start" : "End"}" of menu "Trim" of menu bar 1`
5593
5877
  : operation.type === "set-selected-clip-gain"
5594
5878
  ? `click menu item "Adjust Volume" of menu "Modify" of menu bar 1\n delay 0.2\n set value of first text field of front window to ${appleScriptString(`${operation.gainDb}`)}\n key code 36`
5595
5879
  : `click menu item "Add Marker" of menu 1 of menu item "Markers" of menu "Mark" of menu bar 1`;
5596
- return `
5880
+ const helper = operation.type === "rename-selected-clip"
5881
+ ? `using terms from application "System Events"\n on findInspectorNameField(containerItem, depth)\n if depth > 10 then return missing value\n try\n if (role of containerItem as text) is "AXScrollArea" then\n if (description of containerItem as text) is "metadata inspector" then\n repeat with childRef in UI elements of containerItem\n set child to contents of childRef\n try\n if (role of child as text) is "AXTextField" and (description of child as text) is "name" then\n return child\n end if\n on error\n -- Ignore inaccessible inspector fields.\n end try\n end repeat\n return missing value\n end if\n end if\n on error\n -- Ignore inaccessible inspector containers.\n end try\n try\n repeat with candidateRef in UI elements of containerItem\n set candidate to contents of candidateRef\n set candidateRole to ""\n set candidateDescription to ""\n try\n set candidateRole to role of candidate as text\n set candidateDescription to description of candidate as text\n on error\n -- Ignore inaccessible nodes and continue the bounded search.\n end try\n if candidateRole is "AXScrollArea" and candidateDescription is "metadata inspector" then\n set foundItem to my findInspectorNameField(candidate, depth + 1)\n if foundItem is not missing value then return foundItem\n else if candidateRole is "AXGroup" or candidateRole is "AXSplitGroup" or candidateRole is "AXWindow" then\n set foundItem to my findInspectorNameField(candidate, depth + 1)\n if foundItem is not missing value then return foundItem\n end if\n end repeat\n on error\n -- Ignore inaccessible containers and continue the bounded search.\n end try\n return missing value\n end findInspectorNameField\nend using terms from\n`
5882
+ : "";
5883
+ return `${helper}
5597
5884
  tell application "System Events"
5598
5885
  tell process "Final Cut Pro"
5599
5886
  ${requireFrontmostAppleScript()}
@@ -5611,7 +5898,11 @@ tell application "System Events"
5611
5898
  end tell`;
5612
5899
  }
5613
5900
  function parseContext(output) {
5614
- const [frontState, frontWindow, selectedCountText, selectedName, selectedRole, undoState, bladeState, focusedName, focusedRole, focusedDescription, timelineWindowState, timelineFocusedState, focusTargetState, focusAttemptsState, framekitWindowState, framekitMinimizedState, focusedWindowName, overlayBlockedState, undoCommandState, targetIdentity] = output.split(String.fromCharCode(31));
5901
+ const [frontState, frontWindow, selectedCountText, rawSelectedName, selectedRole, undoState, bladeState, focusedName, focusedRole, focusedDescription, timelineWindowState, timelineFocusedState, focusTargetState, focusAttemptsState, framekitWindowState, framekitMinimizedState, focusedWindowName, overlayBlockedState, undoCommandState, targetIdentity, occurrenceIndexState] = output.split(String.fromCharCode(31));
5902
+ const selectedName = rawSelectedName && selectedRole === "AXLayoutItem"
5903
+ ? rawSelectedName.replace(/^Video-Clip:/, "")
5904
+ : rawSelectedName;
5905
+ const occurrenceIndex = occurrenceIndexState ? Number(occurrenceIndexState) : undefined;
5615
5906
  const selectedCount = Number(selectedCountText ?? "0");
5616
5907
  const timelineWindowAvailable = timelineWindowState === undefined ? Boolean(frontWindow) : timelineWindowState === "true";
5617
5908
  const timelineFocused = timelineFocusedState === undefined
@@ -5625,7 +5916,7 @@ function parseContext(output) {
5625
5916
  const target = selectedCount < 0
5626
5917
  ? { kind: "unknown" }
5627
5918
  : selectedCount === 1
5628
- ? { kind: "selected-clip", ...(selectedName ? { name: selectedName } : {}), ...(selectedRole ? { role: selectedRole } : {}), ...(targetIdentity ? { identity: targetIdentity } : {}) }
5919
+ ? { kind: "selected-clip", ...(selectedName ? { name: selectedName } : {}), ...(selectedRole ? { role: selectedRole } : {}), ...(targetIdentity ? { identity: targetIdentity } : {}), ...(occurrenceIndex && Number.isInteger(occurrenceIndex) && occurrenceIndex > 0 ? { occurrenceIndex } : {}) }
5629
5920
  : selectedCount > 1
5630
5921
  ? { kind: "unknown" }
5631
5922
  : (focusedRole === "AXTextField" && (focusedDescription === "text field" || focusedDescription === "Title")