rushes 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,10 @@ import { streamSSE } from "hono/streaming";
3
3
  import { z } from "zod";
4
4
  import { RushesError, InvalidError, NotFoundError } from "../core/errors.js";
5
5
  import { addFile, addFormat, addVariant, addVersion, ensureProjectIdOnce, lockPicture, noteInPlay, resolveCut, resolveVideo, setShots, setVariantFilms, shelveFilm, shotAt } from "../core/project.js";
6
- import { addTake, editSection, setSections } from "../core/script.js";
7
- import { addNote, addUserReply, applyReply, applyUserEdit, checkNoteFormat, filterNotes } from "../core/notes.js";
6
+ import { addTake, allSections, editSection, filmScript, filmScriptDraft, setSections } from "../core/script.js";
7
+ import { chooseFilm, filmPlace, firstFilm } from "../core/films.js";
8
+ import { moveToFirstFilmOnce } from "./films.js";
9
+ import { addNote, addUserReply, applyReply, applyUserEdit, byFilm, checkNoteFormat, filterNotes } from "../core/notes.js";
8
10
  import { FORMAT_ID_RE, MAX_FORMATS, isPictureSize, labelOfId, versionFormats } from "../core/formats.js";
9
11
  import { createBatch, latestBatch } from "../core/batches.js";
10
12
  import { markSent, noteState, NOTE_STATES, withState } from "../core/noteState.js";
@@ -30,8 +32,8 @@ import { filmTakes, putAway } from "../core/takes.js";
30
32
  import { AGENTS, AgentPermissionsSchema, AlwaysRuleSchema, LaneStageSchema, SectionStatusSchema, StageSchema, BoxSchema, PinSchema, FileKindSchema, MarkSchema, ProjectIdSchema, ShotSchema, LEVEL_MIN, LEVEL_MAX, LEVEL_STEP, lanesForVideo, picksForVideo, variantFilms } from "../core/schema.js";
31
33
  import { LABEL_MAX, oneLineOf } from "../core/labels.js";
32
34
  import { byOf, logBookFor } from "./logbook.js";
33
- import { BriefService } from "./brief.js";
34
- import { StoryboardService } from "./storyboard.js";
35
+ import { briefRecords, storyboardRecords } from "./plans.js";
36
+ import { slugify, uniqueId } from "../core/ids.js";
35
37
  import { buildState, planWarning } from "../core/plan.js";
36
38
  import { broughtInEvent, cutEvent, fileEvent, filmEvent, formatEvent, lineEvent, lockEvent, notesSentEvent, picksEvent, repliesEvent, scriptEvent, takeEvent, variantEvent, variantFilmsEvent, visualEvent, } from "../core/logEvents.js";
37
39
  import { LOG_AREAS, LOG_MAX, changeLogFileName, logText, recentChanges } from "../core/logText.js";
@@ -41,6 +43,7 @@ import { balanceSummary } from "../core/balance.js";
41
43
  import { clearDetectCache, detectAgents } from "./agent/detect.js";
42
44
  import { openInTerminal } from "./agent/terminal.js";
43
45
  import { agentRulesFor } from "./agent/rules.js";
46
+ import { adoptAgentDefaultsOnce, rememberDefault } from "./agent/setupOnce.js";
44
47
  import { notifyWhenWaiting, osNotifier } from "./agent/notify.js";
45
48
  import { VERSION } from "../version.js";
46
49
  export { VERSION };
@@ -153,23 +156,29 @@ const VariantBody = z.object({
153
156
  cues: z.array(z.object({ name: z.string().min(1), t, file: z.string().min(1).optional() })).optional(),
154
157
  });
155
158
  const VariantFilmsBody = z.object({ videos: z.array(z.string().min(1).max(200)).max(100) });
159
+ // §31.6: the script, brief and storyboard are a film's: a write names its film (`video`, an id or a name). With one
160
+ // film it may be left out; with several, leaving it out is refused with the films listed.
161
+ const filmRef = z.string().min(1).max(200).optional();
156
162
  const ScriptBody = z.object({
163
+ video: filmRef,
157
164
  wordsPerSecond: z.number().positive().optional(),
158
165
  replace: z.boolean().optional(),
159
166
  sections: z.array(z.object({ id: z.string().min(1).optional(), start: t, end: t, current: z.string() })),
160
167
  });
161
168
  const SectionEditBody = z.object({
169
+ video: filmRef,
162
170
  proposed: z.string().nullable().optional(),
163
171
  direction: z.string().optional(),
164
172
  status: SectionStatusSchema.optional(),
165
173
  });
166
- const TakeBody = z.object({ file: z.string().min(1) });
174
+ const TakeBody = z.object({ file: z.string().min(1), video: filmRef });
167
175
  // §24 step 2: a save of one brief.md section, and the approval. `hash` proves the page saw the current file.
168
- const BriefSectionBody = z.object({ heading: z.string().min(1).max(200), text: z.string().max(100_000), hash: z.string().min(1).max(64) });
169
- const BriefStatusBody = z.object({ status: z.enum(["draft", "approved"]), hash: z.string().min(1).max(64) });
176
+ const BriefSectionBody = z.object({ video: filmRef, heading: z.string().min(1).max(200), text: z.string().max(100_000), hash: z.string().min(1).max(64) });
177
+ const BriefStatusBody = z.object({ video: filmRef, status: z.enum(["draft", "approved"]), hash: z.string().min(1).max(64) });
170
178
  // §24.12: a change to one storyboard shot: its words, its direction, its status, in any combination.
171
179
  const StoryboardShotBody = z
172
180
  .object({
181
+ video: filmRef,
173
182
  heading: z.string().min(1).max(200),
174
183
  description: z.string().max(100_000).optional(),
175
184
  direction: z.string().max(1000).optional(),
@@ -187,9 +196,12 @@ const PicksBody = z.object({ video: z.string().min(1).max(200).optional(), lanes
187
196
  // §28: the Send to AI switch, the agent and what it may do unasked.
188
197
  // `batch` (I3): the filed batch the copy dialog was showing when its Set up opened the sheet. Once Send to AI is on, it is
189
198
  // handed to the agent, as Send would have.
190
- const AgentSetupBody = z.object({ on: z.boolean(), agent: z.enum(AGENTS).optional(), permissions: AgentPermissionsSchema.optional(), batch: z.string().min(1).optional() });
191
- // No stage: every tab's open notes (Send). A stage: that tab's only.
192
- const BatchBody = z.object({ stage: StageSchema.optional() });
199
+ // §32: `prompt`: the first-Send sheet's Copy a prompt (off, and no agent for new projects either). The switch turned off
200
+ // sends no `prompt`, so it leaves the Mac-wide default as it is.
201
+ const AgentSetupBody = z.object({ on: z.boolean(), agent: z.enum(AGENTS).optional(), permissions: AgentPermissionsSchema.optional(), batch: z.string().min(1).optional(), prompt: z.boolean().optional() });
202
+ // No stage: every tab's open notes (Send). A stage: that tab's only. §31.2.2: `video`, the film Send is pressed on:
203
+ // only its notes and its script go. Without one, every film in play (an older client).
204
+ const BatchBody = z.object({ stage: StageSchema.optional(), video: filmRef });
193
205
  const NoteQuery = z.object({
194
206
  stage: StageSchema.optional(),
195
207
  status: z.enum(["todo", "done"]).optional(),
@@ -201,7 +213,11 @@ const NoteQuery = z.object({
201
213
  onlyThisFormat: z.enum(["true", "false"]).optional(),
202
214
  // §26: the notes of a shelved film are left out unless asked for (or a batch is: it lists what it sent).
203
215
  includeShelved: z.enum(["true", "false"]).optional(),
216
+ // §31.6: one film's notes (and the visuals', which are on every film).
217
+ video: z.string().min(1).max(200).optional(),
204
218
  });
219
+ // §31.6: the film a read is about, for the routes that take ?video= alone.
220
+ const VideoQuery = z.object({ video: z.string().min(1).max(200).optional() });
205
221
  // ShotSchema's own limits (name trimmed 1-80 chars, tag at most 24) apply at the boundary; `n` is server-assigned.
206
222
  const ShotsBody = z.object({
207
223
  version: z.string().optional(),
@@ -270,6 +286,8 @@ const LogQuery = z.object({
270
286
  .string()
271
287
  .refine((s) => ISO_DATE.test(s) && Number.isFinite(Date.parse(s)), "since must be a date and time, e.g. 2026-10-07T09:00:00Z")
272
288
  .optional(),
289
+ // §31.6: the lines Activity shows on this film: its own and the project's.
290
+ video: z.string().min(1).max(200).optional(),
273
291
  });
274
292
  const LogLineBody = z.object({
275
293
  text: z.string().max(2000),
@@ -325,25 +343,34 @@ export function createApp(store, opts = {}) {
325
343
  const jobs = opts.proxyJobs ?? new ProxyJobs(store);
326
344
  const peaks = opts.peakJobs ?? new PeakJobs(store, { run: jobs.run, available: () => jobs.available() });
327
345
  const found = opts.found ?? new FoundScanner({ store, probe: ffprobeDuration, announce: foundAnnouncer(store) });
328
- const brief = opts.brief ?? new BriefService(store);
329
- const storyboard = opts.storyboard ?? new StoryboardService(store);
346
+ const briefs = opts.briefs ?? briefRecords(store, opts.brief);
347
+ const storyboards = opts.storyboards ?? storyboardRecords(store, opts.storyboard);
330
348
  // §28: made before any route is reachable, so every agent route and Send has it.
331
349
  const agent = opts.agent ?? noAgent();
332
350
  const sendWaitMs = opts.sendWaitMs ?? SEND_WAIT_MS;
333
351
  const detect = opts.detect ?? (() => detectAgents());
334
352
  const terminal = opts.terminal ?? openInTerminal;
335
- /** §24.12: whether the plan (brief, script, storyboard) is approved, from the files as they are now. */
336
- const planBuild = async () => {
337
- const [b, script, sb] = await Promise.all([brief.view(), store.read("script"), storyboard.view()]);
338
- return buildState({ brief: b, script: script.sections, storyboard: sb });
353
+ /** §24.12, §31.5: whether a film's plan (its brief, script and storyboard) is approved, from the files as they are now. */
354
+ const planBuild = async (video) => {
355
+ const project = await store.read("project");
356
+ const place = filmPlace(project, video);
357
+ const [b, script, sb] = await Promise.all([briefs.at(place).view(), store.read("script"), storyboards.at(place).view()]);
358
+ return buildState({ brief: b, script: filmScript(script, project, place.video).sections, storyboard: sb });
339
359
  };
360
+ /**
361
+ * §31.6: the film a request for a film's material is about: the one it names, or the only one. With several films
362
+ * and none named, a 400 that lists them. Null while the project has no film.
363
+ */
364
+ const filmOf = async (given, what) => chooseFilm(await store.read("project"), given, what)?.id ?? null;
365
+ /** The whole script's sections, for what must know every take whichever film it is in (the log, refs). */
366
+ const everySection = (script) => ({ sections: allSections(script) });
340
367
  // §22: the Change Log, shared with the found scanner (logBookFor keeps one per store).
341
368
  const log = logBookFor(store);
342
369
  const by = (c) => byOf(c.req.header("x-rushes-project"));
343
370
  /** R17: writes exports/change-log-YYYY-MM-DD.md (a same-day export replaces it) and returns its path. Written as Export notes writes. */
344
371
  async function exportChangeLog(now) {
345
372
  const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
346
- const md = await log.markdown({ project, script }, now);
373
+ const md = await log.markdown({ project, script: everySection(script) }, now);
347
374
  const name = changeLogFileName(now);
348
375
  const dir = join(store.root, "exports");
349
376
  await mkdir(dir, { recursive: true });
@@ -500,8 +527,15 @@ export function createApp(store, opts = {}) {
500
527
  if (!known && registeredMedia(project, script, await store.read("visuals")).has(path))
501
528
  known = true;
502
529
  // §24.12: a picture storyboard.md names (a safe, project-relative image path) is served too, registered or not.
503
- if (!known && (await storyboard.stills()).has(path))
504
- known = true;
530
+ // §31.3: any film's storyboard.
531
+ if (!known) {
532
+ for (const sb of await storyboards.all()) {
533
+ if ((await sb.stills()).has(path)) {
534
+ known = true;
535
+ break;
536
+ }
537
+ }
538
+ }
505
539
  // The file on disk to send. For a found file it's exactly the path that was checked.
506
540
  let file = fromManifestPath(store.root, path);
507
541
  let viaFound = false;
@@ -589,11 +623,18 @@ export function createApp(store, opts = {}) {
589
623
  });
590
624
  // ---- assets: the Assets tab and rushes_list_assets ----
591
625
  app.get("/api/assets", async (c) => {
592
- const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
593
- let assets = await listAssets(store, project, script);
626
+ const [project, script, visuals] = await Promise.all([store.read("project"), store.read("script"), store.read("visuals")]);
627
+ let assets = await listAssets(store, project, script, visuals);
594
628
  const kind = c.req.query("kind");
595
629
  if (kind)
596
630
  assets = assets.filter((a) => a.kind === kind);
631
+ // §31.6: one film's files: its own, the shared visuals, and (naming no film) the first film's.
632
+ const video = c.req.query("video");
633
+ if (video) {
634
+ const film = chooseFilm(project, video).id;
635
+ const first = firstFilm(project);
636
+ assets = assets.filter((a) => a.shared || (a.videos ? a.videos.includes(film) : a.video ? a.video === film : film === first));
637
+ }
597
638
  return c.json({ assets });
598
639
  });
599
640
  app.post("/api/reveal", async (c) => {
@@ -659,7 +700,8 @@ export function createApp(store, opts = {}) {
659
700
  app.post("/api/files", async (c) => {
660
701
  const b = await body(c, AddFileBody);
661
702
  const file = toManifestPath(store.root, b.file);
662
- const { result } = await store.update("project", (p) => addFile(p, { ...b, file }));
703
+ // §31.2.4: with several films, a file that names none is the first film's.
704
+ const { result } = await store.update("project", (p) => addFile(p, { ...b, file, video: b.video ?? (p.videos.length > 1 ? p.videos[0].id : undefined) }));
663
705
  await log.add(() => fileEvent(result), by(c));
664
706
  return c.json(result, 201);
665
707
  });
@@ -668,7 +710,8 @@ export function createApp(store, opts = {}) {
668
710
  store.read("project"), store.read("notes"), store.read("script"), store.read("picks"), store.read("visuals"),
669
711
  ]);
670
712
  const now = new Date();
671
- const md = notesMarkdown(project, notesFile.notes, now, script, picks, visuals);
713
+ // §31.3: a note on the script names a line of its own film's script.
714
+ const md = notesMarkdown(project, notesFile.notes, now, (video) => filmScript(script, project, video), picks, visuals);
672
715
  const name = exportFileName(project.name, now);
673
716
  const dir = join(store.root, "exports");
674
717
  await mkdir(dir, { recursive: true });
@@ -710,17 +753,44 @@ export function createApp(store, opts = {}) {
710
753
  app.get("/api/state", async (c) => {
711
754
  // §20.6: found is what the last scan left in memory; it never waits on a scan or a probe.
712
755
  // §22.8: the log's head is read-only, so a state request never writes (R6).
713
- const [project, script, notes, picks, batches, ffmpeg, foundSummary, logHead, briefView, storyboardView, visuals] = await Promise.all([
714
- store.read("project"), store.read("script"), store.read("notes"), store.read("picks"), store.read("batches"), jobs.available(), found.summary(), log.head(), brief.view(), storyboard.view(), store.read("visuals"),
756
+ const [project, scriptFile, notes, picks, batches, ffmpeg, foundSummary, logHead, visuals] = await Promise.all([
757
+ store.read("project"), store.read("script"), store.read("notes"), store.read("picks"), store.read("batches"), jobs.available(), found.summary(), log.head(), store.read("visuals"),
715
758
  ]);
716
- const tabs = tabStates(project, script, notes, visuals);
759
+ // §31.5: everything Plan and Review show for each film: its script, brief, storyboard and plan state, its tabs
760
+ // (counts, to-do dots, unlocking) and its Activity head (the "new" dot). The desk picks the film on screen.
761
+ const heads = await log.filmHeads({ videos: project.videos, lanes: project.lanes, notes: notes.notes });
762
+ const planOf = async (video) => {
763
+ const place = filmPlace(project, video);
764
+ const [b, sb] = await Promise.all([briefs.at(place).view(), storyboards.at(place).view()]);
765
+ const s = filmScript(scriptFile, project, place.video);
766
+ return {
767
+ script: s,
768
+ brief: b,
769
+ storyboard: sb,
770
+ build: buildState({ brief: b, script: s.sections, storyboard: sb }),
771
+ tabs: tabStates(project, s, notes, visuals, place.video),
772
+ log: (place.video && heads[place.video]) ?? logHead,
773
+ // Where the agent finds this film's plan files.
774
+ paths: { brief: place.brief, storyboard: place.storyboard },
775
+ };
776
+ };
777
+ const films = {};
778
+ for (const v of project.videos)
779
+ films[v.id] = await planOf(v.id);
780
+ // The first film's (or, with no film yet, the project's) plan, at the top level as before, with the whole
781
+ // project's tabs and Activity head.
782
+ const first = project.videos.length > 0 ? films[project.videos[0].id] : await planOf(null);
783
+ const script = first.script;
784
+ const briefView = first.brief;
785
+ const storyboardView = first.storyboard;
786
+ const tabs = tabStates(project, filmScript(scriptFile, project, null), notes, visuals);
717
787
  // §19.5: why each cut may play badly (or null). Never waits on a probe: an unprobed cut is
718
788
  // null until its background probe lands, which then announces a change (ruling B).
719
789
  const videos = await Promise.all(project.videos.map(async (v) => ({
720
790
  ...v,
721
791
  versions: await Promise.all(v.versions.map(async (ver) => ({ ...ver, proxyNeed: await jobs.needNow(fromManifestPath(store.root, ver.file)) }))),
722
792
  })));
723
- return c.json({ version: VERSION, project: { ...project, videos }, script, notes, picks: withUse(project, picks), batches, tabs, visuals, proxies: { ffmpeg, jobs: jobs.list() }, found: foundSummary, log: logHead, brief: briefView, storyboard: storyboardView, build: buildState({ brief: briefView, script: script.sections, storyboard: storyboardView }) });
793
+ return c.json({ version: VERSION, project: { ...project, videos }, script, notes, picks: withUse(project, picks), batches, tabs, visuals, proxies: { ffmpeg, jobs: jobs.list() }, found: foundSummary, log: logHead, brief: briefView, storyboard: storyboardView, build: first.build, films });
724
794
  });
725
795
  // ---- found: the project's other files (§20) ----
726
796
  app.get("/api/found", async (c) => {
@@ -809,36 +879,69 @@ export function createApp(store, opts = {}) {
809
879
  await found.restore(b.paths);
810
880
  return c.json({ ok: true });
811
881
  });
882
+ // §31.6: ?video= is one film's: its tabs, its brief, storyboard and plan. Without one, the first film's plan (with
883
+ // one film, the same as ever) and the whole project's tabs.
812
884
  app.get("/api/tabs", async (c) => {
885
+ const q = VideoQuery.safeParse(c.req.query());
886
+ if (!q.success)
887
+ throw new InvalidError("Query is invalid", q.error.issues);
813
888
  const [project, script, notes, visuals] = await Promise.all([store.read("project"), store.read("script"), store.read("notes"), store.read("visuals")]);
814
- const [b, sb] = await Promise.all([brief.view(), storyboard.view()]);
889
+ const film = q.data.video ? chooseFilm(project, q.data.video).id : null;
890
+ const place = filmPlace(project, film);
891
+ const [b, sb] = await Promise.all([briefs.at(place).view(), storyboards.at(place).view()]);
892
+ const own = filmScript(script, project, place.video);
815
893
  return c.json({
816
- tabs: tabStates(project, script, notes, visuals),
894
+ tabs: tabStates(project, film ? own : filmScript(script, project, null), notes, visuals, film),
817
895
  // §26: every film and whether it is shelved, so an agent leaves the shelved ones alone.
818
896
  films: project.videos.map((v) => ({ id: v.id, name: v.name, shelved: v.shelved ?? null })),
897
+ // §31.3: where each film's own brief and storyboard are.
898
+ plans: Object.fromEntries(project.videos.map((v) => {
899
+ const p = filmPlace(project, v.id);
900
+ return [v.id, { brief: p.brief, storyboard: p.storyboard }];
901
+ })),
902
+ ...(film ? { film } : {}),
819
903
  brief: { exists: b.exists, status: b.status, changed: b.changed },
820
904
  storyboard: { exists: sb.exists, shots: sb.total, approved: sb.approved, changed: sb.changed },
821
- build: buildState({ brief: b, script: script.sections, storyboard: sb }),
905
+ build: buildState({ brief: b, script: own.sections, storyboard: sb }),
822
906
  });
823
907
  });
824
- // ---- brief: brief.md is the file of record (§24 step 2) ----
908
+ // ---- brief: brief.md is the file of record (§24 step 2); §31.3: each film has its own ----
909
+ const videoQuery = (c) => {
910
+ const q = VideoQuery.safeParse(c.req.query());
911
+ if (!q.success)
912
+ throw new InvalidError("Query is invalid", q.error.issues);
913
+ return q.data.video;
914
+ };
915
+ app.get("/api/brief", async (c) => {
916
+ const film = await filmOf(videoQuery(c), "the brief");
917
+ const place = filmPlace(await store.read("project"), film);
918
+ return c.json({ brief: await briefs.at(place).view(), film, path: place.brief });
919
+ });
825
920
  app.put("/api/brief/sections/:index", async (c) => {
826
921
  const index = Number(c.req.param("index"));
827
922
  if (!Number.isInteger(index) || index < 0)
828
923
  throw new InvalidError("Section index must be a whole number from 0");
829
924
  const b = await body(c, BriefSectionBody);
925
+ const brief = await briefs.of(await filmOf(b.video, "the brief"));
830
926
  return c.json({ brief: await brief.setSection(index, b.heading, b.text, b.hash) });
831
927
  });
832
- // ---- storyboard: storyboard.md is the file of record (§24.12) ----
928
+ // ---- storyboard: storyboard.md is the file of record (§24.12); §31.3: each film has its own ----
929
+ app.get("/api/storyboard", async (c) => {
930
+ const film = await filmOf(videoQuery(c), "the storyboard");
931
+ const place = filmPlace(await store.read("project"), film);
932
+ return c.json({ storyboard: await storyboards.at(place).view(), film, path: place.storyboard });
933
+ });
833
934
  app.put("/api/storyboard/shots/:index", async (c) => {
834
935
  const index = Number(c.req.param("index"));
835
936
  if (!Number.isInteger(index) || index < 0)
836
937
  throw new InvalidError("Shot index must be a whole number from 0");
837
938
  const b = await body(c, StoryboardShotBody);
939
+ const storyboard = await storyboards.of(await filmOf(b.video, "the storyboard"));
838
940
  return c.json({ storyboard: await storyboard.setShot(index, b.heading, { description: b.description, direction: b.direction, status: b.status }, b.hash) });
839
941
  });
840
942
  app.put("/api/brief/status", async (c) => {
841
943
  const b = await body(c, BriefStatusBody);
944
+ const brief = await briefs.of(await filmOf(b.video, "the brief"));
842
945
  return c.json({ brief: await brief.setStatus(b.status, b.hash) });
843
946
  });
844
947
  // ---- notes ----
@@ -847,7 +950,8 @@ export function createApp(store, opts = {}) {
847
950
  if (!q.success)
848
951
  throw new InvalidError("Query is invalid", q.error.issues);
849
952
  const [{ notes }, visuals, project] = await Promise.all([store.read("notes"), store.read("visuals"), store.read("project")]);
850
- const listed = filterNotes(notes, { ...q.data, onlyThisFormat: q.data.onlyThisFormat === "true" }).filter((n) => q.data.includeShelved === "true" || q.data.batch !== undefined || noteInPlay(n, project));
953
+ const video = q.data.video ? chooseFilm(project, q.data.video).id : undefined;
954
+ const listed = filterNotes(notes, { ...q.data, video, videos: project.videos, onlyThisFormat: q.data.onlyThisFormat === "true" }).filter((n) => q.data.includeShelved === "true" || q.data.batch !== undefined || noteInPlay(n, project));
851
955
  return c.json({ notes: withVisualViews(listed, visuals) });
852
956
  });
853
957
  app.post("/api/notes", async (c) => {
@@ -867,7 +971,15 @@ export function createApp(store, opts = {}) {
867
971
  shot = shotAt(version.shots, b.t);
868
972
  }
869
973
  }
870
- const { result } = await store.update("notes", (f) => addNote(f, { ...b, shot, by: "user" }));
974
+ // §31.2.4: nothing is made on no film. A note that names none, in a project with several films, is the first film's
975
+ // (a visual's is on every film and names none). With one film, or none yet, it is left as it is.
976
+ let video = b.video ?? null;
977
+ if (!video && b.stage !== "visuals") {
978
+ const project = await store.read("project");
979
+ if (project.videos.length > 1)
980
+ video = project.videos[0].id;
981
+ }
982
+ const { result } = await store.update("notes", (f) => addNote(f, { ...b, video, shot, by: "user" }));
871
983
  return c.json({ note: withState(result) }, 201);
872
984
  });
873
985
  app.patch("/api/notes/:id", async (c) => {
@@ -889,7 +1001,9 @@ export function createApp(store, opts = {}) {
889
1001
  app.post("/api/replies", async (c) => {
890
1002
  const b = await body(c, RepliesBody);
891
1003
  const { result } = await store.update("notes", (f) => b.replies.map((r) => applyReply(f, r)));
892
- await log.add(() => repliesEvent(result), by(c));
1004
+ // §30: one line per film, so each film's Activity counts only its own notes.
1005
+ for (const [film, notes] of byFilm(result, (n) => n.video))
1006
+ await log.add(() => repliesEvent(notes, film), by(c));
893
1007
  return c.json({ notes: result.map(withState) });
894
1008
  });
895
1009
  // ---- media ----
@@ -938,8 +1052,14 @@ export function createApp(store, opts = {}) {
938
1052
  // before formats (a formats call was refused above).
939
1053
  const size = read && isPictureSize(read.width, read.height) ? read : null;
940
1054
  const formatWarnings = [];
941
- // §24.12: the storyboard's shots, read before the write so the write itself waits for nothing.
942
- const planned = await storyboard.cutShots();
1055
+ // §24.12: the storyboard's shots, read before the write so the write itself waits for nothing. §31.3: the film's
1056
+ // own storyboard, and only for its first cut: work out which film the cut is for, as addVersion will.
1057
+ const before = await store.read("project");
1058
+ const known = before.videos.find((v) => v.id === b.video || v.id === slugify(b.video));
1059
+ const plannedFor = known?.id ?? uniqueId(slugify(b.video), before.videos.map((v) => v.id));
1060
+ const planned = known && known.versions.length > 0
1061
+ ? []
1062
+ : await storyboards.at(filmPlace({ videos: known ? before.videos : [...before.videos, { id: plannedFor }] }, plannedFor)).cutShots();
943
1063
  let lockedVersion = null;
944
1064
  let autoProxy = false;
945
1065
  let films = 1;
@@ -967,7 +1087,7 @@ export function createApp(store, opts = {}) {
967
1087
  formatWarnings.push(added.warning);
968
1088
  }
969
1089
  // A film's first cut starts with the storyboard's shots, once (never recomputed). Those at or past the cut's end are left out.
970
- if (planned.length && out.video.versions.length === 1 && out.version.shots.length === 0) {
1090
+ if (planned.length && out.video.id === plannedFor && out.video.versions.length === 1 && out.version.shots.length === 0) {
971
1091
  const reachable = planned.filter((s) => out.version.duration === null || s.start < out.version.duration);
972
1092
  if (reachable.length)
973
1093
  setShots(p, out.video.id, out.version.id, reachable);
@@ -999,7 +1119,10 @@ export function createApp(store, opts = {}) {
999
1119
  proxy.proxyJob = jobs.start(result.video.id, result.version.id);
1000
1120
  }
1001
1121
  // §24.12: a soft nudge, never a refusal: the plan (brief, script, storyboard) is not all approved yet.
1002
- const planNote = planWarning(await planBuild());
1122
+ const planNote = planWarning(await planBuild(result.video.id));
1123
+ // §31.4: a project that has just gained its second film moves what was on no film to the first one.
1124
+ if (films > 1)
1125
+ await moveToFirstFilmOnce(store, log).catch((e) => console.error(`Rushes: couldn't move what was on no film: ${e.message}`));
1003
1126
  const warnings = { ...(formatWarnings.length ? { formatWarnings } : {}), ...(planNote ? { planWarning: planNote } : {}) };
1004
1127
  const reply = { video: result.video, version: result.version, ...(restored ? { restored: true } : {}) };
1005
1128
  if (lockedVersion)
@@ -1188,10 +1311,15 @@ export function createApp(store, opts = {}) {
1188
1311
  const cues = b.cues?.map((q) => (q.file === undefined ? q : { ...q, file: toManifestPath(store.root, q.file) }));
1189
1312
  const { result } = await store.update("project", (p) => {
1190
1313
  const added = addVariant(p, { ...b, cues, file: toManifestPath(store.root, b.file) });
1191
- // With more than one film, a variant on no film is listed on none of their tabs: say so, so the agent names one.
1192
- const warning = variantFilms(added.variant).length === 0 && p.videos.length > 1
1193
- ? `No film was named, and none could be told from the names, so this ${added.lane.stage === "voice" ? "read" : added.lane.stage === "music" ? "bed" : "pass"} is on no film: it waits, folded, under "Not on this film" on each film's tab. Pass \`video\` (a film's id or name, or a list of them) to put it on films.`
1194
- : undefined;
1314
+ // §31.2.4: nothing is made on no film. With more than one film, one that names none and can't be told from its
1315
+ // names goes on the first film: say so, so the agent names one next time (or moves it with rushes_set_films).
1316
+ let warning;
1317
+ if (variantFilms(added.variant).length === 0 && p.videos.length > 1) {
1318
+ const first = p.videos[0];
1319
+ added.variant.videos = [first.id];
1320
+ const what = added.lane.stage === "voice" ? "read" : added.lane.stage === "music" ? "bed" : "pass";
1321
+ warning = `No film was named, and none could be told from the names, so this ${what} is on ${first.name}, the project's first film. Pass \`video\` (a film's id or name, or a list of them) to put it on the films it was made for, or move it with rushes_set_films.`;
1322
+ }
1195
1323
  return { ...added, ...(warning ? { warning } : {}) };
1196
1324
  });
1197
1325
  await log.add(() => variantEvent(result.lane, result.variant), by(c));
@@ -1233,29 +1361,45 @@ export function createApp(store, opts = {}) {
1233
1361
  return c.json({ variant: result });
1234
1362
  });
1235
1363
  // ---- script ----
1236
- app.get("/api/script", async (c) => c.json({ script: await store.read("script") }));
1364
+ // §31.3: each film has its own script. ?video= (or `video` in a write's body) names it: with one film it may be
1365
+ // left out; with several, leaving it out is refused with the films listed (§31.6).
1366
+ app.get("/api/script", async (c) => {
1367
+ const [project, file] = await Promise.all([store.read("project"), store.read("script")]);
1368
+ const film = chooseFilm(project, videoQuery(c), "the script")?.id ?? null;
1369
+ const own = filmScript(file, project, film);
1370
+ // The shape it always had (schema, rev, wordsPerSecond, sections), now one film's, with the film named.
1371
+ return c.json({ script: { schema: file.schema === 1 && film === firstFilm(project) ? 1 : 2, rev: file.rev, ...own, ...(film ? { video: film } : {}) } });
1372
+ });
1237
1373
  app.put("/api/script", async (c) => {
1238
1374
  const b = await body(c, ScriptBody);
1239
- const { result } = await store.update("script", (s) => {
1375
+ const project = await store.read("project");
1376
+ const film = chooseFilm(project, b.video, "the script")?.id ?? null;
1377
+ const { result } = await store.update("script", (f) => {
1378
+ const s = filmScriptDraft(f, project, film);
1240
1379
  if (b.wordsPerSecond)
1241
1380
  s.wordsPerSecond = b.wordsPerSecond;
1242
1381
  return setSections(s, b.sections, { replace: b.replace });
1243
1382
  });
1244
- await log.add(() => scriptEvent(result.length), by(c));
1245
- return c.json({ sections: result });
1383
+ // The film is named on the line only with several films, so a one-film project's log reads as it always did.
1384
+ await log.add(() => scriptEvent(result.length, project.videos.length > 1 ? film : null), by(c));
1385
+ return c.json({ sections: result, ...(film ? { video: film } : {}) });
1246
1386
  });
1247
1387
  app.patch("/api/script/:id", async (c) => {
1248
- const b = await body(c, SectionEditBody);
1249
- const { result } = await store.update("script", (s) => editSection(s, c.req.param("id"), b));
1388
+ const { video, ...b } = await body(c, SectionEditBody);
1389
+ const project = await store.read("project");
1390
+ const film = chooseFilm(project, video, "the script")?.id ?? null;
1391
+ const { result } = await store.update("script", (f) => editSection(filmScriptDraft(f, project, film), c.req.param("id"), b));
1250
1392
  return c.json({ section: result });
1251
1393
  });
1252
1394
  app.post("/api/script/:id/takes", async (c) => {
1253
1395
  const b = await body(c, TakeBody);
1396
+ const project = await store.read("project");
1397
+ const film = chooseFilm(project, b.video, "the take")?.id ?? null;
1254
1398
  const file = toManifestPath(store.root, b.file);
1255
1399
  const info = await probe(fromManifestPath(store.root, file), { formats: AUDIO_FORMATS });
1256
- const { data, result } = await store.update("script", (s) => addTake(s, c.req.param("id"), { file, duration: info.duration }));
1400
+ const { data, result } = await store.update("script", (f) => addTake(filmScriptDraft(f, project, film), c.req.param("id"), { file, duration: info.duration }));
1257
1401
  await log.add(() => {
1258
- const section = data.sections.find((s) => s.id === c.req.param("id"));
1402
+ const section = filmScript(data, project, film).sections.find((s) => s.id === c.req.param("id"));
1259
1403
  return takeEvent(section, result, section.takes.findIndex((t) => t.id === result.id) + 1);
1260
1404
  }, by(c));
1261
1405
  return c.json({ take: result }, 201);
@@ -1266,7 +1410,7 @@ export function createApp(store, opts = {}) {
1266
1410
  // agent and the loudness readout can never disagree about it.
1267
1411
  // Always among the takes the film hears (lanesForVideo), which is what Mix plays and the readout
1268
1412
  // measures: a take that has left the film is never its take in use.
1269
- const filmUse = (project, picks, video) => inUse({ lanes: lanesForVideo(project.lanes, video, project.videos.length) }, picksForVideo(picks, video));
1413
+ const filmUse = (project, picks, video) => inUse({ lanes: lanesForVideo(project.lanes, video, project.videos) }, picksForVideo(picks, video));
1270
1414
  const withUse = (project, picks, video) => {
1271
1415
  if (video)
1272
1416
  return { ...picksForVideo(picks, video), use: filmUse(project, picks, video) };
@@ -1386,7 +1530,7 @@ export function createApp(store, opts = {}) {
1386
1530
  */
1387
1531
  const runBalance = async (video, who, guard) => {
1388
1532
  const [project, picks] = await Promise.all([store.read("project"), store.read("picks")]);
1389
- const heard = { ...project, lanes: lanesForVideo(project.lanes, video, project.videos.length) };
1533
+ const heard = { ...project, lanes: lanesForVideo(project.lanes, video, project.videos) };
1390
1534
  const result = await balanceFilm(heard, picksForVideo(picks, video), store.root, opts.loudnessRunner ?? defaultRunner, opts.loudnessTimeoutMs);
1391
1535
  if (!result.available)
1392
1536
  return { result, written: false, project, picks };
@@ -1453,7 +1597,7 @@ export function createApp(store, opts = {}) {
1453
1597
  const [project, picks] = await Promise.all([store.read("project"), store.read("picks")]);
1454
1598
  const run = opts.loudnessRunner ?? defaultRunner;
1455
1599
  // A film hears only its own reads, beds and passes, as its Mix tab plays them.
1456
- const heard = { ...project, lanes: lanesForVideo(project.lanes, b.video, project.videos.length) };
1600
+ const heard = { ...project, lanes: lanesForVideo(project.lanes, b.video, project.videos) };
1457
1601
  const result = await measureMix(heard, picksForVideo(picks, b.video), b.lanes, store.root, run, opts.loudnessTimeoutMs);
1458
1602
  return c.json(result);
1459
1603
  });
@@ -1479,23 +1623,43 @@ export function createApp(store, opts = {}) {
1479
1623
  return settled === late ? { handedTo: agent.status().agent, starting: true } : settled;
1480
1624
  };
1481
1625
  app.post("/api/batches", async (c) => {
1482
- const { stage } = await body(c, BatchBody);
1626
+ const { stage, video } = await body(c, BatchBody);
1627
+ // §32: a Send before the desk has read the agent still goes where the Mac-wide default says.
1628
+ await adoptAgentDefaultsOnce(store);
1629
+ // §31.2.2: Send on a film sends that film's notes and script alone, and the batch carries the film.
1630
+ const film = video ? chooseFilm(await store.read("project"), video).id : null;
1483
1631
  let handing;
1484
1632
  const run = batchQueue.catch(() => undefined).then(async () => {
1485
1633
  const [project, script, notes, batches] = await Promise.all([store.read("project"), store.read("script"), store.read("notes"), store.read("batches")]);
1486
1634
  // createBatch marks the notes it takes and files the batch in `batches`; on copies, it only
1487
1635
  // tells us what goes in.
1488
- const result = createBatch({ project, script, notes: structuredClone(notes), batches: structuredClone(batches) }, stage);
1636
+ const result = createBatch({ project, script: filmScript(script, project, film), notes: structuredClone(notes), batches: structuredClone(batches), video: film }, stage);
1489
1637
  // R11: the prompt ends with the last five lines of the log, from before this send. A log that
1490
- // can't be read adds nothing: the batch must still be sent.
1638
+ // can't be read adds nothing: the batch must still be sent. §31.5: with a film, the lines Activity shows on it.
1491
1639
  const recent = await Promise.all([store.read("project"), store.read("script")])
1492
- .then(async ([projectNow, scriptNow]) => recentChanges((await log.view({ limit: 5 }, { project: projectNow, script: scriptNow })).entries))
1640
+ .then(async ([projectNow, scriptNow]) => recentChanges((await log.view({ limit: 5, ...(film ? { video: film } : {}) }, { project: projectNow, script: everySection(scriptNow), films: { videos: projectNow.videos, lanes: projectNow.lanes, notes: notes.notes } })).entries))
1493
1641
  .catch(() => "");
1494
1642
  if (recent)
1495
1643
  result.prompt = `${result.prompt}\n\n${recent}`;
1496
1644
  await store.update("batches", (f) => { f.batches.push(result); });
1497
1645
  await store.update("notes", (f) => markSent(f.notes, result));
1498
- await log.add(() => notesSentEvent(result), by(c));
1646
+ // §30: one line per film the batch's notes are on (its script edits go with the notes on no film). §31.2.2: a
1647
+ // batch sent on a film is that film's alone: one line, script edits and the shared visuals' notes included.
1648
+ const noteFilm = new Map(notes.notes.map((n) => [n.id, n.video ?? null]));
1649
+ const stageOf = new Map(notes.notes.map((n) => [n.id, n.stage]));
1650
+ const own = film && project.videos.length > 1 ? film : null;
1651
+ const groups = own ? [[own, result.noteIds]] : byFilm(result.noteIds, (id) => noteFilm.get(id));
1652
+ const takesEdits = (f) => f === null || f === own;
1653
+ if (groups.length === 0 || (result.sectionIds.length > 0 && !groups.some(([f]) => takesEdits(f))))
1654
+ groups.push([own, []]);
1655
+ for (const [lineFilm, ids] of groups) {
1656
+ const sectionIds = takesEdits(lineFilm) ? result.sectionIds : [];
1657
+ // Each film's line names the tab its own notes came from ("from Picture"), not the whole batch's.
1658
+ const stages = new Set([...ids.map((id) => stageOf.get(id)), ...(sectionIds.length ? ["script"] : [])]);
1659
+ const stage = stages.size === 1 ? ([...stages][0] ?? result.stage) : result.stage;
1660
+ const part = { ...result, stage, noteIds: ids, sectionIds };
1661
+ await log.add(() => notesSentEvent(part, lineFilm), by(c));
1662
+ }
1499
1663
  handing = (async () => agent.send(result))();
1500
1664
  return result;
1501
1665
  });
@@ -1503,16 +1667,40 @@ export function createApp(store, opts = {}) {
1503
1667
  const batch = await run;
1504
1668
  return c.json({ batch, agent: await handOverOf(handing) }, 201);
1505
1669
  });
1670
+ // I3, Send again: a batch whose hand-over was refused while Send to AI was on (its `undelivered` mark) goes to the
1671
+ // agent now, while notes of it still wait. The mark is in batches.json, so this works after a restart too. Refused
1672
+ // again (still not signed in), it says why and keeps the mark, as Send does.
1673
+ app.post("/api/batches/:id/resend", async (c) => {
1674
+ const id = c.req.param("id");
1675
+ const [batches, notes] = await Promise.all([store.read("batches"), store.read("notes")]);
1676
+ const batch = batches.batches.find((b) => b.id === id);
1677
+ if (!batch)
1678
+ throw new NotFoundError("batch", id);
1679
+ if (!notes.notes.some((n) => n.batch === id && noteState(n) === "sent")) {
1680
+ throw new RushesError(`Nothing in ${id} is waiting for the agent any more.`, 409, "batch_not_waiting");
1681
+ }
1682
+ if (!batch.undelivered)
1683
+ throw new RushesError(`${id} already reached the agent.`, 409, "batch_delivered");
1684
+ const handed = await handOverOf(agent.resend(batch));
1685
+ // Null: another Send again took it a moment ago.
1686
+ if (!handed)
1687
+ throw new RushesError(`${id} already reached the agent.`, 409, "batch_delivered");
1688
+ return c.json({ batch: { ...batch, undelivered: null }, agent: handed });
1689
+ });
1506
1690
  app.get("/api/batches/:id", async (c) => {
1507
- const [batches, notes, script, visuals] = await Promise.all([store.read("batches"), store.read("notes"), store.read("script"), store.read("visuals")]);
1691
+ const [batches, notes, script, visuals, project] = await Promise.all([store.read("batches"), store.read("notes"), store.read("script"), store.read("visuals"), store.read("project")]);
1508
1692
  const id = c.req.param("id");
1509
1693
  const batch = id === "latest" ? latestBatch(batches) : batches.batches.find((b) => b.id === id);
1510
1694
  if (!batch)
1511
1695
  throw new NotFoundError("batch", id);
1696
+ // §31.6: a batch is about one film (its `video`): its sections are that film's script's, and the film is named so an
1697
+ // agent working the batch passes it on. A batch from before names none: its sections are the first film's.
1698
+ const film = batch.video ? project.videos.find((v) => v.id === batch.video) : undefined;
1512
1699
  return c.json({
1513
1700
  batch,
1701
+ ...(film ? { film: { id: film.id, name: film.name } } : {}),
1514
1702
  notes: withVisualViews(notes.notes.filter((n) => batch.noteIds.includes(n.id)), visuals),
1515
- sections: script.sections.filter((s) => batch.sectionIds.includes(s.id)),
1703
+ sections: filmScript(script, project, batch.video ?? null).sections.filter((s) => batch.sectionIds.includes(s.id)),
1516
1704
  });
1517
1705
  });
1518
1706
  // ---- visuals (§25) ----
@@ -1535,8 +1723,9 @@ export function createApp(store, opts = {}) {
1535
1723
  const q = LogQuery.safeParse(c.req.query());
1536
1724
  if (!q.success)
1537
1725
  throw new InvalidError(q.error.issues.map((i) => i.message).join("; "), q.error.issues);
1538
- const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
1539
- return c.json(await log.view(q.data, { project, script }));
1726
+ const [project, script, notes] = await Promise.all([store.read("project"), store.read("script"), store.read("notes")]);
1727
+ const video = q.data.video ? chooseFilm(project, q.data.video).id : undefined;
1728
+ return c.json(await log.view({ ...q.data, video }, { project, script: everySection(script), films: { videos: project.videos, lanes: project.lanes, notes: notes.notes } }));
1540
1729
  });
1541
1730
  app.post("/api/log", async (c) => {
1542
1731
  const b = await body(c, LogLineBody);
@@ -1571,7 +1760,7 @@ export function createApp(store, opts = {}) {
1571
1760
  const script = await store.read("script");
1572
1761
  const refs = new Set([
1573
1762
  ...project.lanes.flatMap((l) => l.variants.map((x) => `${l.id}/${x.id}`)),
1574
- ...script.sections.flatMap((s) => s.takes.map((x) => `${s.id}:${x.id}`)),
1763
+ ...allSections(script).flatMap((s) => s.takes.map((x) => `${s.id}:${x.id}`)),
1575
1764
  ]);
1576
1765
  if (!refs.has(b.ref))
1577
1766
  throw new NotFoundError("ref", shown(b.ref));
@@ -1583,7 +1772,11 @@ export function createApp(store, opts = {}) {
1583
1772
  });
1584
1773
  // ---- Send to AI (§28) ----
1585
1774
  const agentStatusOf = async () => ({ status: await agent.reload() });
1586
- app.get("/api/agent", async (c) => c.json(await agentStatusOf()));
1775
+ // §32: the desk reads this as it loads: a project with no rules of its own starts from the Mac-wide default first.
1776
+ app.get("/api/agent", async (c) => {
1777
+ await adoptAgentDefaultsOnce(store);
1778
+ return c.json(await agentStatusOf());
1779
+ });
1587
1780
  // ?fresh=1 checks again now (after the user signs in), not from the last 30 s.
1588
1781
  app.get("/api/agent/detect", async (c) => {
1589
1782
  if (c.req.query("fresh") === "1")
@@ -1600,7 +1793,9 @@ export function createApp(store, opts = {}) {
1600
1793
  // else. It never chooses an agent, never keeps one the user didn't choose, and leaves the switch as it is.
1601
1794
  const permissions = b.permissions;
1602
1795
  if (permissions !== undefined && b.agent === undefined) {
1603
- await rules.update((f) => void (f.permissions = permissions));
1796
+ const { data } = await rules.update((f) => void (f.permissions = permissions));
1797
+ // §32: the menu's choice is the default for new projects too.
1798
+ await rememberDefault({ permissions }, data);
1604
1799
  return c.json(await agentStatusOf());
1605
1800
  }
1606
1801
  // The row's switch names no agent: it turns on the one agent.json names, so it can't stand in for the sheet's "who"
@@ -1649,6 +1844,12 @@ export function createApp(store, opts = {}) {
1649
1844
  });
1650
1845
  if (b.on)
1651
1846
  await consent();
1847
+ // §32: the user's choice is Send to AI's default for every new project on this Mac (last choice wins): the agent
1848
+ // turned on, with what it may do, or no agent after Copy a prompt. Turning the switch off leaves it as it is.
1849
+ if (b.on || b.prompt) {
1850
+ const now = await rules.read();
1851
+ await rememberDefault({ agent: b.on ? checked : null, ...(permissions !== undefined ? { permissions } : {}) }, now);
1852
+ }
1652
1853
  // I3: the batch the dialog showed goes to the agent now, if its hand-over was refused and it hasn't gone since (the
1653
1854
  // runner takes it from its refused set once, under its send lock), while notes of it still wait.
1654
1855
  if (b.on && filed && (await store.read("notes")).notes.some((n) => n.batch === filed.id && noteState(n) === "sent")) {