15 Commits

Author SHA1 Message Date
twotalesanimation 269a5cbfda fix(delivery): separate packages by show, and number same-day deliveries
Deploy / deploy (push) Successful in 6m27s
Two faults in how a package's folder is named, both of which put unrelated
files in one directory on the delivery volume.

The default layout had no {showId}, so every show's episode 101 resolved to
{deliveryRoot}/101/{packageName}. The token existed and was populated — it
just never appeared in the path. With hardlinked packages that means two
shows delivering the same episode number on the same day write into the same
folder, and identically named shots overwrite each other. reviewDir had the
same hole, and is worse there: reviewNameFor scopes its lookup by projectId,
so a second show computes the bare base name and lands on the first show's
folder instead of suffixing past it.

createDeliveryPackage also never checked for an existing package of the same
name. packageNameTemplate is date-only and packageNumber is a per-project
counter that is not in the template, so a second delivery on the same day got
an identical name and rootPath and built on top of the first. MOV reviews
already did this correctly, so nextReviewName moves to deliveries.ts as
nextPackageName and both paths share it; the review-side name is kept as an
alias because it reads better at that call site.

Putting {showId} ahead of {episode} exposes an empty segment on non-episodic
shows, so paths go through tidyPath, which collapses it and leaves the UNC
root alone.

Historic packages are unaffected: buildDeliveryJobManifest reads rootPath and
configSnapshot off the record, so only new packages use the new layout. A
project with its own deliveryConfig.layout in the database still overrides
these defaults.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 08:08:37 +02:00
twotalesanimation 59af7959e6 fix(connector): request the full QC queue instead of the default 50
Deploy / deploy (push) Successful in 6m41s
loadQCQueue called /api/ext/qc/queue with no limit, so it always got the
endpoint's default page of 50. The query orders oldest-first, so a project
with more than 50 exports in READY_FOR_QC showed only the oldest 50 with
nothing to say the list was short.

Ask for 200 — the server's hard ceiling in getQCQueue — and say so in the
status line when the count comes back at the cap, so a truncated queue is
visible rather than silent.

The diagnostics call in checkServerPathReachable stays on the default: it
only reads entries[0].

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 07:24:21 +02:00
twotalesanimation a6ee1917e7 fix(connector): cancel the export poll when the panel closes or reloads
Deploy / deploy (push) Successful in 6m46s
app.scheduleTask outlives the panel instance that armed it. The repeating task
id was held in the pipelineState closure, so closing or reloading the panel took
the id with it and left nothing able to cancel the task: it kept firing every
15 s for the rest of the AE session, and every tick landing while a modal dialog
was open raised "Cannot run a script while a modal dialog is waiting for
response."

The id now lives in global scope beside the tick function that scheduleTask
already evaluates there, so the next panel instance can still reach it.
getPollTaskId and setPollTaskId wrap the access and treat anything that is not a
positive number as no task. Panel startup cancels whatever a previous instance
left armed before pointing the tick at itself, rather than letting the old task
fire into a fresh, empty state whose shot code went with the closure that armed
it, and panel.onClose stops the poll on the way out.

The export is unaffected either way: it runs on the farm, and the header picks
its status back up from the server on the next Refresh. Section 12.1 of
RenderPipeline2.md records that.

PANEL_VERSION goes to 2.6.1 per the documented rule, so Pipeline → Machines does
not show two workstations on one version behaving differently.

This change was authored in the working tree, not by Claude; it is committed
here alongside the status and client-portal work at the author's request, and
the message was written from reading the diff. It has not been exercised in a
live After Effects session as part of this commit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 18:18:08 +02:00
twotalesanimation 28e8c47907 feat(client-portal): let a reviewer edit and delete their own notes
Notes left through a review link were write-once. A client who mistyped a
timecode or changed their mind had no way to correct it and had to add a second
note contradicting the first, which the studio then had to reconcile by hand.

PATCH and DELETE on comment/[commentId] cover both. Only the reviewer's own
notes are touchable: the studio's comments and those of every other review
session are read-only through a link, whatever the holder sends. Ownership is
re-checked server-side on every write, so the canEdit flag now returned by the
versions route only decides whether to offer the controls and grants nothing.

Refusals are 404 rather than 403 throughout, since a link holder has no business
learning which comment ids exist outside their own notes.

Only the text is editable. The frame a note is pinned to is what the studio
works from, so moving it would silently repoint feedback someone may already
have actioned; a note about a different frame is a new note. Deleting a drawing
note also removes its strokes, mirroring deleteComment in actions/comments.ts,
and the page reloads the player afterwards so the frame does not keep showing
marks that no longer exist. Delete goes through a confirmation that shows the
note and says plainly that it disappears for the studio too.

Worth knowing before this reaches a show: everyone holding the same review link
is the same author. A ReviewSession with no email resolves to a token-derived
guest user, so one link sent to three people gives all three one identity and
any of them can now edit or delete the others' notes. That model is not new,
which is why their comments already showed as one name, but edit and delete is
the first feature where it grants real power rather than muddling attribution.
Per-reviewer links with email set are the fix if that is not wanted, and that is
a change to how links are issued rather than to this code. The scope is
documented on reviewClientEmail so the next reader meets it before it surprises
them.

getOrCreateClientUser was copy-pasted into the comment and approve routes with
the fallback-email expression spelled out in three places. It is one set of
helpers in review-auth.ts now, including findReviewUser, a read-only variant so
that merely opening a review link does not conjure a User row just to answer
"is this theirs?", and ownsComment, the single rule shared by the route that
offers the controls and the route that enforces them.

Nine tests cover that rule directly: internal users' notes stay read-only, a
session that has never posted owns nothing, and an authorless comment — one
whose User was deleted, since Comment.authorId is SetNull — cannot be claimed by
anyone. The routes themselves are not covered, so exercise edit and delete
against a real review link before handing one to a client.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 18:17:40 +02:00
twotalesanimation 94792279c5 fix(status): reset review state on a new version, and derive shot status everywhere
Requesting changes on a shot and then re-rendering it through the render queue
left every layer of the app still showing the old verdict. Three independent
causes, all on the pipeline path.

finalizePreview inherited the superseded version's approvalStatus
unconditionally. The carry-over exists so a re-export of a signed-off shot does
not reappear as awaiting review, but it applied equally to NEEDS_CHANGES and
REJECTED, so the render queued to address a note arrived already wearing that
note and nothing registered that the work had been redone. carryApproval now
carries only APPROVED.

The pipeline never moved the task. One left on CHANGES by a review or a QC fail
stayed there through every re-render, with no way out but a manual kanban drag.
A genuinely new version now moves it to INTERNAL_REVIEW, as actions/versions.ts
and batch-upload already did. A replaced version is excluded: regeneratePreview
re-delivers the same version after a slate fix and is not a new submission.

The pipeline never called recalcShotStatus at all, so shot boards went stale the
moment a render changed a task. finalizePreview and the QC fail path both
recalculate now; the latter already documented the REVISIONS derivation it was
relying on and never triggering.

Shot.status is derived from tasks and approval flags, but six call sites wrote
it directly with the status they expected: internallyApproveShot,
shareWithClient, unshareFromClient, clientApproveShot, unapproveShot and the
client approve route. Rule 1 of the derivation is that any CHANGES task outranks
an approval, so a shot could be pushed past open rework and then snap back to
REVISIONS on the next unrelated recalc, which is close to unreportable as a bug.
They now set the approval inputs and let recalcShotStatus derive.
unshareFromClient additionally hardcoded READY_FOR_CLIENT even for a
client-approved shot. updateShotStatus keeps its direct write as the deliberate
manual override, now documented as transient for the same reason.

markShotForRevisions replaces the duplicated change-request logic. Both copies
marked all non-DONE tasks CHANGES, which matches nothing on the shot this is
most often called for: one out for client review precisely because all its tasks
are finished. The request then derived to INTERNAL_REVIEW and had no visible
effect anywhere. When nothing is picked up it now reopens the task behind the
shot's latest version, which is the deliverable the reviewer was looking at.

A client's shot-level change request also marks the versions and writes Approval
rows now. The dashboard counters, the version badges and the portal's own
filters all read Version.approvalStatus, so a shot-level verdict was invisible
everywhere those look.

clearStaleShotApproval covers the reverse case: uploading a new version onto an
approved shot moved the task to INTERNAL_REVIEW and changed nothing visible,
because the derivation short-circuits on shotApprovalStatus. The shot kept
reading COMPLETE while carrying work nobody had looked at. This is the one
user-visible behaviour change here, so watch the boards on a live show: an
approved shot now drops back to INTERNAL_REVIEW on a new upload. sharedWithClient
is deliberately left alone, since revoking client access stays a separate act.

submitApproval and unapproveVersion are transactional now. The verdict, the
version, the task and the derived shot status are one decision, and a failure
partway through left the three layers disagreeing with no way to tell which one
was right.

KanbanCard compared approvalStatus against "CHANGES_REQUESTED", which is not a
member of the enum, so the changes-requested icon never rendered at all.

Thirteen tests cover carryApproval, markShotForRevisions including the all-DONE
regression, and clearStaleShotApproval. What is not covered is the pipeline
transaction itself, which needs a database: queue a render against a shot in
REVISIONS and confirm the task and shot both move before trusting this on a
show.

Version.reviewStatus is still written nowhere while being published through
ext/shots/lookup and EXT_API_REFERENCE.md as a permanent "PENDING". Left alone
deliberately: removing a field from that contract could break the connector.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 18:17:04 +02:00
twotalesanimation 93137cdcd2 fix(connector): anchor built comps on the plate's own EXR timecode
Build Shot produced comps starting at 00:00:00:00 because the panel never
actually read the EXR timecode. getFootageStartFrames ranked a fragile "New
Comp from Selection" probe first: it toggles the Project panel via the Window
menu to get focus, and where that does not land the menu item is greyed out,
executeCommand silently does nothing, and the probe returns null. A shot with
no timecodeStart then fell through the API rank to zero.

The worker already reads EXR headers properly in ExrHeader.cs, and its
validation ranks the plate's own timeCode above the API value, which stores the
editorial in-point and sits a handle-length ahead of the plate by design. Shots
were therefore being built from rank 3 and validated against rank 1. That is a
timecode desync waiting to reach a delivery, not just a cosmetic start frame.

readExrTimecode ports the worker's reader to ExtendScript and becomes rank 1:
one short header read, walking `name\0 type\0 int32 size data` for timeCode and
falling back to timeCodeString where a writer omitted the packed attribute.
decodePackedTimecode mirrors Timecode.FromPacked, decoding the SMPTE 12M BCD a
byte at a time so the arithmetic never touches the sign bit. The menu probe is
kept as rank 2 and now runs only when the plate carries no timecode at all, so
the Project-panel toggle is off the normal path.

setCompStartFrame was the second failure. Assigning displayStartFrame on a
version of AE that does not have the property is ignored silently rather than
throwing, so the early return skipped the displayStartTime fallback entirely.
It now reads the value back, falls through when it did not take, and returns
whether anything stuck; buildShotFromCode logs when nothing does. A start frame
that cannot be set is now visible in the diagnostics report instead of a comp
quietly sitting at zero.

A plate whose timecode is present but zero still falls through to the API rank,
keeping the existing frames > 0 convention so the safety net survives. If a
genuine 00:00:00:00 plate should win outright that is a deliberate follow-up.

The parser is covered against synthetic headers, including the 0x18585712
example documented in ExrHeader.cs, drop-frame, truncated and non-EXR input.
What is not yet exercised in a live After Effects session is mainSource.file
resolving to the sequence's first frame and displayStartFrame taking on a given
AE build, so build one shot and check its start against the plate before
relying on this. Picture-lock automation was reverted for a timecode desync of
the same shape.

PANEL_VERSION goes to 2.6.0 per the documented rule, so Pipeline → Machines
does not show two workstations on one version behaving differently. The
startSource comment in the manifest schema enumerated only the two older
values; the queue-time provenance check keys on /\bAPI\b/ and so already reads
"EXR timecode …" as trustworthy rather than suspect.

The same silent-failure setCompStartFrame still exists in the farm-side
vfxr_build_preview.jsx, which is fed the right value from the manifest but can
drop it the same way. Left for its own change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 16:53:49 +02:00
twotalesanimation 6678721fb1 fix(pipeline): create the comp task an export needs when a shot has none
Deploy / deploy (push) Successful in 6m48s
A shot with no COMP task rendered and previewed fine and then showed
nothing in the app. createExport set Export.taskId from the shot's first
COMP task or null, and finalizePreview registered the review Version with
that same null taskId — so the MP4 was uploaded and stored, but the
Version hung off no task and none of the review flows had anywhere to
draw it. From the artist's side the export completed and produced
nothing.

E1 now resolves the shot's comp task inside the version-allocation
transaction and creates one when there isn't any, titled after the
preview file the export will produce: {shotCode}_cmp_TT_{version}, the
same convention the manual batch upload's create-task path already uses.

renderOutputBase() is exported and buildPreviewManifest takes its `base`
from it, so the task title and the MOV/MP4 name come from one function
rather than two copies of the same template. The title therefore already
carries the version, which makes finalizePreview's rename-to-the-
delivered-version a no-op on that first export rather than an immediate
rename of a task created moments earlier.

The lookup and the create sit inside the transaction so the P2002
version-collision retry rolls a losing attempt's task back with
everything else, instead of leaving a duplicate behind.

recalcShotStatus runs only when a task was actually created: a shot with
no tasks derives WAITING and now has one. Approval-driven statuses still
take precedence, so an already-approved shot stays COMPLETE.

Both the queue-time ExportEvent note and the E1 response record what
happened, so a task appearing under a shot on its own is traceable to the
export that made it.

Exports already in flight with a null taskId keep their orphaned
versions; backfilling those is a separate migration.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 14:09:01 +02:00
twotalesanimation bac525ddd0 feat(shot-status): shot version beside the name, and a scaled-in-edit flag
Deploy / deploy (push) Successful in 7m28s
Two small board additions.

The shot version now shows next to the shot code. It is Shot.shotVersion —
the value the AE panel burns into overlays and queueExport renders under,
and the one the shot detail page edits — not a count of uploaded review
Versions, so the board agrees with what the artist has in the panel.

Shot.isScaled records that a shot is scaled in the edit: the plate is not
used at its native size, which changes how the shot is comped and
reviewed. That makes it a standing property of the shot rather than
something buried in the notes, so it is flagged the way isKeyShot is — a
cyan pill next to the shot name, and a Scaled toggle column beside Key.
toggleScaledShot() (actions/shots.ts) mirrors toggleKeyShot, same roles.

KeyShotToggle's switch markup would have been duplicated verbatim for the
second flag, so both now sit on a shared FlagToggle taking a colour tone
and a setter. The key-shot switch behaves exactly as before, optimistic
update and rollback included.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 09:57:05 +02:00
twotalesanimation 7f066c1372 feat(pipeline): MOV review delivery packages from selected shots
Deploy / deploy (push) Successful in 7m28s
A formal review is shared as a flat, dated folder of the preview MOVs —
{deliveryRoot}/PRODUCER_REVIEWS/20260828_Producer_review, then _02, _03
for further reviews the same day. It reuses the delivery package's
machinery end to end: DeliveryPackage/DeliveryItem, the DELIVERY_BUILD
job, the same claim path and the same hardlink-or-copy builder, with
DeliveryPackage.kind telling the two apart.

Three things separate a review from a delivery:

A review never advances an Export. Reviews happen throughout a shot's
life, long before QC passes it, and the same version is routinely shown
twice — so nothing is marked PACKAGED, and markDelivered() refuses a
review package outright (the button is hidden too).

Selection is by shot, not by export. Shot Status → Bulk Actions → Build
MOV Review Package; the server resolves each shot to its newest export
that actually has a deliveryMovPath, which is not always its newest
export — a shot whose latest version is still rendering belongs in the
review as the version that can be watched. Shots with no MOV at all are
listed in the confirm dialog with the reason rather than silently
shrinking the folder.

The folder is exactly the MOVs. No CSV, no manifest.json written beside
them; the manifest still returns to the server, so the record of what was
shared is kept without cluttering the share. Names follow the same
client-naming rule as a delivery, so a shot reads identically in a review
folder and in the delivery that follows it.

Verification (DeliveryStage.BuildReviewItem) is proportional as it is for
EXRs, adapted to a single file with no validation-time digest: a hard
link is the source and needs nothing, a copy is checked against its
source by length always and by full hash under "always-hash". A missing
MOV fails the item here — in an EXR delivery the MOV is a viewing copy
beside the real deliverable, but in a review it is the deliverable, and a
review folder quietly one shot short is worse than one that says so.

Worker bumped to 1.6.0 for the new manifest field (DeliveryManifest.Kind).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 08:58:21 +02:00
twotalesanimation ed9f9b13c1 feat(client-portal): show shots and task titles in the client's own naming
Deploy / deploy (push) Successful in 6m8s
Shot.clientCode already drove slates, overlay burn-ins and delivered file
names, but the client portal — the one place the client actually reads — was
still showing our internal codes.

Task titles were the larger leak. They follow the house convention
"UNG_106_010_020_cmp_TT_v004", so the internal code sat embedded in the
string the client reads and copies, in three places on the shot list and
again in the player header. Swapping only the heading would have left it on
display directly underneath.

lib/shot-code.ts resolves both: clientShotCode picks the alias when set, and
clientTaskTitle swaps the code out of a title by substring, leaving a
hand-edited title that does not carry the code untouched rather than guessing
at it.

Applied at the API boundary rather than at each render site, so the shot
list, search, playlist labels, alt text, player header and every
copy-to-clipboard button inherit it and nothing downstream has to remember
which code it is holding. The internal code is no longer sent to the browser
on these routes at all.

Slack notifications deliberately keep the internal code: those go to our
artists, who need the code that matches the comp and the SAN path.

The two existing "clientCode || shotCode" expressions in preview.ts and
deliveries.ts now use the same helper so slates, deliveries and the portal
cannot drift apart. Shots with no clientCode are unchanged throughout.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 23:16:53 +02:00
twotalesanimation 1fad6a739d fix(worker): drain ffmpeg's pipes so thumbnail generation stops deadlocking
Deploy / deploy (push) Successful in 9m16s
ffmpeg was started with stdout and stderr redirected and neither pipe ever
read. Windows gives an anonymous pipe a ~4 KB buffer, which ffmpeg's banner
and stream summary exceed on their own, so it blocked forever on the write,
never exited, and the two-minute cap fired:

    TaskCanceledException at Process.WaitForExitAsync
    Preview complete for job ... in 221s (mov + mp4)

The exception was swallowed as "non-fatal", so every preview silently
produced no thumbnail while paying 120s for the privilege. Nothing
downstream was wrong — there was simply never a thumbnail to promote.

Both pipes are now drained concurrently before the wait. A timeout kills the
process tree rather than leaking an ffmpeg per job, and attempts report a
three-way outcome so a hung or unstartable ffmpeg is not retried — without
that, the slate fallback would have doubled the wasted time to four minutes.

Failures are no longer silent: an unset or missing ffmpegPath, the seek that
was chosen, and ffmpeg's own exit code, command and stderr are all logged.

finalizePreview likewise records every promotion outcome on the export
timeline, not just success. Silence there was indistinguishable from a broken
worker, a project whose flag never saved, and the feature working as
configured — which is what made this take so long to find.

Adds scripts/diagnose-thumbnails.mjs, which walks the chain (ffmpeg →
Export.thumbnailKey → project flag → Shot.generatedThumbnailUrl → what the UI
resolves) and names the first broken link.

Worker 1.5.1 -> 1.5.2; republish required for the fix to take effect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 22:48:29 +02:00
twotalesanimation 9cd7b0df6e chore: retrigger deploy
Deploy / deploy (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 17:23:42 +02:00
twotalesanimation caaa333f02 feat(pipeline): render-derived shot thumbnails, and bulk shot delete
Deploy / deploy (push) Failing after 19m11s
Two independent features landing together:

Generated shot thumbnails — a shot can now carry a thumbnail promoted
from a render export (Shot.generatedThumbnailUrl/generatedThumbnailFrom)
alongside the existing brief-supplied thumbnailUrl, which always takes
display precedence (lib/shot-thumbnail.ts) so a promoted frame can only
ever fill a gap, never overwrite the brief. Shows with
pipelineConfig.autoShotThumbnail promote automatically on every
finished export (lib/render-pipeline/preview.ts); promoteExportThumbnail/
clearGeneratedThumbnail (actions/shots.ts) are the manual equivalent for
everyone else. Worker-side seek logic for picking the promoted frame is
covered by RenderWorker/VFXReviewWorker.Tests/ThumbnailSeekTests.cs.

Bulk shot delete — the shot-status page's selection bar gets a "Bulk
Actions" dropdown (alongside the existing Change Due Date) with Delete
Shots. bulkDeleteShots() (actions/shots.ts) deletes one at a time rather
than in a single statement: exports_shotId_fkey is ON DELETE RESTRICT
by design, so a shot with renders or deliveries on record is protected
and gets skipped and reported by name rather than aborting the whole
selection or being silently destroyed along with its history.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 17:06:55 +02:00
twotalesanimation b151e8cc52 feat(pipeline): per-shot client naming alias for slates, overlays, and delivery
Deploy / deploy (push) Successful in 7m25s
Clients sometimes ship footage under a naming convention that doesn't
match our own shot codes. Adds an optional Shot.clientCode, editable on
the Slate tab: when set, it replaces shotCode only in what the client
actually sees — slate identity, overlay burn-in, and delivered EXR/MOV
file and folder names in Netflix packages — with our own version string
flatly appended (no "_cmp_TT_" studio jargon mixed in). Internal render
paths, EXR filenames on the SAN, comp names, and DB lookups are
untouched. Shots without a client code render identically to before.

Delivery packages denormalize clientCode at build time, same as the
existing shotCode/versionString snapshot, so a later shot edit can't
retroactively change already-built delivery history. The worker now
renames delivered EXR frames and the delivery MOV using the existing
frame-number parser (SequencePattern) so only the base name changes —
frame numbers and padding survive exactly. This is the one piece of the
change that could plausibly ship the wrong bytes, so it's covered by
new unit tests (renaming, padding, MOV rename, checksum-survives-rename,
and a graceful fallback for an unparseable frame number) rather than
resting on manual verification alone.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-26 00:38:12 +02:00
twotalesanimation 26a4719c2a fix(connector): strip reference LUT/overlay before Queue Export renders EXRs
Build Shot adds the show LUT and overlay burn-in into the artist's main
comp, enabled by default, for reference while compositing. The legacy
manual "Queue EXR" button has always disabled both before rendering;
Queue Export (the pipeline's one-click path) never got that same step,
so EXRs queued through it could ship with the LUT graded in and the
burn-in baked on. Queue Export now disables them the same way, right
before the project save the render worker reads from.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 22:47:42 +02:00
75 changed files with 4273 additions and 333 deletions
+72
View File
@@ -2,6 +2,11 @@
How a finished shot becomes a dated folder ready to upload to the client.
There are two kinds of package. An **EXR delivery** is the shippable one and is
what most of this guide describes. A **MOV review** is a flat folder of preview
MOVs shared for a formal review — see
[MOV review packages](#mov-review-packages) at the end.
This is the operational guide. The design rationale and normative rules live in
[RenderPipeline2.md](RenderPipeline2.md) §11.
@@ -236,3 +241,70 @@ a different spec is a config change rather than a code change.
Omit `exportIds` to take every ready export in the episode; `options` accepts
`date`, `name`, `includeMovs` and `copyMode` to override the config for one
build.
---
## MOV review packages
For a formal review you share the preview MOVs, not the EXRs. That is its own
kind of package, built the same way and listed on the same page.
### Building one
**Shot Status**, tick the shots, then **Bulk Actions → Build MOV Review
Package**. A dialog shows exactly what would be built before anything happens:
the folder name, the version each shot contributes, and any shots being left
out. Requires **admin, producer or supervisor**.
The version each shot contributes is its **newest export that actually has a
preview MOV** — not necessarily its newest export. A shot whose latest version
is still rendering goes into the review as the version that can be watched.
A shot with no MOV at all is listed as left out, with the reason, rather than
quietly reducing the folder.
### What lands on disk
```
{deliveryRoot}/PRODUCER_REVIEWS/20260828_Producer_review/
├── EP6_VFX_012_v004.mov
├── EP6_VFX_013_v002.mov
└── UNG_106_010_040_cmp_TT_v001.mov
```
Flat — the MOVs sit beside each other so they can be scrubbed through in order.
Names follow the same client-naming rule as a delivery: the production's own
code where it has one, ours where it does not, so a shot reads identically in a
review folder and in the delivery that follows it.
The folder is **exactly the MOVs**: no CSV, no `manifest.json` beside them. The
manifest still goes back to the app, so the record of what was shared is kept
without cluttering the share.
Second review the same day is `20260828_Producer_review_02`, then `_03`. A
number is never reused, even if the package that took it was cancelled.
### What it does not do
**A review never moves a shot along.** Reviews happen throughout a shot's life,
long before QC passes it, and the same version is routinely shown twice — so
building one changes nothing about the exports in it, and there is no
**Mark delivered** on a review package. Shots stay exactly where they are in
the pipeline.
A **missing MOV fails the package** here, unlike in an EXR delivery where a
missing MOV is logged and the build continues. In a review the MOV is the
deliverable, and a review folder quietly one shot short is worse than one that
says so.
### Configuration
Two more keys in the same `deliveryConfig` (§11.6):
```json
{
"reviewNameTemplate": "{yyyymmdd}_Producer_review",
"layout": {
"reviewDir": "{deliveryRoot}/PRODUCER_REVIEWS/{packageName}"
}
}
```
+54 -3
View File
@@ -207,7 +207,7 @@ stateDiagram-v2
| T9 | VALIDATION_FAILED | QUEUED | Retry (full re-render) | User | new attempt; old validation rows kept for history |
| T10 | GENERATING_PREVIEW | PREVIEW_FAILED | ffmpeg/upload failure | Worker | error stored |
| T11 | PREVIEW_FAILED | GENERATING_PREVIEW | Retry preview | User | validation is NOT re-run |
| T12 | GENERATING_PREVIEW | READY_FOR_QC | `finalize` report | Worker | `Version` row created (isLatest, **never client-shared**), thumbnail set, metadata JSON key stored; **no task/shot status change** — QC typically runs on already client-approved shots and must not disturb review state (Section 10) |
| T12 | GENERATING_PREVIEW | READY_FOR_QC | `finalize` report | Worker | `Version` row created (isLatest, **never client-shared**), thumbnail set, metadata JSON key stored; `Shot.generatedThumbnailUrl` set when the project opts in (§9.1a) — never `Shot.thumbnailUrl`; **no task/shot status change** — QC typically runs on already client-approved shots and must not disturb review state (Section 10) |
| T13 | READY_FOR_QC | QC_FAILED | `POST .../qc {FAIL}` | Artist (AE) or user (web) | `QCReview` row; task → CHANGES (drives existing Shot REVISIONS derivation) |
| T14 | READY_FOR_QC | READY_FOR_DELIVERY | `POST .../qc {PASS}` | Artist / user | `QCReview` row |
| T15 | READY_FOR_DELIVERY | PACKAGED | Delivery build completes | Worker | `DeliveryItem` links Export to package |
@@ -268,6 +268,9 @@ model Export {
shot Shot @relation(fields: [shotId], references: [id])
projectId String
taskId String? // comp task the preview Version attaches to
// (E1 creates one named after the preview file
// when the shot has none, so the preview lands
// somewhere the app shows it)
versionId String? // preview Version created at READY_FOR_QC
versionNumber Int // 4
versionString String // "v004"
@@ -448,6 +451,7 @@ model DeliveryPackage {
projectId String
episode String // "101"
name String // "260805_Delivery" (per 18.1-Q6 convention)
kind DeliveryKind @default(EXR_DELIVERY) // EXR_DELIVERY | MOV_REVIEW (§11.6)
packageNumber Int // sequential per project → "Package #15"
status DeliveryStatus @default(DRAFT)
rootPath String? // final path on delivery volume
@@ -464,6 +468,7 @@ model DeliveryPackage {
@@unique([projectId, packageNumber])
@@index([projectId, episode])
@@index([projectId, kind])
}
model DeliveryItem {
@@ -488,6 +493,8 @@ model DeliveryItem {
**Version locking:** the package references `Export` rows, and items denormalise `shotCode`/`versionString` at creation. Later re-renders of a shot never mutate a package — delivery history is immutable by construction.
**`kind`** distinguishes a shippable EXR delivery from a MOV review folder (§11.6). Both use these two models and the same `DELIVERY_BUILD` job; only a review leaves `exrPath` null, and only a delivery advances its exports to PACKAGED/DELIVERED.
### 5.8 Changes to existing models (additive only)
| Model | Addition | Purpose |
@@ -1100,18 +1107,36 @@ Runs on the worker after validation passes (Export = GENERATING_PREVIEW).
### 9.1 Stages
1. **Build + render preview comp (AE, headless).** The worker launches `AfterFX.com -noui -r vfxr_build_preview.jsx`, passing a job-context JSON file (manifest + slate/overlay fields fetched from E3). The script is the connector's existing preview-comp code, packaged with the worker: it imports the *validated* EXR sequence, builds the preview comp from the studio template (head slate populated from API data, overlays/burn-ins throughout), applies the colour chain (linear → log → show LUT from `colorPipeline` config), queues it with the project's MOV output-module template, and renders the **delivery-grade preview MOV** to the SAN beside the EXRs (`Export.deliveryMovPath`). This is the "MOV LT Preview" that ships inside delivery packages (Section 11).
2. **Web transcode (ffmpeg).** The delivery MOV is transcoded to a web-playable H.264 (1920-wide, CRF 18) and a thumbnail JPEG (frame at 25% duration, 960-wide), uploaded via E20 presign.
2. **Web transcode (ffmpeg).** The delivery MOV is transcoded to a web-playable H.264 (1920-wide, CRF 18) and a thumbnail JPEG (960-wide), uploaded via E20 presign. The thumbnail is taken at **25% of *picture* duration**, seeking past the head slate: the build script reports the SHOT layer's in-point as `pictureStartSeconds`, and the worker seeks to `pictureStart + 25%`. Builds that report no picture start fall back to scanning the whole file. (Until 2026-08-27 this used ffmpeg's `thumbnail` filter, which only considers the first 100 frames — on a slated preview, the slate card. Every thumbnail produced before then is a picture of the slate.)
3. **Metadata JSON.** Worker-composed (manifest + validation summary + render stats + checksums + tool/template versions), uploaded via E20.
| Artifact | Produced by | Destination |
|---|---|---|
| Delivery MOV (slate + burn-ins, graded via show LUT, delivery codec from AE output template) | AE headless render | SAN → `Export.deliveryMovPath`; copied/linked into delivery packages |
| Web preview MOV (H.264) | ffmpeg transcode of the delivery MOV | object storage `videos/` → `Version.fileUrl` |
| Thumbnail | ffmpeg | `image/` → `Version.thumbnailUrl` + `Export.thumbnailKey` |
| Thumbnail | ffmpeg | `image/` → `Version.thumbnailUrl` + `Export.thumbnailKey`; also `Shot.generatedThumbnailUrl` when the project opts in (§9.3) |
| Metadata JSON | worker | `renders/` → `Export.metadataKey` |
Because the web preview is a transcode of the AE-generated MOV, review media and delivery media are guaranteed to show identical slates, burn-ins, and colour — one source of truth.
### 9.1a Render frames as shot thumbnails
Shots carry two stills, in two columns, and the distinction is the whole design:
| Column | Written by | Meaning |
|---|---|---|
| `Shot.thumbnailUrl` | humans only — single upload, batch upload, ext API | The reference frame that came with the brief. Editorial data. |
| `Shot.generatedThumbnailUrl` | the pipeline, and the manual promote action | A frame lifted from a finished export. |
Display resolution is `thumbnailUrl ?? generatedThumbnailUrl` (`lib/shot-thumbnail.ts`), applied at every shot surface: shot grid, kanban, schedule, shot status, storyboard (screen and PDF), shoot log, slate tab, client portal, and the ext APIs the Nuke/AE panel reads. **The reference always wins**, so the pipeline can only fill a gap and can never overwrite the brief — clearing the generated one always falls back.
Promotion happens two ways:
* **Automatically**, for projects with `pipelineConfig.autoShotThumbnail` set (Project Settings → *Use render frames as shot thumbnails*). Off by default and deliberately per-show: productions that ship a still with every shot already have a reference frame and the renders should not compete with it. It exists for shows that arrive with no stills at all, where the alternative is an empty grid. `finalizePreview` writes the column and notes it on the export timeline.
* **By hand**, via `promoteExportThumbnail` / `clearGeneratedThumbnail` (Shot Settings → Thumbnail → *From renders*), which work regardless of the project flag — one shot on an otherwise hands-off show. With no explicit export, the newest export of that shot that has a thumbnail is used.
Note this is the one place a render-derived artifact reaches the client portal. It is a still, not a `Version`, so §10.0 is intact — no technical render re-enters the review flow and no approval state moves — but a client viewing a shot with no supplied still now sees a frame from the render rather than a placeholder.
### 9.2 Colour configuration
`Project.deliveryConfig.colorPipeline` (per 18.1-Q4/Q12) — **required and unique per project**; enabling the pipeline on a project without it is a validation error, and values must never be carried over from another show:
@@ -1230,6 +1255,27 @@ Tokens: `{showId} {episode} {yymmdd} {yyyymmdd} {packageName} {packageDir} {shot
The Delivery Packages page (Section 13) lists every package permanently: `#15 · 101/260805_Delivery · Episode 101 · 18 shots · built 2026-08-05 · delivered 2026-08-05 by Chris`, expandable to items → Export → full render/validation/QC history. Packages are never deleted; a mistaken package is CANCELLED (DRAFT/QUEUED/FAILED only) or superseded by building a new one.
### 11.6 MOV review packages (`DeliveryPackage.kind = MOV_REVIEW`)
A formal review is shared as a flat, dated folder of the preview MOVs — the same package/job/verification machinery as §11.1–11.5, a different shape on disk:
```
{deliveryRoot}/PRODUCER_REVIEWS/20260828_Producer_review/
├── EP6_VFX_012_v004.mov ← client naming where the production supplies it
├── EP6_VFX_013_v002.mov
└── UNG_106_010_040_cmp_TT_v001.mov ← ours where it does not
```
The second review that day is `_02`, the third `_03`; the first carries no suffix. Numbering counts every package built under that base — cancelled and failed ones included — so a number is never reused for a different folder. Config: `reviewNameTemplate` (default `{yyyymmdd}_Producer_review`) and `layout.reviewDir` (default `{deliveryRoot}/PRODUCER_REVIEWS/{packageName}`).
Three rules separate a review from a delivery:
- **It never advances an Export.** Reviews happen throughout a shot's life, long before QC passes it, and the same version is routinely shown twice. Nothing is marked PACKAGED or DELIVERED when the folder is built, and `Mark delivered` is refused on a review package.
- **Selection is by shot, not by export.** The user picks shots on Shot Status → *Bulk Actions → Build MOV Review Package*; the server resolves each to its **newest export that actually has a `deliveryMovPath`** — not necessarily its newest export, since a shot whose latest version is still rendering should go into the review as the version that can be watched. Shots with no MOV at all are listed in the confirm dialog and left out rather than silently dropped.
- **The folder is exactly the MOVs.** No CSV, no `manifest.json` written beside them. The manifest still returns to the server, so the record of what was shared is kept without cluttering the share.
Verification is proportional as in §11.3, adapted to a single file with no validation-time digest: a hard link is the source and needs nothing; a copy is checked against its source by length always, and by full hash under `"verifyMode": "always-hash"`. A missing MOV **fails the item** here — in an EXR delivery the MOV is a viewing copy beside the real deliverable, but in a review it *is* the deliverable, and a review folder quietly one shot short is worse than one that says so.
---
## 12. AE Panel Changes
@@ -1246,6 +1292,11 @@ The panel keeps all existing capabilities (episode/shot discovery, overlays, pic
| Latest Export + QC status | new E2 `exports/latest` — e.g. `v004 — READY_FOR_QC`, `v004 — RENDERING 42% (ETA 1:36 on RENDER-01)`, `v003 — QC FAILED: "grain mismatch"` |
While an export is active the panel polls E2 every 15 s to live-update the header.
The poll stops when the export leaves an active status, and also when the panel is
closed or reloaded — `app.scheduleTask` outlives the panel instance that armed it,
so the task id is kept in ExtendScript global scope where the next instance can
still cancel it. The export is unaffected either way: it runs on the farm, and the
header picks its status back up on the next Refresh.
### 12.2 Buttons and their API calls
@@ -238,4 +238,104 @@ public class DeliveryStageTests : IDisposable
Assert.True(second.Ok);
}
[Fact]
public async Task NoClientCodeKeepsTheInternalRenderFilenames()
{
// Regression pin: DeliveredBaseName defaults to "" for a shot with no
// client code, and delivery must render byte-identical to before this
// feature existed.
WriteFrames(2);
var manifest = Manifest(fileCount: 2);
Assert.Equal("", manifest.Items[0].DeliveredBaseName);
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
Assert.True(File.Exists(Path.Combine(_packageDir, "SHOT_001", "SHOT_001_cmp_TT_v001.01001.exr")));
Assert.True(File.Exists(Path.Combine(_packageDir, "SHOT_001", "SHOT_001_cmp_TT_v001.01002.exr")));
}
[Fact]
public async Task ClientCodeRenamesDeliveredFramesPreservingNumberAndPadding()
{
WriteFrames(3, startFrame: 1001);
var manifest = Manifest(fileCount: 3);
manifest.Items[0].DeliveredBaseName = "SNV_101_0461_CP_CAMF_PL_v001";
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
var deliveredDir = Path.Combine(_packageDir, "SHOT_001");
Assert.True(File.Exists(Path.Combine(deliveredDir, "SNV_101_0461_CP_CAMF_PL_v001.01001.exr")));
Assert.True(File.Exists(Path.Combine(deliveredDir, "SNV_101_0461_CP_CAMF_PL_v001.01002.exr")));
Assert.True(File.Exists(Path.Combine(deliveredDir, "SNV_101_0461_CP_CAMF_PL_v001.01003.exr")));
// The internal shotCode-based name must not leak into the delivery.
Assert.False(File.Exists(Path.Combine(deliveredDir, "SHOT_001_cmp_TT_v001.01001.exr")));
Assert.Equal(3, Directory.GetFiles(deliveredDir, "*.exr").Length);
}
[Fact]
public async Task ClientCodeRenamesTheDeliveryMov()
{
WriteFrames(2);
var movSrc = Path.Combine(_sourceDir, "SHOT_001_cmp_TT_v001.mov");
File.WriteAllText(movSrc, "mov bytes");
var manifest = Manifest(fileCount: 2);
manifest.IncludeMovs = true;
manifest.Items[0].DeliveryMovPath = movSrc;
manifest.Items[0].DeliveredBaseName = "SNV_101_0461_CP_CAMF_PL_v001";
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
var deliveredDir = Path.Combine(_packageDir, "SHOT_001");
Assert.True(File.Exists(Path.Combine(deliveredDir, "SNV_101_0461_CP_CAMF_PL_v001.mov")));
Assert.Equal(Path.Combine(deliveredDir, "SNV_101_0461_CP_CAMF_PL_v001.mov"), result.Items[0].MovPath);
}
[Fact]
public async Task ClientCodeRenameStillVerifiesAgainstTheValidationTimeChecksum()
{
// Renaming must not change file *content*, so a checksum recorded at
// validation time (against the internal name) has to still match the
// delivered (renamed) files — the hash is content-based, not name-based.
WriteFrames(3);
var manifest = Manifest(copyMode: "always-copy");
manifest.Items[0].DeliveredBaseName = "SNV_101_0461_CP_CAMF_PL_v001";
var first = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(first.Ok);
Directory.Delete(_packageDir, recursive: true);
var replay = Manifest(checksum: first.Items[0].Checksum, copyMode: "always-copy");
replay.Items[0].DeliveredBaseName = "SNV_101_0461_CP_CAMF_PL_v001";
var second = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, replay, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(second.Ok);
}
[Fact]
public async Task UnparseableFrameNumberFallsBackToTheSourceFilename()
{
// A file that doesn't match the render's own numbering convention
// (shouldn't happen for a real render, but must never crash a delivery)
// is delivered under its original name rather than failing the item.
Directory.CreateDirectory(_sourceDir);
File.WriteAllText(Path.Combine(_sourceDir, "SHOT_001_cmp_TT_v001_no_frame_number.exr"), "junk");
var manifest = Manifest(fileCount: 1);
manifest.Items[0].OutputPattern = "SHOT_001_cmp_TT_v001_no_frame_number.exr";
manifest.Items[0].DeliveredBaseName = "SNV_101_0461_CP_CAMF_PL_v001";
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
Assert.True(File.Exists(Path.Combine(_packageDir, "SHOT_001", "SHOT_001_cmp_TT_v001_no_frame_number.exr")));
}
}
@@ -0,0 +1,193 @@
using Microsoft.Extensions.Logging.Abstractions;
using VFXReviewWorker;
using Xunit;
namespace VFXReviewWorker.Tests;
/// <summary>
/// MOV review packages (RenderPipeline2 §11.6). A review folder is opened
/// directly by a producer, so the things pinned here are the ones they would
/// notice: it is flat, it carries the client's own naming, and it contains the
/// MOVs and nothing else.
/// </summary>
public class MovReviewStageTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"vfxr_review_{Guid.NewGuid():N}");
private readonly string _renderDir;
private readonly string _reviewDir;
public MovReviewStageTests()
{
_renderDir = Path.Combine(_root, "renders", "SHOT_001", "v004");
_reviewDir = Path.Combine(_root, "DELIVERY", "PRODUCER_REVIEWS", "20260828_Producer_review");
Directory.CreateDirectory(_renderDir);
}
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch { }
}
private string WriteMov(string shotCode, string version, string contents = "mov bytes")
{
var path = Path.Combine(_renderDir, $"{shotCode}_cmp_TT_{version}.mov");
File.WriteAllText(path, contents);
return path;
}
private DeliveryManifest Manifest(params DeliveryManifestItem[] items) => new()
{
Kind = "MOV_REVIEW",
PackageId = "pkg1",
PackageName = "20260828_Producer_review",
PackageNumber = 7,
Episode = "101",
PackageDir = _reviewDir,
// A review writes no report; the server keeps the record instead.
ReportFile = "",
Items = items.ToList(),
};
private DeliveryManifestItem Item(
string shotCode, string version, string? movPath, string? deliveredBase = null) => new()
{
ItemId = $"item_{shotCode}",
ExportId = $"exp_{shotCode}",
ShotCode = shotCode,
VersionString = version,
SourceDir = "",
OutputPattern = "",
FrameStart = 1001,
FrameEnd = 1050,
DeliveryMovPath = movPath,
// Flat: every item's folder is the package folder itself.
ShotDir = _reviewDir,
DeliveredBaseName = deliveredBase ?? $"{shotCode}_cmp_TT_{version}",
};
private DeliveryStage NewStage() => new(
new WorkerOptions { ServerUrl = "n/a", ApiKey = "n/a" },
new ApiClient(new WorkerOptions { ServerUrl = "http://localhost:1", ApiKey = "x" }, NullLogger<ApiClient>.Instance),
NullLogger<DeliveryStage>.Instance);
[Fact]
public async Task BuildsAFlatFolderOfMovsUnderTheClientFacingName()
{
var mov = WriteMov("SHOT_001", "v004");
var manifest = Manifest(Item("SHOT_001", "v004", mov, deliveredBase: "EP6_VFX_012_v004"));
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
var item = Assert.Single(result.Items);
Assert.Equal("VERIFIED", item.Status);
Assert.Equal(1, item.FileCount);
// No shot subfolder: the MOVs sit beside each other to be scrubbed through.
Assert.Null(item.ExrPath);
Assert.Equal(Path.Combine(_reviewDir, "EP6_VFX_012_v004.mov"), item.MovPath);
Assert.Single(Directory.GetDirectories(_reviewDir).Concat(Directory.GetFiles(_reviewDir)));
}
[Fact]
public async Task LeavesNoReportOrManifestBesideTheMovs()
{
var manifest = Manifest(Item("SHOT_001", "v004", WriteMov("SHOT_001", "v004")));
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
Assert.Null(result.ReportPath);
// What a producer opens is exactly the MOVs — no manifest.json, no CSV.
Assert.False(File.Exists(Path.Combine(_reviewDir, "manifest.json")));
Assert.All(Directory.GetFiles(_reviewDir), f => Assert.EndsWith(".mov", f));
}
[Fact]
public async Task HardLinksSoASeventyShotReviewCostsNoDisk()
{
var mov = WriteMov("SHOT_001", "v004");
var manifest = Manifest(Item("SHOT_001", "v004", mov));
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.Equal("hardlink", result.Items[0].LinkMode);
File.WriteAllText(mov, "rewritten");
Assert.Equal("rewritten", File.ReadAllText(result.Items[0].MovPath!));
}
[Fact]
public async Task AlwaysCopyModeProducesAnIndependentFile()
{
var mov = WriteMov("SHOT_001", "v004");
var manifest = Manifest(Item("SHOT_001", "v004", mov));
manifest.CopyMode = "always-copy";
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
Assert.Equal("copy", result.Items[0].LinkMode);
File.WriteAllText(mov, "rewritten");
Assert.NotEqual("rewritten", File.ReadAllText(result.Items[0].MovPath!));
}
[Fact]
public async Task AMissingMovFailsTheReviewRatherThanShippingItShort()
{
// In an EXR delivery a missing MOV is a missing viewing copy and the
// package continues. In a review the MOV *is* the deliverable.
var manifest = Manifest(Item("SHOT_001", "v004", Path.Combine(_renderDir, "never_rendered.mov")));
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.False(result.Ok);
Assert.Equal("FAILED", result.Items[0].Status);
Assert.Contains("Preview MOV not found", result.Items[0].ErrorMessage!);
}
[Fact]
public async Task AnItemWithNoRecordedMovFails()
{
var manifest = Manifest(Item("SHOT_001", "v004", null));
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.False(result.Ok);
Assert.Contains("No preview MOV", result.Items[0].ErrorMessage!);
}
[Fact]
public async Task HashesEveryFileWhenTheConfigDemandsIt()
{
var manifest = Manifest(Item("SHOT_001", "v004", WriteMov("SHOT_001", "v004")));
manifest.VerifyMode = "always-hash";
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.True(result.Ok);
// A MOV has no validation-time digest of its own, so the one recorded
// here is the one this build computed.
Assert.False(string.IsNullOrWhiteSpace(result.Items[0].Checksum));
}
[Fact]
public async Task OneBadShotFailsThePackageAndTheRestStillReport()
{
var manifest = Manifest(
Item("SHOT_001", "v004", WriteMov("SHOT_001", "v004")),
Item("SHOT_002", "v002", Path.Combine(_renderDir, "absent.mov")));
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
CancellationToken.None, CancellationToken.None);
Assert.False(result.Ok);
Assert.Equal("VERIFIED", result.Items[0].Status);
Assert.Equal("FAILED", result.Items[1].Status);
}
}
@@ -0,0 +1,54 @@
using VFXReviewWorker;
using Xunit;
namespace VFXReviewWorker.Tests;
/// <summary>
/// The preview MP4 opens on the Netflix slate. ffmpeg's <c>thumbnail</c> filter
/// only considers the first 100 frames, so every thumbnail the pipeline has ever
/// produced was a picture of the slate card rather than of the shot — invisible
/// while thumbnails were only decoration in the QC queue, and unacceptable now
/// they can become a shot's thumbnail.
///
/// The fix is to seek past the slate, so the seek arithmetic is worth pinning.
/// </summary>
public class ThumbnailSeekTests
{
private static PreviewBuildResult Build(double? pictureStart, int? frameCount) =>
new() { PictureStartSeconds = pictureStart, FrameCount = frameCount };
[Fact]
public void SeeksAQuarterIntoPictureNotIntoTheFile()
{
// 5s slate, then 96 frames (4s) of picture at 24fps → 5 + 1 = 6s.
var seek = PreviewStage.ThumbnailSeekSeconds(Build(5.0, 96), 24);
Assert.NotNull(seek);
Assert.Equal(6.0, seek!.Value, 3);
}
[Fact]
public void HandlesATemplateWithNoSlateAtAll()
{
var seek = PreviewStage.ThumbnailSeekSeconds(Build(0.0, 240), 24);
Assert.Equal(2.5, seek!.Value, 3);
}
[Fact]
public void FallsBackWhenTheBuildDidNotReportWherePictureStarts()
{
// Older worker, or a template with no SHOT layer: null means "keep the
// old whole-file behaviour" rather than guessing an offset.
Assert.Null(PreviewStage.ThumbnailSeekSeconds(Build(null, 96), 24));
Assert.Null(PreviewStage.ThumbnailSeekSeconds(null, 24));
}
[Theory]
[InlineData(-1.0, 96, 24)] // negative slate length
[InlineData(5.0, 0, 24)] // no picture frames
[InlineData(5.0, -5, 24)] // nonsense frame count
[InlineData(5.0, 96, 0)] // no fps to divide by
public void RefusesNumbersThatDoNotDescribeARealClip(double start, int frames, double fps)
{
Assert.Null(PreviewStage.ThumbnailSeekSeconds(Build(start, frames), fps));
}
}
+165 -14
View File
@@ -11,6 +11,10 @@ namespace VFXReviewWorker;
/// hard-links (or copies) each shot's EXRs and delivery MOV into it, verifies
/// what it wrote, and leaves a manifest + CSV report beside the shots.
///
/// A MOV_REVIEW package (§11.6) runs the same path for a different shape: one
/// flat folder, one preview MOV per shot, and nothing written into it but the
/// MOVs themselves — it is shared with a producer, not filed as a delivery.
///
/// Hard links make an 18-shot EXR package near-instant and cost no extra disk.
/// They are safe here because rendered versions are immutable by pipeline
/// design — a new version is a new directory, nothing ever rewrites an EXR in
@@ -38,9 +42,10 @@ public sealed class DeliveryStage
var manifestFiles = new List<object>();
var alwaysCopy = string.Equals(manifest.CopyMode, "always-copy", StringComparison.OrdinalIgnoreCase);
var alwaysHash = string.Equals(manifest.VerifyMode, "always-hash", StringComparison.OrdinalIgnoreCase);
var isReview = string.Equals(manifest.Kind, "MOV_REVIEW", StringComparison.OrdinalIgnoreCase);
_log.LogInformation("Building delivery package {Name} ({Count} shots) at {Dir}",
manifest.PackageName, manifest.Items.Count, packageDir);
_log.LogInformation("Building {What} {Name} ({Count} shots) at {Dir}",
isReview ? "MOV review" : "delivery package", manifest.PackageName, manifest.Items.Count, packageDir);
Directory.CreateDirectory(packageDir);
for (var i = 0; i < manifest.Items.Count; i++)
@@ -51,7 +56,9 @@ public sealed class DeliveryStage
await _api.ProgressAsync(job.Id, machineId, (double)i / manifest.Items.Count, i, manifest.Items.Count, null,
$"Packaging {item.ShotCode} {item.VersionString} ({i + 1}/{manifest.Items.Count})", shutdown);
var result = BuildItem(item, mapper, alwaysCopy, alwaysHash, manifestFiles);
var result = isReview
? BuildReviewItem(item, mapper, alwaysCopy, alwaysHash, manifestFiles)
: BuildItem(item, mapper, alwaysCopy, alwaysHash, manifestFiles);
results.Add(result);
if (result.Status == "FAILED")
{
@@ -63,15 +70,22 @@ public sealed class DeliveryStage
// The report is the client-facing document, so it is written even for a
// partial build — it is the fastest way to see what did and did not land.
//
// A review folder gets neither: it is opened by a producer who wants the
// MOVs and nothing else. The manifest still travels back to the server,
// so the record of what was shared is kept without cluttering the share.
string? reportPath = null;
try
if (!isReview)
{
reportPath = WriteReport(manifest, results, mapper);
WriteManifestJson(manifest, results, manifestFiles, packageDir);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Could not write delivery report/manifest for {Name}", manifest.PackageName);
try
{
reportPath = WriteReport(manifest, results, mapper);
WriteManifestJson(manifest, results, manifestFiles, packageDir);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Could not write delivery report/manifest for {Name}", manifest.PackageName);
}
}
return new DeliveryResult(ok, results, packageDir, reportPath, manifestFiles);
@@ -109,11 +123,18 @@ public sealed class DeliveryStage
Directory.CreateDirectory(shotDir);
// Delivered names carry the client-facing base (or the studio's own
// convention when no client code is set), not the internal render
// filename — only the frame number and extension survive from the
// source. A frame whose number can't be parsed falls back to the
// source filename verbatim rather than failing the whole delivery.
var destNames = sources.ToDictionary(s => s, s => DeliveredFrameName(s, item, pattern));
long totalBytes = 0;
var usedCopy = false;
foreach (var src in sources)
{
var dest = Path.Combine(shotDir, Path.GetFileName(src));
var dest = Path.Combine(shotDir, destNames[src]);
if (Place(src, dest, alwaysCopy, out var copied) is string placeError)
{
return DeliveryItemResult.Failed(item, placeError);
@@ -134,7 +155,7 @@ public sealed class DeliveryStage
if (usedCopy || alwaysHash)
{
digest = SequenceChecksum(sources.Select(s => Path.Combine(shotDir, Path.GetFileName(s))));
digest = SequenceChecksum(sources.Select(s => Path.Combine(shotDir, destNames[s])));
if (item.Checksum is { Length: > 0 } && !string.Equals(digest, item.Checksum, StringComparison.OrdinalIgnoreCase))
{
return DeliveryItemResult.Failed(item,
@@ -174,7 +195,10 @@ public sealed class DeliveryStage
var movSrc = mapper.Map(item.DeliveryMovPath!);
if (File.Exists(movSrc))
{
movDest = Path.Combine(shotDir, Path.GetFileName(movSrc));
var movName = string.IsNullOrWhiteSpace(item.DeliveredBaseName)
? Path.GetFileName(movSrc)
: item.DeliveredBaseName + Path.GetExtension(movSrc);
movDest = Path.Combine(shotDir, movName);
if (Place(movSrc, movDest, alwaysCopy, out var movCopied) is string movError)
{
return DeliveryItemResult.Failed(item, movError);
@@ -192,7 +216,7 @@ public sealed class DeliveryStage
foreach (var src in sources)
{
var name = Path.GetFileName(src);
var name = destNames[src];
manifestFiles.Add(new
{
shotCode = item.ShotCode,
@@ -224,6 +248,108 @@ public sealed class DeliveryStage
}
}
/// <summary>
/// One shot of a MOV review package: place its preview MOV straight into
/// the (flat) review folder under the client-facing name.
///
/// A missing MOV is fatal here, unlike in an EXR delivery where the MOV is
/// a viewing copy beside the real deliverable — in a review it *is* the
/// deliverable, and a review folder quietly one shot short is worse than
/// one that says so.
/// </summary>
private DeliveryItemResult BuildReviewItem(
DeliveryManifestItem item, PathMapper mapper, bool alwaysCopy, bool alwaysHash, List<object> manifestFiles)
{
try
{
if (string.IsNullOrWhiteSpace(item.DeliveryMovPath))
{
return DeliveryItemResult.Failed(item, "No preview MOV is recorded for this version");
}
var movSrc = mapper.Map(item.DeliveryMovPath!);
if (!File.Exists(movSrc))
{
return DeliveryItemResult.Failed(item, $"Preview MOV not found: {movSrc}");
}
// ShotDir is the package folder itself for a review — the MOVs sit
// beside each other so a producer can scrub through them in order.
var reviewDir = mapper.Map(item.ShotDir);
Directory.CreateDirectory(reviewDir);
var name = string.IsNullOrWhiteSpace(item.DeliveredBaseName)
? Path.GetFileName(movSrc)
: item.DeliveredBaseName + Path.GetExtension(movSrc);
var dest = Path.Combine(reviewDir, name);
if (Place(movSrc, dest, alwaysCopy, out var copied) is string error)
{
return DeliveryItemResult.Failed(item, error);
}
var sourceLength = new FileInfo(movSrc).Length;
var destLength = new FileInfo(dest).Length;
// There is no validation-time digest for a MOV to check against, so
// a copy is proved against the source it came from: length always
// (it catches the truncation a full disk causes, for free), and the
// full hash when the config asks for it. A hard link is the source.
string? digest = null;
if (copied)
{
if (destLength != sourceLength)
{
return DeliveryItemResult.Failed(item,
$"Copied MOV is {destLength} bytes but the source is {sourceLength} — the copy is incomplete");
}
if (alwaysHash)
{
digest = XxHash64.HashFile(dest);
var sourceDigest = XxHash64.HashFile(movSrc);
if (!string.Equals(digest, sourceDigest, StringComparison.OrdinalIgnoreCase))
{
return DeliveryItemResult.Failed(item,
$"Copied MOV does not match its source: expected {sourceDigest}, got {digest}");
}
}
}
else if (alwaysHash)
{
digest = XxHash64.HashFile(dest);
}
manifestFiles.Add(new
{
shotCode = item.ShotCode,
relativePath = name,
bytes = destLength,
exportId = item.ExportId,
});
return new DeliveryItemResult
{
ItemId = item.ItemId,
ShotCode = item.ShotCode,
VersionString = item.VersionString,
Status = "VERIFIED",
// No EXR sequence is involved, so there is no shot folder to record.
ExrPath = null,
MovPath = dest,
FileCount = 1,
TotalBytes = destLength,
Checksum = digest,
LinkMode = copied ? "copy" : "hardlink",
FrameStart = item.FrameStart,
FrameEnd = item.FrameEnd,
};
}
catch (Exception ex)
{
return DeliveryItemResult.Failed(item, $"{ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>
/// Hard-link when possible, copy when not. Returns null on success or the
/// error message. `copied` reports which happened, so the package records
@@ -252,6 +378,31 @@ public sealed class DeliveryStage
}
}
/// <summary>
/// The delivered filename for one source frame: DeliveredBaseName with the
/// frame number (re-padded to the render's own convention) and extension —
/// never the internal render filename it was copied from. Falls back to
/// the source filename verbatim (never fatal) when there's no client-facing
/// base to use, or the frame number can't be parsed out of the source name.
/// </summary>
internal string DeliveredFrameName(string src, DeliveryManifestItem item, SequencePattern pattern)
{
var sourceName = Path.GetFileName(src);
if (string.IsNullOrWhiteSpace(item.DeliveredBaseName))
{
return sourceName;
}
var frame = pattern.FrameNumberOf(sourceName);
if (frame is null)
{
_log.LogWarning("Could not parse a frame number out of {Name} for {Shot} — delivering under its original name",
sourceName, item.ShotCode);
return sourceName;
}
var padding = Math.Max(1, pattern.Padding);
return $"{item.DeliveredBaseName}.{frame.Value.ToString().PadLeft(padding, '0')}{pattern.Extension}";
}
private static string SequenceChecksum(IEnumerable<string> files)
{
var state = new XxHash64.State(0);
+26
View File
@@ -100,6 +100,12 @@ public sealed class BlenderManifest
public sealed class DeliveryManifest
{
public string Stage { get; set; } = "DELIVERY";
/// <summary>
/// "EXR_DELIVERY" builds the per-shot folders of EXRs + MOVs; "MOV_REVIEW"
/// builds a flat folder of preview MOVs for a formal review (§11.6). One
/// job type and one claim path either way — only what lands on disk differs.
/// </summary>
public string Kind { get; set; } = "EXR_DELIVERY";
public string PackageId { get; set; } = "";
public string PackageName { get; set; } = "";
public int PackageNumber { get; set; }
@@ -129,8 +135,22 @@ public sealed class DeliveryManifestItem
public string? Checksum { get; set; }
public string? DeliveryMovPath { get; set; }
public string ShotDir { get; set; } = "";
/// <summary>
/// Server-computed: "{clientCode}_{versionString}" when the shot has a
/// client naming code, else the studio's own "{shotCode}_cmp_TT_{versionString}".
/// The delivered EXR sequence and MOV are named from this, not the
/// internal render filename they're copied from.
/// </summary>
public string DeliveredBaseName { get; set; } = "";
/// <summary>When this export's validation ran — lets a linked package detect a source changed since QC.</summary>
public DateTimeOffset? ValidatedAt { get; set; }
/// <summary>
/// True on a MOV_REVIEW item: there is no EXR sequence, so SourceDir,
/// OutputPattern, FileCount and Checksum are empty and DeliveryMovPath is
/// the whole deliverable.
/// </summary>
public bool IsMovOnly => string.IsNullOrWhiteSpace(SourceDir);
}
/// <summary>PREVIEW_ONLY manifest (server-built, RenderPipeline2 §9).</summary>
@@ -186,6 +206,12 @@ public sealed class PreviewBuildResult
public int? FrameCount { get; set; }
public int? Width { get; set; }
public int? Height { get; set; }
/// <summary>
/// Seconds of slate ahead of picture in the preview comp (the SHOT layer's
/// in-point). Null on builds predating this field, or when the template has
/// no SHOT layer — the thumbnail then falls back to scanning from frame 0.
/// </summary>
public double? PictureStartSeconds { get; set; }
}
/// <summary>The Render Manifest (§6.2) — the fields the render and validation stages need; the rest is preserved raw.</summary>
+168 -11
View File
@@ -179,7 +179,7 @@ public sealed class PreviewStage
null, null, null, build.TempAep, build, sw.Elapsed.TotalSeconds);
}
var thumbnail = await TryMakeThumbnailAsync(job.Id, mp4Local, shutdown);
var thumbnail = await TryMakeThumbnailAsync(job.Id, mp4Local, build, manifest.Fps, shutdown);
sw.Stop();
_log.LogInformation("Preview complete for job {JobId} in {Sec:F0}s (mov + mp4{Thumb})",
@@ -231,14 +231,96 @@ public sealed class PreviewStage
return process.ExitCode;
}
/// <summary>Optional 960-wide poster frame at 25% duration (§9.1). Never fatal.</summary>
private async Task<string?> TryMakeThumbnailAsync(string jobId, string mp4Path, CancellationToken ct)
/// <summary>
/// Optional 960-wide poster frame at 25% of <em>picture</em> duration
/// (§9.1). Never fatal.
/// </summary>
/// <remarks>
/// The preview MP4 opens on the Netflix slate, so the frame has to be taken
/// relative to picture rather than to the file. This previously used
/// ffmpeg's <c>thumbnail</c> filter, which considers only the first 100
/// frames — on a slated preview that is the slate card, which is what every
/// thumbnail in the system was until now. Seeking to
/// <c>pictureStart + 25%</c> matches what §9.1 always documented and is what
/// makes these frames usable as shot thumbnails.
///
/// A build that reports no picture start (older worker, or a template with
/// no SHOT layer) keeps the old whole-file behaviour rather than guessing.
/// </remarks>
private async Task<string?> TryMakeThumbnailAsync(
string jobId, string mp4Path, PreviewBuildResult? build, double fps, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(_options.FfmpegPath) || !File.Exists(_options.FfmpegPath))
if (string.IsNullOrWhiteSpace(_options.FfmpegPath))
{
_log.LogWarning(
"No thumbnail for job {JobId}: ffmpegPath is not set in config.json. " +
"Thumbnails are skipped, and shots cannot take a frame from this render.",
jobId);
return null;
}
if (!File.Exists(_options.FfmpegPath))
{
_log.LogWarning(
"No thumbnail for job {JobId}: ffmpegPath points at {Path}, which does not exist.",
jobId, _options.FfmpegPath);
return null;
}
var outPath = Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_thumb.jpg");
var seek = ThumbnailSeekSeconds(build, fps);
if (seek is { } t)
{
_log.LogInformation(
"Thumbnail for job {JobId}: seeking to {Seek:F2}s (slate {Start:F2}s + 25% of {Frames} frames @ {Fps}fps)",
jobId, t, build!.PictureStartSeconds, build.FrameCount, fps);
var attempt = await RunFfmpegThumbnailAsync(jobId, mp4Path, outPath, t, ct);
if (attempt == ThumbAttempt.Wrote) return outPath;
// A hung or unstartable ffmpeg will hang the same way a second
// time, and each attempt costs the full two-minute cap.
if (attempt == ThumbAttempt.Broken) return null;
// The seek is derived from what the AE build reported; if those
// numbers disagree with the rendered file, ffmpeg lands past the
// end and writes nothing. Falling back to the whole-file scan means
// a wrong seek costs picture content, never the thumbnail itself.
_log.LogWarning(
"Thumbnail seek to {Seek:F2}s produced nothing for job {JobId} — retrying across the whole file. " +
"The frame will likely be the slate.", t, jobId);
}
else
{
_log.LogInformation(
"Thumbnail for job {JobId}: build reported no picture start, scanning the whole file " +
"(the frame will likely be the slate).", jobId);
}
if (await RunFfmpegThumbnailAsync(jobId, mp4Path, outPath, null, ct) == ThumbAttempt.Wrote) return outPath;
_log.LogWarning("No thumbnail produced for job {JobId} — see the ffmpeg output above.", jobId);
return null;
}
/// <summary>How one ffmpeg attempt ended.</summary>
private enum ThumbAttempt
{
/// <summary>A thumbnail was written.</summary>
Wrote,
/// <summary>ffmpeg ran and wrote nothing — a different attempt may work.</summary>
NoOutput,
/// <summary>ffmpeg hung or could not start — retrying costs minutes and fixes nothing.</summary>
Broken,
}
/// <summary>
/// One ffmpeg invocation. <paramref name="seekSeconds"/> null means the old
/// whole-file <c>thumbnail</c> filter. Logs ffmpeg's own diagnosis when no
/// file is produced.
/// </summary>
private async Task<ThumbAttempt> RunFfmpegThumbnailAsync(
string jobId, string mp4Path, string outPath, double? seekSeconds, CancellationToken ct)
{
TryDelete(outPath);
var psi = new ProcessStartInfo
@@ -249,27 +331,102 @@ public sealed class PreviewStage
UseShellExecute = false,
CreateNoWindow = true,
};
foreach (var a in new[] { "-y", "-i", mp4Path, "-vf", "thumbnail,scale=960:-1", "-frames:v", "1", outPath })
var args = new List<string> { "-y" };
if (seekSeconds is { } t)
{
psi.ArgumentList.Add(a);
// Before -i: ffmpeg seeks by keyframe, which is fast and accurate
// enough for a poster frame.
args.Add("-ss");
args.Add(t.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture));
args.Add("-i");
args.Add(mp4Path);
args.Add("-vf");
args.Add("scale=960:-1");
}
else
{
args.Add("-i");
args.Add(mp4Path);
args.Add("-vf");
args.Add("thumbnail,scale=960:-1");
}
args.Add("-frames:v");
args.Add("1");
args.Add(outPath);
foreach (var a in args) psi.ArgumentList.Add(a);
try
{
using var process = Process.Start(psi);
if (process is null) return null;
if (process is null)
{
_log.LogWarning("Could not start ffmpeg at {Path} for job {JobId}", _options.FfmpegPath, jobId);
return ThumbAttempt.Broken;
}
// Drain BOTH pipes while the process runs. Windows gives an
// anonymous pipe a ~4 KB buffer; ffmpeg's banner and stream summary
// exceed that on their own, so a redirected-but-unread pipe fills,
// ffmpeg blocks forever on the write, and the wait below times out
// with the process still alive. That is a deadlock, not a slow
// encode, and it is why this step failed with nothing but a
// cancellation to show for it.
var stderrTask = process.StandardError.ReadToEndAsync();
var stdoutTask = process.StandardOutput.ReadToEndAsync();
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromMinutes(2));
await process.WaitForExitAsync(timeout.Token);
return File.Exists(outPath) ? outPath : null;
try
{
await process.WaitForExitAsync(timeout.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
// Our own 2-minute cap, not a shutdown: leaving ffmpeg running
// would hold the scratch file open and leak a process per job.
_log.LogWarning(
"ffmpeg timed out after 2 minutes for job {JobId} — killing it. Command: {Args}",
jobId, string.Join(" ", args));
try { process.Kill(entireProcessTree: true); } catch { }
return ThumbAttempt.Broken;
}
var stderr = await stderrTask;
await stdoutTask;
if (File.Exists(outPath) && new FileInfo(outPath).Length > 0) return ThumbAttempt.Wrote;
_log.LogWarning(
"ffmpeg wrote no thumbnail for job {JobId} (exit {Exit}). Command: {Args} -- ffmpeg said: {Stderr}",
jobId, process.ExitCode, string.Join(" ", args), Tail(stderr, 1200));
return ThumbAttempt.NoOutput;
}
catch (Exception ex)
{
_log.LogWarning(ex, "Thumbnail generation failed (non-fatal)");
return null;
_log.LogWarning(ex, "Thumbnail generation failed for job {JobId} (non-fatal)", jobId);
return ThumbAttempt.Broken;
}
}
/// <summary>Last <paramref name="max"/> characters — ffmpeg puts the error at the end.</summary>
private static string Tail(string? text, int max) =>
string.IsNullOrEmpty(text) ? "(no output)"
: text.Length <= max ? text
: text[^max..];
/// <summary>
/// Timestamp for the poster frame: a quarter of the way into picture,
/// skipping the slate. Null when the build did not report where picture
/// starts, or when the numbers do not describe a real clip.
/// </summary>
internal static double? ThumbnailSeekSeconds(PreviewBuildResult? build, double fps)
{
if (build?.PictureStartSeconds is not { } start || start < 0) return null;
if (build.FrameCount is not { } frames || frames <= 0) return null;
if (fps <= 0) return null;
return start + (frames / fps) * 0.25;
}
private static PreviewStageResult Fail(string message, bool retryable, Stopwatch sw, PreviewBuildResult? build = null)
{
sw.Stop();
@@ -15,7 +15,7 @@
every change that gets published. publish.ps1 appends the git SHA via
SourceRevisionId, giving "1.1.0+feb1c7b".
-->
<Version>1.5.1</Version>
<Version>1.6.0</Version>
</PropertyGroup>
<ItemGroup>
+7 -1
View File
@@ -30,7 +30,11 @@
queued: [],
frameCount: null,
width: null,
height: null
height: null,
// Seconds of slate ahead of picture in the preview comp — the SHOT
// layer's in-point. The worker needs it to grab a thumbnail from
// picture rather than from the slate card.
pictureStartSeconds: null
};
var resultPath = null;
@@ -512,6 +516,8 @@
var shotLayer = previewComp.layer("SHOT");
var targetOutPoint = shotLayer.inPoint + shotComp.duration;
// Everything before this is slate; the thumbnail has to start after it.
result.pictureStartSeconds = shotLayer.inPoint;
if (targetOutPoint > previewComp.duration) {
previewComp.duration = targetOutPoint;
}
+301 -18
View File
@@ -32,7 +32,7 @@ var SETTINGS_KEY = "cfg";
// Bump on every change deployed to a workstation. The panel reports this to
// the server on load, so Pipeline → Machines shows which version each machine
// is actually running and flags the ones left behind.
var PANEL_VERSION = "2.5.0";
var PANEL_VERSION = "2.6.2";
(function VFXReviewConnector(thisObj) {
var uiState = {
@@ -65,7 +65,6 @@ var PANEL_VERSION = "2.5.0";
var pipelineState = {
pollShotCode: null,
pollTaskId: 0,
prefilledShotCode: null
};
@@ -958,17 +957,29 @@ var PANEL_VERSION = "2.5.0";
}
}
// Assigning displayStartFrame on a version of AE that does not have the
// property is ignored silently rather than throwing, which is one of the
// ways a comp ends up back at 00:00:00:00. Read the value back and fall
// through to displayStartTime when it did not take, and tell the caller
// whether anything stuck.
function setCompStartFrame(comp, frameNumber) {
var wanted = Math.round(frameNumber);
try {
comp.displayStartFrame = frameNumber;
return;
if (Math.round(comp.displayStartFrame) === wanted) {
return true;
}
} catch (frameError) {
}
try {
comp.displayStartTime = frameNumber / comp.frameRate;
return Math.round(comp.displayStartTime * comp.frameRate) === wanted;
} catch (timeError) {
}
return false;
}
function deselectAllProjectItems() {
@@ -1051,13 +1062,220 @@ var PANEL_VERSION = "2.5.0";
return frames;
}
// The plate's own start timecode: AE metadata when we can read it,
// otherwise the API's source clip timecode less the handle frames — the
// same convention the Set Start Timecode button uses.
// The first file of an imported sequence: the frame whose header carries the
// plate's start timecode. importEXRSequence sorts before importing, so this
// is the sequence's first frame and not an arbitrary one.
function getFootageFirstFile(footageItem) {
try {
if (footageItem && footageItem.mainSource && footageItem.mainSource.file) {
return footageItem.mainSource.file;
}
} catch (fileError) {
}
return null;
}
function readUInt32LE(buf, offset) {
return (buf.charCodeAt(offset) & 0xFF) +
(buf.charCodeAt(offset + 1) & 0xFF) * 256 +
(buf.charCodeAt(offset + 2) & 0xFF) * 65536 +
(buf.charCodeAt(offset + 3) & 0xFF) * 16777216;
}
function readInt32LE(buf, offset) {
var value = readUInt32LE(buf, offset);
return value >= 2147483648 ? value - 4294967296 : value;
}
// A null-terminated header string. Returns null when the terminator is not
// found within a sane distance, which means the bytes are not a header we
// understand and parsing should stop rather than guess.
function readExrString(buf, offset) {
var end = offset;
var limit = Math.min(buf.length, offset + 256);
while (end < limit && buf.charCodeAt(end) !== 0) {
end += 1;
}
if (end >= limit) {
return null;
}
return buf.substring(offset, end);
}
function pad2(value) {
return (value < 10 ? "0" : "") + value;
}
function makeTimecode(hours, minutes, seconds, frames, dropFrame) {
if (hours > 23 || minutes > 59 || seconds > 59) {
return null;
}
return {
hours: hours,
minutes: minutes,
seconds: seconds,
frames: frames,
dropFrame: dropFrame,
text: pad2(hours) + ":" + pad2(minutes) + ":" + pad2(seconds) +
(dropFrame ? ";" : ":") + pad2(frames)
};
}
// SMPTE 12M as stored in the EXR timeCode attribute: BCD-packed, which is
// why the raw value reads back as its own hex digits (0x18585712 is
// 18:58:57:12). Every field sits inside a single byte, so the nibbles can be
// picked off per byte and never touch the sign bit.
function decodePackedTimecode(buf, offset) {
var b0 = buf.charCodeAt(offset) & 0xFF; // frames, drop-frame flag
var b1 = buf.charCodeAt(offset + 1) & 0xFF; // seconds
var b2 = buf.charCodeAt(offset + 2) & 0xFF; // minutes
var b3 = buf.charCodeAt(offset + 3) & 0xFF; // hours
return makeTimecode(
(b3 & 0x0F) + ((b3 >> 4) & 0x03) * 10,
(b2 & 0x0F) + ((b2 >> 4) & 0x07) * 10,
(b1 & 0x0F) + ((b1 >> 4) & 0x07) * 10,
(b0 & 0x0F) + ((b0 >> 4) & 0x03) * 10,
((b0 >> 6) & 0x01) === 1);
}
function parseTimecodeText(text) {
var parts = String(text).split(/[:;]/);
if (parts.length < 4) {
return null;
}
return makeTimecode(
parseInt(parts[0], 10) || 0,
parseInt(parts[1], 10) || 0,
parseInt(parts[2], 10) || 0,
parseInt(parts[3], 10) || 0,
String(text).indexOf(";") !== -1);
}
// Reads the plate's timecode straight out of the OpenEXR header, the way the
// worker's ExrHeader.cs does, so the panel anchors comps on exactly the
// value validation later checks them against. Header layout is
// magic(4) version(4) then attributes as `name\0 type\0 int32 size data`,
// terminated by an empty name — one short read, no pixel decode.
//
// Returns null when the file is unreadable or carries no timecode at all.
function readExrTimecode(file) {
var EXR_HEADER_BYTES = 65536;
var EXR_MAGIC = 20000630;
var buf = null;
var opened = false;
var pos = 8;
var packed = null;
var text = null;
var name;
var type;
var size;
if (!file || !file.exists) {
return null;
}
try {
file.encoding = "BINARY";
opened = file.open("r");
if (opened) {
buf = file.read(EXR_HEADER_BYTES);
}
} catch (readError) {
buf = null;
}
try {
if (opened) {
file.close();
}
} catch (closeError) {
}
if (!buf || buf.length < 16 || readUInt32LE(buf, 0) !== EXR_MAGIC) {
return null;
}
while (pos < buf.length) {
name = readExrString(buf, pos);
if (name === null) {
break;
}
pos += name.length + 1;
if (name.length === 0) {
break; // an empty name ends the header
}
type = readExrString(buf, pos);
if (type === null) {
break;
}
pos += type.length + 1;
if (pos + 4 > buf.length) {
break;
}
size = readInt32LE(buf, pos);
pos += 4;
if (size < 0 || pos + size > buf.length) {
break;
}
if (name === "timeCode" && size >= 8) {
packed = decodePackedTimecode(buf, pos);
} else if (name === "timeCodeString" && size >= 11) {
text = parseTimecodeText(buf.substr(pos, size).replace(/\0+$/, ""));
}
pos += size;
}
// The packed attribute is the authoritative one; timeCodeString is a
// convenience copy that some writers emit and others omit.
return packed || text;
}
// Non-drop frame count, mirroring Timecode.ToFrames in the worker. The show
// rate is the authority — a plate's own rate is whatever happens to be on
// disk, and plates are conformed to the show rate on import.
function timecodeToFrames(tc, fps) {
var rate = Math.round(resolveFps(fps));
return ((tc.hours * 60 + tc.minutes) * 60 + tc.seconds) * rate + tc.frames;
}
// The plate's own start timecode, ranked the way validation ranks it
// (RenderPipeline2 §8.1a): the EXR header's embedded timecode first, then
// AE's own read of the footage metadata, and only then the API's source clip
// timecode less the handle frames — the convention the Set Start Timecode
// button uses. The API value is the editorial in-point and sits a
// handle-length ahead of the plate by design, so it is the last resort
// rather than the first.
function getFootageStartFrames(footageItem, apiShot, fps) {
var probed = probeFootageStartFrames(footageItem, fps);
var exrTc = readExrTimecode(getFootageFirstFile(footageItem));
var probed;
var frames;
if (exrTc) {
frames = timecodeToFrames(exrTc, fps);
if (frames > 0) {
return {
frames: frames,
source: "EXR timecode " + exrTc.text +
(exrTc.dropFrame ? " (drop-frame flag set on the plate)" : "")
};
}
}
probed = probeFootageStartFrames(footageItem, fps);
if (probed !== null && probed > 0) {
return { frames: probed, source: "footage metadata" };
}
@@ -1069,7 +1287,10 @@ var PANEL_VERSION = "2.5.0";
}
}
return { frames: 0, source: probed === 0 ? "footage starts at 00:00:00:00" : "no timecode found" };
return {
frames: 0,
source: (exrTc || probed === 0) ? "the plate starts at 00:00:00:00" : "no timecode found"
};
}
function findComp(name) {
@@ -1914,7 +2135,9 @@ var PANEL_VERSION = "2.5.0";
diagLog("start frame " + startInfo.frames + " from " + startInfo.source);
footageComp = app.project.items.addComp(shotCode + "_FOOTAGE", width, height, 1, maxDuration, fps);
setCompStartFrame(footageComp, startInfo.frames);
if (!setCompStartFrame(footageComp, startInfo.frames)) {
diagLog("could not set the start frame on " + footageComp.name + " - it will read 00:00:00:00");
}
if (precompFolder) {
footageComp.parentFolder = precompFolder;
}
@@ -1925,7 +2148,9 @@ var PANEL_VERSION = "2.5.0";
}
shotComp = app.project.items.addComp(shotCode, width, height, 1, maxDuration, fps);
setCompStartFrame(shotComp, startInfo.frames);
if (!setCompStartFrame(shotComp, startInfo.frames)) {
diagLog("could not set the start frame on " + shotComp.name + " - it will read 00:00:00:00");
}
if (episodeProjectFolder) {
shotComp.parentFolder = episodeProjectFolder;
} else {
@@ -3636,13 +3861,34 @@ var PANEL_VERSION = "2.5.0";
}
}
// A scheduled task outlives the panel instance that armed it. Held only in
// this closure, the id of a repeating task goes with the instance when the
// panel is closed or reloaded, and nothing can cancel it again: it fires
// every 15 s for the rest of the AE session, and every tick that lands
// while a modal dialog is open raises "Cannot run a script while a modal
// dialog is waiting for response." The id therefore lives beside the tick
// in global scope, where the next instance can still reach it.
var POLL_TASK_ID_KEY = "__vfxrExportPollTaskId";
function getPollTaskId() {
var taskId = $.global[POLL_TASK_ID_KEY];
return (typeof taskId === "number" && taskId > 0) ? taskId : 0;
}
function setPollTaskId(taskId) {
$.global[POLL_TASK_ID_KEY] = taskId || 0;
}
function stopExportPolling() {
if (pipelineState.pollTaskId) {
var taskId = getPollTaskId();
if (taskId) {
try {
app.cancelTask(pipelineState.pollTaskId);
app.cancelTask(taskId);
} catch (cancelError) {
}
pipelineState.pollTaskId = 0;
setPollTaskId(0);
}
pipelineState.pollShotCode = null;
}
@@ -3676,9 +3922,9 @@ var PANEL_VERSION = "2.5.0";
stopExportPolling();
pipelineState.pollShotCode = shotCode;
try {
pipelineState.pollTaskId = app.scheduleTask("__vfxrExportPollTick()", 15000, true);
setPollTaskId(app.scheduleTask("__vfxrExportPollTick()", 15000, true));
} catch (scheduleError) {
pipelineState.pollTaskId = 0;
setPollTaskId(0);
}
}
@@ -4002,6 +4248,25 @@ var PANEL_VERSION = "2.5.0";
return;
}
// The rendered EXRs must be clean, linear and free of burn-in — the
// show LUT and overlay are reference-only, for the artist's own
// viewing while compositing. The legacy manual "Queue EXR" button has
// always disabled them before rendering (see queueEXR()); Queue Export
// does the same here so the pipeline's EXR output matches.
app.beginUndoGroup("VFXReview Connector - Queue Export (disable LUT/overlay)");
try {
for (i = 0; i < comps.length; i += 1) {
comp = getMainCompForSelection(comps[i]);
if (!comp) {
continue;
}
disableLayerByName(comp, getOverlayCompName());
disableLayerByName(comp, getLutCompName());
}
} finally {
app.endUndoGroup();
}
// The worker renders the saved file; unsaved changes would silently
// render stale comps.
try {
@@ -4155,8 +4420,13 @@ var PANEL_VERSION = "2.5.0";
// catching mask slips, export glitches and metadata faults at full res, so
// selecting a queue entry imports the real sequence.
// The queue endpoint defaults to 50 rows and refuses anything above 200, so
// ask for the ceiling: a busy project can have well over 50 exports sitting
// in READY_FOR_QC, and the panel silently showed only the oldest 50.
var QC_QUEUE_LIMIT = 200;
function loadQCQueue() {
var url = CONFIG.baseUrl + "/api/ext/qc/queue";
var url = CONFIG.baseUrl + "/api/ext/qc/queue?limit=" + QC_QUEUE_LIMIT;
var data;
var entries;
var i;
@@ -4167,7 +4437,7 @@ var PANEL_VERSION = "2.5.0";
return;
}
if (CURRENT_PROJECT) {
url += "?projectCode=" + encodeURIComponent(CURRENT_PROJECT.code);
url += "&projectCode=" + encodeURIComponent(CURRENT_PROJECT.code);
}
setQCStatus("Loading QC queue...");
@@ -4192,7 +4462,8 @@ var PANEL_VERSION = "2.5.0";
if (entries.length) {
uiState.qcList.selection = 0;
setQCStatus(entries.length + " export(s) awaiting QC");
setQCStatus(entries.length + " export(s) awaiting QC" +
(entries.length >= QC_QUEUE_LIMIT ? " (list is capped — QC some and reload)" : ""));
} else {
setQCStatus("Nothing waiting for QC");
}
@@ -4778,6 +5049,11 @@ var PANEL_VERSION = "2.5.0";
return win;
}
// A previous instance may have left a repeating poll armed, and its shot
// code went with that closure. Cancel it before the tick is pointed at this
// instance, rather than letting it fire into a fresh, empty state.
stopExportPolling();
// app.scheduleTask evaluates in global scope — expose the poll tick there
$.global.__vfxrExportPollTick = pollExportTick;
@@ -4788,6 +5064,13 @@ var PANEL_VERSION = "2.5.0";
diagLog("panel v" + PANEL_VERSION + " loaded on " + getHostName());
reportPanelVersion();
// Closing the panel leaves an armed task running with no UI left to update.
// The export itself is unaffected: it runs on the farm, and the panel picks
// its status back up from the server on the next Refresh.
panel.onClose = function () {
stopExportPolling();
};
if (panel instanceof Window) {
panel.center();
panel.show();
+25 -4
View File
@@ -201,16 +201,37 @@ Constructs a full shot composite in the open AE project from the episode and sho
**Process:**
1. Calls the shot lookup API to retrieve metadata (description, notes, episode, scene, etc.).
2. If a comp with the shot code already exists, updates its overlay instead of rebuilding.
3. Scans `FOOTAGE_ROOT/{episodeCode}/` for subfolders matching `{shotCode}_*` and imports each as an EXR image sequence at 24 fps.
3. Scans `FOOTAGE_ROOT/{episodeCode}/` for subfolders matching `{shotCode}_*` and imports each as an EXR image sequence, conformed to the shot's frame rate.
4. Creates a `{shotCode}_FOOTAGE` precomp containing all imported sequences, each with an OCIO Color Space Transform effect added (disabled by default).
5. Creates the main `{shotCode}` comp and places the footage precomp inside it.
6. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
7. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
8. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
6. Anchors both comps on the plate's start timecode — see [Start timecode](#start-timecode).
7. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
8. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
9. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
If any step fails, the status line names the stage and a copyable report opens —
see [Diagnostics and logging](#diagnostics-and-logging).
#### Start timecode
Neither comp starts at `00:00:00:00`. Both are anchored on the plate's own start
timecode, taken from the first source that has one:
| Rank | Source | Notes |
|---|---|---|
| 1 | The first EXR's header | The `timeCode` attribute, or `timeCodeString` where the packed one is absent. Read straight off disk — no pixel decode, and no dependency on what AE chose to expose. |
| 2 | AE's footage metadata | What "New Comp from Selection" would have inherited. |
| 3 | API `timecodeStart` less `handleFrames` | The convention **Set Start Timecode** uses. Last resort: the API stores the *editorial* in-point, which is a handle-length ahead of the plate by design. |
This is the same ranking the render worker's validation uses (RenderPipeline2
§8.1a), so a comp is anchored on exactly the value its EXRs are later checked
against — a shot built from rank 3 and validated against rank 1 is how a
timecode desync gets into a delivery.
The status line and the diagnostics log both name the rank that was used, e.g.
`start frame 864108 from EXR timecode 10:00:04:12`. A plate carrying no timecode
in any rank leaves the comp at `00:00:00:00` and says so.
---
## Render Pipeline
+82 -72
View File
@@ -5,7 +5,7 @@ import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { ApprovalStatus } from "@prisma/client";
import { recalcShotStatus } from "@/lib/shot-status";
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
import { notifyApprovalChange } from "@/lib/notifications";
import { slackNotifyApproval } from "@/lib/slack";
import { versionLabel } from "@/lib/utils";
@@ -29,57 +29,62 @@ export async function submitApproval(data: z.infer<typeof approvalSchema>) {
throw new Error("Insufficient permissions to review versions");
}
// Create the approval record
const approval = await db.approval.create({
data: {
versionId: parsed.versionId,
userId: session.user.id,
status: parsed.status,
notes: parsed.notes,
},
});
// The verdict, the version, the task and the derived shot status are one
// decision and are written as one: a failure partway through used to leave the
// three layers disagreeing, with no way to tell which one was right.
const { approval, version } = await db.$transaction(async (tx) => {
const approval = await tx.approval.create({
data: {
versionId: parsed.versionId,
userId: session.user.id,
status: parsed.status,
notes: parsed.notes,
},
});
// Update version approval status
await db.version.update({
where: { id: parsed.versionId },
data: { approvalStatus: parsed.status },
});
await tx.version.update({
where: { id: parsed.versionId },
data: { approvalStatus: parsed.status },
});
// Load version + task + shot + project for downstream effects
const version = await db.version.findUnique({
where: { id: parsed.versionId },
include: {
task: {
include: {
shot: true,
project: true,
// Load version + task + shot + project for downstream effects
const version = await tx.version.findUnique({
where: { id: parsed.versionId },
include: {
task: {
include: {
shot: true,
project: true,
},
},
},
},
});
if (!version) throw new Error("Version not found");
// Update task status based on approval result
if (version.task && parsed.status !== "PENDING_REVIEW") {
if (parsed.status === "APPROVED") {
await tx.task.update({
where: { id: version.task.id },
data: { status: "DONE" },
});
} else if (parsed.status === "REJECTED" || parsed.status === "NEEDS_CHANGES") {
await tx.task.update({
where: { id: version.task.id },
data: { status: "CHANGES" },
});
}
// Recalculate shot status from updated task states
if (version.task.shot) {
await recalcShotStatus(version.task.shot.id, tx);
}
}
return { approval, version };
});
if (!version) throw new Error("Version not found");
// Update task status based on approval result
if (version.task && parsed.status !== "PENDING_REVIEW") {
if (parsed.status === "APPROVED") {
await db.task.update({
where: { id: version.task.id },
data: { status: "DONE" },
});
} else if (parsed.status === "REJECTED" || parsed.status === "NEEDS_CHANGES") {
await db.task.update({
where: { id: version.task.id },
data: { status: "CHANGES" },
});
}
// Recalculate shot status from updated task states
if (version.task.shot) {
await recalcShotStatus(version.task.shot.id).catch(() => {});
}
}
// Notifications
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
const reviewerName = reviewer?.name ?? "Reviewer";
@@ -166,34 +171,39 @@ export async function unapproveVersion(versionId: string) {
throw new Error("Only approved versions can be unapproved");
}
// Create an audit record for the unapproval
await db.approval.create({
data: {
versionId,
userId: session.user.id,
status: "PENDING_REVIEW",
notes: "Approval undone",
},
});
// Reset version approval status
await db.version.update({
where: { id: versionId },
data: { approvalStatus: "PENDING_REVIEW" },
});
// Reset task back to INTERNAL_REVIEW if it was moved to DONE
if (version.task && version.task.status === "DONE") {
await db.task.update({
where: { id: version.task.id },
data: { status: "INTERNAL_REVIEW" },
// One decision, one write — same reasoning as submitApproval.
await db.$transaction(async (tx) => {
// Create an audit record for the unapproval
await tx.approval.create({
data: {
versionId,
userId: session.user.id,
status: "PENDING_REVIEW",
notes: "Approval undone",
},
});
}
// Recalculate shot status
if (version.task?.shot) {
await recalcShotStatus(version.task.shot.id).catch(() => {});
}
// Reset version approval status
await tx.version.update({
where: { id: versionId },
data: { approvalStatus: "PENDING_REVIEW" },
});
// Reset task back to INTERNAL_REVIEW if it was moved to DONE
if (version.task && version.task.status === "DONE") {
await tx.task.update({
where: { id: version.task.id },
data: { status: "INTERNAL_REVIEW" },
});
}
// Undoing a version approval also invalidates any shot-level sign-off that
// rested on it, otherwise the shot keeps reading COMPLETE / READY_FOR_CLIENT.
if (version.task?.shot) {
await clearStaleShotApproval(tx, version.task.shot.id);
await recalcShotStatus(version.task.shot.id, tx);
}
});
revalidatePath(`/review/${versionId}`);
if (version.task) {
+43
View File
@@ -0,0 +1,43 @@
"use server";
import { revalidatePath } from "next/cache";
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
import { PipelineError } from "@/lib/render-pipeline/errors";
import {
createMovReviewPackage,
previewMovReviewPackage,
} from "@/lib/render-pipeline/reviews";
/**
* Server actions behind "Build MOV Review Package" on the shot-status page
* (RenderPipeline2 §11.6). The heavy lifting lives in lib/render-pipeline;
* these only carry the session and turn service errors into messages a toast
* can show.
*/
function message(err: unknown): string {
if (err instanceof PipelineError) return err.message;
return err instanceof Error ? err.message : "Unknown error";
}
/** What the confirm dialog shows: the folder, the resolved versions, the gaps. */
export async function previewMovReview(shotIds: string[]) {
try {
await requirePipelineAdmin();
const preview = await previewMovReviewPackage(shotIds);
return { ok: true as const, ...preview };
} catch (err) {
return { ok: false as const, error: message(err) };
}
}
export async function buildMovReview(shotIds: string[]) {
try {
const user = await requirePipelineAdmin();
const result = await createMovReviewPackage({ shotIds }, user.id);
revalidatePath("/pipeline/deliveries");
return { ok: true as const, ...result };
} catch (err) {
return { ok: false as const, error: message(err) };
}
}
+5 -1
View File
@@ -108,10 +108,14 @@ export async function updateProject(data: z.infer<typeof updateProjectSchema>) {
...(rest.slackChannel !== undefined && { slackChannel: rest.slackChannel || null }),
// Blank fields are dropped rather than stored as empty strings, so a comp
// name left blank keeps following the convention instead of pinning "".
// Booleans are kept as-is: `false` is a meaningful stored value, and the
// blank-string test would otherwise discard every non-string setting.
...(rest.pipelineConfig !== undefined && {
pipelineConfig: rest.pipelineConfig
? (Object.fromEntries(
Object.entries(rest.pipelineConfig).filter(([, v]) => typeof v === "string" && v.trim())
Object.entries(rest.pipelineConfig).filter(([, v]) =>
typeof v === "boolean" ? true : typeof v === "string" && !!v.trim()
)
) as Prisma.InputJsonValue)
: Prisma.DbNull,
}),
+223 -47
View File
@@ -4,8 +4,8 @@ import { auth } from "@/auth";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { ShotStatus, ShotPriority, ShotApprovalStatus } from "@prisma/client";
import { recalcShotStatus } from "@/lib/shot-status";
import { ShotStatus, ShotPriority, ShotApprovalStatus, Prisma } from "@prisma/client";
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
const createShotSchema = z.object({
scene: z.string().min(1).max(50).regex(/^[A-Z0-9_]+$/i, "Alphanumeric and underscore only"),
@@ -341,6 +341,15 @@ export async function importShotsFromCsv(
return { success: true, created, errors };
}
/**
* Manual override of the shot's status.
*
* Deliberately the one place that writes Shot.status without deriving it — but
* note the override is transient: Shot.status is a derived field, so the next
* recalc (any task move, approval, upload or render) recomputes it from the
* tasks and approval flags and discards whatever was set here. Change the
* underlying task states if the new status needs to stick.
*/
export async function updateShotStatus(
shotId: string,
status: ShotStatus
@@ -498,6 +507,7 @@ export async function updateShotSlate(
slateDescription?: string | null;
slateVfxScope?: string | null;
slateSubmissionNote?: string | null;
clientCode?: string | null;
}
) {
const session = await auth();
@@ -516,6 +526,7 @@ export async function updateShotSlate(
slateDescription: data.slateDescription !== undefined ? (data.slateDescription?.trim() || null) : undefined,
slateVfxScope: data.slateVfxScope !== undefined ? (data.slateVfxScope?.trim() || null) : undefined,
slateSubmissionNote: data.slateSubmissionNote !== undefined ? (data.slateSubmissionNote?.trim() || null) : undefined,
clientCode: data.clientCode !== undefined ? (data.clientCode?.trim() || null) : undefined,
},
});
@@ -548,6 +559,34 @@ export async function toggleKeyShot(shotId: string, isKeyShot: boolean) {
return { success: true };
}
/**
* Scaled in the edit: the plate is not used at its native size, which changes
* how the shot is comped and reviewed. Same shape as toggleKeyShot — a standing
* property of the shot, flipped from the shot-status board.
*/
export async function toggleScaledShot(shotId: string, isScaled: boolean) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
throw new Error("Insufficient permissions");
}
const shot = await db.shot.findUnique({
where: { id: shotId },
select: { projectId: true },
});
if (!shot) throw new Error("Shot not found");
await db.shot.update({
where: { id: shotId },
data: { isScaled },
});
revalidatePath(`/projects/${shot.projectId}`);
revalidatePath(`/shot-status`);
return { success: true };
}
export async function deleteShot(shotId: string) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
@@ -613,6 +652,59 @@ export async function bulkUpdateDueDates(
return { success: true, updated: shots.length };
}
// ── Bulk Delete Shots ─────────────────────────────────────────────────────────
export async function bulkDeleteShots(shotIds: string[]) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
throw new Error("Insufficient permissions");
}
if (!shotIds.length) return { success: true, deleted: 0, failed: [] as { shotId: string; shotCode: string; reason: string }[] };
const shots = await db.shot.findMany({
where: { id: { in: shotIds } },
select: { id: true, shotCode: true, projectId: true },
});
const projectIds = [...new Set(shots.map((s) => s.projectId))];
const failed: { shotId: string; shotCode: string; reason: string }[] = [];
let deleted = 0;
// One at a time, not deleteMany: a shot with renders or deliveries is
// protected at the database level (exports_shotId_fkey is ON DELETE
// RESTRICT, deliberately — delivery history must never be destroyable by
// deleting the shot underneath it). A single bulk statement would abort
// entirely on the first shot it hits; deleting individually means every
// shot that *can* go still does, and the ones that can't are reported by
// name instead of failing the whole selection.
for (const shot of shots) {
try {
await db.shot.delete({ where: { id: shot.id } });
deleted += 1;
} catch (e) {
failed.push({
shotId: shot.id,
shotCode: shot.shotCode,
reason:
e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2003"
? "has renders or deliveries — delete those first"
: e instanceof Error
? e.message
: "unknown error",
});
}
}
for (const pid of projectIds) {
revalidatePath(`/projects/${pid}`);
}
revalidatePath(`/shot-status`);
return { success: true, deleted, failed };
}
export async function renameFootagePlate(plateId: string, label: string) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
@@ -654,13 +746,19 @@ export async function internallyApproveShot(shotId: string) {
});
if (!shot) throw new Error("Shot not found");
await db.shot.update({
where: { id: shotId },
data: {
shotApprovalStatus: "INTERNALLY_APPROVED",
sharedWithClient: false,
status: "READY_FOR_CLIENT",
},
// Set the approval inputs and let the derivation pick the status. Writing
// READY_FOR_CLIENT directly skipped the rule that an outstanding CHANGES task
// outranks any approval, so a shot could be pushed past open rework and then
// snap back to REVISIONS on the next unrelated recalc.
await db.$transaction(async (tx) => {
await tx.shot.update({
where: { id: shotId },
data: {
shotApprovalStatus: "INTERNALLY_APPROVED",
sharedWithClient: false,
},
});
await recalcShotStatus(shotId, tx);
});
revalidatePath(`/projects/${shot.projectId}`);
@@ -703,7 +801,7 @@ export async function shareWithClient(shotId: string) {
// Mark shot as shared
await tx.shot.update({
where: { id: shotId },
data: { sharedWithClient: true, status: "CLIENT_REVIEW" },
data: { sharedWithClient: true },
});
// For each task, make the latest version client-visible
@@ -723,6 +821,8 @@ export async function shareWithClient(shotId: string) {
});
}
}
await recalcShotStatus(shotId, tx);
});
revalidatePath(`/projects/${shot.projectId}`);
@@ -755,7 +855,7 @@ export async function unshareFromClient(shotId: string) {
await db.$transaction(async (tx) => {
await tx.shot.update({
where: { id: shotId },
data: { sharedWithClient: false, status: "READY_FOR_CLIENT" },
data: { sharedWithClient: false },
});
// Hide all client-visible versions on this shot's tasks
@@ -766,6 +866,8 @@ export async function unshareFromClient(shotId: string) {
data: { isClientVisible: false },
});
}
await recalcShotStatus(shotId, tx);
});
revalidatePath(`/projects/${shot.projectId}`);
@@ -794,9 +896,12 @@ export async function clientApproveShot(shotId: string) {
if (!shot) throw new Error("Shot not found");
if (!shot.sharedWithClient) throw new Error("Shot is not shared with client");
await db.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
await db.$transaction(async (tx) => {
await tx.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "CLIENT_APPROVED" },
});
await recalcShotStatus(shotId, tx);
});
revalidatePath(`/projects/${shot.projectId}`);
@@ -826,14 +931,15 @@ export async function unapproveShot(shotId: string) {
throw new Error("Shot is not client-approved");
}
const newStatus = shot.sharedWithClient ? "CLIENT_REVIEW" : "READY_FOR_CLIENT";
await db.shot.update({
where: { id: shotId },
data: {
shotApprovalStatus: "INTERNALLY_APPROVED",
status: newStatus,
},
// The derivation already encodes "CLIENT_REVIEW if still shared, else
// READY_FOR_CLIENT" for an INTERNALLY_APPROVED shot, and additionally honours
// any open CHANGES task.
await db.$transaction(async (tx) => {
await tx.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "INTERNALLY_APPROVED" },
});
await recalcShotStatus(shotId, tx);
});
revalidatePath(`/projects/${shot.projectId}`);
@@ -1134,9 +1240,12 @@ export async function assignShotGroups(
}
/**
* Internal: handle client requesting changes on a shot.
* Resets shotApprovalStatus = PENDING, sharedWithClient = false.
* Recalculates shot status (will become REVISIONS if tasks set to CHANGES).
* Session-authenticated wrapper for requesting changes on a shot — a supervisor
* or producer relaying a client note from inside the app.
*
* The client portal cannot use this: it runs on a review token, not a session,
* so it calls markShotForRevisions directly from its route. Both go through that
* one helper so the two entry points cannot drift apart again.
*/
export async function clientRequestShotChanges(shotId: string, taskId?: string) {
const session = await auth();
@@ -1151,28 +1260,7 @@ export async function clientRequestShotChanges(shotId: string, taskId?: string)
});
if (!shot) throw new Error("Shot not found");
await db.$transaction(async (tx) => {
// Reset shot approval
await tx.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "PENDING", sharedWithClient: false },
});
// If a specific task is called out, mark it CHANGES; otherwise mark all non-DONE tasks
if (taskId) {
await tx.task.update({
where: { id: taskId },
data: { status: "CHANGES" },
});
} else {
await tx.task.updateMany({
where: { shotId, status: { not: "DONE" } },
data: { status: "CHANGES" },
});
}
await recalcShotStatus(shotId, tx);
});
await db.$transaction((tx) => markShotForRevisions(tx, shotId, taskId));
revalidatePath(`/projects/${shot.projectId}`);
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
@@ -1211,3 +1299,91 @@ export async function updateShotVersion(shotId: string, version: string) {
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
return { success: true, shotVersion: version };
}
// ── Generated (render-derived) shot thumbnails ───────────────────────────────
//
// A shot can carry two stills: `thumbnailUrl`, the reference frame that came
// with the brief, and `generatedThumbnailUrl`, a frame promoted from a render
// export. The reference always wins on display (lib/shot-thumbnail.ts), so
// these actions can only ever fill a gap — a promotion never overwrites the
// brief, and clearing one always falls back to it.
//
// Shows with `pipelineConfig.autoShotThumbnail` promote on every finished
// export automatically (lib/render-pipeline/preview.ts). These actions are the
// manual equivalent, and work regardless of that flag: a supervisor can pull a
// frame onto one shot on a project that is otherwise hands-off.
/**
* Promote a render export's thumbnail onto its shot.
*
* With no `exportId`, uses the newest export of that shot which actually has a
* thumbnail — "use the latest render frame".
*/
export async function promoteExportThumbnail(shotId: string, exportId?: string) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
throw new Error("Insufficient permissions");
}
const shot = await db.shot.findUnique({
where: { id: shotId },
select: { id: true, projectId: true },
});
if (!shot) throw new Error("Shot not found");
const exportRow = await db.export.findFirst({
where: {
shotId,
thumbnailKey: { not: null },
...(exportId ? { id: exportId } : {}),
},
orderBy: { versionNumber: "desc" },
select: { id: true, thumbnailKey: true, versionString: true },
});
if (!exportRow?.thumbnailKey) {
throw new Error(
exportId
? "That export has no thumbnail — its preview may have been skipped, or the worker had no ffmpeg configured"
: "No render of this shot has produced a thumbnail yet"
);
}
const generatedThumbnailUrl = `/api/files/${exportRow.thumbnailKey}`;
await db.shot.update({
where: { id: shotId },
data: { generatedThumbnailUrl, generatedThumbnailFrom: exportRow.versionString },
});
revalidatePath(`/projects/${shot.projectId}`);
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
return {
success: true,
generatedThumbnailUrl,
generatedThumbnailFrom: exportRow.versionString,
};
}
/** Drop the render-derived still. The reference frame, if any, comes back. */
export async function clearGeneratedThumbnail(shotId: string) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
throw new Error("Insufficient permissions");
}
const shot = await db.shot.findUnique({
where: { id: shotId },
select: { id: true, projectId: true },
});
if (!shot) throw new Error("Shot not found");
await db.shot.update({
where: { id: shotId },
data: { generatedThumbnailUrl: null, generatedThumbnailFrom: null },
});
revalidatePath(`/projects/${shot.projectId}`);
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
return { success: true };
}
+10 -3
View File
@@ -4,7 +4,7 @@ import { auth } from "@/auth";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { recalcShotStatus } from "@/lib/shot-status";
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
import { notifyNewVersionUploaded } from "@/lib/notifications";
import { slackNotifyVersionUploaded } from "@/lib/slack";
@@ -50,9 +50,16 @@ export async function createVersion(data: z.infer<typeof createVersionSchema>) {
data: { status: "INTERNAL_REVIEW" },
});
// Recalculate shot status
// Recalculate shot status — clearing any stale sign-off first, so a new
// version does not land under a shot still reading COMPLETE.
if (task.shot) {
await recalcShotStatus(task.shot.id).catch(() => {});
const shotId = task.shot.id;
await db
.$transaction(async (tx) => {
await clearStaleShotApproval(tx, shotId);
await recalcShotStatus(shotId, tx);
})
.catch(() => {});
}
// Get the next version number for this task
@@ -29,6 +29,7 @@ interface PackageRow {
id: string;
packageNumber: number;
name: string;
kind: "EXR_DELIVERY" | "MOV_REVIEW";
episode: string;
status: string;
rootPath: string | null;
@@ -242,6 +243,11 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
<summary className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-zinc-900/60 flex-wrap">
<span className="text-sm text-white font-medium">#{p.packageNumber}</span>
<span className="text-sm text-zinc-300">{p.name}</span>
{p.kind === "MOV_REVIEW" && (
<span className="rounded-full border border-violet-500/30 bg-violet-500/10 px-2 py-0.5 text-xs text-violet-300">
MOV review
</span>
)}
<span
className={cn(
"rounded-full border px-2 py-0.5 text-xs",
@@ -257,7 +263,7 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
<span className="text-xs text-zinc-600">{new Date(p.createdAt).toLocaleDateString()}</span>
{p.status === "BUILDING" && <RefreshCw className="h-3.5 w-3.5 text-blue-400 animate-spin" />}
<span className="ml-auto flex items-center gap-2">
{canBuild && p.status === "READY" && (
{canBuild && p.status === "READY" && p.kind === "EXR_DELIVERY" && (
<Button
size="sm"
variant="outline"
@@ -309,7 +315,9 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
</span>
<span className="text-zinc-300">{item.shotCode}</span>
<span className="text-zinc-500">{item.versionString}</span>
{item.fileCount != null && <span className="text-zinc-600">{item.fileCount}f</span>}
{p.kind === "EXR_DELIVERY" && item.fileCount != null && (
<span className="text-zinc-600">{item.fileCount}f</span>
)}
{item.linkMode && <span className="text-zinc-600">{item.linkMode}</span>}
{item.errorMessage && <span className="text-red-400">{item.errorMessage}</span>}
</div>
@@ -64,6 +64,7 @@ interface ProjectTabsClientProps {
overlayComp?: string | null;
previewComp?: string | null;
lutComp?: string | null;
autoShotThumbnail?: boolean | null;
} | null;
};
clients: Client[];
@@ -41,7 +41,7 @@ export default async function KanbanPage({
where: { projectId: id },
orderBy: [{ status: "asc" }, { sortOrder: "asc" }],
include: {
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
asset: { select: { id: true, assetCode: true, name: true } },
assignedArtist: {
select: { id: true, name: true, email: true, image: true },
+2 -1
View File
@@ -60,7 +60,7 @@ async function getProject(id: string) {
tasks: {
orderBy: [{ status: "asc" }, { sortOrder: "asc" }],
include: {
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
asset: { select: { id: true, assetCode: true, name: true } },
assignedArtist: { select: { id: true, name: true, email: true, image: true } },
_count: { select: { versions: true } },
@@ -207,6 +207,7 @@ export default async function ProjectPage({ params }: { params: Promise<{ id: st
overlayComp?: string | null;
previewComp?: string | null;
lutComp?: string | null;
autoShotThumbnail?: boolean | null;
} | null,
}}
clients={clients}
@@ -76,6 +76,7 @@ const PRIORITY_CONFIG: Record<string, { label: string; dot: string }> = {
};
import { useToast } from "@/components/ui/use-toast";
import { shotThumbnail } from "@/lib/shot-thumbnail";
export default function ShotDetailPage() {
const params = useParams<{ id: string; shotId: string }>();
@@ -251,11 +252,11 @@ export default function ShotDetailPage() {
<ArrowLeft className="h-4 w-4" />
</Link>
</Button>
{shot.thumbnailUrl && (
{shotThumbnail(shot) && (
<div className="relative flex-shrink-0 w-72 aspect-[2.39] rounded-lg overflow-hidden border border-border">
<Image
src={shot.thumbnailUrl}
src={shotThumbnail(shot)!}
alt={shot.shotCode}
fill
className="object-cover"
@@ -53,7 +53,12 @@ export interface ScheduleTask {
email: string;
image: string | null;
} | null;
shot: { id: string; shotCode: string; thumbnailUrl: string | null } | null;
shot: {
id: string;
shotCode: string;
thumbnailUrl: string | null;
generatedThumbnailUrl: string | null;
} | null;
asset: { id: string; assetCode: string; name: string } | null;
project: { id: string; name: string; code: string };
}
+2 -2
View File
@@ -31,7 +31,7 @@ export default async function SchedulePage({
...(artist ? { assignedArtistId: artist } : {}),
},
include: {
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
asset: { select: { id: true, assetCode: true, name: true } },
project: { select: { id: true, name: true, code: true } },
assignedArtist: {
@@ -49,7 +49,7 @@ export default async function SchedulePage({
...(artist ? { assignedArtistId: artist } : {}),
},
include: {
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
asset: { select: { id: true, assetCode: true, name: true } },
project: { select: { id: true, name: true, code: true } },
assignedArtist: {
+362 -20
View File
@@ -18,11 +18,19 @@ import {
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { updateShotNotes, bulkUpdateDueDates, toggleKeyShot } from "@/actions/shots";
import { updateShotNotes, bulkUpdateDueDates, bulkDeleteShots, toggleKeyShot, toggleScaledShot } from "@/actions/shots";
import { previewMovReview, buildMovReview } from "@/actions/deliveries";
import { useToast } from "@/components/ui/use-toast";
import {
Film,
@@ -38,8 +46,13 @@ import {
ShieldCheck,
Eye,
Star,
Trash2,
ChevronsUpDown,
Clapperboard,
Scaling,
} from "lucide-react";
import { format } from "date-fns";
import { shotThumbnail } from "@/lib/shot-thumbnail";
type ShotRow = {
id: string;
@@ -51,9 +64,12 @@ type ShotRow = {
priority: string;
dueDate: Date | string | null;
thumbnailUrl: string | null;
generatedThumbnailUrl: string | null;
notes: string | null;
description: string | null;
isKeyShot: boolean;
isScaled: boolean;
shotVersion: string | null;
artist: { id: string; name: string | null; image: string | null; email: string } | null;
shotGroup: { id: string; name: string } | null;
};
@@ -209,6 +225,203 @@ function BulkDueDateDialog({
);
}
function BulkDeleteDialog({
open,
onClose,
onConfirm,
count,
}: {
open: boolean;
onClose: () => void;
onConfirm: () => Promise<void>;
count: number;
}) {
const [isPending, startTransition] = useTransition();
const handleConfirm = () => {
startTransition(async () => {
await onConfirm();
});
};
return (
<Dialog open={open} onOpenChange={(o) => { if (!o && !isPending) onClose(); }}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle className="text-red-400">Delete {count} shot{count !== 1 ? "s" : ""}?</DialogTitle>
</DialogHeader>
<p className="text-sm text-zinc-300">
This will permanently delete <span className="font-semibold text-white">{count}</span>{" "}
shot{count !== 1 ? "s" : ""}, including all tasks, versions, footage, and annotations.
This cannot be undone.
</p>
<p className="text-xs text-zinc-500">
A shot with renders or deliveries already on record is protected and will be skipped
rather than deleted — you'll see which ones and why.
</p>
<DialogFooter className="mt-2">
<Button variant="ghost" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button variant="destructive" onClick={handleConfirm} disabled={isPending}>
{isPending && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
{isPending ? "Deleting…" : `Yes, delete ${count} shot${count !== 1 ? "s" : ""}`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
// ── MovReviewDialog ───────────────────────────────────────────────────────────
type ReviewPreview = Awaited<ReturnType<typeof previewMovReview>>;
/**
* Confirm what a MOV review package would contain before building it
* (RenderPipeline2 §11.6).
*
* The version each shot resolves to is the newest one that actually has a
* preview MOV, which is not always the newest one full stop — so the dialog
* names the version per shot rather than making anyone guess, and lists the
* shots with no MOV at all instead of quietly building a smaller folder.
*/
function MovReviewDialog({
open,
onClose,
onBuilt,
shotIds,
}: {
open: boolean;
onClose: () => void;
onBuilt: () => void;
shotIds: string[];
}) {
const { toast } = useToast();
const [preview, setPreview] = useState<ReviewPreview | null>(null);
const [loading, setLoading] = useState(false);
const [isPending, startTransition] = useTransition();
useEffect(() => {
if (!open) {
setPreview(null);
return;
}
let cancelled = false;
setLoading(true);
previewMovReview(shotIds)
.then((result) => {
if (!cancelled) setPreview(result);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const ready = preview?.ok ? preview.candidates : [];
const skipped = preview?.ok ? preview.skipped : [];
const handleBuild = () => {
startTransition(async () => {
const result = await buildMovReview(shotIds);
if (!result.ok) {
toast({ title: "Could not build review package", description: result.error, variant: "destructive" });
return;
}
toast({
title: `${result.package.name} queued`,
description: `${result.package.itemCount} MOV${result.package.itemCount !== 1 ? "s" : ""} → ${result.package.rootPath}`,
});
onBuilt();
});
};
return (
<Dialog open={open} onOpenChange={(o) => { if (!o && !isPending) onClose(); }}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>Build MOV review package</DialogTitle>
</DialogHeader>
{loading && (
<p className="text-sm text-zinc-400 flex items-center gap-2">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Working out what each shot would contribute…
</p>
)}
{!loading && preview && !preview.ok && (
<p className="text-sm text-red-400">{preview.error}</p>
)}
{!loading && preview?.ok && (
<div className="space-y-4">
<div className="rounded-md border border-zinc-800 bg-zinc-900/60 px-3 py-2">
<div className="text-xs text-zinc-500">Folder</div>
<div className="text-sm text-white font-medium break-all">{preview.packageName}</div>
<div className="text-xs text-zinc-500 break-all">{preview.packageDir}</div>
</div>
{ready.length > 0 && (
<div className="space-y-1.5">
<div className="text-xs font-medium text-zinc-400">
{ready.length} MOV{ready.length !== 1 ? "s" : ""}
</div>
<div className="max-h-52 overflow-y-auto rounded-md border border-zinc-800 divide-y divide-zinc-800/60">
{ready.map((c) => (
<div key={c.shotId} className="flex items-center gap-2 px-3 py-1.5 text-xs">
<span className="text-zinc-200">{c.shotCode}</span>
<span className="text-zinc-500">{c.versionString}</span>
<span className="ml-auto text-zinc-600 truncate">{c.deliveredName}</span>
</div>
))}
</div>
</div>
)}
{skipped.length > 0 && (
<div className="space-y-1.5">
<div className="text-xs font-medium text-amber-400">
{skipped.length} shot{skipped.length !== 1 ? "s" : ""} left out
</div>
<div className="max-h-32 overflow-y-auto rounded-md border border-amber-500/20 bg-amber-500/5 divide-y divide-amber-500/10">
{skipped.map((sk) => (
<div key={sk.shotId} className="flex items-center gap-2 px-3 py-1.5 text-xs">
<span className="text-zinc-300">{sk.shotCode}</span>
<span className="text-amber-400/80">{sk.reason}</span>
</div>
))}
</div>
</div>
)}
<p className="text-xs text-zinc-500">
A render machine builds the folder. Nothing about these shots changes — a review is
not a delivery, so the versions stay exactly where they are in the pipeline.
</p>
</div>
)}
<DialogFooter className="mt-2">
<Button variant="ghost" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button onClick={handleBuild} disabled={isPending || loading || ready.length === 0}>
{isPending && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
{isPending ? "Queueing…" : `Build with ${ready.length} MOV${ready.length !== 1 ? "s" : ""}`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
// ── NotesCell ─────────────────────────────────────────────────────────────────
function NotesCell({
@@ -264,10 +477,30 @@ function NotesCell({
);
}
// ── KeyShotToggle ─────────────────────────────────────────────────────────────
// ── Shot flag toggles ─────────────────────────────────────────────────────────
function KeyShotToggle({ shot }: { shot: ShotRow }) {
const [optimistic, setOptimistic] = useState(shot.isKeyShot);
/**
* A standing yes/no property of a shot, flipped straight from the board.
* Optimistic: the switch moves immediately and rolls back if the save fails,
* because a producer ticking twenty shots should not wait on a round trip each
* time.
*/
function FlagToggle({
value,
onSet,
onLabel,
offLabel,
failureTitle,
tone,
}: {
value: boolean;
onSet: (next: boolean) => Promise<unknown>;
onLabel: string;
offLabel: string;
failureTitle: string;
tone: { on: string; ring: string };
}) {
const [optimistic, setOptimistic] = useState(value);
const [isPending, startTransition] = useTransition();
const { toast } = useToast();
@@ -276,10 +509,10 @@ function KeyShotToggle({ shot }: { shot: ShotRow }) {
setOptimistic(next);
startTransition(async () => {
try {
await toggleKeyShot(shot.id, next);
await onSet(next);
} catch {
setOptimistic(!next);
toast({ title: "Failed to update key shot", variant: "destructive" });
toast({ title: failureTitle, variant: "destructive" });
}
});
};
@@ -289,12 +522,13 @@ function KeyShotToggle({ shot }: { shot: ShotRow }) {
type="button"
role="switch"
aria-checked={optimistic}
aria-label={optimistic ? "Remove key shot" : "Mark as key shot"}
aria-label={optimistic ? offLabel : onLabel}
disabled={isPending}
onClick={handle}
className={cn(
"relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-400 disabled:opacity-50",
optimistic ? "bg-amber-500" : "bg-zinc-600 hover:bg-zinc-500"
"relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus-visible:ring-2 disabled:opacity-50",
tone.ring,
optimistic ? tone.on : "bg-zinc-600 hover:bg-zinc-500"
)}
>
<span
@@ -307,6 +541,32 @@ function KeyShotToggle({ shot }: { shot: ShotRow }) {
);
}
function KeyShotToggle({ shot }: { shot: ShotRow }) {
return (
<FlagToggle
value={shot.isKeyShot}
onSet={(next) => toggleKeyShot(shot.id, next)}
onLabel="Mark as key shot"
offLabel="Remove key shot"
failureTitle="Failed to update key shot"
tone={{ on: "bg-amber-500", ring: "focus-visible:ring-amber-400" }}
/>
);
}
function ScaledShotToggle({ shot }: { shot: ShotRow }) {
return (
<FlagToggle
value={shot.isScaled}
onSet={(next) => toggleScaledShot(shot.id, next)}
onLabel="Mark as scaled in the edit"
offLabel="Remove scaled flag"
failureTitle="Failed to update scaled flag"
tone={{ on: "bg-cyan-500", ring: "focus-visible:ring-cyan-400" }}
/>
);
}
function ShotTable({
shots,
canManage,
@@ -349,6 +609,12 @@ function ShotTable({
Key
</span>
</th>
<th className="py-2 px-3 text-xs font-medium text-zinc-500 w-20 text-center">
<span className="flex items-center gap-1 justify-center">
<Scaling className="h-3 w-3" />
Scaled
</span>
</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-800/60">
@@ -382,9 +648,9 @@ function ShotTable({
{/* Thumbnail */}
<td className="py-2 px-3">
<div className="w-24 aspect-[2.39/1] rounded overflow-hidden bg-zinc-800 flex items-center justify-center shrink-0">
{shot.thumbnailUrl ? (
{shotThumbnail(shot) ? (
<Image
src={shot.thumbnailUrl}
src={shotThumbnail(shot)!}
alt={shot.shotCode}
width={96}
height={40}
@@ -409,6 +675,15 @@ function ShotTable({
>
{shot.shotCode}
</Link>
{shot.shotVersion && (
<span className="font-mono text-xs text-zinc-400 shrink-0">{shot.shotVersion}</span>
)}
{shot.isScaled && (
<span className="flex items-center gap-1 rounded-full border border-cyan-500/30 bg-cyan-500/10 px-1.5 py-0.5 text-[10px] font-medium text-cyan-300 shrink-0">
<Scaling className="h-2.5 w-2.5" />
Scaled
</span>
)}
</div>
{shot.description && (
<p className="text-xs text-zinc-500 mt-0.5 truncate max-w-[200px]">
@@ -451,6 +726,11 @@ function ShotTable({
<td className="py-2 px-3 text-center">
<KeyShotToggle shot={shot} />
</td>
{/* Scaled-in-edit toggle */}
<td className="py-2 px-3 text-center">
<ScaledShotToggle shot={shot} />
</td>
</tr>
);
})}
@@ -513,6 +793,8 @@ export function ShotStatusClient({
}
}, [selectedProjectId]);
const [dueDateDialogOpen, setDueDateDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [movReviewDialogOpen, setMovReviewDialogOpen] = useState(false);
const toggleEpisode = (ep: string) =>
setExpandedEpisodes((prev) => {
@@ -586,6 +868,26 @@ export function ShotStatusClient({
}
};
const handleBulkDelete = async () => {
try {
const result = await bulkDeleteShots([...selectedIds]);
if (result.failed.length > 0) {
toast({
title: `Deleted ${result.deleted} shot${result.deleted !== 1 ? "s" : ""}, ${result.failed.length} skipped`,
description: result.failed.map((f) => `${f.shotCode}: ${f.reason}`).join("; "),
variant: "destructive",
});
} else {
toast({ title: `Deleted ${result.deleted} shot${result.deleted !== 1 ? "s" : ""}` });
}
setDeleteDialogOpen(false);
clearSelection();
router.refresh();
} catch (e) {
toast({ title: "Failed to delete shots", description: e instanceof Error ? e.message : undefined, variant: "destructive" });
}
};
// Group by episode for episodic projects
const isEpisodic = selectedProject?.projectType === "EPISODIC";
const episodeGroups: [string, ShotRow[]][] = isEpisodic
@@ -722,15 +1024,36 @@ export function ShotStatusClient({
<span className="text-sm font-medium text-blue-300">
{selectionCount} shot{selectionCount !== 1 ? "s" : ""} selected
</span>
<Button
size="sm"
variant="outline"
className="h-7 gap-1.5 border-blue-500/40 text-blue-300 hover:bg-blue-500/20 hover:text-blue-200"
onClick={() => setDueDateDialogOpen(true)}
>
<CalendarDays className="h-3.5 w-3.5" />
Change Due Date
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="sm"
variant="outline"
className="h-7 gap-1.5 border-blue-500/40 text-blue-300 hover:bg-blue-500/20 hover:text-blue-200"
>
Bulk Actions
<ChevronsUpDown className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem onClick={() => setDueDateDialogOpen(true)}>
<CalendarDays className="h-3.5 w-3.5 mr-2" />
Change Due Date
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setMovReviewDialogOpen(true)}>
<Clapperboard className="h-3.5 w-3.5 mr-2" />
Build MOV Review Package
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setDeleteDialogOpen(true)}
className="text-red-400 focus:text-red-300"
>
<Trash2 className="h-3.5 w-3.5 mr-2" />
Delete Shots
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<button
onClick={clearSelection}
className="text-zinc-500 hover:text-zinc-300 transition-colors"
@@ -925,6 +1248,25 @@ export function ShotStatusClient({
onApply={handleBulkDueDate}
count={selectionCount}
/>
{/* Bulk delete dialog */}
<BulkDeleteDialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
onConfirm={handleBulkDelete}
count={selectionCount}
/>
{/* MOV review package (§11.6) */}
<MovReviewDialog
open={movReviewDialogOpen}
onClose={() => setMovReviewDialogOpen(false)}
onBuilt={() => {
setMovReviewDialogOpen(false);
clearSelection();
}}
shotIds={[...selectedIds]}
/>
</div>
);
}
+5
View File
@@ -37,9 +37,14 @@ async function getShotsForProject(projectId: string) {
priority: true,
dueDate: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
notes: true,
description: true,
isKeyShot: true,
isScaled: true,
// The shot-level version the panel burns into overlays and queueExport
// renders under — not the count of review Versions uploaded.
shotVersion: true,
artist: { select: { id: true, name: true, image: true, email: true } },
shotGroup: { select: { id: true, name: true } },
},
+9 -3
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { uploadToHetzner, deleteFromHetzner } from "@/lib/storage";
import { recalcShotStatus } from "@/lib/shot-status";
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
export const maxDuration = 300; // 5 min — large .mov high-res files
@@ -194,8 +194,14 @@ export async function POST(
data: { status: "INTERNAL_REVIEW" },
});
// Recalculate the parent shot's status
await recalcShotStatus(shotId).catch(() => {});
// Recalculate the parent shot's status, clearing any stale sign-off first so
// the new version does not land under a shot still reading COMPLETE.
await db
.$transaction(async (tx) => {
await clearStaleShotApproval(tx, shotId);
await recalcShotStatus(shotId, tx);
})
.catch(() => {});
return NextResponse.json({
success: true,
+43 -27
View File
@@ -1,21 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { ApprovalStatus } from "@prisma/client";
import { recalcShotStatus } from "@/lib/shot-status";
import { validateReviewToken } from "@/lib/review-auth";
async function getOrCreateClientUser(email: string, label?: string | null) {
const existing = await db.user.findUnique({ where: { email } });
if (existing) return existing;
return db.user.create({
data: {
email,
name: label ?? email.split("@")[0],
role: "CLIENT",
isActive: true,
},
});
}
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
export async function POST(
req: NextRequest,
@@ -48,9 +35,12 @@ export async function POST(
}
if (action === "APPROVE") {
await db.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
await db.$transaction(async (tx) => {
await tx.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "CLIENT_APPROVED" },
});
await recalcShotStatus(shotId, tx);
});
} else if (action === "NEEDS_CHANGES") {
// Increment shotVersion: v001 → v002, v009 → v010, etc.
@@ -59,17 +49,41 @@ export async function POST(
const nextNum = verMatch ? parseInt(verMatch[1], 10) + 1 : 2;
const nextVersion = "v" + String(nextNum).padStart(3, "0");
const user = await getOrCreateReviewUser(session, token);
await db.$transaction(async (tx) => {
await tx.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "PENDING", sharedWithClient: false, shotVersion: nextVersion },
data: { shotVersion: nextVersion },
});
// Mark all non-DONE tasks as CHANGES
await tx.task.updateMany({
where: { shotId, status: { not: "DONE" } },
data: { status: "CHANGES" },
// Clears the approval, unshares, marks the tasks needing rework and
// recalculates — including the case where every task was already DONE,
// which used to match nothing and leave the request with no effect.
await markShotForRevisions(tx, shotId);
// The shot-level verdict has to land on the versions too: the dashboard
// counters, the version badges and the client portal's own filters all
// read Version.approvalStatus, so a shot-level change request was
// invisible everywhere those look.
const shown = await tx.version.findMany({
where: { task: { shotId }, isClientVisible: true, isLatest: true },
select: { id: true },
});
await recalcShotStatus(shotId, tx);
for (const v of shown) {
await tx.approval.create({
data: {
versionId: v.id,
userId: user.id,
status: "NEEDS_CHANGES",
notes: notes ?? "Changes requested on the shot",
},
});
await tx.version.update({
where: { id: v.id },
data: { approvalStatus: "NEEDS_CHANGES" },
});
}
});
} else {
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
@@ -99,8 +113,7 @@ export async function POST(
return NextResponse.json({ error: "Version not found" }, { status: 404 });
}
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
const user = await getOrCreateClientUser(email, session.label);
const user = await getOrCreateReviewUser(session, token);
// Record approval
await db.approval.create({
@@ -126,9 +139,12 @@ export async function POST(
select: { sharedWithClient: true, shotApprovalStatus: true },
});
if (shot?.sharedWithClient && shot.shotApprovalStatus !== "CLIENT_APPROVED") {
// status is left to the recalc below — writing COMPLETE here was
// overwritten by it anyway, and disagreed with it whenever another
// task on the shot was still on CHANGES.
await db.shot.update({
where: { id: version.task.shot.id },
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
data: { shotApprovalStatus: "CLIENT_APPROVED" },
});
}
}
@@ -0,0 +1,127 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { validateReviewToken, findReviewUser, ownsComment } from "@/lib/review-auth";
/**
* Edit and delete for notes left through a client review link.
*
* A reviewer may only touch their own notes: the studio's comments and those of
* any other review session are read-only here, whatever the link holder sends.
* Ownership is the review session's guest User (lib/review-auth.ts) — the link
* is the credential, so everyone holding it shares that identity.
*/
/** Matches the internal addComment/editComment limits (actions/comments.ts). */
const MAX_LENGTH = 5000;
/** The annotation companion comments written by the drawing tools. */
const ANNOTATION_PREFIX = "✏️ Annotation at frame";
type Ctx = { params: Promise<{ token: string; commentId: string }> };
/**
* Resolves the request to a comment the caller is allowed to change, or the
* response explaining why not.
*
* "Not yours" is deliberately answered with 404 rather than 403: a link holder
* has no business learning which comment ids exist outside their own notes.
*/
async function authorizeCommentEdit(req: NextRequest, ctx: Ctx) {
const { token, commentId } = await ctx.params;
const result = await validateReviewToken(token, req);
if (result.type === "requiresPassword") {
return { error: NextResponse.json({ requiresPassword: true }, { status: 401 }) };
}
if (result.type === "invalid") {
return {
error: NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }),
};
}
const session = result.session;
const notFound = NextResponse.json({ error: "Comment not found" }, { status: 404 });
const comment = await db.comment.findUnique({
where: { id: commentId },
select: {
id: true,
authorId: true,
versionId: true,
frameNumber: true,
text: true,
version: {
select: {
shot: { select: { projectId: true } },
task: { select: { projectId: true } },
},
},
},
});
if (!comment) return { error: notFound };
// Same project scoping the rest of the portal applies.
const projectId = comment.version.shot?.projectId ?? comment.version.task?.projectId;
if (projectId !== session.projectId) return { error: notFound };
const user = await findReviewUser(session, token);
if (!ownsComment(comment, user?.id)) return { error: notFound };
return { comment };
}
/** PATCH — change the text of one's own note. */
export async function PATCH(req: NextRequest, ctx: Ctx) {
const authorized = await authorizeCommentEdit(req, ctx);
if (authorized.error) return authorized.error;
const { comment } = authorized;
const body = await req.json().catch(() => null);
const text = typeof body?.text === "string" ? body.text.trim() : "";
if (!text) {
return NextResponse.json({ error: "Note text is required" }, { status: 400 });
}
if (text.length > MAX_LENGTH) {
return NextResponse.json(
{ error: `Note must be ${MAX_LENGTH} characters or fewer` },
{ status: 400 }
);
}
// Only the text is editable. The frame a note is pinned to is what the studio
// works from, so moving it would silently repoint feedback someone may have
// already actioned; a note about a different frame is a new note.
const updated = await db.comment.update({
where: { id: comment.id },
data: { text },
include: {
author: { select: { id: true, name: true, image: true, email: true } },
replies: {
orderBy: { createdAt: "asc" },
include: { author: { select: { id: true, name: true, image: true, email: true } } },
},
},
});
return NextResponse.json({ comment: { ...updated, canEdit: true } });
}
/** DELETE — remove one's own note. */
export async function DELETE(req: NextRequest, ctx: Ctx) {
const authorized = await authorizeCommentEdit(req, ctx);
if (authorized.error) return authorized.error;
const { comment } = authorized;
await db.comment.delete({ where: { id: comment.id } });
// A drawing leaves a companion comment; deleting the note without the strokes
// would leave marks on the frame that nothing explains. Mirrors deleteComment
// in actions/comments.ts.
if (comment.text.startsWith(ANNOTATION_PREFIX)) {
await db.annotation.deleteMany({
where: { versionId: comment.versionId, frameNumber: comment.frameNumber },
});
}
return NextResponse.json({ success: true });
}
+4 -18
View File
@@ -1,21 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { slackNotifyNewFeedback } from "@/lib/slack";
import { validateReviewToken } from "@/lib/review-auth";
/** Find or create a guest user for the client reviewer based on the session email */
async function getOrCreateClientUser(email: string, label?: string | null) {
const existing = await db.user.findUnique({ where: { email } });
if (existing) return existing;
return db.user.create({
data: {
email,
name: label ?? email.split("@")[0],
role: "CLIENT",
isActive: true,
},
});
}
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
export async function POST(
req: NextRequest,
@@ -52,8 +38,7 @@ export async function POST(
}
// Resolve commenter identity
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
const user = await getOrCreateClientUser(email, session.label);
const user = await getOrCreateReviewUser(session, token);
const comment = await db.comment.create({
data: {
@@ -85,5 +70,6 @@ export async function POST(
});
}
return NextResponse.json({ comment }, { status: 201 });
// canEdit mirrors the GET shape — a note you just wrote is always your own.
return NextResponse.json({ comment: { ...comment, canEdit: true } }, { status: 201 });
}
+20 -1
View File
@@ -1,6 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { validateReviewToken } from "@/lib/review-auth";
import { shotThumbnail } from "@/lib/shot-thumbnail";
import { clientShotCode, clientTaskTitle } from "@/lib/shot-code";
/** GET /api/client/[token]/project — returns project + shots with tasks that have client-visible versions */
export async function GET(
@@ -43,12 +45,14 @@ export async function GET(
select: {
id: true,
shotCode: true,
clientCode: true,
episode: true,
sequence: true,
description: true,
status: true,
shotApprovalStatus: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
tasks: {
where: {
versions: { some: { isClientVisible: true } },
@@ -113,7 +117,22 @@ export async function GET(
return NextResponse.json({
project,
shots,
// Shots the client sees resolve the same way as internally: the reference
// still first, a render-derived one only where the show supplied none.
// Everything the client reads is in their own naming: the alias replaces
// our shot code, and the same swap runs over task titles, which carry the
// code by convention ("UNG_106_010_020_cmp_TT_v004"). The internal code is
// not sent at all — there is nothing here for it to be useful for, and
// leaking it invites the client to quote it back at us.
shots: shots.map(({ generatedThumbnailUrl, clientCode, ...shot }) => ({
...shot,
shotCode: clientShotCode({ ...shot, clientCode }),
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
tasks: shot.tasks.map((task) => ({
...task,
title: clientTaskTitle(task.title, { ...shot, clientCode }),
})),
})),
assetTasks,
sessionLabel: session.label,
});
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { validateReviewToken } from "@/lib/review-auth";
import { validateReviewToken, findReviewUser, ownsComment } from "@/lib/review-auth";
import { clientShotCode, clientTaskTitle } from "@/lib/shot-code";
/** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */
export async function GET(
@@ -40,7 +41,7 @@ export async function GET(
task: {
include: {
project: { select: { id: true, name: true, code: true } },
shot: { select: { id: true, shotCode: true, highResKey: true, highResFilename: true } },
shot: { select: { id: true, shotCode: true, clientCode: true, highResKey: true, highResFilename: true } },
asset: { select: { assetCode: true, name: true } },
},
},
@@ -64,7 +65,7 @@ export async function GET(
return NextResponse.json({ error: "Version not found" }, { status: 404 });
}
const comments = await db.comment.findMany({
const commentRows = await db.comment.findMany({
where: { versionId },
orderBy: { frameNumber: "asc" },
include: {
@@ -78,9 +79,22 @@ export async function GET(
},
});
// Which notes this reviewer may edit or delete. Read-only: opening a review
// link should not create the guest User, so a session that has never posted
// simply owns nothing. The edit/delete route re-checks this — the flag drives
// the UI, it does not grant anything.
const reviewUser = await findReviewUser(session, token);
const comments = commentRows.map((c) => ({
...c,
canEdit: ownsComment(c, reviewUser?.id),
}));
// Resolve the shot that has the high-res file (comes from version.shot OR version.task.shot)
const highResShot = version.shot ?? (version.task as any)?.shot ?? null;
// The shot the title and breadcrumb are drawn from — either relation.
const namingShot = version.shot ?? ((version.task as any)?.shot ?? null);
const serializedVersion = {
...version,
fileSize: version.fileSize?.toString() ?? null,
@@ -92,17 +106,24 @@ export async function GET(
shot: version.shot
? {
...version.shot,
shotCode: clientShotCode(version.shot),
clientCode: undefined,
hasHighRes: !!version.shot.highResKey,
highResFilename: version.shot.highResFilename ?? null,
highResKey: undefined,
}
: null,
// Task titles carry the shot code by convention, so the player header gets
// the same swap as the shot list (lib/shot-code.ts).
task: version.task
? {
...version.task,
title: namingShot ? clientTaskTitle(version.task.title, namingShot) : version.task.title,
shot: (version.task as any)?.shot
? {
...((version.task as any).shot),
shotCode: clientShotCode((version.task as any).shot),
clientCode: undefined,
highResKey: undefined, // strip storage key
}
: null,
+3 -1
View File
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { DeliveryStatus } from "@prisma/client";
import { DeliveryKind, DeliveryStatus } from "@prisma/client";
import { toErrorResponse } from "@/lib/render-pipeline/errors";
import { requirePipelineUser, requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
import {
@@ -15,10 +15,12 @@ export async function GET(req: NextRequest) {
await requirePipelineUser();
const { searchParams } = new URL(req.url);
const status = searchParams.get("status");
const kind = searchParams.get("kind");
const result = await listDeliveryPackages({
projectId: searchParams.get("projectId") ?? undefined,
episode: searchParams.get("episode") ?? undefined,
status: status ? (status as DeliveryStatus) : undefined,
kind: kind ? (kind as DeliveryKind) : undefined,
});
return NextResponse.json(result);
} catch (err) {
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { shotThumbnail } from "@/lib/shot-thumbnail";
// ── Auth ─────────────────────────────────────────────────────────────────────
@@ -91,6 +92,7 @@ export async function GET(
seqTimecodeStart: true,
seqTimecodeEnd: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
artist: {
select: { id: true, name: true, email: true },
},
@@ -111,6 +113,9 @@ export async function GET(
return NextResponse.json({
project,
pagination: { page, limit, total, pages: Math.ceil(total / limit) },
shots,
shots: shots.map(({ generatedThumbnailUrl, ...shot }) => ({
...shot,
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
})),
});
}
+6 -1
View File
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { shotThumbnail } from "@/lib/shot-thumbnail";
// ── Auth ─────────────────────────────────────────────────────────────────────
@@ -67,6 +68,7 @@ export async function GET(req: NextRequest) {
seqTimecodeEnd: true,
shotVersion: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
createdAt: true,
updatedAt: true,
project: {
@@ -104,5 +106,8 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ error: "Shot not found" }, { status: 404 });
}
return NextResponse.json({ shot });
const { generatedThumbnailUrl, ...rest } = shot;
return NextResponse.json({
shot: { ...rest, thumbnailUrl: shotThumbnail(shot) },
});
}
+3 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { shotThumbnail } from "@/lib/shot-thumbnail";
export async function GET(req: NextRequest) {
const session = await auth();
@@ -33,6 +34,7 @@ export async function GET(req: NextRequest) {
shotApprovalStatus: true,
sharedWithClient: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
tasks: {
select: {
id: true,
@@ -75,7 +77,7 @@ export async function GET(req: NextRequest) {
status: shot.status,
shotApprovalStatus: shot.shotApprovalStatus,
sharedWithClient: shot.sharedWithClient,
thumbnailUrl: shot.thumbnailUrl,
thumbnailUrl: shotThumbnail(shot),
latestVersion: {
id: latest.id,
versionNumber: latest.versionNumber,
+7 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { shotThumbnail } from "@/lib/shot-thumbnail";
function requireRole(role: string) {
return ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(role);
@@ -27,6 +28,7 @@ export async function GET(
scene: true,
episode: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
references: {
orderBy: { sortOrder: "asc" },
select: {
@@ -41,5 +43,9 @@ export async function GET(
});
if (!shot) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ shot });
const { generatedThumbnailUrl, ...rest } = shot;
return NextResponse.json({
shot: { ...rest, thumbnailUrl: shotThumbnail(shot) },
});
}
+7 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { shotThumbnail } from "@/lib/shot-thumbnail";
// ─── Helpers ──────────────────────────────────────────────────────────────────
@@ -409,13 +410,18 @@ export async function GET(req: NextRequest) {
where: { projectId },
select: {
id: true, shotCode: true, scene: true, episode: true, shotNumber: true,
description: true, notes: true, status: true, thumbnailUrl: true,
description: true, notes: true, status: true,
thumbnailUrl: true, generatedThumbnailUrl: true,
frameStart: true, frameEnd: true, fps: true, isKeyShot: true, shotVersion: true,
shotGroup: { select: { id: true, name: true } },
},
orderBy: [{ episode: "asc" }, { scene: "asc" }, { shotNumber: "asc" }],
});
// Collapse the two columns before anything reads them, so the "only shots
// with thumbnails" filter and the page renderer agree on what counts as one.
shots = shots.map((s) => ({ ...s, thumbnailUrl: shotThumbnail(s) }));
if (onlyThumbs) shots = shots.filter((s) => !!s.thumbnailUrl);
if (epFilter.length) shots = shots.filter((s) => epFilter.includes(s.episode ?? ""));
if (grpFilter.length) shots = shots.filter((s) => grpFilter.includes(s.shotGroup?.id ?? ""));
+10 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { shotThumbnail } from "@/lib/shot-thumbnail";
// GET /api/storyboard/shots?projectId=xxx
export async function GET(req: NextRequest) {
@@ -26,6 +27,7 @@ export async function GET(req: NextRequest) {
notes: true,
status: true,
thumbnailUrl: true,
generatedThumbnailUrl: true,
frameStart: true,
frameEnd: true,
fps: true,
@@ -40,5 +42,12 @@ export async function GET(req: NextRequest) {
],
});
return NextResponse.json({ shots });
// The reference still wins; a render-derived one fills the gap where a show
// shipped no stills at all (lib/shot-thumbnail.ts).
return NextResponse.json({
shots: shots.map(({ generatedThumbnailUrl, ...shot }) => ({
...shot,
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
})),
});
}
+179 -1
View File
@@ -31,6 +31,8 @@ import {
Copy,
Check,
Download,
Pencil,
Trash2,
} from "lucide-react";
import { useReviewStore } from "@/hooks/use-review-player";
import { ReviewPasswordGate } from "@/components/clients/ReviewPasswordGate";
@@ -42,6 +44,8 @@ interface Comment {
text: string;
isResolved: boolean;
createdAt: string;
/** This reviewer wrote it, so they can change or remove it. Set by the API. */
canEdit?: boolean;
author: { id: string; name: string | null; image: string | null; email: string };
replies: { id: string; text: string; createdAt: string; author: { name: string | null } }[];
}
@@ -104,6 +108,13 @@ export default function ClientReviewPage({
const [commentFrame, setCommentFrame] = useState<number | null>(null);
const [submittingComment, setSubmittingComment] = useState(false);
// Editing / deleting one's own notes
const [editingCommentId, setEditingCommentId] = useState<string | null>(null);
const [editingText, setEditingText] = useState("");
const [savingEdit, setSavingEdit] = useState(false);
const [deletingComment, setDeletingComment] = useState<Comment | null>(null);
const [deleting, setDeleting] = useState(false);
// Approval dialog
const [approvalDialog, setApprovalDialog] = useState<{
open: boolean;
@@ -209,6 +220,58 @@ export default function ClientReviewPage({
}
};
const beginEditComment = (comment: Comment) => {
setEditingCommentId(comment.id);
setEditingText(comment.text);
};
const cancelEditComment = () => {
setEditingCommentId(null);
setEditingText("");
};
const handleSaveEditedComment = async () => {
const trimmed = editingText.trim();
if (!editingCommentId || !trimmed || !version) return;
setSavingEdit(true);
try {
const res = await fetch(`/api/client/${token}/comment/${editingCommentId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: trimmed }),
});
if (!res.ok) throw new Error("Failed to save note");
cancelEditComment();
await refreshComments(token, version.id);
toast({ title: "Note updated" });
} catch {
toast({ title: "Failed to update note", variant: "destructive" });
} finally {
setSavingEdit(false);
}
};
const handleDeleteComment = async () => {
if (!deletingComment || !version) return;
setDeleting(true);
try {
const res = await fetch(`/api/client/${token}/comment/${deletingComment.id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Failed to delete note");
setDeletingComment(null);
// Deleting a drawing note also removes its strokes server-side, and those
// live in the canvas's own state — a full reload remounts the player so
// the frame does not keep showing marks that no longer exist.
loadVersion(token, version.id);
toast({ title: "Note deleted" });
} catch {
toast({ title: "Failed to delete note", variant: "destructive" });
} finally {
setDeleting(false);
}
};
const handleDownloadHighRes = async () => {
const shotId = version?.highResShotId ?? version?.shot?.id;
if (!shotId || !token) return;
@@ -510,8 +573,51 @@ export default function ClientReviewPage({
<div className="space-y-3">
{comments.map((comment) => (
<div key={comment.id} className="space-y-2">
{editingCommentId === comment.id ? (
// Editing replaces the note in place, so it stays in the
// list at its own frame rather than jumping to a dialog.
<div className="rounded-lg bg-zinc-800/70 p-3 space-y-2">
<div className="flex items-center gap-2">
<span className="text-xs text-zinc-400">Editing note</span>
<span className="ml-auto font-mono text-xs text-amber-400/80">
{frameToTimecode(comment.frameNumber, version.fps)}
</span>
</div>
<Textarea
value={editingText}
onChange={(e) => setEditingText(e.target.value)}
rows={3}
maxLength={5000}
autoFocus
className="bg-zinc-900 border-zinc-700 text-sm resize-none"
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleSaveEditedComment();
if (e.key === "Escape") cancelEditComment();
}}
/>
<div className="flex gap-2">
<Button
size="sm"
className="h-7 text-xs"
disabled={!editingText.trim() || savingEdit}
onClick={handleSaveEditedComment}
>
{savingEdit ? "Saving…" : "Save"}
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 text-xs"
onClick={cancelEditComment}
disabled={savingEdit}
>
Cancel
</Button>
</div>
</div>
) : (
<div
className="rounded-lg bg-zinc-800/70 p-3 space-y-2 cursor-pointer hover:bg-zinc-700/70 transition-colors"
className="group rounded-lg bg-zinc-800/70 p-3 space-y-2 cursor-pointer hover:bg-zinc-700/70 transition-colors"
onClick={() => playerRef.current?.seekToFrame(comment.frameNumber)}
title={`Jump to frame ${comment.frameNumber}`}
>
@@ -529,7 +635,36 @@ export default function ClientReviewPage({
</span>
</div>
<p className="text-sm text-zinc-200 leading-relaxed">{comment.text}</p>
{comment.canEdit && (
// Own notes only. The buttons stop propagation so they
// do not also seek the player to the note's frame.
<div className="flex items-center gap-1 pt-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:text-white hover:bg-zinc-700"
onClick={(e) => {
e.stopPropagation();
beginEditComment(comment);
}}
>
<Pencil className="h-3 w-3" />
Edit
</button>
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:text-red-400 hover:bg-zinc-700"
onClick={(e) => {
e.stopPropagation();
setDeletingComment(comment);
}}
>
<Trash2 className="h-3 w-3" />
Delete
</button>
</div>
)}
</div>
)}
{comment.replies.map((reply) => (
<div key={reply.id} className="ml-4 rounded-lg bg-zinc-800/40 border border-zinc-700/50 p-2.5">
<span className="text-xs text-zinc-400 font-medium">
@@ -658,6 +793,49 @@ export default function ClientReviewPage({
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete confirmation — a note may already have been actioned by the
studio, so removing it is worth one deliberate step. */}
<Dialog
open={!!deletingComment}
onOpenChange={(open) => { if (!open) setDeletingComment(null); }}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Delete this note?</DialogTitle>
</DialogHeader>
{deletingComment && (
<div className="space-y-2">
<p className="text-xs text-zinc-500 font-mono">
Frame {deletingComment.frameNumber} ·{" "}
{version ? frameToTimecode(deletingComment.frameNumber, version.fps) : ""}
</p>
<p className="rounded bg-zinc-800/70 p-3 text-sm text-zinc-200">
{deletingComment.text}
</p>
<p className="text-xs text-zinc-500">
This removes it for everyone, including the studio. It cannot be undone.
</p>
</div>
)}
<DialogFooter>
<Button
variant="ghost"
onClick={() => setDeletingComment(null)}
disabled={deleting}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={handleDeleteComment}
disabled={deleting}
>
{deleting ? "Deleting…" : "Delete note"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
@@ -41,6 +41,7 @@ const settingsSchema = z.object({
overlayComp: z.string().optional(),
previewComp: z.string().optional(),
lutComp: z.string().optional(),
autoShotThumbnail: z.boolean().optional(),
});
type SettingsFormValues = z.infer<typeof settingsSchema>;
@@ -79,6 +80,7 @@ interface ProjectSettingsTabProps {
overlayComp?: string | null;
previewComp?: string | null;
lutComp?: string | null;
autoShotThumbnail?: boolean | null;
} | null;
};
clients: Client[];
@@ -127,6 +129,7 @@ export function ProjectSettingsTab({ project, clients, teamMembers }: ProjectSet
overlayComp: project.pipelineConfig?.overlayComp ?? "",
previewComp: project.pipelineConfig?.previewComp ?? "",
lutComp: project.pipelineConfig?.lutComp ?? "",
autoShotThumbnail: project.pipelineConfig?.autoShotThumbnail ?? false,
},
});
@@ -159,6 +162,7 @@ export function ProjectSettingsTab({ project, clients, teamMembers }: ProjectSet
overlayComp: data.overlayComp?.trim() || null,
previewComp: data.previewComp?.trim() || null,
lutComp: data.lutComp?.trim() || null,
autoShotThumbnail: data.autoShotThumbnail ?? false,
},
});
toast({ title: "Project settings saved" });
@@ -427,6 +431,28 @@ export function ProjectSettingsTab({ project, clients, teamMembers }: ProjectSet
<Input id="lutComp" placeholder="_SHOW LUT" {...register("lutComp")} />
</div>
</div>
<div className="pt-4 mt-4 border-t border-border/60">
<label className="flex items-start gap-2.5 cursor-pointer group">
<input
id="autoShotThumbnail"
type="checkbox"
className="accent-amber-500 h-3.5 w-3.5 mt-0.5"
{...register("autoShotThumbnail")}
/>
<span className="space-y-1">
<span className="block text-sm group-hover:text-foreground transition-colors">
Use render frames as shot thumbnails
</span>
<span className="block text-xs text-muted-foreground">
Every finished export sets its shot&apos;s thumbnail from the render.
A thumbnail supplied with the brief always takes priority and is
never overwritten &mdash; turn this on for shows that arrive with no
stills at all, where the alternative is an empty grid.
</span>
</span>
</label>
</div>
</div>
</section>
+2 -1
View File
@@ -23,6 +23,7 @@ import {
ActiveDragData,
} from "@/app/(dashboard)/schedule/SchedulePageClient";
import { TASK_TYPE_LABELS } from "@/components/tasks/TaskCard";
import { shotThumbnail } from "@/lib/shot-thumbnail";
const STATUS_STYLES: Record<
TaskStatus,
@@ -134,7 +135,7 @@ export function ScheduleTaskBlock({
const statusStyle = STATUS_STYLES[task.status];
const contextCode = task.shot?.shotCode ?? task.asset?.assetCode;
const contextName = task.shot?.shotCode ?? task.asset?.name ?? task.title;
const thumbnail = task.shot?.thumbnailUrl ?? null;
const thumbnail = shotThumbnail(task.shot);
const isOverdue =
task.dueDate &&
+3 -2
View File
@@ -33,6 +33,7 @@ import {
import type { ShotWithDetails } from "@/types";
import { duplicateShot } from "@/actions/shots";
import { useToast } from "@/components/ui/use-toast";
import { shotThumbnail } from "@/lib/shot-thumbnail";
interface ShotCardProps {
shot: ShotWithDetails;
@@ -128,9 +129,9 @@ export function ShotCard({ shot, projectId, compact = false, canManage = false }
{/* Thumbnail with cinema scope aspect ratio (2.39:1) */}
<div className="mb-3 -mx-6 -mt-6 overflow-hidden rounded-t-lg">
<div className="relative w-full aspect-[2.39]">
{shot.thumbnailUrl || latestVersion?.thumbnailUrl || latestVersion?.posterUrl ? (
{shotThumbnail(shot) || latestVersion?.thumbnailUrl || latestVersion?.posterUrl ? (
<Image
src={shot.thumbnailUrl || latestVersion?.thumbnailUrl || latestVersion?.posterUrl || ""}
src={shotThumbnail(shot) || latestVersion?.thumbnailUrl || latestVersion?.posterUrl || ""}
alt={shot.shotCode}
fill
className="object-cover"
+74 -20
View File
@@ -1,8 +1,13 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { useQuery } from "@tanstack/react-query";
import { Layers, ExternalLink } from "lucide-react";
import { Layers, ExternalLink, ImageIcon, Loader2 } from "lucide-react";
import { promoteExportThumbnail } from "@/actions/shots";
import { useToast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
import {
EXPORT_STATUS_STYLES,
@@ -16,6 +21,7 @@ interface ExportRow {
statusChangedAt: string;
createdAt: string;
outputDir: string;
thumbnailUrl: string | null;
job: {
attempt: number;
progress: number;
@@ -29,6 +35,29 @@ interface ExportRow {
* pipeline history for this shot, linking into the Export detail page.
*/
export function ShotExportsTab({ shotId }: { shotId: string }) {
const router = useRouter();
const { toast } = useToast();
const [promotingId, setPromotingId] = useState<string | null>(null);
// Take this export's frame as the shot's thumbnail. Fills in only where the
// shot has no reference frame of its own (§9.1a) — it never overwrites one.
const promote = async (exportId: string, versionString: string) => {
setPromotingId(exportId);
try {
await promoteExportThumbnail(shotId, exportId);
toast({ title: `Shot thumbnail taken from ${versionString}` });
router.refresh();
} catch (err) {
toast({
title: "Could not use that frame",
description: (err as Error).message,
variant: "destructive",
});
} finally {
setPromotingId(null);
}
};
const { data, isLoading } = useQuery({
queryKey: ["shot-exports", shotId],
queryFn: async () => {
@@ -56,29 +85,54 @@ export function ShotExportsTab({ shotId }: { shotId: string }) {
return (
<div className="space-y-2">
{exports.map((e) => (
<Link
<div
key={e.id}
href={`/pipeline/exports/${e.id}`}
className="flex items-center gap-4 rounded-lg border border-border bg-card p-4 hover:border-zinc-600 transition-colors"
>
<span className="font-mono text-sm text-white w-14">{e.versionString}</span>
<span
className={cn(
"rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
EXPORT_STATUS_STYLES[e.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
<Link href={`/pipeline/exports/${e.id}`} className="flex flex-1 min-w-0 items-center gap-4">
{e.thumbnailUrl ? (
<span className="relative h-8 w-[76px] shrink-0 overflow-hidden rounded border border-border">
<Image src={e.thumbnailUrl} alt="" fill className="object-cover" sizes="76px" />
</span>
) : (
<span className="h-8 w-[76px] shrink-0 rounded border border-border bg-zinc-900" />
)}
>
{statusLabel(e.status)}
</span>
<span className="flex-1 min-w-0 truncate text-xs text-muted-foreground">
{e.job?.machineName ? `${e.job.machineName} · attempt ${e.job.attempt} · ` : ""}
{e.outputDir}
</span>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{new Date(e.createdAt).toLocaleDateString()}
</span>
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
</Link>
<span className="font-mono text-sm text-white w-14">{e.versionString}</span>
<span
className={cn(
"rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
EXPORT_STATUS_STYLES[e.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
)}
>
{statusLabel(e.status)}
</span>
<span className="flex-1 min-w-0 truncate text-xs text-muted-foreground">
{e.job?.machineName ? `${e.job.machineName} · attempt ${e.job.attempt} · ` : ""}
{e.outputDir}
</span>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{new Date(e.createdAt).toLocaleDateString()}
</span>
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
</Link>
{e.thumbnailUrl && (
<button
type="button"
onClick={() => promote(e.id, e.versionString)}
disabled={promotingId !== null}
title="Use this frame as the shot thumbnail (never replaces one supplied with the brief)"
className="shrink-0 flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground hover:text-foreground hover:border-zinc-600 disabled:opacity-50 transition-colors"
>
{promotingId === e.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<ImageIcon className="h-3.5 w-3.5" />
)}
Use frame
</button>
)}
</div>
))}
</div>
);
+102 -2
View File
@@ -18,9 +18,14 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { updateShot, deleteShot } from "@/actions/shots";
import {
updateShot,
deleteShot,
promoteExportThumbnail,
clearGeneratedThumbnail,
} from "@/actions/shots";
import { useToast } from "@/components/ui/use-toast";
import { Upload, X, Film, ImageIcon, Trash2, BookImage, Loader2 } from "lucide-react";
import { Upload, X, Film, ImageIcon, Trash2, BookImage, Loader2, Sparkles } from "lucide-react";
// ─── Shot References ──────────────────────────────────────────────────────────
@@ -191,6 +196,8 @@ interface ShotSettingsTabProps {
dueDate: Date | string | null;
artistId: string | null;
thumbnailUrl: string | null;
generatedThumbnailUrl?: string | null;
generatedThumbnailFrom?: string | null;
projectId: string;
};
artists: Artist[];
@@ -208,6 +215,48 @@ export function ShotSettingsTab({ shot, artists, onSaved }: ShotSettingsTabProps
const [clearThumbnail, setClearThumbnail] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Render-derived still, managed separately from the reference frame above.
const [generatedUrl, setGeneratedUrl] = useState(shot.generatedThumbnailUrl ?? null);
const [generatedFrom, setGeneratedFrom] = useState(shot.generatedThumbnailFrom ?? null);
const [isPromoting, setIsPromoting] = useState(false);
const handlePromote = async () => {
setIsPromoting(true);
try {
const res = await promoteExportThumbnail(shot.id);
setGeneratedUrl(res.generatedThumbnailUrl);
setGeneratedFrom(res.generatedThumbnailFrom);
toast({ title: `Thumbnail taken from ${res.generatedThumbnailFrom}` });
router.refresh();
} catch (err) {
toast({
title: "Could not use a render frame",
description: (err as Error).message,
variant: "destructive",
});
} finally {
setIsPromoting(false);
}
};
const handleClearGenerated = async () => {
setIsPromoting(true);
try {
await clearGeneratedThumbnail(shot.id);
setGeneratedUrl(null);
setGeneratedFrom(null);
router.refresh();
} catch (err) {
toast({
title: "Could not clear the render frame",
description: (err as Error).message,
variant: "destructive",
});
} finally {
setIsPromoting(false);
}
};
const formatDate = (d: Date | string | null) => {
if (!d) return "";
return new Date(d).toISOString().split("T")[0];
@@ -452,6 +501,57 @@ export function ShotSettingsTab({ shot, artists, onSaved }: ShotSettingsTabProps
className="hidden"
onChange={handleThumbnailChange}
/>
{/* ── From renders ───────────────────────────────────────────────────
A second, separate still taken from a finished export. It never
replaces the one above — it only shows where there is none — so a
show that ships reference frames keeps them, and a show that ships
none stops rendering empty grids. */}
<div className="pt-4 mt-2 border-t border-border/60 space-y-3">
<div className="flex items-center gap-2 text-xs font-medium text-zinc-400">
<Sparkles className="h-3.5 w-3.5 text-amber-500/70" />
From renders
</div>
{generatedUrl ? (
<div className="flex items-start gap-3">
<div className="relative w-40 aspect-[2.39] rounded-md overflow-hidden border border-border shrink-0">
<Image src={generatedUrl} alt={shot.shotCode} fill className="object-cover" />
</div>
<div className="space-y-2 min-w-0">
<p className="text-xs text-muted-foreground">
{generatedFrom ? <>Taken from <span className="font-mono">{generatedFrom}</span>.</> : "Taken from a render."}{" "}
{thumbnailPreview && !clearThumbnail
? "Not shown anywhere while this shot has a thumbnail of its own."
: "Shown wherever this shot appears, until a thumbnail is uploaded above."}
</p>
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm" onClick={handlePromote} disabled={isPromoting}>
{isPromoting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Refresh from latest"}
</Button>
<Button type="button" variant="ghost" size="sm" onClick={handleClearGenerated} disabled={isPromoting}>
Remove
</Button>
</div>
</div>
</div>
) : (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
Take a frame from this shot&apos;s most recent finished export. Never
replaces the thumbnail above &mdash; it only fills in where there
isn&apos;t one.
</p>
<Button type="button" variant="outline" size="sm" onClick={handlePromote} disabled={isPromoting}>
{isPromoting ? (
<><Loader2 className="h-3.5 w-3.5 animate-spin mr-1.5" /> Fetching&hellip;</>
) : (
"Use latest render frame"
)}
</Button>
</div>
)}
</div>
</div>
{/* References */}
+20 -3
View File
@@ -9,6 +9,7 @@ import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/components/ui/use-toast";
import { updateShotSlate } from "@/actions/shots";
import type { ShotWithDetails } from "@/types";
import { shotThumbnail } from "@/lib/shot-thumbnail";
interface Props {
shot: ShotWithDetails;
@@ -48,10 +49,16 @@ export function ShotSlateTab({ shot, projectName, onSaved }: Props) {
const [slateDescription, setSlateDescription] = useState(shot.slateDescription ?? shot.description ?? "");
const [slateVfxScope, setSlateVfxScope] = useState(shot.slateVfxScope ?? "");
const [slateSubmissionNote, setSlateSubmissionNote] = useState(shot.slateSubmissionNote ?? "");
const [clientCode, setClientCode] = useState(shot.clientCode ?? "");
const today = new Date();
const dateStr = `${today.getFullYear()}/${String(today.getMonth() + 1).padStart(2, "0")}/${String(today.getDate()).padStart(2, "0")}`;
const versionName = `${shot.shotCode}_cmp_TT_${shot.shotVersion ?? "v001"}`;
// Client code, when set, replaces shotCode in what the client actually
// sees (slate, overlay burn-in, delivered names) — just their own naming
// with our version appended, no "_cmp_TT_" studio jargon mixed in.
const versionName = clientCode.trim()
? `${clientCode.trim()}_${shot.shotVersion ?? "v001"}`
: `${shot.shotCode}_cmp_TT_${shot.shotVersion ?? "v001"}`;
const frames =
shot.frameStart != null && shot.frameEnd != null
? String(shot.frameEnd - shot.frameStart + 1)
@@ -65,6 +72,7 @@ export function ShotSlateTab({ shot, projectName, onSaved }: Props) {
slateDescription: slateDescription.trim() || null,
slateVfxScope: slateVfxScope.trim() || null,
slateSubmissionNote: slateSubmissionNote.trim() || null,
clientCode: clientCode.trim() || null,
});
toast({ title: "Slate saved" });
onSaved();
@@ -105,6 +113,15 @@ export function ShotSlateTab({ shot, projectName, onSaved }: Props) {
</SlateRow>
{/* Editable rows */}
<SlateRow label="Client Code">
<Input
value={clientCode}
onChange={(e) => setClientCode(e.target.value)}
placeholder={`Leave blank to use ${shot.shotCode}`}
className="h-7 bg-zinc-900 border-zinc-700 text-sm font-mono text-zinc-100 placeholder:text-zinc-600 placeholder:font-sans"
/>
</SlateRow>
<SlateRow label="Shot Type">
<Input
value={slateType}
@@ -148,9 +165,9 @@ export function ShotSlateTab({ shot, projectName, onSaved }: Props) {
<div className="w-56 shrink-0 flex flex-col">
{/* Thumbnail */}
<div className="aspect-video bg-zinc-900 border-b border-zinc-800 overflow-hidden flex items-center justify-center">
{shot.thumbnailUrl ? (
{shotThumbnail(shot) ? (
<Image
src={shot.thumbnailUrl}
src={shotThumbnail(shot)!}
alt={shot.shotCode}
width={224}
height={126}
+5 -1
View File
@@ -42,7 +42,11 @@ interface KanbanTask {
status: TaskStatus;
priority: string;
dueDate: Date | null;
shot?: { shotCode: string; thumbnailUrl?: string | null } | null;
shot?: {
shotCode: string;
thumbnailUrl?: string | null;
generatedThumbnailUrl?: string | null;
} | null;
asset?: { assetCode: string; name: string } | null;
assignedArtist?: {
id: string;
+11 -4
View File
@@ -19,6 +19,7 @@ import {
import { TaskStatus, TaskType } from "@prisma/client";
import { TASK_STATUS_CONFIG, TASK_TYPE_LABELS } from "./TaskCard";
import { formatDistanceToNow } from "date-fns";
import { shotThumbnail } from "@/lib/shot-thumbnail";
const PRIORITY_DOT: Record<string, string> = {
LOW: "bg-zinc-500",
@@ -34,7 +35,11 @@ interface KanbanTask {
status: TaskStatus;
priority: string;
dueDate: Date | null;
shot?: { shotCode: string; thumbnailUrl?: string | null } | null;
shot?: {
shotCode: string;
thumbnailUrl?: string | null;
generatedThumbnailUrl?: string | null;
} | null;
asset?: { assetCode: string; name: string } | null;
assignedArtist?: { id: string; name: string | null; email: string; image: string | null } | null;
_count?: { versions: number };
@@ -71,11 +76,12 @@ export function KanbanCard({ task, isDragOverlay = false }: KanbanCardProps) {
const contextCode = task.shot?.shotCode ?? task.asset?.assetCode;
// Resolve thumbnail: prefer latest version thumbnail, then shot thumbnail
// Resolve thumbnail: prefer latest version thumbnail, then the shot's own
// (reference frame first, render-derived one only as a fallback).
const thumbnail =
latestVersion?.thumbnailUrl ??
latestVersion?.posterUrl ??
task.shot?.thumbnailUrl ??
shotThumbnail(task.shot) ??
null;
return (
@@ -137,7 +143,8 @@ export function KanbanCard({ task, isDragOverlay = false }: KanbanCardProps) {
</span>
{latestVersion.approvalStatus === "APPROVED" ? (
<CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
) : latestVersion.approvalStatus === "CHANGES_REQUESTED" ? (
) : latestVersion.approvalStatus === "NEEDS_CHANGES" ||
latestVersion.approvalStatus === "REJECTED" ? (
<XCircle className="h-3.5 w-3.5 text-red-500" />
) : (
<Clock className="h-3.5 w-3.5 text-zinc-600" />
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import { DELIVERY_CONFIG_DEFAULT, applyTokens, nextPackageName, tidyPath } from "./deliveries";
const BASE = "260901_Delivery";
describe("nextPackageName", () => {
it("uses the bare base for the first package of the day", () => {
expect(nextPackageName(BASE, [])).toBe(BASE);
});
it("suffixes later packages sharing the base", () => {
expect(nextPackageName(BASE, [BASE])).toBe(`${BASE}_02`);
expect(nextPackageName(BASE, [BASE, `${BASE}_02`])).toBe(`${BASE}_03`);
});
it("never reuses a number after a gap", () => {
expect(nextPackageName(BASE, [BASE, `${BASE}_02`, `${BASE}_04`])).toBe(`${BASE}_05`);
});
it("ignores names that only share a prefix", () => {
expect(nextPackageName(BASE, [`${BASE}_final`, "260902_Delivery"])).toBe(BASE);
});
});
describe("delivery layout", () => {
const tokens = {
deliveryRoot: "//SAN/DELIVERY",
showId: "ACME",
episode: "101",
packageName: BASE,
};
it("separates shows so two shows' episode 101 cannot collide", () => {
const acme = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, tokens);
const other = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, { ...tokens, showId: "BRAVO" });
expect(acme).toBe("//SAN/DELIVERY/ACME/101/260901_Delivery");
expect(other).not.toBe(acme);
});
it("puts producer reviews under the show too", () => {
expect(applyTokens(DELIVERY_CONFIG_DEFAULT.layout.reviewDir, tokens)).toBe(
"//SAN/DELIVERY/ACME/PRODUCER_REVIEWS/260901_Delivery"
);
});
});
describe("tidyPath", () => {
it("drops the empty segment a non-episodic show leaves behind", () => {
const raw = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, {
deliveryRoot: "//SAN/DELIVERY",
showId: "ACME",
episode: "",
packageName: BASE,
});
expect(tidyPath(raw)).toBe("//SAN/DELIVERY/ACME/260901_Delivery");
});
it("keeps the UNC root intact", () => {
expect(tidyPath("//SAN/DELIVERY/ACME")).toBe("//SAN/DELIVERY/ACME");
});
it("leaves a well-formed path alone", () => {
expect(tidyPath("V:/DELIVERY/ACME/101/x")).toBe("V:/DELIVERY/ACME/101/x");
});
});
+95 -9
View File
@@ -1,9 +1,10 @@
import { DeliveryStatus, Prisma } from "@prisma/client";
import { DeliveryKind, DeliveryStatus, Prisma } from "@prisma/client";
import { z } from "zod";
import { db } from "@/lib/db";
import { PipelineError } from "./errors";
import { applyTransition } from "./transitions";
import { getConfigNumber, getConfigValue } from "./config";
import { clientShotCode } from "@/lib/shot-code";
/**
* Delivery builder (RenderPipeline2 §11). The web app decides *what* goes in a
@@ -19,7 +20,14 @@ import { getConfigNumber, getConfigValue } from "./config";
export interface DeliveryConfig {
packageNameTemplate: string;
layout: { packageDir: string; shotDir: string; reportFile: string };
/**
* MOV review packages (§11.6). A formal review is shared as a flat, dated
* folder of preview MOVs, so it gets its own name template and its own
* directory under the delivery root — never mixed in with the episode
* folders that hold shippable EXR packages.
*/
reviewNameTemplate: string;
layout: { packageDir: string; shotDir: string; reportFile: string; reviewDir: string };
deliveryRoot: string;
includeMovs: boolean;
checksumAlgo: string;
@@ -36,10 +44,14 @@ export interface DeliveryConfig {
export const DELIVERY_CONFIG_DEFAULT: DeliveryConfig = {
packageNameTemplate: "{yymmdd}_Delivery",
reviewNameTemplate: "{yyyymmdd}_Producer_review",
layout: {
packageDir: "{deliveryRoot}/{episode}/{packageName}",
// {showId} is not optional in practice: without it every show's episode 101
// lands in one folder on the delivery volume.
packageDir: "{deliveryRoot}/{showId}/{episode}/{packageName}",
shotDir: "{packageDir}/{shotCode}",
reportFile: "{packageDir}/{packageName}_report.csv",
reviewDir: "{deliveryRoot}/{showId}/PRODUCER_REVIEWS/{packageName}",
},
deliveryRoot: "//SAN/DELIVERY",
includeMovs: true,
@@ -98,6 +110,36 @@ export function applyTokens(template: string, tokens: Partial<TokenValues>): str
});
}
/**
* Collapse the empty segment an unset token leaves behind — a non-episodic
* show resolves {episode} to "" and would otherwise build ".../SHOW//NAME".
* The leading pair of a UNC root (//SAN/...) is preserved.
*/
export function tidyPath(path: string): string {
const uncPrefix = /^\/\//.test(path) ? "//" : "";
return uncPrefix + path.slice(uncPrefix.length).replace(/\/{2,}/g, "/").replace(/\/+$/, "");
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Second and later packages sharing a base name get `_02`, `_03`, ... Numbering
* counts every package built under that base — cancelled and failed ones
* included — so a number is never reused for a different folder.
*/
export function nextPackageName(base: string, existingNames: string[]): string {
const pattern = new RegExp(`^${escapeRegExp(base)}(?:_(\\d+))?$`);
let highest = 0;
for (const name of existingNames) {
const match = pattern.exec(name);
if (!match) continue;
highest = Math.max(highest, match[1] ? Number.parseInt(match[1], 10) : 1);
}
return highest === 0 ? base : `${base}_${String(highest + 1).padStart(2, "0")}`;
}
export function dateTokens(date: Date) {
const yyyy = String(date.getFullYear());
const mm = String(date.getMonth() + 1).padStart(2, "0");
@@ -224,7 +266,7 @@ export async function createDeliveryPackage(input: CreateDeliveryInput, userId:
...(input.exportIds?.length ? { id: { in: input.exportIds } } : {}),
...(input.episode ? { shot: { episode: input.episode } } : {}),
},
include: { shot: { select: { id: true, shotCode: true, episode: true } } },
include: { shot: { select: { id: true, shotCode: true, clientCode: true, episode: true } } },
orderBy: { shotId: "asc" },
});
@@ -270,8 +312,17 @@ export async function createDeliveryPackage(input: CreateDeliveryInput, userId:
versionString: "",
packageNumber: String(packageNumber),
};
tokens.packageName = input.options?.name ?? applyTokens(config.packageNameTemplate, tokens);
tokens.packageDir = applyTokens(config.layout.packageDir, tokens);
// A second delivery on the same day is normal — a retake batch, or a client
// asking for the rest of a sequence — and the date-only template gives it a
// name identical to the morning's. Suffix it the way MOV reviews already
// are, so it gets its own folder instead of merging into the first one.
const baseName = applyTokens(config.packageNameTemplate, tokens);
const sameBase = await tx.deliveryPackage.findMany({
where: { projectId: project.id, kind: "EXR_DELIVERY", name: { startsWith: baseName } },
select: { name: true },
});
tokens.packageName = input.options?.name ?? nextPackageName(baseName, sameBase.map((p) => p.name));
tokens.packageDir = tidyPath(applyTokens(config.layout.packageDir, tokens));
const pkg = await tx.deliveryPackage.create({
data: {
@@ -293,6 +344,7 @@ export async function createDeliveryPackage(input: CreateDeliveryInput, userId:
exportId: e.id,
shotId: e.shotId,
shotCode: e.shot.shotCode,
clientCode: e.shot.clientCode,
versionString: e.versionString,
})),
});
@@ -341,12 +393,25 @@ export interface DeliveryManifestItem {
checksum: string | null;
deliveryMovPath: string | null;
shotDir: string;
/**
* `{clientCode}_{versionString}` when the shot has a client code, else the
* studio's own `{shotCode}_cmp_TT_{versionString}` — what the worker names
* the delivered EXR sequence and MOV as, replacing the internal render
* filename it copies from.
*/
deliveredBaseName: string;
/** When validation last ran for this export; null when it never did. */
validatedAt: string | null;
}
export interface DeliveryManifest {
stage: "DELIVERY";
/**
* EXR_DELIVERY builds the per-shot folders of EXRs + MOVs; MOV_REVIEW builds
* a flat folder of preview MOVs only. One job type, one claim path, one
* verification story — the worker branches on this.
*/
kind: DeliveryKind;
packageId: string;
packageName: string;
packageNumber: number;
@@ -393,6 +458,7 @@ export async function buildDeliveryJobManifest(
return {
stage: "DELIVERY",
kind: pkg.kind,
packageId: pkg.id,
packageName: pkg.name,
packageNumber: pkg.packageNumber,
@@ -417,11 +483,16 @@ export async function buildDeliveryJobManifest(
checksum: item.export.checksum,
deliveryMovPath: snapshot.includeMovs ? item.export.deliveryMovPath : null,
validatedAt: item.export.validations[0]?.createdAt.toISOString() ?? null,
// Client code substitutes for shotCode in what the client sees; folder
// naming follows the same rule as the delivered filenames themselves.
shotDir: applyTokens(snapshot.layout.shotDir, {
...baseTokens,
shotCode: item.shotCode,
shotCode: clientShotCode(item),
versionString: item.versionString,
}),
deliveredBaseName: item.clientCode
? `${item.clientCode}_${item.versionString}`
: `${item.shotCode}_cmp_TT_${item.versionString}`,
})),
};
}
@@ -508,7 +579,9 @@ export async function reportDeliveryBuild(jobId: string, body: DeliveryReport) {
const failed = body.items.filter((i) => i.status === "FAILED");
const success = body.ok && failed.length === 0 && verified.length === pkg.items.length;
if (success) {
// A review is not a delivery: the same version is shown in as many reviews
// as it takes, so building one must never advance the Export state machine.
if (success && pkg.kind === "EXR_DELIVERY") {
for (const item of pkg.items) {
const exportRow = await tx.export.findUnique({ where: { id: item.exportId }, select: { id: true, status: true } });
if (exportRow?.status === "READY_FOR_DELIVERY") {
@@ -547,12 +620,18 @@ export async function reportDeliveryBuild(jobId: string, body: DeliveryReport) {
// ── E17 / E19 / cancel ───────────────────────────────────────────────────────
export async function listDeliveryPackages(filter: { projectId?: string; episode?: string; status?: DeliveryStatus }) {
export async function listDeliveryPackages(filter: {
projectId?: string;
episode?: string;
status?: DeliveryStatus;
kind?: DeliveryKind;
}) {
const packages = await db.deliveryPackage.findMany({
where: {
...(filter.projectId ? { projectId: filter.projectId } : {}),
...(filter.episode ? { episode: filter.episode } : {}),
...(filter.status ? { status: filter.status } : {}),
...(filter.kind ? { kind: filter.kind } : {}),
},
orderBy: { createdAt: "desc" },
include: {
@@ -566,6 +645,7 @@ export async function listDeliveryPackages(filter: { projectId?: string; episode
id: p.id,
packageNumber: p.packageNumber,
name: p.name,
kind: p.kind,
episode: p.episode,
status: p.status,
rootPath: p.rootPath,
@@ -593,6 +673,12 @@ export async function markDelivered(packageId: string, userId: string) {
if (pkg.status !== "READY") {
throw new PipelineError(409, `Package is ${pkg.status} — only a READY package can be marked delivered`);
}
if (pkg.kind !== "EXR_DELIVERY") {
throw new PipelineError(
409,
"A MOV review package is shared for review, not delivered — it has no delivered state"
);
}
for (const item of pkg.items) {
const exportRow = await tx.export.findUnique({ where: { id: item.exportId }, select: { id: true, status: true } });
+19
View File
@@ -0,0 +1,19 @@
import { describe, it, expect } from "vitest";
import { renderOutputBase } from "./exports";
import { nextTaskTitle } from "./preview";
describe("renderOutputBase", () => {
it("follows the panel's house convention", () => {
expect(renderOutputBase("UNG_102_019_010", "v001")).toBe("UNG_102_019_010_cmp_TT_v001");
});
// createExport names the comp task it creates after this basename, and
// buildPreviewManifest names the MOV/MP4 off the same call — so a shot queued
// with no task ends up with a task titled exactly like its preview file. The
// title already carries the version, which makes finalizePreview's rename of
// the task to the delivered version a no-op on that first export.
it("gives a freshly created comp task a title finalizePreview leaves alone", () => {
const title = renderOutputBase("UNG_102_019_010", "v003");
expect(nextTaskTitle(title, "v003")).toBe(title);
});
});
+52 -4
View File
@@ -4,6 +4,7 @@ import { PipelineError } from "./errors";
import { describePlateProvenance, renderManifestSchema, type RenderManifest } from "./manifest";
import { applyTransition, type TransitionActor } from "./transitions";
import { getConfigNumber, getConfigValue } from "./config";
import { recalcShotStatus } from "@/lib/shot-status";
/** Statuses in which a shot has a live export in flight (§6.4 E1 409 rule). */
const ACTIVE_STATUSES: ExportStatus[] = [
@@ -48,7 +49,7 @@ function nextExrOutputBase(current: string | null, shotCode: string, versionStri
* shot-code based and deliberately excludes the source clip name that
* `Shot.exrOutput` carries from the EDL import.
*/
function renderOutputBase(shotCode: string, versionString: string): string {
export function renderOutputBase(shotCode: string, versionString: string): string {
return `${shotCode}_cmp_TT_${versionString}`;
}
@@ -89,7 +90,6 @@ export async function createExport(input: CreateExportInput) {
where: { id: manifest.shotId },
include: {
project: { select: { id: true, code: true, showId: true, projectType: true } },
tasks: { where: { type: "COMP" }, orderBy: { sortOrder: "asc" }, take: 1, select: { id: true } },
},
});
if (!shot) throw new PipelineError(404, `Shot not found: ${manifest.shotId}`);
@@ -157,6 +157,43 @@ export async function createExport(input: CreateExportInput) {
const versionString = freshShot.shotVersion ?? formatVersionString(versionNumber);
const exrBase = nextExrOutputBase(freshShot.exrOutput, shot.shotCode, versionString);
// Every Version the pipeline registers hangs off a Task, so a shot with
// no comp task renders fine and then has its preview land nowhere the
// app shows it — the export completes and the artist sees nothing.
// Give the export the task it needs, named after the preview file it
// will produce (the same name the manual batch upload picks, and the
// one finalizePreview's rename keeps in step from here on).
//
// The lookup is repeated inside the transaction because `shot` was read
// before it opened, and because the P2002 retry above re-runs this
// block: a rolled-back attempt takes its task with it.
const existingTask = await tx.task.findFirst({
where: { shotId: shot.id, type: "COMP" },
orderBy: { sortOrder: "asc" },
select: { id: true },
});
let taskId = existingTask?.id ?? null;
let taskCreated = false;
if (!taskId) {
const lastTask = await tx.task.findFirst({
where: { shotId: shot.id },
orderBy: { sortOrder: "desc" },
select: { sortOrder: true },
});
const task = await tx.task.create({
data: {
title: renderOutputBase(shot.shotCode, versionString),
type: "COMP",
shotId: shot.id,
projectId: shot.project.id,
createdById: submittedBy?.id ?? null,
sortOrder: (lastTask?.sortOrder ?? -1) + 1,
},
});
taskId = task.id;
taskCreated = true;
}
// {root}/{showId}/[{episode} for episodic]/{shotCode}/{version}
const showSegment = shot.project.showId || shot.project.code;
const episodeSegment =
@@ -187,7 +224,7 @@ export async function createExport(input: CreateExportInput) {
data: {
shotId: shot.id,
projectId: shot.project.id,
taskId: shot.tasks[0]?.id ?? null,
taskId,
versionNumber,
versionString,
status: "QUEUED",
@@ -248,10 +285,17 @@ export async function createExport(input: CreateExportInput) {
note:
`Queue Export ${versionString}${input.force ? " (force)" : ""}` +
`${input.skipPreview ? " (skip preview)" : ""} — ` +
`${provenance.ok ? "" : "WARNING: "}${provenance.note}`,
`${provenance.ok ? "" : "WARNING: "}${provenance.note}` +
(taskCreated
? ` — shot had no comp task, created "${renderOutputBase(shot.shotCode, versionString)}" for the review version`
: ""),
},
});
if (taskCreated) {
await recalcShotStatus(shot.id, tx);
}
return {
export: {
id: created.id,
@@ -265,6 +309,7 @@ export async function createExport(input: CreateExportInput) {
submissionNote,
},
renderJob: { id: renderJob.id, attempt: renderJob.attempt, priority: renderJob.priority },
task: { id: taskId, created: taskCreated },
shot: { id: shot.id, shotVersion: versionString, exrOutput: exrBase },
superseded: toSupersede.map((s) => s.id),
};
@@ -506,6 +551,9 @@ export async function listExports(filter: ListExportsFilter) {
statusChangedAt: e.statusChangedAt,
createdAt: e.createdAt,
outputDir: e.outputDir,
// Lets the shot's Exports tab offer this export's frame as the shot
// thumbnail (§9.1a) without a second round trip per row.
thumbnailUrl: e.thumbnailKey ? `/api/files/${e.thumbnailKey}` : null,
job: e.renderJobs[0]
? {
id: e.renderJobs[0].id,
+5 -3
View File
@@ -74,9 +74,11 @@ export const renderManifestSchema = z
timingPlate: plateRefSchema.optional(),
plates: z.array(plateRefSchema).optional(),
/**
* Verbatim from the panel's start-frame resolution: "footage metadata"
* (trustworthy) or "API timecode …" (fallback, suspect). Known at queue
* time, so a suspect export is flagged before it burns render hours.
* Verbatim from the panel's start-frame resolution, in the order it
* ranks them: "EXR timecode …" (the plate's own header, best),
* "footage metadata" (AE's read of it, trustworthy) or
* "API timecode …" (fallback, suspect). Known at queue time, so a
* suspect export is flagged before it burns render hours.
*/
startSource: z.string().optional(),
startFrames: z.number().int().optional(),
+26 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { nextTaskTitle } from "./preview";
import { nextTaskTitle, carryApproval } from "./preview";
describe("nextTaskTitle", () => {
it("swaps an existing version suffix", () => {
@@ -30,3 +30,28 @@ describe("nextTaskTitle", () => {
expect(nextTaskTitle("SHOT_cmp_TT_V12", "v013")).toBe("SHOT_cmp_TT_v013");
});
});
describe("carryApproval", () => {
it("carries an approval forward, so a re-export does not reopen a signed-off shot", () => {
expect(carryApproval("APPROVED")).toBe("APPROVED");
});
// The regression: a render queued to address a note used to arrive already
// wearing that note, so nothing registered that the work had been redone.
it("resets NEEDS_CHANGES — this render is the fix for it", () => {
expect(carryApproval("NEEDS_CHANGES")).toBe("PENDING_REVIEW");
});
it("resets REJECTED for the same reason", () => {
expect(carryApproval("REJECTED")).toBe("PENDING_REVIEW");
});
it("leaves an unreviewed version pending", () => {
expect(carryApproval("PENDING_REVIEW")).toBe("PENDING_REVIEW");
});
it("defaults to pending when there is no previous version", () => {
expect(carryApproval(null)).toBe("PENDING_REVIEW");
expect(carryApproval(undefined)).toBe("PENDING_REVIEW");
});
});
+113 -14
View File
@@ -1,9 +1,12 @@
import { ExportStatus, Prisma } from "@prisma/client";
import { ApprovalStatus, ExportStatus, Prisma } from "@prisma/client";
import { db } from "@/lib/db";
import { PipelineError } from "./errors";
import { applyTransition } from "./transitions";
import { getConfigNumber, getPreviewConfig } from "./config";
import { resolveProjectTemplates } from "./project-templates";
import { resolveProjectTemplates, autoShotThumbnailEnabled } from "./project-templates";
import { clientShotCode } from "@/lib/shot-code";
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
import { renderOutputBase } from "./exports";
/** Slate date format used by the panel's getDateString (YYYY/MM/DD). */
function slateDate(d = new Date()): string {
@@ -73,6 +76,7 @@ export async function buildPreviewManifest(exportRow: ExportForPreview): Promise
where: { id: exportRow.shotId },
select: {
shotCode: true,
clientCode: true,
episode: true,
scene: true,
description: true,
@@ -88,7 +92,15 @@ export async function buildPreviewManifest(exportRow: ExportForPreview): Promise
// above all its own show LUT. Falling back to another show's would render a
// preview that is quietly the wrong colour.
const templates = await resolveProjectTemplates(shot.project);
const base = `${shot.shotCode}_cmp_TT_${exportRow.versionString}`;
// Shared with createExport, which names the shot's comp task after this
// basename when it has to create one: the task and the file it holds must
// not drift apart.
const base = renderOutputBase(shot.shotCode, exportRow.versionString);
// Client code, when set, replaces shotCode in everything the client sees —
// slate identity and (via ctx.slate.versionName) the overlay burn-in — but
// never in internal paths: movOutput/mp4Output below stay on `base`. Just
// their own naming with our version appended, no "_cmp_TT_" studio jargon.
const clientBase = shot.clientCode ? `${shot.clientCode}_${exportRow.versionString}` : base;
return {
stage: "PREVIEW",
@@ -111,14 +123,14 @@ export async function buildPreviewManifest(exportRow: ExportForPreview): Promise
slateScopeProp: cfg.slateScopeProp,
slateSubmissionProp: cfg.slateSubmissionProp,
slate: {
versionName: base,
versionName: clientBase,
date: slateDate(),
// The slate's own description is authored on the Shot's Slate tab and
// falls back to the general shot description — the same precedence the
// tab shows as its placeholder.
description: shot.slateDescription ?? shot.description,
notes: shot.notes,
shotCode: shot.shotCode,
shotCode: clientShotCode(shot),
// The production's own name, not its code: this is read off a slate.
show: shot.project?.name ?? shot.project?.code ?? null,
episode: shot.episode,
@@ -250,6 +262,22 @@ export async function createPreviewJob(
});
}
/**
* What approval a pipeline-created Version inherits from the one it supersedes.
*
* Only APPROVED carries. A re-export re-renders EXRs for delivery from a shot
* that has usually already been signed off, and defaulting to PENDING_REVIEW
* would make an approved shot silently reappear as awaiting review.
*
* The rejecting verdicts are the opposite case: NEEDS_CHANGES and REJECTED
* describe the version someone asked to be fixed, and the render coming through
* here is the fix. Carrying them forward left every re-render wearing the note
* that prompted it, so nothing in the app registered that the work was redone.
*/
export function carryApproval(previous: ApprovalStatus | null | undefined): ApprovalStatus {
return previous === "APPROVED" ? "APPROVED" : "PENDING_REVIEW";
}
/**
* `UNG_102_019_010_cmp_TT_v004` + v005 → `UNG_102_019_010_cmp_TT_v005`.
* Mirrors `nextExrOutputBase` (exports.ts) so the task title, the EXR base and
@@ -319,6 +347,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
let versionId: string | null = null;
let versionReplaced = false;
let versionCreated = false;
let inheritedApproval: string | null = null;
if (artifacts.previewMovKey) {
const mediaFields = {
@@ -351,12 +380,6 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
// Version numbering stays monotonic for the task (existing review flows
// rely on the newest version having the highest number) while matching
// the export version whenever it is ahead.
// A re-export does not change the picture — it re-renders EXRs for
// delivery from a shot that has usually already been approved. A fresh
// Version defaults to PENDING_REVIEW, which is what the dashboard, the
// shot page and the client portal all read, so an approved shot would
// silently reappear as awaiting review. The approval carries over from
// the version this one supersedes.
const previousLatest = exportRow.taskId
? await tx.version.findFirst({
where: { taskId: exportRow.taskId },
@@ -364,6 +387,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
select: { approvalStatus: true, versionNumber: true },
})
: null;
const carriedApproval = carryApproval(previousLatest?.approvalStatus);
const taskMax = exportRow.taskId
? await tx.version.aggregate({
@@ -384,13 +408,14 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
// client portal, so the pipeline stays out of it. What this version
// is and where it came from lives on the Export and its timeline,
// which is where someone would go looking anyway.
approvalStatus: previousLatest?.approvalStatus ?? "PENDING_REVIEW",
approvalStatus: carriedApproval,
isLatest: true,
isClientVisible: false, // never shared to the client portal (§10.0)
},
});
versionId = version.id;
inheritedApproval = previousLatest?.approvalStatus ?? null;
versionCreated = true;
inheritedApproval = carriedApproval;
}
if (exportRow.taskId) {
@@ -401,6 +426,44 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
}
}
// Promote the render frame onto the shot, for shows that opted in.
//
// Only `generatedThumbnailUrl` is written — `thumbnailUrl` holds the
// reference frame that came with the brief and the pipeline never touches
// it. Shows that supply stills therefore look exactly as they did; shows
// that supply none get their empty grids filled from the renders instead.
//
// Every outcome is recorded on the export timeline, including the ones that
// did nothing: silence here is indistinguishable from a broken worker, a
// project whose flag never saved, and a feature working as configured.
let thumbnailNote: string;
if (!artifacts.thumbnailKey) {
thumbnailNote =
" — no thumbnail in this render, so the shot's was left alone " +
"(the worker reported no thumbnail: check ffmpegPath in its config.json)";
} else {
const shot = await tx.shot.findUnique({
where: { id: exportRow.shotId },
select: { project: { select: { pipelineConfig: true } } },
});
if (!shot) {
thumbnailNote = " — shot not found, thumbnail not applied";
} else if (!autoShotThumbnailEnabled(shot.project)) {
thumbnailNote =
" — shot thumbnail left alone (this project has \"Use render frames as " +
"shot thumbnails\" turned off)";
} else {
await tx.shot.update({
where: { id: exportRow.shotId },
data: {
generatedThumbnailUrl: `/api/files/${artifacts.thumbnailKey}`,
generatedThumbnailFrom: exportRow.versionString,
},
});
thumbnailNote = " — shot thumbnail updated from this render";
}
}
// The task title carries the version it is showing (house convention:
// "UNG_102_019_010_cmp_TT_v004"). The preview just uploaded *is* the task's
// new latest version, so the title has to follow the file — the same rename
@@ -424,6 +487,40 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
}
}
// A genuinely new version is new work awaiting review, so the task moves the
// same way a manual upload moves it (actions/versions.ts, batch-upload) —
// otherwise a task left on CHANGES by a review or a QC fail stays there
// through every re-render, and the shot stays on REVISIONS with no way out
// but a manual kanban drag.
//
// A *replaced* version is deliberately excluded: regeneratePreview
// re-delivers the same version after a slate fix, and that is not a new
// submission. Nor is an already-approved carry-over, which would drag a
// signed-off shot back into review.
let taskStatusMoved = false;
let approvalCleared = false;
if (versionCreated && exportRow.taskId && inheritedApproval !== "APPROVED") {
const task = await tx.task.findUnique({
where: { id: exportRow.taskId },
select: { status: true },
});
if (task && task.status !== "INTERNAL_REVIEW") {
await tx.task.update({
where: { id: exportRow.taskId },
data: { status: "INTERNAL_REVIEW" },
});
taskStatusMoved = true;
}
approvalCleared = await clearStaleShotApproval(tx, exportRow.shotId);
}
// Shot.status is derived from task states (lib/shot-status.ts); nothing in
// the pipeline recalculated it, so shot boards went stale the moment a
// render changed a task.
if (taskStatusMoved || approvalCleared) {
await recalcShotStatus(exportRow.shotId, tx);
}
const updated = await applyTransition(
tx,
exportRow,
@@ -438,7 +535,9 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
? " — review version media replaced"
: ` — review version created (${inheritedApproval ?? "PENDING_REVIEW"})`
: " — no preview media reported") +
(taskRenamed ? ` — task renamed to ${taskTitle}` : ""),
(taskRenamed ? ` — task renamed to ${taskTitle}` : "") +
(taskStatusMoved ? " — task moved to INTERNAL_REVIEW" : "") +
thumbnailNote,
},
{
...(versionId ? { versionId } : {}),
+29 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { conventionalNames } from "./project-templates";
import { conventionalNames, autoShotThumbnailEnabled } from "./project-templates";
/**
* The convention has to reproduce UNG's existing comp names exactly, or
@@ -32,3 +32,31 @@ describe("conventionalNames", () => {
expect(conventionalNames("").overlayComp).toBe("SHOW_VFX_OVERLAY");
});
});
/**
* The flag decides whether finished renders start writing shot thumbnails, so
* anything short of an explicit `true` has to leave shots alone — a malformed
* config in particular, which must not be read as consent.
*/
describe("autoShotThumbnailEnabled", () => {
it("is on only when explicitly enabled", () => {
expect(autoShotThumbnailEnabled({ pipelineConfig: { autoShotThumbnail: true } })).toBe(true);
});
it("defaults to off", () => {
expect(autoShotThumbnailEnabled({ pipelineConfig: {} })).toBe(false);
expect(autoShotThumbnailEnabled({ pipelineConfig: null })).toBe(false);
expect(autoShotThumbnailEnabled({})).toBe(false);
expect(autoShotThumbnailEnabled({ pipelineConfig: { autoShotThumbnail: false } })).toBe(false);
});
it("stays off when the config is malformed", () => {
expect(autoShotThumbnailEnabled({ pipelineConfig: { autoShotThumbnail: "yes" } })).toBe(false);
expect(autoShotThumbnailEnabled({ pipelineConfig: "not an object" })).toBe(false);
});
it("does not disturb the other settings it shares a column with", () => {
const cfg = { pipelineConfig: { templateAep: "X:/show.aep", autoShotThumbnail: true } };
expect(autoShotThumbnailEnabled(cfg)).toBe(true);
});
});
+20
View File
@@ -27,6 +27,16 @@ export const pipelineConfigSchema = z.object({
/** AE output-module templates, when this show does not use the studio defaults. */
movTemplate: z.string().max(200).optional().nullable(),
mp4Template: z.string().max(200).optional().nullable(),
/**
* Promote each finished export's thumbnail onto its shot
* (`Shot.generatedThumbnailUrl`). Off by default and deliberately per-show:
* productions that ship a still with every shot already have a reference
* frame, and the renders should not compete with it. Turn it on for shows
* that arrive with no stills at all, where an empty grid is the alternative.
*
* Never touches `Shot.thumbnailUrl` — see lib/shot-thumbnail.ts.
*/
autoShotThumbnail: z.boolean().optional().nullable(),
});
export type PipelineConfigInput = z.infer<typeof pipelineConfigSchema>;
@@ -55,6 +65,16 @@ export function conventionalNames(showId: string) {
};
}
/**
* Whether finished exports promote their thumbnail onto the shot. Defaults to
* false, including when `pipelineConfig` is malformed — a broken config must
* not start rewriting shot thumbnails.
*/
export function autoShotThumbnailEnabled(project: { pipelineConfig?: unknown }): boolean {
const parsed = pipelineConfigSchema.safeParse(project.pipelineConfig ?? {});
return parsed.success ? parsed.data.autoShotThumbnail === true : false;
}
export async function resolveProjectTemplates(project: {
showId: string | null;
code: string;
+4
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { db } from "@/lib/db";
import { PipelineError } from "./errors";
import { applyTransition } from "./transitions";
import { recalcShotStatus } from "@/lib/shot-status";
/**
* QC workflow (RenderPipeline2 §10) — technical/final-delivery QC on shots the
@@ -104,6 +105,9 @@ export async function submitQCReview(exportId: string, input: QCSubmitInput, act
if (task && task.status !== "CHANGES") {
await tx.task.update({ where: { id: task.id }, data: { status: "CHANGES" } });
taskUpdated = { id: task.id, status: "CHANGES" };
// Shot.status is derived from its tasks and does not recompute on its
// own, so without this the shot never actually reached REVISIONS.
await recalcShotStatus(exportRow.shotId, tx);
}
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, it, expect } from "vitest";
import { nextReviewName, reviewMovName } from "./reviews";
/**
* Review folders are named by date, and several reviews a day are normal —
* a morning pass and an afternoon one land in the same studio's inbox, so the
* numbering has to be unambiguous about which came first.
*/
describe("nextReviewName", () => {
const BASE = "20260828_Producer_review";
it("leaves the first review of the day unnumbered", () => {
expect(nextReviewName(BASE, [])).toBe(BASE);
});
it("numbers from _02 once the plain name is taken", () => {
expect(nextReviewName(BASE, [BASE])).toBe(`${BASE}_02`);
expect(nextReviewName(BASE, [BASE, `${BASE}_02`])).toBe(`${BASE}_03`);
});
it("counts from the highest number, not the count", () => {
// A cancelled _02 still holds its number: reusing it would give two
// different folders the same name in the delivery history.
expect(nextReviewName(BASE, [BASE, `${BASE}_02`, `${BASE}_04`])).toBe(`${BASE}_05`);
});
it("picks up numbering even when the plain name was never used", () => {
expect(nextReviewName(BASE, [`${BASE}_02`])).toBe(`${BASE}_03`);
});
it("ignores names that merely start with the base", () => {
// A hand-named "…_review_final" is somebody's own folder, not part of
// this sequence, and must not push the number along.
expect(nextReviewName(BASE, [`${BASE}_final`, `${BASE}_02x`])).toBe(BASE);
});
it("does not confuse another day's reviews", () => {
expect(nextReviewName(BASE, ["20260827_Producer_review_03"])).toBe(BASE);
});
it("treats the base as a literal, not a pattern", () => {
const dotted = "2026.08.28_review";
expect(nextReviewName(dotted, ["2026x08x28_review"])).toBe(dotted);
});
});
describe("reviewMovName", () => {
const SOURCE = "//SAN/renders/UNG_106_010_020/v004/UNG_106_010_020_cmp_TT_v004.mov";
it("uses the client's own naming when the production supplies it", () => {
expect(reviewMovName({ shotCode: "UNG_106_010_020", clientCode: "EP6_VFX_012" }, "v004", SOURCE)).toBe(
"EP6_VFX_012_v004.mov"
);
});
it("falls back to the studio convention", () => {
expect(reviewMovName({ shotCode: "UNG_106_010_020", clientCode: null }, "v004", SOURCE)).toBe(
"UNG_106_010_020_cmp_TT_v004.mov"
);
});
it("ignores a whitespace-only client code", () => {
expect(reviewMovName({ shotCode: "UNG_106_010_020", clientCode: " " }, "v004", SOURCE)).toBe(
"UNG_106_010_020_cmp_TT_v004.mov"
);
});
it("keeps whatever extension the source actually has", () => {
expect(
reviewMovName({ shotCode: "UNG_106_010_020", clientCode: null }, "v004", "//SAN/a/b_v004.mxf")
).toBe("UNG_106_010_020_cmp_TT_v004.mxf");
});
it("does not mistake a dot in a folder name for an extension", () => {
expect(
reviewMovName({ shotCode: "UNG_106_010_020", clientCode: null }, "v004", "//SAN/v1.2/rendered_mov")
).toBe("UNG_106_010_020_cmp_TT_v004.mov");
});
});
+413
View File
@@ -0,0 +1,413 @@
import { Prisma } from "@prisma/client";
import { z } from "zod";
import { db } from "@/lib/db";
import { PipelineError } from "./errors";
import { getConfigNumber } from "./config";
import {
applyTokens,
dateTokens,
nextPackageName,
resolveDeliveryConfig,
tidyPath,
type DeliveryConfig,
type DeliveryManifest,
type TokenValues,
} from "./deliveries";
/**
* MOV review packages (RenderPipeline2 §11.6).
*
* A formal review is shared as a flat, dated folder of the preview MOVs —
* `20260828_Producer_review`, `_02` for the second one that day. It is built by
* the same worker, through the same queue and the same claim path, as an EXR
* delivery; only the shape of what lands on disk differs.
*
* The one rule that separates it from a delivery: **a review never advances an
* Export**. Reviews happen throughout a shot's life, long before QC passes it,
* and the same version is routinely shown twice. So there is no eligibility
* gate beyond "this version has a MOV", and nothing is marked PACKAGED or
* DELIVERED when the folder is built.
*/
// ── Which version of each shot gets reviewed ─────────────────────────────────
export interface ReviewCandidate {
shotId: string;
shotCode: string;
clientCode: string | null;
episode: string;
exportId: string;
versionString: string;
versionNumber: number;
status: string;
deliveryMovPath: string;
/** What the MOV is named in the review folder. */
deliveredName: string;
frameStart: number;
frameEnd: number;
}
export interface ReviewSkip {
shotId: string;
shotCode: string;
reason: string;
}
/**
* `{clientCode}_{versionString}` when the production supplies its own naming,
* else the studio's `{shotCode}_cmp_TT_{versionString}` — the same rule the EXR
* delivery names its files by, so a shot reads identically in a review folder
* and in the delivery that follows it.
*/
export function reviewMovName(
shot: { shotCode: string; clientCode: string | null },
versionString: string,
sourcePath: string
): string {
const base = shot.clientCode?.trim()
? `${shot.clientCode.trim()}_${versionString}`
: `${shot.shotCode}_cmp_TT_${versionString}`;
const dot = sourcePath.lastIndexOf(".");
const slash = Math.max(sourcePath.lastIndexOf("/"), sourcePath.lastIndexOf("\\"));
const ext = dot > slash ? sourcePath.slice(dot) : ".mov";
return `${base}${ext}`;
}
/**
* The newest export of each shot that actually has a delivery MOV on the SAN.
*
* Newest-with-a-MOV rather than newest outright: a shot whose latest version is
* still rendering should go into the review as the version that can be watched,
* not be dropped from it. Shots with no MOV at all come back in `skipped` so
* the caller can say which ones and why rather than silently shipping fewer.
*/
export async function resolveReviewCandidates(shotIds: string[]) {
if (shotIds.length === 0) {
throw new PipelineError(422, "No shots selected");
}
const shots = await db.shot.findMany({
where: { id: { in: shotIds } },
select: {
id: true,
shotCode: true,
clientCode: true,
episode: true,
projectId: true,
project: { select: { id: true, name: true, code: true, showId: true, deliveryConfig: true } },
},
});
if (shots.length === 0) throw new PipelineError(404, "No such shots");
const projectIds = [...new Set(shots.map((s) => s.projectId))];
if (projectIds.length > 1) {
// Delivery roots and naming templates are per project; one folder cannot
// honour two of them.
throw new PipelineError(422, "Selected shots span more than one project — review one project at a time");
}
const exports = await db.export.findMany({
where: {
shotId: { in: shots.map((s) => s.id) },
deliveryMovPath: { not: null },
status: { notIn: ["CANCELLED"] },
},
orderBy: [{ shotId: "asc" }, { versionNumber: "desc" }],
select: {
id: true,
shotId: true,
versionString: true,
versionNumber: true,
status: true,
deliveryMovPath: true,
frameStart: true,
frameEnd: true,
},
});
const newestPerShot = new Map<string, (typeof exports)[number]>();
for (const e of exports) {
if (!newestPerShot.has(e.shotId)) newestPerShot.set(e.shotId, e);
}
const candidates: ReviewCandidate[] = [];
const skipped: ReviewSkip[] = [];
for (const shot of shots) {
const chosen = newestPerShot.get(shot.id);
if (!chosen?.deliveryMovPath) {
skipped.push({
shotId: shot.id,
shotCode: shot.shotCode,
reason: "no preview MOV rendered yet",
});
continue;
}
candidates.push({
shotId: shot.id,
shotCode: shot.shotCode,
clientCode: shot.clientCode,
episode: shot.episode ?? "",
exportId: chosen.id,
versionString: chosen.versionString,
versionNumber: chosen.versionNumber,
status: chosen.status,
deliveryMovPath: chosen.deliveryMovPath,
deliveredName: reviewMovName(shot, chosen.versionString, chosen.deliveryMovPath),
frameStart: chosen.frameStart,
frameEnd: chosen.frameEnd,
});
}
candidates.sort((a, b) => a.shotCode.localeCompare(b.shotCode));
skipped.sort((a, b) => a.shotCode.localeCompare(b.shotCode));
return { project: shots[0].project, candidates, skipped };
}
// ── Folder naming ────────────────────────────────────────────────────────────
/**
* `20260828_Producer_review`, then `_02`, `_03` for further reviews the same
* day. EXR deliveries now number the same way, so the rule lives in
* deliveries.ts; this name is kept because it reads better at the call site.
*/
export const nextReviewName = nextPackageName;
async function reviewNameFor(
tx: Prisma.TransactionClient | typeof db,
projectId: string,
base: string
): Promise<string> {
const existing = await tx.deliveryPackage.findMany({
where: { projectId, kind: "MOV_REVIEW", name: { startsWith: base } },
select: { name: true },
});
return nextReviewName(base, existing.map((p) => p.name));
}
function reviewTokens(
config: DeliveryConfig,
project: { code: string; showId: string | null },
episode: string,
buildDate: Date,
packageNumber: number
): TokenValues {
return {
showId: project.showId || project.code,
episode,
...dateTokens(buildDate),
packageName: "",
packageDir: "",
deliveryRoot: config.deliveryRoot,
shotCode: "",
versionString: "",
packageNumber: String(packageNumber),
};
}
/**
* The episode a review folder belongs to: the one every selected shot shares,
* or "" when the review spans several. It is a label on the record only —
* unlike an EXR package, the folder path never includes it.
*/
function commonEpisode(candidates: ReviewCandidate[]): string {
const episodes = new Set(candidates.map((c) => c.episode));
return episodes.size === 1 ? [...episodes][0] : "";
}
// ── Preview: what would this build ───────────────────────────────────────────
/**
* What the dialog shows before anyone commits: the folder that would be
* created, the version each shot resolves to, and the shots that have no MOV.
* The name is what it would be *right now* — another review built in between
* takes the number and this one moves up.
*/
export async function previewMovReviewPackage(shotIds: string[]) {
const { project, candidates, skipped } = await resolveReviewCandidates(shotIds);
const config = await resolveDeliveryConfig(project.deliveryConfig);
const buildDate = new Date();
const tokens = reviewTokens(config, project, commonEpisode(candidates), buildDate, 0);
const base = applyTokens(config.reviewNameTemplate, tokens);
tokens.packageName = await reviewNameFor(db, project.id, base);
tokens.packageDir = tidyPath(applyTokens(config.layout.reviewDir, tokens));
return {
projectId: project.id,
projectName: project.name,
packageName: tokens.packageName,
packageDir: tokens.packageDir,
candidates,
skipped,
};
}
// ── Create ───────────────────────────────────────────────────────────────────
export const createMovReviewSchema = z.object({
shotIds: z.array(z.string().min(1)).min(1).max(500),
options: z
.object({
/** Override the dated name entirely, e.g. for a re-share under an agreed folder name. */
name: z.string().max(120).optional(),
copyMode: z.enum(["auto", "always-copy"]).optional(),
})
.optional(),
});
export type CreateMovReviewInput = z.infer<typeof createMovReviewSchema>;
/**
* Build a MOV review package from selected shots. Shots without a MOV are
* skipped and reported rather than failing the build — a producer asking for a
* review of 15 shots wants the 13 that exist, plus a clear list of the 2 that
* do not.
*/
export async function createMovReviewPackage(input: CreateMovReviewInput, userId: string) {
const { project, candidates, skipped } = await resolveReviewCandidates(input.shotIds);
if (candidates.length === 0) {
throw new PipelineError(422, "None of the selected shots has a preview MOV yet — nothing to review");
}
const config = await resolveDeliveryConfig(project.deliveryConfig);
if (input.options?.copyMode) config.copyMode = input.options.copyMode;
const buildDate = new Date();
const maxAttempts = await getConfigNumber("render.maxAttempts");
const episode = commonEpisode(candidates);
return db.$transaction(async (tx) => {
const lastNumber = await tx.deliveryPackage.aggregate({
where: { projectId: project.id },
_max: { packageNumber: true },
});
const packageNumber = (lastNumber._max.packageNumber ?? 0) + 1;
const tokens = reviewTokens(config, project, episode, buildDate, packageNumber);
const base = applyTokens(config.reviewNameTemplate, tokens);
tokens.packageName = input.options?.name ?? (await reviewNameFor(tx, project.id, base));
tokens.packageDir = tidyPath(applyTokens(config.layout.reviewDir, tokens));
const pkg = await tx.deliveryPackage.create({
data: {
projectId: project.id,
kind: "MOV_REVIEW",
episode,
name: tokens.packageName,
packageNumber,
status: "QUEUED",
rootPath: tokens.packageDir,
configSnapshot: { ...config, tokens } as unknown as Prisma.InputJsonValue,
createdById: userId,
},
});
// Same version lock as a delivery: shotCode, clientCode and versionString
// are copied in, so a later rename or re-render cannot rewrite what this
// review was.
await tx.deliveryItem.createMany({
data: candidates.map((c) => ({
packageId: pkg.id,
exportId: c.exportId,
shotId: c.shotId,
shotCode: c.shotCode,
clientCode: c.clientCode,
versionString: c.versionString,
})),
});
const manifest = await buildMovReviewJobManifest(tx, pkg.id);
const job = await tx.renderJob.create({
data: {
type: "DELIVERY_BUILD",
deliveryId: pkg.id,
attempt: 1,
maxAttempts,
// Same reasoning as a delivery build: someone is waiting on the folder
// and no After Effects is involved, so it jumps the render queue.
priority: 10,
manifest: manifest as unknown as Prisma.InputJsonValue,
},
});
return {
package: {
id: pkg.id,
kind: pkg.kind,
name: pkg.name,
packageNumber,
episode,
status: pkg.status,
rootPath: pkg.rootPath,
itemCount: candidates.length,
},
skipped,
renderJob: { id: job.id },
};
});
}
// ── The MOV_REVIEW manifest ──────────────────────────────────────────────────
/**
* The DELIVERY_BUILD manifest for a review: the same envelope the EXR builder
* gets, with `kind: "MOV_REVIEW"` and one MOV per item. Every item's `shotDir`
* is the package folder itself — a review is flat, so the MOVs sit beside each
* other where a producer can scrub through them in order.
*/
export async function buildMovReviewJobManifest(
tx: Prisma.TransactionClient,
packageId: string
): Promise<DeliveryManifest> {
const pkg = await tx.deliveryPackage.findUniqueOrThrow({
where: { id: packageId },
include: {
items: { include: { export: true } },
project: { select: { code: true, showId: true } },
},
});
const snapshot = pkg.configSnapshot as unknown as DeliveryConfig & { tokens: TokenValues };
const packageDir = pkg.rootPath ?? snapshot.tokens.packageDir;
return {
stage: "DELIVERY",
kind: "MOV_REVIEW",
packageId: pkg.id,
packageName: pkg.name,
packageNumber: pkg.packageNumber,
episode: pkg.episode,
packageDir,
// A review folder is exactly the MOVs — no CSV, no manifest.json dropped
// in beside them. The manifest still comes back to the server, so the
// record of what was shared is kept without cluttering what is shared.
reportFile: "",
includeMovs: true,
copyMode: snapshot.copyMode ?? "auto",
verifyMode: snapshot.verifyMode ?? "auto",
checksumAlgo: snapshot.checksumAlgo,
reportFormats: [],
items: pkg.items.map((item) => ({
itemId: item.id,
exportId: item.exportId,
shotCode: item.shotCode,
versionString: item.versionString,
// No EXR sequence is involved, so the fields that describe one are empty
// rather than misleadingly populated.
sourceDir: "",
outputPattern: "",
frameStart: item.export.frameStart,
frameEnd: item.export.frameEnd,
fileCount: null,
checksum: null,
deliveryMovPath: item.export.deliveryMovPath,
shotDir: packageDir,
deliveredBaseName: item.clientCode
? `${item.clientCode}_${item.versionString}`
: `${item.shotCode}_cmp_TT_${item.versionString}`,
validatedAt: null,
})),
};
}
+66
View File
@@ -0,0 +1,66 @@
import { describe, it, expect, vi } from "vitest";
// Mock Prisma so the pure helpers can be tested without a database.
vi.mock("@/lib/db", () => ({ db: {} }));
import { reviewClientEmail, ownsComment } from "./review-auth";
import type { ReviewSession } from "@prisma/client";
const session = (email: string | null): ReviewSession =>
({ email, label: null } as ReviewSession);
describe("reviewClientEmail", () => {
it("uses the session's own email when it has one", () => {
expect(reviewClientEmail(session("dailies@client.com"), "tok123456789")).toBe(
"dailies@client.com"
);
});
it("falls back to a token-derived address when it has none", () => {
expect(reviewClientEmail(session(null), "tok123456789")).toBe(
"client+tok12345@review.external"
);
});
// Identity has to be stable across requests, or a reviewer would stop owning
// the notes they wrote a minute ago.
it("is stable for the same token", () => {
const a = reviewClientEmail(session(null), "tok123456789");
const b = reviewClientEmail(session(null), "tok123456789");
expect(a).toBe(b);
});
it("separates two different review links", () => {
expect(reviewClientEmail(session(null), "aaaaaaaaaaaa")).not.toBe(
reviewClientEmail(session(null), "bbbbbbbbbbbb")
);
});
});
describe("ownsComment", () => {
it("lets a reviewer edit their own note", () => {
expect(ownsComment({ authorId: "u1" }, "u1")).toBe(true);
});
it("refuses another author's note", () => {
expect(ownsComment({ authorId: "u2" }, "u1")).toBe(false);
});
// The studio's notes reach the portal in the same list; they must stay
// read-only there.
it("refuses a note written by an internal user", () => {
expect(ownsComment({ authorId: "supervisor-id" }, "client-id")).toBe(false);
});
it("refuses when the reviewer has never posted, so has no identity yet", () => {
expect(ownsComment({ authorId: "u1" }, undefined)).toBe(false);
expect(ownsComment({ authorId: "u1" }, null)).toBe(false);
});
// An authorless comment (its User row was deleted — Comment.authorId is
// SetNull) belongs to nobody and must not become claimable.
it("refuses an authorless note rather than letting it be claimed", () => {
expect(ownsComment({ authorId: null }, "u1")).toBe(false);
expect(ownsComment({ authorId: null }, null)).toBe(false);
});
});
+59
View File
@@ -32,3 +32,62 @@ export async function validateReviewToken(
return { type: "ok", session };
}
/**
* The email a review session writes its activity under.
*
* A session with no email on it still needs a stable identity so its comments
* group under one author and stay attributable to that link — hence the
* token-derived fallback. Note what this means for ownership: everyone holding
* the same review link *is* the same author. That is the intended scope, since
* the link is the credential.
*/
export function reviewClientEmail(session: ReviewSession, token: string): string {
return session.email ?? `client+${token.slice(0, 8)}@review.external`;
}
/** The guest User a review session posts as, creating it on first activity. */
export async function getOrCreateReviewUser(session: ReviewSession, token: string) {
const email = reviewClientEmail(session, token);
const existing = await db.user.findUnique({ where: { email } });
if (existing) return existing;
return db.user.create({
data: {
email,
name: session.label ?? email.split("@")[0],
role: "CLIENT",
isActive: true,
},
});
}
/**
* The guest User a review session posts as, or null if it has never posted.
*
* Read-only counterpart to getOrCreateReviewUser, for the paths that only need
* to ask "is this theirs?" — merely opening a review link should not conjure a
* User row.
*/
export async function findReviewUser(session: ReviewSession, token: string) {
return db.user.findUnique({
where: { email: reviewClientEmail(session, token) },
select: { id: true },
});
}
/**
* May this review session change or remove this comment?
*
* Only its own. The studio's notes and those of every other review session are
* read-only through a client link, and an authorless comment (its User was
* deleted) belongs to nobody and so cannot be claimed.
*
* Shared by the listing route, which uses it to decide whether to offer the
* controls, and the edit/delete route, which enforces it.
*/
export function ownsComment(
comment: { authorId: string | null },
reviewUserId: string | null | undefined
): boolean {
return !!reviewUserId && !!comment.authorId && comment.authorId === reviewUserId;
}
+45
View File
@@ -0,0 +1,45 @@
import { describe, it, expect } from "vitest";
import { clientShotCode, clientTaskTitle } from "./shot-code";
describe("clientShotCode", () => {
it("prefers the client's alias", () => {
expect(clientShotCode({ shotCode: "UNG_106_010_020", clientCode: "EP6_VFX_012" })).toBe("EP6_VFX_012");
});
it("falls back to our code when there is no alias", () => {
expect(clientShotCode({ shotCode: "UNG_106_010_020", clientCode: null })).toBe("UNG_106_010_020");
expect(clientShotCode({ shotCode: "UNG_106_010_020" })).toBe("UNG_106_010_020");
});
it("ignores a whitespace-only alias", () => {
expect(clientShotCode({ shotCode: "UNG_106_010_020", clientCode: " " })).toBe("UNG_106_010_020");
});
});
describe("clientTaskTitle", () => {
const shot = { shotCode: "UNG_106_010_020", clientCode: "EP6_VFX_012" };
it("swaps the internal code out of a house-convention title", () => {
expect(clientTaskTitle("UNG_106_010_020_cmp_TT_v004", shot)).toBe("EP6_VFX_012_cmp_TT_v004");
});
it("leaves the title alone when there is no alias", () => {
const t = "UNG_106_010_020_cmp_TT_v004";
expect(clientTaskTitle(t, { shotCode: "UNG_106_010_020", clientCode: null })).toBe(t);
});
it("leaves a title that does not carry the code untouched", () => {
// Hand-edited titles are not guessed at — better an unhelpful title than a
// mangled one.
expect(clientTaskTitle("Roto pass", shot)).toBe("Roto pass");
});
it("swaps every occurrence", () => {
expect(clientTaskTitle("UNG_106_010_020 / UNG_106_010_020_cmp", shot)).toBe("EP6_VFX_012 / EP6_VFX_012_cmp");
});
it("is a no-op when the alias equals the code", () => {
const same = { shotCode: "UNG_106_010_020", clientCode: "UNG_106_010_020" };
expect(clientTaskTitle("UNG_106_010_020_cmp", same)).toBe("UNG_106_010_020_cmp");
});
});
+41
View File
@@ -0,0 +1,41 @@
/**
* What a client is shown for a shot.
*
* `Shot.clientCode` is the naming alias some productions supply — their own
* code for the same shot. It already drives slates, overlay burn-ins and
* delivered file names (RenderPipeline2 §11.2); internal paths, comp names and
* every DB lookup stay on `shotCode`.
*
* The client portal is the other place the client's own naming belongs, and
* that includes task titles: they follow the house convention
* `UNG_102_019_010_cmp_TT_v004`, so the internal code is embedded in the
* string the client reads and copies.
*
* Apply these at the API boundary rather than at each render site, so nothing
* downstream has to remember which code it is holding.
*/
export interface ShotCodeFields {
shotCode: string;
clientCode?: string | null;
}
/** The shot's code as the client knows it; their alias if set, ours otherwise. */
export function clientShotCode(shot: ShotCodeFields): string {
return shot.clientCode?.trim() || shot.shotCode;
}
/**
* A task title with the internal shot code swapped for the client's alias.
*
* Titles are built from the shot code by convention, so this is a substring
* swap rather than a rename — a title that does not contain the code (a
* hand-edited one, say) is returned untouched rather than guessed at.
*/
export function clientTaskTitle(title: string, shot: ShotCodeFields): string {
const alias = shot.clientCode?.trim();
if (!alias || !title || alias === shot.shotCode) return title;
// split/join rather than a regex: shot codes are user-supplied and would
// otherwise need escaping.
return title.split(shot.shotCode).join(alias);
}
+190 -2
View File
@@ -3,8 +3,13 @@ import { describe, it, expect, vi } from "vitest";
// Mock Prisma db so the pure deriveShotStatus function can be tested in isolation
vi.mock("@/lib/db", () => ({ db: {} }));
import { deriveShotStatus } from "./shot-status";
import type { TaskStatus } from "@prisma/client";
import {
deriveShotStatus,
clearStaleShotApproval,
markShotForRevisions,
recalcShotStatus,
} from "./shot-status";
import type { TaskStatus, ShotApprovalStatus } from "@prisma/client";
// Helper to build task arrays quickly
const tasks = (...statuses: TaskStatus[]) => statuses.map((status) => ({ status }));
@@ -142,3 +147,186 @@ describe("deriveShotStatus", () => {
});
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Fake Prisma client — enough of the surface for the two write helpers. Each
// call mutates the in-memory shot so the assertions read final state, not spies.
// ─────────────────────────────────────────────────────────────────────────────
type FakeTask = { id: string; status: TaskStatus };
type FakeVersion = { id: string; taskId: string; isLatest: boolean; createdAt: Date };
// The helpers take a Prisma client; the fake implements just the calls they make.
type TxArg = Parameters<typeof recalcShotStatus>[1];
const asTx = (c: { shotState: unknown }): NonNullable<TxArg> =>
c as unknown as NonNullable<TxArg>;
function fakeClient(shot: {
id: string;
shotApprovalStatus: ShotApprovalStatus;
sharedWithClient: boolean;
status?: string;
tasks: FakeTask[];
versions?: FakeVersion[];
}) {
const versions = shot.versions ?? [];
return {
shot: {
findUnique: async () => shot,
update: async ({ data }: { data: Record<string, unknown> }) => {
Object.assign(shot, data);
return shot;
},
},
task: {
findMany: async ({ where }: { where: { status?: { not: TaskStatus } } }) =>
where.status?.not
? shot.tasks.filter((t) => t.status !== where.status!.not)
: shot.tasks,
update: async ({ where, data }: { where: { id: string }; data: { status: TaskStatus } }) => {
const t = shot.tasks.find((x) => x.id === where.id);
if (t) t.status = data.status;
return t;
},
updateMany: async ({
where,
data,
}: {
where: { status?: { not: TaskStatus } };
data: { status: TaskStatus };
}) => {
for (const t of shot.tasks) {
if (!where.status?.not || t.status !== where.status.not) t.status = data.status;
}
return { count: shot.tasks.length };
},
},
version: {
findFirst: async () =>
[...versions].sort(
(a, b) =>
Number(b.isLatest) - Number(a.isLatest) ||
b.createdAt.getTime() - a.createdAt.getTime()
)[0] ?? null,
},
shotState: shot,
};
}
describe("clearStaleShotApproval", () => {
it("clears an internal sign-off so new work is visible", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "INTERNALLY_APPROVED",
sharedWithClient: false,
tasks: [{ id: "t1", status: "INTERNAL_REVIEW" }],
});
expect(await clearStaleShotApproval(asTx(c), "s1")).toBe(true);
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
});
it("clears a client sign-off, so an upload cannot hide under COMPLETE", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "CLIENT_APPROVED",
sharedWithClient: true,
tasks: [{ id: "t1", status: "INTERNAL_REVIEW" }],
});
expect(await clearStaleShotApproval(asTx(c), "s1")).toBe(true);
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
});
it("is a no-op when there is no sign-off to clear", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "PENDING",
sharedWithClient: false,
tasks: [{ id: "t1", status: "IN_PROGRESS" }],
});
expect(await clearStaleShotApproval(asTx(c), "s1")).toBe(false);
});
it("leaves sharedWithClient alone — revoking access is a separate act", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "CLIENT_APPROVED",
sharedWithClient: true,
tasks: [{ id: "t1", status: "DONE" }],
});
await clearStaleShotApproval(asTx(c), "s1");
expect(c.shotState.sharedWithClient).toBe(true);
});
});
describe("markShotForRevisions", () => {
it("marks the open tasks and lands the shot on REVISIONS", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "CLIENT_APPROVED",
sharedWithClient: true,
tasks: [
{ id: "t1", status: "DONE" },
{ id: "t2", status: "IN_PROGRESS" },
],
});
const changed = await markShotForRevisions(asTx(c), "s1");
expect(changed).toEqual(["t2"]);
expect(c.shotState.tasks.find((t) => t.id === "t1")!.status).toBe("DONE");
expect(c.shotState.tasks.find((t) => t.id === "t2")!.status).toBe("CHANGES");
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
expect(c.shotState.sharedWithClient).toBe(false);
expect(c.shotState.status).toBe("REVISIONS");
});
// The regression this helper exists for: a shot out for client review has all
// its tasks DONE, so the old "non-DONE" filter matched nothing and the change
// request silently derived to INTERNAL_REVIEW instead of REVISIONS.
it("reopens the task behind the latest version when every task is DONE", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "CLIENT_APPROVED",
sharedWithClient: true,
tasks: [
{ id: "t1", status: "DONE" },
{ id: "t2", status: "DONE" },
],
versions: [
{ id: "v1", taskId: "t1", isLatest: false, createdAt: new Date("2026-01-01") },
{ id: "v2", taskId: "t2", isLatest: true, createdAt: new Date("2026-02-01") },
],
});
const changed = await markShotForRevisions(asTx(c), "s1");
expect(changed).toEqual(["t2"]);
expect(c.shotState.tasks.find((t) => t.id === "t2")!.status).toBe("CHANGES");
expect(c.shotState.status).toBe("REVISIONS");
});
it("marks only the called-out task when one is named", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "INTERNALLY_APPROVED",
sharedWithClient: false,
tasks: [
{ id: "t1", status: "TODO" },
{ id: "t2", status: "DONE" },
],
});
const changed = await markShotForRevisions(asTx(c), "s1", "t2");
expect(changed).toEqual(["t2"]);
expect(c.shotState.tasks.find((t) => t.id === "t1")!.status).toBe("TODO");
expect(c.shotState.tasks.find((t) => t.id === "t2")!.status).toBe("CHANGES");
});
it("still clears the approval when a shot has no tasks to mark", async () => {
const c = fakeClient({
id: "s1",
shotApprovalStatus: "CLIENT_APPROVED",
sharedWithClient: true,
tasks: [],
});
const changed = await markShotForRevisions(asTx(c), "s1");
expect(changed).toEqual([]);
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
expect(c.shotState.status).toBe("WAITING");
});
});
+97
View File
@@ -77,3 +77,100 @@ export async function recalcShotStatus(
data: { status: newStatus },
});
}
/**
* New review material arrived on a shot, so any standing sign-off is stale.
*
* deriveShotStatus short-circuits on shotApprovalStatus: a CLIENT_APPROVED shot
* reads COMPLETE and an INTERNALLY_APPROVED one reads READY_FOR_CLIENT no matter
* what its tasks say. Without this, uploading a new version onto an approved
* shot moved the task to INTERNAL_REVIEW and changed nothing visible — the shot
* still read as signed off while carrying work nobody had looked at.
*
* sharedWithClient is left alone; clearing the approval is enough to pull the
* shot back to INTERNAL_REVIEW, and revoking client access is a separate,
* deliberate act (unshareFromClient).
*
* @returns true if a stale approval was actually cleared.
*/
export async function clearStaleShotApproval(
client: TxClient,
shotId: string
): Promise<boolean> {
const shot = await client.shot.findUnique({
where: { id: shotId },
select: { shotApprovalStatus: true },
});
if (!shot || shot.shotApprovalStatus === "PENDING") return false;
await client.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "PENDING" },
});
return true;
}
/**
* Put a shot into revisions: clear its approval, unshare it, and mark the tasks
* that need rework so the derivation lands on REVISIONS.
*
* The task selection is the subtle part. Marking every non-DONE task as CHANGES
* matches nothing at all on the shot this is most often called for — one that is
* out for client review precisely *because* all of its tasks are finished. That
* left the shot deriving to INTERNAL_REVIEW and the change request with no
* visible effect anywhere. So when nothing was picked up, the task behind the
* shot's latest version is marked instead: that is the deliverable the reviewer
* was actually looking at.
*
* @param taskId Mark only this task (a reviewer calling out one specific task).
* @returns ids of the tasks moved to CHANGES.
*/
export async function markShotForRevisions(
client: TxClient,
shotId: string,
taskId?: string
): Promise<string[]> {
await client.shot.update({
where: { id: shotId },
data: { shotApprovalStatus: "PENDING", sharedWithClient: false },
});
let changed: string[];
if (taskId) {
await client.task.update({ where: { id: taskId }, data: { status: "CHANGES" } });
changed = [taskId];
} else {
const open = await client.task.findMany({
where: { shotId, status: { not: "DONE" } },
select: { id: true },
});
if (open.length > 0) {
await client.task.updateMany({
where: { shotId, status: { not: "DONE" } },
data: { status: "CHANGES" },
});
changed = open.map((t) => t.id);
} else {
// Every task is DONE — reopen the one that produced what was reviewed.
const latest = await client.version.findFirst({
where: { task: { shotId } },
orderBy: [{ isLatest: "desc" }, { createdAt: "desc" }],
select: { taskId: true },
});
if (latest?.taskId) {
await client.task.update({
where: { id: latest.taskId },
data: { status: "CHANGES" },
});
changed = [latest.taskId];
} else {
changed = [];
}
}
}
await recalcShotStatus(shotId, client);
return changed;
}
+40
View File
@@ -0,0 +1,40 @@
import { describe, it, expect } from "vitest";
import { shotThumbnail, isGeneratedThumbnail } from "./shot-thumbnail";
/**
* The whole point of the second column is that promotion can never destroy the
* reference frame that came with the brief. These cases are that guarantee.
*/
describe("shotThumbnail", () => {
it("prefers the reference frame over a render-derived one", () => {
expect(
shotThumbnail({ thumbnailUrl: "/api/files/image/ref.jpg", generatedThumbnailUrl: "/api/files/image/gen.jpg" })
).toBe("/api/files/image/ref.jpg");
});
it("falls back to the render frame when the show supplied no still", () => {
expect(shotThumbnail({ thumbnailUrl: null, generatedThumbnailUrl: "/api/files/image/gen.jpg" })).toBe(
"/api/files/image/gen.jpg"
);
});
it("returns null when the shot has neither", () => {
expect(shotThumbnail({ thumbnailUrl: null, generatedThumbnailUrl: null })).toBeNull();
expect(shotThumbnail(null)).toBeNull();
expect(shotThumbnail({})).toBeNull();
});
it("treats an empty string as no thumbnail", () => {
// updateShot accepts "" from a cleared form field, which must not win over
// a generated frame or render as a broken <img src="">.
expect(shotThumbnail({ thumbnailUrl: "", generatedThumbnailUrl: "/api/files/image/gen.jpg" })).toBe(
"/api/files/image/gen.jpg"
);
});
it("reports whether what is displayed came from a render", () => {
expect(isGeneratedThumbnail({ thumbnailUrl: null, generatedThumbnailUrl: "/g.jpg" })).toBe(true);
expect(isGeneratedThumbnail({ thumbnailUrl: "/r.jpg", generatedThumbnailUrl: "/g.jpg" })).toBe(false);
expect(isGeneratedThumbnail({ thumbnailUrl: null, generatedThumbnailUrl: null })).toBe(false);
});
});
+41
View File
@@ -0,0 +1,41 @@
/**
* Shot thumbnail resolution.
*
* A shot can carry two stills:
*
* • `thumbnailUrl` — the reference frame supplied with the brief
* (client still, batch upload, ext API). Editorial
* data: only ever written by a human.
* • `generatedThumbnailUrl` — a frame promoted from a render export, either
* automatically (projects with
* `pipelineConfig.autoShotThumbnail`) or by hand.
*
* The reference always wins. Shows that arrive with stills look exactly as they
* do today; shows that arrive without any get their empty grids filled from the
* renders instead. Because the two live in different columns, a promotion can
* never destroy the reference — clearing the generated one always falls back to
* the brief.
*/
export interface ShotThumbnailFields {
thumbnailUrl?: string | null;
generatedThumbnailUrl?: string | null;
}
/** The still to display for a shot, or null when it has neither. */
export function shotThumbnail(shot: ShotThumbnailFields | null | undefined): string | null {
return shot?.thumbnailUrl || shot?.generatedThumbnailUrl || null;
}
/** True when the displayed still came from a render rather than the brief. */
export function isGeneratedThumbnail(shot: ShotThumbnailFields | null | undefined): boolean {
return !shot?.thumbnailUrl && !!shot?.generatedThumbnailUrl;
}
/**
* Prisma `select` fragment for the two columns. Spread it wherever a query
* already selects `thumbnailUrl` so the fallback has something to fall back to.
*/
export const shotThumbnailSelect = {
thumbnailUrl: true,
generatedThumbnailUrl: true,
} as const;
@@ -0,0 +1,9 @@
-- Client naming alias: substituted for shotCode only on slates, overlay
-- burn-ins, and delivered file/folder names. Internal paths, comp names and
-- DB lookups always use shotCode.
-- AlterTable
ALTER TABLE "shots" ADD COLUMN "clientCode" TEXT;
-- AlterTable
ALTER TABLE "delivery_items" ADD COLUMN "clientCode" TEXT;
@@ -0,0 +1,6 @@
-- Thumbnail promoted from a render export. Kept separate from "thumbnailUrl"
-- (the client-supplied reference frame) so promotion can only fill a gap and
-- never overwrite the brief. Display precedence is
-- COALESCE("thumbnailUrl", "generatedThumbnailUrl").
ALTER TABLE "shots" ADD COLUMN "generatedThumbnailUrl" TEXT;
ALTER TABLE "shots" ADD COLUMN "generatedThumbnailFrom" TEXT;
@@ -0,0 +1,14 @@
-- MOV review packages (RenderPipeline2 §11.6): a flat, dated folder of preview
-- MOVs shared for a formal review. Same package/job/verification machinery as
-- an EXR delivery, but it never advances an Export — a shot can appear in as
-- many reviews as it takes before the delivery that actually ships it.
-- CreateEnum
CREATE TYPE "DeliveryKind" AS ENUM ('EXR_DELIVERY', 'MOV_REVIEW');
-- AlterTable: every existing package predates reviews, so it is a delivery.
ALTER TABLE "delivery_packages"
ADD COLUMN "kind" "DeliveryKind" NOT NULL DEFAULT 'EXR_DELIVERY';
-- CreateIndex
CREATE INDEX "delivery_packages_projectId_kind_idx" ON "delivery_packages"("projectId", "kind");
@@ -0,0 +1,4 @@
-- Scaled-in-edit flag. The plate is not used at its native size, which changes
-- how the shot is comped and reviewed — a standing property of the shot, like
-- isKeyShot, rather than a note someone has to read.
ALTER TABLE "shots" ADD COLUMN "isScaled" BOOLEAN NOT NULL DEFAULT false;
+35 -2
View File
@@ -173,6 +173,15 @@ enum MachineStatus {
DISABLED
}
/// What a package is for. A MOV_REVIEW package is a flat folder of preview
/// MOVs shared for a formal review — it never touches the Export state
/// machine, so a shot can appear in as many reviews as it takes before the
/// EXR delivery that actually ships it.
enum DeliveryKind {
EXR_DELIVERY
MOV_REVIEW
}
enum DeliveryStatus {
DRAFT
QUEUED
@@ -392,6 +401,10 @@ model EpisodeDueDate {
model Shot {
id String @id @default(cuid())
shotCode String
/// Client-supplied naming alias, used only for slates, overlay burn-ins,
/// and delivered file/folder names — never for internal paths, comp names
/// or DB lookups, which always use shotCode. Null = use shotCode as today.
clientCode String?
scene String @default("")
episode String?
shotNumber Int @default(0)
@@ -407,6 +420,15 @@ model Shot {
fps Float @default(24)
dueDate DateTime?
thumbnailUrl String?
/// Thumbnail promoted from a render export — automatically when the project
/// opts in via `pipelineConfig.autoShotThumbnail`, or by hand. Deliberately a
/// separate column: `thumbnailUrl` is the client-supplied reference frame and
/// is never written by the pipeline, so promotion can only fill a gap, never
/// destroy the brief. Display precedence is `thumbnailUrl ?? generatedThumbnailUrl`
/// (lib/shot-thumbnail.ts).
generatedThumbnailUrl String?
/// Version string of the export the generated thumbnail came from, e.g. "v004".
generatedThumbnailFrom String?
originalFootageUrl String?
originalFootageKey String?
shotGroupId String?
@@ -428,6 +450,11 @@ model Shot {
shotVersion String @default("v001")
// Key shot flag — highlighted for prioritisation
isKeyShot Boolean @default(false)
/// The shot is scaled in the edit — the plate is not used at its native
/// size. That changes how the shot is comped and reviewed, so it is a
/// standing property of the shot rather than a note, and it is flagged on
/// the shot-status board the way a key shot is.
isScaled Boolean @default(false)
// Netflix slate fields — managed via the Slate tab, used by the preview pipeline
slateType String?
slateDescription String? @db.Text
@@ -1084,8 +1111,9 @@ model DeliveryPackage {
id String @id @default(cuid())
projectId String
project Project @relation(fields: [projectId], references: [id])
episode String // "101" — empty string on standard (non-episodic) shows
name String // "260805_Delivery"
episode String // "101" — empty string on standard (non-episodic) shows, and on reviews spanning several
name String // "260805_Delivery" | "20260828_Producer_review_02"
kind DeliveryKind @default(EXR_DELIVERY)
packageNumber Int // sequential per project → "Package #15"
status DeliveryStatus @default(DRAFT)
rootPath String? // final path on the delivery volume
@@ -1103,6 +1131,7 @@ model DeliveryPackage {
@@unique([projectId, packageNumber])
@@index([projectId, episode])
@@index([projectId, kind])
@@index([status])
@@map("delivery_packages")
}
@@ -1117,6 +1146,10 @@ model DeliveryItem {
export Export @relation(fields: [exportId], references: [id])
shotId String
shotCode String
/// Snapshot of Shot.clientCode at package build time — same immutability
/// rule as shotCode/versionString: a later shot edit must not retroactively
/// change already-built delivery history.
clientCode String?
versionString String
exrPath String? // path inside the package
movPath String?
+90
View File
@@ -0,0 +1,90 @@
/**
* Why is a shot not showing a render-derived thumbnail?
*
* Walks the chain in order and reports the first broken link:
*
* ffmpeg on the worker → Export.thumbnailKey → project flag →
* Shot.generatedThumbnailUrl → what the UI resolves
*
* Usage: node scripts/diagnose-thumbnails.mjs [PROJECT_CODE]
*/
import { PrismaClient } from "@prisma/client";
const db = new PrismaClient();
const projectCode = process.argv[2]?.toUpperCase();
const projects = await db.project.findMany({
where: projectCode ? { code: projectCode } : {},
select: { id: true, code: true, name: true, pipelineConfig: true },
orderBy: { code: "asc" },
});
if (projects.length === 0) {
console.log(projectCode ? `No project with code ${projectCode}.` : "No projects.");
process.exit(0);
}
for (const p of projects) {
const cfg = (p.pipelineConfig ?? {});
const flag = cfg.autoShotThumbnail;
const on = flag === true;
console.log(`\n━━ ${p.code} — ${p.name}`);
console.log(` auto-promote flag : ${JSON.stringify(flag)} ${on ? "✔ on" : "✘ OFF"}`);
if (flag === undefined) {
console.log(` ⚠ key absent from pipelineConfig. Either the setting was never saved,`);
console.log(` or the server that saved it predates the boolean fix in actions/projects.ts.`);
console.log(` Stored keys: ${JSON.stringify(Object.keys(cfg))}`);
}
const exports = await db.export.findMany({
where: { shot: { projectId: p.id } },
orderBy: { createdAt: "desc" },
take: 10,
select: {
versionString: true, status: true, createdAt: true,
thumbnailKey: true, skipPreview: true,
shot: {
select: {
shotCode: true, thumbnailUrl: true,
generatedThumbnailUrl: true, generatedThumbnailFrom: true,
},
},
},
});
if (exports.length === 0) {
console.log(" (no exports yet)");
continue;
}
console.log(` last ${exports.length} exports:`);
for (const e of exports) {
const s = e.shot;
const displayed = s.thumbnailUrl || s.generatedThumbnailUrl || null;
const source = s.thumbnailUrl ? "reference" : s.generatedThumbnailUrl ? "render" : "NOTHING";
console.log(
`\n ${s.shotCode} ${e.versionString} [${e.status}]${e.skipPreview ? " skipPreview" : ""}`
);
console.log(` export.thumbnailKey : ${e.thumbnailKey ?? "✘ NULL — worker produced no thumbnail (ffmpeg?)"}`);
console.log(` shot.thumbnailUrl : ${s.thumbnailUrl ?? "(none)"}`);
console.log(` shot.generatedThumbnail : ${s.generatedThumbnailUrl ?? "(none)"}${s.generatedThumbnailFrom ? ` [from ${s.generatedThumbnailFrom}]` : ""}`);
console.log(` → UI shows : ${displayed ?? "nothing"} (${source})`);
if (!e.thumbnailKey) {
console.log(` ⇒ Broken at the WORKER. Check ffmpegPath in config.json on the`);
console.log(` machine that ran it, and its log for "no thumbnail".`);
} else if (!on) {
console.log(` ⇒ Thumbnail exists but the project flag is off, so it was not promoted.`);
console.log(` Turn on "Use render frames as shot thumbnails", or use the`);
console.log(` per-export "Use frame" button on the shot's Exports tab.`);
} else if (!s.generatedThumbnailUrl) {
console.log(` ⇒ Thumbnail exists and the flag is on, but nothing was promoted.`);
console.log(` This export probably finalized BEFORE the flag was turned on —`);
console.log(` promotion happens at finalize, it is not retroactive. Re-render,`);
console.log(` or press "Use frame" on the Exports tab.`);
}
}
}
await db.$disconnect();
+4
View File
@@ -148,6 +148,8 @@ export interface VersionWithDetails {
export interface ShotWithDetails {
id: string;
shotCode: string;
/** Client-supplied naming alias — slates/overlays/delivery only, never internal paths. */
clientCode: string | null;
scene: string;
episode: string | null;
shotNumber: number;
@@ -163,6 +165,8 @@ export interface ShotWithDetails {
frameEnd: number | null;
dueDate: Date | null;
thumbnailUrl: string | null;
generatedThumbnailUrl: string | null;
generatedThumbnailFrom: string | null;
originalFootageUrl: string | null;
originalFootageKey: string | null;
shotGroupId: string | null;