@morshoto/framekit 0.1.5 → 0.1.10

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 (40) hide show
  1. package/bin/framekit.mjs +2 -1
  2. package/dist-package/adapters/final-cut/typescript/src/assets.js +223 -15
  3. package/dist-package/adapters/final-cut/typescript/src/background-export.js +384 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +588 -0
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +20 -5
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +33 -7
  7. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +805 -51
  8. package/dist-package/adapters/final-cut/typescript/src/index.js +5 -0
  9. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +390 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +6 -3
  11. package/dist-package/adapters/final-cut/typescript/src/media.js +151 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native-session.js +412 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native.js +2271 -424
  14. package/dist-package/adapters/final-cut/typescript/src/publisher.js +225 -32
  15. package/dist-package/adapters/final-cut/typescript/src/session.js +145 -17
  16. package/dist-package/apps/mcp-server/src/main.js +73 -17
  17. package/dist-package/apps/mcp-server/src/routing.js +242 -39
  18. package/dist-package/apps/mcp-server/src/server.js +677 -89
  19. package/dist-package/apps/mcp-server/src/version.js +109 -1
  20. package/dist-package/packages/runtime/src/application/media-analysis-service.js +3 -4
  21. package/dist-package/packages/runtime/src/application/project-service.js +46 -7
  22. package/dist-package/packages/runtime/src/audio/dialogue-normalization.js +9 -0
  23. package/dist-package/packages/runtime/src/capabilities.js +62 -9
  24. package/dist-package/packages/runtime/src/context/project-catalog.js +159 -0
  25. package/dist-package/packages/runtime/src/domain/capabilities.js +33 -0
  26. package/dist-package/packages/runtime/src/domain/context.js +14 -1
  27. package/dist-package/packages/runtime/src/domain/editing.js +27 -1
  28. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  29. package/dist-package/packages/runtime/src/domain/skills.js +2 -0
  30. package/dist-package/packages/runtime/src/domain/timeline-target.js +217 -0
  31. package/dist-package/packages/runtime/src/editing/edit-service.js +57 -1
  32. package/dist-package/packages/runtime/src/editing/intent.js +178 -2
  33. package/dist-package/packages/runtime/src/index.js +1 -0
  34. package/dist-package/packages/runtime/src/runtime.js +2 -2
  35. package/dist-package/packages/runtime/src/skills/builtin.js +314 -39
  36. package/dist-package/packages/runtime/src/skills/requirements.js +1 -0
  37. package/dist-package/packages/runtime/src/skills/runtime.js +33 -8
  38. package/dist-package/packages/runtime/src/verification/verification.js +81 -4
  39. package/dist-package/packages/testkit/src/in-memory-editor.js +130 -4
  40. package/package.json +12 -2
@@ -1,8 +1,11 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { createHash } from "node:crypto";
2
3
  import { execFile as execFileCallback } from "node:child_process";
3
- import { access, constants, stat } from "node:fs/promises";
4
+ import { access, constants, readdir, stat } from "node:fs/promises";
5
+ import { homedir } from "node:os";
4
6
  import { basename, dirname, extname, resolve } from "node:path";
5
7
  import { promisify } from "node:util";
8
+ import { assertValidTimelineTarget } from "../../../../packages/runtime/src/index.js";
6
9
  const execFile = promisify(execFileCallback);
7
10
  class NativeFinalCutPreflightError extends Error {
8
11
  code;
@@ -14,8 +17,44 @@ class NativeFinalCutPreflightError extends Error {
14
17
  this.name = "NativeFinalCutPreflightError";
15
18
  }
16
19
  }
20
+ export class NativeFinalCutMediaImportError extends Error {
21
+ code;
22
+ details;
23
+ constructor(code, message, details) {
24
+ const diagnostics = details.diagnostics ? `; diagnostics=${details.diagnostics}` : "";
25
+ super(`${code}: ${message}; stage=${details.stage}; elapsedMs=${details.elapsedMs}; stageElapsedMs=${details.stageElapsedMs}; partialImportPossible=${details.partialImportPossible}${diagnostics}`);
26
+ this.code = code;
27
+ this.details = details;
28
+ this.name = "NativeFinalCutMediaImportError";
29
+ }
30
+ }
31
+ export function serializeNativeFinalCutMediaImportError(error) {
32
+ if (!(error instanceof NativeFinalCutMediaImportError))
33
+ return undefined;
34
+ return {
35
+ code: error.code,
36
+ message: error.message,
37
+ details: error.details,
38
+ };
39
+ }
40
+ export const NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE = "FINAL_CUT_NATIVE_MEDIA_DIRECTORY_INPUT";
41
+ export class NativeFinalCutMediaImportDirectoryError extends Error {
42
+ directoryPath;
43
+ code = NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE;
44
+ guidance = {
45
+ previewTool: "editor.native.media.directory.preview",
46
+ executeTool: "editor.native.media.directory.execute",
47
+ };
48
+ constructor(directoryPath) {
49
+ super(`${NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE}: ${directoryPath} is a directory; editor.native.media.import accepts one readable local media file. Use editor.native.media.directory.preview followed by editor.native.media.directory.execute with confirm=true to enumerate and batch import the directory`);
50
+ this.directoryPath = directoryPath;
51
+ this.name = "NativeFinalCutMediaImportDirectoryError";
52
+ }
53
+ }
54
+ export const SUPPORTED_VIDEO_EXTENSIONS = Object.freeze([".m4v", ".mov", ".mp4"]);
17
55
  export class FinalCutNativeAutomationAdapter {
18
56
  enabled;
57
+ titleDiscoveryAvailable;
19
58
  executor;
20
59
  canDriveNativeMouse;
21
60
  liveState;
@@ -28,6 +67,7 @@ export class FinalCutNativeAutomationAdapter {
28
67
  mediaImportTimeoutMs;
29
68
  mediaImportDiscoveryTimeoutMs;
30
69
  mediaImportPollMs;
70
+ requestContext = new AsyncLocalStorage();
31
71
  nativeUiDepth = 0;
32
72
  operations = new Map();
33
73
  latestOperationId;
@@ -36,13 +76,17 @@ export class FinalCutNativeAutomationAdapter {
36
76
  stableMediaHandles = new Map();
37
77
  occurrenceHandles = new Map();
38
78
  ambiguousMediaHandles = new Set();
79
+ mediaImportDirectoryPreviews = new Map();
39
80
  bladePreviews = new Map();
81
+ maskPreviews = new Map();
40
82
  rangePreviews = new Map();
41
83
  mediaInsertionPreviews = new Map();
42
84
  titlePreviews = new Map();
85
+ pictureInPicturePreviews = new Map();
43
86
  transitionPreviews = new Map();
44
87
  constructor(options = {}) {
45
88
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
89
+ this.titleDiscoveryAvailable = this.enabled;
46
90
  this.executor = options.executor ?? runAppleScript;
47
91
  this.canDriveNativeMouse = options.executor === undefined;
48
92
  this.liveState = options.liveState;
@@ -71,25 +115,33 @@ export class FinalCutNativeAutomationAdapter {
71
115
  mediaAppend: this.enabled,
72
116
  mediaInsert: this.enabled,
73
117
  titlePlacement: this.enabled,
118
+ titleDiscovery: this.titleDiscoveryAvailable,
119
+ pictureInPicture: this.enabled,
74
120
  transitionDiscovery: this.enabled,
75
121
  transitionPlacement: this.enabled,
122
+ masking: this.enabled,
76
123
  timelineFocus: this.enabled,
77
124
  requiresAccessibility: true,
78
125
  requiresFinalCutFrontmost: true,
79
126
  };
80
127
  }
81
- async inspect() {
82
- return this.withNativeUi(() => this.inspectNative());
128
+ async inspect(options = {}) {
129
+ return this.requestContext.run(options, () => this.inspectNative());
83
130
  }
84
- async focusTimeline() {
85
- return this.withNativeUi(() => this.focusTimelineNative());
131
+ async focusTimeline(options = {}) {
132
+ return this.withNativeUi(() => this.focusTimelineNative(), options.signal);
86
133
  }
87
134
  async inspectNative() {
88
135
  if (!this.enabled) {
89
136
  return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
90
137
  }
91
138
  try {
92
- return await this.attachLiveState(await this.ensureTimelineReady());
139
+ const deadline = this.now() + this.nativePreflightTimeoutMs;
140
+ const context = await this.inspectRawNative(deadline, passiveTimelinePreflightScript());
141
+ if (shouldRetryPassiveInspection(context) && this.now() < deadline) {
142
+ return await this.inspectRawNative(deadline, passiveTimelinePreflightScript());
143
+ }
144
+ return context;
93
145
  }
94
146
  catch (error) {
95
147
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
@@ -106,9 +158,9 @@ export class FinalCutNativeAutomationAdapter {
106
158
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
107
159
  }
108
160
  }
109
- async inspectRawNative(deadline) {
161
+ async inspectRawNative(deadline = this.now() + this.nativePreflightTimeoutMs, script = inspectScript()) {
110
162
  try {
111
- return await this.attachLiveState(parseContext(await this.executeNativeScript(inspectScript(), deadline)));
163
+ return await this.attachLiveState(parseContext(await this.executeNativeScript(script, deadline, "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT")));
112
164
  }
113
165
  catch (error) {
114
166
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error));
@@ -144,8 +196,8 @@ export class FinalCutNativeAutomationAdapter {
144
196
  this.operations.set(operationId, record);
145
197
  this.latestOperationId = operationId;
146
198
  }
147
- async edit(operation) {
148
- return this.withNativeUi(() => this.editNative(operation));
199
+ async edit(operation, options = {}) {
200
+ return this.withNativeUi(() => this.editNative(operation), options.signal);
149
201
  }
150
202
  async editNative(operation) {
151
203
  this.assertEnabled();
@@ -169,8 +221,8 @@ export class FinalCutNativeAutomationAdapter {
169
221
  this.rememberOperation(operationId, { kind: "selection", before, after, beforeLive, afterLive, undoCommand: after.undoCommand });
170
222
  return { operationId, operation, command, before, after, verification, undoAvailable: after.undoAvailable, ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}) };
171
223
  }
172
- async undo(operationId) {
173
- return this.withNativeUi(() => this.undoNative(operationId));
224
+ async undo(operationId, options = {}) {
225
+ return this.withNativeUi(() => this.undoNative(operationId), options.signal);
174
226
  }
175
227
  async undoNative(operationId) {
176
228
  this.assertEnabled();
@@ -209,99 +261,217 @@ export class FinalCutNativeAutomationAdapter {
209
261
  this.latestOperationId = undefined;
210
262
  return { operationId, undone: true, context: after, verification };
211
263
  }
212
- async importMedia(sourcePath) {
213
- return this.withNativeUi(() => this.importMediaNative(sourcePath));
264
+ async importMedia(sourcePath, options = {}) {
265
+ return this.withNativeUi(() => this.importMediaNative(sourcePath), options.signal);
266
+ }
267
+ async previewImportMediaDirectory(directoryPath, options = {}) {
268
+ return this.requestContext.run(options, () => this.previewImportMediaDirectoryNative(directoryPath));
269
+ }
270
+ async previewImportMediaDirectoryNative(directoryPath) {
271
+ this.assertEnabled();
272
+ const trimmedPath = directoryPath.trim();
273
+ if (!trimmedPath)
274
+ throw new Error("INVALID_OPERATION: local media directory path cannot be empty");
275
+ const normalizedPath = resolveLocalPath(trimmedPath);
276
+ const snapshot = await snapshotSupportedVideoFiles(normalizedPath);
277
+ const expiresAt = this.now() + 30_000;
278
+ const previewToken = opaqueHandle("media-directory-preview");
279
+ this.mediaImportDirectoryPreviews.set(previewToken, {
280
+ directoryPath: normalizedPath,
281
+ files: snapshot.files,
282
+ fileIdentities: snapshot.fileIdentities,
283
+ expiresAt,
284
+ });
285
+ return {
286
+ previewToken,
287
+ directoryPath: normalizedPath,
288
+ files: structuredClone(snapshot.files),
289
+ command: "Import all previewed video files",
290
+ expiresAt: new Date(expiresAt).toISOString(),
291
+ };
292
+ }
293
+ async executeImportMediaDirectory(previewToken, confirm, options = {}) {
294
+ return this.withNativeUi(() => this.executeImportMediaDirectoryNative(previewToken, confirm), options.signal);
214
295
  }
215
296
  async importMediaNative(sourcePath) {
216
297
  this.assertEnabled();
217
- const normalizedPath = resolve(sourcePath.trim());
298
+ const importStartedAt = this.now();
299
+ let stage = "pre-import-browser-discovery";
300
+ let stageStartedAt = importStartedAt;
301
+ let partialImportPossible = false;
302
+ const beginStage = (nextStage) => {
303
+ stage = nextStage;
304
+ stageStartedAt = this.now();
305
+ };
306
+ const fail = (code, message, partialImportPossible, diagnostics) => {
307
+ throw new NativeFinalCutMediaImportError(code, message, {
308
+ stage,
309
+ elapsedMs: Math.max(0, this.now() - importStartedAt),
310
+ stageElapsedMs: Math.max(0, this.now() - stageStartedAt),
311
+ partialImportPossible,
312
+ ...(diagnostics ? { diagnostics } : {}),
313
+ });
314
+ };
315
+ const normalizedPath = resolveLocalPath(sourcePath);
218
316
  const name = basename(normalizedPath);
219
- if (!name)
317
+ if (!sourcePath.trim())
220
318
  throw new Error("INVALID_OPERATION: local media path cannot be empty");
221
319
  try {
222
320
  const details = await stat(normalizedPath);
223
321
  await access(normalizedPath, constants.R_OK);
322
+ if (details.isDirectory())
323
+ throw new NativeFinalCutMediaImportDirectoryError(normalizedPath);
224
324
  if (!details.isFile())
225
325
  throw new Error("path is not a file");
226
326
  }
227
327
  catch (error) {
328
+ if (error instanceof NativeFinalCutMediaImportDirectoryError)
329
+ throw error;
228
330
  throw new Error(`FINAL_CUT_NATIVE_MEDIA_PATH_UNAVAILABLE: ${normalizedPath} is not a readable local media file (${String(error)})`);
229
331
  }
230
- const beforeDiscoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
231
- await this.ensureBrowserReady(beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
232
- const beforeMatches = await this.searchMediaNative(name, beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
233
- const beforeIdentities = new Set(beforeMatches
234
- .filter((match) => match.name.toLowerCase() === name.toLowerCase())
235
- .map((match) => browserMediaIdentity(match))
236
- .filter((identity) => Boolean(identity)));
237
- const hasIndistinguishablePreExistingMatch = beforeMatches.some((match) => match.name.toLowerCase() === name.toLowerCase() && !browserMediaIdentity(match));
238
- if (hasIndistinguishablePreExistingMatch) {
239
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for pre-existing ${name}`);
240
- }
241
332
  try {
242
- await this.executeNativeScript(importMediaScript(dirname(normalizedPath), name), this.now() + this.mediaImportTimeoutMs);
243
- }
244
- catch (error) {
245
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
246
- }
247
- const discoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
248
- let sawPreExistingMatch = false;
249
- while (this.now() <= discoveryDeadline) {
250
- let matches;
333
+ const beforeDiscoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
334
+ await this.ensureBrowserReady(beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
335
+ const beforeMatches = await this.searchMediaNative(name, beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
336
+ const beforeIdentities = new Set(beforeMatches
337
+ .filter((match) => match.name.toLowerCase() === name.toLowerCase())
338
+ .map((match) => browserMediaIdentity(match))
339
+ .filter((identity) => Boolean(identity)));
340
+ const hasIndistinguishablePreExistingMatch = beforeMatches.some((match) => match.name.toLowerCase() === name.toLowerCase() && !browserMediaIdentity(match));
341
+ if (hasIndistinguishablePreExistingMatch) {
342
+ fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE", `Final Cut did not expose an immutable Browser source identity for pre-existing ${name}`, false);
343
+ }
344
+ beginStage("native-import-ui");
345
+ partialImportPossible = true;
251
346
  try {
252
- matches = await this.searchMediaNative(name, discoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
347
+ await this.executeNativeScript(importMediaScript(dirname(normalizedPath), name), this.now() + this.mediaImportTimeoutMs);
253
348
  }
254
349
  catch (error) {
255
- if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT") {
256
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: Final Cut imported ${name}, but Browser Accessibility did not expose a stable media identity before the ${this.mediaImportDiscoveryTimeoutMs}ms discovery deadline`);
257
- }
258
- throw error;
259
- }
260
- const exactMatches = matches.filter((match) => match.name.toLowerCase() === name.toLowerCase());
261
- if (exactMatches.some((match) => !browserMediaIdentity(match))) {
262
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for ${name}`);
350
+ fail(nativeErrorCode(error), nativeErrorMessage(error), true);
263
351
  }
264
- const newMatches = exactMatches.filter((match) => {
265
- const identity = browserMediaIdentity(match);
266
- if (!identity)
267
- return false;
268
- if (beforeIdentities.has(identity)) {
269
- sawPreExistingMatch = true;
270
- return false;
352
+ beginStage("post-import-browser-discovery");
353
+ const discoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
354
+ let sawPreExistingMatch = false;
355
+ while (this.now() <= discoveryDeadline) {
356
+ let matches = [];
357
+ try {
358
+ matches = await this.searchMediaNative(name, discoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
271
359
  }
272
- return true;
273
- });
274
- if (newMatches.length > 1) {
275
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_AMBIGUOUS: Final Cut exposed multiple newly appearing Browser results for ${name}`);
360
+ catch (error) {
361
+ const code = nativeMediaImportErrorCode(error);
362
+ const diagnostics = code === "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT"
363
+ ? await this.readBrowserMediaDiagnostics(name)
364
+ : undefined;
365
+ fail(code, nativeErrorMessage(error), true, diagnostics);
366
+ }
367
+ const exactMatches = matches.filter((match) => match.name.toLowerCase() === name.toLowerCase());
368
+ if (exactMatches.some((match) => !browserMediaIdentity(match))) {
369
+ fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE", `Final Cut did not expose an immutable Browser source identity for ${name}`, true);
370
+ }
371
+ const newMatches = exactMatches.filter((match) => {
372
+ const identity = browserMediaIdentity(match);
373
+ if (!identity)
374
+ return false;
375
+ if (beforeIdentities.has(identity)) {
376
+ sawPreExistingMatch = true;
377
+ return false;
378
+ }
379
+ return true;
380
+ });
381
+ if (newMatches.length > 1) {
382
+ fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_AMBIGUOUS", `Final Cut exposed multiple newly appearing Browser results for ${name}`, true);
383
+ }
384
+ const match = newMatches[0];
385
+ if (match) {
386
+ const identity = browserMediaIdentity(match);
387
+ if (!identity) {
388
+ fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE", `Final Cut did not expose an immutable Browser source identity for ${name}`, true);
389
+ throw new Error("unreachable");
390
+ }
391
+ const mediaHandle = this.stableMediaHandle(identity);
392
+ const stableMatch = { ...match, handle: mediaHandle };
393
+ this.stableMediaHandles.set(identity, mediaHandle);
394
+ this.mediaHandles.set(mediaHandle, stableMatch);
395
+ return {
396
+ mediaHandle,
397
+ sourcePath: normalizedPath,
398
+ sourceIdentity: identity,
399
+ name,
400
+ kind: mediaKind(normalizedPath),
401
+ verification: {
402
+ verified: true,
403
+ stage: "post-import-browser-discovery",
404
+ detail: "Final Cut exposed one newly imported Browser asset with immutable source identity",
405
+ },
406
+ };
407
+ }
408
+ if (this.now() >= discoveryDeadline)
409
+ break;
410
+ await this.sleep(Math.min(this.mediaImportPollMs, discoveryDeadline - this.now()));
276
411
  }
277
- const match = newMatches[0];
278
- if (match) {
279
- const identity = browserMediaIdentity(match);
280
- if (!identity)
281
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for ${name}`);
282
- const mediaHandle = this.stableMediaHandle(identity);
283
- const stableMatch = { ...match, handle: mediaHandle };
284
- this.stableMediaHandles.set(identity, mediaHandle);
285
- this.mediaHandles.set(mediaHandle, stableMatch);
286
- return {
287
- mediaHandle,
288
- sourcePath: normalizedPath,
289
- name,
290
- kind: mediaKind(normalizedPath),
291
- };
412
+ const diagnostics = await this.readBrowserMediaDiagnostics(name);
413
+ if (sawPreExistingMatch) {
414
+ fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_PRE_EXISTING", `Final Cut exposed only pre-existing Browser results for ${name}`, true, diagnostics);
292
415
  }
293
- if (this.now() >= discoveryDeadline)
294
- break;
295
- await this.sleep(Math.min(this.mediaImportPollMs, discoveryDeadline - this.now()));
416
+ fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT", `Final Cut imported ${name}, but Browser Accessibility did not expose a stable media identity before the ${this.mediaImportDiscoveryTimeoutMs}ms discovery deadline`, true, diagnostics);
296
417
  }
297
- if (sawPreExistingMatch) {
298
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_PRE_EXISTING: Final Cut exposed only pre-existing Browser results for ${name}`);
418
+ catch (error) {
419
+ if (error instanceof NativeFinalCutMediaImportError)
420
+ throw error;
421
+ fail(nativeMediaImportErrorCode(error), nativeErrorMessage(error), partialImportPossible);
422
+ }
423
+ return fail("FINAL_CUT_NATIVE_AUTOMATION_FAILED", "native media import ended without a result", partialImportPossible);
424
+ }
425
+ async executeImportMediaDirectoryNative(previewToken, confirm) {
426
+ this.assertEnabled();
427
+ if (!confirm)
428
+ throw new Error("FINAL_CUT_NATIVE_CONFIRMATION_REQUIRED: batch media import requires confirm=true");
429
+ const preview = this.mediaImportDirectoryPreviews.get(previewToken);
430
+ if (!preview)
431
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown media directory preview");
432
+ this.mediaImportDirectoryPreviews.delete(previewToken);
433
+ if (this.now() > preview.expiresAt)
434
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media directory preview has expired");
435
+ await assertMediaImportDirectoryPreviewFresh(preview);
436
+ const results = [];
437
+ for (const file of preview.files) {
438
+ try {
439
+ const media = await this.importMedia(file.sourcePath);
440
+ results.push({
441
+ sourcePath: file.sourcePath,
442
+ name: file.name,
443
+ status: "imported",
444
+ media,
445
+ });
446
+ }
447
+ catch (error) {
448
+ const serializedError = serializeNativeFinalCutMediaImportError(error);
449
+ results.push({
450
+ sourcePath: file.sourcePath,
451
+ name: file.name,
452
+ status: "failed",
453
+ error: serializedError ?? {
454
+ code: nativeErrorCode(error),
455
+ message: String(error),
456
+ },
457
+ });
458
+ }
299
459
  }
300
- const diagnostics = await this.readBrowserMediaDiagnostics(name);
301
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: Final Cut imported ${name}, but Browser Accessibility did not expose a stable media identity${diagnostics ? `; diagnostics=${diagnostics}` : ""}`);
460
+ const importedCount = results.filter((result) => result.status === "imported").length;
461
+ const failedCount = results.length - importedCount;
462
+ return {
463
+ previewToken,
464
+ directoryPath: preview.directoryPath,
465
+ files: structuredClone(preview.files),
466
+ results,
467
+ importedCount,
468
+ failedCount,
469
+ partial: importedCount > 0 && failedCount > 0,
470
+ status: failedCount === 0 ? "completed" : importedCount > 0 ? "partial" : "failed",
471
+ };
302
472
  }
303
- async searchMedia(query) {
304
- return this.withNativeUi(() => this.searchMediaNative(query));
473
+ async searchMedia(query, options = {}) {
474
+ return this.withNativeUi(() => this.searchMediaNative(query), options.signal);
305
475
  }
306
476
  async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
307
477
  this.assertEnabled();
@@ -311,7 +481,13 @@ export class FinalCutNativeAutomationAdapter {
311
481
  if (!context.frontmost)
312
482
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
313
483
  try {
314
- const rawMatches = parseMediaMatches(await this.executeNativeScript(searchMediaScript(query), deadline, timeoutCode));
484
+ const searchDeadline = deadline ?? this.now() + this.mediaImportDiscoveryTimeoutMs;
485
+ const output = await this.executeNativeScript(searchMediaScript(query), searchDeadline, timeoutCode);
486
+ const explicitFailure = output.trim();
487
+ if (explicitFailure.startsWith("FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE")) {
488
+ throw new Error(explicitFailure);
489
+ }
490
+ const rawMatches = parseMediaMatches(output);
315
491
  const normalizedQuery = query.toLocaleLowerCase();
316
492
  if (rawMatches.some((match) => !browserMediaIdentity(match) && match.name.toLocaleLowerCase().includes(normalizedQuery))) {
317
493
  const diagnostics = await this.readBrowserMediaDiagnostics(query);
@@ -345,6 +521,8 @@ export class FinalCutNativeAutomationAdapter {
345
521
  return matches;
346
522
  }
347
523
  catch (error) {
524
+ if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE")
525
+ throw error;
348
526
  if (deadline !== undefined && nativeErrorCode(error) === timeoutCode)
349
527
  throw error;
350
528
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
@@ -359,8 +537,8 @@ export class FinalCutNativeAutomationAdapter {
359
537
  return "";
360
538
  }
361
539
  }
362
- async previewAppendSelectedMedia() {
363
- return this.withNativeUi(() => this.previewSelectedMediaInsertionNative());
540
+ async previewAppendSelectedMedia(options = {}) {
541
+ return this.withNativeUi(() => this.previewSelectedMediaInsertionNative(), options.signal);
364
542
  }
365
543
  async previewSelectedMediaInsertionNative() {
366
544
  this.assertEnabled();
@@ -377,7 +555,7 @@ export class FinalCutNativeAutomationAdapter {
377
555
  if (!context.frontmost)
378
556
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
379
557
  try {
380
- const matches = parseMediaMatches(await this.executor(selectedBrowserMediaScript()));
558
+ const matches = parseMediaMatches(await this.executeNativeScript(selectedBrowserMediaScript()));
381
559
  if (matches.length === 0)
382
560
  throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: no selected Browser media was exposed by Accessibility");
383
561
  if (matches.length > 1)
@@ -393,8 +571,8 @@ export class FinalCutNativeAutomationAdapter {
393
571
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
394
572
  }
395
573
  }
396
- async selectMedia(handle) {
397
- return this.withNativeUi(() => this.selectMediaNative(handle));
574
+ async selectMedia(handle, options = {}) {
575
+ return this.withNativeUi(() => this.selectMediaNative(handle), options.signal);
398
576
  }
399
577
  async selectMediaNative(handle) {
400
578
  this.assertEnabled();
@@ -405,7 +583,7 @@ export class FinalCutNativeAutomationAdapter {
405
583
  if (!before.frontmost)
406
584
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
407
585
  try {
408
- await this.executor(selectMediaScript(match));
586
+ await this.executeNativeScript(selectMediaScript(match));
409
587
  }
410
588
  catch (error) {
411
589
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
@@ -417,11 +595,11 @@ export class FinalCutNativeAutomationAdapter {
417
595
  target: { kind: "browser-media", name: match.name, ...(match.role ? { role: match.role } : {}) },
418
596
  };
419
597
  }
420
- async locateOccurrence(mediaHandle) {
421
- return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle));
598
+ async locateOccurrence(mediaHandle, options = {}) {
599
+ return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle), options.signal);
422
600
  }
423
- async targetMedia(query) {
424
- return this.withNativeUi(() => this.targetMediaNative(query));
601
+ async targetMedia(query, options = {}) {
602
+ return this.withNativeUi(() => this.targetMediaNative(query), options.signal);
425
603
  }
426
604
  async targetMediaNative(query) {
427
605
  this.assertEnabled();
@@ -446,11 +624,38 @@ export class FinalCutNativeAutomationAdapter {
446
624
  if (!live?.playheadTime) {
447
625
  throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_UNAVAILABLE: deterministic targeting requires live playhead state");
448
626
  }
627
+ const occurrence = located.occurrences[0];
628
+ const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
629
+ if (!occurrenceIdentity) {
630
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_IDENTITY_UNAVAILABLE: timeline occurrence has no stable identity");
631
+ }
632
+ if (!occurrence.start || !occurrence.duration) {
633
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: timeline occurrence has no rational coordinates");
634
+ }
635
+ if (!live.project?.id || !live.sequence?.id) {
636
+ throw new Error("FINAL_CUT_NATIVE_STABLE_TARGET_UNAVAILABLE: live project and sequence identities are required");
637
+ }
638
+ const target = {
639
+ projectId: live.project.id,
640
+ sequenceId: live.sequence.id,
641
+ revision: structuredClone(live.revision),
642
+ timelineStartTime: structuredClone(live.sequence.startTime),
643
+ frameDuration: structuredClone(live.sequence.frameDuration),
644
+ mediaId: occurrence.sourceIdentity ?? media.sourceIdentity,
645
+ occurrence: {
646
+ id: occurrenceIdentity,
647
+ mediaId: occurrence.sourceIdentity ?? media.sourceIdentity,
648
+ startTime: parseRationalString(occurrence.start, "occurrence start"),
649
+ durationTime: parseRationalString(occurrence.duration, "occurrence duration"),
650
+ },
651
+ };
652
+ assertValidTimelineTarget(target);
449
653
  return {
450
654
  query,
451
655
  status: "unique",
452
656
  media,
453
- occurrence: located.occurrences[0],
657
+ occurrence,
658
+ target,
454
659
  selected: true,
455
660
  playheadTime: `${live.playheadTime.value}/${live.playheadTime.timescale}`,
456
661
  };
@@ -470,7 +675,7 @@ export class FinalCutNativeAutomationAdapter {
470
675
  let occurrenceOutput = "";
471
676
  for (let attempt = 0; attempt < 2; attempt += 1) {
472
677
  try {
473
- occurrenceOutput = await this.executor(locateOccurrenceScript(match, scanAll));
678
+ occurrenceOutput = await this.executeNativeScript(locateOccurrenceScript(match, scanAll));
474
679
  break;
475
680
  }
476
681
  catch (error) {
@@ -486,8 +691,13 @@ export class FinalCutNativeAutomationAdapter {
486
691
  if (timelineOffset === undefined) {
487
692
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
488
693
  }
489
- await selectTimelineOccurrence(this.executor, timelineOffset);
694
+ await this.selectTimelineOccurrence(timelineOffset);
490
695
  await this.ensureOccurrenceRange(occurrences[0]);
696
+ const selectedContext = await this.inspectRawNative();
697
+ if (selectedContext.target.kind !== "selected-clip" || !selectedContext.target.identity) {
698
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_IDENTITY_UNAVAILABLE: selected timeline occurrence has no stable native identity");
699
+ }
700
+ occurrences[0].nativeIdentity = selectedContext.target.identity;
491
701
  }
492
702
  const live = this.liveState ? await this.liveState().catch(() => undefined) : liveBefore;
493
703
  for (const occurrence of occurrences) {
@@ -514,8 +724,8 @@ export class FinalCutNativeAutomationAdapter {
514
724
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
515
725
  }
516
726
  }
517
- async previewBlade(occurrenceHandle) {
518
- return this.withNativeUi(() => this.previewBladeNative(occurrenceHandle));
727
+ async previewBlade(occurrenceHandle, options = {}) {
728
+ return this.withNativeUi(() => this.previewBladeNative(occurrenceHandle), options.signal);
519
729
  }
520
730
  async previewBladeNative(occurrenceHandle) {
521
731
  this.assertEnabled();
@@ -547,8 +757,146 @@ export class FinalCutNativeAutomationAdapter {
547
757
  expiresAt: new Date(expiresAtMs).toISOString(),
548
758
  };
549
759
  }
550
- async executeBlade(previewToken) {
551
- return this.withNativeUi(() => this.executeBladeNative(previewToken));
760
+ async executeBlade(previewToken, options = {}) {
761
+ return this.withNativeUi(() => this.executeBladeNative(previewToken), options.signal);
762
+ }
763
+ async previewMask(request, options = {}) {
764
+ return this.withNativeUi(() => this.previewMaskNative(request), options.signal);
765
+ }
766
+ async executeMask(previewToken, options = {}) {
767
+ return this.withNativeUi(() => this.executeMaskNative(previewToken), options.signal);
768
+ }
769
+ async previewMaskNative(request) {
770
+ this.assertEnabled();
771
+ assertNativeMaskConfiguration(request.mask);
772
+ const occurrence = this.occurrenceHandles.get(request.occurrenceHandle);
773
+ if (!occurrence)
774
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown occurrence handle ${request.occurrenceHandle}`);
775
+ if (this.ambiguousMediaHandles.has(occurrence.mediaHandle)) {
776
+ throw new Error("FINAL_CUT_NATIVE_AMBIGUOUS_OCCURRENCE: masking requires exactly one timeline occurrence");
777
+ }
778
+ const context = await this.requireTimelineContext();
779
+ if (!context.frontmost)
780
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
781
+ assertNativeMaskTarget(context, occurrence);
782
+ await this.validateOccurrenceBinding(occurrence);
783
+ const live = await this.requireLiveState();
784
+ const expiresAt = this.now() + 30_000;
785
+ const previewToken = opaqueHandle("mask-preview");
786
+ const mask = structuredClone(request.mask);
787
+ this.maskPreviews.set(previewToken, {
788
+ occurrence: structuredClone(occurrence),
789
+ mask,
790
+ sequenceId: live.sequence?.id,
791
+ revision: live.revision.id,
792
+ expiresAt,
793
+ });
794
+ return {
795
+ previewToken,
796
+ occurrence: structuredClone(occurrence),
797
+ mask,
798
+ ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
799
+ revision: live.revision.id,
800
+ command: "Add native Draw Mask",
801
+ expiresAt: new Date(expiresAt).toISOString(),
802
+ };
803
+ }
804
+ async executeMaskNative(previewToken) {
805
+ this.assertEnabled();
806
+ const preview = this.maskPreviews.get(previewToken);
807
+ if (!preview)
808
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown native mask preview");
809
+ this.maskPreviews.delete(previewToken);
810
+ if (this.now() > preview.expiresAt)
811
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native mask preview has expired");
812
+ const before = await this.requireNativeWriteContext();
813
+ const beforeLive = await this.requireLiveState();
814
+ if (!before.frontmost)
815
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
816
+ if (before.target.kind !== "selected-clip")
817
+ throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one timeline occurrence");
818
+ assertNativeMaskTarget(before, preview.occurrence);
819
+ validateMaskPreviewBinding(preview, beforeLive);
820
+ await this.validateOccurrenceBinding(preview.occurrence);
821
+ let observedAfter;
822
+ let observedLive;
823
+ try {
824
+ const observedMask = parseNativeMaskReadback(await this.executeNativeScript(applyMaskScript(preview.mask)));
825
+ observedAfter = await this.requireTimelineContext();
826
+ observedLive = await this.waitForRevision(beforeLive.revision.id);
827
+ const verification = verifyNativeMask(preview, observedAfter, beforeLive, observedLive, observedMask);
828
+ if (!verification.verified) {
829
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
830
+ }
831
+ const operationId = opaqueHandle("native-mask");
832
+ const operation = {
833
+ kind: "masking",
834
+ before,
835
+ after: observedAfter,
836
+ beforeLive,
837
+ afterLive: observedLive,
838
+ undoCommand: observedAfter.undoCommand,
839
+ };
840
+ this.rememberOperation(operationId, operation);
841
+ return {
842
+ operationId,
843
+ previewToken,
844
+ occurrence: structuredClone(preview.occurrence),
845
+ mask: structuredClone(preview.mask),
846
+ observedMask,
847
+ before,
848
+ after: observedAfter,
849
+ beforeRevision: beforeLive.revision,
850
+ afterRevision: observedLive.revision,
851
+ verification,
852
+ undoAvailable: observedAfter.undoAvailable,
853
+ ...(observedAfter.undoCommand ? { undoCommand: observedAfter.undoCommand } : {}),
854
+ };
855
+ }
856
+ catch (error) {
857
+ const rollback = await this.rollbackFailedMask(before, beforeLive, previewToken, error, observedAfter, observedLive);
858
+ const failure = `${nativeErrorCode(error)}: ${String(error)}`;
859
+ if (rollback.rolledBack)
860
+ throw new Error(`${failure}; mask placement was rolled back`);
861
+ throw new Error(`${failure}; rollback unavailable: ${rollback.detail}`);
862
+ }
863
+ }
864
+ async rollbackFailedMask(before, beforeLive, previewToken, error, after, afterLive) {
865
+ const observedAfter = after ?? await this.inspectRawNative();
866
+ const observedLive = afterLive ?? await this.readLiveState();
867
+ if (!observedAfter.available || !observedAfter.undoAvailable || !observedAfter.undoCommand) {
868
+ return {
869
+ rolledBack: false,
870
+ detail: observedAfter.error?.message ?? "Final Cut did not expose a matching Undo command",
871
+ };
872
+ }
873
+ const revisionChanged = Boolean(observedLive && observedLive.revision.id !== beforeLive.revision.id);
874
+ const undoChanged = observedAfter.undoCommand !== before.undoCommand;
875
+ if (!revisionChanged && !undoChanged) {
876
+ return { rolledBack: false, detail: "Final Cut did not expose a changed revision or Undo command after mask placement" };
877
+ }
878
+ const operationId = opaqueHandle("native-mask-failed");
879
+ this.rememberOperation(operationId, {
880
+ kind: "masking",
881
+ before,
882
+ after: observedAfter,
883
+ beforeLive,
884
+ afterLive: observedLive,
885
+ undoCommand: observedAfter.undoCommand,
886
+ });
887
+ try {
888
+ const undoResult = await this.undo(operationId);
889
+ if (!undoResult.verification.verified) {
890
+ return { rolledBack: false, detail: undoResult.verification.detail };
891
+ }
892
+ }
893
+ catch (rollbackError) {
894
+ return {
895
+ rolledBack: false,
896
+ detail: `operationId=${operationId}; native rollback failed: ${String(rollbackError)}`,
897
+ };
898
+ }
899
+ return { rolledBack: true, detail: `preview=${previewToken}; original failure=${String(error)}` };
552
900
  }
553
901
  async executeBladeNative(previewToken) {
554
902
  this.assertEnabled();
@@ -558,7 +906,7 @@ export class FinalCutNativeAutomationAdapter {
558
906
  this.bladePreviews.delete(previewToken);
559
907
  if (this.now() > preview.expiresAt)
560
908
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: Blade preview has expired");
561
- const before = await this.requireTimelineContext();
909
+ const before = await this.requireNativeWriteContext();
562
910
  if (!before.frontmost)
563
911
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
564
912
  if (before.target.kind !== "selected-clip")
@@ -584,7 +932,7 @@ export class FinalCutNativeAutomationAdapter {
584
932
  if (!after.frontmost)
585
933
  throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut changed focus during Blade");
586
934
  const afterLive = await this.readLiveState();
587
- const resultingSegments = parseOccurrences(await this.executor(locateOccurrenceScript({ handle: preview.occurrence.mediaHandle, name: preview.occurrence.name }, true)), preview.occurrence.mediaHandle);
935
+ const resultingSegments = parseOccurrences(await this.executeNativeScript(locateOccurrenceScript({ handle: preview.occurrence.mediaHandle, name: preview.occurrence.name }, true)), preview.occurrence.mediaHandle);
588
936
  normalizeOccurrenceTimes(resultingSegments, afterLive?.sequence);
589
937
  if (resultingSegments.length < 2) {
590
938
  throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut did not expose two resulting timeline segments after Blade");
@@ -603,13 +951,13 @@ export class FinalCutNativeAutomationAdapter {
603
951
  ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
604
952
  };
605
953
  }
606
- async previewDeleteRange(range) {
607
- return this.withNativeUi(() => this.previewRangeNative("delete-range", range));
954
+ async previewDeleteRange(range, options = {}) {
955
+ return this.withNativeUi(() => this.previewRangeNative("delete-range", range), options.signal);
608
956
  }
609
- async executeDeleteRange(previewToken) {
610
- return this.withNativeUi(() => this.executeRangeNative(previewToken));
957
+ async executeDeleteRange(previewToken, options = {}) {
958
+ return this.withNativeUi(() => this.executeRangeNative(previewToken), options.signal);
611
959
  }
612
- async previewTrimToDuration(duration) {
960
+ async previewTrimToDuration(duration, options = {}) {
613
961
  return this.withNativeUi(async () => {
614
962
  this.assertEnabled();
615
963
  const live = await this.requireLiveState();
@@ -628,45 +976,89 @@ export class FinalCutNativeAutomationAdapter {
628
976
  }
629
977
  const range = { start: addRational(sequenceStart, duration), end: addRational(sequenceStart, currentDuration) };
630
978
  return this.createRangePreview("trim-to-duration", range, currentDuration, duration, live, duration);
631
- });
979
+ }, options.signal);
980
+ }
981
+ async executeTrimToDuration(previewToken, options = {}) {
982
+ return this.withNativeUi(() => this.executeRangeNative(previewToken, "trim-to-duration"), options.signal);
983
+ }
984
+ async previewAppendMedia(mediaHandle, options = {}) {
985
+ return this.withNativeUi(() => this.previewMediaInsertionNative("append", mediaHandle), options.signal);
632
986
  }
633
- async executeTrimToDuration(previewToken) {
634
- return this.withNativeUi(() => this.executeRangeNative(previewToken, "trim-to-duration"));
987
+ async executeAppendMedia(previewToken, options = {}) {
988
+ return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "handle"), options.signal);
635
989
  }
636
- async previewAppendMedia(mediaHandle) {
637
- return this.withNativeUi(() => this.previewMediaInsertionNative("append", mediaHandle));
990
+ async executeAppendSelectedMedia(previewToken, options = {}) {
991
+ return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "selected"), options.signal);
638
992
  }
639
- async executeAppendMedia(previewToken) {
640
- return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "handle"));
993
+ async previewInsertMedia(mediaHandle, options = {}) {
994
+ return this.withNativeUi(() => this.previewMediaInsertionNative("insert", mediaHandle), options.signal);
641
995
  }
642
- async executeAppendSelectedMedia(previewToken) {
643
- return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "selected"));
996
+ async executeInsertMedia(previewToken, options = {}) {
997
+ return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "insert"), options.signal);
644
998
  }
645
- async previewInsertMedia(mediaHandle) {
646
- return this.withNativeUi(() => this.previewMediaInsertionNative("insert", mediaHandle));
999
+ async previewTitleAdd(request, options = {}) {
1000
+ return this.withNativeUi(() => this.previewTitleAddNative(request), options.signal);
647
1001
  }
648
- async executeInsertMedia(previewToken) {
649
- return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "insert"));
1002
+ async executeTitleAdd(previewToken, options = {}) {
1003
+ return this.withNativeUi(() => this.executeTitleAddNative(previewToken), options.signal);
650
1004
  }
651
- async previewTitleAdd(request) {
652
- return this.withNativeUi(() => this.previewTitleAddNative(request));
1005
+ async searchTitles(query, options = {}) {
1006
+ return this.withNativeUi(() => this.searchTitlesNative(query), options.signal);
653
1007
  }
654
- async executeTitleAdd(previewToken) {
655
- return this.withNativeUi(() => this.executeTitleAddNative(previewToken));
1008
+ async previewPictureInPicture(request, options = {}) {
1009
+ return this.withNativeUi(() => this.previewPictureInPictureNative(request), options.signal);
656
1010
  }
657
- async searchTransitions(query) {
658
- return this.withNativeUi(() => this.searchTransitionsNative(query));
1011
+ async executePictureInPicture(previewToken, options = {}) {
1012
+ return this.withNativeUi(() => this.executePictureInPictureNative(previewToken), options.signal);
659
1013
  }
660
- async previewTransitionAdd(request) {
661
- return this.withNativeUi(() => this.previewTransitionAddNative(request));
1014
+ async searchTransitions(query, options = {}) {
1015
+ return this.withNativeUi(() => this.searchTransitionsNative(query), options.signal);
1016
+ }
1017
+ async previewTransitionAdd(request, options = {}) {
1018
+ return this.withNativeUi(() => this.previewTransitionAddNative(request), options.signal);
1019
+ }
1020
+ async executeTransitionAdd(previewToken, options = {}) {
1021
+ return this.withNativeUi(() => this.executeTransitionAddNative(previewToken), options.signal);
1022
+ }
1023
+ async searchTitlesNative(query) {
1024
+ this.assertEnabled();
1025
+ try {
1026
+ await this.ensureTitleBrowserReady();
1027
+ const normalizedQuery = query.trim();
1028
+ const identity = titleIdentityFromId(normalizedQuery);
1029
+ let lastError;
1030
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1031
+ try {
1032
+ const matches = parseTitleMatches(await this.executeNativeScript(titleSearchScript(identity ?? normalizedQuery, identity !== undefined)));
1033
+ if (matches.length === 0) {
1034
+ this.titleDiscoveryAvailable = false;
1035
+ throw new Error("FINAL_CUT_NATIVE_TITLE_DISCOVERY_EMPTY: Final Cut's Titles browser returned no title assets");
1036
+ }
1037
+ this.titleDiscoveryAvailable = true;
1038
+ return matches;
1039
+ }
1040
+ catch (error) {
1041
+ lastError = error;
1042
+ if (attempt === 0)
1043
+ await this.sleep(250);
1044
+ }
1045
+ }
1046
+ throw lastError;
1047
+ }
1048
+ catch (error) {
1049
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1050
+ }
662
1051
  }
663
- async executeTransitionAdd(previewToken) {
664
- return this.withNativeUi(() => this.executeTransitionAddNative(previewToken));
1052
+ async ensureTitleBrowserReady() {
1053
+ const output = await this.executeNativeScript(titleBrowserPreflightScript());
1054
+ const [frontmost = "false", windowAvailable = "false"] = output.split(String.fromCharCode(31));
1055
+ if (frontmost !== "true")
1056
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut must be frontmost for title discovery");
1057
+ if (windowAvailable !== "true")
1058
+ throw new Error("FINAL_CUT_NATIVE_TITLE_BROWSER_UNAVAILABLE: Final Cut's Titles browser is unavailable");
665
1059
  }
666
1060
  async searchTransitionsNative(query) {
667
1061
  this.assertEnabled();
668
- if (!query.trim())
669
- throw new Error("INVALID_OPERATION: transition search query cannot be empty");
670
1062
  const context = await this.requireTimelineContext();
671
1063
  if (!context.frontmost)
672
1064
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut must be frontmost for transition discovery");
@@ -738,7 +1130,7 @@ export class FinalCutNativeAutomationAdapter {
738
1130
  this.transitionPreviews.delete(previewToken);
739
1131
  if (this.now() > preview.expiresAt)
740
1132
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native transition preview has expired");
741
- const before = await this.requireTimelineContext();
1133
+ const before = await this.requireNativeWriteContext();
742
1134
  const beforeLive = await this.requireLiveState();
743
1135
  validateTransitionPreviewBinding(preview, beforeLive);
744
1136
  const frameDuration = beforeLive.sequence?.frameDuration;
@@ -763,7 +1155,7 @@ export class FinalCutNativeAutomationAdapter {
763
1155
  await this.waitForPlayhead(preview.editPoint, beforeLive.sequence?.id);
764
1156
  // Command-T may mutate before duration editing fails. Never retry this
765
1157
  // script: the outer recovery path observes and rolls back that mutation.
766
- observedDuration = parseObservedTransitionDuration(await this.executor(applyTransitionScript(preview.duration, frameDuration)), frameDuration);
1158
+ observedDuration = parseObservedTransitionDuration(await this.executeNativeScript(applyTransitionScript(preview.duration, frameDuration)), frameDuration);
767
1159
  if (compareRational(observedDuration, preview.duration) !== 0) {
768
1160
  throw new Error(`FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut read back ${observedDuration.value}/${observedDuration.timescale}, expected ${preview.duration.value}/${preview.duration.timescale}`);
769
1161
  }
@@ -907,22 +1299,22 @@ export class FinalCutNativeAutomationAdapter {
907
1299
  this.titlePreviews.delete(previewToken);
908
1300
  if (this.now() > preview.expiresAt)
909
1301
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native title preview has expired");
910
- const before = await this.requireTimelineContext();
1302
+ const before = await this.requireNativeWriteContext();
911
1303
  const beforeLive = await this.requireLiveState();
912
1304
  this.validateTitleBinding(preview, beforeLive);
913
1305
  const startTimecode = this.toTimecode(preview.start, beforeLive);
914
1306
  const endTimecode = this.toTimecode(preview.end, beforeLive);
915
1307
  try {
916
1308
  await this.executeNativeSequence(async () => {
917
- await this.executor(titleAssetSelectionScript(preview.asset.name));
1309
+ await this.executeNativeScript(titleAssetSelectionScript(preview.asset.name, nativeTitleIdentity(preview.asset)));
918
1310
  await this.focusTimelineForMediaInsertion();
919
- await this.executor(setPlayheadScript(startTimecode));
1311
+ await this.executeNativeScript(setPlayheadScript(startTimecode));
920
1312
  await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
921
- await this.executor(markRangeStartScript());
922
- await this.executor(setPlayheadScript(endTimecode));
1313
+ await this.executeNativeScript(markRangeStartScript());
1314
+ await this.executeNativeScript(setPlayheadScript(endTimecode));
923
1315
  await this.waitForPlayhead(preview.end, beforeLive.sequence?.id);
924
- await this.executor(markRangeEndAndConnectTitleScript());
925
- await this.executor(titleTextEditScript(preview.text));
1316
+ await this.executeNativeScript(markRangeEndAndConnectTitleScript());
1317
+ await this.executeNativeScript(titleTextEditScript(preview.text));
926
1318
  }, async (recovered) => {
927
1319
  const targetChanged = before.target.kind !== recovered.target.kind
928
1320
  || before.target.name !== recovered.target.name
@@ -979,114 +1371,121 @@ export class FinalCutNativeAutomationAdapter {
979
1371
  ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
980
1372
  };
981
1373
  }
982
- async previewMediaInsertionNative(operation, mediaHandle, selectionMode = "handle") {
1374
+ async previewPictureInPictureNative(request) {
983
1375
  this.assertEnabled();
984
- const media = this.mediaHandles.get(mediaHandle);
1376
+ const media = this.mediaHandles.get(request.mediaHandle);
985
1377
  if (!media)
986
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${mediaHandle}`);
987
- if (this.selectedMediaHandle !== mediaHandle) {
988
- throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: select one Browser media result before insertion");
1378
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${request.mediaHandle}`);
1379
+ if (this.selectedMediaHandle !== request.mediaHandle) {
1380
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: select one Browser media result before picture-in-picture placement");
989
1381
  }
1382
+ const anchorOccurrence = this.occurrenceHandles.get(request.anchorOccurrenceHandle);
1383
+ if (!anchorOccurrence) {
1384
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown anchor occurrence ${request.anchorOccurrenceHandle}`);
1385
+ }
1386
+ await this.ensureOccurrenceRange(anchorOccurrence);
990
1387
  const context = await this.requireTimelineContext();
991
1388
  if (!context.frontmost)
992
1389
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
993
1390
  const live = await this.requireLiveState();
994
1391
  const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
995
- const beforeDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
996
- if (!sequenceStart || !beforeDuration)
997
- throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence duration is unavailable");
998
- const insertionTime = operation === "append"
999
- ? addRational(sequenceStart, beforeDuration)
1000
- : live.playheadTime;
1001
- if (!insertionTime)
1002
- throw new Error("CAPABILITY_UNAVAILABLE: Final Cut playhead is unavailable for media insertion");
1392
+ const sequenceDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
1393
+ const frameDuration = live.sequence?.frameDuration;
1394
+ if (!sequenceStart || !sequenceDuration || !frameDuration) {
1395
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence timing is unavailable");
1396
+ }
1397
+ const start = structuredClone(request.start);
1398
+ const duration = structuredClone(request.duration);
1399
+ const end = addRational(start, duration);
1400
+ validatePictureInPictureRequest(request, sequenceStart, sequenceDuration, frameDuration, start, end);
1401
+ validatePictureInPictureAnchor(anchorOccurrence, live);
1003
1402
  const expiresAt = this.now() + 30_000;
1004
- const previewToken = opaqueHandle(`${operation}-media-preview`);
1005
- this.mediaInsertionPreviews.set(previewToken, {
1006
- operation,
1007
- mediaHandle,
1008
- selectionMode,
1009
- beforeDuration,
1010
- insertionTime,
1403
+ const previewToken = opaqueHandle("picture-in-picture-preview");
1404
+ this.pictureInPicturePreviews.set(previewToken, {
1405
+ mediaHandle: request.mediaHandle,
1406
+ anchorOccurrence: structuredClone(anchorOccurrence),
1407
+ start,
1408
+ end,
1409
+ duration,
1410
+ position: structuredClone(request.position),
1411
+ scale: request.scale,
1412
+ ...(request.crop ? { crop: structuredClone(request.crop) } : {}),
1413
+ ...(request.frame ? { frame: structuredClone(request.frame) } : {}),
1011
1414
  sequenceId: live.sequence?.id,
1012
1415
  revision: live.revision.id,
1013
1416
  expiresAt,
1014
1417
  });
1015
1418
  return {
1016
1419
  previewToken,
1017
- operation,
1018
- media,
1019
- beforeDuration,
1020
- insertionTime,
1420
+ media: structuredClone(media),
1421
+ anchorOccurrence: structuredClone(anchorOccurrence),
1422
+ start,
1423
+ end,
1424
+ duration,
1425
+ position: structuredClone(request.position),
1426
+ scale: request.scale,
1427
+ ...(request.crop ? { crop: structuredClone(request.crop) } : {}),
1428
+ ...(request.frame ? { frame: structuredClone(request.frame) } : {}),
1021
1429
  ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
1022
1430
  revision: live.revision.id,
1023
- command: operation === "append" ? "Append selected media" : "Insert selected media at playhead",
1431
+ command: "Add native picture-in-picture",
1024
1432
  expiresAt: new Date(expiresAt).toISOString(),
1025
1433
  };
1026
1434
  }
1027
- async executeMediaInsertionNative(previewToken, expectedOperation, expectedSelectionMode) {
1435
+ async executePictureInPictureNative(previewToken) {
1028
1436
  this.assertEnabled();
1029
- const preview = this.mediaInsertionPreviews.get(previewToken);
1437
+ const preview = this.pictureInPicturePreviews.get(previewToken);
1030
1438
  if (!preview)
1031
- throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown media insertion preview");
1032
- this.mediaInsertionPreviews.delete(previewToken);
1439
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown native picture-in-picture preview");
1440
+ this.pictureInPicturePreviews.delete(previewToken);
1033
1441
  if (this.now() > preview.expiresAt)
1034
- throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media insertion preview has expired");
1035
- if (expectedOperation && preview.operation !== expectedOperation)
1036
- throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview operation does not match execute operation");
1037
- if (expectedSelectionMode && preview.selectionMode !== expectedSelectionMode)
1038
- throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview selection mode does not match execute operation");
1442
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native picture-in-picture preview has expired");
1039
1443
  const media = this.mediaHandles.get(preview.mediaHandle);
1040
1444
  if (!media)
1041
1445
  throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${preview.mediaHandle}`);
1042
- if (preview.selectionMode === "handle" && this.selectedMediaHandle !== preview.mediaHandle) {
1043
- throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before insertion");
1446
+ if (this.selectedMediaHandle !== preview.mediaHandle) {
1447
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before picture-in-picture placement");
1044
1448
  }
1045
- const before = await this.requireTimelineContext();
1449
+ const before = await this.requireNativeWriteContext();
1046
1450
  const beforeLive = await this.requireLiveState();
1047
- this.validateMediaInsertionBinding(preview, beforeLive);
1048
- if (preview.selectionMode === "selected")
1049
- await this.validateSelectedMediaBinding(media);
1451
+ validatePictureInPicturePreviewBinding(preview, beforeLive);
1452
+ const anchorOccurrence = this.occurrenceHandles.get(preview.anchorOccurrence.handle) ?? preview.anchorOccurrence;
1453
+ validatePictureInPictureAnchor(anchorOccurrence, beforeLive);
1454
+ const startTimecode = this.toTimecode(preview.start, beforeLive);
1455
+ const endTimecode = this.toTimecode(preview.end, beforeLive);
1456
+ const operationId = opaqueHandle("native-picture-in-picture");
1050
1457
  try {
1051
- // Re-select by the stable Browser identity immediately before the edit. The
1052
- // cached handle only proves what this process selected, not what Final Cut
1053
- // currently has selected after another UI interaction.
1054
- if (preview.selectionMode === "handle")
1458
+ await this.executeNativeSequence(async () => {
1459
+ await this.selectMediaNative(preview.mediaHandle);
1460
+ await this.focusTimelineForMediaInsertion();
1461
+ if (this.canDriveNativeMouse && anchorOccurrence.timelineOffset !== undefined) {
1462
+ await this.selectTimelineOccurrence(anchorOccurrence.timelineOffset);
1463
+ }
1464
+ await this.validateSelectedPictureInPictureAnchor(anchorOccurrence);
1465
+ await this.executeNativeScript(setPlayheadScript(startTimecode));
1466
+ await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
1467
+ await this.executeNativeScript(markRangeStartScript());
1468
+ await this.executeNativeScript(setPlayheadScript(endTimecode));
1469
+ await this.waitForPlayhead(preview.end, beforeLive.sequence?.id);
1470
+ await this.executeNativeScript(markRangeEndAndConnectPictureInPictureScript());
1471
+ await this.executeNativeScript(pictureInPictureTransformScript(preview));
1472
+ }, async (recovered) => {
1473
+ this.assertRetryContext(before, recovered, true);
1474
+ validatePictureInPicturePreviewBinding(preview, await this.requireLiveState());
1055
1475
  await this.selectMediaNative(preview.mediaHandle);
1056
- await this.focusTimelineForMediaInsertion();
1057
- await this.executeNativeCommand(mediaInsertionScript(preview.operation), async (recovered) => {
1058
- this.assertRetryContext(before, recovered, preview.operation === "insert");
1059
- if (preview.selectionMode === "handle")
1060
- await this.selectMediaNative(preview.mediaHandle);
1061
- const refocused = await this.prepareNativeRetry();
1062
- this.assertRetryContext(before, refocused, preview.operation === "insert");
1063
1476
  await this.focusTimelineForMediaInsertion();
1064
- this.validateMediaInsertionBinding(preview, await this.requireLiveState());
1065
- if (preview.selectionMode === "selected")
1066
- await this.validateSelectedMediaBinding(media);
1067
1477
  });
1068
1478
  }
1069
1479
  catch (error) {
1070
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1071
- }
1072
- const operationId = opaqueHandle(`native-${preview.operation}-media`);
1073
- let after;
1074
- let afterLive;
1075
- try {
1076
- after = await this.requireTimelineContext();
1077
- afterLive = await this.waitForMediaInsertion(preview.beforeDuration, beforeLive.revision.id);
1078
- }
1079
- catch (error) {
1080
- const observedContext = after ?? await this.inspectRawNative();
1081
- const observedLive = afterLive ?? await this.readLiveState();
1082
- if (observedLive && mediaInsertionMutationObserved(beforeLive, observedLive) && observedContext.undoCommand) {
1480
+ const observedContext = await this.inspectRawNative();
1481
+ const observedLive = await this.readLiveState();
1482
+ if (observedLive && observedLive.revision.id !== beforeLive.revision.id && observedContext.undoCommand) {
1083
1483
  this.rememberOperation(operationId, {
1084
- kind: "media-insertion",
1484
+ kind: "picture-in-picture",
1085
1485
  before,
1086
1486
  after: observedContext,
1087
1487
  beforeLive,
1088
1488
  afterLive: observedLive,
1089
- beforeDuration: preview.beforeDuration,
1090
1489
  undoCommand: observedContext.undoCommand,
1091
1490
  });
1092
1491
  try {
@@ -1095,9 +1494,205 @@ export class FinalCutNativeAutomationAdapter {
1095
1494
  catch (rollbackError) {
1096
1495
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1097
1496
  }
1098
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}; insertion was rolled back`);
1497
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; picture-in-picture placement was rolled back`);
1099
1498
  }
1100
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}; post-command state was not safely recoverable, so no Undo handle was retained`);
1499
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1500
+ }
1501
+ let after;
1502
+ let afterLive;
1503
+ try {
1504
+ after = await this.requireTimelineContext();
1505
+ afterLive = await this.waitForRevision(beforeLive.revision.id);
1506
+ const occurrence = await this.readPictureInPictureOccurrence(preview, anchorOccurrence);
1507
+ const observed = parsePictureInPictureReadback(await this.executeNativeScript(pictureInPictureInspectorReadbackScript()));
1508
+ const verification = verifyNativePictureInPicture({ ...preview, media }, after, beforeLive, afterLive, observed, occurrence);
1509
+ const operation = {
1510
+ kind: "picture-in-picture",
1511
+ before,
1512
+ after,
1513
+ beforeLive,
1514
+ afterLive,
1515
+ undoCommand: after.undoCommand,
1516
+ };
1517
+ if (!verification.verified) {
1518
+ if (afterLive.revision.id !== beforeLive.revision.id && after.undoAvailable && after.undoCommand) {
1519
+ this.rememberOperation(operationId, operation);
1520
+ try {
1521
+ await this.undo(operationId);
1522
+ }
1523
+ catch (rollbackError) {
1524
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1525
+ }
1526
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; picture-in-picture placement was rolled back`);
1527
+ }
1528
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
1529
+ }
1530
+ this.rememberOperation(operationId, operation);
1531
+ return {
1532
+ operationId,
1533
+ previewToken,
1534
+ media: structuredClone(media),
1535
+ anchorOccurrence: structuredClone(anchorOccurrence),
1536
+ occurrence: structuredClone(occurrence),
1537
+ start: structuredClone(preview.start),
1538
+ end: structuredClone(preview.end),
1539
+ duration: structuredClone(preview.duration),
1540
+ position: structuredClone(preview.position),
1541
+ scale: preview.scale,
1542
+ ...(preview.crop ? { crop: structuredClone(preview.crop) } : {}),
1543
+ ...(preview.frame ? { frame: structuredClone(preview.frame) } : {}),
1544
+ observed,
1545
+ before,
1546
+ after,
1547
+ beforeRevision: beforeLive.revision,
1548
+ afterRevision: afterLive.revision,
1549
+ verification,
1550
+ undoAvailable: after.undoAvailable,
1551
+ ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
1552
+ };
1553
+ }
1554
+ catch (error) {
1555
+ const observedContext = after ?? await this.inspectRawNative();
1556
+ const observedLive = afterLive ?? await this.readLiveState();
1557
+ if (observedLive && observedLive.revision.id !== beforeLive.revision.id && observedContext.undoCommand) {
1558
+ this.rememberOperation(operationId, {
1559
+ kind: "picture-in-picture",
1560
+ before,
1561
+ after: observedContext,
1562
+ beforeLive,
1563
+ afterLive: observedLive,
1564
+ undoCommand: observedContext.undoCommand,
1565
+ });
1566
+ try {
1567
+ await this.undo(operationId);
1568
+ }
1569
+ catch (rollbackError) {
1570
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1571
+ }
1572
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; picture-in-picture placement was rolled back`);
1573
+ }
1574
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1575
+ }
1576
+ }
1577
+ async previewMediaInsertionNative(operation, mediaHandle, selectionMode = "handle") {
1578
+ this.assertEnabled();
1579
+ const media = this.mediaHandles.get(mediaHandle);
1580
+ if (!media)
1581
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${mediaHandle}`);
1582
+ if (this.selectedMediaHandle !== mediaHandle) {
1583
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: select one Browser media result before insertion");
1584
+ }
1585
+ const context = await this.requireTimelineContext();
1586
+ if (!context.frontmost)
1587
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
1588
+ const live = await this.requireLiveState();
1589
+ const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
1590
+ const beforeDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
1591
+ if (!sequenceStart || !beforeDuration)
1592
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence duration is unavailable");
1593
+ const insertionTime = operation === "append"
1594
+ ? addRational(sequenceStart, beforeDuration)
1595
+ : live.playheadTime;
1596
+ if (!insertionTime)
1597
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut playhead is unavailable for media insertion");
1598
+ const expiresAt = this.now() + 30_000;
1599
+ const previewToken = opaqueHandle(`${operation}-media-preview`);
1600
+ this.mediaInsertionPreviews.set(previewToken, {
1601
+ operation,
1602
+ mediaHandle,
1603
+ selectionMode,
1604
+ beforeDuration,
1605
+ insertionTime,
1606
+ sequenceId: live.sequence?.id,
1607
+ revision: live.revision.id,
1608
+ expiresAt,
1609
+ });
1610
+ return {
1611
+ previewToken,
1612
+ operation,
1613
+ media,
1614
+ beforeDuration,
1615
+ insertionTime,
1616
+ ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
1617
+ revision: live.revision.id,
1618
+ command: operation === "append" ? "Append selected media" : "Insert selected media at playhead",
1619
+ expiresAt: new Date(expiresAt).toISOString(),
1620
+ };
1621
+ }
1622
+ async executeMediaInsertionNative(previewToken, expectedOperation, expectedSelectionMode) {
1623
+ this.assertEnabled();
1624
+ const preview = this.mediaInsertionPreviews.get(previewToken);
1625
+ if (!preview)
1626
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown media insertion preview");
1627
+ this.mediaInsertionPreviews.delete(previewToken);
1628
+ if (this.now() > preview.expiresAt)
1629
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media insertion preview has expired");
1630
+ if (expectedOperation && preview.operation !== expectedOperation)
1631
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview operation does not match execute operation");
1632
+ if (expectedSelectionMode && preview.selectionMode !== expectedSelectionMode)
1633
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview selection mode does not match execute operation");
1634
+ const media = this.mediaHandles.get(preview.mediaHandle);
1635
+ if (!media)
1636
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${preview.mediaHandle}`);
1637
+ if (preview.selectionMode === "handle" && this.selectedMediaHandle !== preview.mediaHandle) {
1638
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before insertion");
1639
+ }
1640
+ const before = await this.requireNativeWriteContext();
1641
+ const beforeLive = await this.requireLiveState();
1642
+ this.validateMediaInsertionBinding(preview, beforeLive);
1643
+ if (preview.selectionMode === "selected")
1644
+ await this.validateSelectedMediaBinding(media);
1645
+ try {
1646
+ // Re-select by the stable Browser identity immediately before the edit. The
1647
+ // cached handle only proves what this process selected, not what Final Cut
1648
+ // currently has selected after another UI interaction.
1649
+ if (preview.selectionMode === "handle")
1650
+ await this.selectMediaNative(preview.mediaHandle);
1651
+ await this.focusTimelineForMediaInsertion();
1652
+ await this.executeNativeCommand(mediaInsertionScript(preview.operation), async (recovered) => {
1653
+ this.assertRetryContext(before, recovered, preview.operation === "insert");
1654
+ if (preview.selectionMode === "handle")
1655
+ await this.selectMediaNative(preview.mediaHandle);
1656
+ const refocused = await this.prepareNativeRetry();
1657
+ this.assertRetryContext(before, refocused, preview.operation === "insert");
1658
+ await this.focusTimelineForMediaInsertion();
1659
+ this.validateMediaInsertionBinding(preview, await this.requireLiveState());
1660
+ if (preview.selectionMode === "selected")
1661
+ await this.validateSelectedMediaBinding(media);
1662
+ });
1663
+ }
1664
+ catch (error) {
1665
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1666
+ }
1667
+ const operationId = opaqueHandle(`native-${preview.operation}-media`);
1668
+ let after;
1669
+ let afterLive;
1670
+ try {
1671
+ after = await this.requireTimelineContext();
1672
+ afterLive = await this.waitForMediaInsertion(preview.beforeDuration, beforeLive.revision.id);
1673
+ }
1674
+ catch (error) {
1675
+ const observedContext = after ?? await this.inspectRawNative();
1676
+ const observedLive = afterLive ?? await this.readLiveState();
1677
+ if (observedLive && mediaInsertionMutationObserved(beforeLive, observedLive) && observedContext.undoCommand) {
1678
+ this.rememberOperation(operationId, {
1679
+ kind: "media-insertion",
1680
+ before,
1681
+ after: observedContext,
1682
+ beforeLive,
1683
+ afterLive: observedLive,
1684
+ beforeDuration: preview.beforeDuration,
1685
+ undoCommand: observedContext.undoCommand,
1686
+ });
1687
+ try {
1688
+ await this.undo(operationId);
1689
+ }
1690
+ catch (rollbackError) {
1691
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1692
+ }
1693
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; insertion was rolled back`);
1694
+ }
1695
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; post-command state was not safely recoverable, so no Undo handle was retained`);
1101
1696
  }
1102
1697
  const afterDuration = afterLive.sequenceTimeRange?.duration ?? afterLive.sequence?.duration;
1103
1698
  const verification = mediaInsertionVerificationDetail(afterDuration, preview.beforeDuration, afterLive.revision.id, beforeLive.revision.id);
@@ -1143,7 +1738,7 @@ export class FinalCutNativeAutomationAdapter {
1143
1738
  async focusTimelineForMediaInsertion() {
1144
1739
  if (!this.canDriveNativeMouse)
1145
1740
  return;
1146
- const coordinates = (await this.executor(timelineInsertionCoordinatesScript())).split("|").map(Number);
1741
+ const coordinates = (await this.executeNativeScript(timelineInsertionCoordinatesScript())).split("|").map(Number);
1147
1742
  const [originX, originY, width, height] = coordinates;
1148
1743
  if (![originX, originY, width, height].every(Number.isFinite)) {
1149
1744
  throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut timeline coordinates");
@@ -1151,9 +1746,11 @@ export class FinalCutNativeAutomationAdapter {
1151
1746
  const x = Math.round(originX + width * 0.5);
1152
1747
  const y = Math.round(originY + height * 0.82);
1153
1748
  try {
1154
- await execFile("swift", ["-e", nativeMouseFocusSource(x, y)]);
1749
+ await this.executeNativeMouseScript(nativeMouseFocusSource(x, y));
1155
1750
  }
1156
1751
  catch (error) {
1752
+ if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_CANCELLED" || nativeErrorCode(error) === "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT")
1753
+ throw error;
1157
1754
  throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline focus failed: ${String(error)}`);
1158
1755
  }
1159
1756
  }
@@ -1216,7 +1813,7 @@ export class FinalCutNativeAutomationAdapter {
1216
1813
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: range preview has expired");
1217
1814
  if (expectedOperation && preview.operation !== expectedOperation)
1218
1815
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview operation does not match execute operation");
1219
- const before = await this.requireTimelineContext();
1816
+ const before = await this.requireNativeWriteContext();
1220
1817
  const beforeLive = await this.requireLiveState();
1221
1818
  this.validateRangeBinding(preview, beforeLive);
1222
1819
  const rangeDuration = subtractRational(preview.range.end, preview.range.start);
@@ -1365,24 +1962,24 @@ export class FinalCutNativeAutomationAdapter {
1365
1962
  const startTimecode = this.toTimecode(range.start, beforeLive);
1366
1963
  const endTimecode = this.toTimecode(range.end, beforeLive);
1367
1964
  const executeRange = async () => {
1368
- await this.executor(setPlayheadScript(startTimecode));
1965
+ await this.executeNativeScript(setPlayheadScript(startTimecode));
1369
1966
  await this.waitForPlayhead(range.start, beforeLive.sequence?.id);
1370
- await this.executor(markRangeStartScript());
1371
- await this.executor(setPlayheadScript(endTimecode));
1967
+ await this.executeNativeScript(markRangeStartScript());
1968
+ await this.executeNativeScript(setPlayheadScript(endTimecode));
1372
1969
  await this.waitForPlayhead(range.end, beforeLive.sequence?.id);
1373
- await this.executor(markRangeEndAndDeleteScript());
1970
+ await this.executeNativeScript(markRangeEndAndDeleteScript());
1374
1971
  };
1375
1972
  await this.executeNativeSequence(executeRange, validateRetry);
1376
1973
  }
1377
1974
  async executeNativeCommand(script, validateRetry) {
1378
1975
  try {
1379
- await this.executor(script);
1976
+ await this.executeNativeScript(script);
1380
1977
  }
1381
1978
  catch (error) {
1382
1979
  if (!isRecoverableNativeFocusRace(error))
1383
1980
  throw error;
1384
1981
  await validateRetry?.(await this.prepareNativeRetry());
1385
- await this.executor(script);
1982
+ await this.executeNativeScript(script);
1386
1983
  }
1387
1984
  }
1388
1985
  async executeNativeSequence(execute, validateRetry) {
@@ -1436,27 +2033,30 @@ export class FinalCutNativeAutomationAdapter {
1436
2033
  if (!this.enabled)
1437
2034
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native writes are disabled");
1438
2035
  }
1439
- async withNativeUi(operation) {
1440
- const outermost = this.nativeUiDepth === 0;
1441
- if (outermost && this.enabled) {
1442
- if (this.nativeOperationLease)
1443
- this.nativeOperationLease.acquire();
1444
- else
1445
- this.suspendLiveConnection?.();
1446
- }
1447
- this.nativeUiDepth += 1;
1448
- try {
1449
- return await operation();
1450
- }
1451
- finally {
1452
- this.nativeUiDepth -= 1;
2036
+ async withNativeUi(operation, signal) {
2037
+ const request = { signal: signal ?? this.requestContext.getStore()?.signal };
2038
+ return this.requestContext.run(request, async () => {
2039
+ const outermost = this.nativeUiDepth === 0;
1453
2040
  if (outermost && this.enabled) {
1454
2041
  if (this.nativeOperationLease)
1455
- this.nativeOperationLease.release();
2042
+ this.nativeOperationLease.acquire();
1456
2043
  else
1457
- this.resumeLiveConnection?.();
2044
+ this.suspendLiveConnection?.();
1458
2045
  }
1459
- }
2046
+ this.nativeUiDepth += 1;
2047
+ try {
2048
+ return await operation();
2049
+ }
2050
+ finally {
2051
+ this.nativeUiDepth -= 1;
2052
+ if (outermost && this.enabled) {
2053
+ if (this.nativeOperationLease)
2054
+ this.nativeOperationLease.release();
2055
+ else
2056
+ this.resumeLiveConnection?.();
2057
+ }
2058
+ }
2059
+ });
1460
2060
  }
1461
2061
  async validateOccurrenceBinding(occurrence) {
1462
2062
  if (!this.liveState || !occurrence.revision)
@@ -1479,6 +2079,50 @@ export class FinalCutNativeAutomationAdapter {
1479
2079
  }
1480
2080
  }
1481
2081
  }
2082
+ async validateSelectedPictureInPictureAnchor(anchor) {
2083
+ if (!anchor.identity) {
2084
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: native PIP requires a stable anchor occurrence identity");
2085
+ }
2086
+ const context = await this.requireTimelineContext();
2087
+ if (context.target.kind !== "selected-clip" || context.target.identity !== anchor.identity) {
2088
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence does not match the requested anchor");
2089
+ }
2090
+ const reread = await this.locateOccurrenceNative(anchor.mediaHandle, true);
2091
+ if (reread.status !== "unique" || reread.occurrences[0]?.identity !== anchor.identity) {
2092
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: anchor occurrence identity became ambiguous or changed");
2093
+ }
2094
+ const observed = reread.occurrences[0];
2095
+ if (anchor.start && observed.start && parseRationalString(anchor.start, "anchor start")
2096
+ && compareRational(parseRationalString(anchor.start, "anchor start"), parseRationalString(observed.start, "observed anchor start")) !== 0) {
2097
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: anchor occurrence start changed");
2098
+ }
2099
+ if (anchor.duration && observed.duration && parseRationalString(anchor.duration, "anchor duration")
2100
+ && compareRational(parseRationalString(anchor.duration, "anchor duration"), parseRationalString(observed.duration, "observed anchor duration")) !== 0) {
2101
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: anchor occurrence duration changed");
2102
+ }
2103
+ }
2104
+ async readPictureInPictureOccurrence(preview, anchor) {
2105
+ const located = await this.locateOccurrenceNative(preview.mediaHandle, true);
2106
+ const matches = located.occurrences.filter((occurrence) => pictureInPictureOccurrenceMatchesRange(occurrence, preview));
2107
+ if (matches.length === 0) {
2108
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_UNAVAILABLE: inserted clip range was not read back");
2109
+ }
2110
+ if (matches.length > 1) {
2111
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_AMBIGUOUS: multiple inserted clips match the requested range");
2112
+ }
2113
+ const occurrence = matches[0];
2114
+ if (!occurrence.identity) {
2115
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_UNAVAILABLE: inserted clip has no stable identity");
2116
+ }
2117
+ const context = await this.requireTimelineContext();
2118
+ if (context.target.kind !== "selected-clip" || context.target.identity !== occurrence.identity) {
2119
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_STALE: selected clip does not match the inserted occurrence");
2120
+ }
2121
+ if (!anchor.identity) {
2122
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: native PIP anchor identity is unavailable");
2123
+ }
2124
+ return occurrence;
2125
+ }
1482
2126
  async ensureOccurrenceRange(occurrence) {
1483
2127
  if (occurrence.start && occurrence.duration)
1484
2128
  return;
@@ -1492,14 +2136,14 @@ export class FinalCutNativeAutomationAdapter {
1492
2136
  let startLive;
1493
2137
  let endLive;
1494
2138
  try {
1495
- await this.executor(occurrenceRangeEndpointScript(occurrence.timelineOffset, "start"));
2139
+ await this.executeNativeScript(occurrenceRangeEndpointScript(occurrence.timelineOffset, "start"));
1496
2140
  startLive = await this.waitForLivePlayheadChangeOrCurrent(originalLive, "start");
1497
- await this.executor(occurrenceRangeEndpointScript(occurrence.timelineOffset, "end"));
2141
+ await this.executeNativeScript(occurrenceRangeEndpointScript(occurrence.timelineOffset, "end"));
1498
2142
  endLive = await this.waitForLivePlayheadChangeOrCurrent(startLive, "end");
1499
2143
  }
1500
2144
  finally {
1501
2145
  try {
1502
- await this.executor(setPlayheadScript(this.toTimecode(originalLive.playheadTime, originalLive)));
2146
+ await this.executeNativeScript(setPlayheadScript(this.toTimecode(originalLive.playheadTime, originalLive)));
1503
2147
  await this.waitForPlayhead(originalLive.playheadTime, originalLive.sequence?.id);
1504
2148
  }
1505
2149
  catch {
@@ -1546,11 +2190,25 @@ export class FinalCutNativeAutomationAdapter {
1546
2190
  if (requiresClip(operation) && context.target.kind !== "selected-clip") {
1547
2191
  throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one clip in Final Cut Pro");
1548
2192
  }
1549
- if (!requiresClip(operation) && context.target.kind === "none") {
2193
+ if (!requiresClip(operation) && (context.target.kind === "none" || context.target.kind === "unknown")) {
1550
2194
  throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: position the playhead in Final Cut Pro");
1551
2195
  }
2196
+ this.assertNativeWriteContext(context);
2197
+ return context;
2198
+ }
2199
+ async requireNativeWriteContext() {
2200
+ const context = await this.requireTimelineContext();
2201
+ this.assertNativeWriteContext(context);
1552
2202
  return context;
1553
2203
  }
2204
+ assertNativeWriteContext(context) {
2205
+ if (!context.readiness.selectedTarget) {
2206
+ throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: position the playhead or select a timeline target in Final Cut Pro");
2207
+ }
2208
+ if (!context.undoAvailable) {
2209
+ throw new Error("FINAL_CUT_NATIVE_UNDO_UNAVAILABLE: Final Cut has no available Undo command; native writes require an available Undo command");
2210
+ }
2211
+ }
1554
2212
  async requireTimelineContext() {
1555
2213
  const context = await this.attachLiveState(await this.ensureTimelineReady());
1556
2214
  if (!context.available) {
@@ -1570,7 +2228,8 @@ export class FinalCutNativeAutomationAdapter {
1570
2228
  let lastContext;
1571
2229
  while (this.now() < deadline) {
1572
2230
  try {
1573
- const context = parseContext(await this.executeNativeScript(timelinePreflightScript(), deadline, "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT"));
2231
+ const observedContext = parseContext(await this.executeNativeScript(timelinePreflightScript(), deadline, "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT"));
2232
+ const context = reconcileTimelineFocus(observedContext);
1574
2233
  lastContext = context;
1575
2234
  if (!context.timelineWindowAvailable) {
1576
2235
  lastCode = "FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW";
@@ -1596,6 +2255,8 @@ export class FinalCutNativeAutomationAdapter {
1596
2255
  const code = nativeErrorCode(error);
1597
2256
  if (code === "FINAL_CUT_NATIVE_PERMISSION_REQUIRED")
1598
2257
  throw new NativeFinalCutPreflightError(code, nativeErrorMessage(error), lastContext);
2258
+ if (code === "FINAL_CUT_NATIVE_CANCELLED")
2259
+ throw new NativeFinalCutPreflightError(code, nativeErrorMessage(error), lastContext);
1599
2260
  lastCode = code;
1600
2261
  lastMessage = nativeErrorMessage(error);
1601
2262
  }
@@ -1623,29 +2284,122 @@ export class FinalCutNativeAutomationAdapter {
1623
2284
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut could not be brought to the front for Browser automation");
1624
2285
  return context;
1625
2286
  }
2287
+ async selectTimelineOccurrence(timelineOffset) {
2288
+ const coordinates = (await this.executeNativeScript(timelineSelectionCoordinatesScript())).split("|").map(Number);
2289
+ const [originX, originY, windowWidth, windowHeight] = coordinates;
2290
+ if (![originX, originY, windowWidth, windowHeight].every(Number.isFinite)) {
2291
+ throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut window coordinates");
2292
+ }
2293
+ const x = Math.round(originX + timelineOffset);
2294
+ const y = Math.round(originY + (windowHeight * 0.77));
2295
+ try {
2296
+ await this.executeNativeMouseScript(nativeMouseSelectionSource(x, y));
2297
+ }
2298
+ catch (error) {
2299
+ if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_CANCELLED" || nativeErrorCode(error) === "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT")
2300
+ throw error;
2301
+ throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline selection failed: ${String(error)}`);
2302
+ }
2303
+ }
2304
+ async executeNativeMouseScript(source) {
2305
+ const requestSignal = this.requestContext.getStore()?.signal;
2306
+ const effectiveDeadline = this.now() + this.nativePreflightTimeoutMs;
2307
+ if (requestSignal?.aborted)
2308
+ throw new Error("FINAL_CUT_NATIVE_CANCELLED: native request was cancelled");
2309
+ const remaining = effectiveDeadline - this.now();
2310
+ if (remaining <= 0)
2311
+ throw new Error("FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT: native automation deadline expired");
2312
+ const controller = new AbortController();
2313
+ let timer;
2314
+ let cancelListener;
2315
+ let timedOut = false;
2316
+ let cancelled = false;
2317
+ const timeout = new Promise((_, reject) => {
2318
+ timer = setTimeout(() => {
2319
+ timedOut = true;
2320
+ controller.abort();
2321
+ reject(new Error("FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT: native automation deadline expired"));
2322
+ }, remaining);
2323
+ });
2324
+ const cancellation = requestSignal
2325
+ ? new Promise((_, reject) => {
2326
+ cancelListener = () => {
2327
+ cancelled = true;
2328
+ controller.abort();
2329
+ reject(new Error("FINAL_CUT_NATIVE_CANCELLED: native request was cancelled"));
2330
+ };
2331
+ requestSignal.addEventListener("abort", cancelListener, { once: true });
2332
+ })
2333
+ : undefined;
2334
+ const execution = execFile("swift", ["-e", source], { signal: controller.signal });
2335
+ try {
2336
+ await Promise.race([execution, timeout, ...(cancellation ? [cancellation] : [])]);
2337
+ }
2338
+ catch (error) {
2339
+ if (timedOut)
2340
+ throw new Error("FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT: native automation deadline expired");
2341
+ if (cancelled || requestSignal?.aborted)
2342
+ throw new Error("FINAL_CUT_NATIVE_CANCELLED: native request was cancelled");
2343
+ throw error;
2344
+ }
2345
+ finally {
2346
+ if (timer !== undefined)
2347
+ clearTimeout(timer);
2348
+ if (requestSignal && cancelListener)
2349
+ requestSignal.removeEventListener("abort", cancelListener);
2350
+ void execution.catch(() => { });
2351
+ }
2352
+ }
1626
2353
  stableMediaHandle(identity) {
1627
2354
  return `media-import-${createHash("sha256").update(identity).digest("hex").slice(0, 24)}`;
1628
2355
  }
1629
2356
  async executeNativeScript(script, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
1630
- if (deadline === undefined)
1631
- return this.executor(script);
1632
- const remaining = deadline - this.now();
2357
+ const requestSignal = this.requestContext.getStore()?.signal;
2358
+ const effectiveDeadline = deadline ?? this.now() + this.nativePreflightTimeoutMs;
2359
+ if (requestSignal?.aborted)
2360
+ throw new Error("FINAL_CUT_NATIVE_CANCELLED: native request was cancelled");
2361
+ const remaining = effectiveDeadline - this.now();
1633
2362
  if (remaining <= 0)
1634
2363
  throw new Error(`${timeoutCode}: native automation deadline expired`);
1635
2364
  const controller = new AbortController();
1636
2365
  let timer;
2366
+ let cancelListener;
2367
+ let timedOut = false;
2368
+ let cancelled = false;
1637
2369
  const timeout = new Promise((_, reject) => {
1638
2370
  timer = setTimeout(() => {
2371
+ timedOut = true;
1639
2372
  controller.abort();
1640
2373
  reject(new Error(`${timeoutCode}: native automation deadline expired`));
1641
2374
  }, remaining);
1642
2375
  });
2376
+ const cancellation = requestSignal
2377
+ ? new Promise((_, reject) => {
2378
+ cancelListener = () => {
2379
+ cancelled = true;
2380
+ controller.abort();
2381
+ reject(new Error("FINAL_CUT_NATIVE_CANCELLED: native request was cancelled"));
2382
+ };
2383
+ requestSignal.addEventListener("abort", cancelListener, { once: true });
2384
+ })
2385
+ : undefined;
2386
+ const execution = this.executor(script, { signal: controller.signal });
1643
2387
  try {
1644
- return await Promise.race([this.executor(script, { signal: controller.signal }), timeout]);
2388
+ return await Promise.race([execution, timeout, ...(cancellation ? [cancellation] : [])]);
2389
+ }
2390
+ catch (error) {
2391
+ if (timedOut)
2392
+ throw new Error(`${timeoutCode}: native automation deadline expired`);
2393
+ if (cancelled || requestSignal?.aborted)
2394
+ throw new Error("FINAL_CUT_NATIVE_CANCELLED: native request was cancelled");
2395
+ throw error;
1645
2396
  }
1646
2397
  finally {
1647
2398
  if (timer !== undefined)
1648
2399
  clearTimeout(timer);
2400
+ if (requestSignal && cancelListener)
2401
+ requestSignal.removeEventListener("abort", cancelListener);
2402
+ void execution.catch(() => { });
1649
2403
  }
1650
2404
  }
1651
2405
  }
@@ -1672,6 +2426,13 @@ function assertNativeTitleAsset(asset) {
1672
2426
  throw new Error("TITLE_ASSET_NOT_FOUND: native title asset identity is incomplete");
1673
2427
  if (asset.kind !== "title")
1674
2428
  throw new Error(`TITLE_ASSET_INCOMPATIBLE: ${asset.id} is not a Final Cut title asset`);
2429
+ if (!nativeTitleIdentity(asset)) {
2430
+ throw new Error("TITLE_ASSET_NATIVE_ID_REQUIRED: filesystem-observed title assets must be rediscovered by Final Cut before placement");
2431
+ }
2432
+ }
2433
+ function nativeTitleIdentity(asset) {
2434
+ const idIdentity = titleIdentityFromId(asset.id);
2435
+ return idIdentity?.trim() || undefined;
1675
2436
  }
1676
2437
  function publicTitleAsset(asset) {
1677
2438
  return { id: asset.id, kind: asset.kind, name: asset.name, vendor: asset.vendor };
@@ -1696,6 +2457,156 @@ function verifyNativeTitle(preview, beforeLive, after, afterLive) {
1696
2457
  detail: `Final Cut selected ${preview.asset.name} for ${preview.start.value}/${preview.start.timescale}-${preview.end.value}/${preview.end.timescale} (${preview.duration.value}/${preview.duration.timescale}) at revision ${afterLive.revision.id}`,
1697
2458
  };
1698
2459
  }
2460
+ function validatePictureInPictureRequest(request, sequenceStart, sequenceDuration, frameDuration, start, end) {
2461
+ if (compareRational(request.duration, zeroRational()) <= 0) {
2462
+ throw new Error("INVALID_OPERATION: native picture-in-picture duration must be positive");
2463
+ }
2464
+ if (!isFrameAligned(start, sequenceStart, frameDuration) || !isFrameAligned(request.duration, zeroRational(), frameDuration)) {
2465
+ throw new Error("INVALID_OPERATION: native picture-in-picture range must align to the sequence frame duration");
2466
+ }
2467
+ const sequenceEnd = addRational(sequenceStart, sequenceDuration);
2468
+ if (compareRational(start, sequenceStart) < 0 || compareRational(end, sequenceEnd) > 0) {
2469
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_RANGE_OUT_OF_BOUNDS: placement must be inside the active sequence");
2470
+ }
2471
+ if (!Number.isFinite(request.position.x) || !Number.isFinite(request.position.y)) {
2472
+ throw new Error("INVALID_OPERATION: native picture-in-picture position must be finite");
2473
+ }
2474
+ if (!Number.isFinite(request.scale) || request.scale <= 0) {
2475
+ throw new Error("INVALID_OPERATION: native picture-in-picture scale must be positive");
2476
+ }
2477
+ validatePictureInPictureStyle(request.crop, request.frame);
2478
+ }
2479
+ function validatePictureInPictureStyle(crop, frame) {
2480
+ if (crop) {
2481
+ const values = [crop.top, crop.right, crop.bottom, crop.left];
2482
+ if (!values.every((value) => Number.isFinite(value) && value >= 0 && value < 1)
2483
+ || crop.left + crop.right >= 1
2484
+ || crop.top + crop.bottom >= 1) {
2485
+ throw new Error("INVALID_OPERATION: native picture-in-picture crop must leave a visible rectangle");
2486
+ }
2487
+ }
2488
+ if (frame && (frame.style !== "solid" || !/^#[0-9a-f]{6}$/i.test(frame.color) || !Number.isFinite(frame.width) || frame.width < 0)) {
2489
+ throw new Error("INVALID_OPERATION: native picture-in-picture frame must be a solid six-digit hex color with nonnegative width");
2490
+ }
2491
+ }
2492
+ function validatePictureInPictureAnchor(anchor, live) {
2493
+ if (!anchor.identity) {
2494
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: native PIP requires a stable anchor occurrence identity");
2495
+ }
2496
+ if (anchor.sequenceId && live.sequence?.id !== anchor.sequenceId) {
2497
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: active sequence changed");
2498
+ }
2499
+ if (anchor.revision && live.revision.id !== anchor.revision) {
2500
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: playhead or timeline revision changed");
2501
+ }
2502
+ if (!anchor.start || !anchor.duration) {
2503
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: anchor occurrence has no exact timeline range");
2504
+ }
2505
+ }
2506
+ function validatePictureInPicturePreviewBinding(preview, live) {
2507
+ if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
2508
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
2509
+ }
2510
+ if (live.revision.id !== preview.revision) {
2511
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
2512
+ }
2513
+ validatePictureInPictureAnchor(preview.anchorOccurrence, live);
2514
+ }
2515
+ function parsePictureInPictureReadback(output) {
2516
+ const [xText, yText, scalePercentText, frameStyle = "", frameColor = "", frameWidthText = "", topText = "", rightText = "", bottomText = "", leftText = ""] = output.split(String.fromCharCode(31));
2517
+ const x = inspectorNumber(xText);
2518
+ const y = inspectorNumber(yText);
2519
+ const scalePercent = inspectorNumber(scalePercentText);
2520
+ if (![x, y, scalePercent].every(Number.isFinite) || scalePercent <= 0) {
2521
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Final Cut did not expose finite transform values");
2522
+ }
2523
+ const readback = {
2524
+ position: { x, y },
2525
+ scale: scalePercent / 100,
2526
+ };
2527
+ if (frameStyle || frameColor || frameWidthText) {
2528
+ const frameWidth = inspectorNumber(frameWidthText);
2529
+ if (!frameStyle || !frameColor || !Number.isFinite(frameWidth)) {
2530
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Final Cut returned an incomplete frame");
2531
+ }
2532
+ const frame = { style: frameStyle, color: frameColor, width: frameWidth };
2533
+ validatePictureInPictureStyle(undefined, frame);
2534
+ readback.frame = frame;
2535
+ }
2536
+ if (topText || rightText || bottomText || leftText) {
2537
+ const crop = {
2538
+ top: inspectorFraction(topText),
2539
+ right: inspectorFraction(rightText),
2540
+ bottom: inspectorFraction(bottomText),
2541
+ left: inspectorFraction(leftText),
2542
+ };
2543
+ if (![crop.top, crop.right, crop.bottom, crop.left].every(Number.isFinite)) {
2544
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Final Cut returned an incomplete crop");
2545
+ }
2546
+ validatePictureInPictureStyle(crop, undefined);
2547
+ readback.crop = crop;
2548
+ }
2549
+ return readback;
2550
+ }
2551
+ function inspectorNumber(value) {
2552
+ const normalized = (value ?? "").trim().replace(/,/g, "").replace(/%$/, "");
2553
+ const number = Number(normalized);
2554
+ return Number.isFinite(number) ? number : Number.NaN;
2555
+ }
2556
+ function inspectorFraction(value) {
2557
+ const normalized = (value ?? "").trim();
2558
+ const number = inspectorNumber(normalized);
2559
+ return normalized.endsWith("%") ? number / 100 : number;
2560
+ }
2561
+ function verifyNativePictureInPicture(preview, after, beforeLive, afterLive, observed, occurrence) {
2562
+ if (afterLive.revision.id === beforeLive.revision.id) {
2563
+ return { verified: false, detail: "Final Cut did not expose a new revision after native picture-in-picture placement" };
2564
+ }
2565
+ if (after.target.kind !== "selected-clip") {
2566
+ return { verified: false, detail: "Final Cut did not expose the inserted picture-in-picture clip as the selected timeline item" };
2567
+ }
2568
+ if (!occurrence.identity || after.target.identity !== occurrence.identity) {
2569
+ return { verified: false, detail: "Final Cut did not expose the inserted picture-in-picture occurrence identity" };
2570
+ }
2571
+ if (!pictureInPictureOccurrenceMatchesRange(occurrence, preview)) {
2572
+ return { verified: false, detail: "Final Cut did not read back the requested picture-in-picture timeline range" };
2573
+ }
2574
+ const observedName = after.target.name ?? "";
2575
+ if (observedName && !observedName.toLowerCase().includes(preview.media.name.toLowerCase())) {
2576
+ return { verified: false, detail: `Final Cut selected ${observedName}, not ${preview.media.name}` };
2577
+ }
2578
+ if (Math.abs(observed.position.x - preview.position.x) > 0.001 || Math.abs(observed.position.y - preview.position.y) > 0.001) {
2579
+ return { verified: false, detail: `Final Cut read back position ${observed.position.x},${observed.position.y}, expected ${preview.position.x},${preview.position.y}` };
2580
+ }
2581
+ if (Math.abs(observed.scale - preview.scale) > 0.0001) {
2582
+ return { verified: false, detail: `Final Cut read back scale ${observed.scale}, expected ${preview.scale}` };
2583
+ }
2584
+ if (preview.crop && JSON.stringify(observed.crop) !== JSON.stringify(preview.crop)) {
2585
+ return { verified: false, detail: "Final Cut did not read back the requested picture-in-picture crop" };
2586
+ }
2587
+ const observedFrame = observed.frame
2588
+ ? { ...observed.frame, color: observed.frame.color.toLowerCase() }
2589
+ : undefined;
2590
+ const previewFrame = preview.frame
2591
+ ? { ...preview.frame, color: preview.frame.color.toLowerCase() }
2592
+ : undefined;
2593
+ if (preview.frame && JSON.stringify(observedFrame) !== JSON.stringify(previewFrame)) {
2594
+ return { verified: false, detail: "Final Cut did not read back the requested picture-in-picture frame" };
2595
+ }
2596
+ if (!after.undoAvailable || !after.undoCommand) {
2597
+ return { verified: false, detail: "Final Cut did not expose an Undo command for native picture-in-picture placement" };
2598
+ }
2599
+ return {
2600
+ verified: true,
2601
+ detail: `Final Cut verified ${preview.media.name} occurrence ${occurrence.identity} at ${preview.start.value}/${preview.start.timescale}-${preview.end.value}/${preview.end.timescale} on the selected anchor's connected lane with transform readback at revision ${afterLive.revision.id}`,
2602
+ };
2603
+ }
2604
+ function pictureInPictureOccurrenceMatchesRange(occurrence, preview) {
2605
+ if (!occurrence.start || !occurrence.duration)
2606
+ return false;
2607
+ return compareRational(parseRationalString(occurrence.start, "picture-in-picture occurrence start"), preview.start) === 0
2608
+ && compareRational(parseRationalString(occurrence.duration, "picture-in-picture occurrence duration"), preview.duration) === 0;
2609
+ }
1699
2610
  function assertNativeTransitionAsset(asset) {
1700
2611
  if (!asset.id.trim() || !asset.name.trim() || !asset.identity.trim()) {
1701
2612
  throw new Error("TRANSITION_ASSET_NOT_FOUND: native transition asset identity is incomplete");
@@ -1730,6 +2641,92 @@ function validateTransitionEditPoint(before, after, duration, live) {
1730
2641
  }
1731
2642
  return beforeEnd;
1732
2643
  }
2644
+ function assertNativeMaskConfiguration(mask) {
2645
+ if (!mask || mask.mode !== "rectangle") {
2646
+ throw new Error("CAPABILITY_UNAVAILABLE: native Final Cut masking supports bounded Draw Mask only");
2647
+ }
2648
+ const { x, y, width, height } = mask.bounds;
2649
+ if (![x, y, width, height].every(Number.isFinite)
2650
+ || x < 0 || y < 0 || width <= 0 || height <= 0
2651
+ || x + width > 1 || y + height > 1) {
2652
+ throw new Error("INVALID_OPERATION: native Draw Mask bounds must be normalized");
2653
+ }
2654
+ }
2655
+ function validateMaskPreviewBinding(preview, live) {
2656
+ if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
2657
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
2658
+ }
2659
+ if (live.revision.id !== preview.revision) {
2660
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
2661
+ }
2662
+ if (preview.occurrence.sequenceId && live.sequence?.id !== preview.occurrence.sequenceId) {
2663
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: target occurrence sequence changed");
2664
+ }
2665
+ }
2666
+ function assertNativeMaskTarget(context, occurrence) {
2667
+ if (context.target.kind !== "selected-clip") {
2668
+ throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one timeline occurrence");
2669
+ }
2670
+ if (context.target.name && context.target.name !== occurrence.name) {
2671
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
2672
+ }
2673
+ if (!occurrence.nativeIdentity || !context.target.identity || context.target.identity !== occurrence.nativeIdentity) {
2674
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
2675
+ }
2676
+ }
2677
+ function parseNativeMaskReadback(output) {
2678
+ const marker = "FRAMEKIT_NATIVE_MASK_READBACK|";
2679
+ const markerIndex = output.lastIndexOf(marker);
2680
+ if (markerIndex < 0) {
2681
+ throw new Error("FINAL_CUT_NATIVE_MASK_READBACK_UNAVAILABLE: Final Cut did not return Draw Mask properties");
2682
+ }
2683
+ const [mode, xText, yText, widthText, heightText] = output
2684
+ .slice(markerIndex + marker.length)
2685
+ .split(/\r?\n/, 1)[0]
2686
+ .trim()
2687
+ .split("|");
2688
+ const values = [xText, yText, widthText, heightText].map((value) => Number(value));
2689
+ if (mode !== "rectangle" || values.some((value) => !Number.isFinite(value))) {
2690
+ throw new Error("FINAL_CUT_NATIVE_MASK_READBACK_UNAVAILABLE: Final Cut returned malformed Draw Mask properties");
2691
+ }
2692
+ const mask = {
2693
+ mode: "rectangle",
2694
+ bounds: { x: values[0], y: values[1], width: values[2], height: values[3] },
2695
+ };
2696
+ assertNativeMaskConfiguration(mask);
2697
+ return mask;
2698
+ }
2699
+ function verifyNativeMask(preview, after, beforeLive, afterLive, observedMask) {
2700
+ if (!afterLive.revision.id || afterLive.revision.id === beforeLive.revision.id) {
2701
+ return { verified: false, detail: "Final Cut did not expose a new revision after native Draw Mask placement" };
2702
+ }
2703
+ if (after.target.kind !== "selected-clip") {
2704
+ return { verified: false, detail: "Final Cut did not retain the masked occurrence as the selected timeline item" };
2705
+ }
2706
+ if (!preview.occurrence.nativeIdentity || after.target.identity !== preview.occurrence.nativeIdentity) {
2707
+ return { verified: false, detail: "Final Cut did not retain the exact masked timeline occurrence" };
2708
+ }
2709
+ if (!after.undoAvailable || !after.undoCommand) {
2710
+ return { verified: false, detail: "Final Cut did not expose an Undo command for native Draw Mask placement" };
2711
+ }
2712
+ if (!sameNativeMask(preview.mask, observedMask)) {
2713
+ return {
2714
+ verified: false,
2715
+ detail: `Final Cut read back Draw Mask ${JSON.stringify(observedMask)}, expected ${JSON.stringify(preview.mask)}`,
2716
+ };
2717
+ }
2718
+ return {
2719
+ verified: true,
2720
+ detail: `Final Cut verified Draw Mask bounds at revision ${afterLive.revision.id}`,
2721
+ };
2722
+ }
2723
+ function sameNativeMask(left, right) {
2724
+ return left.mode === right.mode
2725
+ && left.bounds.x === right.bounds.x
2726
+ && left.bounds.y === right.bounds.y
2727
+ && left.bounds.width === right.bounds.width
2728
+ && left.bounds.height === right.bounds.height;
2729
+ }
1733
2730
  function validateTransitionPreviewBinding(preview, live) {
1734
2731
  if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
1735
2732
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
@@ -1769,6 +2766,28 @@ function verifyNativeTransition(preview, after, beforeLive, afterLive, observedD
1769
2766
  detail: `Final Cut verified ${preview.asset.name} at ${preview.editPoint.value}/${preview.editPoint.timescale} for requested and observed duration ${observedDuration.value}/${observedDuration.timescale} at revision ${afterLive.revision.id}`,
1770
2767
  };
1771
2768
  }
2769
+ function parseTitleMatches(output) {
2770
+ const matches = new Map();
2771
+ for (const record of output.split(String.fromCharCode(30)).map((value) => value.trim()).filter(Boolean)) {
2772
+ const [name = "", identity = ""] = record.split(String.fromCharCode(31));
2773
+ if (!name || !identity) {
2774
+ throw new Error("FINAL_CUT_NATIVE_TITLE_ID_UNAVAILABLE: title browser did not expose stable identities");
2775
+ }
2776
+ const match = {
2777
+ id: `final-cut:title:${identity}`,
2778
+ kind: "title",
2779
+ name,
2780
+ vendor: "Final Cut Pro",
2781
+ identity,
2782
+ };
2783
+ matches.set(match.id, match);
2784
+ }
2785
+ return [...matches.values()].sort((left, right) => `${left.name}:${left.identity}`.localeCompare(`${right.name}:${right.identity}`));
2786
+ }
2787
+ function titleIdentityFromId(value) {
2788
+ const prefix = "final-cut:title:";
2789
+ return value.startsWith(prefix) ? value.slice(prefix.length) : undefined;
2790
+ }
1772
2791
  function parseTransitionMatches(output) {
1773
2792
  return output
1774
2793
  .split(String.fromCharCode(30))
@@ -1861,8 +2880,188 @@ function requireFrontmostAppleScript() {
1861
2880
  return `
1862
2881
  if not frontmost then error number -1719`;
1863
2882
  }
2883
+ function passiveTimelinePreflightScript() {
2884
+ return `
2885
+ -- FRAMEKIT_NATIVE_PASSIVE_PREFLIGHT
2886
+ using terms from application "System Events"
2887
+ on splitText(valueText, delimiter)
2888
+ set oldDelimiters to AppleScript's text item delimiters
2889
+ set AppleScript's text item delimiters to delimiter
2890
+ set parts to text items of valueText
2891
+ set AppleScript's text item delimiters to oldDelimiters
2892
+ return parts
2893
+ end splitText
2894
+
2895
+ on selectedTimelineItem(containerItem, depth, mainOrigin, mainSize)
2896
+ if depth > 6 then return ""
2897
+ set output to ""
2898
+ repeat with candidateRef in UI elements of containerItem
2899
+ try
2900
+ set candidate to contents of candidateRef
2901
+ set candidatePosition to position of candidate
2902
+ set candidateSize to size of candidate
2903
+ set candidateX to item 1 of candidatePosition
2904
+ set candidateY to item 2 of candidatePosition
2905
+ set candidateWidth to item 1 of candidateSize
2906
+ set candidateHeight to item 2 of candidateSize
2907
+ set timelineTop to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.62)
2908
+ set timelineLeft to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.20)
2909
+ if (candidateX + candidateWidth) is greater than timelineLeft and (candidateY + candidateHeight) is greater than timelineTop then
2910
+ set candidateSelected to false
2911
+ try
2912
+ set candidateSelected to (selected of candidate) is true
2913
+ end try
2914
+ if candidateSelected then
2915
+ set candidateRole to role of candidate as text
2916
+ set candidateName to ""
2917
+ try
2918
+ set candidateName to description of candidate as text
2919
+ end try
2920
+ if candidateName is "" then
2921
+ try
2922
+ set candidateName to value of candidate as text
2923
+ end try
2924
+ end if
2925
+ if candidateName is "missing value" then set candidateName to ""
2926
+ set candidateIdentity to ""
2927
+ try
2928
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
2929
+ end try
2930
+ return candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
2931
+ end if
2932
+ set output to my selectedTimelineItem(candidate, depth + 1, mainOrigin, mainSize)
2933
+ if output is not "" then return output
2934
+ end if
2935
+ on error
2936
+ -- Ignore inaccessible descendants and continue the bounded scan.
2937
+ end try
2938
+ end repeat
2939
+ return ""
2940
+ end selectedTimelineItem
2941
+ end using terms from
2942
+
2943
+ on preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, undoEnabled, bladeEnabled, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, undoCommand, selectedIdentity)
2944
+ return processFrontmost & (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) & timelineWindowAvailable & (ASCII character 31) & timelineFocused & (ASCII character 31) & focusTarget & (ASCII character 31) & focusAttempts & (ASCII character 31) & framekitWindowAvailable & (ASCII character 31) & framekitWindowMinimized & (ASCII character 31) & focusedWindowName & (ASCII character 31) & overlayBlocked & (ASCII character 31) & undoCommand & (ASCII character 31) & selectedIdentity
2945
+ end preflightResult
2946
+
2947
+ on focusTargetFor(roleName, descriptionText, elementName)
2948
+ if roleName is "AXTextField" or roleName is "AXSearchField" then return "text-field"
2949
+ if roleName is "AXSheet" or roleName is "AXDialog" then return "modal"
2950
+ set focusText to descriptionText & " " & elementName
2951
+ if focusText contains "Browser" or focusText contains "browser" or focusText contains "search" or focusText contains "Search" then return "browser"
2952
+ if roleName is "AXGroup" or roleName is "AXScrollArea" or roleName is "AXLayoutArea" or roleName is "AXCanvas" then return "timeline"
2953
+ if descriptionText contains "timeline" or descriptionText contains "Timeline" or elementName contains "timeline" or elementName contains "Timeline" then return "timeline"
2954
+ return "unknown"
2955
+ end focusTargetFor
2956
+
2957
+ tell application "System Events"
2958
+ tell process "Final Cut Pro"
2959
+ set processFrontmost to frontmost as text
2960
+ set frontWindowName to ""
2961
+ set timelineWindowAvailable to false
2962
+ set mainOrigin to {0, 0}
2963
+ set mainSize to {0, 0}
2964
+ try
2965
+ if (count of windows) > 0 then
2966
+ set frontWindow to front window
2967
+ set frontWindowName to name of frontWindow as text
2968
+ set timelineWindowAvailable to true
2969
+ set mainOrigin to position of frontWindow
2970
+ set mainSize to size of frontWindow
2971
+ end if
2972
+ end try
2973
+ set selectedCount to -1
2974
+ set selectedName to ""
2975
+ set selectedRole to ""
2976
+ set selectedIdentity to ""
2977
+ set selectionLookupAvailable to false
2978
+ try
2979
+ 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
2980
+ set selectionLookupAvailable to true
2981
+ set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
2982
+ if selectedRecord is not "" then
2983
+ set selectedFields to my splitText(selectedRecord, ASCII character 31)
2984
+ set selectedName to item 1 of selectedFields
2985
+ set selectedRole to item 2 of selectedFields
2986
+ set selectedIdentity to item 3 of selectedFields
2987
+ set selectedCount to 1
2988
+ end if
2989
+ end try
2990
+ if not selectionLookupAvailable then set selectedCount to -1
2991
+ set undoEnabled to false
2992
+ set undoCommand to ""
2993
+ try
2994
+ repeat with candidate in menu items of menu "Edit" of menu bar 1
2995
+ try
2996
+ set candidateName to name of candidate as text
2997
+ if candidateName starts with "Undo" and (enabled of candidate) is true then
2998
+ set undoEnabled to true
2999
+ set undoCommand to candidateName
3000
+ exit repeat
3001
+ end if
3002
+ end try
3003
+ end repeat
3004
+ end try
3005
+ set bladeEnabled to false
3006
+ try
3007
+ set bladeEnabled to enabled of menu item "Blade" of menu "Trim" of menu bar 1
3008
+ end try
3009
+ set framekitWindowAvailable to false
3010
+ set framekitWindowMinimized to false
3011
+ set overlayBlocked to false
3012
+ try
3013
+ repeat with candidateWindow in windows
3014
+ try
3015
+ set candidateWindowName to name of candidateWindow as text
3016
+ if candidateWindowName contains "Framekit" then
3017
+ set framekitWindowAvailable to true
3018
+ set framekitWindow to contents of candidateWindow
3019
+ try
3020
+ set framekitWindowMinimized to (value of attribute "AXMinimized" of framekitWindow) as boolean
3021
+ end try
3022
+ if not framekitWindowMinimized then set overlayBlocked to true
3023
+ exit repeat
3024
+ end if
3025
+ end try
3026
+ end repeat
3027
+ end try
3028
+ set focusedWindowName to ""
3029
+ set focusedName to ""
3030
+ set focusedRole to ""
3031
+ set focusedDescription to ""
3032
+ try
3033
+ set focusedWindow to value of attribute "AXFocusedWindow"
3034
+ set focusedWindowName to name of focusedWindow as text
3035
+ end try
3036
+ try
3037
+ set focusedElement to value of attribute "AXFocusedUIElement"
3038
+ set focusedName to name of focusedElement as text
3039
+ set focusedRole to role of focusedElement as text
3040
+ set focusedDescription to description of focusedElement as text
3041
+ end try
3042
+ set focusTarget to my focusTargetFor(focusedRole, focusedDescription, focusedName)
3043
+ set timelineFocused to processFrontmost is "true" and focusTarget is "timeline"
3044
+ return my preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, undoEnabled, bladeEnabled, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, 0, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, undoCommand, selectedIdentity)
3045
+ end tell
3046
+ end tell`;
3047
+ }
1864
3048
  function timelinePreflightScript() {
1865
3049
  return `
3050
+ on findInspectorField(fieldLabel)
3051
+ tell application "System Events"
3052
+ tell process "Final Cut Pro"
3053
+ repeat with candidate in text fields of front window
3054
+ try
3055
+ set candidateDescription to description of candidate as text
3056
+ set candidateName to name of candidate as text
3057
+ if candidateDescription contains fieldLabel or candidateName contains fieldLabel then return candidate
3058
+ end try
3059
+ end repeat
3060
+ end tell
3061
+ end tell
3062
+ return missing value
3063
+ end findInspectorField
3064
+
1866
3065
  tell application "System Events"
1867
3066
  tell process "Final Cut Pro"
1868
3067
  set frontmost to true
@@ -2255,7 +3454,7 @@ function searchMediaScript(query) {
2255
3454
  set value of searchField to searchQuery
2256
3455
  key code 36
2257
3456
  delay 0.5
2258
- set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, false, {}, "root")
3457
+ set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, browserRootContext, {}, "root")
2259
3458
  return output
2260
3459
  end tell
2261
3460
  end tell`;
@@ -2277,7 +3476,7 @@ function selectedBrowserMediaScript() {
2277
3476
  set seenSourceIdentities to {}
2278
3477
  set browserRoot to mainWindow
2279
3478
  try
2280
- set browserSearchResult to my findBrowserSearchControl(mainWindow, 0, origin, size of mainWindow)
3479
+ set browserSearchResult to my findBrowserSearchControl(mainWindow, 0, false, missing value)
2281
3480
  if browserSearchResult is not missing value then set browserRoot to item 2 of browserSearchResult
2282
3481
  end try
2283
3482
  try
@@ -2324,62 +3523,20 @@ end tell`;
2324
3523
  }
2325
3524
  function browserSearchFieldScript() {
2326
3525
  return `
2327
- set origin to position of mainWindow
2328
- set windowSize to size of mainWindow
2329
3526
  set searchFieldFound to false
2330
3527
  set searchField to missing value
2331
3528
  set searchButton to missing value
2332
- set browserRoot to mainWindow
2333
- -- The Transitions browser may already be open. Prefer the bounded
2334
- -- Browser search control so its Effects Library field cannot capture a
2335
- -- media query.
2336
- try
2337
- set searchField to UI element 4 of UI element 5 of UI element 3 of UI element 1 of UI element 2 of UI element 1 of UI element 1 of UI element 1 of mainWindow
2338
- set searchFieldFound to true
2339
- on error
2340
- set searchField to missing value
2341
- end try
3529
+ set searchButtonIsToggle to false
3530
+ set browserRootContext to false
2342
3531
  try
2343
- if not searchFieldFound then
2344
- set focusedCandidate to value of attribute "AXFocusedUIElement"
2345
- set focusedRole to role of focusedCandidate as text
2346
- set focusedDescription to ""
2347
- try
2348
- set focusedDescription to description of focusedCandidate as text
2349
- end try
2350
- if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) and my browserSearchCandidateVisible(focusedCandidate, origin, windowSize) then
2351
- set searchField to focusedCandidate
2352
- set searchFieldFound to true
2353
- end if
3532
+ set searchControlResult to my findBrowserSearchToggle(mainWindow, 0, false, missing value)
3533
+ if searchControlResult is missing value then
3534
+ if my revealBrowser(mainWindow, 0) then delay 0.5
3535
+ set searchControlResult to my findBrowserSearchToggle(mainWindow, 0, false, missing value)
2354
3536
  end if
2355
3537
  end try
2356
- if not searchFieldFound then
2357
- repeat with searchOffset in {368, 400, 340, 561, 531, 501}
2358
- repeat with searchY in {52, 38}
2359
- try
2360
- click at {(item 1 of origin) + (searchOffset as integer), (item 2 of origin) + (searchY as integer)}
2361
- delay 0.15
2362
- set focusedCandidate to value of attribute "AXFocusedUIElement"
2363
- set focusedRole to role of focusedCandidate as text
2364
- set focusedDescription to ""
2365
- try
2366
- set focusedDescription to description of focusedCandidate as text
2367
- end try
2368
- if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) then
2369
- set searchField to focusedCandidate
2370
- set searchFieldFound to true
2371
- exit repeat
2372
- end if
2373
- end try
2374
- end repeat
2375
- if searchFieldFound then exit repeat
2376
- end repeat
2377
- end if
2378
- try
2379
- if my revealBrowser(mainWindow, 0) then delay 0.5
2380
- end try
2381
3538
  try
2382
- set searchControlResult to my findBrowserSearchControl(mainWindow, 0, origin, windowSize)
3539
+ if searchControlResult is missing value then set searchControlResult to my findBrowserSearchControl(mainWindow, 0, false, missing value)
2383
3540
  if searchControlResult is not missing value then
2384
3541
  set searchControl to item 1 of searchControlResult
2385
3542
  set browserRoot to item 2 of searchControlResult
@@ -2389,53 +3546,51 @@ function browserSearchFieldScript() {
2389
3546
  set searchFieldFound to true
2390
3547
  else if searchRole is "AXButton" then
2391
3548
  set searchButton to searchControl
3549
+ set searchButtonIsToggle to my browserSearchToggle(searchControl)
3550
+ set browserRootContext to searchButtonIsToggle
2392
3551
  end if
2393
3552
  end if
2394
3553
  end try
2395
- if not searchFieldFound then
2396
- try
2397
- set searchControlResult to my findBrowserSearchControl(mainWindow, 0, origin, windowSize)
2398
- if searchControlResult is not missing value then
2399
- set searchControl to item 1 of searchControlResult
2400
- set browserRoot to item 2 of searchControlResult
2401
- set searchRole to role of searchControl as text
2402
- if searchRole is "AXSearchField" or searchRole is "AXTextField" then
2403
- set searchField to searchControl
2404
- set searchFieldFound to true
2405
- else if searchRole is "AXButton" then
2406
- set searchButton to searchControl
2407
- end if
2408
- end if
2409
- end try
2410
- end if
2411
- if not searchFieldFound and searchButton is missing value then
3554
+ if not searchFieldFound and searchButton is not missing value then
2412
3555
  try
2413
- set directSearchButton to UI element 3 of UI element 3 of UI element 1 of UI element 2 of UI element 1 of UI element 1 of UI element 1 of mainWindow
2414
- set directSearchDescription to description of directSearchButton as text
2415
- if directSearchDescription contains "search" or directSearchDescription contains "Search" then
2416
- set searchButton to directSearchButton
3556
+ if searchButtonIsToggle then
3557
+ try
3558
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
3559
+ set focusedRole to role of focusedCandidate as text
3560
+ set focusedDescription to description of focusedCandidate as text
3561
+ if (focusedRole is "AXSearchField" or focusedRole is "AXTextField") and (focusedDescription contains "search" or focusedDescription contains "Search") then
3562
+ set searchField to focusedCandidate
3563
+ set searchFieldFound to true
3564
+ end if
3565
+ end try
2417
3566
  end if
2418
- end try
2419
- end if
2420
- if not searchFieldFound then
2421
- if searchButton is not missing value then
2422
- try
3567
+ if not searchFieldFound then
2423
3568
  perform action "AXPress" of searchButton
2424
3569
  delay 0.2
2425
- set focusedCandidate to value of attribute "AXFocusedUIElement"
2426
- set focusedRole to role of focusedCandidate as text
2427
- set focusedDescription to ""
2428
3570
  try
2429
- set focusedDescription to description of focusedCandidate as text
3571
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
3572
+ set focusedRole to role of focusedCandidate as text
3573
+ if focusedRole is "AXSearchField" or focusedRole is "AXTextField" then
3574
+ set searchField to focusedCandidate
3575
+ set searchFieldFound to true
3576
+ end if
2430
3577
  end try
2431
- if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) then
2432
- set searchField to focusedCandidate
2433
- set searchFieldFound to true
3578
+ end if
3579
+ if not searchFieldFound then
3580
+ set searchControlResult to my findBrowserSearchControl(mainWindow, 0, false, missing value)
3581
+ if searchControlResult is not missing value then
3582
+ set searchControl to item 1 of searchControlResult
3583
+ set browserRoot to item 2 of searchControlResult
3584
+ set searchRole to role of searchControl as text
3585
+ if searchRole is "AXSearchField" or searchRole is "AXTextField" then
3586
+ set searchField to searchControl
3587
+ set searchFieldFound to true
3588
+ end if
2434
3589
  end if
2435
- end try
2436
- end if
3590
+ end if
3591
+ end try
2437
3592
  end if
2438
- if not searchFieldFound then error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser search field was not found through Accessibility or coordinate fallback"
3593
+ if not searchFieldFound then error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser search control was not exposed by Accessibility"
2439
3594
  set searchRole to role of searchField as text
2440
3595
  if searchRole is not "AXTextField" and searchRole is not "AXSearchField" then error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser search field was not hit"
2441
3596
  try
@@ -2449,28 +3604,179 @@ function browserSearchFieldScript() {
2449
3604
  function browserSearchControlFinderScript() {
2450
3605
  return `
2451
3606
  using terms from application "System Events"
2452
- on browserSearchCandidateVisible(candidate, mainOrigin, mainSize)
3607
+ on browserSearchContainer(candidate)
2453
3608
  try
2454
- set candidatePosition to position of candidate
2455
- set candidateX to item 1 of candidatePosition
2456
- set candidateY to item 2 of candidatePosition
2457
- return candidateX is less than ((item 1 of mainOrigin) + ((item 1 of mainSize) * 0.60)) and candidateY is less than ((item 2 of mainOrigin) + ((item 2 of mainSize) * 0.60))
3609
+ set candidateRole to role of candidate as text
3610
+ if candidateRole is not "AXGroup" and candidateRole is not "AXScrollArea" and candidateRole is not "AXSplitGroup" and candidateRole is not "AXLayoutArea" and candidateRole is not "AXToolbar" and candidateRole is not "AXList" and candidateRole is not "AXOutline" and candidateRole is not "AXCollection" and candidateRole is not "AXRadioGroup" then return false
3611
+ set candidateText to ""
3612
+ try
3613
+ set candidateText to description of candidate as text
3614
+ end try
3615
+ if candidateText is "" then
3616
+ try
3617
+ set candidateText to name of candidate as text
3618
+ end try
3619
+ end if
3620
+ if candidateText is "" then
3621
+ try
3622
+ set candidateText to value of candidate as text
3623
+ end try
3624
+ end if
3625
+ return candidateText contains "Browser" or candidateText contains "browser" or candidateText contains "Events" or candidateText contains "events" or candidateText contains "Event" or candidateText contains "event"
3626
+ on error
3627
+ return false
3628
+ end try
3629
+ end browserSearchContainer
3630
+
3631
+ on browserSearchHasMediaMarker(containerItem, depth)
3632
+ if depth > 8 then return false
3633
+ set candidateRole to ""
3634
+ set candidateText to ""
3635
+ try
3636
+ set candidateRole to role of containerItem as text
3637
+ set candidateText to description of containerItem as text
3638
+ end try
3639
+ if candidateText is "" then
3640
+ try
3641
+ set candidateText to name of containerItem as text
3642
+ end try
3643
+ end if
3644
+ if candidateText is "" then
3645
+ try
3646
+ set candidateText to value of containerItem as text
3647
+ end try
3648
+ end if
3649
+ if candidateRole is "AXGroup" or candidateRole is "AXScrollArea" or candidateRole is "AXSplitGroup" or candidateRole is "AXLayoutArea" or candidateRole is "AXToolbar" or candidateRole is "AXList" or candidateRole is "AXOutline" or candidateRole is "AXCollection" or candidateRole is "AXRadioGroup" then
3650
+ if candidateText contains "Browser" or candidateText contains "browser" or candidateText contains "Events" or candidateText contains "events" or candidateText contains "Event" or candidateText contains "event" or candidateText contains "Organizer" or candidateText contains "organizer" or candidateText contains "film" or candidateText contains "Film" then return true
3651
+ try
3652
+ repeat with candidateRef in UI elements of containerItem
3653
+ if my browserSearchHasMediaMarker(contents of candidateRef, depth + 1) then return true
3654
+ end repeat
3655
+ end try
3656
+ end if
3657
+ return false
3658
+ end browserSearchHasMediaMarker
3659
+
3660
+ on browserSearchToggle(candidate)
3661
+ try
3662
+ set candidateRole to role of candidate as text
3663
+ if candidateRole is not "AXButton" then return false
3664
+ set candidateText to ""
3665
+ try
3666
+ set candidateText to description of candidate as text
3667
+ end try
3668
+ if candidateText is "" then
3669
+ try
3670
+ set candidateText to name of candidate as text
3671
+ end try
3672
+ end if
3673
+ if candidateText is "" then
3674
+ try
3675
+ set candidateText to value of candidate as text
3676
+ end try
3677
+ end if
3678
+ return candidateText contains "toggle search bar" or candidateText contains "Toggle Search Bar"
2458
3679
  on error
2459
3680
  return false
2460
3681
  end try
2461
- end browserSearchCandidateVisible
3682
+ end browserSearchToggle
3683
+
3684
+ on browserSearchRootForToggle(browserContainer)
3685
+ set mediaRoot to my findBrowserMediaRoot(browserContainer, 0)
3686
+ if mediaRoot is not missing value then return mediaRoot
3687
+ return browserContainer
3688
+ end browserSearchRootForToggle
3689
+
3690
+ on findBrowserMediaRoot(containerItem, depth)
3691
+ if depth > 8 then return missing value
3692
+ set candidateRole to ""
3693
+ set candidateText to ""
3694
+ try
3695
+ set candidateRole to role of containerItem as text
3696
+ set candidateText to description of containerItem as text
3697
+ end try
3698
+ if candidateText is "" then
3699
+ try
3700
+ set candidateText to name of containerItem as text
3701
+ end try
3702
+ end if
3703
+ if candidateText is "" then
3704
+ try
3705
+ set candidateText to value of containerItem as text
3706
+ end try
3707
+ end if
3708
+ if candidateRole is "AXScrollArea" or candidateRole is "AXOutline" then
3709
+ if candidateText contains "Organizer" or candidateText contains "organizer" or candidateText contains "film" or candidateText contains "Film" then return containerItem
3710
+ end if
3711
+ repeat with candidateRef in UI elements of containerItem
3712
+ try
3713
+ set candidate to contents of candidateRef
3714
+ set nestedRoot to my findBrowserMediaRoot(candidate, depth + 1)
3715
+ if nestedRoot is not missing value then return nestedRoot
3716
+ end try
3717
+ end repeat
3718
+ return missing value
3719
+ end findBrowserMediaRoot
2462
3720
 
2463
- on findBrowserSearchControl(containerItem, depth, mainOrigin, mainSize)
3721
+ on findBrowserSearchToggle(containerItem, depth, inheritedBrowserContext, inheritedBrowserRoot)
2464
3722
  if depth > 12 then return missing value
3723
+ set browserContext to inheritedBrowserContext
3724
+ set browserRoot to inheritedBrowserRoot
3725
+ if my browserSearchContainer(containerItem) then
3726
+ set browserContext to true
3727
+ set browserRoot to containerItem
3728
+ end if
3729
+ set candidateItems to UI elements of containerItem
3730
+ set candidateCount to count of candidateItems
3731
+ repeat with candidateIndex from 1 to candidateCount
3732
+ try
3733
+ set candidate to contents of item candidateIndex of candidateItems
3734
+ set candidateRole to role of candidate as text
3735
+ set candidateBrowserContext to browserContext
3736
+ set candidateBrowserRoot to browserRoot
3737
+ if my browserSearchContainer(candidate) then
3738
+ set candidateBrowserContext to true
3739
+ set candidateBrowserRoot to candidate
3740
+ end if
3741
+ set candidateIsToggle to my browserSearchToggle(candidate)
3742
+ if candidateBrowserContext and candidateIsToggle then return {candidate, my browserSearchRootForToggle(candidateBrowserRoot)}
3743
+ if candidateIsToggle and my browserSearchHasMediaMarker(containerItem, 0) then return {candidate, my browserSearchRootForToggle(containerItem)}
3744
+ if candidateRole is "AXGroup" or candidateRole is "AXSplitGroup" or candidateRole is "AXLayoutArea" or candidateRole is "AXToolbar" or candidateRole is "AXScrollArea" or candidateRole is "AXList" or candidateRole is "AXOutline" or candidateRole is "AXCollection" or candidateRole is "AXRadioGroup" then
3745
+ set nestedCandidate to my findBrowserSearchToggle(candidate, depth + 1, candidateBrowserContext, candidateBrowserRoot)
3746
+ if nestedCandidate is not missing value then return nestedCandidate
3747
+ end if
3748
+ on error
3749
+ end try
3750
+ end repeat
3751
+ return missing value
3752
+ end findBrowserSearchToggle
3753
+
3754
+ on findBrowserSearchControl(containerItem, depth, inheritedBrowserContext, inheritedBrowserRoot)
3755
+ if depth > 12 then return missing value
3756
+ set browserContext to inheritedBrowserContext
3757
+ set browserRoot to inheritedBrowserRoot
3758
+ if my browserSearchContainer(containerItem) then
3759
+ set browserContext to true
3760
+ set browserRoot to containerItem
3761
+ end if
2465
3762
  set candidateItems to UI elements of containerItem
2466
3763
  repeat with candidateIndex in my orderedChildIndices(containerItem)
2467
3764
  try
2468
3765
  set candidate to item (contents of candidateIndex) of candidateItems
3766
+ set candidateBrowserContext to browserContext
3767
+ set candidateBrowserRoot to browserRoot
3768
+ if my browserSearchContainer(candidate) then
3769
+ set candidateBrowserContext to true
3770
+ set candidateBrowserRoot to candidate
3771
+ end if
3772
+ set candidateIsToggle to my browserSearchToggle(candidate)
3773
+ if candidateBrowserContext and candidateIsToggle then return {candidate, my browserSearchRootForToggle(candidateBrowserRoot)}
3774
+ if candidateIsToggle and my browserSearchHasMediaMarker(containerItem, 0) then return {candidate, my browserSearchRootForToggle(containerItem)}
2469
3775
  set candidateRole to role of candidate as text
2470
- if candidateRole is "AXSearchField" and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
2471
- return {candidate, containerItem}
3776
+ if candidateBrowserContext and candidateRole is "AXSearchField" then
3777
+ return {candidate, candidateBrowserRoot}
2472
3778
  end if
2473
- if candidateRole is "AXTextField" then
3779
+ if candidateBrowserContext and candidateRole is "AXTextField" then
2474
3780
  set candidateName to ""
2475
3781
  set candidateDescription to ""
2476
3782
  try
@@ -2479,19 +3785,19 @@ function browserSearchControlFinderScript() {
2479
3785
  try
2480
3786
  set candidateDescription to description of candidate as text
2481
3787
  end try
2482
- if (candidateName contains "search" or candidateName contains "Search" or candidateDescription contains "search" or candidateDescription contains "Search") and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
2483
- return {candidate, containerItem}
3788
+ if candidateName contains "search" or candidateName contains "Search" or candidateDescription contains "search" or candidateDescription contains "Search" then
3789
+ return {candidate, candidateBrowserRoot}
2484
3790
  end if
2485
3791
  end if
2486
- if candidateRole is "AXButton" then
3792
+ if candidateBrowserContext and candidateRole is "AXButton" then
2487
3793
  set candidateDescription to description of candidate as text
2488
- if (candidateDescription contains "search" or candidateDescription contains "Search") and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
2489
- return {candidate, containerItem}
3794
+ if candidateDescription contains "search" or candidateDescription contains "Search" then
3795
+ return {candidate, candidateBrowserRoot}
2490
3796
  end if
2491
3797
  end if
2492
3798
  end try
2493
3799
  try
2494
- set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1, mainOrigin, mainSize)
3800
+ set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1, candidateBrowserContext, candidateBrowserRoot)
2495
3801
  if nestedCandidate is not missing value then
2496
3802
  return nestedCandidate
2497
3803
  end if
@@ -2554,6 +3860,7 @@ function browserMediaTraversalScript() {
2554
3860
  end splitText
2555
3861
 
2556
3862
  on mediaContainer(containerItem, inheritedContext)
3863
+ if inheritedContext then return true
2557
3864
  set containerText to ""
2558
3865
  try
2559
3866
  set containerText to description of containerItem as text
@@ -2574,7 +3881,7 @@ function browserMediaTraversalScript() {
2574
3881
 
2575
3882
  on accessibilityMediaIdentity(candidate, candidateName, candidateRole, mediaContext, browserPath)
2576
3883
  if not mediaContext or candidateName is "" then return ""
2577
- if candidateRole is not "AXGroup" and candidateRole is not "AXBrowserMedia" and candidateRole is not "AXRow" and candidateRole is not "AXCell" then
3884
+ if candidateRole is not "AXGroup" and candidateRole is not "AXBrowserMedia" and candidateRole is not "AXRow" and candidateRole is not "AXCell" and candidateRole is not "AXTextField" then
2578
3885
  return ""
2579
3886
  end if
2580
3887
  return "fcp-ax://browser/" & browserPath & "|" & candidateRole & "|" & candidateName
@@ -2582,6 +3889,7 @@ function browserMediaTraversalScript() {
2582
3889
 
2583
3890
  on browserMediaRole(candidateRole, mediaContext, candidateSelected, candidateSourceIdentity)
2584
3891
  if candidateRole is "AXBrowserMedia" or candidateRole is "AXRow" or candidateRole is "AXCell" then return true
3892
+ if candidateRole is "AXTextField" then return mediaContext
2585
3893
  if candidateRole is "AXButton" then return mediaContext and candidateSourceIdentity is not ""
2586
3894
  if candidateRole is "AXGroup" or candidateRole is "AXStaticText" or candidateRole is "AXImage" then return mediaContext or (candidateSelected and candidateSourceIdentity is not "")
2587
3895
  return false
@@ -2597,51 +3905,64 @@ function browserMediaTraversalScript() {
2597
3905
  end browserRegion
2598
3906
 
2599
3907
  on collectBrowserMedia(containerItem, depth, searchQuery, origin, inheritedContext, seenIdentities, browserPath)
2600
- if depth > 12 then return ""
3908
+ set maxDepth to 12
3909
+ if inheritedContext then set maxDepth to 6
3910
+ if depth > maxDepth then return ""
2601
3911
  set output to ""
2602
3912
  set mediaContext to my mediaContainer(containerItem, inheritedContext)
2603
3913
  tell application "System Events"
2604
3914
  try
2605
3915
  set candidateItems to UI elements of containerItem
2606
- repeat with candidateIndex from 1 to (count of candidateItems)
2607
- try
2608
- set candidate to contents of item candidateIndex of candidateItems
2609
- set candidatePath to browserPath & "/" & (candidateIndex as text)
2610
- set candidateRole to role of candidate as text
2611
- set candidateName to ""
2612
- try
2613
- set candidateName to value of candidate as text
2614
- end try
2615
- if candidateName is "missing value" then set candidateName to ""
2616
- if candidateName is "" then
2617
- try
2618
- set candidateName to name of candidate as text
2619
- end try
2620
- end if
2621
- if candidateName is "missing value" then set candidateName to ""
2622
- if candidateName is "" then
3916
+ repeat with candidateIndex from 1 to (count of candidateItems)
3917
+ try
3918
+ set candidate to contents of item candidateIndex of candidateItems
3919
+ set candidatePath to browserPath & "/" & (candidateIndex as text)
3920
+ set candidateRole to role of candidate as text
3921
+ set candidateMediaContext to my mediaContainer(candidate, mediaContext)
3922
+ set candidateName to ""
3923
+ set candidateMayBeMedia to candidateRole is "AXBrowserMedia" or candidateRole is "AXRow" or candidateRole is "AXCell" or candidateRole is "AXButton" or candidateRole is "AXGroup" or candidateRole is "AXStaticText" or candidateRole is "AXImage" or candidateRole is "AXTextField"
3924
+ set candidateSourceIdentity to ""
3925
+ set candidateSelected to false
3926
+ set isBrowserMedia to false
3927
+ if candidateMayBeMedia then
2623
3928
  try
2624
- set candidateName to description of candidate as text
3929
+ set candidateName to value of candidate as text
2625
3930
  end try
2626
- end if
2627
- if candidateName is "missing value" then set candidateName to ""
2628
- set candidateSelected to false
2629
- try
2630
- set candidateSelected to (selected of candidate) is true
2631
- end try
2632
- set candidateSourceIdentity to ""
2633
- try
2634
- set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
2635
- end try
2636
- set candidatePosition to position of candidate
2637
- set candidateMediaContext to my mediaContainer(candidate, mediaContext)
2638
- set isBrowserMedia to my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity)
2639
- set inBrowserRegion to my browserRegion(candidatePosition, origin, candidateMediaContext)
2640
- if candidateSourceIdentity is "" and isBrowserMedia then set candidateSourceIdentity to my accessibilityMediaIdentity(candidate, candidateName, candidateRole, candidateMediaContext, candidatePath)
2641
- if candidateName is not "" and candidateSourceIdentity is not "" and isBrowserMedia and inBrowserRegion and candidateName contains searchQuery then
2642
- if seenIdentities does not contain candidateSourceIdentity then
2643
- set end of seenIdentities to candidateSourceIdentity
2644
- set output to output & candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateSourceIdentity & (ASCII character 31) & candidateSourceIdentity & (ASCII character 30)
3931
+ if candidateName is "missing value" then set candidateName to ""
3932
+ if candidateName is "" then
3933
+ try
3934
+ set candidateName to name of candidate as text
3935
+ end try
3936
+ end if
3937
+ if candidateName is "missing value" then set candidateName to ""
3938
+ if candidateName is "" then
3939
+ try
3940
+ set candidateName to description of candidate as text
3941
+ end try
3942
+ end if
3943
+ if candidateName is "missing value" then set candidateName to ""
3944
+ if candidateName contains searchQuery then
3945
+ try
3946
+ set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
3947
+ end try
3948
+ if not candidateMediaContext then
3949
+ try
3950
+ set candidateSelected to (selected of candidate) is true
3951
+ end try
3952
+ end if
3953
+ set isBrowserMedia to my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity)
3954
+ set inBrowserRegion to candidateMediaContext
3955
+ if not inBrowserRegion then
3956
+ set candidatePosition to position of candidate
3957
+ set inBrowserRegion to my browserRegion(candidatePosition, origin, candidateMediaContext)
3958
+ end if
3959
+ if candidateSourceIdentity is "" and isBrowserMedia then set candidateSourceIdentity to my accessibilityMediaIdentity(candidate, candidateName, candidateRole, candidateMediaContext, candidatePath)
3960
+ if candidateSourceIdentity is not "" and isBrowserMedia and inBrowserRegion then
3961
+ if seenIdentities does not contain candidateSourceIdentity then
3962
+ set end of seenIdentities to candidateSourceIdentity
3963
+ set output to output & candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateSourceIdentity & (ASCII character 31) & candidateSourceIdentity & (ASCII character 30)
3964
+ end if
3965
+ end if
2645
3966
  end if
2646
3967
  end if
2647
3968
  set output to output & my collectBrowserMedia(candidate, depth + 1, searchQuery, origin, candidateMediaContext, seenIdentities, candidatePath)
@@ -2987,7 +4308,12 @@ function locateOccurrenceScript(match, scanAll) {
2987
4308
  end repeat
2988
4309
  if candidateStart is not "" and candidateDuration is not "" then
2989
4310
  set candidateOffset to ((item 1 of candidatePosition) + 10) - (item 1 of mainOrigin)
2990
- set output to output & targetName & (ASCII character 31) & candidateRole & (ASCII character 31) & sourceIdentity & (ASCII character 31) & (candidateOffset as text) & (ASCII character 31) & candidateStart & (ASCII character 31) & candidateDuration & (ASCII character 30)
4311
+ set candidateIdentity to ""
4312
+ try
4313
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
4314
+ end try
4315
+ if candidateIdentity is "" then error "FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: timeline clip has no AXIdentifier"
4316
+ set output to output & targetName & (ASCII character 31) & candidateRole & (ASCII character 31) & sourceIdentity & (ASCII character 31) & (candidateOffset as text) & (ASCII character 31) & candidateStart & (ASCII character 31) & candidateDuration & (ASCII character 31) & candidateIdentity & (ASCII character 30)
2991
4317
  end if
2992
4318
  else
2993
4319
  set shouldDescend to false
@@ -3033,21 +4359,6 @@ function locateOccurrenceScript(match, scanAll) {
3033
4359
  end tell
3034
4360
  end tell`;
3035
4361
  }
3036
- async function selectTimelineOccurrence(executor, timelineOffset) {
3037
- const coordinates = (await executor(timelineSelectionCoordinatesScript())).split("|").map(Number);
3038
- const [originX, originY, windowWidth, windowHeight] = coordinates;
3039
- if (!Number.isFinite(originX) || !Number.isFinite(originY) || !Number.isFinite(windowWidth) || !Number.isFinite(windowHeight)) {
3040
- throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut window coordinates");
3041
- }
3042
- const x = Math.round(originX + timelineOffset);
3043
- const y = Math.round(originY + (windowHeight * 0.77));
3044
- try {
3045
- await execFile("swift", ["-e", nativeMouseSelectionSource(x, y)]);
3046
- }
3047
- catch (error) {
3048
- throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline selection failed: ${String(error)}`);
3049
- }
3050
- }
3051
4362
  function timelineSelectionCoordinatesScript() {
3052
4363
  return `
3053
4364
  tell application "System Events"
@@ -3484,6 +4795,73 @@ function applyTransitionScript(duration, frameDuration) {
3484
4795
  end tell
3485
4796
  end tell`;
3486
4797
  }
4798
+ function applyMaskScript(mask) {
4799
+ const { x, y, width, height } = mask.bounds;
4800
+ const values = [x, y, width, height].map((value) => value.toString());
4801
+ return `
4802
+ tell application "System Events"
4803
+ tell process "Final Cut Pro"
4804
+ ${requireFrontmostAppleScript()}
4805
+ -- Apply native Draw Mask to the already selected timeline occurrence.
4806
+ click menu item "Show Effects" of menu "Window" of menu bar 1
4807
+ delay 0.3
4808
+ set effectSearchField to missing value
4809
+ repeat with candidate in entire contents of front window
4810
+ try
4811
+ set candidateRole to role of candidate as text
4812
+ set candidateDescription to description of candidate as text
4813
+ if (candidateRole is "AXTextField" or candidateRole is "AXSearchField") and (candidateDescription contains "search" or candidateDescription contains "Search") then
4814
+ set effectSearchField to candidate
4815
+ exit repeat
4816
+ end if
4817
+ end try
4818
+ end repeat
4819
+ if effectSearchField is missing value then error "FINAL_CUT_NATIVE_MASK_UNAVAILABLE: Final Cut did not expose the Effects search field"
4820
+ set value of effectSearchField to "Draw Mask"
4821
+ key code 36
4822
+ delay 0.3
4823
+ set drawMaskEffect to missing value
4824
+ repeat with candidate in entire contents of front window
4825
+ try
4826
+ set candidateName to name of candidate as text
4827
+ if candidateName is "Draw Mask" then
4828
+ set drawMaskEffect to candidate
4829
+ exit repeat
4830
+ end if
4831
+ end try
4832
+ end repeat
4833
+ if drawMaskEffect is missing value then error "FINAL_CUT_NATIVE_MASK_UNAVAILABLE: Final Cut did not expose the Draw Mask effect"
4834
+ perform action "AXPress" of drawMaskEffect
4835
+ delay 0.4
4836
+ -- Draw Mask's normalized inspector fields must be both writable and readable.
4837
+ set positionXField to missing value
4838
+ set positionYField to missing value
4839
+ set widthField to missing value
4840
+ set heightField to missing value
4841
+ repeat with candidate in entire contents of front window
4842
+ try
4843
+ set candidateName to name of candidate as text
4844
+ if candidateName contains "Position X" then set positionXField to candidate
4845
+ if candidateName contains "Position Y" then set positionYField to candidate
4846
+ if candidateName contains "Width" then set widthField to candidate
4847
+ if candidateName contains "Height" then set heightField to candidate
4848
+ end try
4849
+ end repeat
4850
+ if positionXField is missing value or positionYField is missing value or widthField is missing value or heightField is missing value then error "FINAL_CUT_NATIVE_MASK_READBACK_UNAVAILABLE: Draw Mask inspector fields are not accessible"
4851
+ set value of positionXField to ${appleScriptString(values[0])}
4852
+ set value of positionYField to ${appleScriptString(values[1])}
4853
+ set value of widthField to ${appleScriptString(values[2])}
4854
+ set value of heightField to ${appleScriptString(values[3])}
4855
+ key code 36
4856
+ delay 0.2
4857
+ set observedX to value of positionXField as text
4858
+ set observedY to value of positionYField as text
4859
+ set observedWidth to value of widthField as text
4860
+ set observedHeight to value of heightField as text
4861
+ return "FRAMEKIT_NATIVE_MASK_READBACK|rectangle|" & observedX & "|" & observedY & "|" & observedWidth & "|" & observedHeight
4862
+ end tell
4863
+ end tell`;
4864
+ }
3487
4865
  function occurrenceRangeEndpointScript(timelineOffset, endpoint) {
3488
4866
  const shortcut = endpoint === "start" ? "i" : "o";
3489
4867
  return `
@@ -3502,13 +4880,138 @@ function occurrenceRangeEndpointScript(timelineOffset, endpoint) {
3502
4880
  end tell
3503
4881
  end tell`;
3504
4882
  }
3505
- function titleAssetSelectionScript(assetName) {
4883
+ function titleSearchScript(query, identityQuery = false) {
4884
+ const searchQuery = identityQuery ? "" : query;
4885
+ return `
4886
+ using terms from application "System Events"
4887
+ on titlePaneVisible(candidate, mainOrigin, mainSize)
4888
+ try
4889
+ set candidatePosition to position of candidate
4890
+ set candidateSize to size of candidate
4891
+ set candidateX to item 1 of candidatePosition
4892
+ set candidateY to item 2 of candidatePosition
4893
+ set candidateRight to candidateX + (item 1 of candidateSize)
4894
+ set candidateBottom to candidateY + (item 2 of candidateSize)
4895
+ set minimumX to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.02)
4896
+ set minimumY to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.25)
4897
+ set maximumX to (item 1 of mainOrigin) + (item 1 of mainSize)
4898
+ set maximumY to (item 2 of mainOrigin) + (item 2 of mainSize)
4899
+ return candidateRight is greater than minimumX and candidateBottom is greater than minimumY and candidateX is less than maximumX and candidateY is less than maximumY
4900
+ on error
4901
+ return false
4902
+ end try
4903
+ end titlePaneVisible
4904
+
4905
+ on titleCandidateName(candidate)
4906
+ set candidateName to ""
4907
+ try
4908
+ set candidateName to name of candidate as text
4909
+ end try
4910
+ if candidateName is "missing value" then set candidateName to ""
4911
+ if candidateName is "" then
4912
+ try
4913
+ set candidateName to value of candidate as text
4914
+ end try
4915
+ end if
4916
+ if candidateName is "missing value" then set candidateName to ""
4917
+ return candidateName
4918
+ end titleCandidateName
4919
+
4920
+ on collectTitleMatches(nodes, depth, queryText, identityQuery, seenIdentities, mainOrigin, mainSize)
4921
+ if depth > 12 then return ""
4922
+ set output to ""
4923
+ repeat with candidateIndex from 1 to count of nodes
4924
+ try
4925
+ set candidate to contents of item candidateIndex of nodes
4926
+ if my titlePaneVisible(candidate, mainOrigin, mainSize) then
4927
+ set candidateName to my titleCandidateName(candidate)
4928
+ set candidateIdentity to ""
4929
+ try
4930
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
4931
+ end try
4932
+ set matches to false
4933
+ if candidateName is not "" and candidateIdentity is not "" then
4934
+ if identityQuery then
4935
+ set matches to candidateIdentity is queryText
4936
+ else
4937
+ set matches to candidateName contains queryText
4938
+ end if
4939
+ end if
4940
+ if matches and seenIdentities does not contain candidateIdentity then
4941
+ set end of seenIdentities to candidateIdentity
4942
+ set output to output & candidateName & (ASCII character 31) & candidateIdentity & (ASCII character 30)
4943
+ end if
4944
+ set output to output & my collectTitleMatches(UI elements of candidate, depth + 1, queryText, identityQuery, seenIdentities, mainOrigin, mainSize)
4945
+ end if
4946
+ on error
4947
+ -- Ignore inaccessible descendants and continue the bounded scan.
4948
+ end try
4949
+ end repeat
4950
+ return output
4951
+ end collectTitleMatches
4952
+ end using terms from
4953
+ tell application "System Events"
4954
+ tell process "Final Cut Pro"
4955
+ ${requireFrontmostAppleScript()}
4956
+ set mainWindow to window "Final Cut Pro"
4957
+ set mainOrigin to position of mainWindow
4958
+ set mainSize to size of mainWindow
4959
+ click at {(item 1 of mainOrigin) + 104, (item 2 of mainOrigin) + 53}
4960
+ delay 0.3
4961
+ set titleSearchField to missing value
4962
+ repeat with candidate in entire contents of front window
4963
+ try
4964
+ set candidateRole to role of candidate as text
4965
+ set candidateDescription to description of candidate as text
4966
+ if (candidateRole is "AXTextField" or candidateRole is "AXSearchField") and (candidateDescription contains "search" or candidateDescription contains "Search") then
4967
+ set titleSearchField to candidate
4968
+ exit repeat
4969
+ end if
4970
+ end try
4971
+ end repeat
4972
+ if titleSearchField is not missing value then
4973
+ set value of titleSearchField to ${appleScriptString(searchQuery)}
4974
+ try
4975
+ set value of attribute "AXFocused" of titleSearchField to true
4976
+ end try
4977
+ else if ${searchQuery === "" ? "false" : "true"} then
4978
+ click at {(item 1 of mainOrigin) + 280, (item 2 of mainOrigin) + 83}
4979
+ keystroke "a" using {command down}
4980
+ key code 51
4981
+ keystroke ${appleScriptString(searchQuery)}
4982
+ end if
4983
+ delay 0.6
4984
+ set seenIdentities to {}
4985
+ return my collectTitleMatches(UI elements of mainWindow, 0, ${appleScriptString(identityQuery ? query : searchQuery)}, ${identityQuery ? "true" : "false"}, seenIdentities, mainOrigin, mainSize)
4986
+ end tell
4987
+ end tell`;
4988
+ }
4989
+ function titleBrowserPreflightScript() {
4990
+ return `
4991
+ on titleBrowserPreflightResult(processFrontmost, browserWindowAvailable)
4992
+ return processFrontmost & (ASCII character 31) & browserWindowAvailable
4993
+ end titleBrowserPreflightResult
4994
+
4995
+ tell application "System Events"
4996
+ tell process "Final Cut Pro"
4997
+ set processFrontmost to frontmost as text
4998
+ set browserWindowAvailable to false
4999
+ try
5000
+ set browserWindow to window "Final Cut Pro"
5001
+ set browserWindowAvailable to true
5002
+ end try
5003
+ return my titleBrowserPreflightResult(processFrontmost, browserWindowAvailable)
5004
+ end tell
5005
+ end tell`;
5006
+ }
5007
+ function titleAssetSelectionScript(assetName, assetIdentity) {
3506
5008
  return `
3507
5009
  tell application "System Events"
3508
5010
  tell process "Final Cut Pro"
3509
5011
  ${requireFrontmostAppleScript()}
3510
5012
  set mainWindow to window "Final Cut Pro"
3511
5013
  set mainOrigin to position of mainWindow
5014
+ set targetIdentity to ${appleScriptString(assetIdentity ?? "")}
3512
5015
  -- Final Cut 10.7 exposes the Titles tab as a custom Browser control. Its
3513
5016
  -- Control-Command-1 shortcut is not stable across releases (on some
3514
5017
  -- builds it opens Export), so use the bounded window-relative fallback.
@@ -3557,14 +5060,14 @@ tell application "System Events"
3557
5060
  set candidateIdentity to ""
3558
5061
  try
3559
5062
  set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
3560
- if candidateSourceIdentity is not "" then set candidateIdentity to "source:" & candidateSourceIdentity
5063
+ if candidateSourceIdentity is not "" then set candidateIdentity to candidateSourceIdentity
3561
5064
  end try
3562
5065
  if candidateIdentity is "" then
3563
5066
  set candidateIdentity to (candidateRole as text) & "|" & (candidateName as text) & "|" & ((position of candidate) as text) & "|" & ((size of candidate) as text)
3564
5067
  end if
3565
- if (candidateName is ${appleScriptString(assetName)} or candidateName contains ${appleScriptString(assetName)}) and seenTitleIdentities does not contain candidateIdentity then
5068
+ if ((targetIdentity is not "" and candidateIdentity is targetIdentity) or (targetIdentity is "" and (candidateName is ${appleScriptString(assetName)} or candidateName contains ${appleScriptString(assetName)}))) and seenTitleIdentities does not contain candidateIdentity then
3566
5069
  set end of seenTitleIdentities to candidateIdentity
3567
- if candidateName is ${appleScriptString(assetName)} then
5070
+ if targetIdentity is not "" or candidateName is ${appleScriptString(assetName)} then
3568
5071
  set exactMatchCount to exactMatchCount + 1
3569
5072
  set exactTitleItem to candidate
3570
5073
  else
@@ -3606,6 +5109,115 @@ tell application "System Events"
3606
5109
  end tell
3607
5110
  end tell`;
3608
5111
  }
5112
+ function markRangeEndAndConnectPictureInPictureScript() {
5113
+ return `
5114
+ tell application "System Events"
5115
+ tell process "Final Cut Pro"
5116
+ ${requireFrontmostAppleScript()}
5117
+ keystroke "o"
5118
+ delay 0.2
5119
+ -- Q connects the selected Browser video to the selected primary clip.
5120
+ keystroke "q"
5121
+ delay 0.5
5122
+ end tell
5123
+ end tell`;
5124
+ }
5125
+ function pictureInPictureTransformScript(preview) {
5126
+ const optionalFields = [
5127
+ preview.crop ? `
5128
+ set value of cropTopField to ${appleScriptString(String(preview.crop.top * 100))}
5129
+ set value of cropRightField to ${appleScriptString(String(preview.crop.right * 100))}
5130
+ set value of cropBottomField to ${appleScriptString(String(preview.crop.bottom * 100))}
5131
+ set value of cropLeftField to ${appleScriptString(String(preview.crop.left * 100))}` : "",
5132
+ preview.frame ? `
5133
+ set value of frameStyleField to ${appleScriptString(preview.frame.style)}
5134
+ set value of frameColorField to ${appleScriptString(preview.frame.color)}
5135
+ set value of frameWidthField to ${appleScriptString(String(preview.frame.width))}` : "",
5136
+ ].join("");
5137
+ const requiredFieldLookup = `
5138
+ set positionXField to my findInspectorField("Position X")
5139
+ set positionYField to my findInspectorField("Position Y")
5140
+ set scaleField to my findInspectorField("Scale")
5141
+ if positionXField is missing value or positionYField is missing value or scaleField is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_TRANSFORM_UNAVAILABLE: Transform inspector fields were not visible"
5142
+ set value of positionXField to ${appleScriptString(String(preview.position.x))}
5143
+ set value of positionYField to ${appleScriptString(String(preview.position.y))}
5144
+ set value of scaleField to ${appleScriptString(String(preview.scale * 100))}`;
5145
+ const optionalLookup = `${preview.crop ? `
5146
+ set cropTopField to my findInspectorField("Crop Top")
5147
+ set cropRightField to my findInspectorField("Crop Right")
5148
+ set cropBottomField to my findInspectorField("Crop Bottom")
5149
+ set cropLeftField to my findInspectorField("Crop Left")
5150
+ if cropTopField is missing value or cropRightField is missing value or cropBottomField is missing value or cropLeftField is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_CROP_UNAVAILABLE: Crop inspector fields were not visible"` : ""}${preview.frame ? `
5151
+ set frameStyleField to my findInspectorField("Frame Style")
5152
+ set frameColorField to my findInspectorField("Frame Color")
5153
+ set frameWidthField to my findInspectorField("Frame Width")
5154
+ if frameStyleField is missing value or frameColorField is missing value or frameWidthField is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_FRAME_UNAVAILABLE: Frame inspector fields were not visible"` : ""}`;
5155
+ return `
5156
+ tell application "System Events"
5157
+ tell process "Final Cut Pro"
5158
+ ${requireFrontmostAppleScript()}
5159
+ set mainWindow to window "Final Cut Pro"
5160
+ set inspectorTab to missing value
5161
+ repeat with candidate in entire contents of mainWindow
5162
+ try
5163
+ set candidateDescription to description of candidate as text
5164
+ set candidateName to name of candidate as text
5165
+ if candidateDescription contains "Video Inspector" or candidateName is "Inspector" then
5166
+ set inspectorTab to candidate
5167
+ exit repeat
5168
+ end if
5169
+ end try
5170
+ end repeat
5171
+ if inspectorTab is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_TRANSFORM_UNAVAILABLE: Video Inspector was not visible"
5172
+ try
5173
+ perform action "AXPress" of inspectorTab
5174
+ on error
5175
+ click inspectorTab
5176
+ end try
5177
+ delay 0.3
5178
+ ${requiredFieldLookup}
5179
+ ${optionalLookup}
5180
+ ${optionalFields}
5181
+ delay 0.2
5182
+ end tell
5183
+ end tell`;
5184
+ }
5185
+ function pictureInPictureInspectorReadbackScript() {
5186
+ return `
5187
+ on readInspectorField(fieldLabel, fallback)
5188
+ tell application "System Events"
5189
+ tell process "Final Cut Pro"
5190
+ repeat with candidate in text fields of front window
5191
+ try
5192
+ set candidateDescription to description of candidate as text
5193
+ set candidateName to name of candidate as text
5194
+ if candidateDescription contains fieldLabel or candidateName contains fieldLabel then return value of candidate as text
5195
+ end try
5196
+ end repeat
5197
+ end tell
5198
+ end tell
5199
+ return fallback
5200
+ end readInspectorField
5201
+
5202
+ -- FRAMEKIT_NATIVE_PIP_READBACK
5203
+ tell application "System Events"
5204
+ tell process "Final Cut Pro"
5205
+ ${requireFrontmostAppleScript()}
5206
+ set positionXText to my readInspectorField("Position X", "")
5207
+ set positionYText to my readInspectorField("Position Y", "")
5208
+ set scaleText to my readInspectorField("Scale", "")
5209
+ if positionXText is "" or positionYText is "" or scaleText is "" then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Transform inspector values were not visible"
5210
+ set frameStyleText to my readInspectorField("Frame Style", "")
5211
+ set frameColorText to my readInspectorField("Frame Color", "")
5212
+ set frameWidthText to my readInspectorField("Frame Width", "")
5213
+ set cropTopText to my readInspectorField("Crop Top", "")
5214
+ set cropRightText to my readInspectorField("Crop Right", "")
5215
+ set cropBottomText to my readInspectorField("Crop Bottom", "")
5216
+ set cropLeftText to my readInspectorField("Crop Left", "")
5217
+ return positionXText & (ASCII character 31) & positionYText & (ASCII character 31) & scaleText & (ASCII character 31) & frameStyleText & (ASCII character 31) & frameColorText & (ASCII character 31) & frameWidthText & (ASCII character 31) & cropTopText & (ASCII character 31) & cropRightText & (ASCII character 31) & cropBottomText & (ASCII character 31) & cropLeftText
5218
+ end tell
5219
+ end tell`;
5220
+ }
3609
5221
  function titleTextEditScript(text) {
3610
5222
  return `
3611
5223
  tell application "System Events"
@@ -3695,7 +5307,7 @@ function editScript(operation) {
3695
5307
  ? `click menu item "Trim ${operation.edge === "start" ? "Start" : "End"}" of menu "Trim" of menu bar 1`
3696
5308
  : operation.type === "set-selected-clip-gain"
3697
5309
  ? `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`
3698
- : `click menu item "Marker" of menu "Mark" of menu bar 1`;
5310
+ : `click menu item "Add Marker" of menu 1 of menu item "Markers" of menu "Mark" of menu bar 1`;
3699
5311
  return `
3700
5312
  tell application "System Events"
3701
5313
  tell process "Final Cut Pro"
@@ -3735,7 +5347,7 @@ function parseContext(output) {
3735
5347
  || focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
3736
5348
  ? { kind: "selected-clip", name: focusedName, role: focusedRole }
3737
5349
  : { kind: "playhead" };
3738
- return {
5350
+ const context = {
3739
5351
  available: true,
3740
5352
  application: "Final Cut Pro",
3741
5353
  frontmost: frontState === "true",
@@ -3756,6 +5368,41 @@ function parseContext(output) {
3756
5368
  undoAvailable: undoState === "true",
3757
5369
  ...(undoCommandState ? { undoCommand: undoCommandState } : {}),
3758
5370
  };
5371
+ return { ...context, readiness: readinessForContext(context) };
5372
+ }
5373
+ function shouldRetryPassiveInspection(context) {
5374
+ return context.available
5375
+ && context.frontmost
5376
+ && context.timelineWindowAvailable
5377
+ && context.timelineFocused
5378
+ && context.focusTarget === "timeline"
5379
+ && context.target.kind === "unknown";
5380
+ }
5381
+ function reconcileTimelineFocus(context) {
5382
+ if (!context.timelineFocused || context.focusTarget !== "timeline")
5383
+ return context;
5384
+ const focusTarget = classifyNativeFocusTarget(context.focusedRole, context.focusedDescription, context.focusedName);
5385
+ const focusedWindowMismatch = Boolean(context.frontWindow
5386
+ && context.focusedWindowName
5387
+ && context.frontWindow !== context.focusedWindowName);
5388
+ if (focusTarget === "unknown" && !focusedWindowMismatch)
5389
+ return context;
5390
+ const reconciled = {
5391
+ ...context,
5392
+ timelineFocused: false,
5393
+ focusTarget,
5394
+ };
5395
+ return { ...reconciled, readiness: readinessForContext(reconciled) };
5396
+ }
5397
+ function classifyNativeFocusTarget(focusedRole, focusedDescription, focusedName) {
5398
+ if (focusedRole === "AXTextField" || focusedRole === "AXSearchField")
5399
+ return "text-field";
5400
+ if (focusedRole === "AXSheet" || focusedRole === "AXDialog")
5401
+ return "modal";
5402
+ const focusText = [focusedDescription, focusedName].filter(Boolean).join(" ").toLowerCase();
5403
+ if (focusText.includes("browser") || focusText.includes("search"))
5404
+ return "browser";
5405
+ return "unknown";
3759
5406
  }
3760
5407
  function parseMediaMatches(output) {
3761
5408
  return output
@@ -3776,7 +5423,9 @@ function parseMediaMatches(output) {
3776
5423
  }
3777
5424
  function browserMediaIdentity(match) {
3778
5425
  const identity = match.sourceIdentity?.trim();
3779
- return identity || undefined;
5426
+ if (!identity || identity.startsWith("fcp-ax://browser/"))
5427
+ return undefined;
5428
+ return identity;
3780
5429
  }
3781
5430
  function parseOccurrences(output, mediaHandle) {
3782
5431
  return output
@@ -3785,7 +5434,7 @@ function parseOccurrences(output, mediaHandle) {
3785
5434
  .filter(Boolean)
3786
5435
  .map((record, index) => {
3787
5436
  const fields = record.split(String.fromCharCode(31));
3788
- const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset, nativeDuration] = fields;
5437
+ const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset, nativeDuration, identity] = fields;
3789
5438
  const nativeRange = nativeDuration !== undefined;
3790
5439
  const legacyRecord = legacyTimelineOffset !== undefined && !nativeRange;
3791
5440
  const identityOrStart = sourceIdentity;
@@ -3795,6 +5444,7 @@ function parseOccurrences(output, mediaHandle) {
3795
5444
  handle: opaqueHandle("occurrence"),
3796
5445
  mediaHandle,
3797
5446
  name,
5447
+ ...(identity ? { identity } : {}),
3798
5448
  ...(role ? { role } : {}),
3799
5449
  ...(sourceIdentity && !legacyRange ? { sourceIdentity } : {}),
3800
5450
  ...(nativeRange ? { start: legacyTimelineOffset, duration: nativeDuration } : {}),
@@ -3829,6 +5479,109 @@ function timelineTimecodeToRational(value, sequence, label, absolute) {
3829
5479
  function opaqueHandle(kind, suffix) {
3830
5480
  return `${kind}-${Date.now().toString(36)}-${suffix ?? Math.random().toString(36).slice(2, 8)}`;
3831
5481
  }
5482
+ function resolveLocalPath(sourcePath) {
5483
+ const trimmed = sourcePath.trim();
5484
+ if (trimmed === "~")
5485
+ return homedir();
5486
+ if (trimmed.startsWith("~/"))
5487
+ return resolve(homedir(), trimmed.slice(2));
5488
+ if (trimmed.startsWith("~"))
5489
+ throw new Error(`INVALID_OPERATION: local media path must be absolute or start with ~/`);
5490
+ return resolve(trimmed);
5491
+ }
5492
+ async function enumerateSupportedVideoFiles(directoryPath) {
5493
+ let details;
5494
+ try {
5495
+ details = await stat(directoryPath);
5496
+ await access(directoryPath, constants.R_OK);
5497
+ }
5498
+ catch (error) {
5499
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_DIRECTORY_UNAVAILABLE: ${directoryPath} is not a readable directory (${String(error)})`);
5500
+ }
5501
+ if (!details.isDirectory()) {
5502
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_DIRECTORY_UNAVAILABLE: ${directoryPath} is not a directory`);
5503
+ }
5504
+ let entries;
5505
+ try {
5506
+ entries = await readdir(directoryPath, { withFileTypes: true });
5507
+ }
5508
+ catch (error) {
5509
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_DIRECTORY_UNAVAILABLE: ${directoryPath} could not be enumerated (${String(error)})`);
5510
+ }
5511
+ const files = entries
5512
+ .filter((entry) => entry.isFile() && SUPPORTED_VIDEO_EXTENSIONS.includes(extname(entry.name).toLowerCase()))
5513
+ .map((entry) => ({
5514
+ sourcePath: resolve(directoryPath, entry.name),
5515
+ name: entry.name,
5516
+ kind: "video",
5517
+ }))
5518
+ .sort((left, right) => left.sourcePath < right.sourcePath ? -1 : left.sourcePath > right.sourcePath ? 1 : 0);
5519
+ for (const file of files) {
5520
+ try {
5521
+ await access(file.sourcePath, constants.R_OK);
5522
+ }
5523
+ catch (error) {
5524
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_FILE_UNAVAILABLE: ${file.sourcePath} is not readable (${String(error)})`);
5525
+ }
5526
+ }
5527
+ return files;
5528
+ }
5529
+ async function snapshotSupportedVideoFiles(directoryPath) {
5530
+ const files = await enumerateSupportedVideoFiles(directoryPath);
5531
+ const fileIdentities = new Map();
5532
+ for (const file of files) {
5533
+ try {
5534
+ const details = await stat(file.sourcePath);
5535
+ await access(file.sourcePath, constants.R_OK);
5536
+ if (!details.isFile())
5537
+ throw new Error("path is not a file");
5538
+ fileIdentities.set(file.sourcePath, {
5539
+ device: details.dev,
5540
+ inode: details.ino,
5541
+ size: details.size,
5542
+ mtimeMs: details.mtimeMs,
5543
+ ctimeMs: details.ctimeMs,
5544
+ });
5545
+ }
5546
+ catch (error) {
5547
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_FILE_UNAVAILABLE: ${file.sourcePath} could not be snapshotted (${String(error)})`);
5548
+ }
5549
+ }
5550
+ return { files, fileIdentities };
5551
+ }
5552
+ async function assertMediaImportDirectoryPreviewFresh(preview) {
5553
+ let current;
5554
+ try {
5555
+ current = await snapshotSupportedVideoFiles(preview.directoryPath);
5556
+ }
5557
+ catch (error) {
5558
+ throw new Error(`FINAL_CUT_NATIVE_PREVIEW_STALE: media directory contents changed after preview (${String(error)})`);
5559
+ }
5560
+ const sameFileSet = preview.files.length === current.files.length
5561
+ && preview.files.every((file, index) => {
5562
+ const currentFile = current.files[index];
5563
+ return currentFile?.sourcePath === file.sourcePath
5564
+ && currentFile.name === file.name
5565
+ && currentFile.kind === file.kind;
5566
+ });
5567
+ if (!sameFileSet) {
5568
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media directory contents changed after preview");
5569
+ }
5570
+ const sameFileIdentities = preview.files.every((file) => {
5571
+ const expected = preview.fileIdentities.get(file.sourcePath);
5572
+ const actual = current.fileIdentities.get(file.sourcePath);
5573
+ return expected !== undefined
5574
+ && actual !== undefined
5575
+ && expected.device === actual.device
5576
+ && expected.inode === actual.inode
5577
+ && expected.size === actual.size
5578
+ && expected.mtimeMs === actual.mtimeMs
5579
+ && expected.ctimeMs === actual.ctimeMs;
5580
+ });
5581
+ if (!sameFileIdentities) {
5582
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media directory contents changed after preview");
5583
+ }
5584
+ }
3832
5585
  function mediaKind(sourcePath) {
3833
5586
  return new Set([".aif", ".aiff", ".flac", ".m4a", ".mp3", ".wav", ".aac", ".caf"]).has(extname(sourcePath).toLowerCase())
3834
5587
  ? "audio"
@@ -3937,21 +5690,105 @@ function mediaInsertionMutationObserved(before, after) {
3937
5690
  const afterDuration = after.sequenceTimeRange?.duration ?? after.sequence?.duration;
3938
5691
  return Boolean(beforeDuration && afterDuration && compareRational(afterDuration, beforeDuration) > 0);
3939
5692
  }
3940
- function unavailableContext(code, message, observed) {
5693
+ function readinessForContext(context) {
5694
+ const selectedTarget = context.target.kind !== "none" && context.target.kind !== "unknown";
5695
+ const state = context.error?.state
5696
+ ?? (context.available && context.frontmost && context.timelineWindowAvailable && context.timelineFocused && !context.overlayBlocked && selectedTarget && context.undoAvailable
5697
+ ? "ready"
5698
+ : "unavailable");
5699
+ const overlay = context.overlayBlocked
5700
+ ? "blocked"
5701
+ : context.framekitWindowAvailable === undefined || context.framekitWindowAvailable === false
5702
+ ? "unknown"
5703
+ : context.framekitWindowMinimized === false
5704
+ ? "blocked"
5705
+ : "clear";
5706
+ const firstMissing = state === "timeout" || state === "cancelled" || state === "stale"
5707
+ ? undefined
5708
+ : context.error?.code.includes("PERMISSION")
5709
+ ? "permission"
5710
+ : !context.timelineWindowAvailable
5711
+ ? "timeline-window"
5712
+ : context.overlayBlocked
5713
+ ? "overlay"
5714
+ : !context.frontmost
5715
+ ? "frontmost"
5716
+ : !context.timelineFocused
5717
+ ? "timeline-focus"
5718
+ : !selectedTarget
5719
+ ? "target"
5720
+ : !context.undoAvailable
5721
+ ? "undo"
5722
+ : undefined;
5723
+ const retryable = context.error?.retryable ?? state !== "ready";
5724
+ const nextAction = state === "ready"
5725
+ ? "none"
5726
+ : retryable
5727
+ ? "retry"
5728
+ : "unavailable";
5729
+ const guidance = context.error?.message
5730
+ ?? (firstMissing === "timeline-window"
5731
+ ? "Open a Final Cut Pro project timeline and retry"
5732
+ : firstMissing === "overlay"
5733
+ ? "Close or minimize the Framekit overlay and retry"
5734
+ : firstMissing === "frontmost"
5735
+ ? "Bring Final Cut Pro to the front and retry"
5736
+ : firstMissing === "timeline-focus"
5737
+ ? "Focus the Final Cut Pro timeline and retry"
5738
+ : firstMissing === "target"
5739
+ ? "Select a single timeline target and retry"
5740
+ : firstMissing === "undo"
5741
+ ? "Enable an Undo command in Final Cut Pro and retry"
5742
+ : state === "timeout"
5743
+ ? "Final Cut did not respond before the native deadline; retry"
5744
+ : state === "cancelled"
5745
+ ? "The native request was cancelled; retry when ready"
5746
+ : state === "stale"
5747
+ ? "The native target is stale; inspect and preview again"
5748
+ : "Native Final Cut readiness is unavailable; inspect and retry");
3941
5749
  return {
3942
- ...(observed ?? {
3943
- application: "Final Cut Pro",
3944
- frontmost: false,
3945
- timelineWindowAvailable: false,
3946
- timelineFocused: false,
3947
- focusTarget: "none",
3948
- target: { kind: "none" },
3949
- undoAvailable: false,
3950
- bladeAvailable: false,
3951
- }),
5750
+ state,
5751
+ nextAction,
5752
+ retryable,
5753
+ ...(firstMissing ? { firstMissing } : {}),
5754
+ frontmost: context.frontmost,
5755
+ timelineFocus: context.timelineFocused,
5756
+ selectedTarget,
5757
+ overlay,
5758
+ permission: context.error?.code.includes("PERMISSION") ? "required" : context.available ? "granted" : "unknown",
5759
+ undo: context.available ? context.undoAvailable ? "available" : "unavailable" : "unknown",
5760
+ guidance,
5761
+ };
5762
+ }
5763
+ function readinessStateForError(code) {
5764
+ if (code === "FINAL_CUT_NATIVE_CANCELLED")
5765
+ return "cancelled";
5766
+ if (code.includes("TIMEOUT") || code === "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT")
5767
+ return "timeout";
5768
+ if (code.includes("STALE"))
5769
+ return "stale";
5770
+ return "unavailable";
5771
+ }
5772
+ function unavailableContext(code, message, observed) {
5773
+ const state = readinessStateForError(code);
5774
+ const error = { code, message, state, retryable: state !== "unavailable" || code !== "CAPABILITY_UNAVAILABLE" };
5775
+ const base = observed ?? {
5776
+ available: false,
5777
+ application: "Final Cut Pro",
5778
+ frontmost: false,
5779
+ timelineWindowAvailable: false,
5780
+ timelineFocused: false,
5781
+ focusTarget: "none",
5782
+ target: { kind: "none" },
5783
+ undoAvailable: false,
5784
+ bladeAvailable: false,
5785
+ };
5786
+ const context = {
5787
+ ...base,
3952
5788
  available: false,
3953
- error: { code, message },
5789
+ error,
3954
5790
  };
5791
+ return { ...context, readiness: readinessForContext(context) };
3955
5792
  }
3956
5793
  function preflightContext(error) {
3957
5794
  return error instanceof NativeFinalCutPreflightError ? error.context : undefined;
@@ -3978,13 +5815,15 @@ function commandName(operation) {
3978
5815
  return `Trim > Trim ${operation.edge === "start" ? "Start" : "End"}`;
3979
5816
  if (operation.type === "set-selected-clip-gain")
3980
5817
  return "Modify > Adjust Volume";
3981
- return "Mark > Marker";
5818
+ return "Mark > Markers > Add Marker";
3982
5819
  }
3983
5820
  function appleScriptString(value) {
3984
5821
  return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replace(/[\r\n]/g, " ")}"`;
3985
5822
  }
3986
5823
  function nativeErrorCode(error) {
3987
5824
  const message = String(error);
5825
+ if (message.includes("FINAL_CUT_NATIVE_CANCELLED") || message.includes("AbortError") || message.includes("aborted"))
5826
+ return "FINAL_CUT_NATIVE_CANCELLED";
3988
5827
  if (message.includes("-1712") || /AppleEvent.*timed out/i.test(message))
3989
5828
  return "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT";
3990
5829
  const explicitCodes = [...message.matchAll(/FINAL_CUT_NATIVE_[A-Z_]+/g)].map((match) => match[0]);
@@ -4002,10 +5841,18 @@ function nativeErrorCode(error) {
4002
5841
  return "FINAL_CUT_NATIVE_MODAL_BLOCKED";
4003
5842
  return "FINAL_CUT_NATIVE_AUTOMATION_FAILED";
4004
5843
  }
5844
+ function nativeMediaImportErrorCode(error) {
5845
+ const code = nativeErrorCode(error);
5846
+ return code === "FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE"
5847
+ ? "FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE"
5848
+ : code;
5849
+ }
4005
5850
  function nativeErrorMessage(error) {
4006
5851
  const message = String(error);
4007
5852
  if (message.includes("FINAL_CUT_NATIVE_OVERLAY_BLOCKED"))
4008
5853
  return "The Framekit window could not be minimized; close or minimize the overlay and retry";
5854
+ if (message.includes("FINAL_CUT_NATIVE_CANCELLED") || message.includes("AbortError") || message.includes("aborted"))
5855
+ return "The native request was cancelled; retry when ready";
4009
5856
  if (message.includes("FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT") || message.includes("-1712") || /AppleEvent.*timed out/i.test(message))
4010
5857
  return "Final Cut did not respond to an AppleEvent; reopen or bring Final Cut Pro to the front and retry";
4011
5858
  if (message.includes("FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW"))