@agent-native/core 0.189.0 → 0.190.0-nightly-20260925211446

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 (233) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/templates/analytics/.agents/skills/analysis-workspace/SKILL.md +10 -0
  3. package/corpus/templates/analytics/.agents/skills/data-querying/SKILL.md +1 -1
  4. package/corpus/templates/analytics/AGENTS.md +11 -22
  5. package/corpus/templates/analytics/actions/list-data-dictionary.ts +7 -9
  6. package/corpus/templates/analytics/actions/search-analytics-query-catalog.ts +1 -1
  7. package/corpus/templates/analytics/app/components/AnalyticsReviewArtifactPreview.tsx +201 -0
  8. package/corpus/templates/analytics/app/i18n/en-US.ts +2 -0
  9. package/corpus/templates/analytics/app/pages/Settings.tsx +50 -3
  10. package/corpus/templates/analytics/changelog/2026-09-25-first-run-onboarding-records-setup-choices-and-builder-conne.md +6 -0
  11. package/corpus/templates/analytics/changelog/2026-09-25-human-review-previews-analytics-dashboards-as-real-charts.md +6 -0
  12. package/corpus/templates/analytics/changelog/2026-09-25-org-admins-can-review-agent-runs-from-settings.md +6 -0
  13. package/corpus/templates/analytics/changelog/2026-09-25-proactive-query-context.md +6 -0
  14. package/corpus/templates/analytics/seeds/dashboards/agent-native-templates-first-party.json +98 -2
  15. package/corpus/templates/analytics/server/lib/analytics-agent-context.ts +557 -0
  16. package/corpus/templates/analytics/server/lib/analytics-query-catalog.ts +217 -46
  17. package/corpus/templates/analytics/server/lib/dashboard-catalog.ts +2 -2
  18. package/corpus/templates/analytics/server/lib/dashboards-store.ts +39 -5
  19. package/corpus/templates/analytics/server/lib/data-dictionary-context.ts +4 -0
  20. package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +268 -2
  21. package/corpus/templates/analytics/server/plugins/agent-chat.ts +44 -9
  22. package/corpus/templates/calendar/AGENTS.md +5 -0
  23. package/corpus/templates/calendar/CHANGELOG.md +6 -0
  24. package/corpus/templates/calendar/actions/get-event-rules-status.ts +47 -0
  25. package/corpus/templates/calendar/actions/list-events.ts +50 -4
  26. package/corpus/templates/calendar/actions/undo-calendar-event-rule.ts +229 -0
  27. package/corpus/templates/calendar/actions/update-settings.ts +8 -0
  28. package/corpus/templates/calendar/app/i18n/en-US.ts +27 -0
  29. package/corpus/templates/calendar/app/pages/Settings.tsx +196 -1
  30. package/corpus/templates/calendar/changelog/2026-09-25-calendar-feeds-with-the-same-url-keep-their-own-names-and-co.md +6 -0
  31. package/corpus/templates/calendar/changelog/2026-09-25-calendar-invitation-rules-surface-expired-connections-and-un.md +6 -0
  32. package/corpus/templates/calendar/changelog/2026-09-25-restore-locally-hidden-events-from-activity-after-disconnect.md +6 -0
  33. package/corpus/templates/calendar/server/lib/calendar-settings.ts +44 -10
  34. package/corpus/templates/calendar/server/lib/google-api.ts +15 -1
  35. package/corpus/templates/calendar/server/lib/google-calendar.ts +1 -1
  36. package/corpus/templates/calendar/server/plugins/event-rules.ts +628 -0
  37. package/corpus/templates/calendar/shared/api.ts +13 -0
  38. package/corpus/templates/calendar/shared/settings.ts +71 -1
  39. package/corpus/templates/clips/actions/create-recording.ts +83 -2
  40. package/corpus/templates/clips/actions/finalize-recording.ts +610 -110
  41. package/corpus/templates/clips/actions/get-recording-player-data.ts +6 -0
  42. package/corpus/templates/clips/actions/import-loom-recording.ts +2 -0
  43. package/corpus/templates/clips/actions/lib/create-recording-schema.ts +7 -0
  44. package/corpus/templates/clips/actions/lib/loom-import-job.ts +15 -1
  45. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +126 -26
  46. package/corpus/templates/clips/app/hooks/use-drop-video-upload.ts +75 -15
  47. package/corpus/templates/clips/app/routes/_app.r.$recordingId.tsx +5 -1
  48. package/corpus/templates/clips/app/routes/record.tsx +134 -40
  49. package/corpus/templates/clips/chrome-extension/src/background.ts +3 -0
  50. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +73 -16
  51. package/corpus/templates/clips/desktop/src/lib/recorder.ts +188 -18
  52. package/corpus/templates/clips/desktop/src/lib/recording-request.ts +1 -0
  53. package/corpus/templates/clips/server/db/schema.ts +4 -0
  54. package/corpus/templates/clips/server/jobs/media-verification.ts +78 -4
  55. package/corpus/templates/clips/server/jobs/recording-failure-backfill.ts +142 -0
  56. package/corpus/templates/clips/server/lib/media-verification-state.ts +29 -0
  57. package/corpus/templates/clips/server/lib/post-finalize-dispatch.ts +2 -0
  58. package/corpus/templates/clips/server/lib/recording-failures.ts +111 -0
  59. package/corpus/templates/clips/server/lib/recordings.ts +6 -1
  60. package/corpus/templates/clips/server/lib/s3-upload-provider.ts +8 -3
  61. package/corpus/templates/clips/server/lib/upload-lease.ts +25 -6
  62. package/corpus/templates/clips/server/plugins/calendar-jobs.ts +2 -0
  63. package/corpus/templates/clips/server/plugins/db.ts +18 -0
  64. package/corpus/templates/clips/server/routes/api/_agent-native-background/post-finalize-worker.post.ts +48 -5
  65. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/abort.post.ts +322 -31
  66. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +223 -61
  67. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/interrupt.post.ts +62 -4
  68. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/reset-chunks.post.ts +74 -7
  69. package/corpus/templates/clips/shared/recording-core.ts +27 -0
  70. package/corpus/templates/design/actions/get-design.ts +35 -6
  71. package/corpus/templates/mail/.agents/skills/inbox-automations/SKILL.md +4 -0
  72. package/corpus/templates/mail/actions/consolidate-ai-filter-rules.ts +41 -0
  73. package/corpus/templates/mail/actions/get-ai-priority.ts +48 -8
  74. package/corpus/templates/mail/actions/record-ai-priority-feedback.ts +69 -0
  75. package/corpus/templates/mail/actions/update-mail-preferences.ts +2 -0
  76. package/corpus/templates/mail/app/components/email/EmailList.tsx +179 -32
  77. package/corpus/templates/mail/app/components/email/EmailListItem.tsx +97 -9
  78. package/corpus/templates/mail/app/components/email/EmailThread.tsx +55 -1
  79. package/corpus/templates/mail/app/components/email/ImportanceFeedbackMenu.tsx +52 -0
  80. package/corpus/templates/mail/app/components/email/compose-autocomplete.ts +2 -1
  81. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +219 -188
  82. package/corpus/templates/mail/app/components/onboarding/AiInboxSetup.tsx +338 -0
  83. package/corpus/templates/mail/app/components/settings/AiFilterSection.tsx +597 -781
  84. package/corpus/templates/mail/app/components/settings/AiRulePromptField.tsx +37 -0
  85. package/corpus/templates/mail/app/global.css +42 -26
  86. package/corpus/templates/mail/app/hooks/use-ai-priority-feedback.ts +43 -0
  87. package/corpus/templates/mail/app/hooks/use-automations.ts +23 -0
  88. package/corpus/templates/mail/app/i18n/en-US.ts +58 -3
  89. package/corpus/templates/mail/app/pages/InboxPage.tsx +47 -10
  90. package/corpus/templates/mail/changelog/2026-09-25-editing-importance-rules-preserves-disabled-instructions-and.md +6 -0
  91. package/corpus/templates/mail/changelog/2026-09-25-handle-astral-unicode-letters-in-autocomplete-word-boundarie.md +6 -0
  92. package/corpus/templates/mail/changelog/2026-09-25-jev-priority-feedback-and-inbox-settings.md +6 -0
  93. package/corpus/templates/mail/changelog/2026-09-25-keep-existing-ai-filter-rules-intact-when-saving-a-prompt.md +6 -0
  94. package/corpus/templates/mail/server/lib/automation-engine.ts +21 -12
  95. package/corpus/templates/mail/server/lib/automations.ts +100 -1
  96. package/corpus/templates/mail/shared/types.ts +3 -0
  97. package/corpus/templates/plan/app/i18n/en-US.ts +6 -0
  98. package/corpus/templates/plan/app/lib/plan-invite-suggestion.ts +43 -0
  99. package/corpus/templates/plan/app/pages/PlansPage.tsx +249 -4
  100. package/corpus/templates/slides/actions/create-deck.ts +11 -1
  101. package/corpus/templates/slides/app/components/deck/SlideRenderer.tsx +117 -1
  102. package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +373 -330
  103. package/corpus/templates/slides/app/components/design-system/builder-index-response.ts +36 -5
  104. package/corpus/templates/slides/app/components/editor/BlockBubbleMenu.tsx +21 -53
  105. package/corpus/templates/slides/app/components/editor/SlideEditor.tsx +347 -671
  106. package/corpus/templates/slides/app/components/editor/bullet-editing.ts +55 -8
  107. package/corpus/templates/slides/app/components/editor/in-place-text-session.ts +2082 -0
  108. package/corpus/templates/slides/app/components/editor/list-editing.ts +174 -16
  109. package/corpus/templates/slides/app/components/editor/rich-text-selection.ts +497 -62
  110. package/corpus/templates/slides/app/components/editor/slide-text-targets.ts +102 -20
  111. package/corpus/templates/slides/app/context/DeckContext.tsx +9 -4
  112. package/corpus/templates/slides/app/global.css +7 -219
  113. package/corpus/templates/slides/app/i18n/en-US.ts +3 -0
  114. package/corpus/templates/slides/app/lib/sanitize-slide-html.ts +7 -0
  115. package/corpus/templates/slides/app/lib/slide-image-replacement.ts +203 -1
  116. package/corpus/templates/slides/app/lib/slide-source-map.ts +43 -0
  117. package/corpus/templates/slides/app/pages/DeckEditor.tsx +182 -4
  118. package/corpus/templates/slides/app/routes/settings.tsx +33 -2
  119. package/corpus/templates/slides/changelog/2026-09-25-improve-slides-design-system-setup-feedback.md +6 -0
  120. package/corpus/templates/slides/changelog/2026-09-25-org-admins-can-review-agent-runs-from-settings.md +6 -0
  121. package/corpus/templates/slides/changelog/2026-09-25-text-on-a-slide-is-now-edited-in-place-clicking-into-it-chan.md +6 -0
  122. package/corpus/templates/slides/package.json +0 -12
  123. package/corpus/templates/slides/scripts/edit-fidelity/README.md +4 -2
  124. package/corpus/templates/slides/scripts/edit-fidelity/run.ts +12 -3
  125. package/corpus/templates/slides/vite.config.ts +1 -10
  126. package/dist/agent/jev-tool-prefetch.d.ts +29 -3
  127. package/dist/agent/jev-tool-prefetch.js +161 -34
  128. package/dist/agent/production-agent.d.ts +11 -0
  129. package/dist/agent/production-agent.js +39 -8
  130. package/dist/app-config/runtime.d.ts +1 -0
  131. package/dist/app-config/runtime.js +4 -0
  132. package/dist/app-config/schema.d.ts +1 -0
  133. package/dist/client/AgentSidebar.d.ts +3 -1
  134. package/dist/client/AgentSidebar.js +8 -12
  135. package/dist/client/analytics/index.d.ts +1 -1
  136. package/dist/client/analytics/index.js +1 -1
  137. package/dist/client/analytics.d.ts +2 -0
  138. package/dist/client/analytics.js +9 -0
  139. package/dist/client/api-path.js +5 -2
  140. package/dist/client/chat/run-recovery.d.ts +0 -3
  141. package/dist/client/chat/run-recovery.js +13 -23
  142. package/dist/client/index.d.ts +1 -1
  143. package/dist/client/index.js +1 -1
  144. package/dist/client/observability/ObservabilityDashboard.d.ts +3 -0
  145. package/dist/client/observability/ObservabilityDashboard.js +366 -71
  146. package/dist/client/observability/ObservabilityReviewSummaryButton.d.ts +4 -1
  147. package/dist/client/observability/ObservabilityReviewSummaryButton.js +13 -9
  148. package/dist/client/observability/OutputPreview.d.ts +9 -4
  149. package/dist/client/observability/OutputPreview.js +230 -52
  150. package/dist/client/onboarding/FirstRunOnboarding.js +67 -4
  151. package/dist/client/onboarding/use-onboarding.js +2 -0
  152. package/dist/client/sharing/ShareButton.d.ts +2 -0
  153. package/dist/client/sharing/ShareButton.js +1 -0
  154. package/dist/client/sharing/useShareButtonController.d.ts +1 -0
  155. package/dist/client/sharing/useShareButtonController.js +29 -8
  156. package/dist/collab/awareness.d.ts +2 -2
  157. package/dist/collab/struct-routes.d.ts +1 -1
  158. package/dist/deploy/build.js +9 -1
  159. package/dist/embeddings/index.d.ts +3 -1
  160. package/dist/embeddings/index.js +20 -10
  161. package/dist/jobs/sweep-hooks.d.ts +7 -0
  162. package/dist/jobs/sweep-hooks.js +28 -0
  163. package/dist/localization/default-messages.d.ts +1 -0
  164. package/dist/localization/default-messages.js +1 -0
  165. package/dist/mcp/screen-memory-stdio.d.ts +7 -7
  166. package/dist/notifications/routes.d.ts +1 -1
  167. package/dist/observability/actions/authorization.d.ts +1 -0
  168. package/dist/observability/actions/authorization.js +22 -0
  169. package/dist/observability/actions/get-observability-review-detail.d.ts +5 -0
  170. package/dist/observability/actions/get-observability-review-detail.js +10 -2
  171. package/dist/observability/actions/get-observability-review-summary-source.d.ts +2 -0
  172. package/dist/observability/actions/get-observability-review-summary-source.js +3 -2
  173. package/dist/observability/actions/save-observability-instruction-update.js +2 -1
  174. package/dist/observability/actions/save-observability-review-summary.js +21 -10
  175. package/dist/observability/migrations.js +25 -0
  176. package/dist/observability/reviews.d.ts +3 -1
  177. package/dist/observability/reviews.js +410 -53
  178. package/dist/observability/routes.d.ts +6 -6
  179. package/dist/observability/store.d.ts +15 -0
  180. package/dist/observability/store.js +131 -11
  181. package/dist/observability/types.d.ts +18 -0
  182. package/dist/org/handlers.d.ts +1 -1
  183. package/dist/org/index.d.ts +1 -1
  184. package/dist/progress/routes.d.ts +1 -1
  185. package/dist/provider-api/actions/custom-provider-registration.d.ts +5 -5
  186. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  187. package/dist/secrets/routes.d.ts +3 -3
  188. package/dist/server/agent-chat/plugin-options.d.ts +4 -20
  189. package/dist/server/agent-chat/prompt-resources.d.ts +16 -0
  190. package/dist/server/agent-chat/prompt-resources.js +385 -22
  191. package/dist/server/agent-chat-plugin.d.ts +3 -1
  192. package/dist/server/agent-chat-plugin.js +149 -27
  193. package/dist/server/agent-engine-ollama-models-route.d.ts +1 -1
  194. package/dist/server/index.d.ts +3 -0
  195. package/dist/server/index.js +3 -0
  196. package/dist/server/prompts/framework-core-compact.js +1 -1
  197. package/dist/server/prompts/framework-core.js +1 -1
  198. package/dist/server/realtime-token.d.ts +1 -1
  199. package/dist/server/request-context.d.ts +6 -3
  200. package/dist/server/transcribe-voice.d.ts +1 -1
  201. package/dist/settings/org-settings.d.ts +4 -2
  202. package/dist/settings/org-settings.js +3 -3
  203. package/dist/settings/store.d.ts +3 -1
  204. package/dist/settings/store.js +8 -3
  205. package/dist/styles/agent-native.css +5 -0
  206. package/dist/templates/default/app/i18n/ar-SA.ts +1 -0
  207. package/dist/templates/default/app/i18n/de-DE.ts +1 -0
  208. package/dist/templates/default/app/i18n/en-US.ts +1 -0
  209. package/dist/templates/default/app/i18n/es-ES.ts +1 -0
  210. package/dist/templates/default/app/i18n/fr-FR.ts +1 -0
  211. package/dist/templates/default/app/i18n/hi-IN.ts +1 -0
  212. package/dist/templates/default/app/i18n/ja-JP.ts +1 -0
  213. package/dist/templates/default/app/i18n/ko-KR.ts +1 -0
  214. package/dist/templates/default/app/i18n/pt-BR.ts +1 -0
  215. package/dist/templates/default/app/i18n/zh-CN.ts +1 -0
  216. package/dist/templates/default/app/i18n/zh-TW.ts +1 -0
  217. package/dist/tracking/registry.js +11 -4
  218. package/package.json +4 -3
  219. package/src/templates/default/app/i18n/ar-SA.ts +1 -0
  220. package/src/templates/default/app/i18n/de-DE.ts +1 -0
  221. package/src/templates/default/app/i18n/en-US.ts +1 -0
  222. package/src/templates/default/app/i18n/es-ES.ts +1 -0
  223. package/src/templates/default/app/i18n/fr-FR.ts +1 -0
  224. package/src/templates/default/app/i18n/hi-IN.ts +1 -0
  225. package/src/templates/default/app/i18n/ja-JP.ts +1 -0
  226. package/src/templates/default/app/i18n/ko-KR.ts +1 -0
  227. package/src/templates/default/app/i18n/pt-BR.ts +1 -0
  228. package/src/templates/default/app/i18n/zh-CN.ts +1 -0
  229. package/src/templates/default/app/i18n/zh-TW.ts +1 -0
  230. package/corpus/templates/slides/app/components/editor/SlideBubbleMenu.tsx +0 -488
  231. package/corpus/templates/slides/app/components/editor/SlideInlineEditor.tsx +0 -589
  232. package/corpus/templates/slides/app/components/editor/SlideRichTextEditor.tsx +0 -1347
  233. package/corpus/templates/slides/app/components/editor/SlideSlashMenu.tsx +0 -373
@@ -11,6 +11,7 @@
11
11
  import { defineAction } from "@agent-native/core/action";
12
12
  import {
13
13
  compareAndSetAppState,
14
+ compareAndSetManyAppState,
14
15
  deleteAppState,
15
16
  readAppState,
16
17
  writeAppState,
@@ -34,10 +35,15 @@ import {
34
35
  import { allowsLegacyS3ObjectForPersistedMedia } from "../server/lib/media-storage-provenance.js";
35
36
  import {
36
37
  mediaVerificationStateKey,
38
+ mediaVerificationMarkerMatchesUpload,
37
39
  parseMediaVerificationMarker,
38
40
  } from "../server/lib/media-verification-state.js";
39
41
  import { dispatchPostFinalizeJob } from "../server/lib/post-finalize-dispatch.js";
40
42
  import { reconcileMeetingOnRecordingReady } from "../server/lib/reconcile-meeting-on-finalize.js";
43
+ import {
44
+ recordingTrackingSource,
45
+ trackRecordingFailure,
46
+ } from "../server/lib/recording-failures.js";
41
47
  import {
42
48
  listRecordingChunkKeys,
43
49
  validateRecordingChunkKeys,
@@ -117,6 +123,43 @@ const MEDIA_SERVE_VERIFICATION_BACKOFF_MS = 350;
117
123
  const MEDIA_VERIFICATION_MAX_DURABLE_ATTEMPTS = 10;
118
124
  const MEDIA_VERIFICATION_INITIAL_RETRY_DELAY_MS = 5_000;
119
125
 
126
+ function trackUploadBlockingFailure(params: {
127
+ id: string;
128
+ ownerEmail: string;
129
+ uploadAttemptId: string | null | undefined;
130
+ recordingPlatform: string | null | undefined;
131
+ failureCode: string;
132
+ failureType: string;
133
+ }): void {
134
+ try {
135
+ track(
136
+ "clips_upload_blocking_failure",
137
+ {
138
+ app: "clips",
139
+ template: "clips",
140
+ surface: "server_upload",
141
+ stage: "finalize_recording",
142
+ outcome: "failed",
143
+ failure_type: params.failureType,
144
+ failure_code: params.failureCode,
145
+ output_id: params.id,
146
+ output_type: "clip",
147
+ recording_id: params.id,
148
+ recording_attempt_id: params.id,
149
+ ...(params.uploadAttemptId
150
+ ? { upload_attempt_id: params.uploadAttemptId }
151
+ : {}),
152
+ recording_platform: params.recordingPlatform ?? "unknown",
153
+ upload_mode: "buffered",
154
+ },
155
+ recordingTrackingSource(params.ownerEmail),
156
+ );
157
+ // coercion-ok: analytics must not change the persisted upload outcome.
158
+ } catch {
159
+ // Best-effort analytics must never change upload behavior.
160
+ }
161
+ }
162
+
120
163
  function stateNumber(
121
164
  value: Record<string, unknown> | null | undefined,
122
165
  key: string,
@@ -304,15 +347,28 @@ function queueBackgroundBuilderCompression(args: {
304
347
  async function failStoredButUnservableRecording(params: {
305
348
  id: string;
306
349
  ownerEmail: string;
350
+ uploadAttemptId: string | null;
351
+ uploadGenerationId: string | null;
352
+ expectedUploadState: Record<string, unknown> | null;
353
+ expectedVerificationState: Record<string, unknown> | null;
307
354
  failureReason: string;
308
355
  }): Promise<boolean> {
309
- const { id, ownerEmail, failureReason } = params;
356
+ const {
357
+ id,
358
+ ownerEmail,
359
+ uploadAttemptId,
360
+ uploadGenerationId,
361
+ expectedUploadState,
362
+ expectedVerificationState,
363
+ failureReason,
364
+ } = params;
310
365
  const now = new Date().toISOString();
311
366
  const db = getDb();
312
367
  const failed = await db
313
368
  .update(schema.recordings)
314
369
  .set({
315
370
  status: "failed",
371
+ failureCode: "media_verification_failed",
316
372
  failureReason,
317
373
  updatedAt: now,
318
374
  })
@@ -321,13 +377,42 @@ async function failStoredButUnservableRecording(params: {
321
377
  eq(schema.recordings.id, id),
322
378
  ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
323
379
  eq(schema.recordings.status, "processing"),
380
+ uploadAttemptId === null
381
+ ? isNull(schema.recordings.uploadAttemptId)
382
+ : eq(schema.recordings.uploadAttemptId, uploadAttemptId),
383
+ uploadGenerationId === null
384
+ ? isNull(schema.recordings.uploadGenerationId)
385
+ : eq(schema.recordings.uploadGenerationId, uploadGenerationId),
324
386
  ),
325
387
  )
326
388
  .returning({
327
389
  id: schema.recordings.id,
328
390
  uploadAttemptId: schema.recordings.uploadAttemptId,
391
+ recordingPlatform: schema.recordings.recordingPlatform,
329
392
  });
330
393
  if (failed.length !== 1) return false;
394
+ const statePublished = await compareAndSetManyAppState([
395
+ {
396
+ key: `recording-upload-${id}`,
397
+ expectedValue: expectedUploadState,
398
+ nextValue: {
399
+ ...(expectedUploadState ?? {}),
400
+ recordingId: id,
401
+ status: "failed",
402
+ pendingMediaVerification: false,
403
+ uploadAttemptId,
404
+ uploadGenerationId,
405
+ failureReason,
406
+ updatedAt: now,
407
+ },
408
+ },
409
+ {
410
+ key: mediaVerificationStateKey(id),
411
+ expectedValue: expectedVerificationState,
412
+ nextValue: null,
413
+ },
414
+ ]);
415
+ if (!statePublished) return false;
331
416
  try {
332
417
  track(
333
418
  "clips_upload_blocking_failure",
@@ -339,38 +424,23 @@ async function failStoredButUnservableRecording(params: {
339
424
  outcome: "failed",
340
425
  failure_type: "media_verification",
341
426
  failure_code: "media_verification_failed",
342
- output_id: id,
343
- output_type: "clip",
344
- recording_id: id,
345
427
  recording_attempt_id: id,
346
428
  ...(failed[0]?.uploadAttemptId
347
429
  ? { upload_attempt_id: failed[0].uploadAttemptId }
348
430
  : {}),
431
+ recording_platform: failed[0]?.recordingPlatform ?? "unknown",
349
432
  },
350
- { userId: ownerEmail },
433
+ recordingTrackingSource(ownerEmail),
351
434
  );
352
435
  } catch {
353
436
  // coercion-ok: analytics is best-effort and must not change media recovery behavior.
354
437
  }
355
- const uploadStateRaw = await readAppState(`recording-upload-${id}`).catch(
356
- () => null,
357
- );
358
- const uploadState =
359
- uploadStateRaw && typeof uploadStateRaw === "object"
360
- ? (uploadStateRaw as Record<string, unknown>)
361
- : {};
362
- await writeAppState(`recording-upload-${id}`, {
363
- ...uploadState,
438
+ trackRecordingFailure({
364
439
  recordingId: id,
365
- status: "failed",
366
- failureReason,
367
- updatedAt: now,
368
- });
369
- await deleteAppState(mediaVerificationStateKey(id)).catch((err) => {
370
- console.warn("[finalize] failed to clear media verification marker", {
371
- id,
372
- error: err instanceof Error ? err.message : String(err),
373
- });
440
+ userId: ownerEmail,
441
+ uploadAttemptId: failed[0]?.uploadAttemptId,
442
+ platform: failed[0]?.recordingPlatform,
443
+ failureCode: "media_verification_failed",
374
444
  });
375
445
  await writeAppState("refresh-signal", { ts: Date.now() });
376
446
  return true;
@@ -430,11 +500,24 @@ function pendingMediaVerificationFromState(
430
500
  async function persistPendingMediaVerification(params: {
431
501
  id: string;
432
502
  ownerEmail: string;
503
+ uploadAttemptId: string | null;
504
+ uploadGenerationId: string | null;
505
+ expectedUploadState: Record<string, unknown> | null;
506
+ expectedVerificationState: Record<string, unknown> | null;
433
507
  media: PendingMediaVerification;
434
508
  failureReason: string;
435
509
  retryAttempt?: number;
436
510
  }): Promise<boolean> {
437
- const { id, ownerEmail, media, failureReason } = params;
511
+ const {
512
+ id,
513
+ ownerEmail,
514
+ uploadAttemptId,
515
+ uploadGenerationId,
516
+ expectedUploadState,
517
+ expectedVerificationState,
518
+ media,
519
+ failureReason,
520
+ } = params;
438
521
  const now = new Date().toISOString();
439
522
  const retryAttempt = Math.max(0, params.retryAttempt ?? 0);
440
523
  const nextRetryAttempt = Math.min(
@@ -459,6 +542,7 @@ async function persistPendingMediaVerification(params: {
459
542
  hasAudio: media.finalHasAudio,
460
543
  hasCamera: media.finalHasCamera,
461
544
  failureReason: null,
545
+ failureCode: null,
462
546
  uploadProgress: 100,
463
547
  updatedAt: now,
464
548
  })
@@ -468,85 +552,136 @@ async function persistPendingMediaVerification(params: {
468
552
  ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
469
553
  eq(schema.recordings.status, "processing"),
470
554
  isNull(schema.recordings.trashedAt),
555
+ uploadAttemptId === null
556
+ ? isNull(schema.recordings.uploadAttemptId)
557
+ : eq(schema.recordings.uploadAttemptId, uploadAttemptId),
558
+ uploadGenerationId === null
559
+ ? isNull(schema.recordings.uploadGenerationId)
560
+ : eq(schema.recordings.uploadGenerationId, uploadGenerationId),
471
561
  ),
472
562
  )
473
563
  .returning({ id: schema.recordings.id });
474
564
  if (persisted.length !== 1) return false;
475
565
 
476
- await writeAppState(`recording-upload-${id}`, {
477
- recordingId: id,
478
- status: "processing",
479
- progress: 100,
480
- pendingMediaVerification: true,
481
- mediaVerificationAttempt: retryAttempt,
482
- mediaVerificationNextAttemptAt: nextAttemptAt,
483
- mediaVerificationLastError: failureReason,
484
- videoUrl: media.videoUrl,
485
- videoSizeBytes: media.videoSizeBytes,
486
- sourceSizeBytes: media.sourceSizeBytes,
487
- videoFormat: media.videoFormat,
488
- durationMs: media.finalDurationMs,
489
- width: media.finalWidth,
490
- height: media.finalHeight,
491
- hasAudio: media.finalHasAudio,
492
- hasCamera: media.finalHasCamera,
493
- seekableApplied: media.seekableApplied,
494
- mimeType: media.mimeType,
495
- providerId: media.providerId,
496
- assetDbId: media.assetDbId,
497
- locallyTranscoded: media.locallyTranscoded,
498
- updatedAt: now,
499
- });
500
- await writeAppState(mediaVerificationStateKey(id), {
501
- recordingId: id,
502
- status: "pending",
503
- completedAttempts: retryAttempt,
504
- nextAttemptAt,
505
- leaseUntil: null,
506
- updatedAt: now,
507
- });
566
+ const statePublished = await compareAndSetManyAppState([
567
+ {
568
+ key: `recording-upload-${id}`,
569
+ expectedValue: expectedUploadState,
570
+ nextValue: {
571
+ recordingId: id,
572
+ status: "processing",
573
+ progress: 100,
574
+ pendingMediaVerification: true,
575
+ mediaVerificationAttempt: retryAttempt,
576
+ mediaVerificationNextAttemptAt: nextAttemptAt,
577
+ mediaVerificationLastError: failureReason,
578
+ uploadAttemptId,
579
+ uploadGenerationId,
580
+ videoUrl: media.videoUrl,
581
+ videoSizeBytes: media.videoSizeBytes,
582
+ sourceSizeBytes: media.sourceSizeBytes,
583
+ videoFormat: media.videoFormat,
584
+ durationMs: media.finalDurationMs,
585
+ width: media.finalWidth,
586
+ height: media.finalHeight,
587
+ hasAudio: media.finalHasAudio,
588
+ hasCamera: media.finalHasCamera,
589
+ seekableApplied: media.seekableApplied,
590
+ mimeType: media.mimeType,
591
+ providerId: media.providerId,
592
+ assetDbId: media.assetDbId,
593
+ locallyTranscoded: media.locallyTranscoded,
594
+ updatedAt: now,
595
+ },
596
+ },
597
+ {
598
+ key: mediaVerificationStateKey(id),
599
+ expectedValue: expectedVerificationState,
600
+ nextValue: {
601
+ recordingId: id,
602
+ status: "pending",
603
+ completedAttempts: retryAttempt,
604
+ nextAttemptAt,
605
+ leaseUntil: null,
606
+ uploadAttemptId,
607
+ uploadGenerationId,
608
+ updatedAt: now,
609
+ },
610
+ },
611
+ ]);
612
+ if (!statePublished) return false;
508
613
  await writeAppState("refresh-signal", { ts: Date.now() });
509
614
  return true;
510
615
  }
511
616
 
512
- async function claimPendingMediaVerification(
513
- id: string,
514
- retryAttempt: number,
515
- ): Promise<boolean> {
617
+ async function claimPendingMediaVerification(params: {
618
+ id: string;
619
+ retryAttempt: number;
620
+ uploadAttemptId: string | null;
621
+ uploadGenerationId: string | null;
622
+ expectedState: Record<string, unknown> | null;
623
+ }): Promise<Record<string, unknown> | null> {
624
+ const {
625
+ id,
626
+ retryAttempt,
627
+ uploadAttemptId,
628
+ uploadGenerationId,
629
+ expectedState,
630
+ } = params;
516
631
  const key = mediaVerificationStateKey(id);
517
- const raw = await readAppState(key).catch(() => null);
632
+ const raw = expectedState;
518
633
  const marker = parseMediaVerificationMarker(raw);
634
+ const rawMarker =
635
+ raw && typeof raw === "object" ? (raw as Record<string, unknown>) : null;
519
636
  const now = Date.now();
520
637
  if (
521
638
  !marker ||
522
639
  marker.recordingId !== id ||
523
640
  retryAttempt !== marker.completedAttempts + 1 ||
641
+ !mediaVerificationMarkerMatchesUpload(
642
+ marker,
643
+ uploadAttemptId,
644
+ uploadGenerationId,
645
+ ) ||
524
646
  now < Date.parse(marker.nextAttemptAt) ||
525
647
  (marker.status === "leased" &&
526
648
  marker.leaseUntil !== null &&
527
649
  now < Date.parse(marker.leaseUntil))
528
650
  ) {
529
- return false;
651
+ return null;
530
652
  }
531
653
 
532
654
  const updatedAt = new Date(now).toISOString();
533
- return compareAndSetAppState(key, raw as Record<string, unknown>, {
534
- ...marker,
655
+ const claimedState = {
656
+ ...(rawMarker ?? {}),
535
657
  status: "leased",
536
658
  leaseUntil: new Date(now + 60_000).toISOString(),
659
+ uploadAttemptId,
660
+ uploadGenerationId,
537
661
  updatedAt,
538
- });
662
+ };
663
+ return (await compareAndSetAppState(
664
+ key,
665
+ raw as Record<string, unknown>,
666
+ claimedState,
667
+ ))
668
+ ? claimedState
669
+ : null;
539
670
  }
540
671
 
541
672
  async function dispatchMediaVerificationRetry(
542
673
  id: string,
543
674
  retryAttempt: number,
675
+ uploadAttemptId: string | null,
676
+ uploadGenerationId: string | null,
544
677
  ): Promise<void> {
545
678
  await dispatchPostFinalizeJob({
546
679
  recordingId: id,
547
680
  kind: "media-ready",
548
681
  delayMs: mediaVerificationRetryDelayMs(retryAttempt),
549
682
  retryAttempt,
683
+ uploadAttemptId,
684
+ uploadGenerationId,
550
685
  requireAccepted: true,
551
686
  }).catch((err: unknown) => {
552
687
  console.error("[finalize] media verification dispatch failed", {
@@ -560,10 +695,17 @@ async function dispatchMediaVerificationRetry(
560
695
  async function leaveRecordingProcessingForMediaVerification(params: {
561
696
  id: string;
562
697
  ownerEmail: string;
698
+ uploadAttemptId: string | null;
699
+ uploadGenerationId: string | null;
700
+ expectedUploadState: Record<string, unknown> | null;
701
+ expectedVerificationState?: Record<string, unknown> | null;
563
702
  media: PendingMediaVerification;
564
703
  failureReason: string;
565
704
  }) {
566
- const persisted = await persistPendingMediaVerification(params);
705
+ const persisted = await persistPendingMediaVerification({
706
+ ...params,
707
+ expectedVerificationState: params.expectedVerificationState ?? null,
708
+ });
567
709
  if (!persisted) {
568
710
  const aborted = await uploadWasAborted(params.id);
569
711
  return {
@@ -576,7 +718,12 @@ async function leaveRecordingProcessingForMediaVerification(params: {
576
718
  durationMs: params.media.finalDurationMs,
577
719
  };
578
720
  }
579
- await dispatchMediaVerificationRetry(params.id, 1);
721
+ await dispatchMediaVerificationRetry(
722
+ params.id,
723
+ 1,
724
+ params.uploadAttemptId,
725
+ params.uploadGenerationId,
726
+ );
580
727
  return {
581
728
  id: params.id,
582
729
  status: "processing" as const,
@@ -618,6 +765,41 @@ async function queueReadyRecordingThumbnail(
618
765
  });
619
766
  }
620
767
 
768
+ async function compareAndSetProcessingUploadState(params: {
769
+ id: string;
770
+ ownerEmail: string;
771
+ uploadAttemptId: string | null;
772
+ uploadGenerationId: string | null;
773
+ expectedState: Record<string, unknown> | null;
774
+ nextState: Record<string, unknown>;
775
+ }): Promise<boolean> {
776
+ const [recording] = await getDb()
777
+ .select({
778
+ status: schema.recordings.status,
779
+ uploadAttemptId: schema.recordings.uploadAttemptId,
780
+ uploadGenerationId: schema.recordings.uploadGenerationId,
781
+ })
782
+ .from(schema.recordings)
783
+ .where(
784
+ and(
785
+ eq(schema.recordings.id, params.id),
786
+ ownerEmailMatches(schema.recordings.ownerEmail, params.ownerEmail),
787
+ ),
788
+ );
789
+ if (
790
+ recording?.status !== "processing" ||
791
+ (recording.uploadAttemptId ?? null) !== params.uploadAttemptId ||
792
+ (recording.uploadGenerationId ?? null) !== params.uploadGenerationId
793
+ ) {
794
+ return false;
795
+ }
796
+ return compareAndSetAppState(
797
+ `recording-upload-${params.id}`,
798
+ params.expectedState,
799
+ params.nextState,
800
+ );
801
+ }
802
+
621
803
  // Flip recording to 'ready', seed transcript row, fire background transcript,
622
804
  // emit clip.created. Used by both the resumable and buffered upload paths.
623
805
  async function markRecordingReady(params: {
@@ -632,7 +814,8 @@ async function markRecordingReady(params: {
632
814
  finalHeight: number;
633
815
  finalHasAudio: boolean;
634
816
  finalHasCamera: boolean;
635
- recordingAttemptId?: string | null;
817
+ recordingAttemptId: string | null;
818
+ recordingGenerationId: string | null;
636
819
  existingTitle: string;
637
820
  // Whether a seekable rewrite (MP4 faststart / WebM Cues remux) was already
638
821
  // applied to the uploaded bytes. When false, a best-effort background repair
@@ -652,6 +835,7 @@ async function markRecordingReady(params: {
652
835
  finalHasAudio,
653
836
  finalHasCamera,
654
837
  recordingAttemptId,
838
+ recordingGenerationId,
655
839
  existingTitle,
656
840
  seekableApplied,
657
841
  } = params;
@@ -672,6 +856,7 @@ async function markRecordingReady(params: {
672
856
  hasAudio: finalHasAudio,
673
857
  hasCamera: finalHasCamera,
674
858
  failureReason: null,
859
+ failureCode: null,
675
860
  uploadProgress: 100,
676
861
  updatedAt: now,
677
862
  })
@@ -683,6 +868,12 @@ async function markRecordingReady(params: {
683
868
  // duplicate finalize requests and durable verification workers. Only
684
869
  // the winner performs transcript/event/post-finalize side effects.
685
870
  eq(schema.recordings.status, "processing"),
871
+ recordingAttemptId === null
872
+ ? isNull(schema.recordings.uploadAttemptId)
873
+ : eq(schema.recordings.uploadAttemptId, recordingAttemptId),
874
+ recordingGenerationId === null
875
+ ? isNull(schema.recordings.uploadGenerationId)
876
+ : eq(schema.recordings.uploadGenerationId, recordingGenerationId),
686
877
  // Guard against the other direction of the cancel/finalize race:
687
878
  // trash-recording's skipIfReady only blocks trashing a row that is
688
879
  // ALREADY 'ready'. If cancel lands while this finalize is still
@@ -696,7 +887,11 @@ async function markRecordingReady(params: {
696
887
 
697
888
  if (promoted.length !== 1) {
698
889
  const [postUpdate] = await db
699
- .select({ status: schema.recordings.status })
890
+ .select({
891
+ status: schema.recordings.status,
892
+ uploadAttemptId: schema.recordings.uploadAttemptId,
893
+ uploadGenerationId: schema.recordings.uploadGenerationId,
894
+ })
700
895
  .from(schema.recordings)
701
896
  .where(
702
897
  and(
@@ -708,7 +903,11 @@ async function markRecordingReady(params: {
708
903
  id,
709
904
  status: postUpdate?.status,
710
905
  });
711
- if (postUpdate?.status === "ready") {
906
+ const sameUpload =
907
+ postUpdate?.uploadAttemptId === recordingAttemptId &&
908
+ postUpdate?.uploadGenerationId === recordingGenerationId;
909
+ const isReady = sameUpload && postUpdate?.status === "ready";
910
+ if (isReady) {
712
911
  await queueReadyRecordingThumbnail(id);
713
912
  await reconcileMeetingOnRecordingReady({
714
913
  recordingId: id,
@@ -722,19 +921,22 @@ async function markRecordingReady(params: {
722
921
  });
723
922
  }
724
923
  const aborted =
725
- postUpdate?.status === "failed" && (await uploadWasAborted(id));
924
+ sameUpload &&
925
+ postUpdate?.status === "failed" &&
926
+ (await uploadWasAborted(id));
726
927
  return {
727
928
  id,
728
- status:
729
- postUpdate?.status === "ready"
730
- ? ("ready" as const)
731
- : ("failed" as const),
929
+ status: isReady ? ("ready" as const) : ("failed" as const),
732
930
  ...(aborted ? { aborted: true } : {}),
733
931
  transitionedToReady: false,
734
- videoUrl,
735
- videoSizeBytes,
736
- sourceSizeBytes,
737
- durationMs: finalDurationMs,
932
+ ...(isReady
933
+ ? {
934
+ videoUrl,
935
+ videoSizeBytes,
936
+ sourceSizeBytes,
937
+ durationMs: finalDurationMs,
938
+ }
939
+ : {}),
738
940
  };
739
941
  }
740
942
 
@@ -754,7 +956,7 @@ async function markRecordingReady(params: {
754
956
  width: finalWidth,
755
957
  height: finalHeight,
756
958
  },
757
- { userId: ownerEmail },
959
+ recordingTrackingSource(ownerEmail),
758
960
  );
759
961
 
760
962
  await queueReadyRecordingThumbnail(id);
@@ -890,12 +1092,27 @@ async function retryPendingMediaVerification(params: {
890
1092
  existingTitle: string;
891
1093
  media: PendingMediaVerification;
892
1094
  retryAttempt: number;
1095
+ uploadAttemptId: string | null;
1096
+ uploadGenerationId: string | null;
1097
+ expectedUploadState: Record<string, unknown> | null;
1098
+ expectedVerificationState: Record<string, unknown>;
893
1099
  }) {
894
- const { id, ownerEmail, existingTitle, media, retryAttempt } = params;
1100
+ const {
1101
+ id,
1102
+ ownerEmail,
1103
+ existingTitle,
1104
+ media,
1105
+ retryAttempt,
1106
+ uploadAttemptId,
1107
+ uploadGenerationId,
1108
+ expectedUploadState,
1109
+ expectedVerificationState,
1110
+ } = params;
895
1111
  const db = getDb();
896
1112
  const [recording] = await db
897
1113
  .select({
898
1114
  uploadAttemptId: schema.recordings.uploadAttemptId,
1115
+ uploadGenerationId: schema.recordings.uploadGenerationId,
899
1116
  status: schema.recordings.status,
900
1117
  videoUrl: schema.recordings.videoUrl,
901
1118
  editsJson: schema.recordings.editsJson,
@@ -907,7 +1124,12 @@ async function retryPendingMediaVerification(params: {
907
1124
  ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
908
1125
  ),
909
1126
  );
910
- if (!recording || recording.status !== "processing") {
1127
+ if (
1128
+ !recording ||
1129
+ recording.status !== "processing" ||
1130
+ (recording.uploadAttemptId ?? null) !== uploadAttemptId ||
1131
+ (recording.uploadGenerationId ?? null) !== uploadGenerationId
1132
+ ) {
911
1133
  const aborted =
912
1134
  recording?.status === "failed" && (await uploadWasAborted(id));
913
1135
  return {
@@ -951,7 +1173,8 @@ async function retryPendingMediaVerification(params: {
951
1173
  finalHeight: candidate.finalHeight,
952
1174
  finalHasAudio: candidate.finalHasAudio,
953
1175
  finalHasCamera: candidate.finalHasCamera,
954
- recordingAttemptId: recording.uploadAttemptId,
1176
+ recordingAttemptId: uploadAttemptId,
1177
+ recordingGenerationId: uploadGenerationId,
955
1178
  seekableApplied: candidate.seekableApplied,
956
1179
  });
957
1180
  if (result.status === "ready" && result.transitionedToReady) {
@@ -974,6 +1197,10 @@ async function retryPendingMediaVerification(params: {
974
1197
  const failed = await failStoredButUnservableRecording({
975
1198
  id,
976
1199
  ownerEmail,
1200
+ uploadAttemptId,
1201
+ uploadGenerationId,
1202
+ expectedUploadState,
1203
+ expectedVerificationState,
977
1204
  failureReason: terminalReason,
978
1205
  });
979
1206
  if (!failed) {
@@ -1018,6 +1245,10 @@ async function retryPendingMediaVerification(params: {
1018
1245
  const persisted = await persistPendingMediaVerification({
1019
1246
  id,
1020
1247
  ownerEmail,
1248
+ uploadAttemptId,
1249
+ uploadGenerationId,
1250
+ expectedUploadState,
1251
+ expectedVerificationState,
1021
1252
  media: candidate,
1022
1253
  failureReason,
1023
1254
  retryAttempt,
@@ -1050,7 +1281,12 @@ async function retryPendingMediaVerification(params: {
1050
1281
  durationMs: candidate.finalDurationMs,
1051
1282
  };
1052
1283
  }
1053
- await dispatchMediaVerificationRetry(id, retryAttempt + 1);
1284
+ await dispatchMediaVerificationRetry(
1285
+ id,
1286
+ retryAttempt + 1,
1287
+ uploadAttemptId,
1288
+ uploadGenerationId,
1289
+ );
1054
1290
  return {
1055
1291
  id,
1056
1292
  status: "processing" as const,
@@ -1092,10 +1328,12 @@ export default defineAction({
1092
1328
  "Whether the uploaded video bytes were already locally transcoded/compressed before upload",
1093
1329
  ),
1094
1330
  mediaVerificationRetryAttempt: z.number().int().min(1).max(10).optional(),
1331
+ uploadAttemptId: z.string().min(1).max(128).nullable().optional(),
1095
1332
  uploadGenerationId: z
1096
1333
  .string()
1097
1334
  .min(1)
1098
1335
  .max(128)
1336
+ .nullable()
1099
1337
  .optional()
1100
1338
  .describe("Upload generation that owns the scratch data being finalized"),
1101
1339
  }),
@@ -1138,6 +1376,12 @@ export default defineAction({
1138
1376
  if ((existing.uploadGenerationId ?? null) !== generationId) {
1139
1377
  throw new Error("Upload generation changed before finalization");
1140
1378
  }
1379
+ if (
1380
+ args.uploadAttemptId !== undefined &&
1381
+ (existing.uploadAttemptId ?? null) !== args.uploadAttemptId
1382
+ ) {
1383
+ throw new Error("Upload attempt changed before finalization");
1384
+ }
1141
1385
  // Claim finalization before touching provider/scratch state. Reset only
1142
1386
  // admits uploading/failed rows, so once this CAS succeeds it cannot
1143
1387
  // replace the generation underneath a delayed final chunk.
@@ -1150,6 +1394,12 @@ export default defineAction({
1150
1394
  eq(schema.recordings.id, id),
1151
1395
  ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
1152
1396
  eq(schema.recordings.status, "uploading"),
1397
+ existing.uploadAttemptId === null
1398
+ ? isNull(schema.recordings.uploadAttemptId)
1399
+ : eq(
1400
+ schema.recordings.uploadAttemptId,
1401
+ existing.uploadAttemptId,
1402
+ ),
1153
1403
  eq(schema.recordings.uploadGenerationId, generationId),
1154
1404
  ),
1155
1405
  )
@@ -1189,6 +1439,10 @@ export default defineAction({
1189
1439
  uploadStateRaw && typeof uploadStateRaw === "object"
1190
1440
  ? (uploadStateRaw as Record<string, unknown>)
1191
1441
  : null;
1442
+ const verificationStateRaw = await readAppState(
1443
+ mediaVerificationStateKey(id),
1444
+ );
1445
+ let verificationExpectedUploadState = uploadState;
1192
1446
  const mimeType =
1193
1447
  args.mimeType ||
1194
1448
  (typeof uploadState?.mimeType === "string"
@@ -1229,7 +1483,11 @@ export default defineAction({
1229
1483
  finalHeight,
1230
1484
  finalHasAudio,
1231
1485
  finalHasCamera,
1232
- recordingAttemptId: existing.uploadAttemptId,
1486
+ recordingAttemptId:
1487
+ args.uploadAttemptId !== undefined
1488
+ ? args.uploadAttemptId
1489
+ : (existing.uploadAttemptId ?? null),
1490
+ recordingGenerationId: generationId,
1233
1491
  existingTitle: existing.title,
1234
1492
  };
1235
1493
 
@@ -1239,7 +1497,16 @@ export default defineAction({
1239
1497
  args.mediaVerificationRetryAttempt ??
1240
1498
  stateNumber(uploadState, "mediaVerificationAttempt") ??
1241
1499
  1;
1242
- const claimed = await claimPendingMediaVerification(id, retryAttempt);
1500
+ const claimed = await claimPendingMediaVerification({
1501
+ id,
1502
+ retryAttempt,
1503
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1504
+ uploadGenerationId: generationId,
1505
+ expectedState:
1506
+ verificationStateRaw && typeof verificationStateRaw === "object"
1507
+ ? (verificationStateRaw as Record<string, unknown>)
1508
+ : null,
1509
+ });
1243
1510
  if (!claimed) {
1244
1511
  return {
1245
1512
  id,
@@ -1257,6 +1524,10 @@ export default defineAction({
1257
1524
  existingTitle: existing.title,
1258
1525
  media: pendingMedia,
1259
1526
  retryAttempt,
1527
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1528
+ uploadGenerationId: generationId,
1529
+ expectedUploadState: uploadState,
1530
+ expectedVerificationState: claimed,
1260
1531
  });
1261
1532
  }
1262
1533
 
@@ -1283,11 +1554,12 @@ export default defineAction({
1283
1554
  // back to processing. A later user abort writes a different failed
1284
1555
  // state, and markRecordingReady's status guard will still win.
1285
1556
  const recoveryStartedAt = new Date().toISOString();
1286
- await db
1557
+ const [recoveredRecording] = await db
1287
1558
  .update(schema.recordings)
1288
1559
  .set({
1289
1560
  status: "processing",
1290
1561
  failureReason: null,
1562
+ failureCode: null,
1291
1563
  updatedAt: recoveryStartedAt,
1292
1564
  })
1293
1565
  .where(
@@ -1296,15 +1568,46 @@ export default defineAction({
1296
1568
  ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
1297
1569
  eq(schema.recordings.status, "failed"),
1298
1570
  eq(schema.recordings.failureReason, existing.failureReason),
1571
+ existing.uploadAttemptId
1572
+ ? eq(
1573
+ schema.recordings.uploadAttemptId,
1574
+ existing.uploadAttemptId,
1575
+ )
1576
+ : isNull(schema.recordings.uploadAttemptId),
1577
+ generationId
1578
+ ? eq(schema.recordings.uploadGenerationId, generationId)
1579
+ : isNull(schema.recordings.uploadGenerationId),
1299
1580
  ),
1300
- );
1301
- await writeAppState(`recording-upload-${id}`, {
1581
+ )
1582
+ .returning({ id: schema.recordings.id });
1583
+ if (!recoveredRecording) {
1584
+ throw new Error("Recording changed before finalize recovery");
1585
+ }
1586
+ const recoveredUploadState = {
1302
1587
  ...(uploadState ?? {}),
1303
1588
  recordingId: id,
1304
1589
  status: "processing",
1590
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1591
+ uploadGenerationId: generationId,
1305
1592
  failureReason: null,
1593
+ failureCode: null,
1306
1594
  updatedAt: recoveryStartedAt,
1307
- });
1595
+ };
1596
+ const recoveredStateWritten =
1597
+ await compareAndSetProcessingUploadState({
1598
+ id,
1599
+ ownerEmail,
1600
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1601
+ uploadGenerationId: generationId,
1602
+ expectedState: uploadState,
1603
+ nextState: recoveredUploadState,
1604
+ });
1605
+ if (!recoveredStateWritten) {
1606
+ throw new Error(
1607
+ "Upload changed before finalize state was published",
1608
+ );
1609
+ }
1610
+ verificationExpectedUploadState = recoveredUploadState;
1308
1611
  }
1309
1612
  if (existing.status !== "processing" && existing.status !== "failed") {
1310
1613
  const processingStartedAt = new Date().toISOString();
@@ -1313,6 +1616,7 @@ export default defineAction({
1313
1616
  .set({
1314
1617
  status: "processing",
1315
1618
  failureReason: null,
1619
+ failureCode: null,
1316
1620
  uploadProgress: 100,
1317
1621
  updatedAt: processingStartedAt,
1318
1622
  })
@@ -1391,6 +1695,13 @@ export default defineAction({
1391
1695
  const pending = await leaveRecordingProcessingForMediaVerification({
1392
1696
  id,
1393
1697
  ownerEmail,
1698
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1699
+ uploadGenerationId: generationId,
1700
+ expectedUploadState: verificationExpectedUploadState,
1701
+ expectedVerificationState:
1702
+ verificationStateRaw && typeof verificationStateRaw === "object"
1703
+ ? (verificationStateRaw as Record<string, unknown>)
1704
+ : null,
1394
1705
  failureReason,
1395
1706
  media: {
1396
1707
  videoUrl,
@@ -1476,7 +1787,7 @@ export default defineAction({
1476
1787
  : null;
1477
1788
 
1478
1789
  // Flip to 'processing' while we assemble.
1479
- await db
1790
+ const [processingRecording] = await db
1480
1791
  .update(schema.recordings)
1481
1792
  .set({
1482
1793
  status: "processing",
@@ -1484,35 +1795,114 @@ export default defineAction({
1484
1795
  mediaUpdatedAt: new Date().toISOString(),
1485
1796
  updatedAt: new Date().toISOString(),
1486
1797
  })
1487
- .where(eq(schema.recordings.id, id));
1798
+ .where(
1799
+ and(
1800
+ eq(schema.recordings.id, id),
1801
+ ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
1802
+ eq(schema.recordings.status, existing.status),
1803
+ existing.uploadAttemptId
1804
+ ? eq(schema.recordings.uploadAttemptId, existing.uploadAttemptId)
1805
+ : isNull(schema.recordings.uploadAttemptId),
1806
+ generationId
1807
+ ? eq(schema.recordings.uploadGenerationId, generationId)
1808
+ : isNull(schema.recordings.uploadGenerationId),
1809
+ ),
1810
+ )
1811
+ .returning({ id: schema.recordings.id });
1812
+ if (!processingRecording) {
1813
+ throw new Error(
1814
+ "Upload changed before buffered chunks could be assembled",
1815
+ );
1816
+ }
1488
1817
 
1489
- await writeAppState(`recording-upload-${id}`, {
1818
+ const processingUploadState = {
1490
1819
  recordingId: id,
1491
1820
  status: "processing",
1492
1821
  progress: 100,
1822
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1823
+ uploadGenerationId: generationId,
1493
1824
  updatedAt: new Date().toISOString(),
1825
+ };
1826
+ const processingStateWritten = await compareAndSetProcessingUploadState({
1827
+ id,
1828
+ ownerEmail,
1829
+ uploadAttemptId: existing.uploadAttemptId ?? null,
1830
+ uploadGenerationId: generationId,
1831
+ expectedState: uploadState,
1832
+ nextState: processingUploadState,
1494
1833
  });
1834
+ if (!processingStateWritten) {
1835
+ throw new Error("Upload changed before buffered state was published");
1836
+ }
1837
+ verificationExpectedUploadState = processingUploadState;
1495
1838
 
1496
1839
  const failChunkAssembly = async (
1497
1840
  failureReason: string,
1841
+ failureCode:
1842
+ | "chunk_assembly_failed"
1843
+ | "recording_too_large" = "chunk_assembly_failed",
1498
1844
  ): Promise<never> => {
1499
1845
  const now = new Date().toISOString();
1500
- await db
1846
+ const [failedRecording] = await db
1501
1847
  .update(schema.recordings)
1502
1848
  .set({
1503
1849
  status: "failed",
1850
+ failureCode,
1504
1851
  failureReason,
1505
1852
  mediaUpdatedAt: now,
1506
1853
  updatedAt: now,
1507
1854
  })
1508
- .where(eq(schema.recordings.id, id));
1509
- await writeAppState(`recording-upload-${id}`, {
1510
- ...(uploadState ?? {}),
1511
- recordingId: id,
1512
- status: "failed",
1513
- failureReason,
1514
- updatedAt: now,
1515
- });
1855
+ .where(
1856
+ and(
1857
+ eq(schema.recordings.id, id),
1858
+ ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
1859
+ eq(schema.recordings.status, "processing"),
1860
+ existing.uploadAttemptId
1861
+ ? eq(
1862
+ schema.recordings.uploadAttemptId,
1863
+ existing.uploadAttemptId,
1864
+ )
1865
+ : isNull(schema.recordings.uploadAttemptId),
1866
+ generationId
1867
+ ? eq(schema.recordings.uploadGenerationId, generationId)
1868
+ : isNull(schema.recordings.uploadGenerationId),
1869
+ ),
1870
+ )
1871
+ .returning({
1872
+ uploadAttemptId: schema.recordings.uploadAttemptId,
1873
+ recordingPlatform: schema.recordings.recordingPlatform,
1874
+ });
1875
+ if (failedRecording)
1876
+ trackUploadBlockingFailure({
1877
+ id,
1878
+ ownerEmail,
1879
+ uploadAttemptId: failedRecording.uploadAttemptId,
1880
+ recordingPlatform: failedRecording.recordingPlatform,
1881
+ failureCode,
1882
+ failureType:
1883
+ failureCode === "recording_too_large"
1884
+ ? "size_limit"
1885
+ : "finalize_error",
1886
+ });
1887
+ if (failedRecording)
1888
+ trackRecordingFailure({
1889
+ recordingId: id,
1890
+ userId: ownerEmail,
1891
+ uploadAttemptId: failedRecording?.uploadAttemptId,
1892
+ platform: failedRecording?.recordingPlatform,
1893
+ failureCode,
1894
+ });
1895
+ if (failedRecording)
1896
+ await compareAndSetAppState(
1897
+ `recording-upload-${id}`,
1898
+ processingUploadState,
1899
+ {
1900
+ ...processingUploadState,
1901
+ status: "failed",
1902
+ failureReason,
1903
+ updatedAt: now,
1904
+ },
1905
+ );
1516
1906
  throw new Error(failureReason);
1517
1907
  };
1518
1908
 
@@ -1586,7 +1976,10 @@ export default defineAction({
1586
1976
  }
1587
1977
  const assembled = concatBytes(parts);
1588
1978
  if (assembled.byteLength > MAX_RECORDING_UPLOAD_BYTES) {
1589
- await failChunkAssembly(RECORDING_TOO_LARGE_REASON);
1979
+ await failChunkAssembly(
1980
+ RECORDING_TOO_LARGE_REASON,
1981
+ "recording_too_large",
1982
+ );
1590
1983
  }
1591
1984
  // `parts` is no longer needed — dropping the array reference lets V8
1592
1985
  // GC the Uint8Array slices while uploadFile is in flight. Each entry
@@ -1812,10 +2205,11 @@ export default defineAction({
1812
2205
  if (upload === null) {
1813
2206
  const now = new Date().toISOString();
1814
2207
  if (requiresConfiguredVideoStorage()) {
1815
- await db
2208
+ const [failedRecording] = await db
1816
2209
  .update(schema.recordings)
1817
2210
  .set({
1818
2211
  status: "failed",
2212
+ failureCode: "storage_setup_required",
1819
2213
  failureReason: STORAGE_SETUP_REQUIRED_REASON,
1820
2214
  durationMs: finalDurationMs,
1821
2215
  width: finalWidth,
@@ -1826,7 +2220,65 @@ export default defineAction({
1826
2220
  mediaUpdatedAt: now,
1827
2221
  updatedAt: now,
1828
2222
  })
1829
- .where(eq(schema.recordings.id, id));
2223
+ .where(
2224
+ and(
2225
+ eq(schema.recordings.id, id),
2226
+ ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
2227
+ eq(schema.recordings.status, "processing"),
2228
+ existing.uploadAttemptId
2229
+ ? eq(
2230
+ schema.recordings.uploadAttemptId,
2231
+ existing.uploadAttemptId,
2232
+ )
2233
+ : isNull(schema.recordings.uploadAttemptId),
2234
+ generationId
2235
+ ? eq(schema.recordings.uploadGenerationId, generationId)
2236
+ : isNull(schema.recordings.uploadGenerationId),
2237
+ ),
2238
+ )
2239
+ .returning({
2240
+ uploadAttemptId: schema.recordings.uploadAttemptId,
2241
+ recordingPlatform: schema.recordings.recordingPlatform,
2242
+ });
2243
+ if (!failedRecording) {
2244
+ const [current] = await db
2245
+ .select({ failureCode: schema.recordings.failureCode })
2246
+ .from(schema.recordings)
2247
+ .where(
2248
+ and(
2249
+ eq(schema.recordings.id, id),
2250
+ ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
2251
+ ),
2252
+ );
2253
+ if (current?.failureCode === "user_cancelled") {
2254
+ return {
2255
+ id,
2256
+ status: "failed" as const,
2257
+ aborted: true,
2258
+ storageSetupRequired: false,
2259
+ failureReason: "Recording cancelled by user",
2260
+ durationMs: finalDurationMs,
2261
+ };
2262
+ }
2263
+ throw new Error(
2264
+ "Recording changed before storage failure was saved",
2265
+ );
2266
+ }
2267
+ trackUploadBlockingFailure({
2268
+ id,
2269
+ ownerEmail,
2270
+ uploadAttemptId: failedRecording.uploadAttemptId,
2271
+ recordingPlatform: failedRecording.recordingPlatform,
2272
+ failureCode: "storage_setup_required",
2273
+ failureType: "storage_error",
2274
+ });
2275
+ trackRecordingFailure({
2276
+ recordingId: id,
2277
+ userId: ownerEmail,
2278
+ uploadAttemptId: failedRecording?.uploadAttemptId,
2279
+ platform: failedRecording?.recordingPlatform,
2280
+ failureCode: "storage_setup_required",
2281
+ });
1830
2282
 
1831
2283
  await writeAppState(`recording-upload-${id}`, {
1832
2284
  recordingId: id,
@@ -1847,7 +2299,7 @@ export default defineAction({
1847
2299
  };
1848
2300
  }
1849
2301
 
1850
- await db
2302
+ const [waitingStorageRecording] = await db
1851
2303
  .update(schema.recordings)
1852
2304
  .set({
1853
2305
  status: "uploading",
@@ -1861,12 +2313,33 @@ export default defineAction({
1861
2313
  mediaUpdatedAt: now,
1862
2314
  updatedAt: now,
1863
2315
  })
1864
- .where(eq(schema.recordings.id, id));
2316
+ .where(
2317
+ and(
2318
+ eq(schema.recordings.id, id),
2319
+ ownerEmailMatches(schema.recordings.ownerEmail, ownerEmail),
2320
+ eq(schema.recordings.status, "processing"),
2321
+ existing.uploadAttemptId === null
2322
+ ? isNull(schema.recordings.uploadAttemptId)
2323
+ : eq(
2324
+ schema.recordings.uploadAttemptId,
2325
+ existing.uploadAttemptId,
2326
+ ),
2327
+ generationId === null
2328
+ ? isNull(schema.recordings.uploadGenerationId)
2329
+ : eq(schema.recordings.uploadGenerationId, generationId),
2330
+ ),
2331
+ )
2332
+ .returning({ id: schema.recordings.id });
2333
+ if (!waitingStorageRecording) {
2334
+ throw new Error("Recording changed before waiting storage was saved");
2335
+ }
1865
2336
 
1866
- await writeAppState(`recording-upload-${id}`, {
1867
- recordingId: id,
2337
+ const waitingStorageState = {
2338
+ ...processingUploadState,
1868
2339
  status: "waiting_storage",
1869
2340
  failureReason: STORAGE_SETUP_REQUIRED_REASON,
2341
+ storageSetupRequired: true,
2342
+ pendingMediaVerification: false,
1870
2343
  progress: 100,
1871
2344
  chunksReceived: chunkKeys.length,
1872
2345
  totalChunks: chunkKeys.length,
@@ -1877,7 +2350,27 @@ export default defineAction({
1877
2350
  hasAudio: finalHasAudio,
1878
2351
  hasCamera: finalHasCamera,
1879
2352
  updatedAt: now,
1880
- });
2353
+ };
2354
+ const waitingStoragePublished = await compareAndSetManyAppState([
2355
+ {
2356
+ key: `recording-upload-${id}`,
2357
+ expectedValue: processingUploadState,
2358
+ nextValue: waitingStorageState,
2359
+ },
2360
+ {
2361
+ key: mediaVerificationStateKey(id),
2362
+ expectedValue:
2363
+ verificationStateRaw && typeof verificationStateRaw === "object"
2364
+ ? (verificationStateRaw as Record<string, unknown>)
2365
+ : null,
2366
+ nextValue: null,
2367
+ },
2368
+ ]);
2369
+ if (!waitingStoragePublished) {
2370
+ throw new Error(
2371
+ "Upload changed before waiting storage state was published",
2372
+ );
2373
+ }
1881
2374
  await writeAppState("refresh-signal", { ts: Date.now() });
1882
2375
 
1883
2376
  // Keep the chunk scratch-space recoverable. Once the user connects
@@ -1936,6 +2429,13 @@ export default defineAction({
1936
2429
  return await leaveRecordingProcessingForMediaVerification({
1937
2430
  id,
1938
2431
  ownerEmail,
2432
+ uploadAttemptId: readyParams.recordingAttemptId,
2433
+ uploadGenerationId: readyParams.recordingGenerationId,
2434
+ expectedUploadState: verificationExpectedUploadState,
2435
+ expectedVerificationState:
2436
+ verificationStateRaw && typeof verificationStateRaw === "object"
2437
+ ? (verificationStateRaw as Record<string, unknown>)
2438
+ : null,
1939
2439
  failureReason,
1940
2440
  media: {
1941
2441
  videoUrl: upload.url,