@morshoto/framekit 0.1.6 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bin/framekit.mjs +2 -1
  2. package/dist-package/adapters/final-cut/typescript/src/assets.js +157 -35
  3. package/dist-package/adapters/final-cut/typescript/src/background-export.js +384 -0
  4. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +175 -0
  5. package/dist-package/adapters/final-cut/typescript/src/canonical.js +189 -32
  6. package/dist-package/adapters/final-cut/typescript/src/connection.js +55 -17
  7. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +33 -7
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.js +74 -0
  9. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +615 -49
  10. package/dist-package/adapters/final-cut/typescript/src/index.js +10 -0
  11. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +390 -0
  12. package/dist-package/adapters/final-cut/typescript/src/live.js +16 -6
  13. package/dist-package/adapters/final-cut/typescript/src/media.js +151 -0
  14. package/dist-package/adapters/final-cut/typescript/src/native-session.js +412 -0
  15. package/dist-package/adapters/final-cut/typescript/src/native.js +1192 -364
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +225 -32
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +163 -17
  18. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +120 -0
  19. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.js +433 -0
  20. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +372 -0
  21. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.js +66 -0
  22. package/dist-package/apps/mcp-server/src/headless-sessions.js +112 -0
  23. package/dist-package/apps/mcp-server/src/main.js +41 -8
  24. package/dist-package/apps/mcp-server/src/materialization-jobs.js +326 -0
  25. package/dist-package/apps/mcp-server/src/routing.js +227 -39
  26. package/dist-package/apps/mcp-server/src/server.js +642 -97
  27. package/dist-package/apps/mcp-server/src/version.js +109 -1
  28. package/dist-package/packages/runtime/src/application/media-analysis-service.js +1 -3
  29. package/dist-package/packages/runtime/src/application/project-service.js +46 -7
  30. package/dist-package/packages/runtime/src/capabilities.js +55 -7
  31. package/dist-package/packages/runtime/src/context/project-catalog.js +159 -0
  32. package/dist-package/packages/runtime/src/domain/capabilities.js +33 -0
  33. package/dist-package/packages/runtime/src/domain/context.js +14 -1
  34. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  35. package/dist-package/packages/runtime/src/domain/timeline-target.js +217 -0
  36. package/dist-package/packages/runtime/src/editing/edit-service.js +15 -1
  37. package/dist-package/packages/runtime/src/editing/intent.js +178 -2
  38. package/dist-package/packages/runtime/src/index.js +3 -0
  39. package/dist-package/packages/runtime/src/runtime.js +2 -2
  40. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.js +295 -0
  41. package/dist-package/packages/runtime/src/timeline/editing-session.js +490 -0
  42. package/dist-package/packages/testkit/src/in-memory-editor.js +5 -4
  43. package/package.json +12 -6
@@ -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,6 +76,7 @@ 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();
40
81
  maskPreviews = new Map();
41
82
  rangePreviews = new Map();
@@ -45,6 +86,7 @@ export class FinalCutNativeAutomationAdapter {
45
86
  transitionPreviews = new Map();
46
87
  constructor(options = {}) {
47
88
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
89
+ this.titleDiscoveryAvailable = this.enabled;
48
90
  this.executor = options.executor ?? runAppleScript;
49
91
  this.canDriveNativeMouse = options.executor === undefined;
50
92
  this.liveState = options.liveState;
@@ -73,7 +115,7 @@ export class FinalCutNativeAutomationAdapter {
73
115
  mediaAppend: this.enabled,
74
116
  mediaInsert: this.enabled,
75
117
  titlePlacement: this.enabled,
76
- titleDiscovery: this.enabled,
118
+ titleDiscovery: this.titleDiscoveryAvailable,
77
119
  pictureInPicture: this.enabled,
78
120
  transitionDiscovery: this.enabled,
79
121
  transitionPlacement: this.enabled,
@@ -83,18 +125,23 @@ export class FinalCutNativeAutomationAdapter {
83
125
  requiresFinalCutFrontmost: true,
84
126
  };
85
127
  }
86
- async inspect() {
87
- return this.withNativeUi(() => this.inspectNative());
128
+ async inspect(options = {}) {
129
+ return this.requestContext.run(options, () => this.inspectNative());
88
130
  }
89
- async focusTimeline() {
90
- return this.withNativeUi(() => this.focusTimelineNative());
131
+ async focusTimeline(options = {}) {
132
+ return this.withNativeUi(() => this.focusTimelineNative(), options.signal);
91
133
  }
92
134
  async inspectNative() {
93
135
  if (!this.enabled) {
94
136
  return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
95
137
  }
96
138
  try {
97
- 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;
98
145
  }
99
146
  catch (error) {
100
147
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
@@ -111,9 +158,9 @@ export class FinalCutNativeAutomationAdapter {
111
158
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
112
159
  }
113
160
  }
114
- async inspectRawNative(deadline) {
161
+ async inspectRawNative(deadline = this.now() + this.nativePreflightTimeoutMs, script = inspectScript()) {
115
162
  try {
116
- 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")));
117
164
  }
118
165
  catch (error) {
119
166
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error));
@@ -149,8 +196,8 @@ export class FinalCutNativeAutomationAdapter {
149
196
  this.operations.set(operationId, record);
150
197
  this.latestOperationId = operationId;
151
198
  }
152
- async edit(operation) {
153
- return this.withNativeUi(() => this.editNative(operation));
199
+ async edit(operation, options = {}) {
200
+ return this.withNativeUi(() => this.editNative(operation), options.signal);
154
201
  }
155
202
  async editNative(operation) {
156
203
  this.assertEnabled();
@@ -174,8 +221,8 @@ export class FinalCutNativeAutomationAdapter {
174
221
  this.rememberOperation(operationId, { kind: "selection", before, after, beforeLive, afterLive, undoCommand: after.undoCommand });
175
222
  return { operationId, operation, command, before, after, verification, undoAvailable: after.undoAvailable, ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}) };
176
223
  }
177
- async undo(operationId) {
178
- return this.withNativeUi(() => this.undoNative(operationId));
224
+ async undo(operationId, options = {}) {
225
+ return this.withNativeUi(() => this.undoNative(operationId), options.signal);
179
226
  }
180
227
  async undoNative(operationId) {
181
228
  this.assertEnabled();
@@ -214,99 +261,217 @@ export class FinalCutNativeAutomationAdapter {
214
261
  this.latestOperationId = undefined;
215
262
  return { operationId, undone: true, context: after, verification };
216
263
  }
217
- async importMedia(sourcePath) {
218
- 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);
219
295
  }
220
296
  async importMediaNative(sourcePath) {
221
297
  this.assertEnabled();
222
- 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);
223
316
  const name = basename(normalizedPath);
224
- if (!name)
317
+ if (!sourcePath.trim())
225
318
  throw new Error("INVALID_OPERATION: local media path cannot be empty");
226
319
  try {
227
320
  const details = await stat(normalizedPath);
228
321
  await access(normalizedPath, constants.R_OK);
322
+ if (details.isDirectory())
323
+ throw new NativeFinalCutMediaImportDirectoryError(normalizedPath);
229
324
  if (!details.isFile())
230
325
  throw new Error("path is not a file");
231
326
  }
232
327
  catch (error) {
328
+ if (error instanceof NativeFinalCutMediaImportDirectoryError)
329
+ throw error;
233
330
  throw new Error(`FINAL_CUT_NATIVE_MEDIA_PATH_UNAVAILABLE: ${normalizedPath} is not a readable local media file (${String(error)})`);
234
331
  }
235
- const beforeDiscoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
236
- await this.ensureBrowserReady(beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
237
- const beforeMatches = await this.searchMediaNative(name, beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
238
- const beforeIdentities = new Set(beforeMatches
239
- .filter((match) => match.name.toLowerCase() === name.toLowerCase())
240
- .map((match) => browserMediaIdentity(match))
241
- .filter((identity) => Boolean(identity)));
242
- const hasIndistinguishablePreExistingMatch = beforeMatches.some((match) => match.name.toLowerCase() === name.toLowerCase() && !browserMediaIdentity(match));
243
- if (hasIndistinguishablePreExistingMatch) {
244
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for pre-existing ${name}`);
245
- }
246
332
  try {
247
- await this.executeNativeScript(importMediaScript(dirname(normalizedPath), name), this.now() + this.mediaImportTimeoutMs);
248
- }
249
- catch (error) {
250
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
251
- }
252
- const discoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
253
- let sawPreExistingMatch = false;
254
- while (this.now() <= discoveryDeadline) {
255
- 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;
256
346
  try {
257
- 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);
258
348
  }
259
349
  catch (error) {
260
- if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT") {
261
- 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`);
262
- }
263
- throw error;
264
- }
265
- const exactMatches = matches.filter((match) => match.name.toLowerCase() === name.toLowerCase());
266
- if (exactMatches.some((match) => !browserMediaIdentity(match))) {
267
- 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);
268
351
  }
269
- const newMatches = exactMatches.filter((match) => {
270
- const identity = browserMediaIdentity(match);
271
- if (!identity)
272
- return false;
273
- if (beforeIdentities.has(identity)) {
274
- sawPreExistingMatch = true;
275
- 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");
276
359
  }
277
- return true;
278
- });
279
- if (newMatches.length > 1) {
280
- 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()));
281
411
  }
282
- const match = newMatches[0];
283
- if (match) {
284
- const identity = browserMediaIdentity(match);
285
- if (!identity)
286
- throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for ${name}`);
287
- const mediaHandle = this.stableMediaHandle(identity);
288
- const stableMatch = { ...match, handle: mediaHandle };
289
- this.stableMediaHandles.set(identity, mediaHandle);
290
- this.mediaHandles.set(mediaHandle, stableMatch);
291
- return {
292
- mediaHandle,
293
- sourcePath: normalizedPath,
294
- name,
295
- kind: mediaKind(normalizedPath),
296
- };
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);
297
415
  }
298
- if (this.now() >= discoveryDeadline)
299
- break;
300
- 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);
301
417
  }
302
- if (sawPreExistingMatch) {
303
- 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);
304
422
  }
305
- const diagnostics = await this.readBrowserMediaDiagnostics(name);
306
- 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}` : ""}`);
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
+ }
459
+ }
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
+ };
307
472
  }
308
- async searchMedia(query) {
309
- return this.withNativeUi(() => this.searchMediaNative(query));
473
+ async searchMedia(query, options = {}) {
474
+ return this.withNativeUi(() => this.searchMediaNative(query), options.signal);
310
475
  }
311
476
  async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
312
477
  this.assertEnabled();
@@ -316,7 +481,13 @@ export class FinalCutNativeAutomationAdapter {
316
481
  if (!context.frontmost)
317
482
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
318
483
  try {
319
- 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);
320
491
  const normalizedQuery = query.toLocaleLowerCase();
321
492
  if (rawMatches.some((match) => !browserMediaIdentity(match) && match.name.toLocaleLowerCase().includes(normalizedQuery))) {
322
493
  const diagnostics = await this.readBrowserMediaDiagnostics(query);
@@ -350,6 +521,8 @@ export class FinalCutNativeAutomationAdapter {
350
521
  return matches;
351
522
  }
352
523
  catch (error) {
524
+ if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE")
525
+ throw error;
353
526
  if (deadline !== undefined && nativeErrorCode(error) === timeoutCode)
354
527
  throw error;
355
528
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
@@ -364,8 +537,8 @@ export class FinalCutNativeAutomationAdapter {
364
537
  return "";
365
538
  }
366
539
  }
367
- async previewAppendSelectedMedia() {
368
- return this.withNativeUi(() => this.previewSelectedMediaInsertionNative());
540
+ async previewAppendSelectedMedia(options = {}) {
541
+ return this.withNativeUi(() => this.previewSelectedMediaInsertionNative(), options.signal);
369
542
  }
370
543
  async previewSelectedMediaInsertionNative() {
371
544
  this.assertEnabled();
@@ -382,7 +555,7 @@ export class FinalCutNativeAutomationAdapter {
382
555
  if (!context.frontmost)
383
556
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
384
557
  try {
385
- const matches = parseMediaMatches(await this.executor(selectedBrowserMediaScript()));
558
+ const matches = parseMediaMatches(await this.executeNativeScript(selectedBrowserMediaScript()));
386
559
  if (matches.length === 0)
387
560
  throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: no selected Browser media was exposed by Accessibility");
388
561
  if (matches.length > 1)
@@ -398,8 +571,8 @@ export class FinalCutNativeAutomationAdapter {
398
571
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
399
572
  }
400
573
  }
401
- async selectMedia(handle) {
402
- return this.withNativeUi(() => this.selectMediaNative(handle));
574
+ async selectMedia(handle, options = {}) {
575
+ return this.withNativeUi(() => this.selectMediaNative(handle), options.signal);
403
576
  }
404
577
  async selectMediaNative(handle) {
405
578
  this.assertEnabled();
@@ -410,7 +583,7 @@ export class FinalCutNativeAutomationAdapter {
410
583
  if (!before.frontmost)
411
584
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
412
585
  try {
413
- await this.executor(selectMediaScript(match));
586
+ await this.executeNativeScript(selectMediaScript(match));
414
587
  }
415
588
  catch (error) {
416
589
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
@@ -422,11 +595,11 @@ export class FinalCutNativeAutomationAdapter {
422
595
  target: { kind: "browser-media", name: match.name, ...(match.role ? { role: match.role } : {}) },
423
596
  };
424
597
  }
425
- async locateOccurrence(mediaHandle) {
426
- return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle));
598
+ async locateOccurrence(mediaHandle, options = {}) {
599
+ return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle), options.signal);
427
600
  }
428
- async targetMedia(query) {
429
- return this.withNativeUi(() => this.targetMediaNative(query));
601
+ async targetMedia(query, options = {}) {
602
+ return this.withNativeUi(() => this.targetMediaNative(query), options.signal);
430
603
  }
431
604
  async targetMediaNative(query) {
432
605
  this.assertEnabled();
@@ -451,11 +624,38 @@ export class FinalCutNativeAutomationAdapter {
451
624
  if (!live?.playheadTime) {
452
625
  throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_UNAVAILABLE: deterministic targeting requires live playhead state");
453
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);
454
653
  return {
455
654
  query,
456
655
  status: "unique",
457
656
  media,
458
- occurrence: located.occurrences[0],
657
+ occurrence,
658
+ target,
459
659
  selected: true,
460
660
  playheadTime: `${live.playheadTime.value}/${live.playheadTime.timescale}`,
461
661
  };
@@ -475,7 +675,7 @@ export class FinalCutNativeAutomationAdapter {
475
675
  let occurrenceOutput = "";
476
676
  for (let attempt = 0; attempt < 2; attempt += 1) {
477
677
  try {
478
- occurrenceOutput = await this.executor(locateOccurrenceScript(match, scanAll));
678
+ occurrenceOutput = await this.executeNativeScript(locateOccurrenceScript(match, scanAll));
479
679
  break;
480
680
  }
481
681
  catch (error) {
@@ -491,7 +691,7 @@ export class FinalCutNativeAutomationAdapter {
491
691
  if (timelineOffset === undefined) {
492
692
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
493
693
  }
494
- await selectTimelineOccurrence(this.executor, timelineOffset);
694
+ await this.selectTimelineOccurrence(timelineOffset);
495
695
  await this.ensureOccurrenceRange(occurrences[0]);
496
696
  const selectedContext = await this.inspectRawNative();
497
697
  if (selectedContext.target.kind !== "selected-clip" || !selectedContext.target.identity) {
@@ -524,8 +724,8 @@ export class FinalCutNativeAutomationAdapter {
524
724
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
525
725
  }
526
726
  }
527
- async previewBlade(occurrenceHandle) {
528
- return this.withNativeUi(() => this.previewBladeNative(occurrenceHandle));
727
+ async previewBlade(occurrenceHandle, options = {}) {
728
+ return this.withNativeUi(() => this.previewBladeNative(occurrenceHandle), options.signal);
529
729
  }
530
730
  async previewBladeNative(occurrenceHandle) {
531
731
  this.assertEnabled();
@@ -557,14 +757,14 @@ export class FinalCutNativeAutomationAdapter {
557
757
  expiresAt: new Date(expiresAtMs).toISOString(),
558
758
  };
559
759
  }
560
- async executeBlade(previewToken) {
561
- return this.withNativeUi(() => this.executeBladeNative(previewToken));
760
+ async executeBlade(previewToken, options = {}) {
761
+ return this.withNativeUi(() => this.executeBladeNative(previewToken), options.signal);
562
762
  }
563
- async previewMask(request) {
564
- return this.withNativeUi(() => this.previewMaskNative(request));
763
+ async previewMask(request, options = {}) {
764
+ return this.withNativeUi(() => this.previewMaskNative(request), options.signal);
565
765
  }
566
- async executeMask(previewToken) {
567
- return this.withNativeUi(() => this.executeMaskNative(previewToken));
766
+ async executeMask(previewToken, options = {}) {
767
+ return this.withNativeUi(() => this.executeMaskNative(previewToken), options.signal);
568
768
  }
569
769
  async previewMaskNative(request) {
570
770
  this.assertEnabled();
@@ -609,7 +809,7 @@ export class FinalCutNativeAutomationAdapter {
609
809
  this.maskPreviews.delete(previewToken);
610
810
  if (this.now() > preview.expiresAt)
611
811
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native mask preview has expired");
612
- const before = await this.requireTimelineContext();
812
+ const before = await this.requireNativeWriteContext();
613
813
  const beforeLive = await this.requireLiveState();
614
814
  if (!before.frontmost)
615
815
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
@@ -621,7 +821,7 @@ export class FinalCutNativeAutomationAdapter {
621
821
  let observedAfter;
622
822
  let observedLive;
623
823
  try {
624
- const observedMask = parseNativeMaskReadback(await this.executor(applyMaskScript(preview.mask)));
824
+ const observedMask = parseNativeMaskReadback(await this.executeNativeScript(applyMaskScript(preview.mask)));
625
825
  observedAfter = await this.requireTimelineContext();
626
826
  observedLive = await this.waitForRevision(beforeLive.revision.id);
627
827
  const verification = verifyNativeMask(preview, observedAfter, beforeLive, observedLive, observedMask);
@@ -706,7 +906,7 @@ export class FinalCutNativeAutomationAdapter {
706
906
  this.bladePreviews.delete(previewToken);
707
907
  if (this.now() > preview.expiresAt)
708
908
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: Blade preview has expired");
709
- const before = await this.requireTimelineContext();
909
+ const before = await this.requireNativeWriteContext();
710
910
  if (!before.frontmost)
711
911
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
712
912
  if (before.target.kind !== "selected-clip")
@@ -732,7 +932,7 @@ export class FinalCutNativeAutomationAdapter {
732
932
  if (!after.frontmost)
733
933
  throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut changed focus during Blade");
734
934
  const afterLive = await this.readLiveState();
735
- 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);
736
936
  normalizeOccurrenceTimes(resultingSegments, afterLive?.sequence);
737
937
  if (resultingSegments.length < 2) {
738
938
  throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut did not expose two resulting timeline segments after Blade");
@@ -751,13 +951,13 @@ export class FinalCutNativeAutomationAdapter {
751
951
  ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
752
952
  };
753
953
  }
754
- async previewDeleteRange(range) {
755
- return this.withNativeUi(() => this.previewRangeNative("delete-range", range));
954
+ async previewDeleteRange(range, options = {}) {
955
+ return this.withNativeUi(() => this.previewRangeNative("delete-range", range), options.signal);
756
956
  }
757
- async executeDeleteRange(previewToken) {
758
- return this.withNativeUi(() => this.executeRangeNative(previewToken));
957
+ async executeDeleteRange(previewToken, options = {}) {
958
+ return this.withNativeUi(() => this.executeRangeNative(previewToken), options.signal);
759
959
  }
760
- async previewTrimToDuration(duration) {
960
+ async previewTrimToDuration(duration, options = {}) {
761
961
  return this.withNativeUi(async () => {
762
962
  this.assertEnabled();
763
963
  const live = await this.requireLiveState();
@@ -776,49 +976,49 @@ export class FinalCutNativeAutomationAdapter {
776
976
  }
777
977
  const range = { start: addRational(sequenceStart, duration), end: addRational(sequenceStart, currentDuration) };
778
978
  return this.createRangePreview("trim-to-duration", range, currentDuration, duration, live, duration);
779
- });
979
+ }, options.signal);
780
980
  }
781
- async executeTrimToDuration(previewToken) {
782
- return this.withNativeUi(() => this.executeRangeNative(previewToken, "trim-to-duration"));
981
+ async executeTrimToDuration(previewToken, options = {}) {
982
+ return this.withNativeUi(() => this.executeRangeNative(previewToken, "trim-to-duration"), options.signal);
783
983
  }
784
- async previewAppendMedia(mediaHandle) {
785
- return this.withNativeUi(() => this.previewMediaInsertionNative("append", mediaHandle));
984
+ async previewAppendMedia(mediaHandle, options = {}) {
985
+ return this.withNativeUi(() => this.previewMediaInsertionNative("append", mediaHandle), options.signal);
786
986
  }
787
- async executeAppendMedia(previewToken) {
788
- return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "handle"));
987
+ async executeAppendMedia(previewToken, options = {}) {
988
+ return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "handle"), options.signal);
789
989
  }
790
- async executeAppendSelectedMedia(previewToken) {
791
- return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "selected"));
990
+ async executeAppendSelectedMedia(previewToken, options = {}) {
991
+ return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "selected"), options.signal);
792
992
  }
793
- async previewInsertMedia(mediaHandle) {
794
- return this.withNativeUi(() => this.previewMediaInsertionNative("insert", mediaHandle));
993
+ async previewInsertMedia(mediaHandle, options = {}) {
994
+ return this.withNativeUi(() => this.previewMediaInsertionNative("insert", mediaHandle), options.signal);
795
995
  }
796
- async executeInsertMedia(previewToken) {
797
- return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "insert"));
996
+ async executeInsertMedia(previewToken, options = {}) {
997
+ return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "insert"), options.signal);
798
998
  }
799
- async previewTitleAdd(request) {
800
- return this.withNativeUi(() => this.previewTitleAddNative(request));
999
+ async previewTitleAdd(request, options = {}) {
1000
+ return this.withNativeUi(() => this.previewTitleAddNative(request), options.signal);
801
1001
  }
802
- async executeTitleAdd(previewToken) {
803
- return this.withNativeUi(() => this.executeTitleAddNative(previewToken));
1002
+ async executeTitleAdd(previewToken, options = {}) {
1003
+ return this.withNativeUi(() => this.executeTitleAddNative(previewToken), options.signal);
804
1004
  }
805
- async searchTitles(query) {
806
- return this.withNativeUi(() => this.searchTitlesNative(query));
1005
+ async searchTitles(query, options = {}) {
1006
+ return this.withNativeUi(() => this.searchTitlesNative(query), options.signal);
807
1007
  }
808
- async previewPictureInPicture(request) {
809
- return this.withNativeUi(() => this.previewPictureInPictureNative(request));
1008
+ async previewPictureInPicture(request, options = {}) {
1009
+ return this.withNativeUi(() => this.previewPictureInPictureNative(request), options.signal);
810
1010
  }
811
- async executePictureInPicture(previewToken) {
812
- return this.withNativeUi(() => this.executePictureInPictureNative(previewToken));
1011
+ async executePictureInPicture(previewToken, options = {}) {
1012
+ return this.withNativeUi(() => this.executePictureInPictureNative(previewToken), options.signal);
813
1013
  }
814
- async searchTransitions(query) {
815
- return this.withNativeUi(() => this.searchTransitionsNative(query));
1014
+ async searchTransitions(query, options = {}) {
1015
+ return this.withNativeUi(() => this.searchTransitionsNative(query), options.signal);
816
1016
  }
817
- async previewTransitionAdd(request) {
818
- return this.withNativeUi(() => this.previewTransitionAddNative(request));
1017
+ async previewTransitionAdd(request, options = {}) {
1018
+ return this.withNativeUi(() => this.previewTransitionAddNative(request), options.signal);
819
1019
  }
820
- async executeTransitionAdd(previewToken) {
821
- return this.withNativeUi(() => this.executeTransitionAddNative(previewToken));
1020
+ async executeTransitionAdd(previewToken, options = {}) {
1021
+ return this.withNativeUi(() => this.executeTransitionAddNative(previewToken), options.signal);
822
1022
  }
823
1023
  async searchTitlesNative(query) {
824
1024
  this.assertEnabled();
@@ -829,7 +1029,13 @@ export class FinalCutNativeAutomationAdapter {
829
1029
  let lastError;
830
1030
  for (let attempt = 0; attempt < 2; attempt += 1) {
831
1031
  try {
832
- return parseTitleMatches(await this.executeNativeScript(titleSearchScript(identity ?? normalizedQuery, identity !== undefined)));
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;
833
1039
  }
834
1040
  catch (error) {
835
1041
  lastError = error;
@@ -853,8 +1059,6 @@ export class FinalCutNativeAutomationAdapter {
853
1059
  }
854
1060
  async searchTransitionsNative(query) {
855
1061
  this.assertEnabled();
856
- if (!query.trim())
857
- throw new Error("INVALID_OPERATION: transition search query cannot be empty");
858
1062
  const context = await this.requireTimelineContext();
859
1063
  if (!context.frontmost)
860
1064
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut must be frontmost for transition discovery");
@@ -926,7 +1130,7 @@ export class FinalCutNativeAutomationAdapter {
926
1130
  this.transitionPreviews.delete(previewToken);
927
1131
  if (this.now() > preview.expiresAt)
928
1132
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native transition preview has expired");
929
- const before = await this.requireTimelineContext();
1133
+ const before = await this.requireNativeWriteContext();
930
1134
  const beforeLive = await this.requireLiveState();
931
1135
  validateTransitionPreviewBinding(preview, beforeLive);
932
1136
  const frameDuration = beforeLive.sequence?.frameDuration;
@@ -951,7 +1155,7 @@ export class FinalCutNativeAutomationAdapter {
951
1155
  await this.waitForPlayhead(preview.editPoint, beforeLive.sequence?.id);
952
1156
  // Command-T may mutate before duration editing fails. Never retry this
953
1157
  // script: the outer recovery path observes and rolls back that mutation.
954
- observedDuration = parseObservedTransitionDuration(await this.executor(applyTransitionScript(preview.duration, frameDuration)), frameDuration);
1158
+ observedDuration = parseObservedTransitionDuration(await this.executeNativeScript(applyTransitionScript(preview.duration, frameDuration)), frameDuration);
955
1159
  if (compareRational(observedDuration, preview.duration) !== 0) {
956
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}`);
957
1161
  }
@@ -1095,22 +1299,22 @@ export class FinalCutNativeAutomationAdapter {
1095
1299
  this.titlePreviews.delete(previewToken);
1096
1300
  if (this.now() > preview.expiresAt)
1097
1301
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native title preview has expired");
1098
- const before = await this.requireTimelineContext();
1302
+ const before = await this.requireNativeWriteContext();
1099
1303
  const beforeLive = await this.requireLiveState();
1100
1304
  this.validateTitleBinding(preview, beforeLive);
1101
1305
  const startTimecode = this.toTimecode(preview.start, beforeLive);
1102
1306
  const endTimecode = this.toTimecode(preview.end, beforeLive);
1103
1307
  try {
1104
1308
  await this.executeNativeSequence(async () => {
1105
- await this.executor(titleAssetSelectionScript(preview.asset.name, nativeTitleIdentity(preview.asset)));
1309
+ await this.executeNativeScript(titleAssetSelectionScript(preview.asset.name, nativeTitleIdentity(preview.asset)));
1106
1310
  await this.focusTimelineForMediaInsertion();
1107
- await this.executor(setPlayheadScript(startTimecode));
1311
+ await this.executeNativeScript(setPlayheadScript(startTimecode));
1108
1312
  await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
1109
- await this.executor(markRangeStartScript());
1110
- await this.executor(setPlayheadScript(endTimecode));
1313
+ await this.executeNativeScript(markRangeStartScript());
1314
+ await this.executeNativeScript(setPlayheadScript(endTimecode));
1111
1315
  await this.waitForPlayhead(preview.end, beforeLive.sequence?.id);
1112
- await this.executor(markRangeEndAndConnectTitleScript());
1113
- await this.executor(titleTextEditScript(preview.text));
1316
+ await this.executeNativeScript(markRangeEndAndConnectTitleScript());
1317
+ await this.executeNativeScript(titleTextEditScript(preview.text));
1114
1318
  }, async (recovered) => {
1115
1319
  const targetChanged = before.target.kind !== recovered.target.kind
1116
1320
  || before.target.name !== recovered.target.name
@@ -1242,7 +1446,7 @@ export class FinalCutNativeAutomationAdapter {
1242
1446
  if (this.selectedMediaHandle !== preview.mediaHandle) {
1243
1447
  throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before picture-in-picture placement");
1244
1448
  }
1245
- const before = await this.requireTimelineContext();
1449
+ const before = await this.requireNativeWriteContext();
1246
1450
  const beforeLive = await this.requireLiveState();
1247
1451
  validatePictureInPicturePreviewBinding(preview, beforeLive);
1248
1452
  const anchorOccurrence = this.occurrenceHandles.get(preview.anchorOccurrence.handle) ?? preview.anchorOccurrence;
@@ -1255,16 +1459,16 @@ export class FinalCutNativeAutomationAdapter {
1255
1459
  await this.selectMediaNative(preview.mediaHandle);
1256
1460
  await this.focusTimelineForMediaInsertion();
1257
1461
  if (this.canDriveNativeMouse && anchorOccurrence.timelineOffset !== undefined) {
1258
- await selectTimelineOccurrence(this.executor, anchorOccurrence.timelineOffset);
1462
+ await this.selectTimelineOccurrence(anchorOccurrence.timelineOffset);
1259
1463
  }
1260
1464
  await this.validateSelectedPictureInPictureAnchor(anchorOccurrence);
1261
- await this.executor(setPlayheadScript(startTimecode));
1465
+ await this.executeNativeScript(setPlayheadScript(startTimecode));
1262
1466
  await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
1263
- await this.executor(markRangeStartScript());
1264
- await this.executor(setPlayheadScript(endTimecode));
1467
+ await this.executeNativeScript(markRangeStartScript());
1468
+ await this.executeNativeScript(setPlayheadScript(endTimecode));
1265
1469
  await this.waitForPlayhead(preview.end, beforeLive.sequence?.id);
1266
- await this.executor(markRangeEndAndConnectPictureInPictureScript());
1267
- await this.executor(pictureInPictureTransformScript(preview));
1470
+ await this.executeNativeScript(markRangeEndAndConnectPictureInPictureScript());
1471
+ await this.executeNativeScript(pictureInPictureTransformScript(preview));
1268
1472
  }, async (recovered) => {
1269
1473
  this.assertRetryContext(before, recovered, true);
1270
1474
  validatePictureInPicturePreviewBinding(preview, await this.requireLiveState());
@@ -1300,7 +1504,7 @@ export class FinalCutNativeAutomationAdapter {
1300
1504
  after = await this.requireTimelineContext();
1301
1505
  afterLive = await this.waitForRevision(beforeLive.revision.id);
1302
1506
  const occurrence = await this.readPictureInPictureOccurrence(preview, anchorOccurrence);
1303
- const observed = parsePictureInPictureReadback(await this.executor(pictureInPictureInspectorReadbackScript()));
1507
+ const observed = parsePictureInPictureReadback(await this.executeNativeScript(pictureInPictureInspectorReadbackScript()));
1304
1508
  const verification = verifyNativePictureInPicture({ ...preview, media }, after, beforeLive, afterLive, observed, occurrence);
1305
1509
  const operation = {
1306
1510
  kind: "picture-in-picture",
@@ -1433,7 +1637,7 @@ export class FinalCutNativeAutomationAdapter {
1433
1637
  if (preview.selectionMode === "handle" && this.selectedMediaHandle !== preview.mediaHandle) {
1434
1638
  throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before insertion");
1435
1639
  }
1436
- const before = await this.requireTimelineContext();
1640
+ const before = await this.requireNativeWriteContext();
1437
1641
  const beforeLive = await this.requireLiveState();
1438
1642
  this.validateMediaInsertionBinding(preview, beforeLive);
1439
1643
  if (preview.selectionMode === "selected")
@@ -1534,7 +1738,7 @@ export class FinalCutNativeAutomationAdapter {
1534
1738
  async focusTimelineForMediaInsertion() {
1535
1739
  if (!this.canDriveNativeMouse)
1536
1740
  return;
1537
- const coordinates = (await this.executor(timelineInsertionCoordinatesScript())).split("|").map(Number);
1741
+ const coordinates = (await this.executeNativeScript(timelineInsertionCoordinatesScript())).split("|").map(Number);
1538
1742
  const [originX, originY, width, height] = coordinates;
1539
1743
  if (![originX, originY, width, height].every(Number.isFinite)) {
1540
1744
  throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut timeline coordinates");
@@ -1542,9 +1746,11 @@ export class FinalCutNativeAutomationAdapter {
1542
1746
  const x = Math.round(originX + width * 0.5);
1543
1747
  const y = Math.round(originY + height * 0.82);
1544
1748
  try {
1545
- await execFile("swift", ["-e", nativeMouseFocusSource(x, y)]);
1749
+ await this.executeNativeMouseScript(nativeMouseFocusSource(x, y));
1546
1750
  }
1547
1751
  catch (error) {
1752
+ if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_CANCELLED" || nativeErrorCode(error) === "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT")
1753
+ throw error;
1548
1754
  throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline focus failed: ${String(error)}`);
1549
1755
  }
1550
1756
  }
@@ -1607,7 +1813,7 @@ export class FinalCutNativeAutomationAdapter {
1607
1813
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: range preview has expired");
1608
1814
  if (expectedOperation && preview.operation !== expectedOperation)
1609
1815
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview operation does not match execute operation");
1610
- const before = await this.requireTimelineContext();
1816
+ const before = await this.requireNativeWriteContext();
1611
1817
  const beforeLive = await this.requireLiveState();
1612
1818
  this.validateRangeBinding(preview, beforeLive);
1613
1819
  const rangeDuration = subtractRational(preview.range.end, preview.range.start);
@@ -1756,24 +1962,24 @@ export class FinalCutNativeAutomationAdapter {
1756
1962
  const startTimecode = this.toTimecode(range.start, beforeLive);
1757
1963
  const endTimecode = this.toTimecode(range.end, beforeLive);
1758
1964
  const executeRange = async () => {
1759
- await this.executor(setPlayheadScript(startTimecode));
1965
+ await this.executeNativeScript(setPlayheadScript(startTimecode));
1760
1966
  await this.waitForPlayhead(range.start, beforeLive.sequence?.id);
1761
- await this.executor(markRangeStartScript());
1762
- await this.executor(setPlayheadScript(endTimecode));
1967
+ await this.executeNativeScript(markRangeStartScript());
1968
+ await this.executeNativeScript(setPlayheadScript(endTimecode));
1763
1969
  await this.waitForPlayhead(range.end, beforeLive.sequence?.id);
1764
- await this.executor(markRangeEndAndDeleteScript());
1970
+ await this.executeNativeScript(markRangeEndAndDeleteScript());
1765
1971
  };
1766
1972
  await this.executeNativeSequence(executeRange, validateRetry);
1767
1973
  }
1768
1974
  async executeNativeCommand(script, validateRetry) {
1769
1975
  try {
1770
- await this.executor(script);
1976
+ await this.executeNativeScript(script);
1771
1977
  }
1772
1978
  catch (error) {
1773
1979
  if (!isRecoverableNativeFocusRace(error))
1774
1980
  throw error;
1775
1981
  await validateRetry?.(await this.prepareNativeRetry());
1776
- await this.executor(script);
1982
+ await this.executeNativeScript(script);
1777
1983
  }
1778
1984
  }
1779
1985
  async executeNativeSequence(execute, validateRetry) {
@@ -1827,27 +2033,30 @@ export class FinalCutNativeAutomationAdapter {
1827
2033
  if (!this.enabled)
1828
2034
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native writes are disabled");
1829
2035
  }
1830
- async withNativeUi(operation) {
1831
- const outermost = this.nativeUiDepth === 0;
1832
- if (outermost && this.enabled) {
1833
- if (this.nativeOperationLease)
1834
- this.nativeOperationLease.acquire();
1835
- else
1836
- this.suspendLiveConnection?.();
1837
- }
1838
- this.nativeUiDepth += 1;
1839
- try {
1840
- return await operation();
1841
- }
1842
- finally {
1843
- 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;
1844
2040
  if (outermost && this.enabled) {
1845
2041
  if (this.nativeOperationLease)
1846
- this.nativeOperationLease.release();
2042
+ this.nativeOperationLease.acquire();
1847
2043
  else
1848
- this.resumeLiveConnection?.();
2044
+ this.suspendLiveConnection?.();
1849
2045
  }
1850
- }
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
+ });
1851
2060
  }
1852
2061
  async validateOccurrenceBinding(occurrence) {
1853
2062
  if (!this.liveState || !occurrence.revision)
@@ -1927,14 +2136,14 @@ export class FinalCutNativeAutomationAdapter {
1927
2136
  let startLive;
1928
2137
  let endLive;
1929
2138
  try {
1930
- await this.executor(occurrenceRangeEndpointScript(occurrence.timelineOffset, "start"));
2139
+ await this.executeNativeScript(occurrenceRangeEndpointScript(occurrence.timelineOffset, "start"));
1931
2140
  startLive = await this.waitForLivePlayheadChangeOrCurrent(originalLive, "start");
1932
- await this.executor(occurrenceRangeEndpointScript(occurrence.timelineOffset, "end"));
2141
+ await this.executeNativeScript(occurrenceRangeEndpointScript(occurrence.timelineOffset, "end"));
1933
2142
  endLive = await this.waitForLivePlayheadChangeOrCurrent(startLive, "end");
1934
2143
  }
1935
2144
  finally {
1936
2145
  try {
1937
- await this.executor(setPlayheadScript(this.toTimecode(originalLive.playheadTime, originalLive)));
2146
+ await this.executeNativeScript(setPlayheadScript(this.toTimecode(originalLive.playheadTime, originalLive)));
1938
2147
  await this.waitForPlayhead(originalLive.playheadTime, originalLive.sequence?.id);
1939
2148
  }
1940
2149
  catch {
@@ -1981,11 +2190,25 @@ export class FinalCutNativeAutomationAdapter {
1981
2190
  if (requiresClip(operation) && context.target.kind !== "selected-clip") {
1982
2191
  throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one clip in Final Cut Pro");
1983
2192
  }
1984
- if (!requiresClip(operation) && context.target.kind === "none") {
2193
+ if (!requiresClip(operation) && (context.target.kind === "none" || context.target.kind === "unknown")) {
1985
2194
  throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: position the playhead in Final Cut Pro");
1986
2195
  }
2196
+ this.assertNativeWriteContext(context);
1987
2197
  return context;
1988
2198
  }
2199
+ async requireNativeWriteContext() {
2200
+ const context = await this.requireTimelineContext();
2201
+ this.assertNativeWriteContext(context);
2202
+ return context;
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
+ }
1989
2212
  async requireTimelineContext() {
1990
2213
  const context = await this.attachLiveState(await this.ensureTimelineReady());
1991
2214
  if (!context.available) {
@@ -2005,7 +2228,8 @@ export class FinalCutNativeAutomationAdapter {
2005
2228
  let lastContext;
2006
2229
  while (this.now() < deadline) {
2007
2230
  try {
2008
- 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);
2009
2233
  lastContext = context;
2010
2234
  if (!context.timelineWindowAvailable) {
2011
2235
  lastCode = "FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW";
@@ -2031,6 +2255,8 @@ export class FinalCutNativeAutomationAdapter {
2031
2255
  const code = nativeErrorCode(error);
2032
2256
  if (code === "FINAL_CUT_NATIVE_PERMISSION_REQUIRED")
2033
2257
  throw new NativeFinalCutPreflightError(code, nativeErrorMessage(error), lastContext);
2258
+ if (code === "FINAL_CUT_NATIVE_CANCELLED")
2259
+ throw new NativeFinalCutPreflightError(code, nativeErrorMessage(error), lastContext);
2034
2260
  lastCode = code;
2035
2261
  lastMessage = nativeErrorMessage(error);
2036
2262
  }
@@ -2058,29 +2284,122 @@ export class FinalCutNativeAutomationAdapter {
2058
2284
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut could not be brought to the front for Browser automation");
2059
2285
  return context;
2060
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
+ }
2061
2353
  stableMediaHandle(identity) {
2062
2354
  return `media-import-${createHash("sha256").update(identity).digest("hex").slice(0, 24)}`;
2063
2355
  }
2064
2356
  async executeNativeScript(script, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
2065
- if (deadline === undefined)
2066
- return this.executor(script);
2067
- 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();
2068
2362
  if (remaining <= 0)
2069
2363
  throw new Error(`${timeoutCode}: native automation deadline expired`);
2070
2364
  const controller = new AbortController();
2071
2365
  let timer;
2366
+ let cancelListener;
2367
+ let timedOut = false;
2368
+ let cancelled = false;
2072
2369
  const timeout = new Promise((_, reject) => {
2073
2370
  timer = setTimeout(() => {
2371
+ timedOut = true;
2074
2372
  controller.abort();
2075
2373
  reject(new Error(`${timeoutCode}: native automation deadline expired`));
2076
2374
  }, remaining);
2077
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 });
2078
2387
  try {
2079
- 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;
2080
2396
  }
2081
2397
  finally {
2082
2398
  if (timer !== undefined)
2083
2399
  clearTimeout(timer);
2400
+ if (requestSignal && cancelListener)
2401
+ requestSignal.removeEventListener("abort", cancelListener);
2402
+ void execution.catch(() => { });
2084
2403
  }
2085
2404
  }
2086
2405
  }
@@ -2107,6 +2426,9 @@ function assertNativeTitleAsset(asset) {
2107
2426
  throw new Error("TITLE_ASSET_NOT_FOUND: native title asset identity is incomplete");
2108
2427
  if (asset.kind !== "title")
2109
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
+ }
2110
2432
  }
2111
2433
  function nativeTitleIdentity(asset) {
2112
2434
  const idIdentity = titleIdentityFromId(asset.id);
@@ -2558,6 +2880,171 @@ function requireFrontmostAppleScript() {
2558
2880
  return `
2559
2881
  if not frontmost then error number -1719`;
2560
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
+ }
2561
3048
  function timelinePreflightScript() {
2562
3049
  return `
2563
3050
  on findInspectorField(fieldLabel)
@@ -2967,7 +3454,7 @@ function searchMediaScript(query) {
2967
3454
  set value of searchField to searchQuery
2968
3455
  key code 36
2969
3456
  delay 0.5
2970
- set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, false, {}, "root")
3457
+ set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, browserRootContext, {}, "root")
2971
3458
  return output
2972
3459
  end tell
2973
3460
  end tell`;
@@ -2989,7 +3476,7 @@ function selectedBrowserMediaScript() {
2989
3476
  set seenSourceIdentities to {}
2990
3477
  set browserRoot to mainWindow
2991
3478
  try
2992
- set browserSearchResult to my findBrowserSearchControl(mainWindow, 0, origin, size of mainWindow)
3479
+ set browserSearchResult to my findBrowserSearchControl(mainWindow, 0, false, missing value)
2993
3480
  if browserSearchResult is not missing value then set browserRoot to item 2 of browserSearchResult
2994
3481
  end try
2995
3482
  try
@@ -3036,62 +3523,20 @@ end tell`;
3036
3523
  }
3037
3524
  function browserSearchFieldScript() {
3038
3525
  return `
3039
- set origin to position of mainWindow
3040
- set windowSize to size of mainWindow
3041
3526
  set searchFieldFound to false
3042
3527
  set searchField to missing value
3043
3528
  set searchButton to missing value
3044
- set browserRoot to mainWindow
3045
- -- The Transitions browser may already be open. Prefer the bounded
3046
- -- Browser search control so its Effects Library field cannot capture a
3047
- -- media query.
3048
- try
3049
- 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
3050
- set searchFieldFound to true
3051
- on error
3052
- set searchField to missing value
3053
- end try
3529
+ set searchButtonIsToggle to false
3530
+ set browserRootContext to false
3054
3531
  try
3055
- if not searchFieldFound then
3056
- set focusedCandidate to value of attribute "AXFocusedUIElement"
3057
- set focusedRole to role of focusedCandidate as text
3058
- set focusedDescription to ""
3059
- try
3060
- set focusedDescription to description of focusedCandidate as text
3061
- end try
3062
- if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) and my browserSearchCandidateVisible(focusedCandidate, origin, windowSize) then
3063
- set searchField to focusedCandidate
3064
- set searchFieldFound to true
3065
- 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)
3066
3536
  end if
3067
3537
  end try
3068
- if not searchFieldFound then
3069
- repeat with searchOffset in {368, 400, 340, 561, 531, 501}
3070
- repeat with searchY in {52, 38}
3071
- try
3072
- click at {(item 1 of origin) + (searchOffset as integer), (item 2 of origin) + (searchY as integer)}
3073
- delay 0.15
3074
- set focusedCandidate to value of attribute "AXFocusedUIElement"
3075
- set focusedRole to role of focusedCandidate as text
3076
- set focusedDescription to ""
3077
- try
3078
- set focusedDescription to description of focusedCandidate as text
3079
- end try
3080
- if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) then
3081
- set searchField to focusedCandidate
3082
- set searchFieldFound to true
3083
- exit repeat
3084
- end if
3085
- end try
3086
- end repeat
3087
- if searchFieldFound then exit repeat
3088
- end repeat
3089
- end if
3090
- try
3091
- if my revealBrowser(mainWindow, 0) then delay 0.5
3092
- end try
3093
3538
  try
3094
- 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)
3095
3540
  if searchControlResult is not missing value then
3096
3541
  set searchControl to item 1 of searchControlResult
3097
3542
  set browserRoot to item 2 of searchControlResult
@@ -3101,53 +3546,51 @@ function browserSearchFieldScript() {
3101
3546
  set searchFieldFound to true
3102
3547
  else if searchRole is "AXButton" then
3103
3548
  set searchButton to searchControl
3549
+ set searchButtonIsToggle to my browserSearchToggle(searchControl)
3550
+ set browserRootContext to searchButtonIsToggle
3104
3551
  end if
3105
3552
  end if
3106
3553
  end try
3107
- if not searchFieldFound then
3554
+ if not searchFieldFound and searchButton is not missing value then
3108
3555
  try
3109
- set searchControlResult to my findBrowserSearchControl(mainWindow, 0, origin, windowSize)
3110
- if searchControlResult is not missing value then
3111
- set searchControl to item 1 of searchControlResult
3112
- set browserRoot to item 2 of searchControlResult
3113
- set searchRole to role of searchControl as text
3114
- if searchRole is "AXSearchField" or searchRole is "AXTextField" then
3115
- set searchField to searchControl
3116
- set searchFieldFound to true
3117
- else if searchRole is "AXButton" then
3118
- set searchButton to searchControl
3119
- end if
3120
- end if
3121
- end try
3122
- end if
3123
- if not searchFieldFound and searchButton is missing value then
3124
- try
3125
- 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
3126
- set directSearchDescription to description of directSearchButton as text
3127
- if directSearchDescription contains "search" or directSearchDescription contains "Search" then
3128
- 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
3129
3566
  end if
3130
- end try
3131
- end if
3132
- if not searchFieldFound then
3133
- if searchButton is not missing value then
3134
- try
3567
+ if not searchFieldFound then
3135
3568
  perform action "AXPress" of searchButton
3136
3569
  delay 0.2
3137
- set focusedCandidate to value of attribute "AXFocusedUIElement"
3138
- set focusedRole to role of focusedCandidate as text
3139
- set focusedDescription to ""
3140
3570
  try
3141
- 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
3142
3577
  end try
3143
- if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) then
3144
- set searchField to focusedCandidate
3145
- 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
3146
3589
  end if
3147
- end try
3148
- end if
3590
+ end if
3591
+ end try
3149
3592
  end if
3150
- 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"
3151
3594
  set searchRole to role of searchField as text
3152
3595
  if searchRole is not "AXTextField" and searchRole is not "AXSearchField" then error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser search field was not hit"
3153
3596
  try
@@ -3161,28 +3604,179 @@ function browserSearchFieldScript() {
3161
3604
  function browserSearchControlFinderScript() {
3162
3605
  return `
3163
3606
  using terms from application "System Events"
3164
- on browserSearchCandidateVisible(candidate, mainOrigin, mainSize)
3607
+ on browserSearchContainer(candidate)
3165
3608
  try
3166
- set candidatePosition to position of candidate
3167
- set candidateX to item 1 of candidatePosition
3168
- set candidateY to item 2 of candidatePosition
3169
- 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"
3170
3679
  on error
3171
3680
  return false
3172
3681
  end try
3173
- 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
3174
3720
 
3175
- on findBrowserSearchControl(containerItem, depth, mainOrigin, mainSize)
3721
+ on findBrowserSearchToggle(containerItem, depth, inheritedBrowserContext, inheritedBrowserRoot)
3176
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
3177
3762
  set candidateItems to UI elements of containerItem
3178
3763
  repeat with candidateIndex in my orderedChildIndices(containerItem)
3179
3764
  try
3180
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)}
3181
3775
  set candidateRole to role of candidate as text
3182
- if candidateRole is "AXSearchField" and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
3183
- return {candidate, containerItem}
3776
+ if candidateBrowserContext and candidateRole is "AXSearchField" then
3777
+ return {candidate, candidateBrowserRoot}
3184
3778
  end if
3185
- if candidateRole is "AXTextField" then
3779
+ if candidateBrowserContext and candidateRole is "AXTextField" then
3186
3780
  set candidateName to ""
3187
3781
  set candidateDescription to ""
3188
3782
  try
@@ -3191,19 +3785,19 @@ function browserSearchControlFinderScript() {
3191
3785
  try
3192
3786
  set candidateDescription to description of candidate as text
3193
3787
  end try
3194
- if (candidateName contains "search" or candidateName contains "Search" or candidateDescription contains "search" or candidateDescription contains "Search") and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
3195
- 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}
3196
3790
  end if
3197
3791
  end if
3198
- if candidateRole is "AXButton" then
3792
+ if candidateBrowserContext and candidateRole is "AXButton" then
3199
3793
  set candidateDescription to description of candidate as text
3200
- if (candidateDescription contains "search" or candidateDescription contains "Search") and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
3201
- return {candidate, containerItem}
3794
+ if candidateDescription contains "search" or candidateDescription contains "Search" then
3795
+ return {candidate, candidateBrowserRoot}
3202
3796
  end if
3203
3797
  end if
3204
3798
  end try
3205
3799
  try
3206
- set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1, mainOrigin, mainSize)
3800
+ set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1, candidateBrowserContext, candidateBrowserRoot)
3207
3801
  if nestedCandidate is not missing value then
3208
3802
  return nestedCandidate
3209
3803
  end if
@@ -3266,6 +3860,7 @@ function browserMediaTraversalScript() {
3266
3860
  end splitText
3267
3861
 
3268
3862
  on mediaContainer(containerItem, inheritedContext)
3863
+ if inheritedContext then return true
3269
3864
  set containerText to ""
3270
3865
  try
3271
3866
  set containerText to description of containerItem as text
@@ -3286,7 +3881,7 @@ function browserMediaTraversalScript() {
3286
3881
 
3287
3882
  on accessibilityMediaIdentity(candidate, candidateName, candidateRole, mediaContext, browserPath)
3288
3883
  if not mediaContext or candidateName is "" then return ""
3289
- 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
3290
3885
  return ""
3291
3886
  end if
3292
3887
  return "fcp-ax://browser/" & browserPath & "|" & candidateRole & "|" & candidateName
@@ -3294,6 +3889,7 @@ function browserMediaTraversalScript() {
3294
3889
 
3295
3890
  on browserMediaRole(candidateRole, mediaContext, candidateSelected, candidateSourceIdentity)
3296
3891
  if candidateRole is "AXBrowserMedia" or candidateRole is "AXRow" or candidateRole is "AXCell" then return true
3892
+ if candidateRole is "AXTextField" then return mediaContext
3297
3893
  if candidateRole is "AXButton" then return mediaContext and candidateSourceIdentity is not ""
3298
3894
  if candidateRole is "AXGroup" or candidateRole is "AXStaticText" or candidateRole is "AXImage" then return mediaContext or (candidateSelected and candidateSourceIdentity is not "")
3299
3895
  return false
@@ -3309,7 +3905,9 @@ function browserMediaTraversalScript() {
3309
3905
  end browserRegion
3310
3906
 
3311
3907
  on collectBrowserMedia(containerItem, depth, searchQuery, origin, inheritedContext, seenIdentities, browserPath)
3312
- if depth > 12 then return ""
3908
+ set maxDepth to 12
3909
+ if inheritedContext then set maxDepth to 6
3910
+ if depth > maxDepth then return ""
3313
3911
  set output to ""
3314
3912
  set mediaContext to my mediaContainer(containerItem, inheritedContext)
3315
3913
  tell application "System Events"
@@ -3320,40 +3918,51 @@ function browserMediaTraversalScript() {
3320
3918
  set candidate to contents of item candidateIndex of candidateItems
3321
3919
  set candidatePath to browserPath & "/" & (candidateIndex as text)
3322
3920
  set candidateRole to role of candidate as text
3921
+ set candidateMediaContext to my mediaContainer(candidate, mediaContext)
3323
3922
  set candidateName to ""
3324
- try
3325
- set candidateName to value of candidate as text
3326
- end try
3327
- if candidateName is "missing value" then set candidateName to ""
3328
- if candidateName is "" then
3329
- try
3330
- set candidateName to name of candidate as text
3331
- end try
3332
- end if
3333
- if candidateName is "missing value" then set candidateName to ""
3334
- if candidateName is "" then
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
3335
3928
  try
3336
- set candidateName to description of candidate as text
3929
+ set candidateName to value of candidate as text
3337
3930
  end try
3338
- end if
3339
- if candidateName is "missing value" then set candidateName to ""
3340
- set candidateSelected to false
3341
- try
3342
- set candidateSelected to (selected of candidate) is true
3343
- end try
3344
- set candidateSourceIdentity to ""
3345
- try
3346
- set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
3347
- end try
3348
- set candidatePosition to position of candidate
3349
- set candidateMediaContext to my mediaContainer(candidate, mediaContext)
3350
- set isBrowserMedia to my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity)
3351
- set inBrowserRegion to my browserRegion(candidatePosition, origin, candidateMediaContext)
3352
- if candidateSourceIdentity is "" and isBrowserMedia then set candidateSourceIdentity to my accessibilityMediaIdentity(candidate, candidateName, candidateRole, candidateMediaContext, candidatePath)
3353
- if candidateName is not "" and candidateSourceIdentity is not "" and isBrowserMedia and inBrowserRegion and candidateName contains searchQuery then
3354
- if seenIdentities does not contain candidateSourceIdentity then
3355
- set end of seenIdentities to candidateSourceIdentity
3356
- 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
3357
3966
  end if
3358
3967
  end if
3359
3968
  set output to output & my collectBrowserMedia(candidate, depth + 1, searchQuery, origin, candidateMediaContext, seenIdentities, candidatePath)
@@ -3750,21 +4359,6 @@ function locateOccurrenceScript(match, scanAll) {
3750
4359
  end tell
3751
4360
  end tell`;
3752
4361
  }
3753
- async function selectTimelineOccurrence(executor, timelineOffset) {
3754
- const coordinates = (await executor(timelineSelectionCoordinatesScript())).split("|").map(Number);
3755
- const [originX, originY, windowWidth, windowHeight] = coordinates;
3756
- if (!Number.isFinite(originX) || !Number.isFinite(originY) || !Number.isFinite(windowWidth) || !Number.isFinite(windowHeight)) {
3757
- throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut window coordinates");
3758
- }
3759
- const x = Math.round(originX + timelineOffset);
3760
- const y = Math.round(originY + (windowHeight * 0.77));
3761
- try {
3762
- await execFile("swift", ["-e", nativeMouseSelectionSource(x, y)]);
3763
- }
3764
- catch (error) {
3765
- throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline selection failed: ${String(error)}`);
3766
- }
3767
- }
3768
4362
  function timelineSelectionCoordinatesScript() {
3769
4363
  return `
3770
4364
  tell application "System Events"
@@ -4713,7 +5307,7 @@ function editScript(operation) {
4713
5307
  ? `click menu item "Trim ${operation.edge === "start" ? "Start" : "End"}" of menu "Trim" of menu bar 1`
4714
5308
  : operation.type === "set-selected-clip-gain"
4715
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`
4716
- : `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`;
4717
5311
  return `
4718
5312
  tell application "System Events"
4719
5313
  tell process "Final Cut Pro"
@@ -4753,7 +5347,7 @@ function parseContext(output) {
4753
5347
  || focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
4754
5348
  ? { kind: "selected-clip", name: focusedName, role: focusedRole }
4755
5349
  : { kind: "playhead" };
4756
- return {
5350
+ const context = {
4757
5351
  available: true,
4758
5352
  application: "Final Cut Pro",
4759
5353
  frontmost: frontState === "true",
@@ -4774,6 +5368,41 @@ function parseContext(output) {
4774
5368
  undoAvailable: undoState === "true",
4775
5369
  ...(undoCommandState ? { undoCommand: undoCommandState } : {}),
4776
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";
4777
5406
  }
4778
5407
  function parseMediaMatches(output) {
4779
5408
  return output
@@ -4794,7 +5423,9 @@ function parseMediaMatches(output) {
4794
5423
  }
4795
5424
  function browserMediaIdentity(match) {
4796
5425
  const identity = match.sourceIdentity?.trim();
4797
- return identity || undefined;
5426
+ if (!identity || identity.startsWith("fcp-ax://browser/"))
5427
+ return undefined;
5428
+ return identity;
4798
5429
  }
4799
5430
  function parseOccurrences(output, mediaHandle) {
4800
5431
  return output
@@ -4848,6 +5479,109 @@ function timelineTimecodeToRational(value, sequence, label, absolute) {
4848
5479
  function opaqueHandle(kind, suffix) {
4849
5480
  return `${kind}-${Date.now().toString(36)}-${suffix ?? Math.random().toString(36).slice(2, 8)}`;
4850
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
+ }
4851
5585
  function mediaKind(sourcePath) {
4852
5586
  return new Set([".aif", ".aiff", ".flac", ".m4a", ".mp3", ".wav", ".aac", ".caf"]).has(extname(sourcePath).toLowerCase())
4853
5587
  ? "audio"
@@ -4956,21 +5690,105 @@ function mediaInsertionMutationObserved(before, after) {
4956
5690
  const afterDuration = after.sequenceTimeRange?.duration ?? after.sequence?.duration;
4957
5691
  return Boolean(beforeDuration && afterDuration && compareRational(afterDuration, beforeDuration) > 0);
4958
5692
  }
4959
- 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");
4960
5749
  return {
4961
- ...(observed ?? {
4962
- application: "Final Cut Pro",
4963
- frontmost: false,
4964
- timelineWindowAvailable: false,
4965
- timelineFocused: false,
4966
- focusTarget: "none",
4967
- target: { kind: "none" },
4968
- undoAvailable: false,
4969
- bladeAvailable: false,
4970
- }),
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 ?? {
4971
5776
  available: false,
4972
- error: { code, message },
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,
4973
5785
  };
5786
+ const context = {
5787
+ ...base,
5788
+ available: false,
5789
+ error,
5790
+ };
5791
+ return { ...context, readiness: readinessForContext(context) };
4974
5792
  }
4975
5793
  function preflightContext(error) {
4976
5794
  return error instanceof NativeFinalCutPreflightError ? error.context : undefined;
@@ -4997,13 +5815,15 @@ function commandName(operation) {
4997
5815
  return `Trim > Trim ${operation.edge === "start" ? "Start" : "End"}`;
4998
5816
  if (operation.type === "set-selected-clip-gain")
4999
5817
  return "Modify > Adjust Volume";
5000
- return "Mark > Marker";
5818
+ return "Mark > Markers > Add Marker";
5001
5819
  }
5002
5820
  function appleScriptString(value) {
5003
5821
  return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replace(/[\r\n]/g, " ")}"`;
5004
5822
  }
5005
5823
  function nativeErrorCode(error) {
5006
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";
5007
5827
  if (message.includes("-1712") || /AppleEvent.*timed out/i.test(message))
5008
5828
  return "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT";
5009
5829
  const explicitCodes = [...message.matchAll(/FINAL_CUT_NATIVE_[A-Z_]+/g)].map((match) => match[0]);
@@ -5021,10 +5841,18 @@ function nativeErrorCode(error) {
5021
5841
  return "FINAL_CUT_NATIVE_MODAL_BLOCKED";
5022
5842
  return "FINAL_CUT_NATIVE_AUTOMATION_FAILED";
5023
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
+ }
5024
5850
  function nativeErrorMessage(error) {
5025
5851
  const message = String(error);
5026
5852
  if (message.includes("FINAL_CUT_NATIVE_OVERLAY_BLOCKED"))
5027
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";
5028
5856
  if (message.includes("FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT") || message.includes("-1712") || /AppleEvent.*timed out/i.test(message))
5029
5857
  return "Final Cut did not respond to an AppleEvent; reopen or bring Final Cut Pro to the front and retry";
5030
5858
  if (message.includes("FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW"))