The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Desktop: agents as in their own terminal; Studio: CapCut's keys and editing polish (#32)
riverisbuilding60cb1133417d
diff --git a/.changeset/about-update.md b/.changeset/about-update.mdnew file mode 100644index 0000000..db65881--- /dev/null+++ b/.changeset/about-update.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Settings → About in the desktop app shows the version and its update without going to the menu: it looks for one on opening (unless it looked a few minutes ago), shows "Up to date" with when it last checked, or the new version downloading with its progress, then "Restart to update" once it is ready (it installs at the next quit too). A failed check says why, with Try again. A build run from source says it doesn't update itself. The menu's Check for Updates… is still there.diff --git a/.changeset/agent-background-context.md b/.changeset/agent-background-context.mdnew file mode 100644index 0000000..cb0ca76--- /dev/null+++ b/.changeset/agent-background-context.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: when a background task of the agent's own ends after its turn (a command Claude Code ran in the background, a subagent) and it takes it up by itself, the chat shows that work as a turn of its own, under "A background task finished; the agent went on", with its log; before, it was lost. It ends with the agent's result, and as soon as you write. A ring beside the composer's tools shows how full the agent's context is in the conversation, with the numbers on hover. The `/` menu has the agent's commands from the start (they were there only after a first message), keeps them between launches, finds them by name, and shows each name whole.diff --git a/.changeset/agent-commands.md b/.changeset/agent-commands.mdnew file mode 100644index 0000000..b99cb1a--- /dev/null+++ b/.changeset/agent-commands.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: the agent's own commands in the chat, as in its own: type `/` at the start of a message for the list Claude Code or Codex gives (their built-in commands and your own skills and custom commands), with what each does; it goes to the agent as typed.diff --git a/.changeset/agent-conversations-resume.md b/.changeset/agent-conversations-resume.mdnew file mode 100644index 0000000..bef5bca--- /dev/null+++ b/.changeset/agent-conversations-resume.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: each conversation in the chat is its own session of the agent's, and it goes on where it stopped after a restart, a reload, or switching conversations: the chat keeps the agent's own session id and resumes it, as `claude --resume` or `codex resume` would. A new conversation starts a new session (it carried the last one's context before). A session left idle for 20 minutes closes, and its next message resumes it. A picture attached to a message is sent to the agent beside the text, as one pasted in its own chat is, besides being put in the project. The message goes as written (the first one no longer starts with a line about the language), so a slash command typed first works.diff --git a/.changeset/agent-instructions-own-command.md b/.changeset/agent-instructions-own-command.mdnew file mode 100644index 0000000..41de356--- /dev/null+++ b/.changeset/agent-instructions-own-command.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: the chat's agents are told to use the app's own `openfilm` command, not `npx openfilm` (which an installed OpenFilm skill says), so they work on the Studio in the window at its version; and only not to open Studio in a browser, rather than never to open a browser.diff --git a/.changeset/agent-options-fresh.md b/.changeset/agent-options-fresh.mdnew file mode 100644index 0000000..f2891e5--- /dev/null+++ b/.changeset/agent-options-fresh.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: the model menu has the models the agent offers now. It asks each agent for its options once a launch (what it had from before shows meanwhile), so an updated Claude Code's models replace the ones an earlier version had; and a pick it no longer offers is dropped for the agent's own default.diff --git a/.changeset/agent-steering.md b/.changeset/agent-steering.mdnew file mode 100644index 0000000..f94f64e--- /dev/null+++ b/.changeset/agent-steering.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: write to Claude Code or Codex while it works, as in its own chat. The composer's button turns from Stop to Send once something is written, and the message goes into the running turn (the agent reads it at its next step); it shows as a message of its own, with what the agent does from then on under it. An agent that cannot take a message mid-turn gets it as soon as the turn ends, as before. Esc still stops.diff --git a/.changeset/agent-turn-lighter.md b/.changeset/agent-turn-lighter.mdnew file mode 100644index 0000000..4a81dba--- /dev/null+++ b/.changeset/agent-turn-lighter.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: less work around a running agent. Studio no longer redraws the film when the agent writes a file no page loads (its notes, scripts, logs). The chat around a turn no longer re-renders for every word the agent streams. A model menu whose agent did not answer is asked again only when the menu opens or on Retry, not on every render (each try was a whole session of the agent's). A turn's log open while it runs is read again only once it has grown.diff --git a/.changeset/agents-account.md b/.changeset/agents-account.mdnew file mode 100644index 0000000..f193f9e--- /dev/null+++ b/.changeset/agents-account.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Settings → Agents shows whose account each of your agents uses (organization, email and plan for Claude Code; the ChatGPT account for Codex). The agents use the account signed in on your computer: to use another, switch accounts in the agent itself, then disconnect and connect it again in OpenFilm.diff --git a/.changeset/agents-as-in-terminal.md b/.changeset/agents-as-in-terminal.mdnew file mode 100644index 0000000..3810991--- /dev/null+++ b/.changeset/agents-as-in-terminal.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: Claude Code and Codex in the chat run as they do in your terminal. They get everything your shell sets (an API key or a gateway such as ANTHROPIC_BASE_URL, an MCP server's token, your certificates, your ssh agent), where before they got only its PATH. Their model and reasoning effort are your own config's until you pick another in the menu (the chat no longer sets High). Codex keeps your own developer_instructions, with OpenFilm's after them. Your ffmpeg and Playwright browsers come first for the commands they run; the app's ffmpeg and browser go only to the `openfilm` command (and ffmpeg last on the PATH, for a computer that has none). Electron's ELECTRON_RUN_AS_NODE no longer reaches their commands. A session starts without waiting on your shell to be read again.diff --git a/.changeset/agents-found-on-windows.md b/.changeset/agents-found-on-windows.mdnew file mode 100644index 0000000..a91b5a3--- /dev/null+++ b/.changeset/agents-found-on-windows.md@@ -0,0 +1,7 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: Codex, Claude Code and the other agents are found on Windows where they were missed. The PATH is read as Windows has it now, so an agent installed after signing in to Windows is found without signing out; the folders of pnpm, Volta, nvm-windows, Yarn, Bun, Scoop, Chocolatey and winget are searched, with npm's own global folder; and the shims npm, pnpm and Yarn write are read correctly (npm's current shim was taken for its node.exe). A shim that cannot be read is started through cmd.exe. On a Mac too, the login shell's PATH is read again while the app runs, so an agent installed meanwhile is found without restarting the app.+Settings → Agents: an agent not found has Locate…, which opens the file dialog; the program chosen is tried (it has to answer `--version`) and used from then on, until Find it automatically. "Why isn't it found?" says what to do (installed only in WSL, files that cannot start, nothing found) and copies a report of every folder searched, to send with an issue.diff --git a/.changeset/agents-full-access-only.md b/.changeset/agents-full-access-only.mdnew file mode 100644index 0000000..5f8df81--- /dev/null+++ b/.changeset/agents-full-access-only.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: the model menu has no Mode: every agent works with full access, and a plan mode picked there before is no longer applied.diff --git a/.changeset/agents-not-signed-in.md b/.changeset/agents-not-signed-in.mdnew file mode 100644index 0000000..3fe60cb--- /dev/null+++ b/.changeset/agents-not-signed-in.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Settings → Agents says "Not signed in" for an agent that has never been signed in on the computer, instead of "Signed out".diff --git a/.changeset/agents-usage.md b/.changeset/agents-usage.mdnew file mode 100644index 0000000..8c5f742--- /dev/null+++ b/.changeset/agents-usage.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Settings → Agents shows what is left of Codex's plan without opening it: each window (five hours, this week) with a bar of how much is used and when it resets, as Codex itself says, and its account's email and plan. Claude Code's is not shown: its own report said 0% of a Team account the Claude app showed half used.diff --git a/.changeset/canvas-in-place.md b/.changeset/canvas-in-place.mdindex 1cf7e5d..0a5ec56 100644--- a/.changeset/canvas-in-place.md+++ b/.changeset/canvas-in-place.md@@ -3,4 +3,4 @@---Studio: a canvas change is applied to the picture in place, without loading the film again, so the film no longer jumps to the top left before it settles in the middle. Dragging the canvas's width or height in the inspector changes the picture as the mark moves. The picture no longer shows a light hairline along its right and bottom edges in the dark theme.-Studio's address keeps its key (`?key=…`), so an address copied from the address bar opens Studio in any browser on this computer, or in an agent's preview, without being signed out. The picture is clipped to its own box, so no line shows along its edges. The inspector is open whenever a project opens. A canvas change fits each picture to the new canvas on its own, as CapCut does, so a portrait photo on one clip no longer shrinks 16:9 footage on another. Dragging the canvas's width or height shows the size and shape on the picture and in the inspector as it moves (Custom unless it is a preset). A click on a page's empty part selects the whole page, so a page smaller than the canvas can be moved and sized on the picture. A canvas side typed or dragged stays from 16 to 8192 px and within 1:4 to 4:1. With a whole page in hand, a click on something in it selects that (a drag still moves the page). ⌘A (Ctrl+A) selects every layer on the picture; Shift-click and a drag on empty space select several, as before. Everything a click can select is outlined under the pointer: a page's layers, a whole page by its empty part, a video or a still, with a clip in hand too. A marquee around whole clips on the picture (by the part on the canvas) selects those clips, as Figma takes the frames it goes around; one inside a page selects its layers, as before. While a marquee is drawn, what letting go would select is outlined as it goes. Several clips selected have one frame around them all, and a drag on one of them moves them all, written in one step. The frame around several clips can be dragged anywhere inside it, empty space too, and its corners scale them all in proportion; its size shows below it. Several clips' frame also turns (its corner rings, Shift in 15° steps) and, for videos, stretches from its sides; the arrow keys move them all. Several layers selected show their shared looks in the inspector (type, appearance, adjustments, effects), and let go when the timeline is pressed or the playhead leaves their clip, as one layer does. A clip selected on the timeline away from the playhead has no frame on the picture until the playhead reaches it. A new mask has a hard edge (no feather). The inspector's menus (blend mode, font weight) and the export's range ends open Studio's own dark menu instead of the system's light list. The inspector follows Figma's: several things' X, Y, W and H are their bounds, typed to move or scale them together; Appearance has corner radius, one for all or each corner its own; Fill is a section of its own (a line's color, a box's background, with + and −); Stroke is too, drawn as an outline that adds nothing to the box, inside, centered or outside the edge; Effects add an inner shadow, a layer blur and a background blur beside the drop shadow and faded edges; type can be underlined or struck through. Under a mask, a crop or faded edges, which cut away what is past the edge, the stroke offers Inside only (a stroke already placed otherwise shows where it is, with a note). Setting one corner keeps the others; removing a fill leaves the layer see-through (not the page's own fill back) and still selectable; an SVG shape's fill can be set; an image's Fit button fits it. A clip that plays all of its file shows its in point grayed out, with a note to shorten it first. The Mask button on the picture's selection bar opens a menu of shapes (the one on now checked): the one picked is put on the clip, its handles on the picture. Where a mask or a crop cuts the picture away, nothing is found under the pointer: a clip's, a layer's own, or a parent's that clips what overflows it; a click there reaches what is under it, as in Photoshop and Figma.+Studio's address keeps its key (`?key=…`), so an address copied from the address bar opens Studio in any browser on this computer, or in an agent's preview, without being signed out. The picture is clipped to its own box, so no line shows along its edges. The inspector is open whenever a project opens. A canvas change fits each picture to the new canvas on its own, as CapCut does, so a portrait photo on one clip no longer shrinks 16:9 footage on another. Dragging the canvas's width or height shows the size and shape on the picture and in the inspector as it moves (Custom unless it is a preset). A click on a page's empty part selects the whole page, so a page smaller than the canvas can be moved and sized on the picture. A canvas side typed or dragged stays from 16 to 8192 px and within 1:4 to 4:1. With a whole page in hand, a click on something in it selects that (a drag still moves the page). ⌘A (Ctrl+A) selects every layer on the picture; Shift-click and a drag on empty space select several, as before. Everything a click can select is outlined under the pointer: a page's layers, a whole page by its empty part, a video or a still, with a clip in hand too. A marquee around whole clips on the picture (by the part on the canvas) selects those clips, as Figma takes the frames it goes around; one inside a page selects its layers, as before. While a marquee is drawn, what letting go would select is outlined as it goes. Several clips selected have one frame around them all, and a drag on one of them moves them all, written in one step. The frame around several clips can be dragged anywhere inside it, empty space too, and its corners scale them all in proportion; its size shows below it. Several clips' frame also turns (its corner rings, Shift in 15° steps) and, for videos, stretches from its sides; the arrow keys move them all. Several layers selected show their shared looks in the inspector (type, appearance, adjustments, effects), and let go when the timeline is pressed or the playhead leaves their clip, as one layer does. A clip selected on the timeline away from the playhead has no frame on the picture until the playhead reaches it. A new mask has a hard edge (no feather). The inspector's menus (blend mode, font weight) and the export's range ends open Studio's own dark menu instead of the system's light list. The inspector follows Figma's: several things' X, Y, W and H are their bounds, typed to move or scale them together; Appearance has corner radius, one for all or each corner its own; Fill is a section of its own (a line's color, a box's background, with + and −); Stroke is too, drawn as an outline that adds nothing to the box, inside, centered or outside the edge; Effects add an inner shadow, a layer blur and a background blur beside the drop shadow and faded edges; type can be underlined or struck through. Under a mask, a crop or faded edges, which cut away what is past the edge, the stroke offers Inside only (a stroke already placed otherwise shows where it is, with a note). Setting one corner keeps the others; removing a fill leaves the layer see-through (not the page's own fill back) and still selectable; an SVG shape's fill can be set; an image's Fit button fits it. A clip that plays all of its file shows its in point grayed out, with a note to shorten it first. The Mask button on the picture's selection bar opens a menu of shapes (the one on now checked): the one picked is put on the clip, its handles on the picture. A clip's fades sit right under its position and size in the inspector. A marquee can start on the dark around the picture, as on Figma's canvas, so what sits at its edge can be boxed whole; a click there lets go of what is in hand.diff --git a/.changeset/capcut-keys-paste-attrs.md b/.changeset/capcut-keys-paste-attrs.mdnew file mode 100644index 0000000..274d160--- /dev/null+++ b/.changeset/capcut-keys-paste-attrs.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: CapCut's keys (its Mac set) and its paste attributes. ⌘⇧C copies a clip's attributes and ⌘⇧V pastes them onto the selected clips, with CapCut's dialog to pick position and size, blending, volume and fades (also in the clip's menu). P turns the main-track magnet on or off, ~ linkage, ⇧X sets in and out to the selected clips, ⌥X clears them, ⌘R opens the clip's speed, ⇧⌃S detaches a video's sound, ⌥⇧M goes to the previous marker, and ⇧← / ⇧→ move the playhead 10 frames.diff --git a/.changeset/chat-agent-setup.md b/.changeset/chat-agent-setup.mdnew file mode 100644index 0000000..a555888--- /dev/null+++ b/.changeset/chat-agent-setup.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++In the chat's agent menu, an agent that is not connected or signed out says "Set up" and opens Settings → Agents, where connecting and signing in are, instead of trying to connect from the menu.diff --git a/.changeset/chat-top-room.md b/.changeset/chat-top-room.mdnew file mode 100644index 0000000..268be74--- /dev/null+++ b/.changeset/chat-top-room.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++The chat opens with room above the first message, and messages scrolled up fade softly under the conversation's bar instead of meeting a hard edge.diff --git a/.changeset/chat-turns-kept-as-they-go.md b/.changeset/chat-turns-kept-as-they-go.mdnew file mode 100644index 0000000..a9e00ba--- /dev/null+++ b/.changeset/chat-turns-kept-as-they-go.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: a conversation's messages are kept as the agent works, not only once its turn ends. Quitting the app, a crash or a restart in the middle of a turn no longer loses it: it comes back as it was, marked Interrupted, and the next message goes on from there (the agent resumes its own session, so it still has everything it did). Turns lost this way before (their logs were kept) come back when their project opens.diff --git a/.changeset/click-backdrop-takes-clip.md b/.changeset/click-backdrop-takes-clip.mdnew file mode 100644index 0000000..bd92cf8--- /dev/null+++ b/.changeset/click-backdrop-takes-clip.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: a click on the empty part of a page takes the clip, so a drag moves the whole picture. A box that fills the whole page (a page's backdrop) is no longer taken instead; it is still selected in Layers, or with Alt.diff --git a/.changeset/export-china-platforms.md b/.changeset/export-china-platforms.mdnew file mode 100644index 0000000..4ed1c50--- /dev/null+++ b/.changeset/export-china-platforms.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Export › Social platforms in Chinese offers China's platforms first: 哔哩哔哩 (1080p, 60 fps), 抖音, 快手 and 视频号 (1080 × 1920) and 小红书 (3:4, 1080 × 1440), beside the others; the first time, 哔哩哔哩 is picked. Export › Project takes only the work unless more is asked each time: the work is always taken and shown on, the version history no longer starts on, and a switch's words are lit only when it is on.diff --git a/.changeset/export-missing-simple-toolbar.md b/.changeset/export-missing-simple-toolbar.mdnew file mode 100644index 0000000..d9603f5--- /dev/null+++ b/.changeset/export-missing-simple-toolbar.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: the export dialog says which media files are missing before anything is queued, and holds back exports that draw or play the film until they are relinked (a project, subtitles or an editing project still export). The timeline's toolbar is simpler: three switches in CapCut's order, main-track magnet, snapping and linkage, each with a one-line tip. Sync lock is gone (linkage does its job), and a video and its detached sound are always selected together (⌥-click picks one).diff --git a/.changeset/jianying-hand-tested.md b/.changeset/jianying-hand-tested.mdnew file mode 100644index 0000000..21ce1d2--- /dev/null+++ b/.changeset/jianying-hand-tested.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: four more things work as in CapCut (剪映, tried by hand). With the split tool, ⇧-click cuts every track at that point. ⌥-drag copies a clip (or the selection it is in): the clip stays and a copy lands where you let go, inserted on the main track and on a free track elsewhere. Clips selected together and dragged above or below every track open new tracks there, one for each track they came from. With linkage on, deleting a main-track clip deletes the titles, B-roll and sound riding on it; a music bed under several shots stays. Slip and slide are no longer ⌥-drag gestures; the inspector's source bar still slips a clip.diff --git a/.changeset/jianying-round-two.md b/.changeset/jianying-round-two.mdnew file mode 100644index 0000000..fe8dc1a--- /dev/null+++ b/.changeset/jianying-round-two.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: more of the timeline follows CapCut (剪映 v11.6, tested side by side). With the main-track magnet on, a paste covers and pushes nothing: a copy whose time is taken goes to a free track, or a new one right above the main track, and onto the main track only past its end. The empty timeline's menu gets "Close all gaps on this track". A freeze frame lasts 3 s.diff --git a/.changeset/jump-to-latest-on-expand.md b/.changeset/jump-to-latest-on-expand.mdnew file mode 100644index 0000000..d977f18--- /dev/null+++ b/.changeset/jump-to-latest-on-expand.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: opening or closing a step list in a reply no longer shows "Jump to latest" when nothing is below the view. The button shows only once content actually goes below, and if the view is still at the bottom it keeps following the reply.diff --git a/.changeset/live-turn-footer.md b/.changeset/live-turn-footer.mdnew file mode 100644index 0000000..7b0aa61--- /dev/null+++ b/.changeset/live-turn-footer.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: the line under a reply (copy, the agent and its model, and in developer mode Log) also shows while the turn runs, on hover under its status. Its Log is the turn so far and keeps reading as it goes, the newest model request first, until the turn ends; it stays open as the turn finishes. Settings: Developer moves under Help, and the foot of the list links to the code on GitHub, the examples and the website.diff --git a/.changeset/markers-undo.md b/.changeset/markers-undo.mdnew file mode 100644index 0000000..ec11889--- /dev/null+++ b/.changeset/markers-undo.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: adding, moving, naming or removing a marker is a step of the edit history, so ⌘Z undoes it and ⌘⇧Z makes it again, in turn with the film's edits.diff --git a/.changeset/pages-near-playhead.md b/.changeset/pages-near-playhead.mdnew file mode 100644index 0000000..22039be--- /dev/null+++ b/.changeset/pages-near-playhead.md@@ -0,0 +1,6 @@+---+"openfilm": patch+---++A film with many pages keeps only the eight nearest the playhead open, and opens the others as the playhead comes+near. A film of more than 16 WebGL pages no longer shows its first scenes blank, in the preview or in an export.diff --git a/.changeset/preview-missing-media.md b/.changeset/preview-missing-media.mdnew file mode 100644index 0000000..cf21f5b--- /dev/null+++ b/.changeset/preview-missing-media.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: a project with a missing media file plays again. The clip whose file is gone keeps its time and shows as black, the rest of the film plays and is heard as before, and the viewer says which file is missing while the playhead is over it, with a hint to relink it from the timeline. `openfilm check` and exports still stop at a missing file and name it.diff --git a/.changeset/select-side.md b/.changeset/select-side.mdnew file mode 100644index 0000000..d93761b--- /dev/null+++ b/.changeset/select-side.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: [ selects every clip with a part before the playhead and ] every clip with a part after it, on tracks not locked, as CapCut's 向左全选 / 向右全选.diff --git a/.changeset/sound-role-folders.md b/.changeset/sound-role-folders.mdnew file mode 100644index 0000000..fbd5b6e--- /dev/null+++ b/.changeset/sound-role-folders.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++A sound in any folder named sfx, music or vo (such as assets/sfx/) is read as an effect, music or a voice. A sound effect no longer counts as speech with no subtitles.diff --git a/.changeset/turn-file-changes.md b/.changeset/turn-file-changes.mdnew file mode 100644index 0000000..102a225--- /dev/null+++ b/.changeset/turn-file-changes.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: under each reply, the files the turn added, deleted or changed, as a coding agent's app lists them: a row each with its lines added and removed, and on a click its changed lines. The first four show, the rest open from "N more files". Settings → Developer turns it off. It replaces the "Changed N clips" line developer mode showed.diff --git a/.changeset/whats-new.md b/.changeset/whats-new.mdnew file mode 100644index 0000000..c9545d7--- /dev/null+++ b/.changeset/whats-new.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++After an update, OpenFilm says what is new, once: a few lines in your language, grouped as new, improved and fixed, with a link to the full changelog. A new install shows nothing. Settings → About shows this version's notes again, and Settings → Developer previews the next release's.diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsxindex 20b9fca..d146d30 100644--- a/apps/desktop/chat/src/App.tsx+++ b/apps/desktop/chat/src/App.tsx@@ -6,13 +6,14 @@* (lib/local-agent-run's saved turns).*/import React from 'react';-import { ArrowDown, Coins, CornerDownLeft, LibraryBig, Loader2, Play, Plus, ShieldQuestion, Square, X } from 'lucide-react';+import { ArrowDown, Coins, CornerDownLeft, LibraryBig, Loader2, Play, Plus, ShieldQuestion, Square, SquareSlash, X } from 'lucide-react';import { buildPromptDisplay, type Turn } from '@openfilm/shared';import { useT } from '@/i18n';import { ConversationSessionBar } from '@/components/ConversationSessionBar';import { ProjectConversation, primeStoredTranscript } from '@/components/ProjectConversation';import { ProjectStarters } from '@/components/ProjectStarters';import { ModelPopover } from '@/components/ModelPopover';+import { ContextMeter } from '@/components/ContextMeter';import { CardActions, CardButton, ComposerCard } from '@/components/ComposerCard';import { LocalAgentQuestionCard } from '@/components/TurnQuestionCard';import { Tooltip } from '@/components/Tooltip';@@ -20,29 +21,37 @@ import { StickToBottomContext, useStickToBottom, useTailSpacer } from '@/componeimport { PromptEditor, PromptPill, PromptPillHoverContext, PromptPillRevealContext, fileReferenceId, fileReferencePath, promptReferenceToken, resolvePromptReferences, splitPromptReferenceText, type MentionProvider, type PromptEditorHandle, type PromptEditorState, type PromptPillHover, type PromptReference } from '@/components/prompt-editor';import { filesFromTransfer, transferHasFiles } from '@/lib/composer-attachments';import { attachmentIcon } from '@/lib/project-resources';-import { attachedText, attachmentBlocker, formatFileSize, turnAttachments, useDesktopAttachments } from '@/lib/desktop-attachments';+import { attachedPictures, attachedText, attachmentBlocker, formatFileSize, turnAttachments, useDesktopAttachments } from '@/lib/desktop-attachments';import { deriveProjectTurns } from '@/lib/project-versions';import { makePlaceholder, mergeAssetLists } from '@/lib/asset-lists';import {answerLocalAgentPermission,answerLocalAgentQuestion,cancelLocalAgentTurn,+ canSteer,createLocalAgentTurn,finishRunningLocalTurn,loadLocalAgentTurns,+ localAgentTurn,makeLocalAgentTurnId,+ onUnpromptedTurn,recoverLocalAgentTurns,registerRunningLocalTurn,runLocalAgentTurn,runningLocalTurns,+ recoverLoggedTurns,+ restingItems,saveLocalAgentTurn,+ steerLocalAgentTurn,+ useAgentCommands,+ useAgentContext,useLocalAgentTurn,type LocalAgentTurn,type LocalTranscriptStore,} from '@/lib/local-agent-run';-import type { LocalAgentTurnMeta, PromptImage } from '@/lib/desktop-bridge';+import type { LocalAgentId, LocalAgentTurnMeta, PromptImage } from '@/lib/desktop-bridge';import { referencePictures } from '@/lib/ref-pictures';-import { diffFilms, type TurnFilmChanges } from '@/lib/film-changes';+import type { TurnFileChanges } from '@/lib/file-changes';import { readBalance, type TurnBalance } from '@/lib/balance';import { BalanceNotice } from '@/components/BalanceNotice';import { readStudioFilm } from '@/lib/studio-film';@@ -64,6 +73,9 @@ const EMPTY_STORE: LocalTranscriptStore = { get: () => NO_ITEMS, subscribe: () =const isActive = (turn: Turn | undefined) => turn?.status === 'generating' || turn?.status === 'failing' || turn?.status === 'canceling';+/** how often a running turn is kept, at most (it changes with every word) */+const KEEP_RUNNING_MS = 1500;+/** On a video's thumbnail: it plays, it is not a picture. */function PlayMark() {return (@@ -196,6 +208,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec}}).finally(() => { r.ack(); bump(); });}+ /* then the turns only the logs have (the app closed on them before they were kept): made again, and shown */+ return recoverLoggedTurns(projectKey).then((made) => { if (made) bump(); });});// settleLocalTurn only reads stable setters// eslint-disable-next-line react-hooks/exhaustive-deps@@ -222,6 +236,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec/* ── the composer ── */const thread = useStickToBottom();+ /* scrolled away from the conversation's start: what passes under the session bar fades into it */+ const [scrolled, setScrolled] = React.useState(false);const tail = useTailSpacer(thread.viewport, thread.pinIfFollowing, active);const composerRef = React.useRef<PromptEditorHandle>(null);/* the composer and what stands on it (a question, a permission): its height, with the 6 px under the pane, is all@@ -248,6 +264,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec/** files of the project pointed at with @ (their pills turn back into their paths when sent) */const [fileRefs, setFileRefs] = React.useState<PromptReference[]>([]);const followUpFilled = followUp.trim().length > 0;+ /* the composer's button stops the turn while it runs, until something is written to send */+ const stopping = active && !followUpFilled;const composerPills = React.useMemo(() => [...[...studioRefs.entries()].map(([id, ref]) => refPill(id, ref)), ...fileRefs],[studioRefs, fileRefs],@@ -277,6 +295,28 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec});return pills;}, []);+ /* how full the agent's context is in this conversation */+ const agentContext = useAgentContext(projectKey, sessionId, agent);+ /* the agent's own commands, a `/` at the start of the message, as in its own chat: they go as typed */+ const agentCommands = useAgentCommands(agent);+ const commandMenu = React.useMemo(() => (agentCommands.length ? {+ label: t('composer.commands'),+ providers: [{+ id: 'commands',+ groupLabel: t('composer.commands'),+ items: agentCommands.map((c) => ({+ id: `command:${c.name}`,+ kind: 'file' as const,+ icon: SquareSlash,+ label: `/${c.name}`,+ /* what it does, cut to the row */+ ...(c.description ? { detail: c.description, describes: true } : {}),+ /* found by its name, as in the agent's own chat (its description would put a word in it first) */+ keywords: [c.name],+ select: () => ({ text: `/${c.name}` }),+ })),+ }],+ } : undefined), [agentCommands, t]);const mentionProviders = React.useMemo<MentionProvider[]>(() => {const picked = selection?.refs ?? [];const range = selection ? selectionRange(selection) : null;@@ -396,11 +436,37 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: ProjecReact.useEffect(() => { app.draftRefsInStudio(draft); }, [draftKey]); // eslint-disable-line react-hooks/exhaustive-depsReact.useEffect(() => () => { app.draftRefsInStudio([]); app.highlightInStudio(null); }, []);+ /** each open turn's way to settle (by turn id), and the agent's run each running turn belongs to */+ const settlers = React.useRef(new Map<string, (patch: Partial<Turn & TurnBalance>) => void>());+ const runs = React.useRef(new Map<string, Promise<unknown>>());+ /** the conversation shown now (a turn opened in another is kept, not shown) */+ const shownSession = React.useRef(sessionId);+ shownSession.current = sessionId;++ /* the agent working with nobody having written, in a conversation of this project: a background task of its own came+ back, and it takes it up, as in its own chat. A turn of its own, under a line saying so */+ const openTurnNow = React.useRef(openTurn);+ openTurnNow.current = openTurn;+ React.useEffect(() => onUnpromptedTurn(({ projectId, conversation, agent: by }) => {+ if (projectId !== projectKey) return null;+ const id = makeLocalAgentTurnId();+ const opened = openTurnNow.current(id, '', null, [], { conversation, by, origin: 'background' });+ return { turn: opened.turn, meta: opened.meta, done: () => settlers.current.get(id)?.({ status: 'ready' }) };+ }), [projectKey]);+/**- * Start one turn with the person's own agent. The turn shows at- * once; what the agent is sent (`prepared`: the text, and the references' pictures) may take a moment to make.+ * One turn of the conversation: shown at once, kept, and settled by `settlers` when the agent is done with it. The+ * project's files are read as it opens (`ready`), so what it changed in them is shown under its reply.*/- function startTurn(id: string, instruction: string, prepared: Promise<{ text: string; images: PromptImage[] }>, promptDisplay: Turn['promptDisplay'] | null, attachments: Turn['attachments'] = []): void {+ function openTurn(+ id: string, instruction: string, promptDisplay: Turn['promptDisplay'] | null, attachments: Turn['attachments'] = [],+ /* a turn the agent started by itself (a background task of its own came back): in its own conversation, maybe not+ the one shown, by the agent of that session */+ { conversation = sessionId, by = agent, origin }: { conversation?: string; by?: LocalAgentId; origin?: 'background' } = {},+ ): { turn: LocalAgentTurn; meta: LocalAgentTurnMeta; prefs: Record<string, unknown>; ready: Promise<boolean> } {+ const agent = by;+ const sessionId = conversation;+ const shown = conversation === shownSession.current;const turn = createLocalAgentTurn(id, agent, ordered.length);const agentStore = useLocalAgents.getState();const options = agentOptions(agentStore, agent);@@ -415,8 +481,9 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec...(promptDisplay ? { promptDisplay } : {}),...(attachments?.length ? { attachments } : {}),localAgent: { id: agent, model: modelLabel || null },- };- setTurns((list) => mergeAssetLists([started], list));+ ...(origin ? { origin } : {}),+ } as Turn;+ if (shown) setTurns((list) => mergeAssetLists([started], list));/* the conversation is named by the words: a reference reads as its name there, not as "[1: name]" */const title = instruction.replace(/\[\d+: ([^\]]*)\]/g, '$1').replace(/\s+/g, ' ').trim().slice(0, 80);touchSession(sessionId, (s) => ({ title: s.title || title, turns: s.turns + 1 }));@@ -425,22 +492,50 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: ProjecturnNo: ordered.length, startedAt: Date.now(), turn: started,};registerRunningLocalTurn({ id, projectId: projectKey, projectTitle: project.name, sessionId, agent, prompt: instruction, startedAt: meta.startedAt, turn: started });- /* the film as the turn found it; once the turn settles, what it changed is kept with it and told under its reply.- The turn settles first: reading the film again is not worth keeping the person waiting for */- const filmBefore = readStudioFilm(project.id);- const settle = (patch: Partial<Turn & TurnBalance>) => {+ /* the project's files as the turn found them (read before the agent is sent anything); once the turn settles,+ what it changed in them is kept with it and shown under its reply. The turn settles first: comparing the files+ is not worth keeping the person waiting for */+ const ready = app.chat.snapshot(project.path, id).then(() => true, () => false);+ /* kept as it goes, not only once it ends: the app closed (or crashed) on a turn, it is still there, read back as+ interrupted, what it did so far shown and the next message going on from there */+ let keeping: ReturnType<typeof setTimeout> | null = null;+ const keep = () => { keeping = null; if (settlers.current.has(id)) saveLocalAgentTurn(meta.projectId, { ...started, updatedAt: new Date().toISOString() }, restingItems(turn.items)); };+ const stopKeeping = turn.store.subscribe(() => { keeping ??= setTimeout(keep, KEEP_RUNNING_MS); });+ settlers.current.set(id, (patch) => {+ settlers.current.delete(id);+ if (keeping) clearTimeout(keeping);+ stopKeeping();const done = settleLocalTurn(meta, turn, patch);- void filmBefore.then(async (before) => {- const after = before ? await readStudioFilm(project.id) : null;- const filmChanges = before && after ? diffFilms(before, after) : [];- if (!filmChanges.length) return;- const kept: Turn & TurnFilmChanges = { ...done, filmChanges };+ void ready.then(async (taken) => {+ const found = taken ? await app.chat.changes(project.path, id).catch(() => null) : null;+ const fileChanges = found?.files ?? [];+ if (!fileChanges.length) return;+ const kept: Turn & TurnFileChanges = { ...done, fileChanges };saveLocalAgentTurn(meta.projectId, kept, turn.items);- setTurns((list) => list.map((item) => (item.id === id ? { ...item, filmChanges } : item)));+ setTurns((list) => list.map((item) => (item.id === id ? { ...item, fileChanges } : item)));});+ });+ keep();+ return { turn, meta, prefs, ready };+ }++ /**+ * Send a turn to the agent: what it is sent (`prepared`: the text, and the pictures) may take a moment to make. It+ * settles the turn the agent's run ends on: this one, or the last message sent into it while it ran (steerTurn).+ */+ function runTurn(opened: ReturnType<typeof openTurn>, prepared: Promise<{ text: string; images: PromptImage[] }>): void {+ const { turn, meta, prefs, ready } = opened;+ const id = meta.turnId;+ const finish = (lastTurnId: string | undefined, patch: Partial<Turn & TurnBalance>) => {+ settlers.current.get(lastTurnId ?? id)?.(patch);+ settlers.current.get(id)?.(patch);};- void prepared.then(({ text, images }) => runLocalAgentTurn({+ /* the agent's own session of this conversation, gone on with (after a restart too); a new one is kept for next time */+ const resume = sessions.find((s) => s.id === sessionId)?.agentSessions?.[agent] ?? null;+ const run = Promise.all([prepared, ready]).then(([{ text, images }]) => runLocalAgentTurn({projectId: projectKey,+ conversation: sessionId,+ resume,agent,cwd: project.path,text,@@ -448,23 +543,50 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecturn,options: prefs,meta,- onSessionInfo: (info) => useLocalAgents.getState().noteOptions(agent, info.configOptions),+ onSessionInfo: (info) => {+ useLocalAgents.getState().noteOptions(agent, info.configOptions);+ if (info.sessionId && info.sessionId !== resume) {+ touchSession(sessionId, (s) => ({ agentSessions: { ...s.agentSessions, [agent]: info.sessionId } }));+ }+ },})).then(- ({ stopReason }) => settle(stopReason === 'cancelled' ? { status: 'cancelled', cancelReason: 'user' } : { status: 'ready' }),+ ({ stopReason, lastTurnId }) => finish(lastTurnId, stopReason === 'cancelled' ? { status: 'cancelled', cancelReason: 'user' } : { status: 'ready' }),(error: unknown) => {/* the ACP adapter wraps the agent's own message as JSON-RPC "Internal error: …": the message is the reason */const reason = (error instanceof Error ? error.message : String(error)).replace(/^Internal error:\s*/i, '').trim() || String(error);/* the service the app's own agent runs on has no balance left: said as such, with its page, not as an error */const balance = readBalance((error as { balance?: unknown } | null)?.balance);- turn.patch(balance ? { balance } : { error: reason });- settle({ status: 'error', error: reason, ...(balance ? { balance } : {}) });+ const lastTurnId = (error as { lastTurnId?: string } | null)?.lastTurnId;+ (localAgentTurn(lastTurnId ?? id) ?? turn).patch(balance ? { balance } : { error: reason });+ finish(lastTurnId, { status: 'error', error: reason, ...(balance ? { balance } : {}) });},- );+ ).finally(() => { runs.current.delete(id); });+ runs.current.set(id, run);+ }++ /**+ * A message sent while a turn runs, as in the agent's own chat: into that turn, the agent reading it at its next step+ * (an agent that takes steering). It shows as a turn of its own, what the agent says from then on under it, and the+ * running one is done. One that did not join (the turn ended meanwhile) is sent once that run ends.+ */+ function steerTurn(fromId: string, opened: ReturnType<typeof openTurn>, prepared: Promise<{ text: string; images: PromptImage[] }>): void {+ /* the agent's run going now (one at a time in a conversation): a message that did not join waits for it */+ const run = [...runs.current.values()].at(-1) ?? Promise.resolve();+ void Promise.all([prepared, opened.ready]).then(async ([{ text, images }]) => {+ if (await steerLocalAgentTurn(fromId, opened.turn, text, images)) {+ settlers.current.get(fromId)?.({ status: 'ready' });+ return;+ }+ await run.catch(() => {});+ runTurn(opened, Promise.resolve({ text, images }));+ });}function submitFollowUp(): void {if (!followUpFilled) return;- if (active) { setQueued(true); return; }+ /* while a turn runs: into it, for an agent that takes that; else it waits for the turn to end */+ const steer = active && asset ? canSteer(asset.id) : false;+ if (active && !steer) { setQueued(true); return; }setQueued(false);/* the sentence as the agent reads it: a pill becomes "[n: name]", and what each number is follows, in a block */const used: StudioRef[] = [];@@ -492,11 +614,13 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecconst stage = selection?.stage ?? null;/* each reference's picture is kept in the project for the agent (the block names it), and sent to one that takes pictures */const prepared = referencePictures(refs, { project: project.path, turnId: id })- .then(({ pictures, images }) => ({ text: said + studioReferencesText(refs, { stage, pictures }), images }));- startTurn(id, instruction, prepared, promptDisplay ?? null, turnAttachments(files));+ .then(({ pictures, images }) => ({ text: said + studioReferencesText(refs, { stage, pictures }), images: [...attachedPictures(files), ...images] }));+ const opened = openTurn(id, instruction, promptDisplay ?? null, turnAttachments(files));+ if (steer && asset) steerTurn(asset.id, opened, prepared);+ else runTurn(opened, prepared);}- /* queued while the turn ran: sent as soon as it ends */+ /* queued while the turn ran (an agent that cannot take a message mid-turn): sent as soon as it ends */React.useEffect(() => { if (queued && !active) submitFollowUp(); }, [queued, active]); // eslint-disable-line react-hooks/exhaustive-depsconst onNewSession = () => {@@ -610,17 +734,19 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: ProjeccontentClassName="text-[14px] leading-[22px] text-[var(--chat-text)]"onPasteFiles={(files) => composerFiles.add(files)}mentions={{ providers: mentionProviders, label: t('mention.menu'), onOpen: loadMentionFiles }}+ commands={commandMenu}/></div>- <Tooltip label={active ? t('project.stop') : t('project.sendFollowUp')} shortcut={active ? 'Esc' : 'Enter'}>+ {/* while it works: Stop, or Send once something is written (it goes into the turn, or after it); Esc stops */}+ <Tooltip label={stopping ? t('project.stop') : t('project.sendFollowUp')} shortcut={stopping ? 'Esc' : 'Enter'}><buttontype="button"- onClick={active ? () => { if (asset) void cancelLocalAgentTurn(asset.id); } : submitFollowUp}- disabled={active ? false : !followUpFilled}+ onClick={stopping ? () => { if (asset) void cancelLocalAgentTurn(asset.id); } : submitFollowUp}+ disabled={stopping ? false : !followUpFilled}className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-[6px] text-[var(--text-dim)] transition-colors duration-150 hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:cursor-not-allowed disabled:text-[var(--text-faint)] disabled:hover:bg-transparent"- aria-label={active ? t('project.stop') : t('project.sendFollowUp')}+ aria-label={stopping ? t('project.stop') : t('project.sendFollowUp')}>- {active ? <Square size={14} /> : <CornerDownLeft size={14} />}+ {stopping ? <Square size={14} /> : <CornerDownLeft size={14} />}</button></Tooltip></div>@@ -628,6 +754,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec<div className="flex items-center gap-0.5 px-0.5"><ModelPopover placement="top" align="start" /><div className="min-w-0 flex-1" />+ <ContextMeter context={agentContext} /><inputref={attachInputRef}type="file"@@ -677,9 +804,11 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecbusy={active}/><div className="relative flex min-h-0 min-w-0 flex-1 flex-col">+ {/* the first message well below the session bar, as a chat app opens a conversation */}<divref={thread.viewportRef}- className={`flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto overflow-x-hidden [overflow-anchor:none] [scrollbar-gutter:stable] px-4 pt-3.5${blank ? ' justify-center pb-3.5' : ' pb-10'}`}+ onScroll={(event) => setScrolled(event.currentTarget.scrollTop > 2)}+ className={`flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto overflow-x-hidden [overflow-anchor:none] [scrollbar-gutter:stable] px-4${blank ? ' justify-center py-3.5' : ' pt-8 pb-10'}`}>{blank ? (<div ref={thread.contentRef}>@@ -703,6 +832,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec</div>)}</div>+ <div aria-hidden className={`pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b from-[var(--dock-pane)] to-transparent transition-opacity duration-150 ${scrolled && !blank ? 'opacity-100' : 'opacity-0'}`} /><div aria-hidden className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-[var(--dock-pane)] to-transparent" />{!blank && !thread.atBottom && (<buttondiff --git a/apps/desktop/chat/src/app-bridge.ts b/apps/desktop/chat/src/app-bridge.tsindex f39916b..d1fa5f7 100644--- a/apps/desktop/chat/src/app-bridge.ts+++ b/apps/desktop/chat/src/app-bridge.ts@@ -3,6 +3,7 @@* uses (localAgents, pathForFile) are typed in lib/desktop-bridge.ts.*/import type { StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';+import type { FileChange } from './lib/file-changes';/* what Studio and the chat say to each other about the film is Studio's own contract (its lib/host.ts) */export type { StageBox, StudioCommand, StudioRef, StudioRefImage, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';@@ -55,18 +56,26 @@ interface AppBridge {load(project: string): Promise<{ sessions: unknown[]; last: string | null; turns: unknown[] }>;saveSessions(project: string, sessions: unknown[], last: string | null): Promise<unknown>;saveTurn(project: string, turn: unknown, items: unknown[]): Promise<unknown>;- log(project: string, turnId: string): Promise<TurnLog | null>;+ /** `unless`: the sizes of the log already read; when it has not grown, `{ same: true }` */+ log(project: string, turnId: string, unless?: { size: number; callsSize: number }): Promise<TurnLog | { same: true } | null>;reveal(project: string, turnId?: string): Promise<unknown>;/** a picture a message's reference points at, kept for its agent: .film/refs/<turn>-<n>.jpg (its path in the project) */saveRefImage(project: string, turnId: string, n: number, bytes: ArrayBuffer): Promise<{ path: string }>;+ /** the turns with a log and no saved record (src/chat-store.mjs unsavedTurns), but those of `except` */+ unsaved?(project: string, except?: string[]): Promise<Array<{ turnId: string; events: TurnLog['events'] }>>;+ /** the project's files as a turn starts, kept by the app; then what the turn changed in them (src/file-changes.mjs) */+ snapshot(project: string, turnId: string): Promise<unknown>;+ changes(project: string, turnId: string): Promise<{ files: FileChange[]; cut: boolean } | null>;};/** what an agent's command asks before it spends (a video clip), and what it tells the person (a provider with nobalance left), worded by Studio: shown above the composer until answered; the command waits for a question */asks: { get(): SpendAsk[]; onChange(listener: (asks: SpendAsk[]) => void): () => void; answer(id: string, allow: boolean): void };- /** Settings → Developer: on, each turn shows its full log */- developer: { get(): Promise<boolean>; onChange(listener: (on: boolean) => void): () => void };+ /** Settings → Developer: `logs`, each turn shows its full log; `changes`, what it changed in the files, under its reply */+ developer: { get(): Promise<DeveloperPrefs>; onChange(listener: (prefs: DeveloperPrefs) => void): () => void };}+export interface DeveloperPrefs { logs: boolean; changes: boolean }+/** A question about spending, as Studio words it. */export interface SpendAsk { id: string; title: string; body: string | null; allowLabel: string; denyLabel: string }@@ -76,6 +85,7 @@ export interface TurnLog {/** too long to read whole: these are its last events */cut: boolean;size: number;+ callsSize?: number;events: Array<{ t: number; kind: string; [field: string]: unknown }>;/** the requests the model got and its answers, each only what is new since the one before (lib/model-calls.ts) */calls?: unknown[];diff --git a/apps/desktop/chat/src/components/ContextMeter.tsx b/apps/desktop/chat/src/components/ContextMeter.tsxnew file mode 100644index 0000000..fec7ec8--- /dev/null+++ b/apps/desktop/chat/src/components/ContextMeter.tsx@@ -0,0 +1,34 @@+/**+ * How full the agent's context is in this conversation, as its own chat shows it: a small ring beside the composer's+ * tools, its share of the context window filled, the numbers on hover. Shown once the agent has said (after its first+ * turn in the conversation); the agent compacts it itself as it fills, or the person runs its own /compact.+ */+import { useT } from '@/i18n';+import type { AgentContext } from '@/lib/local-agent-run';+import { Tooltip } from './Tooltip';++const R = 6;+const AROUND = 2 * Math.PI * R;++const tokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));++export function ContextMeter({ context }: { context: AgentContext | null }) {+ const t = useT();+ if (!context) return null;+ const share = Math.min(1, Math.max(0, context.used / context.size));+ const percent = Math.round(share * 100);+ const label = t('composer.context').replace('{percent}', String(percent)).replace('{used}', tokens(context.used)).replace('{size}', tokens(context.size));+ /* nearly full: in the warning color, as the agent will soon compact it */+ const tone = share >= 0.85 ? 'var(--warn)' : 'var(--text-muted)';+ return (+ <Tooltip label={label}>+ <span role="img" aria-label={label} className="flex h-8 w-8 items-center justify-center">+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden>+ <circle cx="8" cy="8" r={R} fill="none" stroke="var(--border-strong)" strokeWidth="2" />+ <circle cx="8" cy="8" r={R} fill="none" stroke={tone} strokeWidth="2" strokeLinecap="round"+ strokeDasharray={`${share * AROUND} ${AROUND}`} transform="rotate(-90 8 8)" />+ </svg>+ </span>+ </Tooltip>+ );+}diff --git a/apps/desktop/chat/src/components/FileChangesList.tsx b/apps/desktop/chat/src/components/FileChangesList.tsxnew file mode 100644index 0000000..fe11a6a--- /dev/null+++ b/apps/desktop/chat/src/components/FileChangesList.tsx@@ -0,0 +1,119 @@+/**+ * Under the agent's reply: what the turn changed in the project's files (lib/file-changes), as a coding agent's app+ * lists them. One card, a row per file: its name, its lines added and removed, and on a click its changed lines. The+ * first few rows show; the rest open from the last row. Settings → Developer turns it off.+ */+import React from 'react';+import { ChevronRight, File, FileAudio, FileCode, FileImage, FileJson, FileText, FileVideo } from 'lucide-react';+import { useT } from '@/i18n';+import type { FileChange, FileHunk } from '@/lib/file-changes';+import { StickToBottomContext } from './useStickToBottom';++/** rows shown before "N more files" */+const ROWS_SHOWN = 4;++const ICONS: Array<[RegExp, typeof File]> = [+ [/\.(html?|css|[cm]?js|jsx|tsx?|py|sh)$/i, FileCode],+ [/\.json$/i, FileJson],+ [/\.(md|txt|srt|vtt|csv|ya?ml|toml|xml)$/i, FileText],+ [/\.(png|jpe?g|gif|webp|avif|svg)$/i, FileImage],+ [/\.(mp3|m4a|wav|aac|ogg|flac|opus)$/i, FileAudio],+ [/\.(mp4|mov|webm|mkv|m4v)$/i, FileVideo],+];+const iconOf = (path: string) => ICONS.find(([test]) => test.test(path))?.[1] ?? File;++export function FileChangesList({ changes }: { changes: FileChange[] }) {+ const t = useT();+ const thread = React.useContext(StickToBottomContext);+ const [all, setAll] = React.useState(false);+ const shown = all ? changes : changes.slice(0, ROWS_SHOWN);+ const hidden = changes.length - shown.length;+ /* opening a row or the rest makes the reply taller: the thread stays where it is, as it does for the work summary */+ const keepPlace = () => thread?.skipNextPin();++ return (+ <div className="min-w-0 overflow-hidden rounded-[10px] border border-[var(--border)]">+ {shown.map((change, i) => (+ <FileRow key={change.path} change={change} first={i === 0} onToggle={keepPlace} />+ ))}+ {hidden > 0 || changes.length > ROWS_SHOWN ? (+ <button+ type="button"+ onClick={() => { keepPlace(); setAll((value) => !value); }}+ className="flex h-9 w-full items-center border-t border-[var(--border)] px-3 text-left text-[12.5px] text-[var(--chat-hint)] transition-colors hover:bg-[var(--bg-hover)] hover:text-[var(--chat-text)]"+ >+ {hidden > 0 ? t('fileChanges.more').replace('{n}', String(hidden)) : t('fileChanges.fewer')}+ </button>+ ) : null}+ </div>+ );+}++function FileRow({ change, first, onToggle }: { change: FileChange; first: boolean; onToggle: () => void }) {+ const t = useT();+ const [open, setOpen] = React.useState(false);+ const Icon = iconOf(change.path);+ const slash = change.path.lastIndexOf('/');+ const name = change.path.slice(slash + 1);+ const folder = slash > 0 ? change.path.slice(0, slash) : '';+ const lines = change.added != null || change.removed != null;+ const canOpen = Boolean(change.hunks?.length);+ const row = (+ <>+ <Icon size={14} aria-hidden className="shrink-0 text-[var(--chat-hint)]" />+ <span className={`min-w-0 truncate text-[13px] text-[var(--chat-text)] ${change.change === 'removed' ? 'line-through opacity-70' : ''}`} title={change.path}>+ {name}+ {folder ? <span className="ml-1.5 text-[12px] text-[var(--chat-hint)]">{folder}</span> : null}+ </span>+ <span className="ml-auto flex shrink-0 items-center gap-1.5 pl-3 font-mono text-[12px] tabular-nums">+ {lines ? (+ <>+ {change.added ? <span className="text-[var(--ok)]">+{change.added}</span> : null}+ {change.removed ? <span className="text-[var(--err)]">−{change.removed}</span> : null}+ </>+ ) : (+ <span className="font-sans text-[var(--chat-hint)]">{t(`fileChanges.${change.change}`)}</span>+ )}+ </span>+ <ChevronRight size={13} aria-hidden className={`shrink-0 text-[var(--chat-hint)] transition-transform ${open ? 'rotate-90' : ''} ${canOpen ? '' : 'invisible'}`} />+ </>+ );+ const shell = `flex h-9 w-full min-w-0 items-center gap-2 px-3 text-left ${first ? '' : 'border-t border-[var(--border)]'}`;+ return (+ <div className="min-w-0">+ {canOpen ? (+ <button type="button" aria-expanded={open} onClick={() => { onToggle(); setOpen((value) => !value); }}+ className={`${shell} transition-colors hover:bg-[var(--bg-hover)]`}>+ {row}+ </button>+ ) : <div className={shell}>{row}</div>}+ {open && change.hunks ? <Hunks hunks={change.hunks} cut={change.cut === true} /> : null}+ </div>+ );+}++/* the changed lines as git shows them: each hunk's place, then its lines, removed (−) and added (+) */+function Hunks({ hunks, cut }: { hunks: FileHunk[]; cut: boolean }) {+ const t = useT();+ return (+ <div className="max-h-[360px] min-w-0 overflow-auto border-t border-[var(--border)] font-mono text-[11.5px] leading-[18px]">+ {hunks.map((hunk, i) => (+ <React.Fragment key={i}>+ <div className="w-max min-w-full whitespace-pre px-3 text-[var(--chat-hint)] opacity-80">+ @@ −{hunk.oldStart},{hunk.oldLines} +{hunk.newStart},{hunk.newLines} @@+ </div>+ {hunk.lines.map((line, j) => {+ const sign = line[0];+ return (+ <div key={j} className={`flex w-max min-w-full whitespace-pre pr-3 ${sign === '-' ? 'bg-[rgba(229,83,75,0.13)] text-[#e5534b]' : sign === '+' ? 'bg-[rgba(63,185,80,0.13)] text-[#3fb950]' : 'text-[var(--chat-hint)]'}`}>+ <span aria-hidden className="w-6 shrink-0 select-none text-center opacity-80">{sign === '-' ? '−' : sign === '+' ? '+' : ''}</span>+ <span>{line.slice(1)}</span>+ </div>+ );+ })}+ </React.Fragment>+ ))}+ {cut ? <div className="px-3 py-1 font-sans text-[12px] text-[var(--chat-hint)]">{t('fileChanges.cut')}</div> : null}+ </div>+ );+}diff --git a/apps/desktop/chat/src/components/FilmChangesList.tsx b/apps/desktop/chat/src/components/FilmChangesList.tsxdeleted file mode 100644index a382c15..0000000--- a/apps/desktop/chat/src/components/FilmChangesList.tsx+++ /dev/null@@ -1,109 +0,0 @@-/**- * Under the agent's reply, in developer mode (Settings → Developer): what the turn changed in the film- * (lib/film-changes), one line that opens to each clip as a diff of film.html — its pill (a click shows it in Studio)- * and what happened in a few words, then its line as it was (−) and as it is (+). A clip that is gone has nothing to- * show: its pill is struck through and does not click. Turns saved before the lines were kept show the words only.- */-import React from 'react';-import { ChevronRight } from 'lucide-react';-import { useT } from '@/i18n';-import { clipPillKind, type ClipAspect, type ClipChange } from '@/lib/film-changes';-import { PromptPill, PromptPillRevealContext } from './prompt-editor';-import { StickToBottomContext } from './useStickToBottom';--/* a place to the tenth of a second, as the timeline shows it; a speed to the hundredth; a track as it is */-const NUMBER: Partial<Record<ClipAspect, (n: number) => string>> = {- at: (n) => n.toFixed(1),- speed: (n) => String(Math.round(n * 100) / 100),- track: (n) => String(n),-};--/** What happened to a clip, in the chat's language: "moved 13.6 → 13.0 s · trimmed". */-function summary(change: ClipChange, t: (path: string) => string): string {- if (change.change !== 'changed') return t(`filmChanges.${change.change}`);- const phrase = (aspect: ClipAspect) => {- const pair = aspect === 'at' ? change.at : aspect === 'speed' ? change.speed : aspect === 'track' ? change.track : undefined;- const said = t(`filmChanges.aspect.${aspect}`);- const show = NUMBER[aspect];- return pair && show ? said.replace('{from}', show(pair[0])).replace('{to}', show(pair[1])) : said;- };- return (change.aspects?.length ? change.aspects : ['other' as const]).map(phrase).join(' · ');-}--/* a clip's line before and after, as git shows a change: one that only moved track is the same line, shown once */-function DiffLines({ before, after }: { before?: string; after?: string }) {- if (before == null && after == null) return null;- const lines: Array<['-' | '+' | ' ', string]> = before != null && before === after- ? [[' ', before]]- : [...(before != null ? [['-', before] as ['-', string]] : []), ...(after != null ? [['+', after] as ['+', string]] : [])];- return (- <div className="min-w-0 overflow-x-auto rounded-[6px] border border-[var(--border)] font-mono text-[11.5px] leading-[18px]">- {lines.map(([sign, text], i) => (- <div- key={i}- className={`flex w-max min-w-full whitespace-pre pr-2 ${sign === '-' ? 'bg-[rgba(229,83,75,0.13)] text-[#e5534b]' : sign === '+' ? 'bg-[rgba(63,185,80,0.13)] text-[#3fb950]' : 'text-[var(--chat-hint)]'}`}- >- <span aria-hidden className="w-5 shrink-0 select-none text-center opacity-80">{sign === ' ' ? '' : sign === '-' ? '−' : '+'}</span>- <span>{text}</span>- </div>- ))}- </div>- );-}--export function FilmChangesList({ changes }: { changes: ClipChange[] }) {- const t = useT();- const ctx = React.useContext(PromptPillRevealContext);- const thread = React.useContext(StickToBottomContext);- const [open, setOpen] = React.useState(false);- const label = changes.length === 1 ? t('filmChanges.one') : t('filmChanges.many').replace('{n}', String(changes.length));- const toggle = () => {- /* opening it makes the reply taller: the thread stays where it is, as it does for the work summary */- thread?.skipNextPin();- setOpen((value) => !value);- };-- return (- <div className="min-w-0">- <button- type="button"- aria-expanded={open}- onClick={toggle}- className="flex items-center gap-1 text-[13px] text-[var(--chat-hint)] transition-colors hover:text-[var(--chat-text)]"- >- <span>{label}</span>- <ChevronRight size={13} aria-hidden className={`transition-transform ${open ? 'rotate-90' : ''}`} />- </button>- {open ? (- <ul className="mt-1 flex flex-col gap-2 border-l border-[var(--border)] pl-3 text-[13px]">- {changes.map((change, index) => {- const gone = change.change === 'removed';- const reference = {- id: `film-change:${change.id}`,- kind: clipPillKind(change.src),- label: change.id,- target: { kind: 'clip', id: change.id, loc: null, label: change.id, clipKind: 'mg', src: change.src, start: 0, end: 0 },- };- const reveal = !gone ? ctx?.onReveal : undefined;- return (- <li key={`${change.id}:${index}`} className="flex min-w-0 flex-col gap-1">- <div className="flex min-w-0 items-center gap-2">- <span className={`min-w-0 shrink ${gone ? 'opacity-60 [&_.truncate]:line-through' : ''}`}>- <PromptPill- reference={reference}- card={ctx?.describe?.(reference) ?? null}- {...(reveal && ctx?.revealLabel ? { hint: ctx.revealLabel } : {})}- {...(reveal ? { onClick: (event: React.MouseEvent) => { event.preventDefault(); reveal(reference); } } : {})}- />- </span>- <span className="min-w-0 truncate text-[var(--chat-hint)]">{summary(change, t)}</span>- </div>- <DiffLines before={change.before} after={change.after} />- </li>- );- })}- </ul>- ) : null}- </div>- );-}diff --git a/apps/desktop/chat/src/components/ModelPopover.tsx b/apps/desktop/chat/src/components/ModelPopover.tsxindex 9ef9fde..f6801fe 100644--- a/apps/desktop/chat/src/components/ModelPopover.tsx+++ b/apps/desktop/chat/src/components/ModelPopover.tsx@@ -56,7 +56,6 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placemconst [open, setOpen] = React.useState(false);/** the option whose side menu is open */const [side, setSide] = React.useState<string | null>(null);- const [note, setNote] = React.useState<string | null>(null);/** how far the card has slid left to make room for a side menu: it only grows while the menu is open */const [cardShift, setCardShift] = React.useState(0);const [sideStyle, setSideStyle] = React.useState<React.CSSProperties | null>(null);@@ -67,7 +66,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placemconst stopTimer = () => { if (closeTimer.current) { window.clearTimeout(closeTimer.current); closeTimer.current = null; } };const showSide = (id: string) => { stopTimer(); setSide(id); };const hideSideSoon = () => { stopTimer(); closeTimer.current = window.setTimeout(() => setSide(null), SIDE_CLOSE_MS); };- React.useEffect(() => { if (!open) { stopTimer(); setSide(null); setNote(null); setCardShift(0); } }, [open]);+ React.useEffect(() => { if (!open) { stopTimer(); setSide(null); setCardShift(0); } }, [open]);React.useEffect(() => stopTimer, []);/* the window's width while open: the card and the side menu share it */const [windowW, setWindowW] = React.useState(() => window.innerWidth);@@ -90,7 +89,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placemReact.useEffect(() => {if (!open) return;void refresh().then(() => {- for (const a of shownAgents(useLocalAgents.getState().roster)) if (a.status === 'ready') void ensureOptions(a.id);+ for (const a of shownAgents(useLocalAgents.getState().roster)) if (a.status === 'ready') void ensureOptions(a.id, { retry: true });});}, [open, refresh, ensureOptions]);@@ -109,20 +108,14 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placemif (a.status === 'ready') return null;if (a.status === 'checking') return t('composer.agentLoading');if (a.status === 'missing') return t('composer.agentNotFound');- if (a.status === 'sign-in' || a.status === 'off') return t('composer.agentConnect');if (a.status === 'waiting') return t('composer.agentWaiting');return t('composer.agentSetUp');};const chooseAgent = (a: RosterAgent) => {- setNote(null);setSide(null);if (a.status === 'ready') { la.pick(a.id); return; }- if (a.status === 'sign-in' || a.status === 'off') {- la.pick(a.id);- void desktopBridge()?.agents?.connect(a.id).then((r) => { if (!r.ok) setNote(r.error ?? t('composer.agentConnectFailed')); });- return;- }if (a.status === 'checking' || a.status === 'waiting') return;+ /* not connected, signed out, not found, no key: set up in Settings → Agents, where connecting and signing in are */setOpen(false);desktopBridge()?.openSettings?.('agents');};@@ -223,7 +216,6 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem</button>);})}- {note ? <p className="px-2.5 pb-1 pt-0.5 text-[11.5px] leading-relaxed text-[var(--text-muted)]">{note}</p> : null}<div className="mx-1 my-1 h-px bg-[var(--border)]" /></>) : null}@@ -235,7 +227,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem) : rows.length === 0 && options && !la.optionsError[agent] ? null : rows.length === 0 ? (<p className="px-2.5 py-1.5 text-[12px] leading-relaxed text-[var(--text-muted)]">{la.optionsError[agent]- ? <>{t('composer.agentOptionsFailed')} <button type="button" onMouseDown={keepFocus} onClick={() => void la.ensureOptions(agent)} className="text-[var(--text)] underline underline-offset-2">{t('project.retry')}</button></>+ ? <>{t('composer.agentOptionsFailed')} <button type="button" onMouseDown={keepFocus} onClick={() => void la.ensureOptions(agent, { retry: true })} className="text-[var(--text)] underline underline-offset-2">{t('project.retry')}</button></>: t('composer.agentLoading')}</p>) : rows.map((o, i) => (diff --git a/apps/desktop/chat/src/components/ProjectConversation.tsx b/apps/desktop/chat/src/components/ProjectConversation.tsxindex a132476..481b5fe 100644--- a/apps/desktop/chat/src/components/ProjectConversation.tsx+++ b/apps/desktop/chat/src/components/ProjectConversation.tsx@@ -2,13 +2,12 @@import React from 'react';import type { PublicProgressSnapshot, TurnAttachment } from '@openfilm/shared';-import { Check, ChevronRight, Copy, Play } from 'lucide-react';+import { BellRing, Check, ChevronRight, Copy, Play } from 'lucide-react';import { AgentActivityList, formatWorkDuration, StatusLine, type AgentActivityItem } from './AgentActivityRow';import { AgentIcon, hasAgentIcon } from './AgentIcons';import { BrandLogo } from './BrandLogo';import { StickToBottomContext } from './useStickToBottom';import { answerStart, countedSteps } from '@/lib/agent-activity-runs';-import { useTurnChanges, type SceneChange, type TurnChanges } from '@/lib/turn-changes';import {preferTranscript,toTraceLogItems,@@ -26,8 +25,8 @@ import { useT, useUiLocale } from '@/i18n';import { relativeTime, useMinuteTick } from '@/lib/relative-time';import { isPendingAssetId } from '@/lib/asset-lists';import { TurnLogButton } from './TurnLog';-import { FilmChangesList } from './FilmChangesList';-import { ChatProjectContext, useDeveloperMode } from '@/lib/developer';+import { FileChangesList } from './FileChangesList';+import { ChatProjectContext, useDeveloperMode, useShowChanges } from '@/lib/developer';import { isVideoAttachment } from '@/lib/composer-attachments';/** What past turns get as "no live process". One constant: a new array each time would defeat the memo. */@@ -234,7 +233,7 @@ const ConversationTurn = React.memo(function ConversationTurn({rootRef?: (node: HTMLDivElement | null) => void;}) {const t = useT();- const developer = useDeveloperMode();+ const showChanges = useShowChanges();/* A past turn's stored record is fetched when the turn scrolls near the viewport, not up front, so it isthere by the time it is read. */const store = React.useContext(LiveTranscriptContext);@@ -267,6 +266,7 @@ const ConversationTurn = React.memo(function ConversationTurn({const storedItems = stored.items;/* Finished (not live, not still running): the changes card and footer go below */const settled = !live && entry.status !== 'active';+ const running = entry.status === 'active';/* A finished turn folds, as in Codex / Claude Code: the process becomes one line ("Worked 3m 40s · 14 steps")and the answer stands out. For the turn you watched, folding must not move the answer you are reading: drawone frame unfolded, note the answer's bottom edge in the viewport, then fold and restore the scroll, so the@@ -294,7 +294,6 @@ const ConversationTurn = React.memo(function ConversationTurn({const delta = tail.getBoundingClientRect().top - top;if (delta !== 0) scroller.scrollTop += delta;}, [folded, thread]);- const changes = useTurnChanges(entry.assetId);const items = React.useMemo(() => (live ? liveTranscript : preferTranscript(lastLive.current ?? [], storedItems ?? [])),// lastLive only changes while live, and live is in the deps.@@ -303,24 +302,6 @@ const ConversationTurn = React.memo(function ConversationTurn({/* Converts two hundred-odd objects once. Without the memo it reruns on every render with new identities, whichdefeats the memo of the whole list below (see toTraceLogItems). */const rows = React.useMemo(() => (items.length ? toTraceLogItems(items) : null), [items]);- /* "The picture changed" comes from the film's code fingerprint, but an agent starting up can touch code in the- workspace the user never sees (a turn that only answered a question showed as a picture change). So say it- only when this turn edited the picture (wrote scenes, edited files); if nothing else changed, no card. */- const shownChanges = React.useMemo(() => {- if (!changes) return null;- if (!changes.picture) return changes;- const edited = (items ?? []).some((item) => item.kind === 'act' && item.act != null && (- PICTURE_ACTS.has(item.act)- /* a local agent's file edits count only for picture code (mg/*.tsx and the like); film.json only moves things */- || (item.act === 'files.edit' && /\.(tsx?|jsx?|css)\b/.test(item.detail ?? ''))- ));- if (edited) return changes;- const rest = { ...changes, picture: false };- const any = rest.scenes.length > 0 || rest.captions- || rest.sounds.added + rest.sounds.removed + rest.sounds.edited > 0- || Math.abs(rest.durationMs.before - rest.durationMs.after) > 1;- return any ? rest : null;- }, [changes, items]);/* Two users need this node: one measures its distance from the viewport (whether to fetch the process), theother the last turn's height (the space below). One callback rather than a wrapper div, which would changethe flex gaps. */@@ -360,6 +341,13 @@ const ConversationTurn = React.memo(function ConversationTurn({The border is a hairline: the background is already half a step off the panel, and the border onlysharpens that edge so two close tones don't blur. Any heavier and it becomes a card, for what isonly a sentence. */}+ {/* A turn the agent started by itself (a background task of its own came back): no message, a line saying so */}+ {entry.origin === 'background' ? (+ <div className="flex items-center gap-2 text-[12px] text-[var(--chat-hint)]">+ <BellRing size={12} aria-hidden className="shrink-0" />+ <span>{t('turnFrame.background')}</span>+ </div>+ ) : (<div className="group/ask flex min-w-0 flex-col gap-1"><div className="flex justify-end"><div className="flex max-w-[88%] flex-col gap-1.5 rounded-[12px] border border-[var(--border)] bg-[var(--surface-2)] px-3 py-2">@@ -379,6 +367,7 @@ const ConversationTurn = React.memo(function ConversationTurn({</div><PromptFooter entry={entry} /></div>+ )}{/* The agent's side is a block of its own: hovering it (not the whole turn) shows the line below */}<div className="group/reply flex min-w-0 flex-col gap-2 empty:hidden">@@ -408,17 +397,16 @@ const ConversationTurn = React.memo(function ConversationTurn({</div>)}- {/* What this turn changed in the film. No "version N · switch to it" link: every small edit is a version,- and going back to one belongs to the top bar's history. */}- {settled && shownChanges ? <TurnChangesCard changes={shownChanges} /> : null}- {/* what it changed in film.html, line by line: for finding out what an agent did, so developer mode's */}- {settled && developer && entry.filmChanges?.length ? <FilmChangesList changes={entry.filmChanges} /> : null}-- {settled ? <TurnFooter entry={entry} items={items} /> : null}+ {/* What this turn changed in the project's files, as a coding agent's app lists them (Settings → Developer+ turns it off). No "version N · switch to it" link: going back belongs to the top bar's history. */}+ {settled && showChanges && entry.fileChanges?.length ? <FileChangesList changes={entry.fileChanges} /> : null}- {/* Still running: one status line below, always one line high, only its text changes (see StatusLine). An- interruption doesn't show Failed here: the reason and Resume appear above the composer, as in Cursor. */}- {entry.status === 'active' ? <StatusLine items={rows ?? NO_ROWS} fallback={liveActivity} /> : null}+ {/* Still running: one status line, always one line high, only its text changes (see StatusLine), and the+ footer under it on hover (its Log is the turn so far). Done, the footer alone. Always there, in one place+ in the tree: a log opened from it stays open as the turn finishes. An interruption doesn't+ show Failed here: the reason and Resume appear above the composer, as in Cursor. */}+ {running ? <StatusLine items={rows ?? NO_ROWS} fallback={liveActivity} /> : null}+ <TurnFooter entry={entry} items={items} running={running} /></div></div>);@@ -630,168 +618,6 @@ function WorkSummary({ items, durationMs }: { items: AgentActivityItem[]; durati);}-/**- * Clicking a scene on the changes card moves the playhead there and selects it on the timeline. Without a- * provider the card is just a card.- * `has` says whether the scene is still in the film: removed ones, or ones changed away since, can't be clicked.- */-export const TurnSceneFocusContext = React.createContext<{- focus: (id: string) => void;- has: (id: string) => boolean;-} | null>(null);--/** A scene's current thumbnail on the changes card (the timeline's images); null without a provider or a frame. */-export const TurnSceneThumbContext = React.createContext<((id: string) => string | null) | null>(null);--const CHANGE_CHIPS_MAX = 6;-const CHANGE_TILES_MAX = 4;--/** Actions that write picture code (see shownChanges). Moving things or adding sound isn't "the picture changed"; those have their own lines. */-const PICTURE_ACTS = new Set<string>(['scene.write', 'scene.edit']);--/**- * What this turn changed in the film (see lib/turn-changes): like Codex's "3 files changed" card, but in scenes,- * since our users look at scenes, not files.- *- * Reading the conversation should land somewhere: you said something, watched it work, and got these changes.- * Every scene can be clicked.- */-function TurnChangesCard({ changes }: { changes: TurnChanges }) {- const t = useT();- const focus = React.useContext(TurnSceneFocusContext);- const thumbOf = React.useContext(TurnSceneThumbContext);- /* The reply should show the film: changed and added scenes with a thumbnail make a row of small pictures (click- to jump); the rest are text pills, as are removed scenes, which have no picture. */- const tiles = thumbOf- ? changes.scenes.filter((scene) => scene.change !== 'removed').map((scene) => ({ scene, url: thumbOf(scene.id) })).filter((x): x is { scene: SceneChange; url: string } => !!x.url).slice(0, CHANGE_TILES_MAX)- : [];- const tiled = new Set(tiles.map((x) => x.scene));- const rest = changes.scenes.filter((scene) => !tiled.has(scene));- /* one chip per name: eight cuts of one source video read "+ talk.mp4 ×8", not the same chip eight times */- const groups: Array<{ scene: SceneChange; count: number }> = [];- for (const scene of rest) {- const same = groups.find((g) => g.scene.label === scene.label && g.scene.change === scene.change);- if (same) same.count += 1; else groups.push({ scene, count: 1 });- }- const chips = groups.slice(0, CHANGE_CHIPS_MAX);- const more = groups.length - chips.length;- const soundTotal = changes.sounds.added + changes.sounds.edited;- const extras = [- soundTotal === 1 ? t('turnFrame.oneSound') : soundTotal > 1 ? t('turnFrame.sounds').replace('{n}', String(soundTotal)) : null,- changes.captions ? t('turnFrame.captions') : null,- changes.picture ? t('turnFrame.picture') : null,- ].filter(Boolean);- const lengthChanged = Math.abs(changes.durationMs.before - changes.durationMs.after) > 1;- const clock = (ms: number) => formatClock(ms);-- return (- <div className="flex w-full max-w-[26rem] flex-col gap-2 self-start rounded-[10px] border border-[var(--border)] p-2">- <div className="flex min-w-0 items-center gap-2.5">- <div className="flex min-w-0 flex-1 flex-col">- <span className="truncate text-[14px] font-medium text-[var(--chat-text)]">{t('turnFrame.changes')}</span>- <span className="truncate text-[12px] text-[var(--chat-hint)]">- {lengthChanged- ? t('turnFrame.length').replace('{from}', clock(changes.durationMs.before)).replace('{to}', clock(changes.durationMs.after))- : clock(changes.durationMs.after)}- {extras.length ? ` · ${extras.join(' · ')}` : ''}- </span>- </div>- </div>- {tiles.length ? (- <div className="grid grid-cols-4 gap-1.5">- {/* two clips can carry one id (the same source cut twice): the index keeps the keys apart */}- {tiles.map(({ scene, url }, i) => <SceneTile key={`${scene.id}:${scene.change}:${i}`} scene={scene} url={url} focus={focus} />)}- </div>- ) : null}- {chips.length ? (- <div className="flex flex-wrap gap-1">- {chips.map(({ scene, count }, i) => <SceneChip key={`${scene.kind}:${scene.id}:${scene.change}:${i}`} scene={scene} count={count} focus={focus} />)}- {more > 0 ? <span className="px-1 py-0.5 text-[12px] text-[var(--chat-hint)]">+{more}</span> : null}- </div>- ) : null}- </div>- );-}--function SceneChip({- scene,- count = 1,- focus,-}: {- scene: SceneChange;- /** how many clips of this one name the chip stands for */- count?: number;- focus: React.ContextType<typeof TurnSceneFocusContext>;-}) {- const t = useT();- const mark = scene.change === 'added' ? '+' : scene.change === 'removed' ? '−' : '~';- const tone = scene.change === 'added'- ? 'text-[var(--ok)]'- : scene.change === 'removed' ? 'text-[var(--err)]' : 'text-[var(--chat-hint)]';- const word = t(`turnFrame.${scene.change}`);- const body = (- <>- <span aria-hidden className={`font-mono text-[11px] ${tone}`}>{mark}</span>- <span className={`truncate ${scene.change === 'removed' ? 'line-through' : ''}`}>{scene.label}</span>- {count > 1 ? <span className="shrink-0 tabular-nums text-[var(--chat-hint)]">×{count}</span> : null}- </>- );- const shell = 'inline-flex h-6 max-w-[12rem] items-center gap-1 rounded-md border border-[var(--border)] px-1.5 text-[12px] text-[var(--chat-text)]';- const live = scene.change !== 'removed' && focus?.has(scene.id);- if (!live || !focus) return <span className={`${shell} opacity-80`} title={`${word} · ${scene.label}`}>{body}</span>;- return (- <button- type="button"- onClick={() => focus.focus(scene.id)}- title={`${word} · ${t('turnFrame.jump')}`}- className={`${shell} transition-colors hover:border-[var(--border-strong)] hover:bg-[var(--surface-2)]`}- >- {body}- </button>- );-}--function SceneTile({- scene,- url,- focus,-}: {- scene: SceneChange;- url: string;- focus: React.ContextType<typeof TurnSceneFocusContext>;-}) {- const t = useT();- const live = focus?.has(scene.id);- const mark = scene.change === 'added' ? '+' : '~';- const body = (- <>- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src={url} alt="" loading="lazy" decoding="async" className="aspect-video w-full rounded-[6px] object-cover" />- <span className="mt-1 flex min-w-0 items-center gap-1 text-[11.5px] text-[var(--chat-hint)]">- <span aria-hidden className={`font-mono text-[10.5px] ${scene.change === 'added' ? 'text-[var(--ok)]' : ''}`}>{mark}</span>- <span className="truncate">{scene.label}</span>- </span>- </>- );- const shell = 'flex min-w-0 flex-col text-left';- if (!live || !focus) return <div className={shell}>{body}</div>;- return (- <button- type="button"- onClick={() => focus.focus(scene.id)}- title={`${t(`turnFrame.${scene.change}`)} · ${t('turnFrame.jump')}`}- className={`${shell} rounded-[7px] outline-none transition hover:opacity-85 focus-visible:ring-2 focus-visible:ring-[var(--border-strong)]`}- >- {body}- </button>- );-}--function formatClock(ms: number): string {- const s = Math.max(0, Math.round(ms / 1000));- return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;-}-const AGENT_NAMES: Record<string, string> = {codex: 'Codex', claude: 'Claude Code', gemini: 'Gemini CLI', copilot: 'GitHub Copilot', cursor: 'Cursor',opencode: 'OpenCode', codebuddy: 'CodeBuddy', qwen: 'Qwen Code', kimi: 'Kimi',@@ -827,7 +653,7 @@ function CopyButton({ text }: { text: string }) {/*** The line under a reply: copy, who answered (icon only) · the model · how long ago, and how it stopped if it- * didn't finish normally.+ * didn't finish normally. While it runs, under the status line: copy what it said so far, its log so far, who.** Several agents can answer in one project and their replies look alike, so the footer says which one. A stopped* turn says so, or a reply cut short leaves the reader unsure whether it finished, broke or was stopped.@@ -836,7 +662,7 @@ function CopyButton({ text }: { text: string }) {* running, so the bottom edge stays put when one replaces the other). The time is how long ago; how long it* worked is in the "Worked …" line.*/-function TurnFooter({ entry, items }: { entry: ProjectVersion; items: TranscriptItem[] | null }) {+function TurnFooter({ entry, items, running = false }: { entry: ProjectVersion; items: TranscriptItem[] | null; running?: boolean }) {const t = useT();const locale = useUiLocale();const now = useMinuteTick();@@ -845,8 +671,8 @@ function TurnFooter({ entry, items }: { entry: ProjectVersion; items: Transcriptconst from = Math.max(0, answerStart(items));return items.slice(from).filter((item) => item.kind === 'text').map((item) => item.text ?? '').join('\n\n').trim();}, [items]);- const when = relativeTime(entry.settledAt, locale, now);- const outcome = entry.outcome === 'stopped' ? t('turnFrame.stopped')+ const when = running ? null : relativeTime(entry.settledAt, locale, now);+ const outcome = running ? null : entry.outcome === 'stopped' ? t('turnFrame.stopped'): entry.outcome === 'failed' ? t('turnFrame.failed'): entry.outcome === 'balance' && entry.balance ? t('turnFrame.balance').replaceAll('{provider}', entry.balance.provider): null;@@ -858,8 +684,8 @@ function TurnFooter({ entry, items }: { entry: ProjectVersion; items: Transcript/* -mt-1.5: the footer belongs to the reply above it — close to it, not a row of its own */<div className={`-mt-1.5 flex h-6 min-w-0 items-center gap-1.5 text-[11.5px] text-[var(--chat-hint)] group-hover/reply:opacity-100 ${HOVER_LINE}`}>{answer ? <CopyButton text={answer} /> : null}- {/* developer mode (Settings → Developer): the turn as it happened, every event */}- {developer && project ? <TurnLogButton project={project} turnId={entry.assetId} /> : null}+ {/* developer mode (Settings → Developer): the turn as it happened, every event; while it runs, as it goes */}+ {developer && project && !isPendingAssetId(entry.assetId) ? <TurnLogButton project={project} turnId={entry.assetId} live={running} /> : null}{entry.agent ? (<span className="flex min-w-0 items-center gap-1.5">{/* the icon says which agent (its name on hover); written out it would only repeat it */}diff --git a/apps/desktop/chat/src/components/TurnLog.tsx b/apps/desktop/chat/src/components/TurnLog.tsxindex 3fefd37..734a1c6 100644--- a/apps/desktop/chat/src/components/TurnLog.tsx+++ b/apps/desktop/chat/src/components/TurnLog.tsx@@ -7,6 +7,8 @@* with the model, provider and thinking level that made it, its tokens, or its error. The messages new in that* request are open; the ones carried over from before, and the system prompt, are one line each until opened.* Events: every event the agent sent, each a line opening to the event exactly as it was.+ *+ * Opened while the turn runs, it reads the log again every moment until the turn ends, so it shows the turn so far.*/import React from 'react';import { createPortal } from 'react-dom';@@ -21,7 +23,7 @@ import { BrandLogo } from './BrandLogo';type LogEvent = TurnLogData['events'][number];type T = (key: string) => string;-export function TurnLogButton({ project, turnId }: { project: string; turnId: string }) {+export function TurnLogButton({ project, turnId, live = false }: { project: string; turnId: string; live?: boolean }) {const t = useT();const [open, setOpen] = React.useState(false);return (@@ -31,7 +33,7 @@ export function TurnLogButton({ project, turnId }: { project: string; turnId: st<ScrollText size={12} aria-hidden />{t('turnLog.open')}</button>- {open ? <TurnLogViewer project={project} turnId={turnId} onClose={() => setOpen(false)} /> : null}+ {open ? <TurnLogViewer project={project} turnId={turnId} live={live} onClose={() => setOpen(false)} /> : null}</>);}@@ -40,13 +42,33 @@ const seconds = (ms: number) => (ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `$const fill = (template: string, values: Record<string, string | number>) => template.replace(/\{(\w+)\}/g, (_, k) => String(values[k] ?? ''));const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n));-function TurnLogViewer({ project, turnId, onClose }: { project: string; turnId: string; onClose: () => void }) {+/** how often a running turn's log is read again */+const LIVE_READ_MS = 1500;++function TurnLogViewer({ project, turnId, live, onClose }: { project: string; turnId: string; live: boolean; onClose: () => void }) {const t = useT();const [log, setLog] = React.useState<TurnLogData | null | undefined>(undefined);const [tab, setTab] = React.useState<'calls' | 'events' | null>(null);const [copied, setCopied] = React.useState(false);- const load = React.useCallback(() => { void app.chat.log(project, turnId).then(setLog).catch(() => setLog(null)); }, [project, turnId]);- React.useEffect(load, [load]);+ const load = React.useCallback(() => {+ void app.chat.log(project, turnId).then((next) => setLog(next && 'same' in next ? undefined : next)).catch(() => setLog(null));+ }, [project, turnId]);+ const known = React.useRef<{ size: number; callsSize: number } | null>(null);+ known.current = log ? { size: log.size, callsSize: log.callsSize ?? 0 } : null;+ /* read on opening and once more as the turn ends (its last events); while it runs, again and again, one read at a time */+ React.useEffect(load, [load, live]);+ React.useEffect(() => {+ if (!live) return undefined;+ let reading = false;+ const timer = window.setInterval(() => {+ if (reading) return;+ reading = true;+ /* read again only once it has grown */+ void app.chat.log(project, turnId, known.current ?? undefined)+ .then((next) => { if (next && !('same' in next)) setLog(next); }).catch(() => {}).finally(() => { reading = false; });+ }, LIVE_READ_MS);+ return () => window.clearInterval(timer);+ }, [live, project, turnId]);React.useEffect(() => {const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); onClose(); } };window.addEventListener('keydown', onKey, true);@@ -89,6 +111,8 @@ function TurnLogViewer({ project, turnId, onClose }: { project: string; turnId:<span className={`rounded-[6px] px-1.5 py-0.5 text-[11.5px] font-medium ${done.ok ? 'bg-[var(--bg-hover)] text-[var(--chat-hint)]' : 'bg-[var(--err)]/15 text-[var(--err)]'}`}>{done.ok ? String(done.stopReason ?? t('turnLog.ended')) : t('turnLog.failed')}</span>+ ) : live ? (+ <span className="rounded-[6px] bg-[var(--bg-hover)] px-1.5 py-0.5 text-[11.5px] font-medium"><span className="text-sweep">{t('turnLog.running')}</span></span>) : null}</div><div className="mt-1 flex min-w-0 items-center gap-1.5 text-[12.5px] text-[var(--chat-hint)]">@@ -112,7 +136,7 @@ function TurnLogViewer({ project, turnId, onClose }: { project: string; turnId:<button type="button" aria-label={t('turnLog.close')} onClick={onClose}className="flex h-8 w-8 items-center justify-center rounded-[8px] text-[var(--chat-hint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--chat-text)]"><X size={16} /></button></div>- {log === undefined ? <p className="px-5 py-4 text-[13px] text-[var(--chat-hint)]">{t('turnLog.loading')}</p>+ {log === undefined || (log === null && live) ? <p className="px-5 py-4 text-[13px] text-[var(--chat-hint)]">{t('turnLog.loading')}</p>: log === null ? <p className="px-5 py-4 text-[13px] text-[var(--chat-hint)]">{t('turnLog.none')}</p> : (<><div className="flex shrink-0 items-center gap-4 border-b border-[var(--border)] px-5">@@ -213,10 +237,11 @@ function MessageRow({ message, index, fresh, open: initial, t }: { message: Item}function Calls({ calls, start, t }: { calls: ModelCall[]; start: number; t: T }) {- const [picked, setPicked] = React.useState(calls.length);+ /* the latest until one is picked: while the turn runs, the newest request as it comes */+ const [picked, setPicked] = React.useState<number | null>(null);const [raw, setRaw] = React.useState(false);const [version, setVersion] = React.useState({ all: null as boolean | null, n: 0 });- const call = calls[Math.min(picked, calls.length) - 1]!;+ const call = calls[Math.min(picked ?? calls.length, calls.length) - 1]!;const u = usageOf(call);const answer = call.answer;const failed = answer?.stopReason === 'error';@@ -233,7 +258,7 @@ function Calls({ calls, start, t }: { calls: ModelCall[]; start: number; t: T })const asked = (c.answer?.content ?? []).filter((p: Item) => p.type === 'toolCall').map((p: Item) => p.name);const error = c.answer?.stopReason === 'error';return (- <button key={c.no} type="button" onClick={() => setPicked(c.no)}+ <button key={c.no} type="button" onClick={() => setPicked(c.no === calls.length ? null : c.no)}className={`block w-full px-4 py-2 text-left text-[12px] ${c.no === call.no ? 'bg-[var(--bg-hover)]' : 'hover:bg-[var(--bg-hover)]'}`}><div className="flex items-baseline gap-2"><b className={`text-[12.5px] ${error ? 'text-[var(--err)]' : 'text-[var(--chat-text)]'}`}>#{c.no}</b>@@ -344,6 +369,8 @@ function rowOf(event: LogEvent, titles: Map<string, string>): Omit<Row, 'at' | 'case 'permission-answer': return { kind: 'ask', label: 'permission · answer', summary: str(event.optionId ?? 'cancelled') };case 'question': return { kind: 'ask', label: 'question', summary: str(event.message ?? event.questions, 300) };case 'question-answer': return { kind: 'ask', label: 'question · answer', summary: str(event.answers ?? 'skipped', 300) };+ case 'steer': return { kind: 'prompt', label: 'steer', summary: str(event.text, 600) };+ case 'steer-answer': return { kind: 'prompt', label: 'steer · answer', summary: str(event.outcome), tone: event.outcome === 'injected' ? undefined : 'error' };case 'cancel': return { kind: 'end', label: 'cancel', summary: '' };case 'set-option': return { kind: 'update', label: 'set option', summary: `${str(event.configId)} = ${str(event.value)}`, tone: 'quiet' };case 'exit': return { kind: 'end', label: 'exit', summary: `code ${str(event.code)}${event.stderr ? ` ${str(event.stderr, 300)}` : ''}`, tone: event.code ? 'error' : undefined };diff --git a/apps/desktop/chat/src/components/project-version.ts b/apps/desktop/chat/src/components/project-version.tsindex e68d269..6b47eac 100644--- a/apps/desktop/chat/src/components/project-version.ts+++ b/apps/desktop/chat/src/components/project-version.ts@@ -1,5 +1,5 @@import type { PromptDisplay, TurnAttachment } from '@openfilm/shared';-import type { ClipChange } from '@/lib/film-changes';+import type { FileChange } from '@/lib/file-changes';import type { Balance } from '@/lib/balance';/**@@ -28,6 +28,8 @@ export interface ProjectVersion {/** When it was sent / settled (ISO): hover says "N minutes ago". */createdAt?: string;settledAt?: string;- /** what the turn changed in the film, clip by clip (lib/film-changes); none when nothing did */- filmChanges?: ClipChange[];+ /** what the turn changed in the project's files (lib/file-changes); none when nothing did */+ fileChanges?: FileChange[];+ /** 'background': the agent started it by itself, a background task of its own having come back (no message) */+ origin?: 'background';}diff --git a/apps/desktop/chat/src/components/prompt-editor/MentionMenuPlugin.tsx b/apps/desktop/chat/src/components/prompt-editor/MentionMenuPlugin.tsxindex e0cd9a7..b30a479 100644--- a/apps/desktop/chat/src/components/prompt-editor/MentionMenuPlugin.tsx+++ b/apps/desktop/chat/src/components/prompt-editor/MentionMenuPlugin.tsx@@ -37,6 +37,7 @@ import {matchMentionTrigger,type MentionEntry,type MentionProvider,+ type MentionTrigger,} from './mention-menu';import { chatLayer } from '@/lib/chat-layer';@@ -51,6 +52,8 @@ export interface MentionMenuConfig {* The file list is fetched only then: most sessions never mention a file.*/onOpen?: () => void;+ /** When typing opens it: an `@` (the default), or a `/` at the start (the agent's commands, matchSlashTrigger). */+ trigger?: (textBeforeCursor: string) => MentionTrigger | null;}/** Lexical requires options to subclass MenuOption (it attaches a ref for scrolling). */@@ -63,7 +66,7 @@ class MentionMenuOption extends MenuOption {}}-export function MentionMenuPlugin({ providers, label, onOpen }: MentionMenuConfig) {+export function MentionMenuPlugin({ providers, label, onOpen, trigger: match = matchMentionTrigger }: MentionMenuConfig) {const [editor] = useLexicalComposerContext();const [query, setQuery] = React.useState('');@@ -83,8 +86,10 @@ export function MentionMenuPlugin({ providers, label, onOpen }: MentionMenuConficonst handleOpen = React.useCallback(() => onOpenRef.current?.(), []);const handleQueryChange = React.useCallback((value: string | null) => setQuery(value ?? ''), []);+ const matchRef = React.useRef(match);+ matchRef.current = match;const triggerFn = React.useCallback((text: string): MenuTextMatch | null => {- const trigger = matchMentionTrigger(text);+ const trigger = matchRef.current(text);if (!trigger) return null;/* No matches, no menu: an open menu takes the arrow keys, so an empty one would lockthem while the user probably wants to move the caret. */@@ -100,6 +105,18 @@ export function MentionMenuPlugin({ providers, label, onOpen }: MentionMenuConfi(option: MentionMenuOption, nodeToReplace: TextNode | null, closeMenu: () => void) => {const { item } = option.entry;const picked = item.disabled ? null : item.select();+ /* a command goes in as its words, with a space for what follows */+ if (picked && 'text' in picked) {+ editor.update(() => {+ const node = $createTextNode(`${picked.text} `);+ if (nodeToReplace) nodeToReplace.replace(node);+ else $insertNodes([node]);+ node.select();+ closeMenu();+ });+ keepCaretInComposer(editor);+ return;+ }const references = picked ? [picked].flat() : [];/* A disabled item yields nothing, but the menu still closes: an open menu takesEnter, so the next Enter would not send. Same when select() returns nothing@@ -284,7 +301,7 @@ function MentionMenu({<div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden p-1.5">{options.map((option, index) => {const { item, groupLabel, firstOfGroup } = option.entry;- const Icon = item.kind === 'file' ? fileIcon(item.label) : PILL_ICON[item.kind];+ const Icon = item.icon ?? (item.kind === 'file' ? fileIcon(item.label) : PILL_ICON[item.kind]);const selected = index === selectedIndex;return (<React.Fragment key={option.key}>@@ -318,12 +335,14 @@ function MentionMenu({<Icon size={13} /></span>{/* A disabled item keeps its full name and the hint shrinks instead. */}- <span className={`truncate text-[var(--text)] ${item.disabled ? 'shrink-0' : 'min-w-0 flex-1'}`}>{item.label}</span>+ <span className={`truncate text-[var(--text)] ${item.disabled || item.describes ? 'max-w-[60%] shrink-0' : 'min-w-0 flex-1'}`}>{item.label}</span>{/* Disabled: why. Otherwise: the file size or timecode. */}{item.disabled && item.disabledHint ? (<span className="min-w-0 flex-1 truncate text-right text-[11px] text-[var(--text-faint)]" title={item.disabledHint}>{item.disabledHint}</span>+ ) : item.detail && item.describes ? (+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-[var(--text-faint)]" title={item.detail}>{item.detail}</span>) : item.detail ? (<span className="shrink-0 tabular-nums text-[11.5px] text-[var(--text-faint)]">{item.detail}diff --git a/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx b/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsxindex 60b9891..61b9e5f 100644--- a/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx+++ b/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx@@ -34,6 +34,7 @@ import {PromptReferenceNode,} from './PromptReferenceNode';import { MentionMenuPlugin, type MentionMenuConfig } from './MentionMenuPlugin';+import { matchSlashTrigger } from './mention-menu';import type { PromptPillCard } from './PromptPill';import {collectPromptReferences,@@ -107,6 +108,8 @@ export interface PromptEditorProps {disabled?: boolean;/** What `@` can pick; without it there is no `@` menu. */mentions?: MentionMenuConfig;+ /** The agent's commands, a `/` at the start of the message; without it there is no `/` menu. */+ commands?: MentionMenuConfig;}/**@@ -139,6 +142,7 @@ export const PromptEditor = React.forwardRef<PromptEditorHandle, PromptEditorProautoFocus,disabled,mentions,+ commands,} = props;const lookup = React.useMemo(() => {@@ -210,6 +214,7 @@ export const PromptEditor = React.forwardRef<PromptEditorHandle, PromptEditorPro<ChangePlugin onChange={onChange} lookup={lookup} /><HandlePlugin ref={ref} lookupRef={lookupRef} autoFocus={autoFocus} />{mentions ? <MentionMenuPlugin {...mentions} /> : null}+ {commands ? <MentionMenuPlugin {...commands} trigger={matchSlashTrigger} /> : null}</PromptReferenceContext.Provider></LexicalComposer>);diff --git a/apps/desktop/chat/src/components/prompt-editor/mention-menu.ts b/apps/desktop/chat/src/components/prompt-editor/mention-menu.tsindex 6077556..1e41240 100644--- a/apps/desktop/chat/src/components/prompt-editor/mention-menu.ts+++ b/apps/desktop/chat/src/components/prompt-editor/mention-menu.ts@@ -1,10 +1,12 @@/**- * The `@` menu: when typing counts as an `@`, which items show, and in what order.+ * The `@` menu (and the `/` menu of the agent's commands): when typing counts as an `@` or a `/`, which items show,+ * and in what order.** Pure logic; the Lexical half is in MentionMenuPlugin. Kept apart so these rules can be* tested on plain strings: an email address opening the menu, or the best match ranked* eighth, raises no error.*/+import type React from 'react';import type { PromptReference, PromptReferenceKind } from './prompt-text';/**@@ -27,12 +29,17 @@ export interface MentionItem {disabled?: boolean;/** Why it is not usable; a gray item without a reason looks broken. */disabledHint?: string;+ /** The detail is a description (an agent's command): the label keeps its width, the detail is cut. */+ describes?: boolean;+ /** Its own icon, instead of its kind's (an agent's command). */+ icon?: React.ComponentType<{ size?: number; className?: string }>;/*** Picks it: records what it needs and returns how it appears in the sentence, possibly- * several references (the current selection is every selected thing). Null or empty- * means it failed (too many references, or the thing is gone).+ * several references (the current selection is every selected thing), or plain text+ * (`{ text }`: an agent's command). Null or empty means it failed (too many references,+ * or the thing is gone).*/- select: () => PromptReference | PromptReference[] | null;+ select: () => PromptReference | PromptReference[] | { text: string } | null;}/**@@ -92,6 +99,17 @@ export function matchMentionTrigger(textBeforeCursor: string): MentionTrigger |return { leadOffset: at, query, replaceableString: textBeforeCursor.slice(at) };}+/**+ * Whether the message so far is a `/` being typed at its very start: an agent's command, as in its own chat (`/` in+ * the middle of a sentence is a path or a fraction). The query is what follows, up to the first space.+ */+export function matchSlashTrigger(textBeforeCursor: string): MentionTrigger | null {+ const m = /^\s*\/([^\s/]{0,40})$/.exec(textBeforeCursor);+ if (!m) return null;+ const at = textBeforeCursor.indexOf('/');+ return { leadOffset: at, query: m[1]!, replaceableString: textBeforeCursor.slice(at) };+}+/* Ranking: prefix < word start < substring < subsequence (other characters in between).Within a tier, an earlier match ranks higher: "video" at position 3 of my-video.mp4beats position 20 of a-really-long-name-video.mp4.diff --git a/apps/desktop/chat/src/components/useStickToBottom.ts b/apps/desktop/chat/src/components/useStickToBottom.tsindex 9fadc9f..3cdfe6e 100644--- a/apps/desktop/chat/src/components/useStickToBottom.ts+++ b/apps/desktop/chat/src/components/useStickToBottom.ts@@ -53,7 +53,8 @@ export type StickToBottom = {*/pinIfFollowing: () => void;/**- * Skips pinning on the next height change and stops following.+ * Skips pinning on the next height change and stops following, unless the view is+ * still at the bottom once the change settles.** Expanding or collapsing a summary changes height, and the observer would pin back to* the bottom, pulling away the row the user just clicked.@@ -194,13 +195,20 @@ export function useStickToBottom(): StickToBottom {const skipNextPin = React.useCallback(() => {skipPin.current = true;following.current = false;- setAtBottom(false);const gen = ++skipGen.current;/* The content grows on the click frame and the spacer shrinks on the next, so bothobservations are skipped. On repeated clicks only the last one counts. */requestAnimationFrame(() => {requestAnimationFrame(() => {- if (skipGen.current === gen) skipPin.current = false;+ if (skipGen.current !== gen) return;+ skipPin.current = false;+ /* Still at the very bottom: nothing went below the view (the running turn's+ min-height took the change), so keep following and hide "Jump to latest". */+ const el = viewportNode.current;+ if (el && el.scrollHeight - el.scrollTop - el.clientHeight <= 2) {+ following.current = true;+ setAtBottom(true);+ }});});}, []);@@ -232,7 +240,8 @@ export function useStickToBottom(): StickToBottom {following.current = true;}previousTop = top;- setAtBottom(following.current && near);+ /* A collapse at the bottom clamps scrollTop; during the skip that is not leaving the bottom */+ setAtBottom((following.current || skipPin.current) && near);};const release = () => {// When the content does not scroll yet, a wheel up does nothing and does not release.@@ -270,6 +279,8 @@ export function useStickToBottom(): StickToBottom {return;}if (following.current) pin();+ /* Not following (a row was expanded): show "Jump to latest" once new content goes below the view */+ else if (el.scrollHeight - el.scrollTop - el.clientHeight > NEAR_BOTTOM_PX) setAtBottom(false);});observer.current = ro;ro.observe(el);diff --git a/apps/desktop/chat/src/i18n/locales/en-US.ts b/apps/desktop/chat/src/i18n/locales/en-US.tsindex c716a52..d3f1d79 100644--- a/apps/desktop/chat/src/i18n/locales/en-US.ts+++ b/apps/desktop/chat/src/i18n/locales/en-US.ts@@ -120,8 +120,8 @@ export const enUS = {previewFailed: 'This file could not be read',},composer: {- agentConnect: 'Connect',- agentConnectFailed: 'It could not connect. Try again in Settings → Agents.',+ commands: 'Commands',+ context: 'Context {percent}% full · {used} of {size} tokens',agentLoading: 'Loading…',agentNone: 'Agent',agentNoneShown: 'No agent is switched on for the chat.',@@ -282,6 +282,7 @@ export const enUS = {reply: 'What came back',rest: 'The rest of the request · {n} tools',reveal: 'Show in folder',+ running: 'Running',sent: 'What the model got · {n} messages, {fresh} new',showAll: 'Show all ({n} chars)',thought: 'Thinking',@@ -289,22 +290,13 @@ export const enUS = {tokens: 'in {input} (cached {cached}) · out {output}',},turnFrame: {- added: 'New',+ background: 'A background task finished; the agent went on',balance: '{provider}: not enough balance',- captions: 'Captions updated',- changes: 'Changes',copied: 'Copied',copy: 'Copy reply',- edited: 'Edited',failed: 'Interrupted',- jump: 'Show in timeline',- length: 'Length {from} → {to}',- oneSound: '1 sound',oneStep: '1 step',- picture: 'Picture updated',plan: 'Plan · {done}/{total}',- removed: 'Removed',- sounds: '{n} sounds',steps: '{n} steps',stopped: 'Stopped',thought: 'Thought for {t}',@@ -315,23 +307,13 @@ export const enUS = {agentRef: {track: 'Track {n}',},- /** what a turn changed in the film, under its reply (components/FilmChangesList) */- filmChanges: {- one: 'Changed 1 clip',- many: 'Changed {n} clips',- added: 'new',- removed: 'removed',- aspect: {- at: 'moved {from} → {to} s',- time: 'trimmed',- speed: 'speed {from}× → {to}×',- track: 'moved from track {from} to {to}',- look: 'look changed',- box: 'moved or resized on the picture',- src: 'file replaced',- overrides: 'edits inside changed',- volume: 'volume changed',- other: 'changed',- },+ /** what a turn changed in the project's files, under its reply (components/FileChangesList) */+ fileChanges: {+ more: '{n} more files',+ fewer: 'Show fewer',+ cut: 'Only the first changed lines are kept.',+ added: 'New',+ removed: 'Deleted',+ changed: 'Changed',},};diff --git a/apps/desktop/chat/src/i18n/locales/es.ts b/apps/desktop/chat/src/i18n/locales/es.tsindex f9aec97..f8e0526 100644--- a/apps/desktop/chat/src/i18n/locales/es.ts+++ b/apps/desktop/chat/src/i18n/locales/es.ts@@ -121,8 +121,8 @@ export const es: Words = {previewFailed: 'No se pudo leer este archivo',},composer: {- agentConnect: 'Conectar',- agentConnectFailed: 'No se pudo conectar. Inténtalo de nuevo en Configuración → Agentes.',+ commands: 'Comandos',+ context: 'Contexto al {percent}% · {used} de {size} tokens',agentLoading: 'Cargando…',agentNone: 'Agente',agentNoneShown: 'No hay ningún agente activado para el chat.',@@ -282,6 +282,7 @@ export const es: Words = {reply: 'Lo que volvió',rest: 'El resto de la solicitud · {n} herramientas',reveal: 'Mostrar en la carpeta',+ running: 'En curso',sent: 'Lo que recibió el modelo · {n} mensajes, {fresh} nuevos',showAll: 'Mostrar todo ({n} caracteres)',thought: 'Razonamiento',@@ -289,22 +290,13 @@ export const es: Words = {tokens: 'entrada {input} (caché {cached}) · salida {output}',},turnFrame: {- added: 'Nuevo',+ background: 'Terminó una tarea en segundo plano; el agente siguió',balance: '{provider}: saldo insuficiente',- captions: 'Subtítulos actualizados',- changes: 'Cambios',copied: 'Copiado',copy: 'Copiar respuesta',- edited: 'Editado',failed: 'Interrumpido',- jump: 'Mostrar en la línea de tiempo',- length: 'Duración {from} → {to}',- oneSound: '1 sonido',oneStep: '1 paso',- picture: 'Imagen actualizada',plan: 'Plan · {done}/{total}',- removed: 'Eliminado',- sounds: '{n} sonidos',steps: '{n} pasos',stopped: 'Detenido',thought: 'Pensó durante {t}',@@ -315,23 +307,13 @@ export const es: Words = {agentRef: {track: 'Pista {n}',},- /** what a turn changed in the film, under its reply (components/FilmChangesList) */- filmChanges: {- one: '1 clip cambiado',- many: '{n} clips cambiados',- added: 'nuevo',- removed: 'eliminado',- aspect: {- at: 'movido {from} → {to} s',- time: 'recortado',- speed: 'velocidad {from}× → {to}×',- track: 'pasado de la pista {from} a la {to}',- look: 'aspecto cambiado',- box: 'movido o redimensionado en la imagen',- src: 'archivo sustituido',- overrides: 'cambios dentro modificados',- volume: 'volumen cambiado',- other: 'cambiado',- },+ /** what a turn changed in the project's files, under its reply (components/FileChangesList) */+ fileChanges: {+ more: '{n} archivos más',+ fewer: 'Mostrar menos',+ cut: 'Solo se guardan las primeras líneas cambiadas.',+ added: 'Nuevo',+ removed: 'Eliminado',+ changed: 'Cambiado',},};diff --git a/apps/desktop/chat/src/i18n/locales/ja.ts b/apps/desktop/chat/src/i18n/locales/ja.tsindex 29db0da..bb234bd 100644--- a/apps/desktop/chat/src/i18n/locales/ja.ts+++ b/apps/desktop/chat/src/i18n/locales/ja.ts@@ -121,8 +121,8 @@ export const ja: Words = {previewFailed: 'このファイルを読み込めませんでした',},composer: {- agentConnect: '接続',- agentConnectFailed: '接続できませんでした。設定 → エージェントでもう一度お試しください。',+ commands: 'コマンド',+ context: 'コンテキスト {percent}% 使用 · {used} / {size} トークン',agentLoading: '読み込み中…',agentNone: 'エージェント',agentNoneShown: 'チャットで使えるエージェントがオンになっていません。',@@ -282,6 +282,7 @@ export const ja: Words = {reply: '返ってきた内容',rest: 'リクエストのその他 · ツール {n} 件',reveal: 'フォルダに表示',+ running: '実行中',sent: 'モデルに渡した内容 · {n} 件、新規 {fresh} 件',showAll: 'すべて表示({n} 文字)',thought: '思考',@@ -289,22 +290,13 @@ export const ja: Words = {tokens: '入力 {input}(キャッシュ {cached})· 出力 {output}',},turnFrame: {- added: '新規',+ background: 'バックグラウンドのタスクが終わり、エージェントが続けました',balance: '{provider}:残高が不足しています',- captions: '字幕を更新しました',- changes: '変更',copied: 'コピーしました',copy: '返信をコピー',- edited: '編集済み',failed: '中断されました',- jump: 'タイムラインで表示',- length: '長さ {from} → {to}',- oneSound: '1 個のサウンド',oneStep: '1 ステップ',- picture: '映像を更新しました',plan: 'プラン · {done}/{total}',- removed: '削除済み',- sounds: '{n} 個のサウンド',steps: '{n} ステップ',stopped: '停止しました',thought: '{t} 考えました',@@ -315,23 +307,13 @@ export const ja: Words = {agentRef: {track: 'トラック {n}',},- /** what a turn changed in the film, under its reply (components/FilmChangesList) */- filmChanges: {- one: '1 個のクリップを変更',- many: '{n} 個のクリップを変更',+ /** what a turn changed in the project's files, under its reply (components/FileChangesList) */+ fileChanges: {+ more: 'ほか {n} ファイル',+ fewer: '折りたたむ',+ cut: '最初の変更行だけを残しています。',added: '新規',removed: '削除',- aspect: {- at: '{from} → {to} 秒に移動',- time: 'トリミング',- speed: '速度 {from}× → {to}×',- track: 'トラック {from} から {to} へ移動',- look: '見た目を変更',- box: '画面上の位置・サイズを変更',- src: 'ファイルを差し替え',- overrides: 'ページ内の調整を変更',- volume: '音量を変更',- other: '変更',- },+ changed: '変更',},};diff --git a/apps/desktop/chat/src/i18n/locales/ko.ts b/apps/desktop/chat/src/i18n/locales/ko.tsindex 84a70c7..681dd68 100644--- a/apps/desktop/chat/src/i18n/locales/ko.ts+++ b/apps/desktop/chat/src/i18n/locales/ko.ts@@ -121,8 +121,8 @@ export const ko: Words = {previewFailed: '이 파일을 읽을 수 없습니다',},composer: {- agentConnect: '연결',- agentConnectFailed: '연결하지 못했습니다. 설정 → 에이전트에서 다시 시도하세요.',+ commands: '명령',+ context: '컨텍스트 {percent}% 사용 · {used} / {size} 토큰',agentLoading: '불러오는 중…',agentNone: '에이전트',agentNoneShown: '채팅에 켜 둔 에이전트가 없습니다.',@@ -282,6 +282,7 @@ export const ko: Words = {reply: '모델 응답',rest: '요청의 나머지 필드 · 도구 {n}개',reveal: '폴더에서 보기',+ running: '진행 중',sent: '모델이 받은 내용 · 메시지 {n}개, 새 메시지 {fresh}개',showAll: '모두 보기 ({n}자)',thought: '생각',@@ -289,22 +290,13 @@ export const ko: Words = {tokens: '입력 {input} (캐시 {cached}) · 출력 {output}',},turnFrame: {- added: '새 항목',+ background: '백그라운드 작업이 끝나 에이전트가 이어서 처리했습니다',balance: '{provider}: 잔액 부족',- captions: '자막 업데이트됨',- changes: '변경 사항',copied: '복사됨',copy: '답변 복사',- edited: '편집됨',failed: '중단됨',- jump: '타임라인에서 보기',- length: '길이 {from} → {to}',- oneSound: '사운드 1개',oneStep: '1단계',- picture: '화면 업데이트됨',plan: '계획 · {done}/{total}',- removed: '삭제됨',- sounds: '사운드 {n}개',steps: '{n}단계',stopped: '중지됨',thought: '{t} 동안 생각함',@@ -315,23 +307,13 @@ export const ko: Words = {agentRef: {track: '트랙 {n}',},- /** what a turn changed in the film, under its reply (components/FilmChangesList) */- filmChanges: {- one: '클립 1개 변경',- many: '클립 {n}개 변경',- added: '새로 추가',+ /** what a turn changed in the project's files, under its reply (components/FileChangesList) */+ fileChanges: {+ more: '파일 {n}개 더 보기',+ fewer: '접기',+ cut: '앞부분의 변경된 줄만 남겼습니다.',+ added: '새 파일',removed: '삭제됨',- aspect: {- at: '{from} → {to}초로 이동',- time: '트리밍',- speed: '속도 {from}× → {to}×',- track: '트랙 {from}에서 {to}(으)로 이동',- look: '모양 변경',- box: '화면 위치·크기 변경',- src: '파일 교체',- overrides: '페이지 안 조정 변경',- volume: '볼륨 변경',- other: '변경',- },+ changed: '변경됨',},};diff --git a/apps/desktop/chat/src/i18n/locales/zh-CN.ts b/apps/desktop/chat/src/i18n/locales/zh-CN.tsindex 9cc366e..a4f4105 100644--- a/apps/desktop/chat/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/chat/src/i18n/locales/zh-CN.ts@@ -121,8 +121,8 @@ export const zhCN: Words = {previewFailed: '无法读取此文件',},composer: {- agentConnect: '连接',- agentConnectFailed: '连接失败。请在设置 → 智能体中重试。',+ commands: '命令',+ context: '上下文已用 {percent}% · {used} / {size} tokens',agentLoading: '正在加载…',agentNone: '智能体',agentNoneShown: '对话中尚未开启任何智能体。',@@ -282,6 +282,7 @@ export const zhCN: Words = {reply: '模型回复',rest: '请求体其余字段 · {n} 个工具',reveal: '在文件夹中显示',+ running: '进行中',sent: '发给模型 · {n} 条消息,新 {fresh} 条',showAll: '展开全部(共 {n} 字符)',thought: '思考',@@ -289,22 +290,13 @@ export const zhCN: Words = {tokens: '输入 {input}(缓存 {cached})· 输出 {output}',},turnFrame: {- added: '新增',+ background: '后台任务完成了,agent 接着处理',balance: '{provider}:余额不足',- captions: '字幕已更新',- changes: '改动',copied: '已复制',copy: '复制回复',- edited: '已编辑',failed: '已中断',- jump: '在时间轴中显示',- length: '时长 {from} → {to}',- oneSound: '1 个声音',oneStep: '1 个步骤',- picture: '画面已更新',plan: '计划 · {done}/{total}',- removed: '已移除',- sounds: '{n} 个声音',steps: '{n} 个步骤',stopped: '已停止',thought: '思考了 {t}',@@ -315,23 +307,13 @@ export const zhCN: Words = {agentRef: {track: '轨道 {n}',},- /** what a turn changed in the film, under its reply (components/FilmChangesList) */- filmChanges: {- one: '改了 1 个片段',- many: '改了 {n} 个片段',+ /** what a turn changed in the project's files, under its reply (components/FileChangesList) */+ fileChanges: {+ more: '还有 {n} 个文件',+ fewer: '收起',+ cut: '只保留了前面的改动行。',added: '新增',removed: '已删除',- aspect: {- at: '从 {from} 秒挪到 {to} 秒',- time: '裁剪了',- speed: '速度 {from}× → {to}×',- track: '从轨道 {from} 挪到 {to}',- look: '样式变了',- box: '画面上的位置或大小变了',- src: '换了文件',- overrides: '页面里的调整变了',- volume: '音量变了',- other: '有改动',- },+ changed: '已修改',},};diff --git a/apps/desktop/chat/src/lib/agent-refs.ts b/apps/desktop/chat/src/lib/agent-refs.tsindex 0fc6397..6e953c0 100644--- a/apps/desktop/chat/src/lib/agent-refs.ts+++ b/apps/desktop/chat/src/lib/agent-refs.ts@@ -15,7 +15,7 @@*/import type { PromptReference as StoredPromptReference } from '@openfilm/shared';import type { StudioRef } from '../app-bridge';-import { clipPillKind } from './film-changes.ts';+import { kindOf, soundRole } from 'openfilm/film-doc';import { refPill } from '../studio-refs.ts';export type AgentRefSegment = { kind: 'text'; text: string } | { kind: 'ref'; ref: StudioRef; raw: string };@@ -89,3 +89,17 @@ export function agentRefPill(ref: StudioRef, { clipSrc, trackLabel }: { clipSrc?const pill = refPill(undefined, ref);return { ...pill, id: `agent:${pill.id}`, ...(ref.kind === 'track' && trackLabel ? { label: trackLabel(ref.track) } : {}) };}++/**+ * The kind of pill (and so its icon) for a clip of this file, as the timeline colors it: a page is a motion graphic,+ * a video or a still is a picture, a sound is a voice, a sound effect or music by where it lives.+ */+export function clipPillKind(src: string, sound = false): 'clipMg' | 'clipVideo' | 'clipVoice' | 'clipSfx' | 'clipMusic' {+ const kind = kindOf({ src, ...(sound ? { sound: true } : {}) });+ if (kind === 'page') return 'clipMg';+ if (kind === 'sound') {+ const role = soundRole(src);+ return role === 'sfx' ? 'clipSfx' : role === 'music' ? 'clipMusic' : 'clipVoice';+ }+ return 'clipVideo';+}diff --git a/apps/desktop/chat/src/lib/desktop-attachments.ts b/apps/desktop/chat/src/lib/desktop-attachments.tsindex 9dcbac9..18d42d2 100644--- a/apps/desktop/chat/src/lib/desktop-attachments.ts+++ b/apps/desktop/chat/src/lib/desktop-attachments.ts@@ -3,12 +3,16 @@* video's frame) and names above the sentence. On the desktop each goes into the project at once, through Studio's own* import (assets/upload/): the agent works in the project folder, so that is where it can read them, and Studio's* media shows them too. The message says where they are (attachedText), the bubble shows their names and thumbnails.+ * A picture is also sent to the agent beside the text (`picture`), as one pasted in its own chat is, to an agent that+ * takes pictures.*/import React from 'react';import type { TurnAttachment } from '@openfilm/shared';import { isImageAttachment, isVideoAttachment, makeAttachmentThumb, readFileDataUrl, videoFrameDataUrl } from '@/lib/composer-attachments';import { attachmentKind } from '@/lib/project-resources';import { app } from '../app-bridge';+import type { PromptImage } from '@/lib/desktop-bridge';+import { attachedPicture } from '@/lib/ref-pictures';export interface DesktopAttachment {id: string;@@ -23,6 +27,8 @@ export interface DesktopAttachment {state: 'importing' | 'ready' | 'failed';/** where it landed in the project */path?: string;+ /** a picture, as its agent is sent it beside the text */+ picture?: PromptImage;error?: string;}@@ -66,6 +72,7 @@ export function useDesktopAttachments() {for (const { item, file } of items) {if (item.kind === 'image') {void readFileDataUrl(file).then(makeAttachmentThumb).then((thumb) => { if (thumb) patch(item.id, { thumb }); }).catch(() => {});+ void attachedPicture(file).then((picture) => { if (picture) patch(item.id, { picture }); });} else if (isVideoAttachment(file)) {/* a video shows a frame of itself, as a picture does: its name alone says little of what was sent */void videoFrameDataUrl(file).then(makeAttachmentThumb).then((thumb) => { if (thumb) patch(item.id, { thumb }); }).catch(() => {});@@ -115,6 +122,11 @@ export function attachedText(files: readonly DesktopAttachment[]): string {return `\n\nAttached files (in this project folder):\n${placed.map((f) => `- ${f.path} (${attachmentKind({ name: f.name, mediaType: f.mediaType })}, ${formatFileSize(f.size)})`).join('\n')}`;}+/** The pictures among them, as their agent is sent them. */+export function attachedPictures(files: readonly DesktopAttachment[]): PromptImage[] {+ return files.flatMap((f) => (f.picture ? [f.picture] : []));+}+/** What the message keeps of them, to show in its bubble. */export function turnAttachments(files: readonly DesktopAttachment[]): TurnAttachment[] {return files.map((f) => ({ kind: f.kind, name: f.name, ...(f.thumb ? { thumb: f.thumb } : {}) }));diff --git a/apps/desktop/chat/src/lib/desktop-bridge.ts b/apps/desktop/chat/src/lib/desktop-bridge.tsindex 9f08636..b3d3d18 100644--- a/apps/desktop/chat/src/lib/desktop-bridge.ts+++ b/apps/desktop/chat/src/lib/desktop-bridge.ts@@ -31,8 +31,8 @@ export interface LocalAgentState {setupRequired?: 'code-tab' | null;id: LocalAgentId;label: string;- /** The executable it uses: the user's own install, or in development the official one among the adapter's dependencies. null = not installed. */- cli: { path: string; source: 'installed' | 'bundled' } | null;+ /** The executable it uses: the one the person chose, one found on the PATH or in installers' folders, or the copy inside the maker's app. null = not installed. */+ cli: { path: string; source: 'chosen' | 'path' | 'app' } | null;/** Its own reported sign-in state; null when it cannot be asked. */signedIn: boolean | null;/** The official install page. When it is missing the UI points there; the app does not install it for the user. */@@ -40,7 +40,14 @@ export interface LocalAgentState {}export interface LocalAgentSessionInfo {+ /** the agent's own id of the conversation: what `start` takes back as `resume` */sessionId: string;+ /** taken up where it stopped (the agent's own record, or the session still open), not a new one */+ resumed?: boolean;+ /** a message sent while it works can join the running turn (`steer`) */+ steering?: boolean;+ /** its commands, as a session opened only to ask said them (`probe`): ACP's availableCommands */+ commands?: unknown[];agentInfo: { name: string; title?: string; version?: string } | null;authMethods: Array<{ id: string; name: string; description?: string }>;/** Whether our MCP tools were handed over (not when the agent does not take HTTP). */@@ -182,7 +189,8 @@ export interface DesktopBridge {signIn(agent: LocalAgentId): Promise<{ ok: true } | { ok: false; error: string }>;/** Opens a session and closes it at once, only for its options. Sends no message, so costs nothing. */probe(agent: LocalAgentId): Promise<{ ok: true; info: LocalAgentSessionInfo } | { ok: false; error: string; code?: string }>;- start(agent: LocalAgentId, cwd: string): Promise<+ /** `resume`: the agent's own id of a conversation it had (an earlier start's info.sessionId), to go on with */+ start(agent: LocalAgentId, cwd: string, resume?: string | null): Promise<| { ok: true; key: string; info: LocalAgentSessionInfo }| { ok: false; error: string; code?: string; install?: string }>;@@ -193,6 +201,10 @@ export interface DesktopBridge {running?(): Promise<LocalAgentRunningTurn[]>;/** The page has put this finished turn back: the shell forgets it. */ack?(key: string, turnId: string): Promise<{ ok: true }>;+ /** A message sent while a turn runs, into that turn; ok: false when it did not join it. Older shells lack it. */+ steer?(key: string, text: string, images?: PromptImage[]): Promise<{ ok: boolean; outcome: string }>;+ /** What the agent does with nobody having written is the turn `turnId` (null: no longer), in its log. */+ adopt?(key: string, turnId: string | null, meta?: LocalAgentTurnMeta): Promise<{ ok: boolean }>;cancel(key: string): Promise<{ ok: true }>;setOption(key: string, configId: string, value: unknown): Promise<{ ok: boolean; error?: string }>;answerPermission(key: string, requestId: string, optionId: string | null): Promise<{ ok: boolean }>;diff --git a/apps/desktop/chat/src/lib/developer.ts b/apps/desktop/chat/src/lib/developer.tsindex fecd3dc..ea70889 100644--- a/apps/desktop/chat/src/lib/developer.ts+++ b/apps/desktop/chat/src/lib/developer.ts@@ -1,13 +1,18 @@/**- * Settings → Developer, as the chat follows it: on, each turn shows its full log (components/TurnLog.tsx). The app- * keeps the choice; Studio's Settings switches it.+ * Settings → Developer, as the chat follows it: `logs` on, each turn shows its full log (components/TurnLog.tsx);+ * `changes` on (unless turned off), what each turn changed in the files, under its reply (components/FileChangesList).+ * The app keeps the choice; Studio's Settings switches it.*/import React from 'react';-import { app } from '../app-bridge';+import { app, type DeveloperPrefs } from '../app-bridge';-let on = false;+let prefs: DeveloperPrefs = { logs: false, changes: true };const listeners = new Set<() => void>();-const set = (next: boolean) => { if (next === on) return; on = next; for (const listener of listeners) listener(); };+const set = (next: DeveloperPrefs) => {+ if (next.logs === prefs.logs && next.changes === prefs.changes) return;+ prefs = next;+ for (const listener of listeners) listener();+};let started = false;function start() {if (started) return;@@ -15,10 +20,16 @@ function start() {void app.developer.get().then(set).catch(() => {});app.developer.onChange(set);}+const subscribe = (listener: () => void) => { start(); listeners.add(listener); return () => { listeners.delete(listener); }; };+/** each turn's full log, from its footer */export function useDeveloperMode(): boolean {- start();- return React.useSyncExternalStore((listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, () => on, () => false);+ return React.useSyncExternalStore(subscribe, () => prefs.logs, () => false);+}++/** what each turn changed in the files, under its reply */+export function useShowChanges(): boolean {+ return React.useSyncExternalStore(subscribe, () => prefs.changes, () => true);}/** The project the chat shows (its folder): where a turn's log is. */diff --git a/apps/desktop/chat/src/lib/file-changes.ts b/apps/desktop/chat/src/lib/file-changes.tsnew file mode 100644index 0000000..fb07feb--- /dev/null+++ b/apps/desktop/chat/src/lib/file-changes.ts@@ -0,0 +1,32 @@+/**+ * What a turn changed in the project's files (src/file-changes.mjs reads the folder as the turn starts and settles):+ * each file added, removed or changed, its lines added and removed, and the changed lines in hunks. Kept with the+ * turn (`fileChanges` on the saved turn), since afterwards nothing can tell what the files were before.+ *+ * Pure: no React, no bridge, so `node --test` runs it (src/file-changes.test.mjs).+ */++export interface FileHunk { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: string[] }++export interface FileChange {+ /** its path in the project, with `/` */+ path: string;+ change: 'added' | 'removed' | 'changed';+ /** lines added and removed: none for a file that is not text (media, a large file) */+ added?: number;+ removed?: number;+ /** the changed lines, with three around each; `cut`: only the first of them are kept */+ hunks?: FileHunk[];+ cut?: boolean;+}++/** What a saved turn keeps of this (lib/chat-store's Turn, extended here: older turns have none). */+export interface TurnFileChanges { fileChanges?: FileChange[] }++/** A saved turn's file changes, as read back from its file: what does not look like one is left out. */+export function readFileChanges(value: unknown): FileChange[] | null {+ if (!Array.isArray(value)) return null;+ const list = value.filter((c): c is FileChange => Boolean(c) && typeof c.path === 'string'+ && (c.change === 'added' || c.change === 'removed' || c.change === 'changed'));+ return list.length ? list : null;+}diff --git a/apps/desktop/chat/src/lib/film-changes.ts b/apps/desktop/chat/src/lib/film-changes.tsdeleted file mode 100644index fbe0373..0000000--- a/apps/desktop/chat/src/lib/film-changes.ts+++ /dev/null@@ -1,121 +0,0 @@-/**- * What a turn changed in the film: film.html as Studio had it when the turn started, and again when it settled,- * compared clip by clip (by id, which a clip keeps wherever it moves). It is the film that is compared, not what the- * agent said it did, so it is the same for any agent, and it counts what the person did in Studio meanwhile too.- *- * Kept with the turn (`filmChanges` on the saved turn), since afterwards nothing can tell what the film was before.- *- * Pure: no React, no bridge, so `node --test` runs it (src/film-changes.test.mjs).- */-import { clipTag, kindOf, soundRole } from 'openfilm/film-doc';-import type { FilmClip, FilmDoc } from 'openfilm/film-doc';--export type { FilmDoc };--/**- * Which of a clip's facts changed: its place in the film (`at`), its part of the source (`time`, a trim), speed,- * track, look (its class and CSS), box (where it sits on the picture), file, a page's overrides, volume; `other` for- * anything else film.html keeps of it (its attributes).- */-export type ClipAspect = 'at' | 'time' | 'speed' | 'track' | 'look' | 'box' | 'src' | 'overrides' | 'volume' | 'other';--export interface ClipChange {- id: string;- change: 'added' | 'removed' | 'changed';- /** its file: as it is now, or as it was for a clip that is gone */- src: string;- /** what changed, for a changed clip, in the order of ClipAspect */- aspects?: ClipAspect[];- /** before and after, for the facts said with numbers */- at?: [number, number];- speed?: [number, number];- track?: [number, number];- /** its line in film.html before the turn and after it (a clip added has no before, one removed no after) */- before?: string;- after?: string;-}--/** What a saved turn keeps of this (lib/chat-store's Turn, extended here: older turns have none). */-export interface TurnFilmChanges { filmChanges?: ClipChange[] }--const ASPECTS: ClipAspect[] = ['at', 'time', 'speed', 'track', 'look', 'box', 'src', 'overrides', 'volume', 'other'];-/** the fields each aspect reads; what is left of a clip is `other` */-const FIELDS: Partial<Record<ClipAspect, Array<keyof FilmClip>>> = {- at: ['at'], time: ['time'], speed: ['speed'], look: ['class', 'style'], box: ['box'], src: ['src', 'sound'], overrides: ['overrides'], volume: ['volume'],-};-const KNOWN = new Set<string>(['id', ...Object.values(FIELDS).flat()]);--const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);-/* an unset `at` is the film's start and an unset speed is 1, as film.html reads them */-const place = (clip: FilmClip) => clip.at ?? 0;-const rate = (clip: FilmClip) => clip.speed ?? 1;--/** Each clip of a film by its id, with its track. */-function clipsOf(doc: FilmDoc): Map<string, { clip: FilmClip; track: number }> {- const out = new Map<string, { clip: FilmClip; track: number }>();- doc.tracks.forEach((track, index) => {- for (const clip of track.clips) if (clip?.id && !out.has(clip.id)) out.set(clip.id, { clip, track: index });- });- return out;-}--/**- * The clips `after` has that `before` did not, those it lost, and those that changed: in the film's order (the clips- * now, then the ones gone, in the order they were). Nothing changed: an empty list.- */-export function diffFilms(before: FilmDoc, after: FilmDoc): ClipChange[] {- const was = clipsOf(before);- const now = clipsOf(after);- const out: ClipChange[] = [];- for (const [id, { clip, track }] of now) {- const old = was.get(id);- if (!old) { out.push({ id, change: 'added', src: clip.src, after: clipTag(clip) }); continue; }- const changed = new Set<ClipAspect>();- for (const aspect of ASPECTS) {- const fields = FIELDS[aspect];- if (fields && fields.some((field) => !same(old.clip[field], clip[field]))) changed.add(aspect);- }- if (place(old.clip) === place(clip)) changed.delete('at');- if (rate(old.clip) === rate(clip)) changed.delete('speed');- if (old.track !== track) changed.add('track');- const keys = new Set([...Object.keys(old.clip), ...Object.keys(clip)].filter((key) => !KNOWN.has(key)));- if ([...keys].some((key) => !same((old.clip as Record<string, unknown>)[key], (clip as Record<string, unknown>)[key]))) changed.add('other');- if (!changed.size) continue;- const aspects = ASPECTS.filter((aspect) => changed.has(aspect));- out.push({- id,- change: 'changed',- src: clip.src,- aspects,- ...(changed.has('at') ? { at: [place(old.clip), place(clip)] as [number, number] } : {}),- ...(changed.has('speed') ? { speed: [rate(old.clip), rate(clip)] as [number, number] } : {}),- ...(changed.has('track') ? { track: [old.track, track] as [number, number] } : {}),- before: clipTag(old.clip),- after: clipTag(clip),- });- }- for (const [id, { clip }] of was) if (!now.has(id)) out.push({ id, change: 'removed', src: clip.src, before: clipTag(clip) });- return out;-}--/** A saved turn's changes, as read back from its file: what does not look like one is left out. */-export function readFilmChanges(value: unknown): ClipChange[] | null {- if (!Array.isArray(value)) return null;- const list = value.filter((c): c is ClipChange => Boolean(c) && typeof c.id === 'string' && typeof c.src === 'string'- && (c.change === 'added' || c.change === 'removed' || c.change === 'changed'));- return list.length ? list : null;-}--/**- * The kind of pill (and so its icon) for a clip of this file, as the timeline colors it: a page is a motion graphic,- * a video or a still is a picture, a sound is a voice, a sound effect or music by where it lives.- */-export function clipPillKind(src: string, sound = false): 'clipMg' | 'clipVideo' | 'clipVoice' | 'clipSfx' | 'clipMusic' {- const kind = kindOf({ src, ...(sound ? { sound: true } : {}) });- if (kind === 'page') return 'clipMg';- if (kind === 'sound') {- const role = soundRole(src);- return role === 'sfx' ? 'clipSfx' : role === 'music' ? 'clipMusic' : 'clipVoice';- }- return 'clipVideo';-}diff --git a/apps/desktop/chat/src/lib/local-agent-run.ts b/apps/desktop/chat/src/lib/local-agent-run.tsindex 7e20cb7..1c431f6 100644--- a/apps/desktop/chat/src/lib/local-agent-run.ts+++ b/apps/desktop/chat/src/lib/local-agent-run.ts@@ -4,14 +4,15 @@* Runs the user's own Codex / Claude Code in the chat panel (see apps/desktop/src/local-agents-ipc.mjs).** These turns never touch the server: no progress stream, nothing stored there. The shell starts the- * agent's ACP adapter on this machine and hands it our MCP tools; what it says and does arrives event by- * event on `desktop:local-agents:event`. Here those events are projected onto the three the chat panel- * knows (agent-text / agent-act / agent-act-done) and fed to the same `reduceTranscript`, so the panel- * has one rendering path whoever is thinking.+ * agent's ACP adapter on this machine; what it says and does arrives event by event on+ * `desktop:local-agents:event`. Here those events are projected onto the three the chat panel knows+ * (agent-text / agent-act / agent-act-done) and fed to the same `reduceTranscript`, so the panel has one+ * rendering path whoever is thinking.*- * One project + one agent = one ACP session, reused across turns: it remembers the last turn, as when- * chatting on in its own interface. The session restarts only when the window closes (shell side) or- * the agent changes.+ * One conversation of the chat + one agent = one session of the agent's own, reused across turns: it+ * remembers the conversation, as when chatting on in its own interface. Its id is kept with the+ * conversation, so after a restart, a reload or an idle session closed, the next turn takes it up where+ * it stopped (the agent's own resume), and a new conversation is a new session.*/import React from 'react';import {@@ -26,6 +27,7 @@ import {import type { Turn } from '@openfilm/shared';import type { Balance } from '@/lib/balance';import { chatTurns, putChatTurn, type SavedTurn } from '@/lib/chat-store';+import { app } from '../app-bridge';import { reduceTranscript, type TranscriptItem, type TranscriptPlanEntry } from '@/lib/agent-transcript';import {desktopBridge,@@ -370,7 +372,8 @@ export class LocalAgentTurn {const act = this.items.find((item) => item.id === `act:${event.callId}`)?.act;if (!act || !LOOK_ONLY.has(act)) revision += 1;}- this.state = { ...this.state, thinking: false, revision };+ /* the state is a new object only when it changed: the chat around the turn re-renders on it, the words do not */+ if (this.state.thinking || this.state.revision !== revision) this.state = { ...this.state, thinking: false, revision };this.emit();}@@ -402,7 +405,7 @@ export class LocalAgentTurn {const prev = this.items.find((item) => item.id === this.openThought);this.patchItem(this.openThought, { text: (prev?.text ?? '') + text });}- this.state = { ...this.state, thinking: true };+ if (!this.state.thinking) this.state = { ...this.state, thinking: true };this.emit();}@@ -504,12 +507,15 @@ export class LocalAgentTurn {private synthetic = new Set<string>();}-/** The ACP session of one project + one agent (`key` is the shell's). Reused across turns. */+/** The ACP session of one conversation + one agent (`key` is the shell's). Reused across turns. */interface LiveSession {key: string;agent: LocalAgentId;cwd: string;info: LocalAgentSessionInfo;+ /** the project and the conversation it is the session of */+ projectId: string;+ conversation: string;}const sessions = new Map<string, LiveSession>();@@ -521,6 +527,134 @@ const sessions = new Map<string, LiveSession>();export function forgetLocalAgentSessions(agent: LocalAgentId): void {for (const [k, s] of sessions) if (s.agent === agent) sessions.delete(k);}+/* ── the agent's own commands (its `/` menu: built-in ones, the person's skills and custom commands), as its sessions+ say them (ACP available_commands_update). Kept by agent: the last list any of its sessions gave, so a new+ conversation has them before its first message. A list that comes before its session is known here waits for it. */++export interface AgentCommand { name: string; description: string; hint: string | null }++/* kept between launches (this page's storage), so the menu has them before the agent's first session */+const COMMANDS_KEY = 'openfilm.agent-commands.v1';+const commandsByAgent = new Map<LocalAgentId, AgentCommand[]>((() => {+ try { return Object.entries(JSON.parse(localStorage.getItem(COMMANDS_KEY) ?? '{}')) as Array<[LocalAgentId, AgentCommand[]]>; } catch { return []; }+})());+const unclaimedCommands = new Map<string, AgentCommand[]>();+const commandListeners = new Set<() => void>();+const NO_COMMANDS: AgentCommand[] = [];++/** The commands as ACP lists them (`availableCommands`: { name, description, input?.hint }). */+export function readCommands(update: Record<string, unknown>): AgentCommand[] {+ const list = Array.isArray(update.availableCommands) ? update.availableCommands as Array<Record<string, unknown>> : [];+ return list.flatMap((c) => (typeof c?.name === 'string' && c.name ? [{+ name: c.name.replace(/^\//, ''),+ description: typeof c.description === 'string' ? c.description : '',+ hint: typeof (c.input as { hint?: unknown } | null)?.hint === 'string' ? (c.input as { hint: string }).hint : null,+ }] : []));+}++/** The agent's commands as one of its sessions said them (the menu's probe too). */+export function keepCommands(agent: LocalAgentId, list: AgentCommand[]): void {+ commandsByAgent.set(agent, list);+ try { localStorage.setItem(COMMANDS_KEY, JSON.stringify(Object.fromEntries(commandsByAgent))); } catch { /* kept for this launch */ }+ for (const listener of commandListeners) listener();+}++/** The agent's commands, for the composer's `/` menu (empty until one of its sessions has said them). */+export function useAgentCommands(agent: LocalAgentId): AgentCommand[] {+ return React.useSyncExternalStore(+ (listener) => { commandListeners.add(listener); return () => { commandListeners.delete(listener); }; },+ () => commandsByAgent.get(agent) ?? NO_COMMANDS,+ () => NO_COMMANDS,+ );+}++/* ── how full the agent's context is (ACP usage_update): tokens in the conversation now, of its context window, as+ the agent's own chat shows it. By session: each conversation has its own. ── */++export interface AgentContext { used: number; size: number }++const contextByKey = new Map<string, AgentContext>();+const contextListeners = new Set<() => void>();+const tellContext = () => { for (const listener of contextListeners) listener(); };++/** How full the agent's context is in this conversation, once its session has said; null before. */+export function useAgentContext(projectId: string, conversation: string, agent: LocalAgentId): AgentContext | null {+ return React.useSyncExternalStore(+ (listener) => { contextListeners.add(listener); return () => { contextListeners.delete(listener); }; },+ () => {+ const session = sessions.get(`${projectId}:${conversation}:${agent}`);+ return session ? contextByKey.get(session.key) ?? null : null;+ },+ () => null,+ );+}++/* ── the agent working with nobody having written: a background task of its own that ended after its turn (a+ command it ran in the background, a subagent), which it takes up by itself, as in its own chat. Its work is shown+ as a turn of its own in its conversation (`onUnpromptedTurn`, from the page showing the project), which ends with+ the agent's own result for it (a usage_update saying where it came from) or after UNPROMPTED_QUIET_MS of quiet,+ and as soon as the person writes. ── */++/** What a turn the agent started by itself needs from the page: the turn to fill, the page's way to settle it, and+ what the turn's log keeps of it (its conversation), so the log can make it again (recoverLoggedTurns). */+export interface UnpromptedTurn { turn: LocalAgentTurn; done: () => void; meta?: LocalAgentTurnMeta }+type UnpromptedHandler = (where: { projectId: string; conversation: string; agent: LocalAgentId }) => UnpromptedTurn | null;++const UNPROMPTED_QUIET_MS = 30_000;+/** words of a turn just ended can come a moment after it: not a turn of the agent's own until this long after */+const AFTER_TURN_MS = 2000;+const turnEndedAt = new Map<string, number>();+/** the updates that mean the agent is working (not a list or a setting changing) */+const WORK_UPDATES = new Set(['agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'tool_call_update', 'plan']);+const unpromptedHandlers = new Set<UnpromptedHandler>();+const unprompted = new Map<string, UnpromptedTurn & { timer: ReturnType<typeof setTimeout> }>();++/** The page showing a project opens the turns the agent starts by itself in it. Returns a way to stop. */+export function onUnpromptedTurn(handler: UnpromptedHandler): () => void {+ unpromptedHandlers.add(handler);+ return () => { unpromptedHandlers.delete(handler); };+}++function openUnprompted(key: string): LocalAgentTurn | null {+ const session = [...sessions.values()].find((s) => s.key === key);+ if (!session || Date.now() - (turnEndedAt.get(key) ?? 0) < AFTER_TURN_MS) return null;+ let opened: UnpromptedTurn | null = null;+ for (const handler of unpromptedHandlers) {+ opened = handler({ projectId: session.projectId, conversation: session.conversation, agent: session.agent });+ if (opened) break;+ }+ if (!opened) return null;+ turns.set(opened.turn.turnId, opened.turn);+ turnByKey.set(key, opened.turn);+ unprompted.set(key, { ...opened, timer: setTimeout(() => endUnprompted(key), UNPROMPTED_QUIET_MS) });+ void desktopBridge()?.localAgents?.adopt?.(key, opened.turn.turnId, opened.meta);+ return opened.turn;+}++function stillUnprompted(key: string): void {+ const open = unprompted.get(key);+ if (!open) return;+ clearTimeout(open.timer);+ open.timer = setTimeout(() => endUnprompted(key), UNPROMPTED_QUIET_MS);+}++function endUnprompted(key: string): void {+ const open = unprompted.get(key);+ if (!open) return;+ unprompted.delete(key);+ clearTimeout(open.timer);+ open.turn.seal();+ if (turnByKey.get(key) === open.turn) turnByKey.delete(key);+ if (current === open.turn) current = null;+ void desktopBridge()?.localAgents?.adopt?.(key, null);+ open.done();+}++/** Whether this turn is one the agent started by itself (it has no run of the page's to wait on). */+export function isUnpromptedTurn(turnId: string): boolean {+ return [...unprompted.values()].some((open) => open.turn.turnId === turnId);+}+const turns = new Map<string, LocalAgentTurn>();let current: LocalAgentTurn | null = null;let unlisten: (() => void) | null = null;@@ -550,6 +684,21 @@ function listen(): void {const bridge = desktopBridge()?.localAgents;if (!bridge) return;unlisten = bridge.onEvent((event) => {+ if (event.kind === 'update' && event.update.sessionUpdate === 'usage_update') {+ const { used, size, _meta } = event.update as { used?: unknown; size?: unknown; _meta?: Record<string, unknown> };+ if (typeof used === 'number' && typeof size === 'number' && size > 0) { contextByKey.set(event.key, { used, size }); tellContext(); }+ /* the agent's result for work it took up by itself (Claude Code says where it came from): that turn is done */+ const origin = _meta?.['_claude/origin'] as { kind?: unknown } | undefined;+ if (origin && origin.kind !== 'human' && unprompted.has(event.key)) endUnprompted(event.key);+ return;+ }+ if (event.kind === 'update' && event.update.sessionUpdate === 'available_commands_update') {+ const list = readCommands(event.update);+ const agent = [...sessions.values()].find((s) => s.key === event.key)?.agent;+ if (agent) keepCommands(agent, list);+ else unclaimedCommands.set(event.key, list);+ return;+ }const turn = turnByKey.get(event.key);if (event.kind === 'done') {const waiter = doneWaiters.get(event.key);@@ -561,12 +710,17 @@ function listen(): void {return;}if (event.kind === 'exit') {+ endUnprompted(event.key);for (const [k, s] of sessions) if (s.key === event.key) sessions.delete(k);if (turn && !turn.state.error && turn === current) turn.patch({ error: 'The agent stopped unexpectedly.' });const waiter = doneWaiters.get(event.key);if (waiter) { doneWaiters.delete(event.key); waiter({ ok: false, error: 'The agent stopped unexpectedly.' }); }return;}+ if (turn && unprompted.has(event.key)) stillUnprompted(event.key);+ /* working with nobody having written: a background task of its own came back */+ const taken = turn ?? (event.kind === 'update' && WORK_UPDATES.has(event.update.sessionUpdate) ? openUnprompted(event.key) : null);+ if (taken && !turn) { dispatch(taken, event as Record<string, unknown> & { kind: string }); return; }if (!turn) {/* The turn has ended or belongs to another window: a permission request must not hang, so deny it,unless it is a turn still running from before this page reloaded (the shell still holds it): then@@ -615,17 +769,14 @@ export function useLocalAgentTurn(turnId: string | null): { turn: LocalAgentTurnreturn turn ? { turn, state } : null;}-/** The session's options (model, reasoning effort…) as last reported; null before any session. */-export function localAgentSessionInfo(projectId: string, agent: LocalAgentId): LocalAgentSessionInfo | null {- return sessions.get(`${projectId}:${agent}`)?.info ?? null;-}-/**- * Runs a turn. The first time it opens a session (starts the adapter, handshakes, hands over MCP); after- * that the same project reuses it.+ * Runs a turn. The first time in a conversation it opens a session (starts the adapter, handshakes), going+ * on with the agent's own one when `resume` names it; after that the same conversation reuses it.*/export async function runLocalAgentTurn({projectId,+ conversation,+ resume = null,agent,cwd,text,@@ -636,6 +787,10 @@ export async function runLocalAgentTurn({images,}: {projectId: string;+ /** the chat's conversation: each has its own session of the agent's */+ conversation: string;+ /** the agent's own id of this conversation, from a turn before (ProjectSessionItem.agentSessions) */+ resume?: string | null;agent: LocalAgentId;cwd: string;text: string;@@ -647,54 +802,98 @@ export async function runLocalAgentTurn({/** Options the user picked in the model menu (configId → value), set one by one once the session is open. */options?: Record<string, unknown>;onSessionInfo?: (info: LocalAgentSessionInfo) => void;-}): Promise<{ stopReason: string }> {+}): Promise<{ stopReason: string; lastTurnId: string }> {const bridge = desktopBridge()?.localAgents;if (!bridge) throw new Error('This needs the OpenFilm Mac app.');listen();turns.set(turn.turnId, turn);current = turn;- const sessionKey = `${projectId}:${agent}`;+ const sessionKey = `${projectId}:${conversation}:${agent}`;let session = sessions.get(sessionKey);- let first = false;if (!session || session.cwd !== cwd) {- const started = await bridge.start(agent, cwd);+ const started = await bridge.start(agent, cwd, resume);if (!started.ok) {throw Object.assign(new Error(started.error), { code: started.code, install: started.install });}- session = { key: started.key, agent, cwd, info: started.info };+ session = { key: started.key, agent, cwd, info: started.info, projectId, conversation };sessions.set(sessionKey, session);- first = true;+ tellContext();+ const said = unclaimedCommands.get(started.key);+ if (said) { unclaimedCommands.delete(started.key); keepCommands(agent, said); }onSessionInfo?.(started.info);}+ /* a turn the agent was working on by itself ends as the person writes */+ endUnprompted(session.key);turnByKey.set(session.key, turn);- /* Picked options: set only when they differ from the session's current value, saving a round trip */- for (const [configId, value] of Object.entries(options)) {- const option = session.info.configOptions?.find((o) => o.id === configId);- if (!option || option.currentValue === value) continue;- const r = await bridge.setOption(session.key, configId, value);+ /* Picked options: set only when they differ from the session's current value, saving a round trip. The model+ first (it decides which efforts there are), then the rest at once */+ const live = session;+ const setOption = async ([configId, value]: [string, unknown]) => {+ const option = live.info.configOptions?.find((o) => o.id === configId);+ if (!option || option.currentValue === value) return;+ const r = await bridge.setOption(live.key, configId, value);if (r.ok) option.currentValue = value;- }+ };+ const picked = Object.entries(options);+ const isModel = ([configId]: [string, unknown]) => live.info.configOptions?.find((o) => o.id === configId)?.category === 'model';+ for (const entry of picked.filter(isModel)) await setOption(entry);+ await Promise.all(picked.filter((entry) => !isModel(entry)).map(setOption));/* where it is and how to work (the project, the `openfilm` manual, Studio already open) it was told when the- session started (apps/desktop src/agents.mjs INSTRUCTIONS); the first message only adds the language */- const prompt = first ? `Reply in the language of the request below.\n\n${text}` : text;+ session started (apps/desktop src/agents.mjs INSTRUCTIONS): the message goes as the person wrote it */+ const key = session.key;+ /* the turn the agent's words go to at the end: this one, or the last message sent into it while it ran (steer) */+ const last = () => turnByKey.get(key) ?? turn;try {- const r = await bridge.prompt(session.key, prompt, meta, images?.length ? images : undefined);+ const r = await bridge.prompt(key, text, meta, images?.length ? images : undefined);/* The answer to the prompt can overtake its last updates (the closing words of its reply): stoplistening only once they have stopped coming, or the saved reply ends mid-sentence. */- await drain(turn);- if (!r.ok) throw Object.assign(new Error(r.error), r.balance ? { balance: r.balance } : {});- return { stopReason: r.stopReason };+ await drain(last());+ if (!r.ok) throw Object.assign(new Error(r.error), { lastTurnId: last().turnId }, r.balance ? { balance: r.balance } : {});+ return { stopReason: r.stopReason, lastTurnId: last().turnId };} finally {+ const ended = last();turn.seal();- turnByKey.delete(session.key);- if (current === turn) current = null;- if (meta) void bridge.ack?.(session.key, meta.turnId);+ ended.seal();+ turnByKey.delete(key);+ turnEndedAt.set(key, Date.now());+ if (current === turn || current === ended) current = null;+ if (meta) void bridge.ack?.(key, meta.turnId);}}+/** Whether a message sent while this turn runs can join it (the agent takes steering), rather than wait for its end. */+export function canSteer(turnId: string): boolean {+ if (!desktopBridge()?.localAgents?.steer) return false;+ for (const [key, t] of turnByKey) {+ if (t.turnId !== turnId) continue;+ for (const s of sessions.values()) if (s.key === key) return s.info.steering === true;+ }+ return false;+}++/**+ * A message sent while `fromTurnId` runs, into that turn, as in the agent's own chat: once it has joined, what the+ * agent says and does from then on goes to `next` (the message's own turn in the conversation), and `from` is done.+ * False when it did not join (the turn ended meanwhile, the agent refused): the caller sends it as a turn of its own.+ */+export async function steerLocalAgentTurn(fromTurnId: string, next: LocalAgentTurn, text: string, images?: PromptImage[]): Promise<boolean> {+ const bridge = desktopBridge()?.localAgents;+ const key = [...turnByKey].find(([, t]) => t.turnId === fromTurnId)?.[0];+ if (!bridge?.steer || !key) return false;+ turns.set(next.turnId, next);+ const r = await bridge.steer(key, text, images?.length ? images : undefined).catch(() => null);+ const from = turnByKey.get(key);+ if (!r?.ok || !from || from.turnId !== fromTurnId) return false;+ await drain(from, 150, 1000);+ from.seal();+ turnByKey.set(key, next);+ current = next;+ return true;+}+export interface RecoveredLocalTurn {key: string;meta: LocalAgentTurnMeta;@@ -728,8 +927,8 @@ export async function recoverLocalAgentTurns(projectId: string): Promise<Recoverconst turn = new LocalAgentTurn(meta.turnId, r.agent, meta.turnNo ?? 0);turns.set(meta.turnId, turn);for (const event of r.events) dispatch(turn, event);- const sessionKey = `${projectId}:${r.agent}`;- if (!sessions.has(sessionKey)) sessions.set(sessionKey, { key: r.key, agent: r.agent, cwd: r.cwd, info: { sessionId: '', agentInfo: null, authMethods: [], mcp: true, models: null, modes: null, configOptions: null } });+ const sessionKey = `${projectId}:${meta.sessionId}:${r.agent}`;+ if (!sessions.has(sessionKey)) sessions.set(sessionKey, { key: r.key, agent: r.agent, cwd: r.cwd, projectId, conversation: meta.sessionId, info: { sessionId: '', agentInfo: null, authMethods: [], mcp: true, models: null, modes: null, configOptions: null } });let finished: RecoveredLocalTurn['finished'];if (r.done) {turn.seal();@@ -823,10 +1022,56 @@ export function saveLocalAgentTurn(projectId: string, turn: Turn, items: TranscrputChatTurn(projectId, { turn, items });}-/** The turns run with a local agent in this project (this session). */+/** A running turn's rows as they are kept while it runs: as read back after the app closed on it, nothing still going. */+export function restingItems(items: TranscriptItem[]): TranscriptItem[] {+ return items.some((item) => item.pending) ? items.map((item) => (item.pending ? { ...item, pending: false } : item)) : items;+}++/** what a turn the app closed on (or crashed in) says, kept while it ran and read back with it not running */+export const INTERRUPTED = 'OpenFilm closed while the agent was working on this.';+const ACTIVE_STATUSES = new Set<Turn['status']>(['generating', 'failing', 'canceling']);++/**+ * The turns run with a local agent in this project (this session). One kept while it ran (the page saves a running+ * turn as it goes) and running no more, the app having closed on it, reads as interrupted: what it did so far stays,+ * and the next message goes on from there.+ */export function loadLocalAgentTurns(projectId: string, sessionId: string | null): SavedLocalTurn[] {if (typeof window === 'undefined') return [];- return readSaved(projectId).filter((x) => !sessionId || x.turn.sessionId === sessionId);+ return readSaved(projectId)+ .filter((x) => !sessionId || x.turn.sessionId === sessionId)+ .map((x) => (ACTIVE_STATUSES.has(x.turn.status) && !runningTurns.has(x.turn.id)+ ? { ...x, turn: { ...x.turn, status: 'error' as const, error: INTERRUPTED } }+ : x));+}++/**+ * The turns of this project that have a log and were never kept (the app closed or crashed before it kept them, or a+ * version from before running turns were kept): each made again from its log, as it went, and kept from now on. One+ * that ended says how; one that did not, interrupted. Not the turns running now (this page's, or the app's after a+ * reload). Resolves with how many it made.+ */+export async function recoverLoggedTurns(projectId: string): Promise<number> {+ const held = await desktopBridge()?.localAgents?.running?.().catch(() => []) ?? [];+ const except = [...turns.keys(), ...runningTurns.keys(), ...held.flatMap((r) => (r.meta?.turnId ? [r.meta.turnId] : []))];+ const found = await app.chat.unsaved?.(projectId, except).catch(() => []) ?? [];+ let made = 0;+ for (const { turnId, events } of found) {+ const prompt = events.find((e) => e.kind === 'prompt') as { meta?: LocalAgentTurnMeta; agent?: LocalAgentId } | undefined;+ const meta = prompt?.meta;+ if (!meta?.turn || !meta.sessionId) continue;+ const turn = new LocalAgentTurn(turnId, meta.agent ?? prompt?.agent ?? 'claude', meta.turnNo ?? 0);+ for (const event of events) if (event.kind === 'update' || event.kind === 'question' || event.kind === 'permission') dispatch(turn, event);+ turn.seal();+ const done = [...events].reverse().find((e) => e.kind === 'done') as { ok?: boolean; stopReason?: string; error?: string; t: number } | undefined;+ const patch: Partial<Turn> = !done ? { status: 'error', error: INTERRUPTED }+ : done.ok === false ? { status: 'error', error: String(done.error ?? INTERRUPTED) }+ : done.stopReason === 'cancelled' ? { status: 'cancelled' } : { status: 'ready' };+ const last = events.at(-1)?.t;+ putChatTurn(projectId, { turn: { ...(meta.turn as Turn), ...patch, ...(last ? { updatedAt: new Date(last).toISOString() } : {}) }, items: turn.items });+ made += 1;+ }+ return made;}/* ── Running local turns (across projects) ─────────────────────────────────────────diff --git a/apps/desktop/chat/src/lib/project-sessions.ts b/apps/desktop/chat/src/lib/project-sessions.tsindex a5a2459..e068e3d 100644--- a/apps/desktop/chat/src/lib/project-sessions.ts+++ b/apps/desktop/chat/src/lib/project-sessions.ts@@ -9,6 +9,8 @@ export interface ProjectSessionItem {updatedAt: string;/** How many turns the session has. 0: just opened, nothing said yet. */turns: number;+ /** Each agent's own id of this conversation (by agent): its next turn goes on with it, after a restart too. */+ agentSessions?: Record<string, string>;}export type SessionRecencyKey = 'today' | 'yesterday' | 'week' | 'earlier';diff --git a/apps/desktop/chat/src/lib/project-versions.ts b/apps/desktop/chat/src/lib/project-versions.tsindex f653a4a..fdefdca 100644--- a/apps/desktop/chat/src/lib/project-versions.ts+++ b/apps/desktop/chat/src/lib/project-versions.ts@@ -1,5 +1,5 @@import type { Turn, LibraryVideo, PromptDisplay, TurnAttachment } from '@openfilm/shared';-import { readFilmChanges, type ClipChange, type TurnFilmChanges } from './film-changes';+import { readFileChanges, type FileChange, type TurnFileChanges } from './file-changes';import { readBalance, type Balance, type TurnBalance } from './balance';/**@@ -42,8 +42,10 @@ export interface ProjectVersionEntry {createdAt?: string;/** When the turn settled (ISO), only for settled turns. Hovering under the reply says "N minutes ago". */settledAt?: string;- /** What the turn changed in the film, clip by clip (lib/film-changes); none when nothing did. */- filmChanges?: ClipChange[];+ /** What the turn changed in the project's files (lib/file-changes); none when nothing did. */+ fileChanges?: FileChange[];+ /** 'background': the agent started it by itself, a background task of its own having come back (no message) */+ origin?: 'background';}/** Longest believable turn: anything longer most likely means a later write touched updatedAt. */@@ -92,7 +94,7 @@ export function deriveProjectTurns(return ordered.map((asset) => {const film = videos.find((item) => item.turnId === asset.id);if (film) filmCount += 1;- const filmChanges = readFilmChanges((asset as Turn & TurnFilmChanges).filmChanges);+ const fileChanges = readFileChanges((asset as Turn & TurnFileChanges).fileChanges);return {assetId: asset.id,label: film ? `v${filmCount}` : '',@@ -104,7 +106,8 @@ export function deriveProjectTurns(status: statusOf(asset, Boolean(film)),current: asset.id === selectedId,...frameOf(asset),- ...(filmChanges ? { filmChanges } : {}),+ ...(fileChanges ? { fileChanges } : {}),+ ...((asset as Turn & { origin?: unknown }).origin === 'background' ? { origin: 'background' as const } : {}),};});}diff --git a/apps/desktop/chat/src/lib/ref-pictures.ts b/apps/desktop/chat/src/lib/ref-pictures.tsindex e0b2904..6972a29 100644--- a/apps/desktop/chat/src/lib/ref-pictures.ts+++ b/apps/desktop/chat/src/lib/ref-pictures.ts@@ -80,3 +80,37 @@ export async function referencePictures(refs: StudioRef[], { project, turnId }:}return { pictures, images };}++/** an attached picture is sent as it is up to this size and this many pixels on its long side; larger, made smaller */+const ATTACHED_MAX_BYTES = 4 * 1024 * 1024;+const ATTACHED_MAX_SIDE = 2048;+const AS_IS = new Set(['image/jpeg', 'image/png', 'image/webp']);++/**+ * A picture attached to a message, as its agent is sent it beside the text (as a picture pasted in its own chat is):+ * itself when it is a JPEG, PNG or WebP small enough, else a JPEG at most ATTACHED_MAX_SIDE on its long side. Null+ * when it cannot be read as a picture.+ */+export async function attachedPicture(file: Blob): Promise<PromptImage | null> {+ try {+ const bitmap = await createImageBitmap(file);+ try {+ const long = Math.max(bitmap.width, bitmap.height);+ if (AS_IS.has(file.type) && file.size <= ATTACHED_MAX_BYTES && long <= ATTACHED_MAX_SIDE) {+ return { data: base64(await file.arrayBuffer()), mimeType: file.type };+ }+ const scale = Math.min(1, ATTACHED_MAX_SIDE / long);+ const canvas = new OffscreenCanvas(Math.max(1, Math.round(bitmap.width * scale)), Math.max(1, Math.round(bitmap.height * scale)));+ const context = canvas.getContext('2d');+ if (!context) return null;+ context.fillStyle = '#fff';+ context.fillRect(0, 0, canvas.width, canvas.height);+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);+ return { data: base64(await (await canvas.convertToBlob({ type: 'image/jpeg', quality: 0.85 })).arrayBuffer()), mimeType: 'image/jpeg' };+ } finally {+ bitmap.close();+ }+ } catch {+ return null;+ }+}diff --git a/apps/desktop/chat/src/lib/studio-film.ts b/apps/desktop/chat/src/lib/studio-film.tsindex aefd542..7ee21ad 100644--- a/apps/desktop/chat/src/lib/studio-film.ts+++ b/apps/desktop/chat/src/lib/studio-film.ts@@ -1,12 +1,12 @@/*** The film as Studio has it: film.html, read through Studio's own API (this page is Studio's, so the API is ours too).- * The chat reads it when a project opens and when a turn starts and settles (lib/film-changes compares the two), and- * keeps which file each clip is, so a clip an agent names in its reply gets the icon of what it is.+ * The chat reads it when a project opens and keeps which file each clip is, so a clip an agent names in its reply gets+ * the icon of what it is.*/import React from 'react';-import type { FilmDoc } from './film-changes';+import type { FilmDoc } from 'openfilm/film-doc';-/** how long a read may take before the turn's changes are left unsaid */+/** how long a read may take before it is given up */const READ_WAIT_MS = 4000;let clipSrc = new Map<string, string>();diff --git a/apps/desktop/chat/src/lib/turn-changes.ts b/apps/desktop/chat/src/lib/turn-changes.tsdeleted file mode 100644index d2a9f33..0000000--- a/apps/desktop/chat/src/lib/turn-changes.ts+++ /dev/null@@ -1,95 +0,0 @@-'use client';--/**- * What a turn did to the film: the data for the changes card in the conversation.- *- * A coding agent's card says "3 files changed +12 −3"; people here look at the film, not files. So this compares- * the film evaluated before and after the turn: scenes added, edited or removed, sounds added, captions touched,- * the length before and after.- *- * It compares films, not tool calls, so it doesn't matter which agent ran, or whether the person dragged something- * on the timeline meanwhile: if the film changed, it changed.- *- * When the picture changed without a change in scene structure, the card says only "picture updated" rather than- * inventing a scene.- *- * Kept on this machine (localStorage): both ends are only visible at the time and can't be rebuilt later.- *- * Nothing computes these changes yet in the desktop app; the card stays empty until something does.- */-import React from 'react';--export interface SceneChange {- /** The scene's identity: its clipId, else the key the evaluation gave it. */- id: string;- label: string;- change: 'added' | 'edited' | 'removed';- /** Where it is in the film (after the change for added or edited, before it for removed). */- startMs: number;- kind: 'scene' | 'video';-}--export interface TurnChanges {- scenes: SceneChange[];- sounds: { added: number; removed: number; edited: number };- captions: boolean;- /** The picture changed, but not in any one scene that can be named. */- picture: boolean;- durationMs: { before: number; after: number };-}--const KEY = 'openfilm.turn-changes.v1';-const MAX = 300;-let cache: Map<string, TurnChanges> | null = null;-const listeners = new Set<() => void>();--function load(): Map<string, TurnChanges> {- if (cache) return cache;- cache = new Map();- if (typeof window === 'undefined') return cache;- try {- const raw = JSON.parse(window.localStorage.getItem(KEY) ?? '[]') as unknown;- if (Array.isArray(raw)) {- for (const entry of raw) {- if (Array.isArray(entry) && typeof entry[0] === 'string' && entry[1]) cache.set(entry[0], entry[1] as TurnChanges);- }- }- } catch { /* unreadable: treat as empty */ }- return cache;-}--function sameJson(a: unknown, b: unknown): boolean {- return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);-}--function persist(): void {- if (!cache || typeof window === 'undefined') return;- try {- window.localStorage.setItem(KEY, JSON.stringify([...cache].slice(-MAX)));- } catch { /* storage full: kept for this session only */ }-}--export function setTurnChanges(turnId: string, changes: TurnChanges | null): void {- const map = load();- const prev = map.get(turnId);- if (!changes && !prev) return;- if (changes && prev && sameJson(prev, changes)) return;- /* Delete then set: a Map keeps insertion order, so the latest goes last and the oldest are dropped first */- map.delete(turnId);- if (changes) map.set(turnId, changes);- persist();- for (const fn of listeners) fn();-}--export function turnChanges(turnId: string): TurnChanges | null {- return load().get(turnId) ?? null;-}--function subscribe(fn: () => void): () => void {- listeners.add(fn);- return () => { listeners.delete(fn); };-}--export function useTurnChanges(turnId: string): TurnChanges | null {- return React.useSyncExternalStore(subscribe, () => turnChanges(turnId), () => null);-}diff --git a/apps/desktop/chat/src/state/local-agent-store.ts b/apps/desktop/chat/src/state/local-agent-store.tsindex 4df646e..59eace9 100644--- a/apps/desktop/chat/src/state/local-agent-store.ts+++ b/apps/desktop/chat/src/state/local-agent-store.ts@@ -16,7 +16,7 @@ import {type LocalAgentSessionInfo,type RosterAgent,} from '@/lib/desktop-bridge';-import { forgetLocalAgentSessions } from '@/lib/local-agent-run';+import { forgetLocalAgentSessions, keepCommands, readCommands } from '@/lib/local-agent-run';export type AgentPick = LocalAgentId;@@ -44,10 +44,14 @@ interface LocalAgentStore extends Persisted {/** The option list a session reported, kept for the menu. */noteOptions(agent: LocalAgentId, options: ConfigOptions | null): void;/** No option list yet: ask for one (a session opened and closed, nothing said, nothing spent). */- ensureOptions(agent: LocalAgentId): Promise<void>;+ /** Ask the agent for its options once; one that failed is asked again only on `retry` (the menu opened, Retry). */+ ensureOptions(agent: LocalAgentId, opts?: { retry?: boolean }): Promise<void>;}const probing = new Set<LocalAgentId>();+/** the agents asked for their options since the app started: the ones kept from before are shown until then, but an+ agent updated since (Claude Code with new models) has other options, so each is asked once a launch */+const askedThisLaunch = new Set<LocalAgentId>();const KEY = 'openfilm.local-agents.v2';@@ -159,17 +163,24 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({set({ options: { ...get().options, [agent]: options } });save(get());},- async ensureOptions(agent) {- /* the own key's are known from Settings (agentOptions) */- if (agent === 'byok' || get().options[agent] || probing.has(agent)) return;+ async ensureOptions(agent, { retry = false } = {}) {+ /* the own key's are known from Settings (agentOptions); a failed probe is not tried again on every render, each+ try being a whole session of the agent's */+ if (agent === 'byok' || probing.has(agent)) return;+ const kept = Boolean(get().options[agent]);+ if (kept && askedThisLaunch.has(agent)) return;+ if (get().optionsError[agent] && !retry) return;const api = desktopBridge()?.localAgents;if (!api) return;probing.add(agent);+ askedThisLaunch.add(agent);set({ optionsError: { ...get().optionsError, [agent]: undefined } });try {const r = await api.probe(agent).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e) }));+ if (r.ok && r.info.commands?.length) keepCommands(agent, readCommands({ availableCommands: r.info.commands }));if (r.ok && r.info.configOptions?.length) get().noteOptions(agent, r.info.configOptions);- else set({ optionsError: { ...get().optionsError, [agent]: r.ok ? 'no options' : r.error } });+ /* the ones kept from before stay when this launch's ask fails */+ else if (!kept) set({ optionsError: { ...get().optionsError, [agent]: r.ok ? 'no options' : r.error } });} finally {probing.delete(agent);}@@ -189,22 +200,29 @@ const AGENT_FORCED_PREFS: Partial<Record<LocalAgentId, Record<string, unknown>>>byok: { mode: 'agent-full-access' },};+/** picks the menu no longer offers: plan mode (Claude Code's `plan`, Codex's collaboration mode) */+const DROPPED_PREFS = new Set(['plan', 'collaboration_mode']);+/*** The options in effect for an agent: the person's picks, then the ones the app sets. The own key on the Anthropic API- * runs Claude Code, whose options are Claude Code's (`roster` says which). With the agent's `options` known, an effort- * the person never picked is High, for every model that has one.+ * runs Claude Code, whose options are Claude Code's (`roster` says which). What the person never picked here is the+ * agent's own, as their config has it: the same model and effort as in their terminal.*/export function effectivePrefs(prefs: Persisted['prefs'], agent: LocalAgentId, roster?: RosterAgent[] | null, options?: ConfigOptions): Record<string, unknown> {const claudeHarness = agent === 'byok' && roster?.find((a) => a.id === 'byok')?.byok?.format === 'anthropic';/* "default" was a row the menu no longer offers (the agents name their default for what it is): the agent's own- current value stands instead */- /* a model the own key no longer names: its first one stands instead */+ current value stands instead. A mode picked once (plan mode, offered for a while) is not kept: every agent works+ with full access. A pick the agent no longer offers (a model gone in its update, one the own key no longer names)+ is not kept either: the agent's own stands instead */+ const offers = (id: string, value: unknown) => {+ const option = options?.find((o) => o.id === id);+ return !option?.options?.length || option.options.some((o) => o.value === value);+ };const models = agent === 'byok' ? byokModels(roster ?? null) : null;const kept = Object.fromEntries(Object.entries(prefs[agent] ?? {})- .filter(([id, value]) => value !== 'default' && !(models && id === 'model' && !models.includes(String(value)))));- const effort = options?.find((o) => o.category === 'thought_level');- const high = effort && !(effort.id in kept) && effort.options?.some((o) => o.value === 'high') ? { [effort.id]: 'high' } : {};- return { ...high, ...kept, ...(AGENT_FORCED_PREFS[claudeHarness ? 'claude' : agent] ?? {}) };+ .filter(([id, value]) => value !== 'default' && !DROPPED_PREFS.has(id) && offers(id, value)+ && !(models && id === 'model' && !models.includes(String(value)))));+ return { ...kept, ...(AGENT_FORCED_PREFS[claudeHarness ? 'claude' : agent] ?? {}) };}/** An option's current value (the person's pick first, else the value the session reports). */diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex d29d411..4d43cee 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -19,6 +19,7 @@"@agentclientprotocol/codex-acp": "^1.13.1","@agentclientprotocol/sdk": "1.5.0","@earendil-works/pi-coding-agent": "1.1.0",+ "diff": "9.0.0","electron-updater": "6.8.9","openfilm": "workspace:*"},diff --git a/apps/desktop/scripts/release.mjs b/apps/desktop/scripts/release.mjsindex 6b07ff7..c4d43f1 100644--- a/apps/desktop/scripts/release.mjs+++ b/apps/desktop/scripts/release.mjs@@ -1,7 +1,7 @@/*** Build the app people install: `pnpm --filter @openfilm/desktop release` (`--arch=x64` for Intel Macs, default this* Mac's; `--unsigned` for a local try; `--platform=win --arch=x64|arm64` for the Windows installer, built here too;- * `--official` for the project's own build).+ * `--official` for the project's own build; `--preview` for "OpenFilm Preview", an app of its own to try a build in).** Which build it is comes from the `openfilm` package's product files: a build of this source uses product.json,* empty in the repository (no update feed: the app never looks for updates); `--official` uses product.official.json@@ -60,6 +60,11 @@ if (unsigned && !win && !process.argv.includes('--unsigned')) {/* this build's product: its update feed (see the header) */const official = process.argv.includes('--official');+/* --preview: "OpenFilm Preview", to try a build in apart from an installed OpenFilm: its own name and bundle, data+ folder, Studio home, port and projects (src/flavor.mjs `preview`, from the package's `openfilmFlavor`); no updates */+const preview = process.argv.includes('--preview');+if (preview && official) throw new Error('--preview is never the official build');+const NAME = preview ? 'OpenFilm Preview' : 'OpenFilm';const productFile = join(protocol, official ? 'product.official.json' : 'product.json');const product = JSON.parse(readFileSync(productFile, 'utf8'));const updates = typeof product.desktop?.updates === 'string' ? product.desktop.updates.trim().replace(/\/+$/, '') : '';@@ -85,7 +90,8 @@ const pack = (dir) => execFileSync('npm', ['pack', '--ignore-scripts', '--pack-dconst dependencies = { ...pkg.dependencies, openfilm: `file:../${pack(protocol)}` };writeFileSync(join(stage, 'package.json'), `${JSON.stringify({name: 'openfilm-desktop',- productName: 'OpenFilm',+ productName: NAME,+ ...(preview ? { openfilmFlavor: 'preview' } : {}),version: pkg.version,description: pkg.description,author: 'OpenFilm',@@ -121,23 +127,27 @@ await builder.build({[arch]: true,config: {afterPack: win ? (context) => windowsResources(context) : undefined,+ /* unsigned on a Mac: signed ad hoc, whole, before the .dmg and .zip are made. Electron's fuses are written into+ its framework after the linker signed it, and an Apple chip kills a program whose pages no longer match its+ signature ("Code Signature Invalid") the moment it starts */+ afterSign: !win && unsigned ? (context) => adHocSign(context) : undefined,win: {icon: join(desktop, 'build/icon.ico'),/* resedit writes the icon and version (afterPack); rcedit would need wine on this Mac */signAndEditExecutable: false,- artifactName: 'OpenFilm-Setup-${arch}.${ext}',+ artifactName: `${NAME.replace(' ', '-')}-Setup-\${arch}.\${ext}`,},nsis: {oneClick: true,perMachine: false,installerIcon: join(desktop, 'build/icon.ico'),uninstallerIcon: join(desktop, 'build/icon.ico'),- shortcutName: 'OpenFilm',+ shortcutName: NAME,deleteAppDataOnUninstall: false,- artifactName: 'OpenFilm-Setup-${arch}.${ext}',+ artifactName: `${NAME.replace(' ', '-')}-Setup-\${arch}.\${ext}`,},- appId: 'dev.openfilm.desktop',- productName: 'OpenFilm',+ appId: preview ? 'dev.openfilm.desktop.preview' : 'dev.openfilm.desktop',+ productName: NAME,copyright: 'Copyright © 2026 OpenFilm',electronVersion,asar: true,@@ -163,7 +173,7 @@ await builder.build({icon: join(desktop, 'build/icon.icns'),minimumSystemVersion: '13.0',/* the .zip the updater downloads; the .dmg has its own name (dmg.artifactName) */- artifactName: 'OpenFilm-${version}-${arch}-mac.${ext}',+ artifactName: `${NAME.replace(' ', '-')}-\${version}-\${arch}-mac.\${ext}`,hardenedRuntime: true,gatekeeperAssess: false,entitlements: join(desktop, 'build/entitlements.mac.plist'),@@ -171,16 +181,16 @@ await builder.build({...(unsigned ? { identity: null } : { identity: IDENTITY, notarize: true }),},/* the downloads keep one name from version to version: the website links the latest release's by it */- dmg: { title: 'OpenFilm', artifactName: 'OpenFilm-${arch}.${ext}' },+ dmg: { title: NAME, artifactName: `${NAME.replace(' ', '-')}-\${arch}.\${ext}` },},});if (!unsigned && !win && FEED) {- const app = join(out, arch === 'arm64' ? 'mac-arm64' : 'mac', 'OpenFilm.app');+ const app = join(out, arch === 'arm64' ? 'mac-arm64' : 'mac', `${NAME}.app`);run('/usr/bin/codesign', ['--verify', '--deep', '--strict', app]);run('/usr/bin/xcrun', ['stapler', 'validate', app]);/* 4. the download */- const dmg = join(out, `OpenFilm-${arch}.dmg`);+ const dmg = join(out, `${NAME.replace(' ', '-')}-${arch}.dmg`);run('/usr/bin/codesign', ['--sign', `Developer ID Application: ${IDENTITY}`, '--timestamp', dmg]);run('/usr/bin/xcrun', ['notarytool', 'submit', dmg, '--keychain-profile', NOTARY_PROFILE, '--wait']);run('/usr/bin/xcrun', ['stapler', 'staple', dmg]);@@ -197,11 +207,16 @@ console.log(`\n${readdirSync(out).filter((f) => /\.(dmg|zip|exe|yml)$/.test(f)).console.log(`feed: ${FEED ?? 'none (a build of this source: it never looks for updates)'}`);if (FEED && !existsSync(join(out, win ? 'latest.yml' : 'latest-mac.yml'))) process.exitCode = 1;+/** An unsigned Mac app signed ad hoc (no identity), all of it, so it starts. @param {{ appOutDir: string }} context */+function adHocSign(context) {+ execFileSync('codesign', ['--force', '--deep', '--sign', '-', join(context.appOutDir, `${NAME}.app`)], { stdio: 'inherit' });+}+/** OpenFilm.exe's icon and version, as rcedit would write them. */async function windowsResources(context) {const ResEdit = await import('resedit');const PE = await import('pe-library');- const file = join(context.appOutDir, 'OpenFilm.exe');+ const file = join(context.appOutDir, `${NAME}.exe`);const exe = PE.NtExecutable.from(readFileSync(file), { ignoreCert: true });const res = PE.NtExecutableResource.from(exe);const icon = ResEdit.Data.IconFile.from(readFileSync(join(desktop, 'build/icon.ico')));diff --git a/apps/desktop/shell/bridge.ts b/apps/desktop/shell/bridge.tsindex 556d453..e17f307 100644--- a/apps/desktop/shell/bridge.ts+++ b/apps/desktop/shell/bridge.ts@@ -10,7 +10,7 @@* (src/preload.cjs). Imported before Studio's modules and the chat's: Studio reads its host as it loads.*/import { flushSync } from 'react-dom';-import type { HostAgent, HostAsk, HostUpdate, StudioCommand, StudioHost, StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';+import type { HostAgent, HostAsk, HostUpdate, HostUpdateState, StudioCommand, StudioHost, StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';type Listener<T> = (value: T) => void;type Stop = () => void;@@ -28,7 +28,7 @@ interface Native {localAgents: Record<string, unknown>;importFile(request: { projectId: string; path: string; name: string }): Promise<{ ok: true; path: string } | { ok: false; error: string }>;chat: Record<string, (...args: never[]) => Promise<unknown>>;- prefs: { get(): Promise<{ developer: boolean }>; set(next: { developer?: boolean }): Promise<unknown>; onChange(listener: Listener<{ developer: boolean }>): Stop };+ prefs: { get(): Promise<AppPrefs>; set(next: Partial<AppPrefs>): Promise<unknown>; onChange(listener: Listener<AppPrefs>): Stop };saveLayout(layout: { chatOpen: boolean; chatWidth: number }): void;setTheme(theme: Theme): void;onFullScreen(listener: Listener<boolean>): Stop;@@ -37,6 +37,8 @@ interface Native {onFfmpeg(listener: Listener<unknown>): Stop;onUpdate(listener: Listener<unknown>): Stop;restartToUpdate(): Promise<{ ok: boolean; error?: string }>;+ updateState(): Promise<unknown>;+ checkForUpdate(): Promise<unknown>;}const native = (window as unknown as { openfilmNative: Native }).openfilmNative;@@ -195,11 +197,16 @@ async function withPicture(ref: StudioRef): Promise<StudioRef> {const asks = signal<HostAsk[]>([]);let answerAsk: (id: string, allow: boolean) => void = () => {};-/* ── the app's developer mode (Settings → Developer, kept by the app): Studio switches it, the chat shows logs by it ── */+/* ── Settings → Developer (kept by the app): Studio switches it, the chat shows each turn's log and changes by it ── */+interface AppPrefs { developer: boolean; changes: boolean }+const developerOf = (prefs: AppPrefs) => ({ logs: prefs.developer === true, changes: prefs.changes !== false });const developer = {- get: async () => (await native.prefs.get()).developer,- set: (on: boolean) => native.prefs.set({ developer: on }),- onChange: (listener: Listener<boolean>) => native.prefs.onChange((prefs) => listener(prefs.developer)),+ get: async () => developerOf(await native.prefs.get()),+ set: (next: { logs?: boolean; changes?: boolean }) => native.prefs.set({+ ...(typeof next.logs === 'boolean' ? { developer: next.logs } : {}),+ ...(typeof next.changes === 'boolean' ? { changes: next.changes } : {}),+ }),+ onChange: (listener: Listener<{ logs: boolean; changes: boolean }>) => native.prefs.onChange((prefs) => listener(developerOf(prefs))),};/* ── the app's update, for Studio's top bar: a version downloaded and ready (src/updates.mjs), Restart to install it ── */@@ -218,6 +225,13 @@ const update: NonNullable<StudioHost['update']> = {return native.onUpdate((state) => { told = true; listener(shownUpdate(state)); });},restart: native.restartToUpdate,+ /* the whole state, for Settings → About: now, then every change */+ onState(listener) {+ let told = false;+ void native.updateState().then((s) => { if (!told && s) listener(s as HostUpdateState); });+ return native.onUpdate((s) => { told = true; if (s) listener(s as HostUpdateState); });+ },+ check: async () => (await native.checkForUpdate()) as HostUpdateState | null,};/* ── Studio's host ── */diff --git a/apps/desktop/src/agent-installation.mjs b/apps/desktop/src/agent-installation.mjsindex a39875d..813b59b 100644--- a/apps/desktop/src/agent-installation.mjs+++ b/apps/desktop/src/agent-installation.mjs@@ -1,9 +1,11 @@/*** Where the person's own agents are (agents.mjs AGENTS: Claude Code, Codex, Gemini CLI, …). Only real installations count: a config folder survives an- * uninstall and is never evidence. On Windows an npm install leaves a `.cmd` shim, which no program can start without- * a shell: what it runs is used instead (cmdTarget). Reads no Electron module, so `node --test` can use it.+ * uninstall and is never evidence. On Windows an install by npm, pnpm or Yarn leaves a `.cmd` shim, which no program+ * can start without a shell: what it runs is used instead (cmdTarget), and one that cannot be read is started through+ * cmd.exe (agents.mjs). A program the person chose themselves (Settings → Agents → Locate) comes before any of these.+ * Reads no Electron module, so `node --test` can use it.*/-import { accessSync, constants, readFileSync, readdirSync, statSync } from 'node:fs';+import { accessSync, constants, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs';import { homedir } from 'node:os';import { delimiter, dirname, isAbsolute, join } from 'node:path';@@ -60,19 +62,99 @@ export function claudeAppCli(home = homedir()) {} catch { return null; /* the Claude app has not downloaded Claude Code */ }}-export const HOME_BIN_CANDIDATES = (home = homedir()) => (process.platform === 'win32'- ? [join(home, '.local', 'bin'), ...(process.env.APPDATA ? [join(process.env.APPDATA, 'npm')] : [])]+const windows = process.platform === 'win32';+const valueOf = (env, name) => Object.entries(env ?? {}).find(([k]) => k.toLowerCase() === name.toLowerCase())?.[1] || undefined;++/**+ * The folders Windows installers put programs in, which an app's PATH does not always have: the agents' own+ * installers (~/.local/bin), npm, pnpm, Volta, nvm-windows, Yarn, Bun, Scoop, Chocolatey, winget, and the commands+ * of apps from the Microsoft Store.+ */+export function windowsBinDirs(env = process.env, home = homedir()) {+ const v = (name) => valueOf(env, name);+ const appData = v('APPDATA') ?? join(home, 'AppData', 'Roaming');+ const local = v('LOCALAPPDATA') ?? join(home, 'AppData', 'Local');+ return [+ join(home, '.local', 'bin'),+ join(appData, 'npm'),+ ...(v('PNPM_HOME') ? [v('PNPM_HOME')] : []), join(local, 'pnpm'),+ ...(v('VOLTA_HOME') ? [join(v('VOLTA_HOME'), 'bin')] : []), join(local, 'Volta', 'bin'),+ ...(v('NVM_SYMLINK') ? [v('NVM_SYMLINK')] : []),+ join(local, 'Yarn', 'bin'),+ join(home, '.bun', 'bin'),+ ...(v('SCOOP') ? [join(v('SCOOP'), 'shims')] : []), join(home, 'scoop', 'shims'),+ join(v('ProgramData') ?? join(home, '..', '..', 'ProgramData'), 'chocolatey', 'bin'),+ join(local, 'Microsoft', 'WinGet', 'Links'),+ join(local, 'Microsoft', 'WindowsApps'),+ ];+}++export const HOME_BIN_CANDIDATES = (home = homedir()) => (windows+ ? windowsBinDirs(process.env, home): [join(home, '.local', 'bin'), '/opt/homebrew/bin', '/usr/local/bin']);-const windows = process.platform === 'win32';+/** What a program is called on Windows, in the order cmd.exe tries (an extensionless file there is a shell script). */+const WIN_SUFFIXES = ['.exe', '.cmd', '.bat'];+const isCmdScript = (path) => /\.(?:cmd|bat)$/i.test(path);++/**+ * A program file on Windows. A Microsoft Store app's command (WindowsApps) is a link that cannot be followed like a+ * file, yet starts like one: there, being there is enough.+ */+function presentFile(path) {+ try { return statSync(path).isFile(); } catch { /* maybe a Store app's command */ }+ try { const s = lstatSync(path); return s.isFile() || s.isSymbolicLink(); } catch { return false; }+}-export function findExecutable(name, extraDirs = [], env = process.env) {- const path = env.PATH ?? env.Path ?? '';- for (const dir of [...new Set([...path.split(delimiter), ...extraDirs])].filter(isAbsolute)) {- for (const suffix of windows ? ['.exe', '.cmd', ''] : ['']) {+/** each folder once (on Windows whatever its case), as first spelled */+function unique(dirs, win) {+ const seen = new Map();+ for (const d of dirs) if (d && isAbsolute(d) && !seen.has(win ? d.toLowerCase() : d)) seen.set(win ? d.toLowerCase() : d, d);+ return [...seen.values()];+}+/* an environment spread from Windows' own has its Path as well as the PATH set on purpose: that one wins */+const pathIn = (env) => env?.PATH ?? valueOf(env, 'PATH') ?? '';++export function findExecutable(name, extraDirs = [], env = process.env, { win = windows } = {}) {+ const path = pathIn(env);+ for (const dir of unique([...path.split(win ? ';' : delimiter), ...extraDirs], win)) {+ for (const suffix of win ? WIN_SUFFIXES : ['']) {const file = join(dir, name + suffix);- if (windows ? existsFile(file) : executableFile(file)) return windows && file.toLowerCase().endsWith('.cmd') ? cmdTarget(file) ?? file : file;+ if (win ? presentFile(file) : executableFile(file)) return win && isCmdScript(file) ? cmdTarget(file) ?? file : file;+ }+ }+ return null;+}++/* what a shim runs: "%dp0%\…" (npm), "%~dp0\…" (pnpm, Yarn); never the node.exe it may run it with */+const SHIM_TARGET = /"%(?:~dp0|_?dp0%)\\?([^"%]+?\.(?:js|cjs|mjs|exe|cmd|bat))"/gi;+const scriptFirst = (rel) => (/\.(?:c|m)?js$/i.test(rel) ? 0 : /\.exe$/i.test(rel) ? 1 : 2);++/**+ * What a `.cmd` shim runs (Windows): the package's script or program, which can be started without a shell (a `.cmd`+ * cannot be). Yarn's shim runs another shim, which is read in turn. Codex's script only starts its own program, so+ * the program itself, for this machine's chip. Null when the shim says nothing that is there.+ */+export function cmdTarget(cmd, depth = 0) {+ let text = '';+ try { text = readFileSync(cmd, 'utf8'); } catch { return null; }+ const rels = [...new Set([...text.matchAll(SHIM_TARGET)].map((m) => m[1]))]+ .filter((rel) => !/(?:^|[\\/])node\.exe$/i.test(rel))+ .sort((a, b) => scriptFirst(a) - scriptFirst(b));+ for (const rel of rels) {+ const target = join(dirname(cmd), ...rel.split(/[\\/]+/));+ if (isCmdScript(target)) {+ const next = depth < 3 && existsFile(target) ? cmdTarget(target, depth + 1) : null;+ if (next) return next;+ continue;}+ if (/[\\/]@openai[\\/]codex[\\/]/i.test(target) && /\.js$/i.test(target)) {+ const triple = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';+ const pkg = target.replace(/[\\/]bin[\\/][^\\/]+$/, '');+ const exe = [join(pkg, 'vendor', triple, 'codex', 'codex.exe'), join(pkg, 'node_modules', '@openai', `codex-win32-${process.arch}`, 'vendor', triple, 'codex', 'codex.exe')].find(existsFile);+ if (exe) return exe;+ }+ if (existsFile(target)) return target;}return null;}@@ -81,41 +163,73 @@ function existsFile(path) {try { return statSync(path).isFile(); } catch { return false; }}+/* where Codex is inside Codex.app and ChatGPT.app */+const CODEX_IN_APP = ['Contents/Resources/codex', 'Contents/Resources/codex-cli/bin/codex'];+/**- * What an npm `.cmd` shim runs (Windows): the package's script or program, which can be started without a shell (a- * `.cmd` cannot be). Codex's script only starts its own program, so the program itself, for this machine's chip.+ * The program the person chose for an agent, as it can be started: a `.cmd` shim's target, the `.cmd` beside a+ * PowerShell shim (`.ps1`), the program inside a folder or an app chosen instead of it. Null when it is not there.*/-export function cmdTarget(cmd) {- let text = '';- try { text = readFileSync(cmd, 'utf8'); } catch { return null; }- const rel = /"%(?:~?dp0|_?dp0)%\\([^"]+?\.(?:js|cjs|mjs|exe))"/i.exec(text)?.[1];- if (!rel) return null;- const target = join(dirname(cmd), ...rel.split(/[\\/]+/));- if (/[\\/]@openai[\\/]codex[\\/]/i.test(target) && /\.js$/i.test(target)) {- const triple = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';- const pkg = target.replace(/[\\/]bin[\\/][^\\/]+$/, '');- const exe = [join(pkg, 'vendor', triple, 'codex', 'codex.exe'), join(pkg, 'node_modules', '@openai', `codex-win32-${process.arch}`, 'vendor', triple, 'codex', 'codex.exe')].find(existsFile);- if (exe) return exe;+export function chosenProgram(path, { names = [], win = windows } = {}) {+ if (typeof path !== 'string' || !isAbsolute(path)) return null;+ let folder = false;+ try { folder = statSync(path).isDirectory(); } catch { /* a file, or not there */ }+ if (folder) {+ const inApp = /\.app$/i.test(path) ? [...CODEX_IN_APP, ...names.map((n) => `Contents/MacOS/${n}`)].map((p) => join(path, p)).find(executableFile) : null;+ return inApp ?? names.map((n) => findExecutable(n, [path, join(path, 'bin')], { PATH: '' }, { win })).find(Boolean) ?? null;}- return existsFile(target) ? target : null;+ if (win) {+ if (/\.ps1$/i.test(path)) {+ const cmd = path.replace(/\.ps1$/i, '.cmd');+ return presentFile(cmd) ? cmdTarget(cmd) ?? cmd : null;+ }+ if (!presentFile(path)) return null;+ return isCmdScript(path) ? cmdTarget(path) ?? path : path;+ }+ return executableFile(path) || (/\.(?:c|m)?js$/i.test(path) && existsFile(path)) ? path : null;}/*** The command line program, or the copy inside the maker's own desktop app (many people only ever installed the* app): Codex ships inside Codex.app and ChatGPT.app; the Claude app keeps Claude Code under Application Support, one- * folder per version, the newest used.+ * folder per version, the newest used. `chosen`: the program the person chose, first. `others`: programs found some+ * other way (a Store app's own copy, agents.mjs), after the rest. `source` says which it is: chosen · path · app.*/export function detectAgentInstallation(id, { home = homedir(), env = process.env, pathDirs = HOME_BIN_CANDIDATES(home),- applicationDirs = ['/Applications', join(home, 'Applications')] } = {}) {+ applicationDirs = ['/Applications', join(home, 'Applications')], chosen = null, others = [], win = windows } = {}) {const program = AGENT_PROGRAMS[id] ?? { names: [id] };+ const install = AGENT_DOWNLOADS[id] ?? null;+ const picked = chosen ? chosenProgram(chosen, { names: program.names, win }) : null;+ if (picked) return { installed: true, cli: picked, source: 'chosen', install };const dirs = [...pathDirs, ...(program.dirs?.(home) ?? [])];let cli = null;- for (const name of program.names) if (!cli) cli = findExecutable(name, dirs, env);- if (!cli && id === 'codex') {- cli = applicationDirs.flatMap((dir) => ['Codex.app', 'ChatGPT.app'].flatMap((app) => [- join(dir, app, 'Contents/Resources/codex'), join(dir, app, 'Contents/Resources/codex-cli/bin/codex'),- ])).find(executableFile) ?? null;+ for (const name of program.names) if (!cli) cli = findExecutable(name, dirs, env, { win });+ if (cli) return { installed: true, cli, source: 'path', install };+ if (id === 'codex') {+ cli = applicationDirs.flatMap((dir) => ['Codex.app', 'ChatGPT.app'].flatMap((app) => CODEX_IN_APP.map((p) => join(dir, app, p)))).find(executableFile) ?? null;}if (!cli && id === 'claude') cli = claudeAppCli(home);- return { installed: Boolean(cli), cli, install: AGENT_DOWNLOADS[id] ?? null };+ if (!cli) cli = others.find((file) => (win ? presentFile(file) : executableFile(file))) ?? null;+ return { installed: Boolean(cli), cli, source: cli ? 'app' : null, install };+}++/**+ * For a person whose agent is not found, what was looked at: every folder searched, and each file there with one of+ * the agent's names (any suffix, a PowerShell shim too) with what it runs, if that can be told.+ */+export function searchReport(id, { home = homedir(), env = process.env, pathDirs = HOME_BIN_CANDIDATES(home), win = windows } = {}) {+ const program = AGENT_PROGRAMS[id] ?? { names: [id] };+ const searched = unique([...pathIn(env).split(win ? ';' : delimiter), ...pathDirs, ...(program.dirs?.(home) ?? [])], win);+ const files = [];+ for (const dir of searched) {+ for (const name of program.names) {+ for (const suffix of ['', '.exe', '.cmd', '.bat', '.ps1']) {+ const file = join(dir, name + suffix);+ if (!presentFile(file)) continue;+ const runs = isCmdScript(file) ? cmdTarget(file) : /\.ps1$/i.test(file) ? null : file;+ files.push({ file, runs, usable: win ? suffix !== '' && suffix !== '.ps1' : executableFile(file) });+ }+ }+ }+ return { searched, files };}diff --git a/apps/desktop/src/agent-installation.test.mjs b/apps/desktop/src/agent-installation.test.mjsindex 404bab1..c0d7e41 100644--- a/apps/desktop/src/agent-installation.test.mjs+++ b/apps/desktop/src/agent-installation.test.mjs@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { claudeAppCli, cmdTarget, detectAgentInstallation } from './agent-installation.mjs';+import { chosenProgram, claudeAppCli, cmdTarget, detectAgentInstallation, findExecutable, searchReport, windowsBinDirs } from './agent-installation.mjs';test("an npm .cmd shim (Windows) runs its package's script: that is what gets started", () => {const npm = mkdtempSync(join(tmpdir(), 'of-npm-'));@@ -40,3 +40,110 @@ test("an agent is found by any of its names, and in its own installer's folder owriteFileSync(join(bin, 'cbc'), '', { mode: 0o755 });assert.equal(detectAgentInstallation('codebuddy', { ...none, pathDirs: [bin] }).cli, join(bin, 'cbc'));});++/** a file, its folders made */+const put = (file, text = '', mode = 0o644) => { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, text, { mode }); return file; };++/* the shim npm writes today: it names node.exe first, which is not what it runs */+const npmShim = (rel) => `@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\nIF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\${rel}" %*\r\n`;++test("npm's shim as it is written today: what it runs, never the node.exe it checks for first", () => {+ const npm = mkdtempSync(join(tmpdir(), 'of-npm-'));+ const script = put(join(npm, 'node_modules', '@google', 'gemini-cli', 'dist', 'index.js'));+ put(join(npm, 'gemini.cmd'), npmShim('node_modules\\@google\\gemini-cli\\dist\\index.js'));+ assert.equal(cmdTarget(join(npm, 'gemini.cmd')), script);+});++test("Codex's npm shim: its own program for this machine's chip, not the script that starts it", () => {+ const npm = mkdtempSync(join(tmpdir(), 'of-npm-'));+ put(join(npm, 'node_modules', '@openai', 'codex', 'bin', 'codex.js'));+ const triple = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';+ const exe = put(join(npm, 'node_modules', '@openai', 'codex', 'node_modules', '@openai', `codex-win32-${process.arch}`, 'vendor', triple, 'codex', 'codex.exe'));+ put(join(npm, 'codex.cmd'), npmShim('node_modules\\@openai\\codex\\bin\\codex.js'));+ assert.equal(cmdTarget(join(npm, 'codex.cmd')), exe);+});++test("pnpm's shim (%~dp0, node.exe beside it or not) and Yarn's, which runs another shim", () => {+ const pnpm = mkdtempSync(join(tmpdir(), 'of-pnpm-'));+ const script = put(join(pnpm, 'global', '5', 'node_modules', '@qwen-code', 'qwen-code', 'cli.js'));+ put(join(pnpm, 'qwen.CMD'), '@SETLOCAL\r\n@IF EXIST "%~dp0\\node.exe" (\r\n "%~dp0\\node.exe" "%~dp0\\global\\5\\node_modules\\@qwen-code\\qwen-code\\cli.js" %*\r\n) ELSE (\r\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n node "%~dp0\\global\\5\\node_modules\\@qwen-code\\qwen-code\\cli.js" %*\r\n)\r\n');+ assert.equal(cmdTarget(join(pnpm, 'qwen.CMD')), script);++ const local = mkdtempSync(join(tmpdir(), 'of-yarn-'));+ const yarnScript = put(join(local, 'Data', 'global', 'node_modules', 'opencode-ai', 'bin', 'opencode.js'));+ put(join(local, 'Data', 'global', 'node_modules', '.bin', 'opencode.cmd'), npmShim('..\\opencode-ai\\bin\\opencode.js'));+ put(join(local, 'bin', 'opencode.cmd'), '@"%~dp0\\..\\Data\\global\\node_modules\\.bin\\opencode.cmd" %*\r\n');+ assert.equal(cmdTarget(join(local, 'bin', 'opencode.cmd')), yarnScript);+});++test('on Windows a program is a .exe, .cmd or .bat (never the extensionless script beside it), the PATH given first', () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-win-'));+ put(join(dir, 'kimi'), '#!/bin/sh');+ assert.equal(findExecutable('kimi', [], { PATH: dir }, { win: true }), null);+ const exe = put(join(dir, 'kimi.exe'));+ /* an environment spread from Windows' own has its Path too: the PATH set on purpose wins */+ assert.equal(findExecutable('kimi', [], { Path: '', PATH: dir }, { win: true }), exe);+ const other = mkdtempSync(join(tmpdir(), 'of-win-'));+ const bat = put(join(other, 'copilot.bat'), '@echo off\r\n');+ assert.equal(findExecutable('copilot', [other], { PATH: '' }, { win: true }), bat, 'a shim that says nothing is kept as it is: cmd.exe starts it');+});++test("the folders Windows installers use, the person's own variables first", () => {+ const home = join(tmpdir(), 'Users', 'ana');+ const env = { APPDATA: join(home, 'Roaming'), LOCALAPPDATA: join(home, 'Local'), pnpm_home: join(home, 'pn'), NVM_SYMLINK: join(home, 'nodejs'), ProgramData: join(tmpdir(), 'PD') };+ const dirs = windowsBinDirs(env, home);+ for (const dir of [join(home, '.local', 'bin'), join(home, 'Roaming', 'npm'), join(home, 'pn'), join(home, 'Local', 'pnpm'), join(home, 'Local', 'Volta', 'bin'),+ join(home, 'nodejs'), join(home, 'scoop', 'shims'), join(tmpdir(), 'PD', 'chocolatey', 'bin'), join(home, 'Local', 'Microsoft', 'WinGet', 'Links'), join(home, 'Local', 'Microsoft', 'WindowsApps')]) {+ assert.ok(dirs.includes(dir), dir);+ }+});++test('the program the person chose comes first; it can be a shim, the .cmd beside a .ps1, or a folder with it inside', () => {+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const bin = join(home, 'bin');+ const onPath = put(join(bin, 'codex'), '', 0o755);+ const mine = put(join(home, 'mine', 'codex'), '', 0o755);+ const opts = { home, env: { PATH: bin }, pathDirs: [], applicationDirs: [] };+ if (process.platform !== 'win32') {+ assert.deepEqual(detectAgentInstallation('codex', opts), { installed: true, cli: onPath, source: 'path', install: 'https://developers.openai.com/codex' });+ assert.equal(detectAgentInstallation('codex', { ...opts, chosen: mine }).source, 'chosen');+ assert.equal(detectAgentInstallation('codex', { ...opts, chosen: mine }).cli, mine);+ assert.equal(detectAgentInstallation('codex', { ...opts, chosen: join(home, 'gone') }).cli, onPath, 'one chosen and gone: found as before');+ assert.equal(chosenProgram(join(home, 'mine'), { names: ['codex'] }), mine, 'a folder: the program in it');+ const app = put(join(home, 'Codex.app', 'Contents', 'Resources', 'codex'), '', 0o755);+ assert.equal(chosenProgram(join(home, 'Codex.app'), { names: ['codex'] }), app, 'an app: the Codex inside it');+ assert.equal(chosenProgram(put(join(home, 'notes.txt')), { names: ['codex'] }), null, 'not a program');+ }+ const npm = join(home, 'npm');+ const script = put(join(npm, 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js'));+ put(join(npm, 'claude.cmd'), npmShim('node_modules\\@anthropic-ai\\claude-code\\cli.js'));+ put(join(npm, 'claude.ps1'), '#!/usr/bin/env pwsh');+ assert.equal(chosenProgram(join(npm, 'claude.ps1'), { names: ['claude'], win: true }), script);+ assert.equal(chosenProgram(join(npm, 'claude.cmd'), { names: ['claude'], win: true }), script);+ assert.equal(chosenProgram('relative\\claude.exe', { names: ['claude'], win: true }), null);+});++test('a program found some other way (a Store app) is used last', () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const store = put(join(home, 'Store', 'OpenAI.Codex', 'codex.exe'), '', 0o755);+ const opts = { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [] };+ assert.equal(detectAgentInstallation('codex', opts).cli, null);+ assert.deepEqual(detectAgentInstallation('codex', { ...opts, others: [store] }), { installed: true, cli: store, source: 'app', install: 'https://developers.openai.com/codex' });+});++test('the report: every folder searched, each file with the name, what a shim runs, and what cannot be started', () => {+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const npm = join(home, 'npm');+ const script = put(join(npm, 'node_modules', '@google', 'gemini-cli', 'dist', 'index.js'));+ put(join(npm, 'gemini'), '#!/bin/sh');+ put(join(npm, 'gemini.cmd'), npmShim('node_modules\\@google\\gemini-cli\\dist\\index.js'));+ put(join(npm, 'gemini.ps1'), '');+ const report = searchReport('gemini', { home, env: { PATH: `${npm};${npm.toUpperCase()}` }, pathDirs: [join(home, 'other')], win: true });+ assert.deepEqual(report.searched, [npm, join(home, 'other')], 'each folder once, whatever its case');+ assert.deepEqual(report.files, [+ { file: join(npm, 'gemini'), runs: join(npm, 'gemini'), usable: false },+ { file: join(npm, 'gemini.cmd'), runs: script, usable: true },+ { file: join(npm, 'gemini.ps1'), runs: null, usable: false },+ ]);+});diff --git a/apps/desktop/src/agent-refs.test.mjs b/apps/desktop/src/agent-refs.test.mjsindex 366956c..b1b7a08 100644--- a/apps/desktop/src/agent-refs.test.mjs+++ b/apps/desktop/src/agent-refs.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { agentRefPill, parseAgentRefs } from '../chat/src/lib/agent-refs.ts';+import { agentRefPill, clipPillKind, parseAgentRefs } from '../chat/src/lib/agent-refs.ts';const refs = (text) => parseAgentRefs(text).filter((s) => s.kind === 'ref').map((s) => s.ref);@@ -59,3 +59,13 @@ test('the other pills are the person\'s own pills for the same thing; a track isassert.equal(agentRefPill(file).label, 'logo.png');assert.equal(agentRefPill(file).kind, 'file');});++test('a clip\'s pill kind follows its file, as the timeline colors it', () => {+ assert.equal(clipPillKind('mg/title.html'), 'clipMg');+ assert.equal(clipPillKind('assets/video/talk.mp4'), 'clipVideo');+ assert.equal(clipPillKind('assets/image/logo.png'), 'clipVideo');+ assert.equal(clipPillKind('assets/audio/vo/01.m4a'), 'clipVoice');+ assert.equal(clipPillKind('assets/audio/sfx/whoosh.mp3'), 'clipSfx');+ assert.equal(clipPillKind('assets/audio/music/bed.mp3'), 'clipMusic');+ assert.equal(clipPillKind('assets/video/talk.mp4', true), 'clipVoice');+});diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjsindex 290ea9b..77ecab2 100644--- a/apps/desktop/src/agent-roster.mjs+++ b/apps/desktop/src/agent-roster.mjs@@ -2,17 +2,21 @@* The agents the chat can use, as Settings → Agents shows them, and the person's choices about them:** · codex, claude, gemini, copilot, cursor, opencode, codebuddy, qwen, kimi — the person's own agents (agents.mjs):- * Codex, Claude Code, Gemini CLI, GitHub Copilot, Cursor, OpenCode, CodeBuddy, Qwen Code and Kimi. Their sign-in- * is their own: connecting uses it as it is, and opens Terminal for their own sign-in command only when they are- * not signed in; disconnecting only stops OpenFilm using them (their sign-in is shared with the makers' own apps,- * and stays). Codex and Claude Code are shown in the chat's menu from the start; the others once the person- * connects one or switches it on.+ * Codex, Claude Code, Gemini CLI, GitHub Copilot, Cursor, OpenCode, CodeBuddy, Qwen Code and Kimi. Each uses the+ * account signed in on the computer as it is: connecting opens Terminal for its own sign-in command only when it+ * is signed out, disconnecting only stops OpenFilm using it, and connecting again uses whichever account is signed+ * in then (one switched in the agent or its maker's app). `account` says whose it is. Codex and Claude Code are+ * shown in the chat's menu from the start; the others once the person connects one or switches it on.* · byok — the app's own agent (Pi, pi-agent.mjs) on the person's own key, on a standard API in one of three formats: the OpenAI* Responses API (…/v1/responses), the OpenAI Chat Completions API (…/v1/chat/completions) or the Anthropic Messages* API (…/v1/messages); Pi speaks each. It may name several models (the chat's menu switches between them, the first* one to begin with). Each has to read pictures (the agent looks at its own frames): setting it up sends one small* request with a picture to each, and a model that cannot take it is refused.*+ * One of the person's own agents not found where it is looked for can be pointed at (`locate`): the program they choose+ * is tried (it has to answer `--version`) and used from then on, until they go back to finding it (`useAutomatic`).+ * `diagnose` says what was searched, for them to read or send with an issue.+ ** Each has a switch for whether the chat's menu shows it. Kept in the app's data folder: agents.json (the choices) and* byok.key (the key, sealed with the system's keychain by the caller's `seal`/`unseal`).*@@ -63,10 +67,13 @@ export function readChoices(dataDir) {const byok = raw.byok && typeof raw.byok === 'object' && Object.hasOwn(BYOK_FORMATS, raw.byok.format)? byokChoice(raw.byok): null;+ const paths = {};+ for (const id of OWN_AGENT_IDS) if (typeof raw.paths?.[id] === 'string' && raw.paths[id]) paths[id] = raw.paths[id];return {shown,disconnected: Array.isArray(raw.disconnected) ? raw.disconnected.filter((id) => AGENT_IDS.includes(id)) : [],byok,+ paths,};}@@ -142,8 +149,12 @@ export async function probeModel({ format, baseUrl, key, model, fetch: fetchImpl** @param {{* dataDir: string,- * localAgents: () => Promise<Array<{ id: string, cli: unknown, signedIn: boolean | null, install: string | null, setupRequired: string | null }>>,+ * localAgents: () => Promise<Array<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, install: string | null, setupRequired: string | null }>>,* openSignIn: (id: string) => Promise<{ ok: boolean, error?: string }>,+ * usePaths?: (paths: Record<string, string>) => void,+ * pickProgram?: (id: string, words?: { title?: string, button?: string }) => Promise<string | null>,+ * checkProgram?: (id: string, path: string) => Promise<{ ok: boolean, error?: string, code?: string }>,+ * diagnose?: (id: string) => Promise<{ found: string | null, hint: string | null, text: string } | null>,* closeSessions: (id: string) => void,* seal: (text: string) => Buffer, unseal: (data: Buffer) => string,* onChange: (list: any[]) => void,@@ -153,6 +164,7 @@ export async function probeModel({ format, baseUrl, key, model, fetch: fetchImplexport function createRoster(deps) {const { dataDir } = deps;let choices = readChoices(dataDir);+ deps.usePaths?.(choices.paths);/** what is happening now, beyond what is kept: a sign-in waited for, an error to show */const live = { waiting: {}, errors: {} };let local = null;@@ -166,10 +178,11 @@ export function createRoster(deps) {if (isOwn(id)) {const found = local?.find((a) => a.id === id);if (!found) return { status: 'checking' };- if (!found.cli) return { status: 'missing', install: found.install ?? null, setupRequired: found.setupRequired ?? null };- if (choices.disconnected.includes(id)) return { status: 'off' };- if (found.signedIn === false) return { status: live.waiting[id] ? 'waiting' : 'sign-in' };- return { status: 'ready' };+ const where = { path: found.cli?.path ?? null, chosen: choices.paths[id] ?? null };+ if (!found.cli) return { status: 'missing', install: found.install ?? null, setupRequired: found.setupRequired ?? null, ...where };+ if (choices.disconnected.includes(id)) return { status: 'off', ...where };+ if (found.signedIn === false) return { status: live.waiting[id] ? 'waiting' : 'sign-in', ...where };+ return { status: 'ready', ...where, ...(found.account ? { account: { ...found.account } } : {}) };}if (choices.disconnected.includes(id)) return { status: 'off' };if (!choices.byok || !byokKey()) return { status: 'key' };@@ -239,7 +252,7 @@ export function createRoster(deps) {}},- /** Disconnect here only: its sessions close; an agent's own sign-in stays as it is. */+ /** Disconnect here only: its sessions close; its own sign-in stays as it is (connecting again uses it as it is then). */disconnect(id) {if (!AGENT_IDS.includes(id)) return;delete live.waiting[id];@@ -247,6 +260,46 @@ export function createRoster(deps) {save({ ...choices, disconnected: [...new Set([...choices.disconnected, id])] });},+ /**+ * Point at the program for one of the person's own agents: they choose it, it is tried (`--version`), and it is+ * used from then on. `words`: the dialog's title and button, in Studio's language. `{ ok: false }` without an+ * error when they cancelled.+ */+ async locate(id, words) {+ if (!isOwn(id) || !deps.pickProgram || !deps.checkProgram) return { ok: false, error: `No agent ${id}` };+ const path = await deps.pickProgram(id, words);+ if (!path) return { ok: false };+ const checked = await deps.checkProgram(id, path);+ if (!checked.ok) return { ok: false, error: checked.error ?? '', ...(checked.code ? { code: checked.code } : {}) };+ delete live.errors[id];+ deps.closeSessions(id);+ choices = { ...choices, paths: { ...choices.paths, [id]: path }, shown: { ...choices.shown, [id]: true } };+ deps.usePaths?.(choices.paths);+ save(choices);+ await refresh();+ return { ok: true };+ },++ /** Back to finding the program where it is installed. */+ async useAutomatic(id) {+ if (!Object.hasOwn(choices.paths, id)) return { ok: true };+ const { [id]: _gone, ...paths } = choices.paths;+ deps.closeSessions(id);+ choices = { ...choices, paths };+ deps.usePaths?.(choices.paths);+ save(choices);+ await refresh();+ return { ok: true };+ },++ /** What was searched for one of the person's own agents, and why it is not found (see agents.mjs diagnoseAgent). */+ async diagnose(id) {+ if (!isOwn(id) || !deps.diagnose) return null;+ const report = await deps.diagnose(id);+ void refresh();+ return report;+ },+setShown(id, shown) {if (!AGENT_IDS.includes(id)) return;save({ ...choices, shown: { ...choices.shown, [id]: shown === true } });diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjsindex f96af1e..03b53b6 100644--- a/apps/desktop/src/agent-roster.test.mjs+++ b/apps/desktop/src/agent-roster.test.mjs@@ -119,3 +119,62 @@ test("Codex and Claude Code are shown in the chat from the start, the person's or.setShown('kimi', true);assert.equal(readChoices(dir).shown.kimi, true);});++test('an agent not found can be pointed at: the program is tried first, kept, and used until found automatically again', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));+ let picked = null;+ let check = { ok: true };+ const used = [];+ const asked = [];+ const r = roster(dir, undefined, {+ localAgents: async () => [{ id: 'codex', cli: null, signedIn: null, install: 'https://developers.openai.com/codex', setupRequired: null }],+ pickProgram: async (id, words) => { asked.push([id, words]); return picked; },+ checkProgram: async () => check,+ usePaths: (paths) => used.push(paths),+ });+ assert.deepEqual(used, [{}], 'told at once what was kept');+ await r.refresh();+ assert.deepEqual(await r.locate('codex', { title: 'Choose the Codex program' }), { ok: false }, 'cancelled: nothing said, nothing kept');+ assert.deepEqual(asked, [['codex', { title: 'Choose the Codex program' }]]);+ picked = 'C:\\tools\\notes.txt';+ check = { ok: false, error: '', code: 'not-a-program' };+ assert.deepEqual(await r.locate('codex'), { ok: false, error: '', code: 'not-a-program' });+ assert.deepEqual(readChoices(dir).paths, {}, 'a program that does not start is not kept');+ picked = 'C:\\tools\\codex.exe';+ check = { ok: true, version: 'codex-cli 1.0.0' };+ assert.deepEqual(await r.locate('codex'), { ok: true });+ assert.deepEqual(readChoices(dir).paths, { codex: 'C:\\tools\\codex.exe' });+ assert.deepEqual(used.at(-1), { codex: 'C:\\tools\\codex.exe' });+ assert.equal(r.list().find((a) => a.id === 'codex').chosen, 'C:\\tools\\codex.exe');+ assert.deepEqual(await r.useAutomatic('codex'), { ok: true });+ assert.deepEqual(readChoices(dir).paths, {});+ assert.deepEqual(used.at(-1), {});+ assert.deepEqual(await r.locate('byok'), { ok: false, error: 'No agent byok' }, 'only the person\'s own programs');+});++test('a kept path for something that is not one of the agents is dropped', () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));+ writeFileSync(join(dir, 'agents.json'), JSON.stringify({ paths: { codex: '/opt/codex', byok: '/x', nope: '/y', claude: 3 } }));+ assert.deepEqual(readChoices(dir).paths, { codex: '/opt/codex' });+});++test('disconnecting only stops OpenFilm using an agent; connecting again uses the account signed in then', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));+ let account = { method: 'claude.ai', email: '[email protected]' };+ const closed = [];+ const r = roster(dir, undefined, {+ localAgents: async () => [{ id: 'claude', cli: { path: '/bin/claude' }, signedIn: true, account, install: null, setupRequired: null }],+ closeSessions: (id) => closed.push(id),+ });+ await r.refresh();+ assert.deepEqual(r.list().find((a) => a.id === 'claude').account, { method: 'claude.ai', email: '[email protected]' });+ r.disconnect('claude');+ assert.equal(r.list().find((a) => a.id === 'claude').status, 'off');+ /* the account switched in Claude Code itself */+ account = { method: 'claude.ai', email: '[email protected]' };+ assert.deepEqual(await r.connect('claude'), { ok: true });+ const claude = r.list().find((a) => a.id === 'claude');+ assert.equal(claude.status, 'ready');+ assert.equal(claude.account.email, '[email protected]');+ assert.deepEqual(closed, ['claude', 'claude'], 'its sessions closed both times: none goes on with the old account');+});diff --git a/apps/desktop/src/agent-usage.mjs b/apps/desktop/src/agent-usage.mjsnew file mode 100644index 0000000..9ea2d47--- /dev/null+++ b/apps/desktop/src/agent-usage.mjs@@ -0,0 +1,119 @@+/**+ * How much of its plan Codex has left, for Settings → Agents, so the person does not open Codex to see it: asked of+ * its app server (`codex app-server`, JSON-RPC over stdin/stdout) on the account signed in on the computer,+ * `account/read` (the account's email and plan) and `account/rateLimits/read` (each window's share used, how long it+ * is, when it resets).+ *+ * Not Claude Code's: its /usage (and the SDK's data behind it) said 0% of a Team account the Claude app showed half+ * used, so it is not shown rather than shown wrong.+ *+ * Nothing here reads or keeps a key or a token: Codex answers about its own sign-in. Asked at most once a minute (the+ * answer is kept), and never for longer than a short wait.+ *+ * Reads no Electron module, so `node --test` can use the readers.+ */+import { spawn } from 'node:child_process';+import { PATH_SEP, childEnvironment, loginShellEnvironment, loginShellVariables } from './environment.mjs';+import { resolveAgentCli } from './agents.mjs';++/**+ * @typedef {{ kind: 'five_hour' | 'seven_day' | 'window', minutes: number | null,+ * usedPercent: number, resetsAt: number | null }} UsageWindow+ * a window of the plan: its share used (0–100), how long it is (minutes; null when the program does not say), when+ * it resets (ms since 1970)+ * @typedef {{ plan: string | null, windows: UsageWindow[], account?: { email?: string, plan?: string } }} AgentUsage+ */++const KEPT_MS = 60_000;+const WAIT_MS = 20_000;+/** @type {Map<string, { at: number, usage: Promise<AgentUsage | null> }>} */+const kept = new Map();++const clampPercent = (/** @type {unknown} */ n) => (typeof n === 'number' && Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : null);+const text = (/** @type {unknown} */ v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);++/**+ * Codex's account and rate limits, as windows: the primary and secondary ones of its usage, each as long as it says.+ * @param {any} account `account/read`'s result @param {any} limits `account/rateLimits/read`'s result+ * @returns {AgentUsage | null}+ */+export function readCodexUsage(account, limits) {+ const snapshot = limits?.rateLimitsByLimitId?.codex ?? limits?.rateLimits ?? null;+ /** @type {UsageWindow[]} */+ const windows = [];+ for (const w of [snapshot?.primary, snapshot?.secondary]) {+ const used = clampPercent(w?.usedPercent);+ if (used == null) continue;+ const minutes = typeof w.windowDurationMins === 'number' ? w.windowDurationMins : null;+ const kind = minutes === 300 ? 'five_hour' : minutes === 10_080 ? 'seven_day' : 'window';+ windows.push({ kind, minutes, usedPercent: used, resetsAt: typeof w.resetsAt === 'number' ? w.resetsAt * 1000 : null });+ }+ const acc = account?.account;+ const plan = text(snapshot?.planType) ?? text(acc?.planType) ?? null;+ const who = acc?.type === 'chatgpt' ? { ...(text(acc.email) ? { email: text(acc.email) } : {}), ...(text(acc.planType) ? { plan: text(acc.planType) } : {}) } : null;+ if (!windows.length && !who) return null;+ return { plan, windows, ...(who ? { account: who } : {}) };+}++/** A promise that gives up (null) after `ms`. @template T @param {Promise<T>} p @param {number} ms */+const within = (p, ms) => Promise.race([p, new Promise((done) => setTimeout(() => done(null), ms).unref?.())]);++/** Codex's usage, on OpenFilm's sign-in: its app server asked twice, then stopped. @param {string} cli */+async function codexUsage(cli) {+ const shell = await loginShellVariables();+ const child = spawn(cli, ['app-server'], { env: childEnvironment({ shell }), stdio: ['pipe', 'pipe', 'ignore'] });+ child.once('error', () => {});+ /** @type {Map<number, (message: any) => void>} */+ const waiting = new Map();+ let buffer = '';+ child.stdout.on('data', (data) => {+ buffer += data;+ for (let i = buffer.indexOf('\n'); i >= 0; i = buffer.indexOf('\n')) {+ const line = buffer.slice(0, i);+ buffer = buffer.slice(i + 1);+ try {+ const message = JSON.parse(line);+ if (message.id != null) waiting.get(message.id)?.(message);+ } catch { /* not ours */ }+ }+ });+ let next = 0;+ const call = (/** @type {string} */ method, /** @type {unknown} */ params) => new Promise((done) => {+ const id = ++next;+ waiting.set(id, (m) => { waiting.delete(id); done(m.result ?? null); });+ child.stdin.write(`${JSON.stringify({ id, method, ...(params === undefined ? {} : { params }) })}\n`);+ });+ try {+ return await within((async () => {+ await call('initialize', { clientInfo: { name: 'openfilm-desktop', title: 'OpenFilm', version: '1' }, capabilities: null });+ child.stdin.write(`${JSON.stringify({ method: 'initialized' })}\n`);+ const account = await call('account/read', { refreshToken: false });+ const limits = await call('account/rateLimits/read', undefined);+ return readCodexUsage(account, limits);+ })(), WAIT_MS);+ } finally {+ child.kill();+ }+}++/**+ * What is left of an agent's plan (Codex's), or null: another agent, not installed, signed out, or a program that does+ * not say. Kept for a minute; `fresh` asks again.+ * @param {string} id @param {{ fresh?: boolean }} [opts] @returns {Promise<AgentUsage | null>}+ */+export function agentUsage(id, { fresh = false } = {}) {+ if (id !== 'codex') return Promise.resolve(null);+ const hit = kept.get(id);+ if (hit && !fresh && Date.now() - hit.at < KEPT_MS) return hit.usage;+ const usage = (async () => {+ const pathDirs = (await loginShellEnvironment()).PATH.split(PATH_SEP);+ const cli = resolveAgentCli(id, { pathDirs });+ if (!cli) return null;+ return codexUsage(cli.path);+ })().catch(() => null);+ kept.set(id, { at: Date.now(), usage });+ return usage;+}++/** Forget what was kept (a sign-in changed: another account's usage). @param {string} id */+export function forgetAgentUsage(id) { kept.delete(id); }diff --git a/apps/desktop/src/agent-usage.test.mjs b/apps/desktop/src/agent-usage.test.mjsnew file mode 100644index 0000000..609dd87--- /dev/null+++ b/apps/desktop/src/agent-usage.test.mjs@@ -0,0 +1,27 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { agentUsage, readCodexUsage } from './agent-usage.mjs';++test('Claude Code\'s usage is not asked: its own report is wrong for Team accounts', async () => {+ assert.equal(await agentUsage('claude'), null);+ assert.equal(await agentUsage('gemini'), null);+});++test('Codex\'s rate limits as windows, each as long as it says; its account\'s email and plan', () => {+ const account = { account: { type: 'chatgpt', email: '[email protected]', planType: 'plus' }, requiresOpenaiAuth: true };+ const limits = {+ rateLimits: { primary: { usedPercent: 99, windowDurationMins: 300, resetsAt: 1 } },+ rateLimitsByLimitId: { codex: { planType: 'plus', primary: { usedPercent: 3, windowDurationMins: 10_080, resetsAt: 1_792_329_499 }, secondary: { usedPercent: 40, windowDurationMins: 60, resetsAt: null } } },+ };+ assert.deepEqual(readCodexUsage(account, limits), {+ plan: 'plus',+ windows: [+ { kind: 'seven_day', minutes: 10_080, usedPercent: 3, resetsAt: 1_792_329_499_000 },+ { kind: 'window', minutes: 60, usedPercent: 40, resetsAt: null },+ ],+ account: { email: '[email protected]', plan: 'plus' },+ });+ assert.deepEqual(readCodexUsage({ account: { type: 'apiKey' } }, null), null, 'an API key: nothing to show');+ assert.deepEqual(readCodexUsage(null, { rateLimits: { primary: { usedPercent: 10, windowDurationMins: 300, resetsAt: null } } }),+ { plan: null, windows: [{ kind: 'five_hour', minutes: 300, usedPercent: 10, resetsAt: null }] });+});diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjsindex cfa2386..fa88ac6 100644--- a/apps/desktop/src/agents.mjs+++ b/apps/desktop/src/agents.mjs@@ -15,6 +15,9 @@* else hold or pass on their credentials. The app runs their own program, sign-in is its own (`claude auth login`,* `codex login`, in Terminal, or a command window on Windows), and the app never sees a token.*+ * Each uses the account signed in on the computer, as it is: one switched in the agent (or its maker's app) is the+ * one used once the agent is connected again here.+ ** The agent works the way it would in a terminal: in the project's folder, with the `openfilm` command on its PATH* (this app's copy, so its Studio is the one in the window) and a few lines saying where it is (INSTRUCTIONS).*@@ -22,14 +25,14 @@*/import { execFile, spawn } from 'node:child_process';import { existsSync, mkdtempSync, readFileSync } from 'node:fs';-import { homedir, tmpdir } from 'node:os';+import { arch, homedir, release, tmpdir } from 'node:os';import { createRequire } from 'node:module';-import { dirname, join } from 'node:path';+import { dirname, isAbsolute, join } from 'node:path';import { Readable, Writable } from 'node:stream';import { fileURLToPath } from 'node:url';import * as acp from '@agentclientprotocol/sdk';-import { PATH_SEP, childEnvironment, loginShellEnvironment } from './environment.mjs';-import { detectAgentInstallation } from './agent-installation.mjs';+import { PATH_SEP, childEnvironment, lastPathSource, loginShellEnvironment, loginShellVariables } from './environment.mjs';+import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, detectAgentInstallation, searchReport } from './agent-installation.mjs';import { nodeBinary } from './node-runtime.mjs';import { outOfBalance } from './pi-config.mjs';@@ -81,9 +84,11 @@ export const INSTRUCTIONS = `You are working inside OpenFilm, a desktop app forthe video editor, showing the project in your working directory; it updates live as you save files.The project is an OpenFilm film: pages with window.film, cut together by film.html. Before you change anything, run-\`openfilm\` with no arguments and read the manual it prints; follow it. Studio is already open on this project: you-never need \`openfilm open\` and never open a browser. Run \`openfilm look\` after each change to see what you made.-Render the MP4 only when the person asks for it; they can also export from Studio.+\`openfilm\` with no arguments and read the manual it prints; follow it. Use the \`openfilm\` command on your PATH (this+app's own, on the Studio beside you), not \`npx openfilm\`, whatever a skill says. Studio is already open on this+project: you never need \`openfilm open\` and never open Studio in a browser. Run \`openfilm look\` after each change+to see what you made. Render the MP4 only when the person asks for it; they can also export from Studio. Reply in the+language the person writes in.When the person mentions something in Studio, they may name a clip, a page or a moment (as seconds); find it infilm.html and the project's files.@@ -111,26 +116,181 @@ export function ownAgentPrompt() {return `${prompt}\n\n## Where you are\n\n${INSTRUCTIONS}\n\n${WEB_INSTRUCTIONS}\n\n<manual>\n${manual}\n</manual>`;}-/** The person's program for this agent, on their login shell's PATH or inside the maker's app. */+/**+ * The person's own `developer_instructions` in Codex's config.toml (top level), or null: the app's instructions go to+ * Codex in the same place, which would otherwise take the place of theirs, so theirs come first. Read for the basic+ * and literal strings TOML has, on one line or several; anything else (a profile's, a key it cannot read) is left.+ */+export function codexDeveloperInstructions(toml) {+ const top = String(toml ?? '').split(/^\s*\[/m)[0];+ const m = /^[ \t]*developer_instructions[ \t]*=[ \t]*("""|'''|"|')/m.exec(top);+ if (!m) return null;+ const quote = m[1];+ const rest = top.slice(m.index + m[0].length);+ /* a basic string on one line ends at its first quote not escaped; the others at their closing quotes */+ const end = quote === '"' ? (/^(?:[^"\\\n]|\\.)*"/.exec(rest)?.[0].length ?? 0) - 1 : rest.indexOf(quote);+ if (end < 0) return null;+ let text = rest.slice(0, end);+ if (quote.length === 3) text = text.replace(/^\r?\n/, '');+ if (quote.startsWith('"')) {+ text = text.replace(/\\(?:u([0-9a-fA-F]{4})|(.))/g, (_, hex, c) => (hex ? String.fromCharCode(parseInt(hex, 16))+ : ({ n: '\n', t: '\t', r: '\r', '"': '"', '\\': '\\' })[c] ?? c));+ }+ return text.trim() || null;+}++/** Codex's config.toml: in CODEX_HOME when the person's shell sets it, else ~/.codex. */+function codexConfigText(shell) {+ try { return readFileSync(join(shell.CODEX_HOME || join(homedir(), '.codex'), 'config.toml'), 'utf8'); } catch { return ''; }+}++/** The programs the person chose for their agents (Settings → Agents → Locate, agent-roster.mjs), by agent. */+let chosenPaths = {};+export function setChosenPaths(paths) {+ chosenPaths = Object.fromEntries(Object.entries(paths ?? {}).filter(([id, path]) => isAgentId(id) && typeof path === 'string' && path));+}++const windows = process.platform === 'win32';+/** what the slower search found last (Windows): npm's global folder, Codex inside a Microsoft Store app */+let slowFound = { npmPrefix: null, storeCodex: null };+let slowCache = null;+const SLOW_FOR_MS = 10 * 60_000;+/* an OpenAI app from the Microsoft Store (ChatGPT, Codex) that carries Codex: where its codex.exe is */+const STORE_CODEX = "Get-AppxPackage -Name 'OpenAI.*' | ForEach-Object { Get-ChildItem -LiteralPath $_.InstallLocation -Recurse -Depth 5 -Filter codex.exe -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName }";++/**+ * Windows only, and only when an agent is not found the quick way: where npm puts global commands (a prefix of the+ * person's own that is not on their PATH), and Codex inside an OpenAI app from the Microsoft Store. Asked again after+ * ten minutes, or at once with `fresh`.+ */+function windowsSlowSearch({ fresh = false } = {}) {+ if (!windows) return Promise.resolve(slowFound);+ if (slowCache && !fresh && Date.now() - slowCache.at < SLOW_FOR_MS) return slowCache.value;+ const value = (async () => {+ const env = childEnvironment({ shell: await loginShellEnvironment() });+ const [npm, store] = await Promise.all([+ run(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', 'npm prefix -g'], 15_000, { env }),+ run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', STORE_CODEX], 20_000, { env }),+ ]);+ const prefix = npm.ok ? npm.stdout.trim().split(/\r?\n/).pop()?.trim() : null;+ const exe = store.ok ? store.stdout.split(/\r?\n/).map((l) => l.trim()).find((l) => /codex\.exe$/i.test(l)) : null;+ slowFound = { npmPrefix: prefix && isAbsolute(prefix) ? prefix : null, storeCodex: exe && isAbsolute(exe) ? exe : null };+ return slowFound;+ })().catch(() => slowFound);+ slowCache = { at: Date.now(), value };+ return value;+}++/** Where this agent was looked for, beyond the PATH. */+const searchDirs = () => [...HOME_BIN_CANDIDATES(), ...(slowFound.npmPrefix ? [slowFound.npmPrefix] : [])];++/**+ * The person's program for this agent: the one they chose; else on their login shell's PATH (on Windows, the PATH the+ * registry has now), in the folders installers use, or inside the maker's app. `source`: chosen · path · app.+ */export function resolveAgentCli(id, { pathDirs = [] } = {}) {if (!isAgentId(id)) return null;- const found = detectAgentInstallation(id, { env: { ...process.env, PATH: pathDirs.join(PATH_SEP) } }).cli;- return found ? { path: found } : null;+ const found = detectAgentInstallation(id, {+ env: { PATH: pathDirs.join(PATH_SEP) },+ pathDirs: searchDirs(),+ chosen: chosenPaths[id] ?? null,+ others: id === 'codex' && slowFound.storeCodex ? [slowFound.storeCodex] : [],+ });+ return found.cli ? { path: found.cli, source: found.source } : null;}-function run(cmd, args, timeoutMs = 10_000, { cwd, env } = {}) {+function run(cmd, args, timeoutMs = 10_000, { cwd, env, options } = {}) {return new Promise((resolve) => {- execFile(cmd, args, { timeout: timeoutMs, encoding: 'utf8', ...(cwd ? { cwd } : {}), ...(env ? { env } : {}) }, (error, stdout, stderr) => {- resolve({ ok: !error, out: `${stdout ?? ''}\n${stderr ?? ''}`, stdout: stdout ?? '' });- });+ try {+ execFile(cmd, args, { timeout: timeoutMs, encoding: 'utf8', windowsHide: true, ...options, ...(cwd ? { cwd } : {}), ...(env ? { env } : {}) }, (error, stdout, stderr) => {+ resolve({ ok: !error, out: `${stdout ?? ''}\n${stderr ?? ''}`, stdout: stdout ?? '' });+ });+ } catch (e) {+ /* a program Windows cannot start that way (EINVAL) */+ resolve({ ok: false, out: e instanceof Error ? e.message : String(e), stdout: '' });+ }});}-/** How to start a program found for an agent: itself, or a script with the app's own Node (an npm install on Windows). */+/* one word of a cmd.exe command line: quoted when it has to be */+const winArg = (a) => (/^[\w.:\\/=+@-]+$/.test(a) ? a : `"${String(a).replace(/"/g, '""')}"`);++/** The app's own Node running a script, through as-node.mjs: what the script starts does not run Electron as Node. */+const AS_NODE = fileURLToPath(new URL('./as-node.mjs', import.meta.url));++/**+ * How to start a program found for an agent: itself, a script with the app's own Node (an npm install on Windows), or+ * a `.cmd` shim whose target could not be told, through cmd.exe. `options` go to spawn.+ */function starting(cliPath, args) {- return /\.(?:c|m)?js$/i.test(cliPath)- ? { cmd: nodeBinary(), args: [cliPath, ...args], env: { ELECTRON_RUN_AS_NODE: '1' } }- : { cmd: cliPath, args, env: {} };+ if (/\.(?:c|m)?js$/i.test(cliPath)) return { cmd: nodeBinary(), args: [AS_NODE, cliPath, ...args], env: { ELECTRON_RUN_AS_NODE: '1' }, options: {} };+ if (windows && /\.(?:cmd|bat)$/i.test(cliPath)) {+ return { cmd: process.env.ComSpec || 'cmd.exe', args: ['/d', '/s', '/c', `"${[cliPath, ...args].map(winArg).join(' ')}"`], env: {}, options: { windowsVerbatimArguments: true } };+ }+ return { cmd: cliPath, args, env: {}, options: {} };+}++/**+ * A program the person chose for an agent, tried: it has to start and answer `--version`. `{ ok, version }`, or why+ * not: `code` 'not-a-program' (nothing there this computer can start) or 'did-not-start' (with what it said).+ */+export async function checkAgentProgram(id, path) {+ const spec = AGENTS[id];+ if (!spec) return { ok: false, error: `No agent ${id}`, code: 'not-a-program' };+ const cli = chosenProgram(path, { names: AGENT_PROGRAMS[id]?.names ?? [id] });+ if (!cli) return { ok: false, error: 'That is not a program this computer can start.', code: 'not-a-program' };+ const how = starting(cli, ['--version']);+ const r = await run(how.cmd, how.args, 20_000, { env: childEnvironment({ shell: await loginShellVariables(), extra: how.env }), options: how.options });+ if (!r.ok) return { ok: false, error: r.out.trim().slice(0, 400), code: 'did-not-start' };+ return { ok: true, path: cli, version: r.stdout.trim().split(/\r?\n/)[0] ?? '' };+}++/** Where in WSL (Linux on Windows) one of these programs is, or null: there the app cannot use it. */+async function inWsl(names) {+ const wsl = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'wsl.exe');+ if (!existsSync(wsl)) return null;+ const r = await run(wsl, ['-e', 'bash', '-lic', names.map((n) => `command -v ${n}`).join(' || ')], 15_000);+ return r.stdout.replace(/\0/g, '').split(/\r?\n/).map((l) => l.trim()).find((l) => /^\/\S+$/.test(l)) ?? null;+}++/**+ * Why an agent is or is not found, for the person to read or send with an issue: the PATH and where it came from, the+ * program chosen, every folder searched, each file there with the agent's name and what it runs; on Windows, npm's+ * global folder and whether it is in WSL instead. `hint`, when it is not found: chosen-missing (the program chosen is+ * gone) · wsl (only in WSL) · unusable (files with its name, none that starts) · none.+ */+export async function diagnoseAgent(id, { appVersion = '' } = {}) {+ const spec = AGENTS[id];+ if (!spec) return null;+ const shell = await loginShellEnvironment({ maxAgeMs: 0 });+ const slow = await windowsSlowSearch({ fresh: true });+ const pathDirs = shell.PATH.split(PATH_SEP);+ const found = resolveAgentCli(id, { pathDirs });+ const names = AGENT_PROGRAMS[id]?.names ?? [id];+ const report = searchReport(id, { env: { PATH: shell.PATH }, pathDirs: searchDirs() });+ const wsl = windows && !found ? await inWsl(names) : null;+ const chosen = chosenPaths[id] ?? null;+ const hint = found ? null : chosen ? 'chosen-missing' : wsl ? 'wsl' : report.files.length ? 'unusable' : 'none';+ const lines = [+ `OpenFilm ${appVersion}`.trim(),+ `Agent: ${spec.label} (${names.join(', ')})`,+ `System: ${process.platform} ${release()} ${arch()}`,+ `PATH from: ${lastPathSource() ?? 'unknown'}`,+ `Chosen: ${chosen ?? '(none)'}`,+ `Found: ${found ? `${found.path} (${found.source})` : '(not found)'}`,+ ...(windows ? [+ `npm global folder: ${slow.npmPrefix ?? '(unknown)'}`,+ ...(id === 'codex' ? [`Codex in a Store app: ${slow.storeCodex ?? '(none)'}`] : []),+ `In WSL: ${found ? '(not checked)' : wsl ?? '(no)'}`,+ ] : []),+ '',+ `Files named ${names.join(', ')}:`,+ ...(report.files.length ? report.files.map((f) => ` ${f.file}${f.runs && f.runs !== f.file ? ` -> ${f.runs}` : ''}${f.usable ? '' : ' (cannot be started)'}`) : [' (none)']),+ '',+ `Folders searched (${report.searched.length}):`,+ ...report.searched.map((d) => ` ${d}`),+ ];+ return { found: found?.path ?? null, program: names[0], hint, text: lines.join('\n') };}/**@@ -138,20 +298,45 @@ function starting(cliPath, args) {* no command for it is asked by opening a session (acpSignedIn).*/export async function agentSignedIn(id, cliPath) {+ return (await agentStatus(id, cliPath)).signedIn;+}++/**+ * Signed in, and as whom, asked of the program: `account` is what it says of its sign-in (Claude Code: email,+ * organization, plan; Codex: how, ChatGPT or an API key), never a key or a token.+ * @returns {Promise<{ signedIn: boolean | null, account: AgentAccount | null }>}+ */+export async function agentStatus(id, cliPath) {const spec = AGENTS[id];- if (!spec || !cliPath) return null;- if (!spec.auth) return acpSignedIn(id);+ if (!spec || !cliPath) return { signedIn: null, account: null };+ if (!spec.auth) return { signedIn: await acpSignedIn(id), account: null };const how = starting(cliPath, spec.auth);- const r = await run(how.cmd, how.args, 10_000, { env: childEnvironment({ shell: await loginShellEnvironment(), extra: how.env }) });+ const r = await run(how.cmd, how.args, 10_000, { env: childEnvironment({ shell: await loginShellVariables(), extra: how.env }), options: how.options });+ return readAgentStatus(id, r.stdout, r.out);+}++/**+ * @typedef {{ method: 'claude.ai' | 'console' | 'api-key' | 'chatgpt' | 'other', email?: string, org?: string, plan?: string }} AgentAccount+ * What a sign-in status says: Claude Code's JSON, Codex's words. @param {string} id @param {string} stdout @param {string} out+ * @returns {{ signedIn: boolean | null, account: AgentAccount | null }}+ */+export function readAgentStatus(id, stdout, out) {if (id === 'claude') {try {- const status = JSON.parse(r.stdout);- return typeof status.loggedIn === 'boolean' ? status.loggedIn : null;+ const s = JSON.parse(stdout);+ if (typeof s.loggedIn !== 'boolean') return { signedIn: null, account: null };+ if (!s.loggedIn) return { signedIn: false, account: null };+ const method = s.authMethod === 'claude.ai' ? 'claude.ai' : /api.?key/i.test(String(s.authMethod)) ? 'api-key' : s.authMethod === 'console' ? 'console' : 'other';+ const text = (/** @type {unknown} */ v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);+ return { signedIn: true, account: { method, email: text(s.email), org: text(s.orgName), plan: text(s.subscriptionType) } };} catch { /* not JSON: read the words */ }}- if (/\bnot logged in\b/i.test(r.out)) return false;- if (/\blogged in\b/i.test(r.out)) return true;- return null;+ if (/\bnot logged in\b/i.test(out)) return { signedIn: false, account: null };+ if (/\blogged in\b/i.test(out)) {+ const method = /chatgpt/i.test(out) ? 'chatgpt' : /api key/i.test(out) ? 'api-key' : 'other';+ return { signedIn: true, account: { method } };+ }+ return { signedIn: null, account: null };}/** what a session opened only to ask found, for a while: the roster asks again every few seconds */@@ -203,14 +388,14 @@ export async function openAgentSignIn(id) {const spec = AGENTS[id];const pathDirs = (await loginShellEnvironment()).PATH.split(PATH_SEP);const cli = spec ? resolveAgentCli(id, { pathDirs }) : null;- if (!spec || !cli) return { ok: false, error: `${spec?.label ?? id} is not installed on this Mac.` };+ if (!spec || !cli) return { ok: false, error: `${spec?.label ?? id} is not installed on this computer.` };asked.delete(id);if (process.platform === 'win32') {- /* a command window of its own, left open so its sign-in can be read and answered */- const how = starting(cli.path, spec.login);+ /* a command window of its own, left open so its sign-in can be read and answered (it runs a shim itself) */+ const how = /\.(?:cmd|bat)$/i.test(cli.path) ? { cmd: cli.path, args: spec.login, env: {} } : starting(cli.path, spec.login);try {spawn('cmd.exe', ['/d', '/c', 'start', `${spec.label} sign-in`, 'cmd.exe', '/k', how.cmd, ...how.args], {- detached: true, stdio: 'ignore', windowsHide: false, env: childEnvironment({ shell: await loginShellEnvironment(), extra: how.env }),+ detached: true, stdio: 'ignore', windowsHide: false, env: childEnvironment({ shell: await loginShellVariables(), extra: how.env }),}).unref();return { ok: true };} catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }@@ -224,7 +409,13 @@ export async function openAgentSignIn(id) {* here but has not downloaded Claude Code yet (opening its Code tab does).*/export async function listAgents() {- const pathDirs = (await loginShellEnvironment()).PATH.split(PATH_SEP);+ /* looked at as the person comes back from installing one: a PATH from a few seconds ago at most */+ const pathDirs = (await loginShellEnvironment({ maxAgeMs: 10_000 })).PATH.split(PATH_SEP);+ /* one not found the quick way: the slower search (Windows), then all of them again; waited for a few seconds at+ most, what it finds later is there on the next look */+ if (windows && Object.keys(AGENTS).some((id) => !resolveAgentCli(id, { pathDirs }))) {+ await Promise.race([windowsSlowSearch(), new Promise((done) => setTimeout(done, 3000).unref?.())]);+ }return Promise.all(Object.entries(AGENTS).map(async ([id, spec]) => {const cli = resolveAgentCli(id, { pathDirs });const { install } = detectAgentInstallation(id);@@ -232,8 +423,9 @@ export async function listAgents() {return {id,label: spec.label,- cli: cli ? { path: cli.path, source: 'installed' } : null,- signedIn: cli ? await agentSignedIn(id, cli.path) : null,+ cli: cli ? { path: cli.path, source: cli.source } : null,+ chosen: chosenPaths[id] ?? null,+ ...(cli ? await agentStatus(id, cli.path) : { signedIn: null, account: null }),install,setupRequired: claudeApp ? 'code-tab' : null,};@@ -355,7 +547,7 @@ export function legacyOptions(session) {export class AgentSession {/*** `harness` (for 'byok'): agent-roster.mjs's `harness(id)`, Pi's folder, its service and its model.- * @param {{ agent: string, cwd: string, resume?: string | null, binDir?: string | null,+ * @param {{ agent: string, cwd: string, resume?: string | null, binDir?: string | null, fallbackDir?: string | null,* harness?: any,* env?: Record<string, string>,* onUpdate?: (update: any) => void, onPermission?: (params: any) => Promise<string | null>,@@ -375,14 +567,18 @@ export class AgentSession {this.replaying = false;}- /** Start the adapter, shake hands, open (or resume) the session. */+ /**+ * Start the adapter, shake hands, open (or resume) the session. The agent gets all the person's login shell sets+ * (their keys, gateways, tokens), as in their terminal, and the app's `openfilm` first on its PATH; the app's ffmpeg+ * (`fallbackDir`) last, for a computer that has none of its own.+ */async start() {- const shell = await loginShellEnvironment();+ const shell = await loginShellVariables({ staleOk: true });const harness = this.opts.harness ?? null;const cli = harness ? null : resolveAgentCli(this.opts.agent, { pathDirs: shell.PATH.split(PATH_SEP) });- if (!harness && !cli) throw Object.assign(new Error(`${this.spec.label} is not installed on this Mac.`), { code: 'not-installed' });+ if (!harness && !cli) throw Object.assign(new Error(`${this.spec.label} is not installed on this computer.`), { code: 'not-installed' });const node = nodeRuntime();- const path = [this.opts.binDir, shell.PATH].filter(Boolean).join(PATH_SEP);+ const path = [this.opts.binDir, shell.PATH, this.opts.fallbackDir].filter(Boolean).join(PATH_SEP);const instructions = INSTRUCTIONS;/* the app's own agent: what Pi runs with (its whole system prompt is ours), and the web search of `openfilm get`(OPENFILM_GET_WEB lists it) */@@ -395,14 +591,17 @@ export class AgentSession {const native = cli && !this.spec.adapter ? starting(cli.path, this.spec.args) : null;const env = childEnvironment({ shell: { ...shell, PATH: path }, extra: { ...this.opts.env, ...(native ? native.env : node.env), ...(cli && this.spec.env ? this.spec.env(cli.path) : {}), ...own } });const claude = this.spec.adapter === AGENTS.claude.adapter;- if (this.spec.adapter === AGENTS.codex.adapter) env.CODEX_CONFIG = JSON.stringify({ developer_instructions: instructions });+ if (this.spec.adapter === AGENTS.codex.adapter) {+ const theirs = codexDeveloperInstructions(codexConfigText(shell));+ env.CODEX_CONFIG = JSON.stringify({ developer_instructions: theirs ? `${theirs}\n\n${instructions}` : instructions });+ }/* the others have no place for it: the session's first message carries it */this.instructions = harness || this.spec.systemPrompt ? null : instructions;const script = harness ? fileURLToPath(new URL('./pi-agent.mjs', import.meta.url)) : native ? null : adapterScript(this.spec.adapter);this.child = native- ? spawn(native.cmd, native.args, { cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })- : spawn(node.command, [script], { cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'] });+ ? spawn(native.cmd, native.args, { ...native.options, cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })+ : spawn(node.command, [...(node.env.ELECTRON_RUN_AS_NODE ? [AS_NODE] : []), script], { cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'] });this.child.stderr.on('data', (d) => { this.stderr = (this.stderr + String(d)).slice(-16_000); });this.child.once('exit', (code) => this.opts.onExit?.({ code, stderr: this.stderr }));this.child.once('error', () => {});@@ -471,6 +670,8 @@ export class AgentSession {configOptions: session.configOptions ?? (this.legacy ? legacyOptions(session) : null),/* what a prompt may carry besides text (pictures, for one): the agent says so as it shakes hands */promptCapabilities: caps.promptCapabilities ?? null,+ /* a message sent while it works joins the turn it is in (steer), as in its own chat */+ steering: init._meta?.steering?.supported === true,};return this.info;}@@ -497,6 +698,17 @@ export class AgentSession {return r.stopReason;}+ /**+ * A message sent while a turn runs, into that turn (ACP's steering extension, `_session/steering`): the agent reads+ * it at its next step, as when the person types while it works in its own chat. → 'injected' when it joined the+ * turn; anything else ('startedNewTurn', 'promptRequired', 'failed') when it did not.+ */+ async steer(blocks) {+ if (!this.sessionId || !this.info?.steering) return 'failed';+ const r = await this.conn.agent.request('_session/steering', { sessionId: this.sessionId, prompt: blocks }).catch(() => null);+ return typeof r?.outcome === 'string' ? r.outcome : 'failed';+ }+/** Stop this turn (it ends with stopReason 'cancelled'). */async cancel() {if (this.sessionId) await this.conn.agent.notify(acp.methods.agent.session.cancel, { sessionId: this.sessionId }).catch(() => {});diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjsindex 858f4f9..3eb5936 100644--- a/apps/desktop/src/agents.test.mjs+++ b/apps/desktop/src/agents.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { allowOption, legacyOptions } from './agents.mjs';+import { allowOption, codexDeveloperInstructions, legacyOptions, readAgentStatus } from './agents.mjs';test('an agent that asks: yes for good where it offers that, else yes this once; nothing to say yes with is null', () => {const options = [@@ -23,3 +23,26 @@ test("the older model and mode lists (Gemini CLI's) read as the config options tassert.deepEqual(options[0].options[1], { value: 'pro', name: 'Pro', description: 'slow' });assert.deepEqual(legacyOptions({}), []);});++test('whose sign-in it is, as each program says it, never a key', () => {+ const claude = JSON.stringify({ loggedIn: true, authMethod: 'claude.ai', email: '[email protected]', orgName: 'Studio', subscriptionType: 'max' });+ assert.deepEqual(readAgentStatus('claude', claude, claude), { signedIn: true, account: { method: 'claude.ai', email: '[email protected]', org: 'Studio', plan: 'max' } });+ const out = JSON.stringify({ loggedIn: false, authMethod: 'none' });+ assert.deepEqual(readAgentStatus('claude', out, out), { signedIn: false, account: null });+ assert.deepEqual(readAgentStatus('codex', 'Logged in using ChatGPT\n', 'Logged in using ChatGPT\n'), { signedIn: true, account: { method: 'chatgpt' } });+ const key = 'Logged in using an API key - sk-proj-***ABCD\n';+ const read = readAgentStatus('codex', key, key);+ assert.deepEqual(read, { signedIn: true, account: { method: 'api-key' } });+ assert.ok(!JSON.stringify(read).includes('sk-'), 'no part of a key');+ assert.deepEqual(readAgentStatus('codex', 'Not logged in\n', 'Not logged in\n'), { signedIn: false, account: null });+});++test("the person's own developer_instructions in Codex's config, read as TOML writes them; a profile's is not theirs at the top", () => {+ assert.equal(codexDeveloperInstructions('model = "gpt"\ndeveloper_instructions = "Be brief.\\nSay \\"why\\"."\n'), 'Be brief.\nSay "why".');+ assert.equal(codexDeveloperInstructions("developer_instructions = 'C:\\no\\escapes'"), 'C:\\no\\escapes');+ assert.equal(codexDeveloperInstructions('developer_instructions = """\nLine one.\nLine two.\n"""\n[profiles.x]\n'), 'Line one.\nLine two.');+ assert.equal(codexDeveloperInstructions("developer_instructions = '''\nAs is: \\n\n'''"), 'As is: \\n');+ assert.equal(codexDeveloperInstructions('[profiles.work]\ndeveloper_instructions = "not at the top"\n'), null);+ assert.equal(codexDeveloperInstructions('model = "gpt"\n'), null);+ assert.equal(codexDeveloperInstructions(''), null);+});diff --git a/apps/desktop/src/as-node.mjs b/apps/desktop/src/as-node.mjsnew file mode 100644index 0000000..4241eee--- /dev/null+++ b/apps/desktop/src/as-node.mjs@@ -0,0 +1,15 @@+/**+ * How the app runs a Node program of its own (an agent's adapter, the app's own agent) on Electron as Node: this file+ * first, then the program. ELECTRON_RUN_AS_NODE is what made Electron a Node; it is taken out of the environment before+ * the program starts, so what the program starts (the person's agent, and every command that agent runs) does not+ * have it. An Electron app the agent runs, or its tests, would start as Node too.+ *+ * electron as-node.mjs <program> [args…]+ */+import { pathToFileURL } from 'node:url';++delete process.env.ELECTRON_RUN_AS_NODE;+const program = process.argv[2];+/* the program sees itself as the script it is: argv[1] is its path, its own arguments follow */+process.argv.splice(1, 1);+await import(pathToFileURL(program).href);diff --git a/apps/desktop/src/chat-ipc.mjs b/apps/desktop/src/chat-ipc.mjsindex 00c5273..ca820fa 100644--- a/apps/desktop/src/chat-ipc.mjs+++ b/apps/desktop/src/chat-ipc.mjs@@ -4,17 +4,24 @@* desktop:chat:load { project } → { sessions, last, turns }* desktop:chat:sessions { project, sessions, last }* desktop:chat:turn { project, turn, items }- * desktop:chat:log { project, turnId } → { file, cut, size, events } | null+ * desktop:chat:log { project, turnId, unless? } → { file, cut, size, callsSize, events, calls } | { same } | null* desktop:chat:reveal { project, turnId? } the turn's log (or the logs folder) in the file manager* desktop:chat:ref-image { project, turnId, n, bytes } → { path } a reference's picture, kept for the agent- * desktop:prefs → { developer } and `desktop:prefs:set` { developer }; told on `desktop:prefs`+ * desktop:chat:unsaved { project, except? } → [{ turnId, events }] turns with a log and no saved record+ * desktop:chat:snapshot { project, turnId } the project's files as a turn starts (file-changes.mjs), kept here+ * desktop:chat:changes { project, turnId } → { files, cut } | null what the turn changed in them since+ * desktop:prefs → { developer, changes } and `desktop:prefs:set` either; told on `desktop:prefs`** `project` is a folder path, and only one Studio has as a project is read or written: the page cannot point the* app at any other folder.*/import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join, resolve } from 'node:path';-import { chatDir, loadChat, readLog, saveRefImage, saveSessions, saveTurn } from './chat-store.mjs';+import { chatDir, loadChat, readLog, saveRefImage, saveSessions, saveTurn, unsavedTurns } from './chat-store.mjs';+import { changes, snapshot } from './file-changes.mjs';++/** how many turns' snapshots are kept at once: one per running turn, and a few whose end was never asked about */+const SNAPSHOTS_MAX = 8;/*** @param {import('electron').IpcMain} ipcMain@@ -40,7 +47,28 @@ export function registerChatIpc(ipcMain, { trusted, projects, dataDir, reveal, thandle('desktop:chat:sessions', async ({ project: path, sessions, last }) => { saveSessions(await project(path), { sessions, last }); return { ok: true }; });handle('desktop:chat:turn', async ({ project: path, turn, items }) => { saveTurn(await project(path), { turn, items }); return { ok: true }; });handle('desktop:chat:ref-image', async ({ project: path, turnId, n, bytes }) => saveRefImage(await project(path), turnId, n, bytes));- handle('desktop:chat:log', async ({ project: path, turnId }) => readLog(await project(path), turnId));+ handle('desktop:chat:unsaved', async ({ project: path, except }) => unsavedTurns(await project(path), {+ except: Array.isArray(except) ? except.filter((id) => typeof id === 'string') : [],+ }));+ handle('desktop:chat:log', async ({ project: path, turnId, unless }) => readLog(await project(path), turnId, {+ unless: unless && Number.isFinite(unless.size) && Number.isFinite(unless.callsSize) ? unless : null,+ }));+ /* the files as each running turn found them, by the turn: compared, and let go, when the turn settles */+ const snapshots = new Map();+ handle('desktop:chat:snapshot', async ({ project: path, turnId }) => {+ const dir = await project(path);+ const taken = await snapshot(dir);+ snapshots.delete(turnId);+ snapshots.set(turnId, { dir, taken });+ while (snapshots.size > SNAPSHOTS_MAX) snapshots.delete(snapshots.keys().next().value);+ return { ok: true };+ });+ handle('desktop:chat:changes', async ({ project: path, turnId }) => {+ const dir = await project(path);+ const kept = snapshots.get(turnId);+ snapshots.delete(turnId);+ return kept && kept.dir === dir ? changes(dir, kept.taken) : null;+ });handle('desktop:chat:reveal', async ({ project: path, turnId }) => {const dir = await project(path);const found = typeof turnId === 'string' ? readLog(dir, turnId) : null;@@ -52,12 +80,17 @@ export function registerChatIpc(ipcMain, { trusted, projects, dataDir, reveal, t/* the app's own preferences: kept by the app, not by the page (whose storage is its address's) */const file = join(dataDir, 'preferences.json');+ /* `developer`: each turn's log (off unless turned on); `changes`: what each turn changed, under its reply (on) */const read = () => {- try { const raw = JSON.parse(readFileSync(file, 'utf8')); return { developer: raw.developer === true }; } catch { return { developer: false }; }+ try {+ const raw = JSON.parse(readFileSync(file, 'utf8'));+ return { developer: raw.developer === true, changes: raw.changes !== false };+ } catch { return { developer: false, changes: true }; }};handle('desktop:prefs', async () => read());handle('desktop:prefs:set', async (next) => {- const prefs = { ...read(), ...(typeof next.developer === 'boolean' ? { developer: next.developer } : {}) };+ const prefs = { ...read() };+ for (const key of ['developer', 'changes']) if (typeof next[key] === 'boolean') prefs[key] = next[key];if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true });writeFileSync(file, `${JSON.stringify(prefs, null, 2)}\n`);tell('desktop:prefs', prefs);diff --git a/apps/desktop/src/chat-store.mjs b/apps/desktop/src/chat-store.mjsindex 99309be..c629d8e 100644--- a/apps/desktop/src/chat-store.mjs+++ b/apps/desktop/src/chat-store.mjs@@ -99,18 +99,54 @@ export function saveRefImage(project, turnId, n, bytes) {return { path: `.film/refs/${name}` };}-/** A turn's events, as written: [{ t, kind, … }] (a broken line, from a crash mid-write, is left out). */-export function readLog(project, turnId) {+/**+ * A turn's events, as written: [{ t, kind, … }] (a broken line, from a crash mid-write, is left out). `unless`: the+ * sizes a reader already has (`size`, `callsSize` of an earlier read): when neither file has grown, `{ same: true }`+ * and nothing is read (a running turn's log is asked for again and again).+ */+export function readLog(project, turnId, { unless = null } = {}) {if (typeof turnId !== 'string' || !ID.test(turnId)) return null;const file = join(logsDir(project), `${fileOf(turnId)}.jsonl`);if (!existsSync(file)) return null;+ const model = join(logsDir(project), `${fileOf(turnId)}.model.jsonl`);+ const size = statSync(file).size;+ const callsSize = existsSync(model) ? statSync(model).size : 0;+ if (unless && unless.size === size && unless.callsSize === callsSize) return { same: true };let text = readFileSync(file, 'utf8');const cut = text.length > LOG_READ_MAX;if (cut) text = text.slice(text.length - LOG_READ_MAX).replace(/^[^\n]*\n/, '');const lines = (body) => body.split('\n').flatMap((line) => { try { return line ? [JSON.parse(line)] : []; } catch { return []; /* half a line */ } });- const model = join(logsDir(project), `${fileOf(turnId)}.model.jsonl`);const calls = existsSync(model) ? lines(readFileSync(model, 'utf8')) : [];- return { file, cut, size: statSync(file).size, events: lines(text), calls };+ return { file, cut, size, callsSize, events: lines(text), calls };+}++/** how many turns found only in the logs are read at once (the newest), and the most of each log that is read */+const UNSAVED_MAX = 20;++/**+ * The turns that have a log and no saved record (`.film/chat/turns`): ones the app closed on, or crashed in, before it+ * kept them. Each with its events, for the chat to make what it shows of it again; the newest first, at most+ * UNSAVED_MAX. `except`: turn ids not to read (running now).+ */+export function unsavedTurns(project, { except = [] } = {}) {+ let names = [];+ try { names = readdirSync(logsDir(project)).filter((n) => n.endsWith('.jsonl') && !n.endsWith('.model.jsonl')); } catch { return []; }+ const saved = new Set((() => { try { return readdirSync(join(chatDir(project), 'turns')); } catch { return []; } })());+ const skip = new Set(except.map(fileOf));+ const found = names+ .map((name) => name.slice(0, -'.jsonl'.length))+ .filter((base) => !saved.has(`${base}.json`) && !skip.has(base))+ .map((base) => ({ base, at: statSync(join(logsDir(project), `${base}.jsonl`)).mtimeMs }))+ .sort((a, b) => b.at - a.at)+ .slice(0, UNSAVED_MAX);+ const out = [];+ for (const { base } of found) {+ const events = readLog(project, base)?.events ?? [];+ const prompt = events.find((e) => e.kind === 'prompt');+ /* only a turn the chat started knows its own id and conversation (its `meta`) */+ if (prompt?.meta?.turnId && typeof prompt.meta.turnId === 'string') out.push({ turnId: prompt.meta.turnId, events });+ }+ return out;}/**diff --git a/apps/desktop/src/chat-store.test.mjs b/apps/desktop/src/chat-store.test.mjsindex dd951da..856108f 100644--- a/apps/desktop/src/chat-store.test.mjs+++ b/apps/desktop/src/chat-store.test.mjs@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { appendFileSync, mkdtempSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { chatDir, loadChat, logsDir, openLog, readLog, refsDir, saveRefImage, saveSessions, saveTurn } from './chat-store.mjs';+import { chatDir, loadChat, logsDir, openLog, readLog, refsDir, saveRefImage, saveSessions, saveTurn, unsavedTurns } from './chat-store.mjs';const project = () => mkdtempSync(join(tmpdir(), 'of-chat-'));const turn = (id, createdAt) => ({ turn: { id, createdAt, sessionId: 's1', prompt: id }, items: [{ kind: 'text', text: id }] });@@ -94,3 +94,30 @@ test('a reference\'s picture is kept as .film/refs/<turn>-<n>.jpg, and nothing bassert.throws(() => saveRefImage(dir, 'local:abc', 1, new Uint8Array([0x89, 0x50, 0x4e, 0x47])), /not a JPEG/);assert.throws(() => saveRefImage(dir, 'local:abc', 1, 'not bytes'), /not a picture/);});++test('a log not grown since the sizes a reader has is not read again', async () => {+ const dir = project();+ const log = openLog(dir, 't2');+ log.write('prompt', { text: 'hello' });+ await new Promise((done) => setTimeout(done, 50));+ const first = readLog(dir, 't2');+ assert.deepEqual(readLog(dir, 't2', { unless: { size: first.size, callsSize: first.callsSize } }), { same: true });+ log.write('done', { ok: true });+ log.end();+ await new Promise((done) => setTimeout(done, 50));+ assert.deepEqual(readLog(dir, 't2', { unless: { size: first.size, callsSize: first.callsSize } }).events.map((e) => e.kind), ['prompt', 'done']);+});++test('a turn with a log and no saved record is found with its events; a saved one, one running, one with no meta are not', async () => {+ const dir = project();+ const write = (id, meta) => { const log = openLog(dir, id); log.write('prompt', { text: 'hi', ...(meta ? { meta } : {}) }); log.write('update', { update: { sessionUpdate: 'agent_message_chunk' } }); log.end(); };+ write('local:lost1', { turnId: 'local:lost1', sessionId: 's1' });+ write('local:kept1', { turnId: 'local:kept1', sessionId: 's1' });+ write('local:busy1', { turnId: 'local:busy1', sessionId: 's1' });+ write('local:bare1', null);+ saveTurn(dir, turn('local:kept1', '2026-10-12T00:00:00Z'));+ await new Promise((done) => setTimeout(done, 50));+ const found = unsavedTurns(dir, { except: ['local:busy1'] });+ assert.deepEqual(found.map((f) => f.turnId), ['local:lost1']);+ assert.deepEqual(found[0].events.map((e) => e.kind), ['prompt', 'update']);+});diff --git a/apps/desktop/src/environment.mjs b/apps/desktop/src/environment.mjsindex 8cb0649..15fedff 100644--- a/apps/desktop/src/environment.mjs+++ b/apps/desktop/src/environment.mjs@@ -6,15 +6,19 @@* ANTHROPIC_BASE_URL and the like, which an agent started here would wrongly inherit. Opened from the Dock, it has* only PATH=/usr/bin:/bin:/usr/sbin:/sbin, where neither Homebrew's ffmpeg nor the person's `claude` can be found.* Both get the same answer: the OS identity variables, plus the PATH (and proxies, and where the agents keep their- * sign-in) of the person's login shell. On Windows there is no login shell: a program started from the Start menu- * has the person's own PATH already, so that is kept (with the Windows system variables a program needs). Reads no- * Electron module, so `node --test` can use it.+ * sign-in) of the person's login shell. On Windows there is no login shell, and the PATH a program inherits from+ * Explorer can be old (what an installer added since the person signed in is missing): the PATH is read where Windows+ * keeps it now, the registry (with the Windows system variables a program needs). Either is read again while the app+ * runs, so an agent installed meanwhile is found without restarting it. Reads no Electron module, so `node --test`+ * can use it.*/import { spawn } from 'node:child_process';import { homedir, userInfo } from 'node:os';import { isAbsolute, join } from 'node:path';-const OS_KEYS = ['HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'TZ'];+/* what the system gives every program the person starts, a terminal included: SSH_AUTH_SOCK (their keys' agent, for git+ over ssh) comes from it, not from the shell's files */+const OS_KEYS = ['HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'TZ', 'SSH_AUTH_SOCK'];/** what a Windows program needs to find its system, its profile and its temporary folder */const WIN_KEYS = ['SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT', 'TEMP', 'TMP', 'USERPROFILE', 'USERNAME', 'USERDOMAIN','HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA', 'ProgramData', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432',@@ -25,6 +29,15 @@ const BASE_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';const PROXY_KEYS = ['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'NO_PROXY', 'https_proxy', 'http_proxy', 'all_proxy', 'no_proxy'];/** where each agent keeps its sign-in; only meaningful when the person set it in their shell */const AGENT_HOME_KEYS = ['CLAUDE_CONFIG_DIR', 'CODEX_HOME'];+/**+ * What a shell sets for itself and its terminal, not for the programs it starts as the person's settings: left out of+ * what the agents are given. Anything else the person's shell exports is theirs (keys, gateways, an MCP server's token,+ * certificates), and their agent has it here as it has it in their terminal.+ */+const SESSION_KEYS = new Set(['PWD', 'OLDPWD', 'SHLVL', '_', 'TERM', 'TERM_PROGRAM', 'TERM_PROGRAM_VERSION', 'TERM_SESSION_ID',+ 'COLORTERM', 'ITERM_SESSION_ID', 'ITERM_PROFILE', 'LC_TERMINAL', 'LC_TERMINAL_VERSION', 'TMUX', 'TMUX_PANE', 'STY', 'WINDOWID',+ 'SECURITYSESSIONID', 'XPC_SERVICE_NAME', 'XPC_FLAGS', 'PS1', 'PS2', 'PROMPT']);+const SESSION_PREFIXES = ['__CF', 'ELECTRON_', 'VSCODE_', 'OPENFILM_'];const ENV_MARKER = '__OPENFILM_LOGIN_ENV__';function accountShell() {@@ -88,6 +101,17 @@ export function shellSubset(dump, home = homedir()) {return env;}+/** All a login shell's environment the person set (SESSION_KEYS left out), with PATH as shellSubset has it. */+export function shellVariables(dump, home = homedir()) {+ const env = {};+ for (const [key, value] of Object.entries(dump ?? {})) {+ if (typeof value !== 'string' || SESSION_KEYS.has(key) || SESSION_PREFIXES.some((p) => key.startsWith(p))) continue;+ env[key] = value;+ }+ env.PATH = mergePath(dump?.PATH, home);+ return env;+}+/** Run the login shell once, with a clean environment; null when it fails or takes too long. */function captureLoginShell(shell, env, timeoutMs) {return new Promise((resolve) => {@@ -111,17 +135,117 @@ function captureLoginShell(shell, env, timeoutMs) {});}-let loginShellCache = null;-/** The login shell's subset (`shellSubset`), asked once per process. Never rejects: on failure, the fallback PATH. */-export function loginShellEnvironment({ source = process.env, timeoutMs = 5000 } = {}) {- /* Windows has no login shell: a program started from the Start menu already has the person's PATH */- if (windows) return Promise.resolve({ PATH: mergePath(pathOf(source), homedir()) });- loginShellCache ??= (async () => {- const base = osEnvironment(source);- const dump = base.SHELL ? await captureLoginShell(base.SHELL, { ...base, PATH: BASE_PATH }, timeoutMs) : null;- return shellSubset(parseEnvDump(dump), base.HOME);- })().catch(() => ({ PATH: mergePath('', homedir()) }));- return loginShellCache;+/** `reg query <key>` output, read: each value's name and its text (REG_SZ and REG_EXPAND_SZ only). */+export function parseRegQuery(text) {+ const values = {};+ for (const line of String(text ?? '').split(/\r?\n/)) {+ const m = /^\s{2,}(\S(?:.*?\S)?)\s{2,}(REG_SZ|REG_EXPAND_SZ)\s{2,}(.*)$/.exec(line);+ if (m) values[m[1]] = m[3].trim();+ }+ return values;+}++/** `%NAME%` replaced by the variable's value, whatever its case; one not set is left as it is. */+export function expandWindowsVars(text, vars) {+ const lower = new Map(Object.entries(vars ?? {}).map(([k, v]) => [k.toLowerCase(), v]));+ return String(text ?? '').replace(/%([^%;]+)%/g, (all, name) => (typeof lower.get(name.toLowerCase()) === 'string' ? lower.get(name.toLowerCase()) : all));+}++const valueOf = (vars, name) => Object.entries(vars ?? {}).find(([k]) => k.toLowerCase() === name.toLowerCase())?.[1];++/**+ * The PATH Windows gives a program started now: the system's, then the person's (as the registry has them, their+ * variables expanded), then whatever else the app's own PATH has. Each folder once, whatever its case.+ */+export function windowsFreshPath({ machine = {}, user = {}, source = process.env } = {}) {+ const vars = { ...source, ...machine, ...user };+ const dirs = [valueOf(machine, 'Path'), valueOf(user, 'Path'), pathOf(source)]+ .flatMap((p) => expandWindowsVars(p ?? '', vars).split(';'))+ .map((d) => d.trim().replace(/^"(.*)"$/, '$1'))+ .filter(Boolean);+ const seen = new Map();+ for (const d of dirs) if (!seen.has(d.toLowerCase())) seen.set(d.toLowerCase(), d);+ return [...seen.values()].join(';');+}++const REG_MACHINE = 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment';+const REG_USER = 'HKCU\\Environment';++function regQuery(key, timeoutMs) {+ return new Promise((resolve) => {+ const reg = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'reg.exe');+ execFile(reg, ['query', key], { timeout: timeoutMs, encoding: 'utf8', windowsHide: true }, (error, stdout) => resolve(error ? null : parseRegQuery(stdout)));+ });+}++/** Where the PATH last came from: 'registry' or 'process' (Windows), 'login shell' or 'fallback' (elsewhere). */+let pathSource = null;+export const lastPathSource = () => pathSource;++/**+ * An environment read again once it is older than `forMs` (or than a caller's `maxAgeMs`, when that is less), so a+ * program installed while the app runs is found without restarting it. A read already going is shared; one that+ * fails (null) keeps the last good one, or `fallback()` when there is none.+ * @param {() => Promise<Record<string, string> | null>} read+ * @param {{ forMs: number, fallback: () => Record<string, string>, now?: () => number }} o+ */+export function environmentCache(read, { forMs, fallback, now = Date.now }) {+ let at = -Infinity;+ let value = null;+ let reading = false;+ return ({ maxAgeMs = forMs, staleOk = false } = {}) => {+ if (value && (reading || now() - at <= Math.min(maxAgeMs, forMs))) return value;+ const last = value;+ at = now();+ reading = true;+ value = Promise.resolve().then(read).catch(() => null)+ .then(async (env) => env ?? (last ? await last : fallback()))+ .finally(() => { reading = false; });+ /* `staleOk`: an old one now, the new one for whoever asks next (an agent starts without waiting on the shell) */+ return staleOk && last ? last : value;+ };+}++/** The registry's environment (Windows): null when neither part of it could be read. */+async function readRegistry(source, timeoutMs) {+ const [machine, user] = await Promise.all([regQuery(REG_MACHINE, timeoutMs), regQuery(REG_USER, timeoutMs)]);+ if (!machine && !user) return null;+ pathSource = 'registry';+ /* the person's own variables as they are now, over the system's */+ return shellVariables({ ...machine, ...user, PATH: windowsFreshPath({ machine: machine ?? {}, user: user ?? {}, source }) }, homedir());+}++/** The login shell's variables (shellVariables): null when it gave no PATH (it failed, or took too long). */+async function readLoginShell(source, timeoutMs) {+ const base = osEnvironment(source);+ const parsed = parseEnvDump(base.SHELL ? await captureLoginShell(base.SHELL, { ...base, PATH: BASE_PATH }, timeoutMs) : null);+ if (!parsed.PATH) return null;+ pathSource = 'login shell';+ return shellVariables(parsed, base.HOME);+}++let shellCache = null;+/**+ * Everything the person's login shell sets (`shellVariables`); on Windows, the registry's. Read again after a minute+ * (Windows: a few seconds), or sooner for a caller that asks (`maxAgeMs`: the agents' list, which is looked at again+ * as the person comes back from installing one; `staleOk`, the last one read while a new one is read for next time).+ * Never rejects: on failure, the last one read, else the fallback PATH.+ * What the agents are given, so they run with what they have in the person's terminal.+ */+export function loginShellVariables({ source = process.env, timeoutMs = 5000, maxAgeMs, staleOk = false } = {}) {+ shellCache ??= environmentCache(() => (windows ? readRegistry(source, timeoutMs) : readLoginShell(source, timeoutMs)), {+ forMs: windows ? 5000 : 60_000,+ fallback: () => {+ pathSource = windows ? 'process' : 'fallback';+ return { PATH: mergePath(windows ? pathOf(source) : '', homedir()) };+ },+ });+ return shellCache({ ...(maxAgeMs === undefined ? {} : { maxAgeMs }), staleOk });+}++/** The part of it Studio and the app's other programs are given (`shellSubset`): PATH, proxies, locale. */+export async function loginShellEnvironment(options = {}) {+ return shellSubset(await loginShellVariables(options));}/** What scripts/start.mjs passes on to Electron besides the OS identity: this app's own switches. */diff --git a/apps/desktop/src/environment.test.mjs b/apps/desktop/src/environment.test.mjsnew file mode 100644index 0000000..383f5ea--- /dev/null+++ b/apps/desktop/src/environment.test.mjs@@ -0,0 +1,93 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { environmentCache, expandWindowsVars, parseRegQuery, shellSubset, shellVariables, windowsFreshPath } from './environment.mjs';++const PROFILE = ['C:', 'Users', 'someone'].join('\\');++const USER = `\r+HKEY_CURRENT_USER\\Environment\r+ Path REG_EXPAND_SZ %USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps;%NVM_HOME%;%NVM_SYMLINK%;C:\\Users\\someone\\AppData\\Roaming\\npm\r+ NVM_HOME REG_SZ C:\\Users\\someone\\AppData\\Local\\nvm\r+ NVM_SYMLINK REG_SZ C:\\nvm4w\\nodejs\r+ OneDrive Consumer REG_SZ C:\\Users\\someone\\OneDrive\r+ TEMP REG_EXPAND_SZ %USERPROFILE%\\AppData\\Local\\Temp\r+ Count REG_DWORD 0x1\r+`;++test('reg query output is read: text values by name, other kinds left out', () => {+ const values = parseRegQuery(USER);+ assert.equal(values.NVM_SYMLINK, 'C:\\nvm4w\\nodejs');+ assert.equal(values['OneDrive Consumer'], 'C:\\Users\\someone\\OneDrive');+ assert.match(values.Path, /^%USERPROFILE%\\AppData/);+ assert.equal(values.Count, undefined);+ assert.deepEqual(parseRegQuery(''), {});+});++test('%VARIABLES% are expanded whatever their case; one not set stays as it is', () => {+ assert.equal(expandWindowsVars('%userprofile%\\bin;%NOPE%\\x', { USERPROFILE: PROFILE }), `${PROFILE}\\bin;%NOPE%\\x`);+});++test("the PATH a program started now gets: the system's, the person's (with their own variables), then the app's own", () => {+ const machine = { Path: '%SystemRoot%\\system32;C:\\Program Files\\nodejs\\', SystemRoot: 'C:\\Windows' };+ const user = parseRegQuery(USER);+ const source = { Path: 'C:\\Windows\\System32;C:\\Old\\stale', USERPROFILE: PROFILE };+ assert.equal(windowsFreshPath({ machine, user, source }), [+ 'C:\\Windows\\system32', 'C:\\Program Files\\nodejs\\',+ 'C:\\Users\\someone\\AppData\\Local\\Microsoft\\WindowsApps', 'C:\\Users\\someone\\AppData\\Local\\nvm', 'C:\\nvm4w\\nodejs', 'C:\\Users\\someone\\AppData\\Roaming\\npm',+ 'C:\\Old\\stale',+ ].join(';'));+});++test('the environment is read again once it is old, sooner when asked; a failed read keeps the last good one', async () => {+ let clock = 0;+ const reads = [];+ let next = { PATH: '/a' };+ const cache = environmentCache(async () => { reads.push(clock); return next; }, { forMs: 60_000, fallback: () => ({ PATH: '/fallback' }), now: () => clock });+ assert.deepEqual(await cache(), { PATH: '/a' });+ next = { PATH: '/a:/b' };+ clock = 30_000;+ assert.deepEqual(await cache(), { PATH: '/a' }, 'still fresh');+ assert.deepEqual(await cache({ maxAgeMs: 10_000 }), { PATH: '/a:/b' }, 'the agents\' list wants it newer');+ clock = 100_000;+ assert.deepEqual(await cache({ maxAgeMs: 120_000 }), { PATH: '/a:/b' }, 'a caller cannot make it older than its own limit');+ assert.equal(reads.length, 3);+ next = null;+ clock = 200_000;+ assert.deepEqual(await cache(), { PATH: '/a:/b' }, 'the shell failed: the last one read');+ const empty = environmentCache(async () => null, { forMs: 1000, fallback: () => ({ PATH: '/fallback' }), now: () => 0 });+ assert.deepEqual(await empty(), { PATH: '/fallback' });+});++test('reads going on at once are one read', async () => {+ let count = 0;+ let clock = 0;+ const cache = environmentCache(() => new Promise((done) => { count++; setTimeout(() => done({ PATH: '/x' }), 5); }), { forMs: 1000, fallback: () => ({}), now: () => clock });+ const first = cache();+ clock = 5000;+ const second = cache({ maxAgeMs: 0 });+ assert.equal(first, second);+ await Promise.all([first, second]);+ assert.equal(count, 1);+});++test('an old one can be taken at once, the new one read for whoever asks next', async () => {+ let clock = 0;+ let next = { PATH: '/a' };+ const cache = environmentCache(async () => next, { forMs: 60_000, fallback: () => ({}), now: () => clock });+ await cache();+ next = { PATH: '/b' };+ clock = 100_000;+ assert.deepEqual(await cache({ staleOk: true }), { PATH: '/a' });+ assert.deepEqual(await cache(), { PATH: '/b' });+});++test("the agents get all the person's shell sets, but what the shell and its terminal set for themselves; Studio a part", () => {+ const dump = {+ PATH: '/opt/homebrew/bin:/usr/bin', ANTHROPIC_BASE_URL: 'https://gateway.example', GITHUB_TOKEN: 't', NODE_EXTRA_CA_CERTS: '/ca.pem',+ HTTPS_PROXY: 'http://proxy', PWD: '/x', SHLVL: '2', _: '/usr/bin/env', TERM_PROGRAM: 'iTerm.app', ELECTRON_RUN_AS_NODE: '1', OPENFILM_HOME: '/o',+ };+ const all = shellVariables(dump, '/home/me/');+ assert.deepEqual(Object.keys(all).sort(), ['ANTHROPIC_BASE_URL', 'GITHUB_TOKEN', 'HTTPS_PROXY', 'NODE_EXTRA_CA_CERTS', 'PATH']);+ assert.ok(all.PATH.startsWith('/opt/homebrew/bin:/usr/bin'));+ assert.deepEqual(Object.keys(shellSubset(all, '/home/me/')).sort(), ['HTTPS_PROXY', 'PATH']);+});diff --git a/apps/desktop/src/file-changes.mjs b/apps/desktop/src/file-changes.mjsnew file mode 100644index 0000000..db18862--- /dev/null+++ b/apps/desktop/src/file-changes.mjs@@ -0,0 +1,126 @@+/**+ * What a turn changed in the project's files, as a coding agent's app shows it: each file added, removed or changed,+ * with its lines added and removed and the changed lines themselves. The folder is read as the turn starts and again+ * as it settles, so it is the same for any agent and counts whatever wrote the files meanwhile.+ *+ * Text files (by their extension, up to TEXT_MAX) are kept whole at the start and compared line by line at the end.+ * Any other file (media, a large file) is compared by its size and time only, and says no lines. Studio's own folder+ * (.film), hidden folders and node_modules are not read.+ *+ * Reads no Electron module, so `node --test` can use it.+ */+import { readdir, readFile, stat } from 'node:fs/promises';+import { join, relative, sep } from 'node:path';+import { structuredPatch } from 'diff';++const TEXT = /\.(html?|css|[cm]?js|jsx|tsx?|json|md|txt|srt|vtt|svg|xml|ya?ml|toml|py|sh|csv)$/i;+const SKIP = new Set(['node_modules']);+/** a text file larger than this is compared as any other file */+const TEXT_MAX = 1024 * 1024;+/** past these the reading stops: what was read is still compared, and the list says it is cut */+const FILES_MAX = 5000;+const KEEP_MAX = 48 * 1024 * 1024;+const DEPTH_MAX = 8;+/** how many changed lines are kept for each file, and for the whole turn */+const LINES_MAX = 400;+const TURN_LINES_MAX = 2000;+/** a diff that takes longer than this gives up: the file says it changed, with no lines */+const DIFF_MS = 1500;++/**+ * @typedef {{ size: number, mtimeMs: number, text?: string }} Seen+ * @typedef {{ files: Map<string, Seen>, cut: boolean }} Snapshot+ * @typedef {{ oldStart: number, oldLines: number, newStart: number, newLines: number, lines: string[] }} Hunk+ * @typedef {{ path: string, change: 'added' | 'removed' | 'changed', added?: number, removed?: number,+ * hunks?: Hunk[], cut?: boolean }} FileChange+ */++/** The project's files now: each one's size and time, and a text file's text. */+export async function snapshot(root) {+ /** @type {Map<string, Seen>} */+ const files = new Map();+ let kept = 0;+ let cut = false;+ const walk = async (dir, depth) => {+ let entries;+ try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; }+ entries.sort((a, b) => a.name.localeCompare(b.name));+ for (const entry of entries) {+ if (files.size >= FILES_MAX) { cut = true; return; }+ if (entry.name.startsWith('.') || SKIP.has(entry.name)) continue;+ const abs = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (depth < DEPTH_MAX) await walk(abs, depth + 1);+ else cut = true;+ continue;+ }+ if (!entry.isFile()) continue;+ let info;+ try { info = await stat(abs); } catch { continue; }+ /** @type {Seen} */+ const seen = { size: info.size, mtimeMs: info.mtimeMs };+ if (TEXT.test(entry.name) && info.size <= TEXT_MAX && kept + info.size <= KEEP_MAX) {+ try { seen.text = await readFile(abs, 'utf8'); kept += info.size; } catch { /* gone meanwhile */ }+ }+ files.set(relative(root, abs).split(sep).join('/'), seen);+ }+ };+ await walk(root, 0);+ return { files, cut };+}++/** A text's lines that changed, in hunks with three lines around each, or null when the diff gave up. */+function hunksOf(path, before, after) {+ const patch = structuredPatch(path, path, before, after, undefined, undefined, { context: 3, timeout: DIFF_MS });+ return patch ? patch.hunks.map(({ oldStart, oldLines, newStart, newLines, lines }) => ({ oldStart, oldLines, newStart, newLines, lines })) : null;+}++/** Keeps the first `max` lines of hunks, the rest dropped: → [the hunks kept, whether any were dropped]. */+function clip(hunks, max) {+ const out = [];+ let left = max;+ for (const hunk of hunks) {+ if (left <= 0) return [out, true];+ if (hunk.lines.length <= left) { out.push(hunk); left -= hunk.lines.length; continue; }+ out.push({ ...hunk, lines: hunk.lines.slice(0, left) });+ return [out, true];+ }+ return [out, false];+}++/**+ * What changed between a snapshot and the folder now: the files added, removed and changed, in path order (an+ * empty list: nothing changed). `cut`: the folder was too large to read whole.+ *+ * @param {string} root+ * @param {Snapshot} before+ * @returns {Promise<{ files: FileChange[], cut: boolean }>}+ */+export async function changes(root, before) {+ const after = await snapshot(root);+ const paths = [...new Set([...before.files.keys(), ...after.files.keys()])].sort();+ /** @type {FileChange[]} */+ const out = [];+ let lines = TURN_LINES_MAX;+ for (const path of paths) {+ const was = before.files.get(path);+ const now = after.files.get(path);+ if (was && now && was.size === now.size && was.mtimeMs === now.mtimeMs) continue;+ if (was?.text != null && now?.text != null && was.text === now.text) continue;+ const change = !was ? 'added' : !now ? 'removed' : 'changed';+ /* lines only when both ends are text (or one end is no file at all) */+ const from = was ? was.text : '';+ const to = now ? now.text : '';+ if (from == null || to == null) { out.push({ path, change }); continue; }+ const hunks = hunksOf(path, from, to);+ if (!hunks) { out.push({ path, change }); continue; }+ let added = 0;+ let removed = 0;+ for (const hunk of hunks) for (const line of hunk.lines) { if (line[0] === '+') added += 1; else if (line[0] === '-') removed += 1; }+ if (!added && !removed && change === 'changed') continue;+ const [kept, dropped] = clip(hunks, Math.min(LINES_MAX, lines));+ lines -= kept.reduce((n, hunk) => n + hunk.lines.length, 0);+ out.push({ path, change, added, removed, hunks: kept, ...(dropped ? { cut: true } : {}) });+ }+ return { files: out, cut: before.cut || after.cut };+}diff --git a/apps/desktop/src/file-changes.test.mjs b/apps/desktop/src/file-changes.test.mjsnew file mode 100644index 0000000..5f61b1d--- /dev/null+++ b/apps/desktop/src/file-changes.test.mjs@@ -0,0 +1,83 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { changes, snapshot } from './file-changes.mjs';+import { readFileChanges } from '../chat/src/lib/file-changes.ts';++const project = () => mkdtempSync(join(tmpdir(), 'openfilm-file-changes-'));++test('nothing written: no changes', async () => {+ const dir = project();+ try {+ writeFileSync(join(dir, 'film.html'), '<div>\n</div>\n');+ const before = await snapshot(dir);+ assert.deepEqual(await changes(dir, before), { files: [], cut: false });+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++test('a text file added, changed and removed: each with its lines, in path order', async () => {+ const dir = project();+ try {+ writeFileSync(join(dir, 'film.html'), 'a\nb\nc\n');+ writeFileSync(join(dir, 'old.md'), 'one\ntwo\n');+ const before = await snapshot(dir);+ writeFileSync(join(dir, 'film.html'), 'a\nB\nc\nd\n');+ mkdirSync(join(dir, 'pages'));+ writeFileSync(join(dir, 'pages', 'title.html'), '<h1>Hi</h1>\n');+ rmSync(join(dir, 'old.md'));+ const { files } = await changes(dir, before);+ assert.deepEqual(files.map((f) => [f.path, f.change, f.added, f.removed]), [+ ['film.html', 'changed', 2, 1],+ ['old.md', 'removed', 0, 2],+ ['pages/title.html', 'added', 1, 0],+ ]);+ assert.deepEqual(files[0].hunks[0].lines, [' a', '-b', '+B', ' c', '+d']);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++test('a file that is not text says it changed, with no lines; a text file touched but the same is no change', async () => {+ const dir = project();+ try {+ writeFileSync(join(dir, 'voice.mp3'), Buffer.from([1, 2, 3]));+ writeFileSync(join(dir, 'film.html'), 'same\n');+ const before = await snapshot(dir);+ writeFileSync(join(dir, 'voice.mp3'), Buffer.from([1, 2, 3, 4]));+ writeFileSync(join(dir, 'music.mp3'), Buffer.from([9]));+ writeFileSync(join(dir, 'film.html'), 'same\n');+ utimesSync(join(dir, 'film.html'), new Date(), new Date(Date.now() + 5000));+ const { files } = await changes(dir, before);+ assert.deepEqual(files, [{ path: 'music.mp3', change: 'added' }, { path: 'voice.mp3', change: 'changed' }]);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++test('Studio\'s own folder, hidden folders and node_modules are not read', async () => {+ const dir = project();+ try {+ const before = await snapshot(dir);+ for (const folder of ['.film', '.git', 'node_modules']) {+ mkdirSync(join(dir, folder));+ writeFileSync(join(dir, folder, 'x.json'), '{}\n');+ }+ assert.deepEqual((await changes(dir, before)).files, []);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++test('a long change keeps only its first lines, and says so', async () => {+ const dir = project();+ try {+ const before = await snapshot(dir);+ writeFileSync(join(dir, 'long.txt'), Array.from({ length: 1000 }, (_, i) => `line ${i}`).join('\n'));+ const [file] = (await changes(dir, before)).files;+ assert.equal(file.added, 1000);+ assert.equal(file.cut, true);+ assert.equal(file.hunks.reduce((n, h) => n + h.lines.length, 0), 400);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++test('a saved turn\'s file changes are read back only as changes', () => {+ assert.equal(readFileChanges(undefined), null);+ assert.equal(readFileChanges([]), null);+ assert.deepEqual(readFileChanges([{ path: 'a.html', change: 'added' }, { path: 'b', change: 'odd' }, null]), [{ path: 'a.html', change: 'added' }]);+});diff --git a/apps/desktop/src/film-changes.test.mjs b/apps/desktop/src/film-changes.test.mjsdeleted file mode 100644index 74bb4dc..0000000--- a/apps/desktop/src/film-changes.test.mjs+++ /dev/null@@ -1,79 +0,0 @@-import { test } from 'node:test';-import assert from 'node:assert/strict';-import { clipPillKind, diffFilms, readFilmChanges } from '../chat/src/lib/film-changes.ts';--const stage = { w: 1920, h: 1080 };-const film = (...tracks) => ({ stage, tracks: tracks.map((clips) => ({ clips })) });--const title = { src: 'mg/title.html', id: 's3', at: 13.6, box: { x: 0, y: 0, w: 1920, h: 1080 } };-const talk = { src: 'assets/video/talk.mp4', id: 'talk', at: 0, time: [2, 10], speed: 1 };-const vo = { src: 'assets/audio/vo/01.m4a', id: 'vo1', at: 1 };-/* what each change says, its film.html lines aside (those have a test of their own) */-const facts = (changes) => changes.map(({ before, after, ...rest }) => rest);--test('the same film: nothing changed', () => {- assert.deepEqual(facts(diffFilms(film([title, talk], [vo]), film([title, talk], [vo]))), []);-});--test('clips added and removed, by id, in the film\'s order', () => {- const logo = { src: 'mg/logo.html', id: 'logo', at: 20 };- assert.deepEqual(facts(diffFilms(film([title, talk], [vo]), film([logo, title], [vo]))), [- { id: 'logo', change: 'added', src: 'mg/logo.html' },- { id: 'talk', change: 'removed', src: 'assets/video/talk.mp4' },- ]);-});--test('a moved clip says where from and where to; a trim, a look, a box, a file and overrides are each named', () => {- const after = film(- [{ ...title, at: 13, style: 'filter: blur(2px)', overrides: [{ at: 'h1', text: 'Hi' }] }, { ...talk, time: [3, 10], box: { x: 10, y: 0 } }],- [{ ...vo, src: 'assets/audio/vo/01-b.m4a' }],- );- assert.deepEqual(facts(diffFilms(film([title, talk], [vo]), after)), [- { id: 's3', change: 'changed', src: 'mg/title.html', aspects: ['at', 'look', 'overrides'], at: [13.6, 13] },- { id: 'talk', change: 'changed', src: 'assets/video/talk.mp4', aspects: ['time', 'box'] },- { id: 'vo1', change: 'changed', src: 'assets/audio/vo/01-b.m4a', aspects: ['src'] },- ]);-});--test('a clip moved to another track, a new speed, a volume, an attribute', () => {- const after = film([title], [{ ...talk, speed: 1.5, volume: 0.5 }, { ...vo, attrs: { title: 'Line one' } }]);- assert.deepEqual(facts(diffFilms(film([title, talk], [vo]), after)), [- { id: 'talk', change: 'changed', src: 'assets/video/talk.mp4', aspects: ['speed', 'track', 'volume'], speed: [1, 1.5], track: [0, 1] },- { id: 'vo1', change: 'changed', src: 'assets/audio/vo/01.m4a', aspects: ['other'] },- ]);-});--test('an unset place is the film\'s start and an unset speed is 1, as film.html reads them', () => {- const before = film([{ src: 'mg/a.html', id: 'a' }, { src: 'assets/video/b.mp4', id: 'b', speed: 1 }]);- const after = film([{ src: 'mg/a.html', id: 'a', at: 0 }, { src: 'assets/video/b.mp4', id: 'b' }]);- assert.deepEqual(facts(diffFilms(before, after)), []);-});--test('each clip\'s line in film.html before the turn and after it', () => {- const logo = { src: 'mg/logo.html', id: 'logo', at: 20 };- assert.deepEqual(diffFilms(film([title], [vo]), film([{ ...title, at: 13 }, logo])).map(({ id, before, after }) => ({ id, before, after })), [- { id: 's3', before: '<iframe id="s3" src="mg/title.html" at="13.6" style="left: 0px; top: 0px; width: 1920px; height: 1080px"></iframe>',- after: '<iframe id="s3" src="mg/title.html" at="13" style="left: 0px; top: 0px; width: 1920px; height: 1080px"></iframe>' },- { id: 'logo', before: undefined, after: '<iframe id="logo" src="mg/logo.html" at="20"></iframe>' },- { id: 'vo1', before: '<audio id="vo1" src="assets/audio/vo/01.m4a" at="1"></audio>', after: undefined },- ]);-});--test('a saved turn\'s changes are read back only as changes', () => {- assert.equal(readFilmChanges(undefined), null);- assert.equal(readFilmChanges([]), null);- assert.equal(readFilmChanges('x'), null);- assert.deepEqual(readFilmChanges([{ id: 'a', change: 'added', src: 'mg/a.html' }, { id: 'b', change: 'odd', src: 'x' }, null]), [- { id: 'a', change: 'added', src: 'mg/a.html' },- ]);-});--test('a clip\'s pill kind follows its file, as the timeline colors it', () => {- assert.equal(clipPillKind('mg/title.html'), 'clipMg');- assert.equal(clipPillKind('assets/video/talk.mp4'), 'clipVideo');- assert.equal(clipPillKind('assets/image/logo.png'), 'clipVideo');- assert.equal(clipPillKind('assets/audio/vo/01.m4a'), 'clipVoice');- assert.equal(clipPillKind('assets/audio/sfx/whoosh.mp3'), 'clipSfx');- assert.equal(clipPillKind('assets/audio/music/bed.mp3'), 'clipMusic');- assert.equal(clipPillKind('assets/video/talk.mp4', true), 'clipVoice');-});diff --git a/apps/desktop/src/flavor.mjs b/apps/desktop/src/flavor.mjsindex c0216bc..0abb656 100644--- a/apps/desktop/src/flavor.mjs+++ b/apps/desktop/src/flavor.mjs@@ -3,6 +3,9 @@* one run from this repository never shares a window, a lock or a Studio with the installed one:** · release — the packaged app. Its Studio is the machine's Studio (~/.openfilm), the one `openfilm open` finds.+ * · preview — a packaged app built with `release --preview`, "OpenFilm Preview", to try a build in: its own data+ * folder, Studio home, port and projects, so it never meets an installed OpenFilm (its package says so:+ * `openfilmFlavor`).* · dev — `pnpm --filter @openfilm/desktop start`: this repository's code, with its own Studio home and its own* folder for new projects.* · bench — `node bench/run.mjs`: this repository's code, everything (data, Studio home, projects) in the throwaway@@ -10,13 +13,19 @@** Reads no Electron module, so `node --test` can use it.*/+import { readFileSync } from 'node:fs';import { homedir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';const packaged = Boolean(process.versions.electron) && !process.defaultApp;export const FLAVORS = Object.freeze({release: { productName: 'OpenFilm', bundleId: 'dev.openfilm.desktop', studioPort: 4747, studioHome: null, library: null },+ preview: {+ productName: 'OpenFilm Preview', bundleId: 'dev.openfilm.desktop.preview', studioPort: 4777,+ studioHome: join(homedir(), '.openfilm-preview'), library: join(homedir(), 'Movies', 'OpenFilm Preview', 'Projects'),+ },dev: {productName: 'OpenFilm Dev', bundleId: 'dev.openfilm.desktop.dev', studioPort: 4757,studioHome: join(homedir(), '.openfilm-dev'), library: join(homedir(), 'Movies', 'OpenFilm Dev', 'Projects'),@@ -29,8 +38,15 @@ const BENCH = Object.freeze({studioHome: join(benchDir, 'home'), library: join(benchDir, 'projects'), userData: join(benchDir, 'data'),});-export function flavorName(env = process.env, isPackaged = packaged) {- if (isPackaged) return 'release';+/** What the app's package says it was built as (`release --preview` writes `openfilmFlavor`). */+function builtFlavor() {+ try {+ return JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8')).openfilmFlavor ?? null;+ } catch { return null; }+}++export function flavorName(env = process.env, isPackaged = packaged, built = isPackaged ? builtFlavor() : null) {+ if (isPackaged) return built === 'preview' ? 'preview' : 'release';if (env.OPENFILM_DESKTOP_FLAVOR === 'dev') return 'dev';if (env.OPENFILM_DESKTOP_FLAVOR === 'bench' && env.OPENFILM_BENCH_DIR) return 'bench';return 'release';diff --git a/apps/desktop/src/flavor.test.mjs b/apps/desktop/src/flavor.test.mjsnew file mode 100644index 0000000..cc20e18--- /dev/null+++ b/apps/desktop/src/flavor.test.mjs@@ -0,0 +1,23 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { FLAVORS, flavorName } from './flavor.mjs';++test('which app this is: packaged, the release unless built as the preview; from source, dev when asked', () => {+ assert.equal(flavorName({}, true, null), 'release');+ assert.equal(flavorName({}, true, 'preview'), 'preview');+ assert.equal(flavorName({ OPENFILM_DESKTOP_FLAVOR: 'dev' }, true, null), 'release', 'a packaged app is never dev');+ assert.equal(flavorName({ OPENFILM_DESKTOP_FLAVOR: 'dev' }, false), 'dev');+ assert.equal(flavorName({}, false), 'release');+});++test('the preview shares nothing with an installed OpenFilm or the dev app', () => {+ const { release, preview, dev } = FLAVORS;+ for (const other of [release, dev]) {+ assert.notEqual(preview.productName, other.productName);+ assert.notEqual(preview.bundleId, other.bundleId);+ assert.notEqual(preview.studioPort, other.studioPort);+ assert.notEqual(preview.studioHome, other.studioHome);+ assert.notEqual(preview.library, other.library);+ }+ assert.ok(preview.studioHome, 'its own Studio home, not the machine\'s ~/.openfilm');+});diff --git a/apps/desktop/src/folder-dialog.mjs b/apps/desktop/src/folder-dialog.mjsindex 2521a56..d59ffec 100644--- a/apps/desktop/src/folder-dialog.mjs+++ b/apps/desktop/src/folder-dialog.mjs@@ -22,3 +22,24 @@ export function folderDialogOptions(options) {properties: ['openDirectory', 'createDirectory'],};}++/**+ * The system's file dialog for the program of one of the person's agents (Settings → Agents → Locate), with Studio's+ * own words. On Windows only programs and the shims installers leave are offered; on a Mac an app can be chosen too+ * (Codex.app: the Codex inside it is used).+ * @param {unknown} options+ * @param {string} [platform]+ * @returns {import('electron').OpenDialogOptions}+ */+export function programDialogOptions(options, platform = process.platform) {+ const o = options && typeof options === 'object' ? /** @type {Record<string, unknown>} */ (options) : {};+ const text = (/** @type {unknown} */ v) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, 120) : null);+ const title = text(o.title) ?? 'Choose the program';+ return {+ title,+ message: title,+ buttonLabel: text(o.button) ?? 'Choose',+ ...(platform === 'win32' ? { filters: [{ name: 'Programs', extensions: ['exe', 'cmd', 'bat', 'ps1', 'js'] }, { name: 'All files', extensions: ['*'] }] } : {}),+ properties: ['openFile', 'showHiddenFiles'],+ };+}diff --git a/apps/desktop/src/folder-dialog.test.mjs b/apps/desktop/src/folder-dialog.test.mjsindex 9ef31ab..a855967 100644--- a/apps/desktop/src/folder-dialog.test.mjs+++ b/apps/desktop/src/folder-dialog.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { folderDialogOptions } from './folder-dialog.mjs';+import { folderDialogOptions, programDialogOptions } from './folder-dialog.mjs';test('with no options the dialog opens a project', () => {const o = folderDialogOptions(undefined);@@ -24,3 +24,12 @@ test('a starting folder that is not a full path, and text that is not text, areassert.equal(o.buttonLabel, 'Open');assert.equal(o.defaultPath, undefined);});++test("an agent's program: Studio's words; on Windows only programs and shims are offered", () => {+ const win = programDialogOptions({ title: 'Choose the Codex program', button: 'Use this' }, 'win32');+ assert.equal(win.title, 'Choose the Codex program');+ assert.equal(win.buttonLabel, 'Use this');+ assert.deepEqual(win.filters?.[0].extensions, ['exe', 'cmd', 'bat', 'ps1', 'js']);+ assert.ok(win.properties?.includes('openFile'));+ assert.equal(programDialogOptions(null, 'darwin').filters, undefined, 'on a Mac an app can be chosen too');+});diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjsindex 61dd18f..604d2c1 100644--- a/apps/desktop/src/local-agents-ipc.mjs+++ b/apps/desktop/src/local-agents-ipc.mjs@@ -5,12 +5,21 @@* desktop:local-agents:list → [{ id, label, cli: { path, source } | null, signedIn, install, setupRequired }]* desktop:local-agents:sign-in { agent } → Terminal runs its own sign-in, which opens its own page* desktop:local-agents:probe { agent } → { ok, info }: a session opened and closed, only for its options- * (model, reasoning effort), so the menu shows them before the first message- * desktop:local-agents:start { agent, cwd } → { ok, key, info } | { ok: false, error, code? }+ * (model, reasoning effort) and its commands (info.commands), so the menu and the+ * composer's / show them before the first message+ * desktop:local-agents:start { agent, cwd, resume? } → { ok, key, info } | { ok: false, error, code? }+ * resume: the agent's own id of a conversation it had (info.sessionId of an earlier+ * start), taken up where it stopped: the session still open here (a reloaded+ * page), else the agent's own resume; a new one when it cannot* desktop:local-agents:prompt { key, text, meta?, images? } → { ok, stopReason } | { ok: false, error }* images: [{ data (base64), mimeType }], the pictures of the message's references,* sent after the text to an agent that takes pictures (the text names their files* either way)+ * desktop:local-agents:steer { key, text, images? } → { ok, outcome } a message sent while a turn runs,+ * into that turn (ok: it joined it); the page sends it as a turn of its own if not+ * desktop:local-agents:adopt { key, turnId | null, meta? } what the agent does with nobody having written (a+ * background task of its own came back) is the page's turn `turnId`: written in its+ * log from the first of it (kept since the last turn), until null* desktop:local-agents:cancel { key }* desktop:local-agents:set-option { key, configId, value }* desktop:local-agents:permission { key, requestId, optionId | null } the page answers a permission request@@ -25,7 +34,8 @@** A session belongs to the page that opened it: when the page goes, its sessions close, no orphan processes. A* reload in the middle of a turn loses nothing: the running turn (the page's meta and every event since) is kept- * here until the reloaded page takes it.+ * here until the reloaded page takes it, and the reloaded page takes the session up again by its id. One left idle+ * for IDLE_MS closes (its process goes); the conversation is resumed from the agent's own record on its next turn.** Every turn is also written down as it happens, in the project's `.film/logs/<turn>.jsonl` (chat-store.mjs):* the prompt and the session it ran in, every event above, each answer the page gave, how it ended.@@ -36,6 +46,13 @@ import { AgentSession, HARNESS_AGENTS, isAgentId, isChatAgent, listAgents, openAimport { openLog } from './chat-store.mjs';const TURN_LOG_MAX = 5000;+/** what the agent sends between turns, kept for a turn of its own the page may open for it */+const BETWEEN_TURNS_MAX = 500;+/** a session nobody has spoken in for this long closes; how often that is looked at */+const IDLE_MS = 20 * 60_000;+const IDLE_CHECK_MS = 60_000;+/** how long a session opened for its options waits for the agent to say its commands */+const PROBE_COMMANDS_MS = 1500;/** the pictures one message may carry, and how big each (base64 of a JPEG at most 1280 px wide) */const PROMPT_IMAGES_MAX = 8;const PROMPT_IMAGE_MAX_CHARS = 8 * 1024 * 1024;@@ -55,10 +72,10 @@ function imageBlocks(images) {* `harness(id)` gives the app's own agent ('byok') what it runs with (agent-roster.mjs), resolved as* each session starts.* `onWorking` hears the folders agents are working in (a turn running there) each time they change.- * @param {{ trusted: (event: any) => boolean, binDir?: string | null, env?: Record<string, string>,+ * @param {{ trusted: (event: any) => boolean, binDir?: string | null, fallbackDir?: string | null, env?: Record<string, string>,* harness?: (id: string) => Promise<any>, onWorking?: (folders: string[]) => void }} opts*/-export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {}, harness = async () => null, log = () => {}, onWorking = () => {} }) {+export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbackDir = null, env = {}, harness = async () => null, log = () => {}, onWorking = () => {} }) {const harnessFor = async (agent) => (HARNESS_AGENTS.includes(agent) ? harness(agent) : undefined);/** @type {Map<string, { session: AgentSession, sender: import('electron').WebContents, pending: Map<string, (answer: any) => void>, agent: string, cwd: string, turn: any }>} */const sessions = new Map();@@ -71,7 +88,13 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {});const send = (entry, key, payload) => {+ /* anything it says counts as use: a session working on its own is not idle */+ entry.lastUsed = Date.now();if (entry.turn && !entry.turn.done) { const { kind, ...fields } = payload; entry.turn.file.write(kind, fields); }+ else if (entry.adopted) { const { kind, ...fields } = payload; entry.adopted.write(kind, fields); }+ else {+ entry.between = [...(entry.between ?? []), payload].slice(-BETWEEN_TURNS_MAX);+ }const log = entry.turn?.log;if (log && !entry.turn.done) {log.push(payload);@@ -113,8 +136,15 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {if (!isChatAgent(agent)) return { ok: false, error: `Unknown agent: ${String(agent)}` };let session;try {- session = new AgentSession({ agent, cwd: homedir(), binDir, env, harness: await harnessFor(agent) });- return { ok: true, info: await session.start() };+ /* its commands too (the composer's / menu), which it says just after the session opens: waited for a moment */+ let commands = null;+ let said = () => {};+ const heard = new Promise((done) => { said = done; });+ session = new AgentSession({ agent, cwd: homedir(), binDir, fallbackDir, env, harness: await harnessFor(agent),+ onUpdate: (update) => { if (update?.sessionUpdate === 'available_commands_update') { commands = update.availableCommands ?? null; said(); } } });+ const info = await session.start();+ await Promise.race([heard, new Promise((done) => setTimeout(done, PROBE_COMMANDS_MS))]);+ return { ok: true, info: { ...info, ...(commands ? { commands } : {}) } };} catch (e) {return { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.code ? { code: String(e.code) } : {}) };} finally {@@ -125,16 +155,25 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {handle('desktop:local-agents:start', async (event, opts) => {const agent = opts?.agent;const cwd = opts?.cwd;+ const resume = typeof opts?.resume === 'string' && opts.resume ? opts.resume : null;if (!isChatAgent(agent)) return { ok: false, error: `Unknown agent: ${String(agent)}` };if (typeof cwd !== 'string' || !cwd) return { ok: false, error: 'Missing project folder.' };+ /* the conversation still open here (the page was reloaded): taken up as it is, no second process */+ const open = resume ? [...sessions].find(([, e]) => e.agent === agent && e.cwd === cwd && e.info?.sessionId === resume && e.sender === event.sender) : null;+ if (open) {+ open[1].lastUsed = Date.now();+ return { ok: true, key: open[0], info: { ...open[1].info, resumed: true, authMethods: [], mcp: false } };+ }const key = randomUUID();const pending = new Map();- const entry = { sender: event.sender, pending, session: null, agent, cwd, turn: null };+ const entry = { sender: event.sender, pending, session: null, agent, cwd, turn: null, lastUsed: Date.now() };try {entry.session = new AgentSession({agent,cwd,+ resume,binDir,+ fallbackDir,env,harness: await harnessFor(agent),onUpdate: (update) => send(entry, key, { kind: 'update', update }),@@ -171,6 +210,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {const text = String(opts?.text ?? '');/* an agent that takes no pictures is given none: the text names each one's file, which it can open itself */const images = entry.info?.promptCapabilities?.image ? imageBlocks(opts?.images) : [];+ entry.between = [];if (turn) {entry.turn = turn;file.write('prompt', { agent: entry.agent, cwd: entry.cwd, session: entry.info ?? null, meta, text, images: images.length });@@ -189,6 +229,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {entry.running -= 1;onWorking(working());}+ entry.lastUsed = Date.now();if (turn) {/* a turn that failed: what the agent's process last wrote to stderr says why */turn.file.write('done', result.ok ? result : { ...result, stderr: String(entry.session?.stderr ?? '').slice(-8000) });@@ -217,6 +258,34 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {if (turn && !turn.done) turn.file.write(kind, fields);};+ handle('desktop:local-agents:steer', async (_event, opts) => {+ const entry = sessions.get(opts?.key);+ if (!entry || !(entry.running > 0)) return { ok: false, outcome: 'noRunningTurn' };+ const images = entry.info?.promptCapabilities?.image ? imageBlocks(opts?.images) : [];+ const text = String(opts?.text ?? '');+ noted(opts, 'steer', { text, images: images.length });+ const outcome = await entry.session.steer([{ type: 'text', text }, ...images]);+ noted(opts, 'steer-answer', { outcome });+ return { ok: outcome === 'injected', outcome };+ });++ handle('desktop:local-agents:adopt', (_event, opts) => {+ const entry = sessions.get(opts?.key);+ if (!entry) return { ok: false };+ entry.adopted?.write('done', { ok: true, unprompted: true });+ entry.adopted?.end();+ entry.adopted = null;+ if (typeof opts?.turnId === 'string') {+ entry.adopted = openLog(entry.cwd, opts.turnId, (e) => log(`turn log ${opts.turnId}: ${e.message}\n`));+ /* `meta`: the page's turn, so a log found without a saved turn can be made a turn again (chat-store unsavedTurns) */+ const meta = opts?.meta && typeof opts.meta === 'object' ? opts.meta : null;+ entry.adopted.write('prompt', { agent: entry.agent, cwd: entry.cwd, session: entry.info ?? null, meta, unprompted: true, text: '' });+ for (const { kind, ...fields } of entry.between ?? []) entry.adopted.write(kind, fields);+ }+ entry.between = [];+ return { ok: true };+ });+handle('desktop:local-agents:cancel', async (_event, opts) => {noted(opts, 'cancel', {});await sessions.get(opts?.key)?.session.cancel();@@ -253,6 +322,15 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, env = {return { ok: true };});+ /* idle sessions close: a conversation not spoken in for a while costs no process; its next turn resumes it */+ const idle = setInterval(() => {+ const now = Date.now();+ for (const [key, entry] of [...sessions]) {+ if (!(entry.running > 0) && !entry.turn && entry.pending.size === 0 && now - (entry.lastUsed ?? 0) > IDLE_MS) close(key);+ }+ }, IDLE_CHECK_MS);+ idle.unref?.();+return {isBusy: () => activePrompts > 0,working,diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjsindex cb4b4b8..07d213a 100644--- a/apps/desktop/src/main.mjs+++ b/apps/desktop/src/main.mjs@@ -13,7 +13,7 @@ import { basename, join } from 'node:path';import { Readable } from 'node:stream';import { fileURLToPath } from 'node:url';import { FLAVOR, IDENTITY, PRODUCT_NAME } from './flavor.mjs';-import { folderDialogOptions } from './folder-dialog.mjs';+import { folderDialogOptions, programDialogOptions } from './folder-dialog.mjs';import { childEnvironment, loginShellEnvironment } from './environment.mjs';import { startWindowStudio } from './studio.mjs';import { CHAT_MIN, STUDIO_MIN, WINDOW_MIN, placeOnDisplays, readWindowState, writeWindowState } from './window-state.mjs';@@ -21,7 +21,8 @@ import { applicationMenu } from './menu.mjs';import { registerLocalAgentIpc } from './local-agents-ipc.mjs';import { registerChatIpc } from './chat-ipc.mjs';import { createRoster } from './agent-roster.mjs';-import { listAgents, openAgentSignIn } from './agents.mjs';+import { checkAgentProgram, diagnoseAgent, listAgents, openAgentSignIn, setChosenPaths } from './agents.mjs';+import { agentUsage, forgetAgentUsage } from './agent-usage.mjs';import { installOpenfilmCommand } from './openfilm-command.mjs';import { startUpdates } from './updates.mjs';import { ensureFfmpeg, ffmpegDir, ffmpegDownloadable, ffmpegIn, ffmpegOnPath } from './ffmpeg-runtime.mjs';@@ -212,10 +213,10 @@ async function start() {});- /* what the installer brings (scripts/release.mjs): ffmpeg and ffprobe, first on the PATH of Studio and the agents,- and the headless browser Studio and `openfilm` draw pages in. A build without them (from source): no ffmpeg on- this computer, the app's own goes first on the PATH and is downloaded once the window is up (they find it the- moment it lands); the browser, Studio downloads the first time (studio-process.mjs) */+ /* what the installer brings (scripts/release.mjs): ffmpeg and ffprobe, first on the PATH of Studio and of the+ agents' `openfilm` command, and the headless browser Studio and `openfilm` draw pages in. A build without them+ (from source): no ffmpeg on this computer, the app's own goes first on the PATH and is downloaded once the window+ is up (they find it the moment it lands); the browser, Studio downloads the first time (studio-process.mjs) */const runtime = app.isPackaged ? join(process.resourcesPath, 'runtime') : null;const ownFfmpeg = runtime && ffmpegIn(join(runtime, 'ffmpeg')) ? join(runtime, 'ffmpeg') : null;const needFfmpeg = !ownFfmpeg && !ffmpegOnPath(env.PATH) && ffmpegDownloadable();@@ -301,9 +302,11 @@ async function start() {log,/* Studio refuses to delete a project an agent is working in */onWorking: tellWorking,- /* the `openfilm` command, and the app's ffmpeg (several folders, PATH-joined) */- binDir: [installOpenfilmCommand(DATA), ...(ffmpegHere ? [ffmpegHere] : [])].join(PATH_SEP),- env: { OPENFILM_HOME: env.OPENFILM_HOME, ...(env.OPENFILM_LIBRARY ? { OPENFILM_LIBRARY: env.OPENFILM_LIBRARY } : {}), ...browsers },+ /* the `openfilm` command first (with the app's ffmpeg and browser in it); the app's ffmpeg last, for a computer+ that has none of its own: the person's own ffmpeg and browsers are what the agent's commands use */+ binDir: installOpenfilmCommand(DATA, { ffmpeg: ffmpegHere, env: browsers }),+ fallbackDir: ffmpegHere,+ env: { OPENFILM_HOME: env.OPENFILM_HOME, ...(env.OPENFILM_LIBRARY ? { OPENFILM_LIBRARY: env.OPENFILM_LIBRARY } : {}) },harness: async (id) => roster?.harness(id) ?? null,});/* Settings → Agents (in Studio's page) and the chat's agent menu: one roster, both told of every change */@@ -311,10 +314,19 @@ async function start() {dataDir: DATA,localAgents: listAgents,openSignIn: openAgentSignIn,- closeSessions: (id) => localAgents?.closeAgent(id),+ /* sessions closed on connecting and disconnecting: the next look at its usage is for whichever account is used now */+ closeSessions: (id) => { forgetAgentUsage(id); localAgents?.closeAgent(id); },seal,unseal,onChange: (list) => view?.webContents.send('desktop:agents', list),+ /* the program the person points at, for an agent not found where it is looked for */+ usePaths: setChosenPaths,+ pickProgram: async (_id, words) => {+ const { canceled, filePaths } = await dialog.showOpenDialog(win, programDialogOptions(words));+ return canceled || !filePaths[0] ? null : filePaths[0];+ },+ checkProgram: checkAgentProgram,+ diagnose: (id) => diagnoseAgent(id, { appVersion: app.getVersion() }),});const agentHandle = (channel, fn) => ipcMain.handle(channel, (event, opts) => {if (!fromPage(event)) throw new Error('not the window\'s page');@@ -323,6 +335,11 @@ async function start() {agentHandle('desktop:agents:list', () => { void roster.refresh(); return roster.list(); });agentHandle('desktop:agents:connect', ({ id }) => roster.connect(String(id)));agentHandle('desktop:agents:disconnect', ({ id }) => { roster.disconnect(String(id)); return { ok: true }; });+ /* what is left of Claude Code's and Codex's plan, on OpenFilm's sign-in (agent-usage.mjs); null when it can't say */+ agentHandle('desktop:agents:usage', ({ id, fresh }) => agentUsage(String(id), { fresh: fresh === true }));+ agentHandle('desktop:agents:locate', ({ id, words }) => roster.locate(String(id), words));+ agentHandle('desktop:agents:automatic', ({ id }) => roster.useAutomatic(String(id)));+ agentHandle('desktop:agents:diagnose', ({ id }) => roster.diagnose(String(id)));agentHandle('desktop:agents:shown', ({ id, shown }) => { roster.setShown(String(id), shown === true); return { ok: true }; });agentHandle('desktop:agents:byok', ({ config }) => roster.configureByok(config));/* a file on the disk brought into the chat goes into the project the page names, through Studio's own import (it@@ -380,6 +397,9 @@ async function start() {},});ipcMain.handle('desktop:update-restart', (event) => (fromPage(event) ? updates?.restart() : { ok: false }));+ /* Settings → About: the state now, and a check that answers with the state it ends in (no dialog) */+ ipcMain.handle('desktop:update-state', (event) => (fromPage(event) ? updates?.snapshot() ?? null : null));+ ipcMain.handle('desktop:update-check', (event) => (fromPage(event) ? updates?.check() ?? null : null));Menu.setApplicationMenu(applicationMenu({productName: PRODUCT_NAME,diff --git a/apps/desktop/src/mention-menu.test.mjs b/apps/desktop/src/mention-menu.test.mjsnew file mode 100644index 0000000..87cced7--- /dev/null+++ b/apps/desktop/src/mention-menu.test.mjs@@ -0,0 +1,12 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { matchSlashTrigger } from '../chat/src/components/prompt-editor/mention-menu.ts';++test("a `/` at the start of the message opens the agent's commands; anywhere else it is only a slash", () => {+ assert.deepEqual(matchSlashTrigger('/'), { leadOffset: 0, query: '', replaceableString: '/' });+ assert.deepEqual(matchSlashTrigger(' /comp'), { leadOffset: 2, query: 'comp', replaceableString: '/comp' });+ assert.equal(matchSlashTrigger('/compact now'), null, 'a space ends the command');+ assert.equal(matchSlashTrigger('make it 1/2'), null);+ assert.equal(matchSlashTrigger('assets/'), null);+ assert.equal(matchSlashTrigger('//'), null);+});diff --git a/apps/desktop/src/openfilm-command.mjs b/apps/desktop/src/openfilm-command.mjsindex 51bd755..9fce0ff 100644--- a/apps/desktop/src/openfilm-command.mjs+++ b/apps/desktop/src/openfilm-command.mjs@@ -5,6 +5,10 @@** OPENFILM_NO_UPDATE_CHECK: the CLI's "a newer openfilm is out, run npx -y openfilm@latest" is not for this copy. The* app updates itself, and with it this command and the window's Studio: there is nothing for an agent to run.+ *+ * What the command alone needs from the app is set in it, not given to the agent: the app's ffmpeg first on its PATH+ * (`ffmpeg`) and the headless browser it draws pages in (`env`, PLAYWRIGHT_BROWSERS_PATH). The agent's own commands run+ * with the person's ffmpeg and their own browsers, as in their terminal.*/import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { createRequire } from 'node:module';@@ -22,26 +26,31 @@ export function openfilmCli() {const sq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;-/** The script's text: Electron as Node, running the CLI with whatever it was given. */-export function commandScript(node, cli) {- return `#!/bin/sh\n# OpenFilm's own copy of the openfilm command (written by the app; changes are lost)\nELECTRON_RUN_AS_NODE=1 OPENFILM_NO_UPDATE_CHECK=1 exec ${sq(node)} ${sq(cli)} "$@"\n`;+/** The script's text: Electron as Node, running the CLI with whatever it was given, with the app's ffmpeg and `env`. */+export function commandScript(node, cli, { ffmpeg = null, env = {} } = {}) {+ const set = [...Object.entries(env).map(([k, v]) => `${k}=${sq(v)}`), ...(ffmpeg ? [`PATH=${sq(ffmpeg)}:"$PATH"`] : [])];+ return `#!/bin/sh\n# OpenFilm's own copy of the openfilm command (written by the app; changes are lost)\n${set.map((s) => `${s} `).join('')}ELECTRON_RUN_AS_NODE=1 OPENFILM_NO_UPDATE_CHECK=1 exec ${sq(node)} ${sq(cli)} "$@"\n`;}/** The same for Windows: a `.cmd` (what a command line there finds as `openfilm`). */-export function commandScriptWindows(node, cli) {- return `@echo off\r\nrem OpenFilm's own copy of the openfilm command (written by the app; changes are lost)\r\nset ELECTRON_RUN_AS_NODE=1\r\nset OPENFILM_NO_UPDATE_CHECK=1\r\n"${node}" "${cli}" %*\r\n`;+export function commandScriptWindows(node, cli, { ffmpeg = null, env = {} } = {}) {+ const set = [...Object.entries(env).map(([k, v]) => `set "${k}=${v}"\r\n`), ...(ffmpeg ? [`set "PATH=${ffmpeg};%PATH%"\r\n`] : [])];+ return `@echo off\r\nrem OpenFilm's own copy of the openfilm command (written by the app; changes are lost)\r\nsetlocal\r\n${set.join('')}set ELECTRON_RUN_AS_NODE=1\r\nset OPENFILM_NO_UPDATE_CHECK=1\r\n"${node}" "${cli}" %*\r\n`;}-/** Write the command into `<dir>/bin` and answer that folder, for PATH. */-export function installOpenfilmCommand(dir, node = nodeBinary(), platform = process.platform) {+/**+ * Write the command into `<dir>/bin` and answer that folder, for PATH. `ffmpeg`: the app's ffmpeg folder, first on the+ * command's PATH; `env`: what else it runs with.+ */+export function installOpenfilmCommand(dir, { node = nodeBinary(), platform = process.platform, ffmpeg = null, env = {} } = {}) {const bin = join(dir, 'bin');mkdirSync(bin, { recursive: true });if (platform === 'win32') {- writeFileSync(join(bin, 'openfilm.cmd'), commandScriptWindows(node, openfilmCli()));+ writeFileSync(join(bin, 'openfilm.cmd'), commandScriptWindows(node, openfilmCli(), { ffmpeg, env }));return bin;}const file = join(bin, 'openfilm');- writeFileSync(file, commandScript(node, openfilmCli()));+ writeFileSync(file, commandScript(node, openfilmCli(), { ffmpeg, env }));chmodSync(file, 0o755);return bin;}diff --git a/apps/desktop/src/openfilm-command.test.mjs b/apps/desktop/src/openfilm-command.test.mjsnew file mode 100644index 0000000..c9b7688--- /dev/null+++ b/apps/desktop/src/openfilm-command.test.mjs@@ -0,0 +1,28 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { commandScript, commandScriptWindows } from './openfilm-command.mjs';++test("the openfilm command alone has the app's ffmpeg first and its browser; the agent's PATH is left as it is", () => {+ const sh = commandScript('/app/node', '/app/openfilm.mjs', { ffmpeg: '/app/ffmpeg', env: { PLAYWRIGHT_BROWSERS_PATH: '/app/pw' } });+ assert.match(sh, /^#!\/bin\/sh\n/);+ assert.match(sh, /PLAYWRIGHT_BROWSERS_PATH='\/app\/pw' PATH='\/app\/ffmpeg':"\$PATH" ELECTRON_RUN_AS_NODE=1 OPENFILM_NO_UPDATE_CHECK=1 exec '\/app\/node' '\/app\/openfilm.mjs' "\$@"\n$/);+ assert.doesNotMatch(commandScript('/n', '/c'), /PATH=/);+ const cmd = commandScriptWindows('C:\\app\\node.exe', 'C:\\app\\openfilm.mjs', { ffmpeg: 'C:\\app\\ffmpeg', env: { PLAYWRIGHT_BROWSERS_PATH: 'C:\\pw' } });+ assert.match(cmd, /setlocal\r\nset "PLAYWRIGHT_BROWSERS_PATH=C:\\pw"\r\nset "PATH=C:\\app\\ffmpeg;%PATH%"\r\n/);+});++test('a script run through as-node.mjs sees itself as the script, with its arguments, and no ELECTRON_RUN_AS_NODE', () => {+ const dir = mkdtempSync(join(tmpdir(), 'openfilm-as-node-'));+ try {+ const script = join(dir, 'show.mjs');+ writeFileSync(script, "console.log(JSON.stringify({ argv: process.argv.slice(1), runAsNode: process.env.ELECTRON_RUN_AS_NODE ?? null }));\n");+ const asNode = fileURLToPath(new URL('./as-node.mjs', import.meta.url));+ const out = JSON.parse(execFileSync(process.execPath, [asNode, script, '--flag', 'x'], { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, encoding: 'utf8' }));+ assert.deepEqual(out, { argv: [script, '--flag', 'x'], runAsNode: null });+ } finally { rmSync(dir, { recursive: true, force: true }); }+});diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjsindex a180ed4..c0ddc46 100644--- a/apps/desktop/src/preload.cjs+++ b/apps/desktop/src/preload.cjs@@ -31,7 +31,11 @@ contextBridge.exposeInMainWorld('openfilmNative', {list: () => ipcRenderer.invoke('desktop:agents:list'),connect: (id) => ipcRenderer.invoke('desktop:agents:connect', { id }),disconnect: (id) => ipcRenderer.invoke('desktop:agents:disconnect', { id }),+ usage: (id, fresh) => ipcRenderer.invoke('desktop:agents:usage', { id, fresh: fresh === true }),setShown: (id, shown) => ipcRenderer.invoke('desktop:agents:shown', { id, shown: shown === true }),+ locate: (id, words) => ipcRenderer.invoke('desktop:agents:locate', { id, words }),+ useAutomatic: (id) => ipcRenderer.invoke('desktop:agents:automatic', { id }),+ diagnose: (id) => ipcRenderer.invoke('desktop:agents:diagnose', { id }),configureByok: (config) => ipcRenderer.invoke('desktop:agents:byok', { config }),onChange: on('desktop:agents'),},@@ -41,10 +45,12 @@ contextBridge.exposeInMainWorld('openfilmNative', {signIn: (agent) => invoke('desktop:local-agents:sign-in')({ agent }),disconnect: (agent) => invoke('desktop:local-agents:disconnect')({ agent }),probe: (agent) => invoke('desktop:local-agents:probe')({ agent }),- start: (agent, cwd) => invoke('desktop:local-agents:start')({ agent, cwd }),+ start: (agent, cwd, resume) => invoke('desktop:local-agents:start')({ agent, cwd, resume }),prompt: (key, text, meta, images) => invoke('desktop:local-agents:prompt')({ key, text, meta, images }),running: () => ipcRenderer.invoke('desktop:local-agents:running'),ack: (key, turnId) => invoke('desktop:local-agents:ack')({ key, turnId }),+ steer: (key, text, images) => invoke('desktop:local-agents:steer')({ key, text, images }),+ adopt: (key, turnId, meta) => invoke('desktop:local-agents:adopt')({ key, turnId, meta }),cancel: (key) => invoke('desktop:local-agents:cancel')({ key }),setOption: (key, configId, value) => invoke('desktop:local-agents:set-option')({ key, configId, value }),answerPermission: (key, requestId, optionId) => invoke('desktop:local-agents:permission')({ key, requestId, optionId }),@@ -58,9 +64,12 @@ contextBridge.exposeInMainWorld('openfilmNative', {load: (project) => ipcRenderer.invoke('desktop:chat:load', { project }),saveSessions: (project, sessions, last) => ipcRenderer.invoke('desktop:chat:sessions', { project, sessions, last }),saveTurn: (project, turn, items) => ipcRenderer.invoke('desktop:chat:turn', { project, turn, items }),- log: (project, turnId) => ipcRenderer.invoke('desktop:chat:log', { project, turnId }),+ log: (project, turnId, unless) => ipcRenderer.invoke('desktop:chat:log', { project, turnId, unless }),reveal: (project, turnId) => ipcRenderer.invoke('desktop:chat:reveal', { project, turnId }),saveRefImage: (project, turnId, n, bytes) => ipcRenderer.invoke('desktop:chat:ref-image', { project, turnId, n, bytes }),+ unsaved: (project, except) => ipcRenderer.invoke('desktop:chat:unsaved', { project, except }),+ snapshot: (project, turnId) => ipcRenderer.invoke('desktop:chat:snapshot', { project, turnId }),+ changes: (project, turnId) => ipcRenderer.invoke('desktop:chat:changes', { project, turnId }),},/* the app's own preferences (Settings → Developer) */prefs: {@@ -82,4 +91,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {onUpdate: on('desktop:update'),/* → { ok } | { ok: false, error }: refused while an agent works or Studio exports (the update stays ready) */restartToUpdate: () => ipcRenderer.invoke('desktop:update-restart'),+ /* → the update's state (update-controller.mjs), now / after a check made now */+ updateState: () => ipcRenderer.invoke('desktop:update-state'),+ checkForUpdate: () => ipcRenderer.invoke('desktop:update-check'),});diff --git a/apps/desktop/src/updates.mjs b/apps/desktop/src/updates.mjsindex 849225d..5f86232 100644--- a/apps/desktop/src/updates.mjs+++ b/apps/desktop/src/updates.mjs@@ -30,8 +30,12 @@ const { autoUpdater } = electronUpdater;export function startUpdates({ dataDir, productName, getWindow, onState, prepareRestart, beforeInstall }) {/* run from source, or built with no update feed (electron-builder writes app-update.yml only with one) */if (!app.isPackaged || !existsSync(join(process.resourcesPath, 'app-update.yml'))) {- const idle = { status: 'idle', version: app.getVersion(), channel: 'stable', availableVersion: null, progress: 0, checkedAt: null, error: null };- return { packaged: false, snapshot: () => idle, restart: async () => ({ ok: false, error: 'not-ready' }), manualCheck: null, channel: () => 'stable', setChannel: () => {}, close: () => {} };+ /* `off`: this build never updates (Settings → About says so) */+ const off = { status: 'off', version: app.getVersion(), channel: 'stable', availableVersion: null, progress: 0, checkedAt: null, error: null };+ return {+ packaged: false, snapshot: () => off, check: async () => off, restart: async () => ({ ok: false, error: 'not-ready' }), manualCheck: null,+ channel: () => 'stable', setChannel: () => {}, close: () => {},+ };}autoUpdater.logger = null;let channel = readUpdateChannel(dataDir);@@ -85,6 +89,8 @@ export function startUpdates({ dataDir, productName, getWindow, onState, preparereturn {packaged: true,snapshot: controller.snapshot,+ /** Check now, quietly (Settings → About shows what it finds); the menu's check answers with a dialog */+ check: controller.check,restart: controller.restart,manualCheck: createManualUpdateCheck({ controller, productName, showMessage, focusWindow: focus }),channel: () => channel,diff --git a/packages/openfilm/src/film-doc.mjs b/packages/openfilm/src/film-doc.mjsindex 025a512..8582a71 100644--- a/packages/openfilm/src/film-doc.mjs+++ b/packages/openfilm/src/film-doc.mjs@@ -32,15 +32,19 @@ export function isStill(src) {}/**- * What a sound is for: `sfx`, `music` and `voice` by their folders (where openfilm get saves them:- * assets/audio/sfx/, music/, vo/); elsewhere a name that says music (bed, music, song, loop…) or an effect (sfx, hit,- * whoosh…) decides; anything else (a video's own sound among them) is a voice.+ * What a sound is for: `sfx`, `music` and `voice` by a folder it is in (where openfilm get saves them:+ * assets/audio/sfx/, music/, vo/; an agent's own assets/sfx/ alike), the nearest one deciding; elsewhere a name that+ * says music (bed, music, song, loop…) or an effect (sfx, hit, whoosh…) decides; anything else (a video's own sound+ * among them) is a voice.*/export function soundRole(src) {const path = String(src).toLowerCase();- if (path.startsWith('assets/audio/sfx/')) return 'sfx';- if (path.startsWith('assets/audio/music/')) return 'music';- if (path.startsWith('assets/audio/vo/')) return 'voice';+ const folders = path.split('/').slice(0, -1).reverse();+ for (const folder of folders) {+ if (/^(sfx|fx|effects?|sound-?effects?)$/.test(folder)) return 'sfx';+ if (/^(music|bgm)$/.test(folder)) return 'music';+ if (/^(vo|voices?|voice-?over|narration)$/.test(folder)) return 'voice';+ }const name = path.split('/').pop() ?? '';if (/(^|[^a-z])(bed|music|song|soundtrack|score|theme|loop|ambient|ambience|beat)([^a-z]|$)/.test(name)) return 'music';if (/(^|[^a-z])(sfx|fx|hit|whoosh|swoosh|riser|impact|ding|chime)([^a-z]|$)/.test(name)) return 'sfx';diff --git a/packages/openfilm/src/film-doc.test.mjs b/packages/openfilm/src/film-doc.test.mjsindex 4d343ba..f408ae5 100644--- a/packages/openfilm/src/film-doc.test.mjs+++ b/packages/openfilm/src/film-doc.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { clipFade, clipKind, clipSpan, fadeGain, filmHtml, kindOf, parseFilm, pictureRect, readFilm, readFilmFile, sourceAt } from './film-doc.mjs';+import { clipFade, clipKind, clipSpan, fadeGain, filmHtml, kindOf, parseFilm, pictureRect, readFilm, readFilmFile, soundRole, sourceAt } from './film-doc.mjs';const film = (clip) => ({ stage: { w: 1920, h: 1080 }, tracks: [{ clips: [clip] }] });const problems = (value) => readFilm(value).problems.join('\n');@@ -293,3 +293,15 @@ test('a page\'s size is the px it is laid out at: read from size="WxH", writtenassert.match(problems(film({ src: 't.html', id: 't', time: [0, 3], size: { w: 0, h: 1080 } })), /size is the px/);assert.match(problems(film({ src: 't.html', id: 't', time: [0, 3], size: { w: 9000, h: 1080 } })), /up to 8192/);});++test('soundRole: the nearest folder named for a role decides, then the name, else a voice', () => {+ assert.equal(soundRole('assets/audio/sfx/pop.wav'), 'sfx');+ assert.equal(soundRole('assets/sfx/pop.wav'), 'sfx');+ assert.equal(soundRole('assets/music/bed.mp3'), 'music');+ assert.equal(soundRole('assets/vo/vo1.wav'), 'voice');+ assert.equal(soundRole('assets/sfx/vo/line.wav'), 'voice');+ assert.equal(soundRole('assets/audio/whoosh.wav'), 'sfx');+ assert.equal(soundRole('assets/audio/bed.mp3'), 'music');+ assert.equal(soundRole('assets/audio/pop.wav'), 'voice');+ assert.equal(soundRole('assets/effective/line.wav'), 'voice');+});diff --git a/packages/openfilm/src/host.mjs b/packages/openfilm/src/host.mjsindex 5c88706..326dc6c 100644--- a/packages/openfilm/src/host.mjs+++ b/packages/openfilm/src/host.mjs@@ -110,7 +110,7 @@ export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, ti/* the film itself: played by the timeline, and the host's driving of it (`timelineInject`) put in */const film = rel === `/${FILM_FILE}` || rel.endsWith(`/${FILM_FILE}`);const start = film ? timelineInject + filmStart(readFilmFile(html).doc?.stage ?? DEFAULT_STAGE) : inject;- res.writeHead(200, headers).end(injectFirst(html, start));+ res.writeHead(200, headers).end(injectFirst(film ? holdPages(html) : html, start));return true;}const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? '');@@ -184,6 +184,19 @@ export function serve(root, { port = 0, swap } = {}) {}/** Put `tag` before any script of the page: after <head> if there is one before the first script, else after the doctype. */+/**+ * The film's page clips served without loading: each <iframe>'s `src` is `data-film-src`. The timeline opens pages+ * itself, a few at a time and only those near the playhead in a film of many (it reads the clips from the file as+ * written); a page the parser had started loading would be cut short, a failed request to every host.+ * @param {string} html+ */+export function holdPages(html) {+ return html.replace(/<iframe\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => tag.replace(+ /(\s)([^\s=>"'/]+)(\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>"']+))?/g,+ (attr, space, name, value = '') => (name.toLowerCase() === 'src' ? `${space}data-film-src${value}` : attr),+ ));+}+export function injectFirst(html, tag) {const firstScript = html.search(/<script\b/i);const prefix = firstScript < 0 ? html : html.slice(0, firstScript);diff --git a/packages/openfilm/src/look.test.mjs b/packages/openfilm/src/look.test.mjsindex 066971e..c7088ab 100644--- a/packages/openfilm/src/look.test.mjs+++ b/packages/openfilm/src/look.test.mjs@@ -53,6 +53,24 @@ test('a film of page clips on its timeline reports no failed request', { timeoutassert.ok(!r.lines.some((l) => /request|ERR_/.test(l)), r.lines.join('\n'));});+test('a film of more pages than are kept open reports no failed request as its pages close and open again', { timeout: 90_000 }, async () => {+ const { mkdtempSync, writeFileSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const dir = mkdtempSync(join(tmpdir(), 'of-look-pages-'));+ /* a 1 × 1 PNG: each page has a file of its own to load */+ writeFileSync(join(dir, 'dot.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64'));+ const clips = [];+ for (let i = 0; i < 12; i++) {+ writeFileSync(join(dir, `p${i}.html`), `<!doctype html><body style="margin:0;background:#123"><img src="dot.png?${i}"><script>window.film = { duration: 1, width: 320, height: 180, frame() {} };</script>`);+ clips.push({ src: `p${i}.html`, at: i });+ }+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips }] }));+ const r = await look([dir], { count: 12 });+ assert.notEqual(r.ok, false, r.lines.join('\n'));+ assert.ok(!r.lines.some((l) => /request|ERR_/.test(l)), r.lines.join('\n'));+});+test('a page that still lists sounds in window.film.audio is told, once, that they are not played', { timeout: 90_000 }, async () => {const { mkdtempSync, writeFileSync } = await import('node:fs');const { tmpdir } = await import('node:os');diff --git a/packages/openfilm/src/timeline.mjs b/packages/openfilm/src/timeline.mjsindex 0518468..5902e8a 100644--- a/packages/openfilm/src/timeline.mjs+++ b/packages/openfilm/src/timeline.mjs@@ -24,18 +24,23 @@ const CLIP_TAGS = new Set(['iframe', 'video', 'img', 'audio']);const sections = [...document.body.children].filter((el) => el.localName === 'section');const elements = sections.map((s) => { s.style.display = 'contents'; return [...s.children].filter((el) => CLIP_TAGS.has(el.localName)); });const url = (src) => new URL(src, location.href);+/* an editor's preview (`?film-missing=skip`) plays on past a clip whose file is not there: the clip keeps its time,+ but is neither loaded, drawn nor heard. Anything else (a check, an export) says the missing file and stops */+const SKIP_MISSING = new URL(location.href).searchParams.get('film-missing') === 'skip';const ready = (a) => Promise.resolve(typeof a.ready === 'function' ? a.ready() : a.ready);-/* a browser opens about six connections to one server: more files asked at once only wait behind each other */-const LOADS = 6;-let loadsBusy = 0;-const loadsWaiting = [];-/** Run `fn` when fewer than LOADS files are loading. */-async function limited(fn) {- if (loadsBusy >= LOADS) await new Promise((go) => loadsWaiting.push(go));- loadsBusy++;- try { return await fn(); } finally { loadsBusy--; loadsWaiting.shift()?.(); }+/** A gate that runs what is given to it when fewer than `most` of its runs are going. */+function gate(most) {+ let busy = 0;+ const waiting = [];+ return async (fn) => {+ if (busy >= most) await new Promise((go) => waiting.push(go));+ busy++;+ try { return await fn(); } finally { busy--; waiting.shift()?.(); }+ };}+/* a browser opens about six connections to one server: more files asked at once only wait behind each other */+const limited = gate(6);/*** Each media file's own length and picture size, read once (the clips of one recording share it); null: unreadable.@@ -138,6 +143,7 @@ function unfade(c) {*/function override(c, list = []) {const win = c.win;+ if (!win) return;const touch = (el, prop) => {let saved = c.touched.get(el);if (!saved) { saved = { props: new Map(), texts: null }; c.touched.set(el, saved); }@@ -372,10 +378,11 @@ const LOAD_MS = 30_000; // how long an export's frame waits for a video's file b/*** Give a video its file; for an exact frame, to start at its source second `from`. Resolves once its first frame is- * there (or it failed: a frame of it then shows nothing).+ * there (or it failed: a frame of it then shows nothing). A page is opened (see wakePage).*/function wake(c, from = null) {if (c.awake) return c.awake;+ if (c.kind === 'page') return wakePage(c);const v = c.el;v.preload = 'auto';/* without the fragment: which seconds play is the film's to keep (a browser would stop the video at its end) */@@ -390,8 +397,9 @@ function wake(c, from = null) {return c.awake;}-/** Let a video's file go: its decoder and buffers are freed. */+/** Let a video's file go: its decoder and buffers are freed. A page is closed (see restPage). */function rest(c) {+ if (c.kind === 'page') { restPage(c); return; }const v = c.el;if (!v.paused) v.pause();v.preload = 'none';@@ -401,28 +409,102 @@ function rest(c) {c.held = false;}+/*+ * A page is open only near the playhead too, once a film has more of them than PAGES_AWAKE: each open page keeps its+ * document, its libraries and its canvases, and a browser keeps only 16 WebGL contexts at once (more, and the oldest+ * page's 3D goes blank). A film of fewer pages keeps them all open, as loaded. A page opened again is the same page:+ * a frame is a function of t (SPEC §3), so it draws what it drew before.+ */+const PAGES_AWAKE = 8;+/* pages opening at once: with PAGES_AWAKE open, no more WebGL contexts than a browser keeps */+const pageLimited = gate(4);+/** the pages open now (or opening) */+const pagesAwake = new Set();++/**+ * Open a page clip's file and wait for its window.film to be ready. Rejects when the page is not a film; resolves+ * without opening when it was let go meanwhile (see restPage).+ */+function wakePage(c) {+ const mine = c.waking = {};+ c.awake = pageLimited(async () => {+ if (c.waking !== mine) return;+ const el = c.el;+ /* a film is a picture, never scrolled: a page a little larger than its frame shows no scrollbars (some browsers+ always draw them; exports draw none) */+ el.setAttribute('scrolling', 'no');+ /* still open (closed while it loaded, see restPage): taken up again as it is; else the document there now+ (blank) is not the page's, and its window.film, if any, is gone once the page commits */+ const href = url(c.row.src).href;+ const before = el.getAttribute('src') === href ? null : el.contentDocument;+ if (before) el.src = href;+ const t0 = performance.now();+ const film = () => (el.contentDocument !== before ? el.contentWindow?.film : null);+ while (!(film() && typeof film().frame === 'function')) {+ if (c.waking !== mine) return;+ if (performance.now() - t0 > 10000) throw new Error(`${c.row.src}: window.film with a frame() function did not appear`);+ await new Promise((r) => setTimeout(r, 20));+ }+ const win = el.contentWindow;+ await ready(win.film);+ if (c.waking !== mine) return;+ c.win = win;+ c.child = win.film;+ c.touched = new Map();+ c.drawn = false;+ /* its own size, when it says one (else its clip's size, or the stage's: see settle) */+ if (c.child.width > 0 && c.child.height > 0) c.own = { w: c.child.width, h: c.child.height };+ window.__filmEditor.stage.woke?.();+ });+ pagesAwake.add(c);+ /* one woken ahead and not waited for: its failure is said when a frame of it is drawn */+ c.awake.catch(() => {});+ return c.awake;+}++/**+ * Close a page clip's document: its length and size stay known, its tweaks are put on again when it opens. Closed once+ * its own files are in: a request cut short is a failed one, which a host reports.+ */+function restPage(c) {+ pagesAwake.delete(c);+ c.awake = c.waking = null;+ c.win = c.child = null;+ c.drawn = false;+ c.touched = new Map();+ const el = c.el;+ const close = () => { if (!c.awake && el.isConnected) el.setAttribute('src', 'about:blank'); };+ if (!el.hasAttribute('src') || el.contentDocument?.readyState === 'complete') close();+ else el.addEventListener('load', close, { once: true });+}+/**- * Wake the videos near t (those on at t always), and let those far from it rest. `only`: wake only those on at t, and- * let none rest unless far too many hold their files (a scrub: the rest is done once it stops, see draw). `exact`:- * for an exact frame (an export's), each woken at the frame it is wanted at.+ * Wake the videos and pages near t (those on at t always), and let those far from it rest. `only`: wake only those on+ * at t, and let none rest unless far too many are awake (a scrub: the rest is done once it stops, see draw). `exact`:+ * for an exact frame (an export's), each video woken at the frame it is wanted at.*/function near(t, { only = false, exact = false } = {}) {+ nearOf('video', AWAKE_MAX, t, only, exact);+ nearOf('page', PAGES_AWAKE, t, only, exact);+}+function nearOf(kind, max, t, only, exact) {const off = (c) => (t < c.at ? c.at - t : t >= c.end ? t - c.end : 0);- const videos = clips.filter((c) => c.kind === 'video');- const wanted = videos- .filter((c) => !c.hidden && (only ? off(c) === 0 : t < c.at ? c.at - t <= WAKE_AHEAD : t - c.end <= WAKE_BEHIND))+ const all = clips.filter((c) => c.kind === kind);+ const wanted = all+ .filter((c) => !c.hidden && !c.missing && (only ? off(c) === 0 : t < c.at ? c.at - t <= WAKE_AHEAD : t - c.end <= WAKE_BEHIND)).sort((a, b) => off(a) - off(b));const on = wanted.filter((c) => off(c) === 0).length;- const keep = new Set(wanted.slice(0, Math.max(on, AWAKE_MAX)));- for (const c of keep) wake(c, exact ? sourceAt(c.span, Math.min(Math.max(0, t - c.at), c.span.length), c.row) : null);- /* the rest: those far off rest, and the farthest while too many hold their files */- const most = only ? 2 * AWAKE_MAX : AWAKE_MAX;- const awake = videos.filter((c) => c.awake && !keep.has(c)).sort((a, b) => off(b) - off(a));+ const keep = new Set(wanted.slice(0, Math.max(on, max)));+ for (const c of keep) wake(c, exact && kind === 'video' ? sourceAt(c.span, Math.min(Math.max(0, t - c.at), c.span.length), c.row) : null);+ /* the rest: videos far off rest, and the farthest while too many are awake (pages: only then, and never more than+ max, a scrub's included) */+ const most = only && kind === 'video' ? 2 * max : max;+ const awake = all.filter((c) => c.awake && !keep.has(c)).sort((a, b) => off(b) - off(a));let over = keep.size + awake.length - most;for (const c of awake) {- /* one an edit is putting on screen (see cue) keeps its file, wherever it is now */+ /* one an edit is putting on screen (see cue) stays awake, wherever it is now */if (cueing.has(c)) continue;- if ((!only && (c.hidden || off(c) > KEEP)) || over > 0) { rest(c); over--; }+ if ((kind === 'video' && !only && (c.hidden || off(c) > KEEP)) || over > 0) { rest(c); over--; }}}/** a scrub's last moment, its neighbors woken (and the far ones let go) once it stops */@@ -477,7 +559,7 @@ function settle(c, row, track, ti) {c.at = row.at ?? 0;/* a hidden track's clips are loaded (an editor shows them, grayed) but neither drawn nor heard */c.hidden = Boolean(track.hidden);- c.volume = track.muted || c.hidden ? 0 : (row.volume ?? 1);+ c.volume = track.muted || c.hidden || c.missing ? 0 : (row.volume ?? 1);c.span = clipSpan(row, c.native, where);c.end = c.at + c.span.length;c.fade = fittedFade(clipFade(row), c.span.length);@@ -502,10 +584,15 @@ function hear() {}}-/** A clip's file has to be there: a missing one is said at once, by its name (not as a page that never answered). */+/**+ * A clip's file has to be there: a missing one is said at once, by its name (not as a page that never answered).+ * In an editor's preview (SKIP_MISSING) it is not an error: false, and the clip is played as missing.+ */async function mustBeThere(src) {const res = await fetch(url(src), { method: 'HEAD' }).catch(() => null);- if (res && res.status === 404) throw new Error(`${src}: there is no such file`);+ if (!(res && res.status === 404)) return true;+ if (SKIP_MISSING) return false;+ throw new Error(`${src}: there is no such file`);}/** Clips loaded so far: what a host waiting for `ready` sees moving (see host.mjs). */@@ -525,37 +612,32 @@ async function load(row, track, ti, el) {el.preload = 'none';c.el = null;const facts = await factsOf(row.src);- if (!facts) await mustBeThere(row.src);+ if (!facts && !(await mustBeThere(row.src))) c.missing = true;c.native = facts?.duration ?? 0;} else if (kind === 'still') {await el.decode().catch(() => {});+ if (!el.naturalWidth && !(await mustBeThere(row.src))) c.missing = true;c.nw = el.naturalWidth || stage.w; c.nh = el.naturalHeight || stage.h;} else if (kind === 'video') {el.muted = true; el.playsInline = true;rest(c);const facts = await factsOf(row.src);- if (!facts) await mustBeThere(row.src);+ if (!facts && !(await mustBeThere(row.src))) c.missing = true;c.native = facts?.duration ?? NaN;c.nw = facts?.w || stage.w; c.nh = facts?.h || stage.h;+ } else if (!(await mustBeThere(row.src))) {+ /* a page that is not there: its clip keeps its time, at the stage's size */+ c.missing = true;+ c.nw = stage.w; c.nh = stage.h;} else {- /* a film is a picture, never scrolled: a page a little larger than its frame shows no scrollbars (some browsers- always draw them; exports draw none) */- el.setAttribute('scrolling', 'no');- await mustBeThere(row.src);- const t0 = performance.now();- /* the page is loading since the file was read (filmStart in host.mjs gave it the stage's size to lay itself out for) */- while (!(el.contentWindow?.film && typeof el.contentWindow.film.frame === 'function')) {- if (performance.now() - t0 > 10000) throw new Error(`${row.src}: window.film with a frame() function did not appear`);- await new Promise((r) => setTimeout(r, 20));- }- const win = c.win = el.contentWindow;- c.child = win.film;- /* its own size, when it says one (else its clip's size, or the stage's: see settle) */- if (c.child.width > 0 && c.child.height > 0) c.own = { w: c.child.width, h: c.child.height };- await ready(c.child);+ /* opened to read its length (the host serves it unopened, see holdPages; filmStart gives it the stage's size) */+ c.row = row;+ await wakePage(c);/* a page without a duration has no end: its clip's #t= is its length, as a still's */const length = c.child.duration;c.native = Number.isFinite(length) && length > 0 ? length : undefined;+ /* more pages than are kept open: the ones read later close again until the playhead comes near (see near) */+ if ([...pagesAwake].filter((p) => p.child).length > PAGES_AWAKE) restPage(c);}settle(c, row, track, ti);progress++;@@ -602,7 +684,7 @@ async function draw(t, live) {if (live && !playing) { near(t, { only: true }); settleNear = setTimeout(() => near(t), 250); } else near(t, { exact: !live });await Promise.all(clips.map(async (c) => {if (c.kind === 'sound') return;- const on = !c.hidden && t >= c.at && t < c.end;+ const on = !c.hidden && !c.missing && t >= c.at && t < c.end;c.shown = on;const appears = on && c.el.style.visibility !== 'visible';c.el.style.visibility = on ? 'visible' : 'hidden';@@ -629,6 +711,12 @@ async function draw(t, live) {await showVideoAt(c.el, want, await frameOf(c));return;}+ /* a page closed while the playhead was far (see near): opened again, then drawn; one that will not open is the+ film's error in an exact frame, and shows nothing to a person watching */+ if (!c.child) {+ try { await wake(c); } catch (e) { if (live) return; throw new Error(`clip "${c.id}" (${c.src}): ${e?.message ?? e}`); }+ if (!c.child || !c.shown) return;+ }const local = sourceAt(c.span, t - c.at, c.row, c.native);c.win.filmHost?.time?.(local);/* a page's error says which clip and which of its own seconds, not only the film's t */@@ -689,6 +777,8 @@ function element(row) {shell.innerHTML = clipTag(row);const el = document.importNode(shell.content.firstElementChild, true);if (el.localName === 'video' || el.localName === 'audio') el.preload = 'none';+ /* a page opens when it is loaded (see wakePage), a few at a time */+ if (el.localName === 'iframe') el.removeAttribute('src');/* out of sight until it is placed and drawn: a page loading would show at its own size in the corner */el.style.visibility = 'hidden';return el;@@ -748,15 +838,15 @@ async function change(value, look) {picture changes at once, not first without them until that moment is drawn again */if (shownT != null) {for (const c of records) {- const on = c.el && !c.hidden && shownT >= c.at && shownT < c.end;- const ready = c.kind === 'still' || (c.kind === 'video' && c.el.readyState >= 2) || (c.kind === 'page' && made.has(c.id));+ const on = c.el && !c.hidden && !c.missing && shownT >= c.at && shownT < c.end;+ const ready = c.kind === 'still' || (c.kind === 'video' && c.el.readyState >= 2) || (c.kind === 'page' && made.has(c.id) && c.drawn);if (on && !c.shown && ready) { c.shown = true; c.el.style.visibility = 'visible'; fadeAt(c, shownT); }}}const now = new Set(records);for (const c of clips) {if (now.has(c)) continue;- if (c.kind === 'video') rest(c);+ if (c.kind === 'video' || c.kind === 'page') rest(c);c.node.remove();}clips.splice(0, clips.length, ...records);@@ -786,22 +876,24 @@ let changing = Promise.resolve(true);* state before its frame. A video on screen already keeps its picture until its new frame is drawn.*/async function cue(c, row, track, t, fresh) {- if (track.hidden || (c.kind !== 'video' && !(fresh && c.kind === 'page'))) return;+ if (track.hidden || c.missing || (c.kind !== 'video' && !(fresh && c.kind === 'page'))) return;if (c.kind === 'video' && c.shown && c.el.readyState >= 2) return;let span;try { span = clipSpan(row, c.native, row.id); } catch { return; }const at = row.at ?? 0;if (t < at || t >= at + span.length) return;- if (c.kind === 'page') {+ cueing.add(c);+ try {+ if (c.kind === 'video') { await glance(c, sourceAt(span, t - at, row)); return; }+ await wake(c);+ if (!c.child) return;const local = sourceAt(span, t - at, row, c.native);c.win.filmHost?.time?.(local);await c.child.frame(local);c.win.filmHost?.settle?.(local);+ c.drawn = true;override(c, c.overrides);- return;- }- cueing.add(c);- try { await glance(c, sourceAt(span, t - at, row)); } finally { cueing.delete(c); }+ } finally { cueing.delete(c); }}/** Where a clip's own pixel (x, y) is on the stage: its placement, as the browser applies it. */@@ -856,7 +948,8 @@ window.__filmEditor = {watch: (t) => draw(t, true),/*** For Studio's stage (studio/server/stage.js): the clips as loaded, a clip placed by a box not kept yet (null: by- * its own again), and `updated`, which the stage sets to hear of each update made in place.+ * its own again), `updated`, which the stage sets to hear of each update made in place, and `woke`, to hear of a page+ * opened again (see wakePage).*/stage: {clips: () => clips,@@ -872,6 +965,7 @@ window.__filmEditor = {place(c, c.row.box);},updated: null,+ woke: null,},/*** The film after an edit (`look`: its file's filmHead, when the edit came from the file; another one than this film@@ -896,7 +990,7 @@ window.__filmEditor = {for (const c of shown) {const local = matrixOf(c).inverse().transformPoint(new DOMPoint(x, y));if (local.x < 0 || local.y < 0 || local.x > c.w || local.y > c.h) continue;- if (c.kind !== 'page') return describe(c, null);+ if (c.kind !== 'page' || !c.win) return describe(c, null);/* the topmost element a person can see there: one faded out or hidden (a line still to come) is passed over */const page = c.win.document;const el = page.elementsFromPoint(local.x, local.y).find((e) => e !== page.body && e !== page.documentElement && seen(c.win, e));diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjsindex 3f1e7cf..848accc 100644--- a/packages/openfilm/src/timeline.test.mjs+++ b/packages/openfilm/src/timeline.test.mjs@@ -192,6 +192,37 @@ test('a film that cannot load says why when its host awaits `ready`, and is no u});+test('a missing file stops a film, said by its name; an editor\'s preview (film-missing=skip) plays on past it', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-missing-'));+ writeFileSync(join(dir, 'here.html'), page('here', 2));+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [+ { src: 'gone.html', id: 'gone', time: [0, 2] },+ { src: 'here.html', id: 'here', at: 2 },+ ] }] }));+ const site = await serve(dir);+ const browser = await launch();+ try {+ const strict = await browser.newPage();+ await strict.goto(`${site.url}/film.html`);+ await strict.waitForFunction(() => Boolean(window.film));+ assert.equal(await strict.evaluate(() => window.film.ready.then(() => null, (e) => e.message)), 'gone.html: there is no such file');+ const preview = await browser.newPage();+ await preview.goto(`${site.url}/film.html?film-missing=skip`);+ await preview.waitForFunction(() => Boolean(window.film));+ assert.equal(await preview.evaluate(() => window.film.ready.then(() => null, (e) => e.message)), null);+ /* the missing clip keeps its time and the film its length; it is never shown, the clip after it is */+ assert.deepEqual(await preview.evaluate(() => window.__filmSpans().map((c) => [c.id, c.at, c.end])), [['gone', 0, 2], ['here', 2, 4]]);+ assert.equal(await preview.evaluate(() => window.film.duration), 4);+ await preview.evaluate(() => window.film.frame(1));+ assert.deepEqual(await preview.evaluate(() => [...document.querySelectorAll('iframe')].map((el) => el.style.visibility)), ['hidden', 'hidden']);+ await preview.evaluate(() => window.film.frame(3));+ assert.deepEqual(await preview.evaluate(() => [...document.querySelectorAll('iframe')].map((el) => el.style.visibility)), ['hidden', 'visible']);+ } finally {+ await browser.close();+ await site.close();+ }+});+const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();/** A folder with two short videos (a numbered test picture, `seconds` long at 10 fps) and a sound. */@@ -498,6 +529,38 @@ test('a text override with line breaks: all the words of an element of <br>s, a}});+test('a film of many pages keeps only a few open: one far from the playhead is closed, and opened again draws as before', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-pages-'));+ const clips = [];+ for (let i = 0; i < 12; i++) {+ writeFileSync(join(dir, `p${i}.html`), `<!doctype html><body style="margin:0"><p id="w"></p><p id="o">own</p>+<script>window.film={duration:1,frame(t){document.getElementById('w').textContent='p${i} '+t.toFixed(2)}}</script></body>`);+ clips.push({ id: `p${i}`, src: `p${i}.html`, at: i, ...(i === 11 ? { overrides: [{ at: '#o', text: 'tweaked' }] } : {}) });+ }+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips }] }));+ const s = await open(dir);+ const now = () => s.film.page.evaluate(() => [...document.querySelectorAll('iframe')].map((f) => {+ const doc = f.contentWindow?.film ? f.contentDocument : null;+ return doc ? `${doc.getElementById('w').textContent}|${doc.getElementById('o').textContent}` : null;+ }));+ try {+ assert.equal(s.film.meta.duration, 12, 'every page\'s length is known, the closed ones\' too');+ assert.ok((await now()).filter(Boolean).length <= 8, 'loaded: no more than 8 open');+ await s.film.seek(11.5);+ let pages = await now();+ assert.equal(pages[11], 'p11 0.50|tweaked', 'opened, drawn at its moment, its tweak on it');+ assert.ok(pages.filter(Boolean).length <= 8, `no more than 8 open: ${pages}`);+ await s.film.seek(0.25);+ pages = await now();+ assert.equal(pages[0], 'p0 0.25|own');+ assert.ok(pages.filter(Boolean).length <= 8, `${pages}`);+ await s.film.seek(11.75);+ assert.equal((await now())[11], 'p11 0.75|tweaked', 'closed and opened again: the same page');+ } finally {+ await s.close();+ }+});+test('a host waits for a film as long as it keeps loading; a page that never gets further fails in time', { timeout: 60_000 }, async () => {const dir = mkdtempSync(join(tmpdir(), 'of-progress-'));/* five pages ready one after another, 0.5 s apart: 2.5 s in all, longer than the host waits without news */diff --git a/packages/openfilm/studio/server/prefs.mjs b/packages/openfilm/studio/server/prefs.mjsindex 65865a8..8c2411b 100644--- a/packages/openfilm/studio/server/prefs.mjs+++ b/packages/openfilm/studio/server/prefs.mjs@@ -3,27 +3,30 @@* Studio's own preferences, the same for every project (`prefs.json` in Studio's home): what the editor does on this* computer, not what a film is. A project's own settings are project-settings.mjs.*- * proxies light copies of heavy footage for the preview (proxies.mjs): on, and how tall+ * proxies light copies of heavy footage for the preview (proxies.mjs): on, and how tall+ * seenVersion the version whose "what's new" was last shown (null: none yet, a new install shows none)*/import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { studioHome } from './projects.mjs';-/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 } }} Prefs */+/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null }} Prefs */-/** As CapCut has them: on, at 720p. */-export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 } });+/** Proxies as CapCut has them: on, at 720p. */+export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null });+const VERSION = /^\d+\.\d+\.\d+(?:-[\w.]+)?$/;const HEIGHTS = [540, 720, 1080];/** What is kept, each field checked; anything missing or wrong is its default. @param {unknown} raw @returns {Prefs} */export function prefsOf(raw) {- const p = /** @type {{ proxies?: { on?: unknown, height?: unknown } } | null} */ (raw && typeof raw === 'object' ? raw : null);+ const p = /** @type {{ proxies?: { on?: unknown, height?: unknown }, seenVersion?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);const height = Number(p?.proxies?.height);return {proxies: {on: typeof p?.proxies?.on === 'boolean' ? p.proxies.on : DEFAULT_PREFS.proxies.on,height: /** @type {540 | 720 | 1080} */ (HEIGHTS.includes(height) ? height : DEFAULT_PREFS.proxies.height),},+ seenVersion: typeof p?.seenVersion === 'string' && VERSION.test(p.seenVersion) ? p.seenVersion : null,};}@@ -37,7 +40,7 @@ export function readPrefs() {/** Change some of them (a field at a time); returns them all. @param {unknown} patch @returns {Prefs} */export function writePrefs(patch) {const now = readPrefs();- const asked = /** @type {{ proxies?: object }} */ (patch && typeof patch === 'object' ? patch : {});+ const asked = /** @type {{ proxies?: object, seenVersion?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});const next = prefsOf({ ...now, ...asked, proxies: { ...now.proxies, ...(asked.proxies ?? {}) } });const at = file();mkdirSync(studioHome(), { recursive: true });diff --git a/packages/openfilm/studio/server/prefs.test.mjs b/packages/openfilm/studio/server/prefs.test.mjsnew file mode 100644index 0000000..a682768--- /dev/null+++ b/packages/openfilm/studio/server/prefs.test.mjs@@ -0,0 +1,12 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { prefsOf } from './prefs.mjs';++test('the version whose notes were last shown: a version, else none', () => {+ assert.equal(prefsOf(null).seenVersion, null, 'a new install has none');+ assert.equal(prefsOf({ seenVersion: '0.1.6' }).seenVersion, '0.1.6');+ assert.equal(prefsOf({ seenVersion: '1.0.0-beta.2' }).seenVersion, '1.0.0-beta.2');+ assert.equal(prefsOf({ seenVersion: '../../etc' }).seenVersion, null);+ assert.equal(prefsOf({ seenVersion: 7 }).seenVersion, null);+ assert.deepEqual(prefsOf({ seenVersion: '0.1.6' }).proxies, { on: true, height: 720 }, 'the rest as before');+});diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjsindex 56aefb6..8801532 100644--- a/packages/openfilm/studio/server/server.test.mjs+++ b/packages/openfilm/studio/server/server.test.mjs@@ -200,7 +200,7 @@ test('the preview plays heavy footage from its proxy once made; what the file ismkdirSync(join(project.path, 'assets'), { recursive: true });const big = join(project.path, 'assets', 'big.mp4');execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=2560x1440:rate=25:duration=1', '-pix_fmt', 'yuv420p', big]);- assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 } });+ assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 }, seenVersion: null });let answer;for (const end = Date.now() + 30_000; answer?.states?.['assets/big.mp4']?.state !== 'ready' && Date.now() < end;) {answer = await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json();@@ -213,7 +213,7 @@ test('the preview plays heavy footage from its proxy once made; what the file isassert.ok(played > 0 && played !== statSync(big).size, 'the proxy');assert.equal(await size('?film-facts=1'), statSync(big).size, 'what the file is: the file');/* off: the original, and no proxy asked for */- assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 } });+ assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 }, seenVersion: null });assert.equal(await size(), statSync(big).size);assert.deepEqual((await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json()).states, {});await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: true } } });diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.jsindex 367a19f..a966f6a 100644--- a/packages/openfilm/studio/server/stage.js+++ b/packages/openfilm/studio/server/stage.js@@ -87,7 +87,7 @@for (const c of shown()) {if (pictures && c.kind === 'page') continue;const p = matrixOf(c).inverse().transformPoint(new DOMPoint(x, y));- if (p.x >= 0 && p.y >= 0 && p.x <= c.w && p.y <= c.h && shownAt(c.el, p.x, p.y, c.w, c.h)) return c;+ if (p.x >= 0 && p.y >= 0 && p.x <= c.w && p.y <= c.h) return c;}return null;};@@ -266,258 +266,6 @@const dy = y - f.cy;return Math.abs(dx * Math.cos(rad) - dy * Math.sin(rad)) <= f.w / 2 + 0.5 && Math.abs(dx * Math.sin(rad) + dy * Math.cos(rad)) <= f.h / 2 + 0.5;};- /* ── what a mask or a crop cuts away: nothing is found there (as in Photoshop and Figma) ── */- /*- * A point is tested against the box's `clip-path` (inset, circle, ellipse, polygon) and its `mask-image`, drawn- * small on a canvas the way CSS draws it (linear and radial gradients, inline SVG, `mask-composite`) and read at the- * point. A mask this cannot draw (a picture file, a repeating gradient, a size of its own) leaves the box whole.- */- const MASK_SIDE = 96;- const masks = new Map();- const svgs = new Map();- /** A list's top-level parts: commas inside parentheses and quotes stay. */- const splitTop = (v, sep = ',') => {- const out = [];- let depth = 0;- let quote = '';- let from = 0;- for (let i = 0; i < v.length; i++) {- const ch = v[i];- if (quote) { if (ch === quote && v[i - 1] !== '\\') quote = ''; continue; }- if (ch === '"' || ch === "'") quote = ch;- else if (ch === '(') depth++;- else if (ch === ')') depth--;- else if (depth === 0 && (sep === ' ' ? /\s/.test(ch) : ch === sep)) { out.push(v.slice(from, i).trim()); from = i + 1; }- }- out.push(v.slice(from).trim());- return out.filter(Boolean);- };- /** A length or % (of `of`), else NaN. */- const lengthIn = (v, of) => {- const m = /^(-?\d*\.?\d+(?:e-?\d+)?)(px|%)?$/.exec(v ?? '');- if (!m) return NaN;- return m[2] === '%' ? (Number(m[1]) / 100) * of : Number(m[1]);- };- const isColor = (v) => /^(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(|^#|^(transparent|black|white|currentcolor)\b/i.test(v);- /** Color stops at their positions along a line `L` long: missing positions spread as CSS does; hints dropped. */- const stopsOf = (parts, L) => {- const stops = [];- for (const p of parts) {- const words = splitTop(p, ' ');- if (!words.length || !isColor(words[0])) continue;- if (words.length === 1) stops.push({ color: words[0], at: NaN });- for (const w of words.slice(1)) stops.push({ color: words[0], at: lengthIn(w, L) / L });- }- if (stops.length < 2) return null;- if (Number.isNaN(stops[0].at)) stops[0].at = 0;- if (Number.isNaN(stops[stops.length - 1].at)) stops[stops.length - 1].at = 1;- for (let i = 1; i < stops.length; i++) {- if (Number.isNaN(stops[i].at)) {- let j = i;- while (Number.isNaN(stops[j].at)) j++;- for (let k = i; k < j; k++) stops[k].at = stops[i - 1].at + ((stops[j].at - stops[i - 1].at) * (k - i + 1)) / (j - i + 1);- }- stops[i].at = Math.max(stops[i].at, stops[i - 1].at);- }- return stops;- };- const addStops = (g, stops, lo, hi) => { for (const s of stops) g.addColorStop(Math.min(1, Math.max(0, (s.at - lo) / (hi - lo || 1))), s.color); };- const ANGLES = { top: 0, right: 90, bottom: 180, left: 270 };- const angleOf = (v, W, H) => {- const m = /^(-?\d*\.?\d+)(deg|turn|rad|grad)$/.exec(v);- if (m) return Number(m[1]) * { deg: 1, turn: 360, rad: 180 / Math.PI, grad: 0.9 }[m[2]];- const to = /^to\s+(.+)$/.exec(v)?.[1]?.split(/\s+/);- if (!to) return null;- if (to.length === 1) return ANGLES[to[0]] ?? null;- const sx = to.includes('right') ? 1 : -1;- const sy = to.includes('bottom') ? 1 : -1;- return (Math.atan2(sx * H, -sy * W) * 180) / Math.PI;- };- /** One mask layer drawn on `ctx` (W × H): false when it cannot be, null while its picture loads. */- const drawLayer = (ctx, layer, W, H) => {- const fn = /^([a-z-]+)\((.*)\)$/s.exec(layer);- if (!fn) return layer === 'none' ? true : false;- const [, name, body] = fn;- if (name === 'url') {- const src = body.trim().replace(/^(['"])(.*)\1$/s, '$2');- if (!src.startsWith('data:image/svg+xml')) return false;- let img = svgs.get(src);- if (!img) { img = new Image(); img.src = src; svgs.set(src, img); }- if (!img.complete) return null;- if (!img.naturalWidth && !img.naturalHeight && img.width === 0) return false;- ctx.drawImage(img, 0, 0, W, H);- return true;- }- const parts = splitTop(body);- if (name === 'linear-gradient') {- let deg = 180;- if (!isColor(parts[0])) { const a = angleOf(parts.shift(), W, H); if (a == null) return false; deg = a; }- const r = (deg * Math.PI) / 180;- const dx = Math.sin(r);- const dy = -Math.cos(r);- const L = Math.abs(W * dx) + Math.abs(H * dy);- const stops = stopsOf(parts, L);- if (!stops) return false;- const lo = Math.min(0, stops[0].at);- const hi = Math.max(1, stops[stops.length - 1].at);- const x0 = W / 2 - (dx * L) / 2;- const y0 = H / 2 - (dy * L) / 2;- const g = ctx.createLinearGradient(x0 + dx * L * lo, y0 + dy * L * lo, x0 + dx * L * hi, y0 + dy * L * hi);- addStops(g, stops, lo, hi);- ctx.fillStyle = g;- ctx.fillRect(0, 0, W, H);- return true;- }- if (name === 'radial-gradient') {- let shape = 'ellipse';- let size = 'farthest-corner';- let cx = W / 2;- let cy = H / 2;- let rx = NaN;- let ry = NaN;- if (!isColor(parts[0])) {- const [before, after] = parts.shift().split(/\s*\bat\b\s*/);- if (after) {- const pos = after.split(/\s+/);- const KEY = { left: 0, top: 0, center: 50, right: 100, bottom: 100 };- const ax = (w, of) => (w in KEY ? (KEY[w] / 100) * of : lengthIn(w, of));- const [px, py = 'center'] = pos[0] === 'top' || pos[0] === 'bottom' ? [pos[1] ?? 'center', pos[0]] : pos;- cx = ax(px, W);- cy = ax(py, H);- }- const words = (before ?? '').split(/\s+/).filter(Boolean);- const lens = words.filter((w) => !/^(circle|ellipse|closest-side|farthest-side|closest-corner|farthest-corner)$/.test(w));- if (words.includes('circle') || lens.length === 1) shape = 'circle';- size = words.find((w) => /-(side|corner)$/.test(w)) ?? size;- if (lens.length === 1) { rx = lengthIn(lens[0], W); ry = rx; }- if (lens.length === 2) { rx = lengthIn(lens[0], W); ry = lengthIn(lens[1], H); }- }- if (Number.isNaN(cx) || Number.isNaN(cy)) return false;- if (Number.isNaN(rx)) {- const sides = [cx, W - cx, cy, H - cy];- const near = size.startsWith('closest');- const pick = near ? Math.min : Math.max;- if (shape === 'circle') {- rx = size.endsWith('side') ? pick(...sides) : pick(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot(x - cx, y - cy)));- ry = rx;- } else {- rx = pick(sides[0], sides[1]);- ry = pick(sides[2], sides[3]);- if (size.endsWith('corner')) { rx *= Math.SQRT2; ry *= Math.SQRT2; }- }- }- if (!(rx > 0 && ry > 0)) return false;- const stops = stopsOf(parts, rx);- if (!stops) return false;- const hi = Math.max(1, stops[stops.length - 1].at);- ctx.save();- ctx.translate(cx, cy);- ctx.scale(1, ry / rx);- const g = ctx.createRadialGradient(0, 0, 0, 0, 0, rx * hi);- addStops(g, stops.map((s) => ({ ...s, at: Math.max(0, s.at) })), 0, hi);- ctx.fillStyle = g;- ctx.fillRect(-cx, -cy * (rx / ry), W, H * (rx / ry));- ctx.restore();- return true;- }- return false;- };- const COMPOSITE = { add: 'source-over', subtract: 'source-out', intersect: 'destination-in', exclude: 'xor' };- /** The mask's alpha all over a W × H box, small: null when it cannot be drawn (or not yet). */- const maskPixels = (image, composite, W, H) => {- const key = `${image}|${composite}|${Math.round(W)}x${Math.round(H)}`;- if (masks.has(key)) return masks.get(key);- const k = MASK_SIDE / Math.max(W, H);- const w = Math.max(1, Math.round(W * k));- const h = Math.max(1, Math.round(H * k));- const layers = splitTop(image);- const ops = splitTop(composite || 'add');- const out = document.createElement('canvas');- out.width = w;- out.height = h;- const octx = out.getContext('2d', { willReadFrequently: true });- if (masks.size > 64) masks.clear();- for (let i = layers.length - 1; i >= 0; i--) {- const one = document.createElement('canvas');- one.width = w;- one.height = h;- const ctx = one.getContext('2d');- ctx.scale(w / W, h / H);- const drawn = drawLayer(ctx, layers[i], W, H);- /* a picture still loading is tried again next time; one this cannot draw leaves the box whole */- if (drawn === null) return null;- if (drawn === false) { masks.set(key, null); return null; }- octx.globalCompositeOperation = i === layers.length - 1 ? 'source-over' : COMPOSITE[ops[i % ops.length]] ?? 'source-over';- octx.drawImage(one, 0, 0);- }- const value = { w, h, k: [w / W, h / H], data: octx.getImageData(0, 0, w, h).data };- masks.set(key, value);- return value;- };- /** Whether `clip-path` keeps point (x, y) of a W × H box (a shape this does not read keeps all of it). */- const clipKeeps = (clip, x, y, W, H) => {- const fn = /^(inset|circle|ellipse|polygon)\((.*)\)/s.exec(clip ?? '');- if (!fn) return true;- const [, name, body] = fn;- if (name === 'inset') {- const v = body.split(/\s+round\s+/)[0].trim().split(/\s+/);- const [t, r = t, b = t, l = r] = v;- return x >= lengthIn(l, W) && x <= W - lengthIn(r, W) && y >= lengthIn(t, H) && y <= H - lengthIn(b, H);- }- if (name === 'polygon') {- const pts = splitTop(body).filter((p) => !/^(nonzero|evenodd)$/.test(p)).map((p) => p.split(/\s+/)).map(([px, py]) => [lengthIn(px, W), lengthIn(py, H)]);- let inside = false;- for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {- const [xi, yi] = pts[i];- const [xj, yj] = pts[j];- if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;- }- return inside;- }- const [size, pos] = body.split(/\s*\bat\b\s*/);- const [px = '50%', py = '50%'] = (pos ?? '').split(/\s+/).filter(Boolean).map((w) => ({ left: '0%', top: '0%', center: '50%', right: '100%', bottom: '100%' }[w] ?? w));- const cx = lengthIn(px, W);- const cy = lengthIn(py, H);- const lens = (size ?? '').split(/\s+/).filter((w) => w && !/side$/.test(w));- const rx = name === 'circle' ? lengthIn(lens[0] ?? '', Math.hypot(W, H) / Math.SQRT2) : lengthIn(lens[0] ?? '', W);- const ry = name === 'circle' ? rx : lengthIn(lens[1] ?? '', H);- if (!(rx > 0 && ry > 0)) return true;- return ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 <= 1;- };- /** Whether point (x, y) of element `el`'s W × H box is drawn: not cut away by its crop or mask. */- const shownAt = (el, x, y, W, H) => {- const s = view(el).getComputedStyle(el);- if (!clipKeeps(s.clipPath, x, y, W, H)) return false;- const image = s.maskImage || s.webkitMaskImage;- if (!image || image === 'none') return true;- const px = maskPixels(image, s.maskComposite || 'add', W, H);- if (!px) return true;- const i = Math.min(px.w - 1, Math.max(0, Math.floor(x * px.k[0])));- const j = Math.min(px.h - 1, Math.max(0, Math.floor(y * px.k[1])));- return px.data[(j * px.w + i) * 4 + 3] > 64;- };- /**- * Whether a page's point (page px) is cut away from `el`: by its own crop or mask, or by one of its parents' (theirs,- * or a parent that clips what overflows it).- */- const cutAway = (el, x, y) => {- const root = el.ownerDocument.documentElement;- for (let node = el; node && node !== root && node !== el.ownerDocument.body; node = node.parentElement) {- const s = css(node);- const clips = node !== el && s.overflow !== 'visible';- if (!clips && s.clipPath === 'none' && (!s.maskImage || s.maskImage === 'none') && (!s.webkitMaskImage || s.webkitMaskImage === 'none')) continue;- const f = frameOf(node);- if (!(f.w > 0 && f.h > 0)) continue;- const rad = (-f.r * Math.PI) / 180;- const dx = x - f.cx;- const dy = y - f.cy;- const lx = dx * Math.cos(rad) - dy * Math.sin(rad) + f.w / 2;- const ly = dx * Math.sin(rad) + dy * Math.cos(rad) + f.h / 2;- if (clips && (lx < 0 || ly < 0 || lx > f.w || ly > f.h)) return true;- if (!shownAt(node, lx, ly, f.w, f.h)) return true;- }- return false;- };/** Override px → page px: `translate` is in the parent's coordinates, so the parent's own scale counts. */const localScale = (el) => {for (let p = el.parentElement; p; p = p.parentElement) {@@ -774,11 +522,17 @@const kind = kindOf(el);if (!kind || invisible(el)) return;if (!includeLocked && lockedOf(c, el)) return;- if (cutAway(el, x, y)) return;hits.push({ el, kind, rect, frame, area: frame.w * frame.h, order });});return hits.sort((a, b) => a.area - b.area || b.order - a.order);};+ /**+ * A box that fills its whole page is the page's backdrop, as a frame's fill in Figma: a click there takes the clip+ * (moving the picture), not the box (which would only move what is inside the page). It is selected in Layers, or+ * with Alt, and once in hand a click on it keeps it.+ */+ const backdrop = (c, hit) => hit.kind === 'box' && !hit.frame.r+ && hit.rect.left <= 1 && hit.rect.top <= 1 && hit.rect.right >= c.win.innerWidth - 1 && hit.rect.bottom >= c.win.innerHeight - 1;/** A layer inside a group is the group until the group is entered (a layer of it is in hand). */const liftToGroup = (hit, current) => {const groups = [];@@ -1047,10 +801,11 @@if ((EDITOR_KEYS.has(e.key) && !mod) || (mod && (k === 'z' || (k === 'a' && !e.shiftKey && !e.altKey) || (e.shiftKey && (k === 'h' || k === 'l'))))) e.preventDefault();post({ type: 'stage-event', event: 'key', key: e.key, code: e.code, repeat: e.repeat, metaKey: e.metaKey, ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey });};+ /* by document: a page closed and opened again (the timeline does, far from the playhead) is a new one to hear */const listening = new WeakSet();const listen = (win) => {- if (!win || listening.has(win)) return;- listening.add(win);+ if (!win?.document || listening.has(win.document)) return;+ listening.add(win.document);win.addEventListener('keydown', onKey, true);};const listenAll = () => { listen(window); for (const c of clips()) if (c.win) listen(c.win); };@@ -1061,7 +816,7 @@listenAll();const h = hooks();/* an update may have added pages: their keys are heard too */- if (h) h.updated = () => { listenAll(); updated(); };+ if (h) { h.updated = () => { listenAll(); updated(); }; h.woke = listenAll; }})();/* ── restacking ── */@@ -1201,7 +956,7 @@if (enter && current) current = current.firstElementChild;const cycle = nodeOf(cycleFrom);let hit;- if (!cycle || all.length < 2) hit = all[0] ? liftToGroup(all[0], current) : null;+ if (!cycle || all.length < 2) hit = all[0] && (cycle || all[0].el === current || !backdrop(c, all[0])) ? liftToGroup(all[0], current) : null;else hit = all[(all.findIndex((h) => h.el === cycle) + 1) % all.length] ?? all[0];if (!hit) return null;if (detail) return describe(c, hit.el, hit.kind);diff --git a/packages/openfilm/studio/server/stage.test.mjs b/packages/openfilm/studio/server/stage.test.mjsindex 665bdd8..fee9c67 100644--- a/packages/openfilm/studio/server/stage.test.mjs+++ b/packages/openfilm/studio/server/stage.test.mjs@@ -1,80 +1,63 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { readFileSync } from 'node:fs';-import { launch } from '../../src/host.mjs';+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { HOST_FLAG, folderFiles, launch } from '../../src/host.mjs';+import { filmHtml } from '../../src/film-doc.mjs';-/* the stage script in a page of its own, one page clip on it: asked as the editor asks, from the page's own origin */-const ORIGIN = 'http://stage.test';-const STAGE = readFileSync(new URL('./stage.js', import.meta.url), 'utf8').replace('__EDITOR__', JSON.stringify(ORIGIN));-const PAGE = `<!doctype html><body style="margin:0;background:#000">-<div id="a" style="position:absolute;left:20px;top:20px;width:100px;height:100px;background:#f00"></div>-<div id="b" style="position:absolute;left:150px;top:50px;width:100px;height:100px;background:#0f0">-<div id="c" style="position:absolute;left:80px;top:0;width:100px;height:100px"></div></div></body>`;-const HOST = `<!doctype html><body style="margin:0">-<iframe id="p" style="position:absolute;left:0;top:0;width:400px;height:200px;border:0;visibility:visible" srcdoc="${PAGE.replace(/"/g, '"')}"></iframe>-<script>- const el = document.getElementById('p');- const clips = [{ id: 'p', kind: 'page', el, w: 400, h: 200, ti: 0, overrides: [], get win() { return el.contentWindow; } }];- window.__filmEditor = { stage: { clips: () => clips } };- window.film = { ready: new Promise((r) => el.addEventListener('load', r)) };-</script>-<script>${STAGE}</script></body>`;+const STAGE = readFileSync(new URL('./stage.js', import.meta.url), 'utf8');-async function stage() {+/** A film served with Studio's stage in it, the page itself standing in for the editor (its own origin). */+async function stageOf(dir) {+ let files = null;+ const server = createServer((req, res) => {+ const url = new URL(req.url, 'http://x');+ if (!files(req, res, url.pathname, url.searchParams)) res.writeHead(403).end();+ });+ await new Promise((ok) => server.listen(0, '127.0.0.1', ok));+ const origin = `http://127.0.0.1:${server.address().port}`;+ files = folderFiles(dir, { timelineInject: `<script>${HOST_FLAG}</script><script>${STAGE.replaceAll('__EDITOR__', JSON.stringify(origin))}</script>` });const browser = await launch();- const page = await browser.newPage();- await page.route(`${ORIGIN}/**`, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));- await page.goto(`${ORIGIN}/`);- await page.evaluate(() => window.film.ready);- const ask = (op, args) => page.evaluate(([op, args]) => new Promise((resolve) => {- const seq = Math.random();- addEventListener('message', function on(e) {- if (e.data?.source !== 'openfilm-film' || e.data.seq !== seq) return;- removeEventListener('message', on);- resolve(e.data.result);- });- postMessage({ source: 'openfilm-studio', type: 'stage', seq, op, ...args }, '*');- }), [op, args]);- const style = (sel, css) => page.evaluate(([sel, css]) => {- const el = sel === 'clip' ? document.getElementById('p') : document.getElementById('p').contentDocument.querySelector(sel);- el.style.cssText += css;- }, [sel, css]);- const layer = async (x, y) => (await ask('hit', { x, y, detail: true }))?.at ?? null;- return { browser, ask, style, layer };+ const page = await browser.newPage({ viewport: { width: 320, height: 180 } });+ await page.goto(`${origin}/film.html`);+ await page.evaluate(async () => { await window.film.ready; await window.film.frame(0.5); });+ let seq = 0;+ /** Ask the stage what the editor asks it. */+ const ask = (op, args) => page.evaluate(({ op, args, seq }) => new Promise((done) => {+ const hear = (e) => {+ if (e.data?.source !== 'openfilm-film' || e.data.type !== 'stage' || e.data.seq !== seq) return;+ window.removeEventListener('message', hear);+ done(e.data.error ? { error: e.data.error } : e.data.result);+ };+ window.addEventListener('message', hear);+ window.postMessage({ source: 'openfilm-studio', type: 'stage', seq, op, ...args }, '*');+ }), { op, args, seq: ++seq });+ return { ask, close: async () => { await browser.close(); server.closeAllConnections?.(); server.close(); } };}-test('what a mask or a crop cuts away is not found: the clip and its layers', { timeout: 60_000 }, async () => {- const { browser, ask, style, layer } = await stage();+test('a click on a page\'s backdrop (a box filling the page) takes the clip, not the box; a smaller box is taken', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-backdrop-'));+ writeFileSync(join(dir, 'logistics.html'), `<!doctype html><body style="margin:0">+<div id="root" style="position:absolute;inset:0;background:#f7f1e9">+ <h1 id="title" style="position:absolute;left:20px;top:20px;margin:0;font:700 24px sans-serif">Every parcel</h1>+ <div id="card" style="position:absolute;left:200px;top:100px;width:80px;height:50px;background:#f60"></div>+</div>+<script>window.film={duration:2,frame(){}}</script></body>`);+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'logistics', src: 'logistics.html' }] }] }));+ const stage = await stageOf(dir);try {- assert.equal(await ask('clipAt', { x: 10, y: 10 }), 'p');- assert.equal(await layer(30, 30), '#a');-- /* the clip's circle: its corners are not the clip, nor its layers */- await style('clip', 'mask-image: radial-gradient(25% 50% at 50% 50%, #000 99%, transparent 100%)');- assert.equal(await ask('clipAt', { x: 10, y: 10 }), null);- assert.equal(await layer(30, 30), null);- assert.equal(await ask('clipAt', { x: 200, y: 100 }), 'p');- assert.equal(await layer(200, 100), '#b');- assert.equal(await layer(115, 100), '#a');-- /* a crop (clip-path) cuts the same way */- await style('clip', 'mask-image: none; clip-path: inset(0 50% 0 0)');- assert.equal(await ask('clipAt', { x: 300, y: 100 }), null);- assert.equal(await ask('clipAt', { x: 100, y: 100 }), 'p');-- /* a layer's own mask, two layers intersected: only where both show */- await style('clip', 'clip-path: none');- await style('#a', 'mask-image: linear-gradient(to right, #000 50%, transparent 50%), linear-gradient(#000 50%, transparent 50%); mask-composite: intersect');- assert.equal(await layer(40, 40), '#a');- assert.equal(await layer(100, 40), null);- assert.equal(await layer(40, 100), null);-- /* a parent that clips what overflows it: its child past its edge is not found there */- await style('#b', 'overflow: hidden');- await style('#c', 'background: #00f');- assert.equal(await layer(240, 100), '#c');- assert.equal(await layer(300, 100), null);+ assert.equal(await stage.ask('hit', { x: 150, y: 160, detail: true }), null, 'the empty part: no layer, so the clip is taken');+ assert.equal((await stage.ask('hit', { x: 40, y: 30, detail: true }))?.label, 'Every parcel');+ const card = await stage.ask('hit', { x: 240, y: 125, detail: true });+ assert.equal(card?.kind, 'box', 'a box smaller than the page is a layer');+ /* with Alt, the layers under the point in turn: the backdrop is one of them, and once in hand a click keeps it */+ const root = await stage.ask('hit', { x: 240, y: 125, cycleFrom: card.handle, detail: true });+ assert.equal(root?.kind, 'box');+ assert.notEqual(root.handle, card.handle);+ assert.equal((await stage.ask('hit', { x: 150, y: 160, from: root.handle, detail: true }))?.handle, root.handle);} finally {- await browser.close();+ await stage.close();}});diff --git a/packages/openfilm/studio/ui/src/App.tsx b/packages/openfilm/studio/ui/src/App.tsxindex 648a82f..f067787 100644--- a/packages/openfilm/studio/ui/src/App.tsx+++ b/packages/openfilm/studio/ui/src/App.tsx@@ -11,6 +11,7 @@ import { ProjectView } from './components/ProjectView';import { BrandLoadingScreen } from './components/BrandLoadingScreen';import { ProjectsPopover } from './components/ProjectsLibrary';import { studioHost } from './lib/host';+import { WhatsNew } from './components/WhatsNew';/*** `to` with this page's key in its address (the server puts it there): the address bar is what a person copies, and@@ -63,7 +64,7 @@ export function App() {<ProjectsPopover open currentProjectId="" onOpen={(next) => go(`/projects/${next}`)} onCurrentRemoved={() => {}} /></div>);- return <>{page}<ConnectionNotice /></>;+ return <>{page}<ConnectionNotice /><WhatsNew /></>;}/**diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.tsindex f1f95c4..4c620b9 100644--- a/packages/openfilm/studio/ui/src/api.ts+++ b/packages/openfilm/studio/ui/src/api.ts@@ -75,7 +75,7 @@ async function call<T>(path: string, init: RequestInit & { json?: unknown } = {}const p = (id: string) => `projects/${encodeURIComponent(id)}`;/** Studio's own preferences, the same for every project (studio/server/prefs.mjs). */-export interface StudioPrefs { proxies: { on: boolean; height: 540 | 720 | 1080 } }+export interface StudioPrefs { proxies: { on: boolean; height: 540 | 720 | 1080 }; seenVersion: string | null }/** Said on the window when they change, for what plays by them (the preview's proxies). */export const PREFS_EVENT = 'openfilm:prefs';@@ -84,7 +84,7 @@ export const api = {version: (check = false) => call<StudioVersion>(`version${check ? '?check=1' : ''}`),projects: () => call<{ projects: Project[] }>('projects').then((r) => r.projects),prefs: () => call<StudioPrefs>('prefs'),- setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']> }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {+ setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {window.dispatchEvent(new Event(PREFS_EVENT));return prefs;}),diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsxindex 433a611..722b975 100644--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx@@ -1412,6 +1412,8 @@ function ClipPanel({{...(onPreviewClip ? { onPreview: (patch: Partial<MgTransform> | null) => onPreviewClip(loc!, patch) } : {})}/>) : null}+ {/* the fades right under the place: used on most clips */}+ {docLoc && block.clipId ? <FadeSection t={t} blocks={[block]} fades={fades} commit={commit} /> : null}{look ? (<><CropSection@@ -1439,7 +1441,6 @@ function ClipPanel({</>) : null}{block.anchor?.move || block.anchor?.resize === 'end' ? <TimingSection t={t} block={block} onMain={onMain} commit={commit} /> : null}- {docLoc && block.clipId ? <FadeSection t={t} blocks={[block]} fades={fades} commit={commit} /> : null}{blockHasVolume(block) ? (<Section id="sound" title={t('inspector.sound')}><VolumeField value={linearVolumeOf(block)} t={t} onCommit={(apply) => commit(volumeEdits([block], apply))} />@@ -1950,6 +1951,7 @@ function MultiClipPanel({</Row></Section>) : null}+ {onEdit && blocks.every((b) => b.clipId && b.loc && parseFilmDocLoc(b.loc) != null) ? <FadeSection t={t} blocks={blocks} fades={fades} commit={commit} /> : null}{look ? (<><AppearanceSection look={look} t={t} radius />@@ -1958,7 +1960,6 @@ function MultiClipPanel({<AdjustSection look={look} t={t} /></>) : null}- {onEdit && blocks.every((b) => b.clipId && b.loc && parseFilmDocLoc(b.loc) != null) ? <FadeSection t={t} blocks={blocks} fades={fades} commit={commit} /> : null}{volumeAll ? (<Section id="sound" title={t('inspector.sound')}><VolumeField value={volume} t={t} onCommit={(apply) => commit(volumeEdits(blocks, apply))} />diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsxindex 31f14e4..edb5a50 100644--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx@@ -100,6 +100,10 @@ const staleBucket = (timeMs: number): number => Math.round(timeMs / STALE_BUCKET/* the key a region is drawn with: ⌘ on a Mac (its Ctrl-click is a right click), Ctrl elsewhere */const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);const REGION_KEY = MAC ? 'Meta' : 'Control';+/** What a press is read for: the overlay's own, or one on the dark around the picture. */+type PressEvent = Pick<PointerEvent, 'button' | 'timeStamp' | 'pointerId' | 'target' | 'clientX' | 'clientY' | 'shiftKey' | 'altKey' | 'metaKey' | 'ctrlKey' | 'stopPropagation'>;+/** Controls in the viewer's picture area: a press on one is theirs. */+const CONTROLS = 'button, a, input, textarea, select, [role="button"], [role="slider"], [role="menu"], [contenteditable="true"]';const regionKeyHeld = (e: { metaKey: boolean; ctrlKey: boolean }) => (MAC ? e.metaKey : e.ctrlKey);/** ⌘A (Ctrl+A elsewhere): every layer on the picture, as Figma selects all. */const isSelectAll = (e: KeyLike) => isSelectAllKey(e, MAC);@@ -2416,6 +2420,250 @@ function FilmStageSelectImpl({} : null;const barLabel = barKind === 'layers' ? t('selectionBar.layers').replace('{n}', String(multi?.length ?? 0)) : undefined;+ /**+ * A press: on the picture, or on the dark around it (a marquee starts there too, as on Figma's canvas, so what sits+ * at an edge can be boxed whole). The moves and the release then come to the overlay, which holds the pointer.+ */+ const pressDown = (e: PressEvent) => {+ if (e.button !== 0) return;+ e.stopPropagation();+ /* pause at the press, not the release: a clock still running would move the selection off under the hand */+ onPause?.();+ const p = local(e);+ /* the first press of a double-click is kept: the second one lands where the picture has moved to */+ const prev = lastPressRef.current;+ if (!prev || e.timeStamp - prev.at > DOUBLE_PRESS_MS) lastPressRef.current = { x: p.x / viewScaleNow(), y: p.y / viewScaleNow(), at: e.timeStamp };+ /* ⌘ held: a box to point at in the chat, whatever is under the press (nothing is selected or moved) */+ if (onRegion && regionKeyHeld(e)) {+ host.current?.setPointerCapture(e.pointerId);+ regionDraftRef.current = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };+ setRegionDraft(regionDraftRef.current);+ setHover(null);+ return;+ }+ measureAt(null);+ const vs = viewScaleNow();+ const stagePt = { x: p.x / vs, y: p.y / vs };+ const target = e.target as HTMLElement | null;+ /* cropping: the crop's handles move its edges, a press inside it pans; a press elsewhere keeps the crop */+ const crop = cropRef.current;+ if (crop) {+ const part = target?.closest('[data-crop-kind]');+ const kind = part?.getAttribute('data-crop-kind');+ if (kind === 'move' || kind === 'scale' || kind === 'stretch') {+ cropDrag.current = {+ kind,+ handle: HANDLE_AT[part?.getAttribute('data-crop-handle') ?? ''] ?? { hx: 0, hy: 0 },+ start: stagePt,+ rect0: crop.rect,+ pos0: crop.pos,+ };+ setDragging(true);+ host.current?.setPointerCapture(e.pointerId);+ } else {+ finishCrop(true);+ }+ return;+ }+ const handle = target?.closest('[data-mg-handle]:not([data-mg-kind="move"])') as HTMLElement | null;+ const moveClip = target?.closest('[data-mg-kind="move"]');+ const outer = pickedRef.current?.element;+ const origin = liveTRef.current ?? outer?.transform;+ const currentTarget = host.current!;+ const pointerId = e.pointerId;+ ++pressSeq.current;+ pressGo.current = Promise.resolve(true);+ const startGesture = (g: Omit<NonNullable<typeof gestureRef.current>, 'snapTargets'>) => {+ if (clipNudge.current) flushClipNudge();+ const gesture = { ...g, snapTargets: [{ x: 0, y: 0, w: stage.w, h: stage.h }] };+ gestureRef.current = gesture;+ /* counted once at the press, and only a move or a scale uses them: the stage first (it wins ties), then the+ part of each clip on screen now that shows */+ if (g.kind !== 'rotate') {+ void ask<{ id: string; visible: boolean; x: number; y: number; w: number; h: number }[]>('clips').then((list) => {+ if (gestureRef.current !== gesture || !list) return;+ gesture.snapTargets = [gesture.snapTargets[0]!, ...list.filter((c) => c.visible && c.id !== g.clipId).map(shownBoxOf)];+ });+ }+ liveTRef.current = g.origin;+ setLiveT(g.origin);+ /* a handle has no "maybe a click": pressed is dragging */+ if (!g.pendingClick) setDragging(true);+ currentTarget.setPointerCapture(pointerId);+ };+ const outerCrop = outer?.isMgOuter && outer.clipLoc ? infoOf(outer.clipLoc)?.crop ?? NO_CROP : NO_CROP;+ const stretchable = outer?.clipKind === 'video';+ if (onEditClip && handle && outer?.isMgOuter && outer.clipLoc && outer.clipId && outer.mgBox && origin && !lockedClip(outer.clipLoc)) {+ const kind = handle.getAttribute('data-mg-kind');+ const at = HANDLE_AT[handle.getAttribute('data-mg-handle') ?? ''];+ startGesture({+ kind: kind === 'rotate' ? 'rotate' : 'scale',+ ...(kind !== 'rotate' && at ? { handle: at } : {}),+ stretchable,+ start: stagePt,+ origin,+ box: outer.mgBox,+ crop: outerCrop,+ clipLoc: outer.clipLoc,+ clipId: outer.clipId,+ });+ return;+ }+ /*+ * A press inside the clip in hand moves it. Only the clip in hand: if a press on any clip started a drag,+ * every drag would move something and the marquee would never happen (and a move is a real edit).+ */+ if (onEditClip && outer?.isMgOuter && outer.clipLoc && outer.clipId && outer.mgBox && origin && !lockedClip(outer.clipLoc)+ && (moveClip || insideFrame(visibleFrame(origin, outer.mgBox, outerCrop), stagePt.x, stagePt.y))) {+ startGesture({+ kind: 'move',+ stretchable,+ pendingClick: true,+ start: stagePt,+ origin,+ box: outer.mgBox,+ crop: outerCrop,+ clipLoc: outer.clipLoc,+ clipId: outer.clipId,+ hit: { x: p.x, y: p.y },+ });+ return;+ }+ /* several clips selected: a press on one of them drags them all, as Figma moves a selection (Shift: a marquee+ that adds to them instead) */+ const linkedNow = linkedLocs ?? [];+ const groupHit = target?.closest('[data-group-kind]') as HTMLElement | null;+ if (linkedNow.length > 1 && groupBox && onEditClip && !e.shiftKey && !linkedNow.some((loc) => lockedClip(loc))+ && (groupHit || insideBox(groupBox, stagePt.x, stagePt.y))) {+ const items = linkedNow.flatMap((loc) => {+ const info = infoOf(loc);+ return info?.box ? [{ loc, id: info.id, t0: info.t, box: info.box }] : [];+ });+ const kind = groupHit?.getAttribute('data-group-kind');+ const handle = kind === 'scale' || kind === 'stretch' || kind === 'rotate' ? groupHit!.getAttribute('data-group-handle') : null;+ const g = groupBox;+ const mid = { x: g.left + g.width / 2, y: g.top + g.height / 2 };+ /* a corner or an edge's middle, on the side pulled (`far`: the opposite one, which stays) */+ const at = (h: string, far: boolean) => ({+ x: h.includes('e') || h.includes('w') ? g.left + (h.includes('e') !== far ? g.width : 0) : mid.x,+ y: h.includes('n') || h.includes('s') ? g.top + (h.includes('s') !== far ? g.height : 0) : mid.y,+ });+ const turning = kind === 'rotate';+ clipsDrag.current = {+ kind: turning ? 'rotate' : handle ? 'scale' : 'move', handle: turning ? null : handle,+ x: p.x, y: p.y, moved: false, items, dx: 0, dy: 0, kx: 1, ky: 1, turn: 0, box0: g,+ anchor: turning ? mid : handle ? at(handle, true) : { x: 0, y: 0 },+ from: handle && !turning ? at(handle, false) : { x: 0, y: 0 },+ a0: Math.atan2(stagePt.y - mid.y, stagePt.x - mid.x),+ };+ currentTarget.setPointerCapture(pointerId);+ return;+ }+ /* several selected: a press inside their box drags them all (Shift adds / takes away instead) */+ const many = multiRef.current;+ const held0 = pickedRef.current;+ if (many && held0 && !e.shiftKey && onTransformLayers && !many.some((it) => lockedClip(it.element.clipLoc)) && insideBox(scaleBox(held0.rect, vs), p.x, p.y)) {+ multiDrag.current = { x: p.x, y: p.y, moved: false, rect0: held0.rect, items: multiItemsNow() };+ currentTarget.setPointerCapture(pointerId);+ return;+ }+ shiftBase.current = e.shiftKey ? selectedLayers() : null;+ /* the layer in hand: its handles scale / turn it, a press in its box moves it (Alt in its box is kept for+ cycling down) */+ const held = pickedRef.current;+ const heldLayer0 = held?.layer;+ const layerHandle = target?.closest('[data-layer-kind]') as HTMLElement | null;+ const layerKind = layerHandle?.getAttribute('data-layer-kind');+ if (held?.element && layerMovable(heldLayer0, held.element)) {+ const base = heldLayer0.geo.g;+ const frame0 = scaleFrame(heldLayer0.frame, vs);+ const aabb0 = scaleBox(heldLayer0.rect, vs);+ const inside = insideBox(scaleBox(held.rect, vs), p.x, p.y);+ const kind = layerKind === 'scale' ? 'scale'+ : layerKind === 'stretch' ? 'stretch'+ : layerKind === 'rotate' ? 'rotate'+ : (layerKind === 'move' || inside) && !e.altKey ? 'move' : null;+ const at = HANDLE_AT[layerHandle?.getAttribute('data-layer-handle') ?? ''] ?? { hx: 0, hy: 0 };+ if (kind) {+ if (nudge.current) flushNudge();+ const d: LayerDrag = {+ kind,+ hx: at.hx,+ hy: at.hy,+ x: p.x,+ y: p.y,+ base,+ frame0,+ aabb0,+ scale: heldLayer0.geo.k * vs,+ layer: heldLayer0,+ element: held.element,+ /* a handle drags at once; a press in the box may be a click until it goes 4px */+ moved: kind !== 'move',+ now: base,+ targets: [{ x: 0, y: 0, w: stage.w * vs, h: stage.h * vs }],+ };+ layerDrag.current = d;+ if (kind !== 'rotate') {+ void ask<{ x: number; y: number; w: number; h: number }[]>('snaps', { handle: heldLayer0.handle }).then((list) => {+ if (list && layerDrag.current === d) d.targets = list.map((r) => ({ x: r.x * vs, y: r.y * vs, w: r.w * vs, h: r.h * vs }));+ });+ }+ if (kind !== 'move') {+ setDragging(true);+ setHover(null);+ }+ currentTarget.setPointerCapture(pointerId);+ return;+ }+ }+ /* about to draw: the previous selection goes first (two boxes on screen would read as two selected), and the+ timeline's with it; but a press on a clip selected there (several: no handles) is not a press elsewhere */+ cycleFrom.current = e.altKey ? pickedRef.current?.layer?.handle ?? null : null;+ pressedFrom.current = pickedRef.current?.layer?.handle ?? null;+ const clearPrevious = () => {+ dropPick();+ onSelectElement?.(null);+ setHover(null);+ };+ const linked = linkedLocs ?? [];+ if (linked.length) {+ pressGo.current = ask<string>('clipAt', stagePt).then((id) => {+ const loc = id ? clipLocOf(docRef.current, id) : undefined;+ if (loc && linked.includes(loc)) {+ draftRef.current = null;+ setDraft(null);+ return false;+ }+ clearPrevious();+ return true;+ });+ } else {+ clearPrevious();+ }+ /* a click or a marquee is decided at the release */+ currentTarget.setPointerCapture(pointerId);+ marqueeClips.current = onSelectClips ? ask<StageClipBox[]>('clips') : null;+ draftRef.current = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };+ setDraft(draftRef.current);+ };+ const pressDownRef = React.useRef(pressDown);+ pressDownRef.current = pressDown;+ React.useEffect(() => {+ const area = host.current?.closest<HTMLElement>('[data-viewer-picture]');+ if (!area) return;+ const onDown = (e: PointerEvent) => {+ const el = e.target as Element | null;+ if (e.button !== 0 || !el || host.current?.contains(el) || el.closest(CONTROLS)) return;+ /* only the dark around the picture: what lies over the picture (the subtitles) has its own presses */+ const r = filmRect();+ if (r && e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) return;+ pressDownRef.current(e);+ };+ area.addEventListener('pointerdown', onDown);+ return () => area.removeEventListener('pointerdown', onDown);+ }, []); // eslint-disable-line react-hooks/exhaustive-deps+return (<divref={host}@@ -2428,229 +2676,7 @@ function FilmStageSelectImpl({onDoubleClick={onStageDoubleClick}onContextMenu={onStageContextMenu}onClick={(e) => e.stopPropagation()}- onPointerDown={(e) => {- if (e.button !== 0) return;- e.stopPropagation();- /* pause at the press, not the release: a clock still running would move the selection off under the hand */- onPause?.();- const p = local(e);- /* the first press of a double-click is kept: the second one lands where the picture has moved to */- const prev = lastPressRef.current;- if (!prev || e.timeStamp - prev.at > DOUBLE_PRESS_MS) lastPressRef.current = { x: p.x / viewScaleNow(), y: p.y / viewScaleNow(), at: e.timeStamp };- /* ⌘ held: a box to point at in the chat, whatever is under the press (nothing is selected or moved) */- if (onRegion && regionKeyHeld(e)) {- e.currentTarget.setPointerCapture(e.pointerId);- regionDraftRef.current = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };- setRegionDraft(regionDraftRef.current);- setHover(null);- return;- }- measureAt(null);- const vs = viewScaleNow();- const stagePt = { x: p.x / vs, y: p.y / vs };- const target = e.target as HTMLElement | null;- /* cropping: the crop's handles move its edges, a press inside it pans; a press elsewhere keeps the crop */- const crop = cropRef.current;- if (crop) {- const part = target?.closest('[data-crop-kind]');- const kind = part?.getAttribute('data-crop-kind');- if (kind === 'move' || kind === 'scale' || kind === 'stretch') {- cropDrag.current = {- kind,- handle: HANDLE_AT[part?.getAttribute('data-crop-handle') ?? ''] ?? { hx: 0, hy: 0 },- start: stagePt,- rect0: crop.rect,- pos0: crop.pos,- };- setDragging(true);- e.currentTarget.setPointerCapture(e.pointerId);- } else {- finishCrop(true);- }- return;- }- const handle = target?.closest('[data-mg-handle]:not([data-mg-kind="move"])') as HTMLElement | null;- const moveClip = target?.closest('[data-mg-kind="move"]');- const outer = pickedRef.current?.element;- const origin = liveTRef.current ?? outer?.transform;- const currentTarget = e.currentTarget;- const pointerId = e.pointerId;- ++pressSeq.current;- pressGo.current = Promise.resolve(true);- const startGesture = (g: Omit<NonNullable<typeof gestureRef.current>, 'snapTargets'>) => {- if (clipNudge.current) flushClipNudge();- const gesture = { ...g, snapTargets: [{ x: 0, y: 0, w: stage.w, h: stage.h }] };- gestureRef.current = gesture;- /* counted once at the press, and only a move or a scale uses them: the stage first (it wins ties), then the- part of each clip on screen now that shows */- if (g.kind !== 'rotate') {- void ask<{ id: string; visible: boolean; x: number; y: number; w: number; h: number }[]>('clips').then((list) => {- if (gestureRef.current !== gesture || !list) return;- gesture.snapTargets = [gesture.snapTargets[0]!, ...list.filter((c) => c.visible && c.id !== g.clipId).map(shownBoxOf)];- });- }- liveTRef.current = g.origin;- setLiveT(g.origin);- /* a handle has no "maybe a click": pressed is dragging */- if (!g.pendingClick) setDragging(true);- currentTarget.setPointerCapture(pointerId);- };- const outerCrop = outer?.isMgOuter && outer.clipLoc ? infoOf(outer.clipLoc)?.crop ?? NO_CROP : NO_CROP;- const stretchable = outer?.clipKind === 'video';- if (onEditClip && handle && outer?.isMgOuter && outer.clipLoc && outer.clipId && outer.mgBox && origin && !lockedClip(outer.clipLoc)) {- const kind = handle.getAttribute('data-mg-kind');- const at = HANDLE_AT[handle.getAttribute('data-mg-handle') ?? ''];- startGesture({- kind: kind === 'rotate' ? 'rotate' : 'scale',- ...(kind !== 'rotate' && at ? { handle: at } : {}),- stretchable,- start: stagePt,- origin,- box: outer.mgBox,- crop: outerCrop,- clipLoc: outer.clipLoc,- clipId: outer.clipId,- });- return;- }- /*- * A press inside the clip in hand moves it. Only the clip in hand: if a press on any clip started a drag,- * every drag would move something and the marquee would never happen (and a move is a real edit).- */- if (onEditClip && outer?.isMgOuter && outer.clipLoc && outer.clipId && outer.mgBox && origin && !lockedClip(outer.clipLoc)- && (moveClip || insideFrame(visibleFrame(origin, outer.mgBox, outerCrop), stagePt.x, stagePt.y))) {- startGesture({- kind: 'move',- stretchable,- pendingClick: true,- start: stagePt,- origin,- box: outer.mgBox,- crop: outerCrop,- clipLoc: outer.clipLoc,- clipId: outer.clipId,- hit: { x: p.x, y: p.y },- });- return;- }- /* several clips selected: a press on one of them drags them all, as Figma moves a selection (Shift: a marquee- that adds to them instead) */- const linkedNow = linkedLocs ?? [];- const groupHit = target?.closest('[data-group-kind]') as HTMLElement | null;- if (linkedNow.length > 1 && groupBox && onEditClip && !e.shiftKey && !linkedNow.some((loc) => lockedClip(loc))- && (groupHit || insideBox(groupBox, stagePt.x, stagePt.y))) {- const items = linkedNow.flatMap((loc) => {- const info = infoOf(loc);- return info?.box ? [{ loc, id: info.id, t0: info.t, box: info.box }] : [];- });- const kind = groupHit?.getAttribute('data-group-kind');- const handle = kind === 'scale' || kind === 'stretch' || kind === 'rotate' ? groupHit!.getAttribute('data-group-handle') : null;- const g = groupBox;- const mid = { x: g.left + g.width / 2, y: g.top + g.height / 2 };- /* a corner or an edge's middle, on the side pulled (`far`: the opposite one, which stays) */- const at = (h: string, far: boolean) => ({- x: h.includes('e') || h.includes('w') ? g.left + (h.includes('e') !== far ? g.width : 0) : mid.x,- y: h.includes('n') || h.includes('s') ? g.top + (h.includes('s') !== far ? g.height : 0) : mid.y,- });- const turning = kind === 'rotate';- clipsDrag.current = {- kind: turning ? 'rotate' : handle ? 'scale' : 'move', handle: turning ? null : handle,- x: p.x, y: p.y, moved: false, items, dx: 0, dy: 0, kx: 1, ky: 1, turn: 0, box0: g,- anchor: turning ? mid : handle ? at(handle, true) : { x: 0, y: 0 },- from: handle && !turning ? at(handle, false) : { x: 0, y: 0 },- a0: Math.atan2(stagePt.y - mid.y, stagePt.x - mid.x),- };- currentTarget.setPointerCapture(pointerId);- return;- }- /* several selected: a press inside their box drags them all (Shift adds / takes away instead) */- const many = multiRef.current;- const held0 = pickedRef.current;- if (many && held0 && !e.shiftKey && onTransformLayers && !many.some((it) => lockedClip(it.element.clipLoc)) && insideBox(scaleBox(held0.rect, vs), p.x, p.y)) {- multiDrag.current = { x: p.x, y: p.y, moved: false, rect0: held0.rect, items: multiItemsNow() };- currentTarget.setPointerCapture(pointerId);- return;- }- shiftBase.current = e.shiftKey ? selectedLayers() : null;- /* the layer in hand: its handles scale / turn it, a press in its box moves it (Alt in its box is kept for- cycling down) */- const held = pickedRef.current;- const heldLayer0 = held?.layer;- const layerHandle = target?.closest('[data-layer-kind]') as HTMLElement | null;- const layerKind = layerHandle?.getAttribute('data-layer-kind');- if (held?.element && layerMovable(heldLayer0, held.element)) {- const base = heldLayer0.geo.g;- const frame0 = scaleFrame(heldLayer0.frame, vs);- const aabb0 = scaleBox(heldLayer0.rect, vs);- const inside = insideBox(scaleBox(held.rect, vs), p.x, p.y);- const kind = layerKind === 'scale' ? 'scale'- : layerKind === 'stretch' ? 'stretch'- : layerKind === 'rotate' ? 'rotate'- : (layerKind === 'move' || inside) && !e.altKey ? 'move' : null;- const at = HANDLE_AT[layerHandle?.getAttribute('data-layer-handle') ?? ''] ?? { hx: 0, hy: 0 };- if (kind) {- if (nudge.current) flushNudge();- const d: LayerDrag = {- kind,- hx: at.hx,- hy: at.hy,- x: p.x,- y: p.y,- base,- frame0,- aabb0,- scale: heldLayer0.geo.k * vs,- layer: heldLayer0,- element: held.element,- /* a handle drags at once; a press in the box may be a click until it goes 4px */- moved: kind !== 'move',- now: base,- targets: [{ x: 0, y: 0, w: stage.w * vs, h: stage.h * vs }],- };- layerDrag.current = d;- if (kind !== 'rotate') {- void ask<{ x: number; y: number; w: number; h: number }[]>('snaps', { handle: heldLayer0.handle }).then((list) => {- if (list && layerDrag.current === d) d.targets = list.map((r) => ({ x: r.x * vs, y: r.y * vs, w: r.w * vs, h: r.h * vs }));- });- }- if (kind !== 'move') {- setDragging(true);- setHover(null);- }- currentTarget.setPointerCapture(pointerId);- return;- }- }- /* about to draw: the previous selection goes first (two boxes on screen would read as two selected), and the- timeline's with it; but a press on a clip selected there (several: no handles) is not a press elsewhere */- cycleFrom.current = e.altKey ? pickedRef.current?.layer?.handle ?? null : null;- pressedFrom.current = pickedRef.current?.layer?.handle ?? null;- const clearPrevious = () => {- dropPick();- onSelectElement?.(null);- setHover(null);- };- const linked = linkedLocs ?? [];- if (linked.length) {- pressGo.current = ask<string>('clipAt', stagePt).then((id) => {- const loc = id ? clipLocOf(docRef.current, id) : undefined;- if (loc && linked.includes(loc)) {- draftRef.current = null;- setDraft(null);- return false;- }- clearPrevious();- return true;- });- } else {- clearPrevious();- }- /* a click or a marquee is decided at the release */- currentTarget.setPointerCapture(pointerId);- marqueeClips.current = onSelectClips ? ask<StageClipBox[]>('clips') : null;- draftRef.current = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };- setDraft(draftRef.current);- }}+ onPointerDown={pressDown}onPointerMove={(e) => {pointerAt.current = local(e);if (cropDrag.current) { stepCrop(local(e), e.shiftKey); return; }diff --git a/packages/openfilm/studio/ui/src/components/PasteAttrsDialog.tsx b/packages/openfilm/studio/ui/src/components/PasteAttrsDialog.tsxnew file mode 100644index 0000000..626dbb3--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/PasteAttrsDialog.tsx@@ -0,0 +1,69 @@+import React from 'react';+import { createPortal } from 'react-dom';+import { useT } from '@/i18n';+import { groupsOf, type AttrGroup, type CopiedAttrs } from '@/lib/clip-attrs';+import { Card, CardActions, CardButton } from './Card';++/**+ * Paste attributes (⌘⇧V), as CapCut's dialog: what the copied clip has, in two parts — its picture (place and size,+ * blending) and its sound (volume, fades) — each ticked, untick what should stay. Enter pastes, Esc backs out.+ */+export function PasteAttrsDialog({+ attrs, onPaste, onCancel,+}: {+ /** The copy; null: closed. */+ attrs: CopiedAttrs | null;+ onPaste: (groups: ReadonlySet<AttrGroup>) => void;+ onCancel: () => void;+}) {+ const t = useT();+ const offered = React.useMemo(() => (attrs ? groupsOf(attrs) : []), [attrs]);+ const [picked, setPicked] = React.useState<ReadonlySet<AttrGroup>>(new Set());+ const pasteRef = React.useRef<HTMLButtonElement>(null);+ React.useEffect(() => { setPicked(new Set(offered)); }, [offered]);+ React.useEffect(() => {+ if (!attrs) return undefined;+ pasteRef.current?.focus();+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); onCancel(); } };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [attrs, onCancel]);+ if (!attrs || typeof document === 'undefined') return null;++ const parts: { title: string; groups: AttrGroup[] }[] = [+ { title: t('clipAttrs.picture'), groups: offered.filter((g) => g === 'place' || g === 'blend') },+ { title: t('clipAttrs.sound'), groups: offered.filter((g) => g === 'volume' || g === 'fade') },+ ].filter((p) => p.groups.length);+ const flip = (g: AttrGroup) => setPicked((now) => {+ const next = new Set(now);+ if (next.has(g)) next.delete(g); else next.add(g);+ return next;+ });++ return createPortal(+ <div className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/45 p-4 backdrop-blur-[2px]" onClick={onCancel}>+ <div className="w-full max-w-[360px]" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label={t('clipAttrs.title')}>+ <Card title={t('clipAttrs.title')} onClose={onCancel}>+ <div className="mt-2 flex flex-col gap-3">+ {parts.map((part) => (+ <fieldset key={part.title} className="flex flex-col gap-1.5">+ <legend className="mb-1 text-[11px] text-[var(--text-faint)]">{part.title}</legend>+ {part.groups.map((g) => (+ <label key={g} className="flex cursor-pointer items-center gap-2 text-[12.5px] text-[var(--text)]">+ <input type="checkbox" checked={picked.has(g)} onChange={() => flip(g)} data-attr-group={g} />+ {t(`clipAttrs.${g}`)}+ </label>+ ))}+ </fieldset>+ ))}+ </div>+ <CardActions>+ <CardButton weight="quiet" onClick={onCancel}>{t('confirm.cancel')}</CardButton>+ <CardButton ref={pasteRef} weight="primary" disabled={!picked.size} onClick={() => onPaste(picked)}>{t('clipAttrs.paste')}</CardButton>+ </CardActions>+ </Card>+ </div>+ </div>,+ document.body,+ );+}diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsxindex 729cb54..05b1124 100644--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx@@ -7,7 +7,7 @@* are written one at a time (see editor/use-film.ts); the agent's writes come in through the folder's events.*/import * as React from 'react';-import { GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, TriangleAlert } from 'lucide-react';+import { ClipboardCopy, ClipboardPaste, GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, TriangleAlert } from 'lucide-react';import { applyOps } from '../../../server/ops.mjs';import { api, ApiError, PREFS_EVENT, projectEvents, type Clip, type Film, type Listing, type Op, type ProjectFilm, type ProjectSettings } from '@/api';import { useT } from '@/i18n';@@ -15,10 +15,12 @@ import { useFilm, type Step } from '@/editor/use-film';import { Player } from '@/editor/player';import { Preview, type FilmInfo, type PreviewHandle } from '@/editor/Preview';import { filmShape, type MediaFacts } from '@/lib/film-shape';+import { changesPicture } from '@/lib/picture-files';import { layoutTracks, type TimelineBlock, type TimelineTrack } from '@/lib/timeline-layout';import { filmClipKind, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc } from '@/lib/film';-import { footageFps, secondFrames, setTimecodeFps, snapToFrame, stepFrames } from '@/lib/timecode';-import { keyCommandOf, loopBack, playStart, shuttleRate } from '@/lib/timeline-keys';+import { footageFps, setTimecodeFps, snapToFrame, stepFrames } from '@/lib/timecode';+import { JUMP_FRAMES, keyCommandOf, loopBack, playStart, shuttleRate } from '@/lib/timeline-keys';+import { attrsOf, pasteAttrs, type AttrGroup, type CopiedAttrs } from '@/lib/clip-attrs';import { cutPoints, namedTrack, nextCut, trackNamesOf } from '@/lib/timeline-nav';import { anyLocked, lockedEdits } from '@/lib/track-lock';import { placeMedia, type SourceRange } from '@/lib/media-place';@@ -85,6 +87,7 @@ import { LiveTime, type PlaybackClock } from './LiveTime';import { Toast, useToast } from './Toast';import { SpendAsks } from './SpendAsks';import { ExportCenter } from './export/ExportCenter';+import { PasteAttrsDialog } from './PasteAttrsDialog';import { ExportTray, type ExportTrayHandle } from './export/ExportTray';import { FilmStageSelect, type FilmStageControl, type LayerGeometry, type StageClipEdit, type StagePick } from './FilmStageSelect';import { openSection } from './inspector-fields';@@ -208,9 +211,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {setFilesTick((n) => n + 1);/* a page, or a file pages use, changed on disk: the picture is drawn from them again. So is a media file a clipplays, made again in place (a render written over the last one): its element would go on playing what it- had loaded of the old file. Other media under assets/ are loaded as they are used */+ had loaded of the old file. Other media under assets/ are loaded as they are used, and what no page loads+ (an agent's notes and scripts) leaves the picture as it is (lib/picture-files) */const used = new Set(blocksRef.current.map((b) => b.src).filter(Boolean));- if (!event.paths || event.paths.some((path) => !path.startsWith('assets/') || used.has(path))) preview.current?.reload?.();+ if (changesPicture(event.paths, used)) preview.current?.reload?.();});}, [projectId]);@@ -700,6 +704,32 @@ export function ProjectView({ projectId, onProject, onLeave }: {/** An edit the timeline planned (lib/timeline-edit), as it planned it: one write, one undo step. */const editOps = React.useCallback((ops: Op[], label: string) => edit(ops, label), [edit]);+ /* ── a clip's attributes copied onto others (lib/clip-attrs, ⌘⇧C / ⌘⇧V, as CapCut's) ── */+ const [copiedAttrs, setCopiedAttrs] = React.useState<CopiedAttrs | null>(null);+ const [pasteAttrsOpen, setPasteAttrsOpen] = React.useState(false);+ const filmClipOf = React.useCallback((id: string) => filmRef.current?.tracks.flatMap((tr) => tr.clips).find((c) => c.id === id) ?? null, []);+ const copyAttrs = React.useCallback((blocks: readonly TimelineBlock[]) => {+ const clip = blocks.map((b) => (b.clipId ? filmClipOf(b.clipId) : null)).find(Boolean);+ if (!clip) { toast.show(t('clipAttrs.selectFirst')); return; }+ setCopiedAttrs(attrsOf(clip));+ toast.show(t('clipAttrs.copied'));+ }, [filmClipOf, toast, t]);+ const askPasteAttrs = React.useCallback((blocks: readonly TimelineBlock[]) => {+ if (!copiedAttrs) { toast.show(t('clipAttrs.nothing')); return; }+ if (!blocks.some((b) => b.clipId && b.loc)) { toast.show(t('clipAttrs.selectFirst')); return; }+ setPasteAttrsOpen(true);+ }, [copiedAttrs, toast, t]);+ const doPasteAttrs = React.useCallback((groups: ReadonlySet<AttrGroup>) => {+ setPasteAttrsOpen(false);+ if (!copiedAttrs) return;+ const targets = selectedBlocks.flatMap((b) => {+ const clip = b.clipId && b.loc ? filmClipOf(b.clipId) : null;+ return clip ? [{ loc: b.loc!, clip, lengthS: (b.endMs - b.startMs) / 1000 }] : [];+ });+ const edits = pasteAttrs(copiedAttrs, groups, targets);+ if (edits.length) void editBlocks(edits).then((err) => { if (err) toast.showError(err); });+ }, [copiedAttrs, selectedBlocks, filmClipOf, editBlocks, toast]);+/* ── fades and transitions: each clip's fades (its `overrides`' own entry), and the transitions they make ── */const clipFades = React.useMemo(() => new Map<string, FadeMs>((film.film?.tracks ?? []).flatMap((tr) => tr.clips.flatMap((c) => {const fade = fadeMsOf(c);@@ -733,7 +763,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {/* the magnet acts on the main track: there a transition's overlap closes up what follows */const cutClip = ask.kind === 'add' ? ask.cut.a : filmTransitions.find((x) => x.key === ask.key)?.a;const cutTrack = model.find((tr) => tr.clips.some((c) => c.id === cutClip))?.index;- const opts = { ripple: magnetOn(model, cutTrack, prefs.magnet), ...followOf(prefs), linked: prefs.linked, whiteSrc: WHITE_SRC };+ const opts = { ripple: magnetOn(model, cutTrack, prefs.magnet), ...followOf(prefs), linked: true, whiteSrc: WHITE_SRC };let plan: TransitionPlan;let label: string;if (ask.kind === 'add') {@@ -764,7 +794,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {/* the magnet acts on the main track alone */const magnet = magnetOn(model, model.find((tr) => tr.clips.some((c) => c.id === block?.clipId))?.index, prefs.magnet);if (!block?.clipId || (one!.prop !== 'speed' && one!.prop !== 'at' && !(one!.prop === 'end' && magnet))) return editBlocks(edits, true);- const ids = prefs.linked ? [block.clipId, ...linkedIds(model, [block.clipId]).filter((id) => id !== block.clipId)] : [block.clipId];+ const ids = [block.clipId, ...linkedIds(model, [block.clipId]).filter((id) => id !== block.clipId)];if (one!.prop === 'at') {/* a start typed in: the clip (and those linked to it) moves as a drag would, in the timeline's mode: with themagnet it goes in at the insert point there and pushes what follows on; without it, it lands there and covers@@ -971,8 +1001,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {}, [removeBlocks]);/* markers, solo, track heights, loudness, freeze frame, replace (use-editor-tools) */const tools = useEditorTools({- projectId, tracks: timelineTracks, film: film.film, settings, patchSettings, player, timeRef, seek, edit: editOps, editModel,- selectedClipIds: selectedKeys, listing, toast,+ projectId, tracks: timelineTracks, film: film.film, settings, patchSettings, player, timeRef, seek, edit: editOps, record: film.record,+ editModel, selectedClipIds: selectedKeys, listing, toast,});/* how many of the person's edits an outside write undid: edits inside pages it left out, and clip edits it changed */@@ -1374,9 +1404,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {const duplicateRef = React.useRef<(blocks: readonly TimelineBlock[]) => Promise<string | null>>(async () => null);/* the whole clip's actions in the picture's menu: the timeline's own */const blockAt = (clipLoc: string) => blocksRef.current.find((b) => b.loc === clipLoc) ?? null;- /* a clip with the clips linked to it (when the timeline's Linked switch is on), as the timeline acts on them */+ /* a clip with the clips linked to it, as the timeline acts on them */const withLinkedBlocks = (b: TimelineBlock): TimelineBlock[] => {- if (!b.clipId || !readTimelinePrefs().linked) return [b];+ if (!b.clipId) return [b];const ids = new Set(linkedIds(editModel(), [b.clipId]));return blocksRef.current.filter((x) => x === b || (x.clipId != null && ids.has(x.clipId)));};@@ -1441,7 +1471,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {}, [stageMenuFor, t]);/** Two groups of menu entries, a line between them when both have some. */const menuGroups = (a: ContextMenuEntry[], b: ContextMenuEntry[]): ContextMenuEntry[] => (a.length && b.length ? [...a, { id: 'tools-sep', separator: true }, ...b] : [...a, ...b]);- const timelineMenuExtra = React.useCallback((blocks: readonly TimelineBlock[]) => (blocks.length ? menuGroups(referEntry(() => blocks.map(refOfBlock)), tools.menuExtra(blocks)) : []), [t, tools.menuExtra]); // eslint-disable-line react-hooks/exhaustive-deps+ /* copy and paste attributes, as CapCut's clip menu has them */+ const attrsEntries = (blocks: readonly TimelineBlock[]): ContextMenuEntry[] => [+ { id: 'copy-attrs', label: t('clipAttrs.copy'), icon: <ClipboardCopy size={14} />, shortcut: shortcutHint('C', { mod: true, shift: true }), disabled: blocks.length !== 1, onSelect: () => copyAttrs(blocks) },+ { id: 'paste-attrs', label: t('clipAttrs.pasteMenu'), icon: <ClipboardPaste size={14} />, shortcut: shortcutHint('V', { mod: true, shift: true }), disabled: !copiedAttrs, hint: t('clipAttrs.nothing'), onSelect: () => askPasteAttrs(blocks) },+ ];+ const timelineMenuExtra = React.useCallback((blocks: readonly TimelineBlock[]) => (blocks.length ? menuGroups(menuGroups(referEntry(() => blocks.map(refOfBlock)), tools.menuExtra(blocks)), attrsEntries(blocks)) : []), [t, tools.menuExtra, copiedAttrs, copyAttrs, askPasteAttrs]); // eslint-disable-line react-hooks/exhaustive-depsconst trackMenuExtra = React.useCallback((track: TimelineTrack) => {const docIndex = track.docIndex;const refer = docIndex == null || !studioHost?.refer ? [] : referEntry(() => { const ref = trackRef(tracksRef.current, docIndex); return ref ? [ref] : []; }, false);@@ -1597,6 +1632,13 @@ export function ProjectView({ projectId, onProject, onLeave }: {return out;// eslint-disable-next-line react-hooks/exhaustive-deps}, [rawListing, timelineTracks]);+ /** The file of a clip under the playhead that is gone (on a track that is seen), for the viewer to say. */+ const missingHere = React.useMemo(() => {+ if (!mediaTrouble.size) return null;+ const hit = timelineTracks.filter((tr) => !tr.hidden).flatMap((tr) => tr.blocks)+ .find((b) => b.src && mediaTrouble.get(b.src) === 'missing' && timeMs >= b.startMs && timeMs < b.endMs);+ return hit?.src ? hit.src.split('/').pop() ?? hit.src : null;+ }, [mediaTrouble, timelineTracks, timeMs]);const relinkCandidates = React.useCallback((src: string): string[] => {const name = src.split('/').pop()?.toLowerCase();return name ? (rawListing?.files ?? []).filter((f) => f.path.split('/').pop()?.toLowerCase() === name && f.path !== src).map((f) => f.path) : [];@@ -2001,11 +2043,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {if (!once) return;if (markedRange) playRange(markedRange); else toggle();return;- case 'frame-back': case 'frame-forward': case 'second-back': case 'second-forward': case 'start': case 'end': {+ case 'frame-back': case 'frame-forward': case 'jump-back': case 'jump-forward': case 'start': case 'end': {if (!(totalMs > 0)) return;take();- /* a frame (or a second) on from the frame the playhead is on, so stepping never drifts */- const frames = (cmd.endsWith('back') ? -1 : 1) * (cmd.startsWith('second') ? secondFrames() : 1);+ /* a frame (or ten, ⇧) on from the frame the playhead is on, so stepping never drifts */+ const frames = (cmd.endsWith('back') ? -1 : 1) * (cmd.startsWith('jump') ? JUMP_FRAMES : 1);const next = cmd === 'start' ? 0 : cmd === 'end' ? totalMs : stepFrames(now, frames);pause();seek(Math.max(0, Math.min(totalMs, next)));@@ -2032,6 +2074,32 @@ export function ProjectView({ projectId, onProject, onLeave }: {case 'insert-source': case 'overwrite-source':/* the source viewer's keys (it takes them first while it is up) */return;+ case 'range-clip': {+ /* ⇧X: the range is the selected clips' span (CapCut's 以片段选定区域) */+ if (!selectedBlocks.length) return;+ take();+ setMarkedRange({ startMs: Math.min(...selectedBlocks.map((b) => b.startMs)), endMs: Math.max(...selectedBlocks.map((b) => b.endMs)) });+ return;+ }+ case 'copy-attrs': if (!selectedBlocks.length) return; take(); if (once) copyAttrs(selectedBlocks); return;+ case 'paste-attrs': if (!selectedBlocks.length) return; take(); if (once) askPasteAttrs(selectedBlocks); return;+ case 'speed': {+ /* ⌘R: the selected clip's speed, in the inspector (CapCut's 变速 panel) */+ if (selectedBlocks.length !== 1 || !once) return;+ take();+ setInspectorContent('selection');+ setInspectorOpen(true);+ window.setTimeout(() => document.querySelector<HTMLInputElement>(`input[aria-label="${t('inspector.speed')}"]`)?.focus(), 80);+ return;+ }+ case 'detach-audio': {+ /* ⇧⌃S: the selected video's sound on a track of its own (CapCut's 分离音频) */+ const video = selectedBlocks.find((b) => b.kind === 'video' && b.clipId);+ if (!video || !once) return;+ take();+ void detachAudio(video).then((err) => { if (err) toast.showError(err); });+ return;+ }default:break;}@@ -2046,14 +2114,15 @@ export function ProjectView({ projectId, onProject, onLeave }: {commands.nudge(cmd === 'nudge-back' ? -1 : 1);return;case 'zoom-fit': take(); commands.zoomFit(); return;+ case 'select-left': case 'select-right': take(); if (once) commands.selectSide(cmd === 'select-left' ? -1 : 1); return;case 'ripple-start': take(); if (once) commands.rippleTrimStart(); return;case 'ripple-end': take(); if (once) commands.rippleTrimEnd(); return;- case 'toggle-snap': case 'toggle-magnet': {+ case 'toggle-snap': case 'toggle-magnet': case 'toggle-linkage': {take();if (!once) return;- const pref = cmd === 'toggle-snap' ? 'snap' : 'magnet';+ const pref = cmd === 'toggle-snap' ? 'snap' : cmd === 'toggle-magnet' ? 'magnet' : 'linkage';const on = !readTimelinePrefs()[pref];- if (pref === 'snap') commands.toggleSnap(); else commands.toggleMagnet();+ if (pref === 'snap') commands.toggleSnap(); else if (pref === 'magnet') commands.toggleMagnet(); else commands.toggleLinkage();toast.show(`${t(`timeline.${pref}`)} · ${t(`timeline.${pref}${on ? 'On' : 'Off'}`)}`);return;}@@ -2406,6 +2475,13 @@ export function ProjectView({ projectId, onProject, onLeave }: {) : null}</Preview></div>+ {/* a clip under the playhead whose file is gone plays as nothing (src/timeline.mjs, film-missing):+ said here, over the picture, with what to do */}+ {missingHere && !fullscreen ? (+ <div data-preview-missing="" className="pointer-events-none absolute left-2 top-2 z-10 max-w-[80%] truncate rounded-[4px] bg-black/75 px-2 py-1 text-[11px] text-white">+ {t('project.previewMissing').replace('{file}', missingHere)}+ </div>+ ) : null}{!viewerReady && !empty && !previewError ? (<div className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-black"><span role="status" className="text-sweep relative text-[13px] text-white/60">{t('project.previewStageMount')}</span>@@ -2627,7 +2703,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {{...(exportClipId ? { focusClipId: exportClipId } : {})}onQueued={(jobs) => exportTrayRef.current?.push(jobs)}projectFps={projectFps}+ missingFiles={[...mediaTrouble].flatMap(([src, why]) => (why === 'missing' ? [src] : []))}/>+ <PasteAttrsDialog attrs={pasteAttrsOpen ? copiedAttrs : null} onPaste={doPasteAttrs} onCancel={() => setPasteAttrsOpen(false)} /><ExportTray ref={exportTrayRef} projectId={projectId} onError={toast.showError} inset={hostPanel?.open ? hostPanel.width : 0} /><SpendAsks projectId={projectId} /><Toast toast={toast.current} />diff --git a/packages/openfilm/studio/ui/src/components/Timeline.tsx b/packages/openfilm/studio/ui/src/components/Timeline.tsxindex e546914..8dac4ba 100644--- a/packages/openfilm/studio/ui/src/components/Timeline.tsx+++ b/packages/openfilm/studio/ui/src/components/Timeline.tsx@@ -45,7 +45,6 @@ import {Link2,Link2Off,Mic,- Rows3,SeparatorVertical,BetweenHorizontalStart,ArrowLeftToLine,@@ -89,12 +88,14 @@ import {import {editModelOf,gapAt,+ gapsOf,insertPointOn,linkedIds,magnetOn,mainTrackOf,planCloseGap,planCloseMainGaps,+ planCloseTrackGaps,planLink,planRemove,planRippleTrimTo,@@ -111,7 +112,7 @@ import { STUDIO_REF_TYPE, type StudioRef } from '@/lib/host';import { orderedRange, rangeLabel, type FilmRange } from '@/lib/studio-refs';import { draftNumbersOf, sameClip, type ChatPoint, type DraftMarks } from '@/lib/chat-marks';import { formatRulerLabel, formatTimecode, frameAt, frameMs, secondFrames, snapToFrame, stepFrames, useTimecodeFps } from '@/lib/timecode';-import { planNudge, splitAllTargets, splitTargets } from '@/lib/timeline-nav';+import { planNudge, sideTargets, splitAllTargets, splitTargets } from '@/lib/timeline-nav';import {VIEW_SPAN_MIN_MS,ZOOM_DEFAULT,@@ -684,9 +685,10 @@ export interface TimelineCommands {unlink: () => void;/** The switches (see lib/timeline-prefs). */toggleMagnet: () => void;+ toggleLinkage: () => void;+ /** [ / ]: every clip before / after the playhead selected (lib/timeline-nav sideTargets). */+ selectSide: (dir: -1 | 1) => void;toggleSnap: () => void;- toggleSync: () => void;- toggleLinked: () => void;/*** ⌘B: split the selected clips at the playhead; with nothing selected, the clip under it on the targeted track (the* one last pressed), else on the topmost track seen. The clips linked to them go too.@@ -985,9 +987,9 @@ export const Timeline = React.memo(function Timeline({const mainDoc = React.useMemo(() => mainTrackOf(model), [model]);const modelRef = React.useRef(model);modelRef.current = model;- /** Block ids → the same clips with every clip linked to them, unless the Linked switch is off (or `alone`). */+ /** Block ids → the same clips with every clip linked to them, unless `alone` (⌥). */const withLinked = React.useCallback((ids: readonly string[], alone = false): string[] => {- if (alone || !prefsRef.current.linked) return [...ids];+ if (alone) return [...ids];const blocks = tracks.flatMap((tr) => tr.blocks);const clipIds = blocks.filter((b) => ids.includes(b.id) && b.clipId).map((b) => b.clipId!);if (!clipIds.length) return [...ids];@@ -2601,16 +2603,18 @@ export const Timeline = React.memo(function Timeline({if (mode === 'split') {if (!inGroup) setSelected(own);if (track.locked) return;+ const at = msAtClientX(e.clientX);+ /* ⇧: every track is cut there, as CapCut's */+ if (e.shiftKey) { void runSplit(splitAllTargets(tracks, at), at); return; }const cut = new Set(own);- void runSplit(tracks.flatMap((tr) => tr.blocks).filter((b) => cut.has(b.id)), msAtClientX(e.clientX));+ void runSplit(tracks.flatMap((tr) => tr.blocks).filter((b) => cut.has(b.id)), at);return;}- /* ⌥-drag slips the content inside the clip, ⌥⇧-drag slides the clip between its neighbors; a ⌥-click- picks this clip alone */+ /* ⌥-drag copies (this clip alone, or the group it is in), as CapCut's; a ⌥-click picks this clip alone */if (e.altKey) {if (!inGroup) setSelected(withLinked([block.id]));collapseIfClick(e, block.id, true);- if (e.shiftKey ? able.move : able.resize) drag.start(e, block, e.shiftKey ? 'slide' : 'slip');+ if (able.move) drag.start(e, block, 'move', inGroup ? current : [block.id], undefined, undefined, true);return;}if (!inGroup) setSelected(own);@@ -3041,7 +3045,7 @@ export const Timeline = React.memo(function Timeline({const onMain = tracks.filter((tr) => tr.docIndex != null && tr.docIndex === mainIndex).flatMap((tr) => tr.blocks);const main = (given ?? all.filter((b) => selectedRef.current.includes(b.id))).find(inside) ?? onMain.find(inside) ?? all.find(inside);if (!main?.clipId) return;- const ids = prefsRef.current.linked ? [main.clipId, ...linkedIds(modelRef.current, [main.clipId]).filter((id) => id !== main.clipId)] : [main.clipId];+ const ids = [main.clipId, ...linkedIds(modelRef.current, [main.clipId]).filter((id) => id !== main.clipId)];const plan = planRippleTrimTo(modelRef.current, ids, edge, atMs, followOf(prefsRef.current));void runPlan(plan, `history.stepRippleTrimmed|${main.clipId}`).then((done) => { if (done && edge === 'start') onSeek(main.startMs); });}, [tracks, runPlan, onSeek]);@@ -3068,9 +3072,9 @@ export const Timeline = React.memo(function Timeline({link: () => linkBlocks(picked()),unlink: () => unlinkBlocks(picked()),toggleMagnet: () => togglePref('magnet'),+ toggleLinkage: () => togglePref('linkage'),+ selectSide: (dir) => { setSelected(sideTargets(tracks, timeMsRef.current, dir).map((b) => b.id)); },toggleSnap: () => togglePref('snap'),- toggleSync: () => togglePref('sync'),- toggleLinked: () => togglePref('linked'),split: () => {const atMs = timeMsRef.current;const found = splitTargets(tracks, selectedRef.current, atMs, targetLaneRef.current);@@ -3155,6 +3159,17 @@ export const Timeline = React.memo(function Timeline({onSelect: () => closeGapOn(found),});}+ /* every gap on this track at once (CapCut's 批量闭合空隙) */+ const row = tracks.find((tr) => tr.lane === menu.lane);+ if (onEditOps && row?.docIndex != null && !laneLocked && gapsOf(modelRef.current, row.docIndex).length) {+ const doc = row.docIndex;+ entries.push({+ id: 'close-gaps',+ label: t('timeline.menuCloseGaps'),+ icon: <BetweenHorizontalStart size={14} />,+ onSelect: () => { void runPlan(planCloseTrackGaps(modelRef.current, doc, followOf(prefsRef.current)), 'history.stepGapsClosed'); },+ });+ }return entries;}@@ -3552,8 +3567,7 @@ export const Timeline = React.memo(function Timeline({) : null}</div>- {/* the switches (lib/timeline-prefs): the main-track magnet (insert, ripple there; off: overwrite), linkage (the- main track carries what rides on it), sync lock (ripples move every unlocked track), linked clips, snapping */}+ {/* the switches (lib/timeline-prefs), in CapCut's order: the main-track magnet, snapping, linkage */}{onEditOps ? <><span data-timeline-magnet={prefs.magnet ? '1' : '0'}><ToolButton onClick={() => togglePref('magnet')} active={prefs.magnet} label={t('timeline.magnet')}@@ -3561,30 +3575,18 @@ export const Timeline = React.memo(function Timeline({<Magnet size={15} /></ToolButton></span>- <span data-timeline-linkage={prefs.linkage ? '1' : '0'}>- <ToolButton onClick={() => togglePref('linkage')} active={prefs.linkage} label={t('timeline.linkage')}- hint={prefs.linkage ? t('timeline.linkageOn') : t('timeline.linkageOff')}>- <Paperclip size={15} />- </ToolButton>- </span>- <span data-timeline-sync={prefs.sync ? '1' : '0'}>- <ToolButton onClick={() => togglePref('sync')} active={prefs.sync} label={t('timeline.sync')}- hint={prefs.sync ? t('timeline.syncOn') : t('timeline.syncOff')}>- <Rows3 size={15} />- </ToolButton>- </span>- <span data-timeline-linked={prefs.linked ? '1' : '0'}>- <ToolButton onClick={() => togglePref('linked')} active={prefs.linked} label={t('timeline.linked')}- hint={prefs.linked ? t('timeline.linkedOn') : t('timeline.linkedOff')}>- {prefs.linked ? <Link2 size={15} /> : <Link2Off size={15} />}- </ToolButton>- </span><span data-timeline-snap={snap ? '1' : '0'}><ToolButton onClick={() => togglePref('snap')} active={snap} label={t('timeline.snap')}hint={snap ? t('timeline.snapOn') : t('timeline.snapOff')}><SeparatorVertical size={15} /></ToolButton></span>+ <span data-timeline-linkage={prefs.linkage ? '1' : '0'}>+ <ToolButton onClick={() => togglePref('linkage')} active={prefs.linkage} label={t('timeline.linkage')}+ hint={prefs.linkage ? t('timeline.linkageOn') : t('timeline.linkageOff')}>+ <Paperclip size={15} />+ </ToolButton>+ </span></> : null}{toolbarExtra}diff --git a/packages/openfilm/studio/ui/src/components/WhatsNew.tsx b/packages/openfilm/studio/ui/src/components/WhatsNew.tsxnew file mode 100644index 0000000..aec808e--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/WhatsNew.tsx@@ -0,0 +1,147 @@+/**+ * "What's new" after an update (lib/whats-new.ts): once Studio runs a newer version than the one whose notes were last+ * shown, the notes since then, in the language shown, grouped as new, improved and fixed, with the full changelog a+ * click away. Closing it marks this version seen. A new install shows nothing (it only remembers the version).+ * Settings › About shows this release's notes again, and Developer previews the newest (WHATS_NEW_EVENT).+ */+import React from 'react';+import { createPortal } from 'react-dom';+import { ArrowUpRight, Sparkles, Wrench, Zap, X } from 'lucide-react';+import { api } from '@/api';+import { useLanguage, useT } from '@/i18n';+import { RELEASES, WHATS_NEW_EVENT, compareVersions, notesToShow, releaseNotes, type NoteKind, type ReleaseNotes } from '@/lib/whats-new';++const CHANGELOG = 'https://github.com/openfilm/openfilm/releases';+const KINDS: readonly NoteKind[] = ['new', 'improved', 'fixed'];+const KIND_ICON: Record<NoteKind, React.ReactNode> = {+ new: <Sparkles size={14} aria-hidden />,+ improved: <Zap size={14} aria-hidden />,+ fixed: <Wrench size={14} aria-hidden />,+};++export function WhatsNew() {+ const t = useT();+ const language = useLanguage();+ const [shown, setShown] = React.useState<ReleaseNotes[] | null>(null);+ /** the version to mark seen when closed (after an update), null when opened on asking */+ const [marking, setMarking] = React.useState<string | null>(null);++ /* after an update: the notes since the version last shown; a new install only remembers its version */+ React.useEffect(() => {+ let live = true;+ void Promise.all([api.version(), api.prefs()]).then(([v, prefs]) => {+ if (!live) return;+ const current = v.version;+ if (!prefs.seenVersion) { void api.setPrefs({ seenVersion: current }).catch(() => {}); return; }+ if (compareVersions(prefs.seenVersion, current) >= 0) return;+ const list = notesToShow(prefs.seenVersion, current);+ if (list.length) { setShown(list); setMarking(current); } else void api.setPrefs({ seenVersion: current }).catch(() => {});+ }).catch(() => {});+ return () => { live = false; };+ }, []);++ /* asked for (Settings › About, Developer): those versions' notes */+ React.useEffect(() => {+ const onAsk = (event: Event) => {+ const versions = (event as CustomEvent<string[]>).detail ?? [];+ const list = versions.map((v) => releaseNotes(v)).filter((r): r is ReleaseNotes => r !== null);+ if (list.length) setShown(list);+ };+ window.addEventListener(WHATS_NEW_EVENT, onAsk);+ return () => window.removeEventListener(WHATS_NEW_EVENT, onAsk);+ }, []);++ const close = React.useCallback(() => {+ if (marking) void api.setPrefs({ seenVersion: marking }).catch(() => {});+ setMarking(null);+ setShown(null);+ }, [marking]);++ React.useEffect(() => {+ if (!shown) return undefined;+ /* Escape closes this alone: Settings, under it, leaves a key already handled */+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); } };+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ }, [shown, close]);++ if (!shown || typeof document === 'undefined') return null;+ const newest = shown[0];+ const date = (iso: string) => {+ const d = new Date(`${iso}T12:00:00`);+ return Number.isNaN(d.getTime()) ? iso : d.toLocaleDateString(language, { year: 'numeric', month: 'long', day: 'numeric' });+ };++ return createPortal(+ /* over Settings (z 10050), where About and Developer open it */+ <div className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/45 p-4 backdrop-blur-[2px]" onClick={close}>+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="whats-new-title"+ onClick={(e) => e.stopPropagation()}+ className="flex max-h-[min(640px,88vh)] w-full max-w-[520px] flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"+ >+ <div className="flex items-start gap-3 px-6 pb-2 pt-6">+ <div className="min-w-0 flex-1">+ <p className="text-[12px] font-medium uppercase tracking-[0.08em] text-[var(--text-faint)]">{t('whatsNew.eyebrow')}</p>+ <h2 id="whats-new-title" className="mt-1 text-[20px] font-semibold text-[var(--text)]">+ {t('whatsNew.title').replace('{version}', newest.version)}+ </h2>+ </div>+ <button type="button" onClick={close} aria-label={t('whatsNew.close')}+ className="-mr-2 -mt-1 rounded-lg p-1.5 text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">+ <X size={16} />+ </button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-6 pb-2">+ {shown.map((release) => {+ const notes = release.notes[language] ?? release.notes.en;+ return (+ <section key={release.version} className="py-3">+ <p className="mb-2.5 text-[12.5px] text-[var(--text-muted)]">+ {shown.length > 1 ? `OpenFilm ${release.version} · ` : ''}{date(release.date)}+ </p>+ <div className="flex flex-col gap-3.5">+ {KINDS.map((kind) => {+ const items = notes.filter((n) => n.kind === kind);+ if (!items.length) return null;+ return (+ <div key={kind}>+ <p className="mb-1.5 flex items-center gap-1.5 text-[12.5px] font-semibold text-[var(--text)]">+ <span className="text-[var(--text-muted)]">{KIND_ICON[kind]}</span>+ {t(`whatsNew.kind.${kind}`)}+ </p>+ <ul className="flex flex-col gap-1.5 pl-5">+ {items.map((n, i) => (+ <li key={i} className="list-disc text-[13.5px] leading-[1.6] text-[var(--text-muted)] marker:text-[var(--text-faint)]">{n.text}</li>+ ))}+ </ul>+ </div>+ );+ })}+ </div>+ </section>+ );+ })}+ </div>+ <div className="flex items-center gap-3 border-t border-[var(--border)] px-6 py-4">+ <a href={CHANGELOG} target="_blank" rel="noreferrer"+ className="inline-flex items-center gap-1 text-[13px] text-[var(--text-muted)] transition hover:text-[var(--text)]">+ {t('whatsNew.changelog')}<ArrowUpRight size={14} aria-hidden />+ </a>+ <button type="button" onClick={close} autoFocus+ className="ml-auto inline-flex h-9 items-center justify-center rounded-[8px] bg-[var(--text)] px-5 text-[14px] font-medium text-[var(--bg)] transition hover:opacity-90">+ {t('whatsNew.ok')}+ </button>+ </div>+ </div>+ </div>,+ document.body,+ );+}++/** Whether this release has notes to show again (Settings › About). */+export const hasNotes = (version: string | undefined) => Boolean(version && releaseNotes(version));+/** The newest release's notes, for a preview before it ships (Developer). */+export const newestVersion = () => RELEASES[0]?.version ?? null;diff --git a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsxindex c5b31da..dfd251c 100644--- a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx+++ b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx@@ -26,7 +26,7 @@ import { api } from '@/api';import {CODEC_LABEL,EXPORT_ALPHA_CODECS,- EXPORT_PRESETS,+ exportPresetsFor,exportDimsForShortEdge,exportEstimateBytes,exportFilmPixels,@@ -132,16 +132,18 @@ const DEFAULTS: Settings = {subtitles: { format: 'srt' },images: { format: 'png', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },slides: { format: 'pptx', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },- project: { as: 'zip', history: true, chat: false, logs: false },+ project: { as: 'zip', history: false, chat: false, logs: false },folder: '',};const STORE_KEY = 'openfilm.exportCenter.v1';-function loadSettings(): Settings {+/** What was chosen last time; the first time, the defaults (哔哩哔哩 rather than YouTube in Chinese). */+function loadSettings(language: string): Settings {+ const first = language === 'zh-CN' ? { ...DEFAULTS, presets: ['bilibili'] } : DEFAULTS;try {const raw = JSON.parse(localStorage.getItem(STORE_KEY) ?? 'null') as Partial<Settings> | null;- if (!raw || typeof raw !== 'object') return DEFAULTS;+ if (!raw || typeof raw !== 'object') return first;return {...DEFAULTS,...raw,@@ -154,10 +156,12 @@ function loadSettings(): Settings {subtitles: { ...DEFAULTS.subtitles, ...raw.subtitles },images: { ...DEFAULTS.images, ...raw.images },slides: { ...DEFAULTS.slides, ...raw.slides },- project: { ...DEFAULTS.project, ...raw.project },+ /* the parts besides the work start off each time (history, chat and logs are the person's own): only zip or+ folder is kept */+ project: { ...DEFAULTS.project, ...(raw.project?.as === 'folder' ? { as: 'folder' } : {}) },};} catch {- return DEFAULTS;+ return first;}}@@ -220,12 +224,19 @@ export interface ExportCenterProps {onQueued?: (jobs: ExportJob[]) => void;/** The project's frame rate (`.film/settings.json`, else its footage's): a video's rate unless another is picked. */projectFps?: number;+ /** Media files the film uses that are gone: an export that draws or plays the film stops at them, so it is held back. */+ missingFiles?: readonly string[];}+/** What draws or plays the film, and so needs every file it uses. */+const RENDERS: ReadonlySet<Dest> = new Set(['social', 'video', 'alpha', 'gif', 'audio', 'images', 'slides']);+export function ExportCenter(props: ExportCenterProps) {const { open, onClose } = props;const t = useT();const language = useLanguage();+ /** the platforms offered in this language (a platform picked in another and not offered here is not exported) */+ const presets = React.useMemo(() => exportPresetsFor(language), [language]);const [can, setCan] = React.useState<ExportCapabilities | null>(null);/** 剪映 and CapCut on this computer: an editing project for one goes into its drafts */const [draftApps, setDraftApps] = React.useState<{ jianying: boolean; capcut: boolean }>({ jianying: false, capcut: false });@@ -246,7 +257,7 @@ export function ExportCenter(props: ExportCenterProps) {React.useEffect(() => {if (!open) return;- const loaded = loadSettings();+ const loaded = loadSettings(language);setS(props.focusClipId? { ...loaded, dest: 'alpha', alpha: { ...loaded.alpha, source: props.focusClipId } }: loaded);@@ -369,7 +380,7 @@ export function ExportCenter(props: ExportCenterProps) {const burn = (on: boolean) => (captions > 0 && on ? { burnSubtitles: true } : {});switch (dest) {case 'social':- return s.presets.map((id) => EXPORT_PRESETS.find((p) => p.id === id) ?? null).filter((p) => p !== null).map((p) => ({+ return s.presets.map((id) => presets.find((p) => p.id === id) ?? null).filter((p) => p !== null).map((p) => ({kind: 'video', codec: 'h264', frame: p.frame, fill: 'contain', shortEdge: p.shortEdge, fps: p.fps,quality: s.socialQuality, audio: true, preset: p.name, label: p.name,...burn(s.socialSubs === 'auto' ? p.burnSubtitles : s.socialSubs === 'on'), ...ranged,@@ -418,7 +429,7 @@ export function ExportCenter(props: ExportCenterProps) {}];}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [dest, s, can, nleApp, draftApp, rangeSec?.[0], rangeSec?.[1], props.frame, blocks, nleSourceFps, captions, projectParts]);+ }, [dest, s, can, presets, nleApp, draftApp, rangeSec?.[0], rangeSec?.[1], props.frame, blocks, nleSourceFps, captions, projectParts]);/* a range, not a size: what is in the picture decides a video's or a GIF's size (export-spec.ts); sound is exact */const estBytes = React.useMemo(() => requests.reduce<[number, number]>(([low, high], r) => {@@ -462,7 +473,14 @@ export function ExportCenter(props: ExportCenterProps) {return n + 1;}, 0);+ /* files the film uses that are gone: said first, by name, before anything is queued (it would stop at them) */+ const missing = props.missingFiles ?? [];+ const missingReason = missing.length && RENDERS.has(dest)+ ? t('exportCenter.missingMedia').replace('{n}', String(missing.length))+ .replace('{files}', missing.slice(0, 3).map((f) => f.split('/').pop()).join(', ') + (missing.length > 3 ? ', …' : ''))+ : null;const emptyReason = ((): string | null => {+ if (missingReason) return missingReason;if (!totalMs && dest !== 'project') return t('exportCenter.emptyFilm');if (dest === 'social' && requests.length === 0) return t('exportCenter.pickPreset');if (dest === 'subtitles' && captionCount != null && captions === 0) return t('exportCenter.noCaptions');@@ -602,7 +620,7 @@ export function ExportCenter(props: ExportCenterProps) {{PRESET_GROUPS.map((group) => (<Field key={group} label={t(`exportCenter.group.${group}`)}><div className="grid grid-cols-2 gap-2 sm:grid-cols-3">- {EXPORT_PRESETS.filter((p) => p.group === group).map((p) => {+ {presets.filter((p) => p.group === group).map((p) => {const on = s.presets.includes(p.id);const dims = exportDimsForShortEdge(filmFrameBox(stage, p.frame), p.shortEdge);const tooLong = p.maxDurationSec != null && rangeMs / 1000 > p.maxDurationSec;@@ -947,7 +965,7 @@ export function ExportCenter(props: ExportCenterProps) {<div className="flex flex-col gap-2.5"><PartTogglechecked- disabled+ lockedonChange={() => {}}label={t('exportCenter.projectPart.work')}hint={t('exportCenter.projectPartHint.work')}@@ -1144,7 +1162,7 @@ export function ExportCenter(props: ExportCenterProps) {{result ? (<span className={result.ok ? 'text-[var(--ok)]' : 'text-[var(--err)]'}>{result.text}</span>) : emptyReason ? (- <span className="text-[var(--text-faint)]">{emptyReason}</span>+ <span data-export-reason="" className={missingReason ? 'text-[var(--warn)]' : 'text-[var(--text-faint)]'}>{emptyReason}</span>) : (<>{/* a project is not a length of film: its size only */}@@ -1300,20 +1318,26 @@ function Segmented<V extends string>({ value, options, onChange }: {);}-function Toggle({ checked, onChange, label, disabled }: {- checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean;+/**+ * A switch and its words: lit when on, quieter when off, faint when it can't be had. `locked`: always on (a part that+ * is always taken), shown on in full, not to be switched.+ */+function Toggle({ checked, onChange, label, disabled, locked }: {+ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean; locked?: boolean;}) {+ const tone = disabled ? 'text-[var(--text-faint)]' : checked || locked ? 'text-[var(--text)]' : 'text-[var(--text-muted)]';return (- <label className={`flex select-none items-center gap-2.5 text-[12.5px] ${disabled ? 'cursor-default text-[var(--text-faint)]' : 'cursor-pointer text-[var(--text)]'}`}>+ <label className={`flex select-none items-center gap-2.5 text-[12.5px] ${tone} ${disabled || locked ? 'cursor-default' : 'cursor-pointer'}`}><buttontype="button"role="switch"- aria-checked={checked}+ aria-checked={checked || Boolean(locked)}+ aria-readonly={locked || undefined}disabled={disabled}- onClick={() => onChange(!checked)}- className={`relative h-[18px] w-[30px] shrink-0 rounded-full transition ${checked ? 'bg-[var(--text)]' : 'bg-[var(--border-strong,var(--border))]'} disabled:opacity-50`}+ onClick={() => { if (!locked) onChange(!checked); }}+ className={`relative h-[18px] w-[30px] shrink-0 rounded-full transition ${checked || locked ? 'bg-[var(--text)]' : 'bg-[var(--border-strong,var(--border))]'} ${locked ? 'cursor-default' : ''} disabled:opacity-50`}>- <span className={`absolute top-[2px] h-[14px] w-[14px] rounded-full bg-[var(--bg)] transition-[left] ${checked ? 'left-[14px]' : 'left-[2px]'}`} />+ <span className={`absolute top-[2px] h-[14px] w-[14px] rounded-full bg-[var(--bg)] transition-[left] ${checked || locked ? 'left-[14px]' : 'left-[2px]'}`} /></button>{label}</label>@@ -1321,13 +1345,13 @@ function Toggle({ checked, onChange, label, disabled }: {}/** A part of the project to take or leave: the switch, what the part is, and how big. */-function PartToggle({ checked, onChange, label, hint, size, disabled }: {- checked: boolean; onChange: (v: boolean) => void; label: string; hint: string; size: string; disabled?: boolean;+function PartToggle({ checked, onChange, label, hint, size, disabled, locked }: {+ checked: boolean; onChange: (v: boolean) => void; label: string; hint: string; size: string; disabled?: boolean; locked?: boolean;}) {return (<div className="flex flex-col gap-0.5"><div className="flex items-center gap-2">- <Toggle checked={checked} onChange={onChange} label={label} disabled={disabled} />+ <Toggle checked={checked} onChange={onChange} label={label} disabled={disabled} locked={locked} />{size && <span className="ml-auto font-mono text-[11px] tabular-nums text-[var(--text-faint)]">{size}</span>}</div><p className="pl-[40px] text-[11.5px] leading-snug text-[var(--text-faint)]">{hint}</p>diff --git a/packages/openfilm/studio/ui/src/components/player-controls/transport.tsx b/packages/openfilm/studio/ui/src/components/player-controls/transport.tsxindex 0cd310c..4989883 100644--- a/packages/openfilm/studio/ui/src/components/player-controls/transport.tsx+++ b/packages/openfilm/studio/ui/src/components/player-controls/transport.tsx@@ -1,7 +1,8 @@/** The player bar's two parts: the seek bar and the round icon button. */import React from 'react';import { useT } from '@/i18n';-import { secondFrames, stepFrames } from '@/lib/timecode';+import { stepFrames } from '@/lib/timecode';+import { JUMP_FRAMES } from '@/lib/timeline-keys';/** The played part and the knob. */const SEEK_COLOR = '#f03';@@ -105,7 +106,7 @@ export function TransportSeekBar({event.stopPropagation();/* a frame, ⇧ a second: the arrows step the same everywhere in Studio */const next = event.key === 'Home' ? 0 : event.key === 'End' ? totalMs- : Math.max(0, Math.min(totalMs, stepFrames(timeMs, (event.key === 'ArrowRight' ? 1 : -1) * (event.shiftKey ? secondFrames() : 1))));+ : Math.max(0, Math.min(totalMs, stepFrames(timeMs, (event.key === 'ArrowRight' ? 1 : -1) * (event.shiftKey ? JUMP_FRAMES : 1))));onPreview(next);onCommit(next);}}diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsxindex aee1d8a..df79296 100644--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx@@ -2,16 +2,23 @@* Settings → Agents, inside an app that has a chat (lib/host.ts `agents`): the agents its chat can use, each connected* or not and shown in the chat's menu or not.*- * Codex, Claude Code, Gemini CLI and the others are the person's own programs, with their own sign-in: connecting- * uses it as it is and opens their own sign-in only when they are signed out (the app waits for it); disconnecting- * stops the app using them and leaves their sign-in alone, since the makers' own apps share it. Codex and Claude Code+ * Codex, Claude Code, Gemini CLI and the others are the person's own programs, on the account signed in on the+ * computer: connecting opens their own sign-in only when they are signed out (the app waits for it), disconnecting+ * only stops the app using them, and connecting again uses the account signed in then (switched in the agent itself).+ * Claude Code's and Codex's rows say whose account it is, and Codex's what is left of its plan. Codex and Claude Code* are always listed under the person's agents, with the person's own key; the others there once switched on (connecting* one does), else under "More agents", with where to get them when they are not installed. The person's own key is on a service of theirs, with a model that reads pictures (the agent looks at its own frames).+ *+ * One not found can be pointed at: Locate… opens the system's file dialog, the program chosen is tried and used from+ * then on (Find automatically goes back). "Why isn't it found?" says what was searched, with a report to copy.*/import React from 'react';-import { Download, KeyRound, Loader2 } from 'lucide-react';-import { useT } from '@/i18n';-import { studioHost, type HostAgent, type HostAgentId, type HostByokFormat } from '@/lib/host';+import { Check, Copy, Download, KeyRound, Loader2 } from 'lucide-react';+import { useLanguage, useT } from '@/i18n';+import { studioHost, type HostAgent, type HostAgentDiagnosis, type HostAgentId, type HostAgentUsage, type HostByokFormat } from '@/lib/host';++/** What is left of the plan: what Codex can say (the app's agent-usage.mjs; Claude Code's own report is wrong for Team accounts). */+const PLAN_AGENTS: readonly HostAgentId[] = ['codex'];import { ProviderMark } from './ProviderMark';import { agentMark } from '@/lib/provider-marks';import { SettingsSelect } from './SettingsSelect';@@ -40,13 +47,65 @@ function AgentMark({ id }: { id: HostAgentId }) {return id === 'byok' ? <KeyRound size={16} /> : <ProviderMark id={agentMark(id)} size={17} />;}+/**+ * What is left of Codex's plan, when it is ready: asked as it becomes ready and when the window comes back into focus+ * (the app keeps an answer a minute). `undefined`: being asked; null: it can't say.+ */+function useAgentUsage(agents: HostAgent[] | null): Partial<Record<HostAgentId, HostAgentUsage | null | undefined>> {+ const [usage, setUsage] = React.useState<Partial<Record<HostAgentId, HostAgentUsage | null | undefined>>>({});+ const ready = (agents ?? []).filter((a) => PLAN_AGENTS.includes(a.id) && a.status === 'ready').map((a) => a.id).join(',');+ React.useEffect(() => {+ const ask = studioHost?.agents?.usage;+ if (!ask || !ready) return undefined;+ let live = true;+ const look = () => {+ for (const id of ready.split(',') as HostAgentId[]) {+ void ask(id).then((u) => { if (live) setUsage((was) => ({ ...was, [id]: u })); }).catch(() => { if (live) setUsage((was) => ({ ...was, [id]: null })); });+ }+ };+ look();+ window.addEventListener('focus', look);+ return () => { live = false; window.removeEventListener('focus', look); };+ }, [ready]);+ return usage;+}++/** One window of a plan: what it is, a bar of its share used, and when it resets. */+function UsageBar({ window: w }: { window: HostAgentUsage['windows'][number] }) {+ const t = useT();+ const language = useLanguage();+ const label = w.kind === 'five_hour' ? t('settings.agents.usageFiveHour')+ : w.kind === 'seven_day' ? t('settings.agents.usageWeek')+ : t('settings.agents.usageWindow').replace('{hours}', String(Math.round((w.minutes ?? 0) / 60)));+ const used = Math.round(w.usedPercent);+ const resets = (() => {+ if (w.resetsAt == null) return null;+ const minutes = Math.max(0, Math.round((w.resetsAt - Date.now()) / 60_000));+ const rtf = new Intl.RelativeTimeFormat(language, { numeric: 'auto' });+ const when = minutes < 60 ? rtf.format(minutes, 'minute') : minutes < 48 * 60 ? rtf.format(Math.round(minutes / 60), 'hour') : rtf.format(Math.round(minutes / 1440), 'day');+ return t('settings.agents.usageResets').replace('{time}', when);+ })();+ return (+ <div className="flex items-center gap-3 text-[13px]">+ <span className="w-[92px] shrink-0 text-[var(--text-muted)]">{label}</span>+ <div className="h-1.5 min-w-[80px] flex-1 overflow-hidden rounded-full bg-[var(--fill-tsp)]" role="progressbar" aria-label={label} aria-valuenow={used} aria-valuemin={0} aria-valuemax={100}>+ <div className={`h-full rounded-full ${used >= 90 ? 'bg-[var(--danger,#e5484d)]' : used >= 70 ? 'bg-[var(--warn,#f5a524)]' : 'bg-[var(--text)]'}`} style={{ width: `${Math.max(used, 1.5)}%` }} />+ </div>+ <span className="w-[64px] shrink-0 text-right tabular-nums text-[var(--text)]">{t('settings.agents.usageUsed').replace('{percent}', String(used))}</span>+ <span className="w-[120px] shrink-0 truncate text-[var(--text-faint)]">{resets ?? ''}</span>+ </div>+ );+}+export function AgentsSection() {const t = useT();const agents = useHostAgents();+ const usage = useAgentUsage(agents);const host = studioHost?.agents;const [busy, setBusy] = React.useState<HostAgentId | null>(null);const [error, setError] = React.useState<{ id: HostAgentId; text: string } | null>(null);const [keyOpen, setKeyOpen] = React.useState(false);+ const [diagnosis, setDiagnosis] = React.useState<{ id: HostAgentId; report: HostAgentDiagnosis | null; copied?: boolean } | null>(null);if (!host) return null;const act = (id: HostAgentId, run: () => Promise<{ ok?: boolean; error?: string } | unknown>) => {@@ -58,6 +117,39 @@ export function AgentsSection() {.finally(() => setBusy(null));};+ /* the person points at the program: tried by the app before it is used; cancelling says nothing */+ const locate = (agent: HostAgent) => act(agent.id, async () => {+ const r = await host.locate!(agent.id, { title: t('settings.agents.locateTitle').replace('{name}', agent.name), button: t('settings.agents.locateButton') });+ if (r.ok) setDiagnosis(null);+ if (r.ok || (!r.error && !r.code)) return { ok: true };+ if (r.code === 'not-a-program') return { ok: false, error: t('settings.agents.notAProgram') };+ if (r.code === 'did-not-start') return { ok: false, error: `${t('settings.agents.didNotStart')} ${r.error ?? ''}`.trim() };+ return r;+ });++ const diagnose = (agent: HostAgent) => {+ setDiagnosis({ id: agent.id, report: null });+ void host.diagnose!(agent.id)+ .then((report) => setDiagnosis((d) => (d?.id === agent.id ? { id: agent.id, report } : d)))+ .catch((e: unknown) => { setDiagnosis(null); setError({ id: agent.id, text: e instanceof Error ? e.message : String(e) }); });+ };++ const hintOf = (report: HostAgentDiagnosis) => {+ switch (report.hint) {+ case 'chosen-missing': return t('settings.agents.hintChosenMissing');+ case 'wsl': return t('settings.agents.hintWsl');+ case 'unusable': return t('settings.agents.hintUnusable');+ case 'none': return t('settings.agents.hintNone').replaceAll('{program}', report.program ?? '');+ default: return report.found ? t('settings.agents.hintFound').replace('{path}', report.found) : null;+ }+ };++ const copyReport = (report: HostAgentDiagnosis, id: HostAgentId) => {+ void navigator.clipboard.writeText(report.text)+ .then(() => setDiagnosis((d) => (d?.id === id ? { ...d, copied: true } : d)))+ .catch(() => {});+ };+const statusLine = (agent: HostAgent) => {switch (agent.status) {case 'off': return t('settings.agents.off');@@ -71,14 +163,44 @@ export function AgentsSection() {}};+ /* whose sign-in it is: an account's organization, email and plan as the program says them, or how it signs in */+ const accountLine = (agent: HostAgent) => {+ /* Codex says its email and plan only to its app server: the usage's answer, when it has come */+ const told = usage[agent.id]?.account;+ const a = agent.account ? { ...agent.account, ...(told?.email ? { email: told.email } : {}), ...(told?.plan && !agent.account.plan ? { plan: told.plan } : {}) } : null;+ if (!a) return null;+ const how = a.method === 'chatgpt' ? t('settings.agents.accountChatgpt') : a.method === 'api-key' ? t('settings.agents.accountApiKey')+ : a.method === 'console' ? t('settings.agents.accountConsole') : null;+ const plan = a.plan ? a.plan.charAt(0).toUpperCase() + a.plan.slice(1) : null;+ const parts = [a.org, a.email, plan, a.email || a.org ? null : how].filter(Boolean);+ return parts.length ? parts.join(' · ') : null;+ };+/* `chosen`: among the agents in use (not under "More agents", where one ready to use is offered to connect) */const action = (agent: HostAgent, chosen = true) => {const working = busy === agent.id;if (agent.status === 'ready' && chosen) {- return <SettingsButton variant="quiet" disabled={working} onClick={() => act(agent.id, () => host.disconnect(agent.id))}>{t('settings.agents.disconnect')}</SettingsButton>;+ return (+ <SettingsButton variant="quiet" disabled={working} title={agent.id === 'byok' ? undefined : t('settings.agents.disconnectHint').replaceAll('{name}', agent.name)}+ onClick={() => act(agent.id, () => host.disconnect(agent.id))}>+ {t('settings.agents.disconnect')}+ </SettingsButton>+ );}if (agent.status === 'missing') {- return agent.install ? <SettingsLinkButton href={agent.install}><Download size={16} />{t('settings.agents.install')}</SettingsLinkButton> : null;+ const canLocate = host.locate && agent.setupRequired !== 'code-tab';+ if (!agent.install && !canLocate) return null;+ return (+ <>+ {canLocate ? (+ <SettingsButton variant="quiet" disabled={working} onClick={() => locate(agent)}>+ {working ? <Loader2 size={16} className="animate-spin" aria-hidden /> : null}+ {t('settings.agents.locate')}+ </SettingsButton>+ ) : null}+ {agent.install ? <SettingsLinkButton href={agent.install}><Download size={16} />{t('settings.agents.install')}</SettingsLinkButton> : null}+ </>+ );}if (agent.status === 'key') return <SettingsButton onClick={() => setKeyOpen(true)}>{t('settings.agents.setUpKey')}</SettingsButton>;if (agent.status === 'unavailable') return null;@@ -95,6 +217,13 @@ export function AgentsSection() {const ownKey = agent.id === 'byok' && agent.byok;const said = error?.id === agent.id ? error.text : agent.error;const open = agent.id === 'byok' && keyOpen;+ /* where it is not found: why, on asking (Claude Code waiting for its app's Code tab is not lost) */+ const lost = agent.status === 'missing' && agent.setupRequired !== 'code-tab' && Boolean(host.diagnose);+ const diag = diagnosis?.id === agent.id ? diagnosis : null;+ /* what is left of its plan: while being asked, and once told (an agent that can't say shows nothing) */+ const plan = usage[agent.id];+ const meter = chosen && agent.status === 'ready' && PLAN_AGENTS.includes(agent.id) && Boolean(host.usage) && (plan === undefined || Boolean(plan?.windows.length));+ const hint = diag?.report ? hintOf(diag.report) : null;return (<SettingsItemkey={agent.id}@@ -112,7 +241,7 @@ export function AgentsSection() {{agent.status === 'ready' && chosen ? <SettingsStatus>{ownKey ? `${byokModels(agent).join(', ')} · •••• ${agent.byok!.last4}` : t('settings.agents.ready')}</SettingsStatus> : null}</>)}- description={agent.status === 'ready' ? null : statusLine(agent)}+ description={agent.status === 'ready' ? accountLine(agent) : statusLine(agent)}control={(<>{ownKey && !open ? <SettingsButton variant="quiet" onClick={() => setKeyOpen(true)}>{t('settings.agents.change')}</SettingsButton> : null}@@ -122,8 +251,44 @@ export function AgentsSection() {</>)}>- {agent.status === 'waiting' || open || said ? (+ {agent.status === 'waiting' || open || said || agent.chosen || lost || meter ? (<div className="flex flex-col gap-1.5 pl-[34px]">+ {meter ? (+ <div className="flex flex-col gap-1.5" aria-label={t('settings.agents.usage')}>+ {plan === undefined ? (+ <p className="flex items-center gap-1.5 text-[13px] text-[var(--text-faint)]"><Loader2 size={13} className="animate-spin" aria-hidden />{t('settings.agents.usageLoading')}</p>+ ) : plan?.windows.map((w) => <UsageBar key={w.kind + (w.minutes ?? '')} window={w} />)}+ </div>+ ) : null}+ {agent.chosen ? (+ <p className="break-all text-[13.5px] leading-relaxed text-[var(--text-muted)]">+ {t('settings.agents.chosenAt').replace('{path}', agent.chosen)}{' '}+ {host.useAutomatic ? (+ <button type="button" onClick={() => act(agent.id, () => host.useAutomatic!(agent.id))} className="underline underline-offset-2 hover:text-[var(--text)]">{t('settings.agents.automatic')}</button>+ ) : null}+ </p>+ ) : null}+ {lost && !diag ? (+ <p className="text-[13.5px] leading-relaxed text-[var(--text-muted)]">+ <button type="button" onClick={() => diagnose(agent)} className="underline underline-offset-2 hover:text-[var(--text)]">{t('settings.agents.whyMissing')}</button>+ </p>+ ) : null}+ {lost && diag && !diag.report ? (+ <p className="flex items-center gap-1.5 text-[13.5px] text-[var(--text-muted)]"><Loader2 size={14} className="animate-spin" aria-hidden />{t('settings.agents.searching')}</p>+ ) : null}+ {lost && diag?.report ? (+ <SettingsInset>+ {hint ? <p className="break-words text-[14px] leading-relaxed text-[var(--text)]">{hint}</p> : null}+ <p className="text-[13px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.reportNote')}</p>+ <div className="flex justify-end gap-1.5">+ <SettingsButton variant="quiet" onClick={() => setDiagnosis(null)}>{t('settings.agents.close')}</SettingsButton>+ <SettingsButton onClick={() => copyReport(diag.report!, agent.id)}>+ {diag.copied ? <Check size={15} aria-hidden /> : <Copy size={15} aria-hidden />}+ {diag.copied ? t('settings.agents.copied') : t('settings.agents.copyReport')}+ </SettingsButton>+ </div>+ </SettingsInset>+ ) : null}{agent.status === 'waiting' ? (<p className="text-[14.5px] leading-relaxed text-[var(--text-muted)]">{t('settings.agents.waitingHint')}{' '}diff --git a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsxindex 8e8c240..6fd677d 100644--- a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx@@ -2,15 +2,18 @@* Settings, opened from the logo at the top left: a search and the sections in groups on the left, the section on the* right as a page of titled groups. General (the theme and the language), Agents (in an app with a chat: the agents* it can use), Providers (the person's own keys for media services), Models (which provider and model makes each kind- * of media) and the keyboard shortcuts; the search finds a section by any phrase on it.+ * of media), the keyboard shortcuts and Developer; the search finds a section by any phrase on it. At the foot of the+ * nav, quietly, where OpenFilm lives: its code, the examples and the website.*/import React from 'react';import { createPortal } from 'react-dom';-import { X, Settings2, Keyboard, Sun, Moon, Monitor, Plug, Boxes, Bot, Search, SquareTerminal } from 'lucide-react';+import { X, Settings2, Keyboard, Sun, Moon, Monitor, Plug, Boxes, Bot, Search, SquareTerminal, Loader2 } from 'lucide-react';import { LANGUAGES, phrasesUnder, useLanguage, useLanguageChoice, useT, type LanguageChoice } from '@/i18n';import { shortcutHint } from '@/lib/shortcut-hint';import { SHORTCUTS, type ShortcutKey } from '@/lib/timeline-keys';-import { studioHost } from '@/lib/host';+import { studioHost, type HostDeveloper, type HostUpdateState } from '@/lib/host';+import { showWhatsNew } from '@/lib/whats-new';+import { hasNotes, newestVersion } from '../WhatsNew';import { api, type StudioPrefs, type StudioVersion } from '@/api';import { AgentsSection } from './AgentsSection';import { ModelsSection } from './ModelsSection';@@ -21,11 +24,18 @@ import { useThemeMode, type ThemeMode } from './theme';export type SettingsSection = 'general' | 'agents' | 'providers' | 'models' | 'developer' | 'shortcuts';-/* the nav, in groups: what OpenFilm does (Agents and Developer only inside an app with a chat: lib/host.ts `agents`,- `developer`), then help */+/* the nav, in groups: what OpenFilm does, then help (Agents and Developer only inside an app with a chat:+ lib/host.ts `agents`, `developer`) */const NAV: Array<{ group: 'settings' | 'help'; sections: SettingsSection[] }> = [- { group: 'settings', sections: ['general', ...(studioHost?.agents ? ['agents' as const] : []), 'providers', 'models', ...(studioHost?.developer ? ['developer' as const] : [])] },- { group: 'help', sections: ['shortcuts'] },+ { group: 'settings', sections: ['general', ...(studioHost?.agents ? ['agents' as const] : []), 'providers', 'models'] },+ { group: 'help', sections: ['shortcuts', ...(studioHost?.developer ? ['developer' as const] : [])] },+];++/** where OpenFilm lives, linked at the foot of the nav */+const LINKS = [+ { label: 'settings.links.github', href: 'https://github.com/openfilm/openfilm' },+ { label: 'settings.links.examples', href: 'https://github.com/openfilm/examples' },+ { label: 'settings.links.site', href: 'https://openfilm.dev' },];const SECTION_ICON: Record<SettingsSection, React.ReactNode> = {@@ -158,6 +168,11 @@ export function SettingsModal({ open, onClose, section: opening }: SettingsModal</div>))}{found.length === 0 ? <p className="px-2.5 pt-4 text-[14px] text-[var(--text-faint)]">{t('settings.noResults')}</p> : null}+ <div className="mt-auto flex flex-wrap gap-x-4 gap-y-1 px-2.5 pt-6 text-[13px] text-[var(--text-faint)]">+ {LINKS.map((link) => (+ <a key={link.href} href={link.href} target="_blank" rel="noreferrer" className="rounded-[4px] transition hover:text-[var(--text)]">{t(link.label)}</a>+ ))}+ </div></nav><div className="relative flex min-w-0 flex-1 flex-col">@@ -223,7 +238,7 @@ function GeneralSection() {/></SettingsGroup><PlaybackGroup />- <AboutGroup />+ {studioHost?.update?.onState ? <AppAboutGroup /> : <AboutGroup />}</SettingsPage>);}@@ -238,7 +253,7 @@ function PlaybackGroup() {React.useEffect(() => { void api.prefs().then(setPrefs).catch(() => {}); }, []);if (!prefs) return null;const change = (proxies: Partial<StudioPrefs['proxies']>) => {- setPrefs({ proxies: { ...prefs.proxies, ...proxies } });+ setPrefs({ ...prefs, proxies: { ...prefs.proxies, ...proxies } });void api.setPrefs({ proxies }).then(setPrefs).catch(() => {});};return (@@ -299,7 +314,9 @@ function AboutGroup() {control={inApp || !info?.checking ? null : (<SettingsButton disabled={state === 'checking'} onClick={check}>{t('settings.about.check')}</SettingsButton>)}- />+ >+ {hasNotes(info?.version) ? <WhatsNewLink version={info!.version} /> : null}+ </SettingsItem>{!inApp && !info?.source && info?.newer ? (<SettingsItemtitle={t('settings.about.howTitle')}@@ -311,26 +328,129 @@ function AboutGroup() {);}-/** The app's developer mode: each turn's full log in its chat (lib/host.ts `developer`). */+/** This release's notes again (components/WhatsNew). */+function WhatsNewLink({ version }: { version: string }) {+ const t = useT();+ return (+ <button type="button" onClick={() => showWhatsNew([version])}+ className="mb-2 text-[13.5px] text-[var(--text-muted)] underline underline-offset-2 transition hover:text-[var(--text)]">+ {t('settings.about.whatsNew')}+ </button>+ );+}++/** A check that answered this long ago is still news: opening About within it looks again only on a click. */+const CHECKED_FRESH_MS = 10 * 60_000;++/**+ * The app's version and its update (lib/host.ts `update`), as an app's About shows them: looked for on opening (unless+ * a check answered a few minutes ago), downloaded by itself with its progress, Restart when it is ready (it installs at+ * the next quit too). The menu's Check for Updates… stays.+ */+function AppAboutGroup() {+ const t = useT();+ const language = useLanguage();+ const update = studioHost?.update;+ const [state, setState] = React.useState<HostUpdateState | null>(null);+ const [refused, setRefused] = React.useState<string | null>(null);+ React.useEffect(() => update?.onState?.(setState), [update]);+ /* looked for once on opening, when the last answer is old or there is none */+ const looked = React.useRef(false);+ React.useEffect(() => {+ if (!state || looked.current) return;+ looked.current = true;+ const stale = state.checkedAt == null || Date.now() - state.checkedAt > CHECKED_FRESH_MS;+ if (stale && ['idle', 'current', 'error'].includes(state.status)) void update?.check?.();+ }, [state, update]);+ const check = () => { setRefused(null); void update?.check?.(); };+ const restart = () => {+ setRefused(null);+ void update?.restart().then((r) => { if (!r.ok && r.error) setRefused(r.error); });+ };+ const ago = (at: number) => {+ const minutes = Math.round((Date.now() - at) / 60_000);+ const rtf = new Intl.RelativeTimeFormat(language, { numeric: 'auto' });+ return minutes < 60 ? rtf.format(-minutes, 'minute') : minutes < 48 * 60 ? rtf.format(-Math.round(minutes / 60), 'hour') : rtf.format(-Math.round(minutes / 1440), 'day');+ };+ const s = state;+ const next = s?.availableVersion ?? '';+ const waiting = refused ?? (s?.status === 'ready' ? s.error : null);+ const why = waiting === 'agent-busy' ? t('update.agentBusy') : waiting === 'exporting' ? t('update.exporting')+ : waiting === 'install-failed' ? t('update.installFailed').replace('{version}', next) : null;+ const errorText = s?.error === 'offline' ? t('settings.about.appOffline') : s?.error === 'unavailable' ? t('settings.about.appUnavailable') : t('settings.about.appFailed');+ const busy = (text: string) => <span className="inline-flex items-center gap-1.5"><Loader2 size={13} className="animate-spin" aria-hidden />{text}</span>;+ const description = !s ? null+ : s.status === 'off' ? t('settings.about.appOff')+ : s.status === 'idle' || s.status === 'checking' ? busy(t('settings.about.checking'))+ : s.status === 'current' ? `${t('settings.about.upToDate')}${s.checkedAt ? ` ${t('settings.about.appChecked').replace('{time}', ago(s.checkedAt))}` : ''}`+ : s.status === 'available' || s.status === 'downloading' ? busy(`${t('settings.about.appDownloading').replace('{version}', next)}${s.status === 'downloading' ? ` ${Math.round(s.progress)}%` : ''}`)+ : s.status === 'staging' ? busy(t('settings.about.appStaging').replace('{version}', next))+ : s.status === 'ready' ? (why ?? t('update.ready').replace('{version}', next))+ : s.status === 'installing' ? busy(t('update.installing'))+ : errorText;+ const control = !s ? null+ : s.status === 'current' ? <SettingsButton onClick={check}>{t('settings.about.check')}</SettingsButton>+ : s.status === 'error' ? <SettingsButton onClick={check}>{t('settings.about.appRetry')}</SettingsButton>+ : s.status === 'ready' ? <SettingsButton variant="primary" onClick={restart}>{t('update.restart')}</SettingsButton>+ : null;+ return (+ <SettingsGroup title={t('settings.about.group')}>+ <SettingsItem+ title={`OpenFilm ${s?.version ?? ''}`.trim()}+ badge={s?.channel === 'beta' ? <span className="rounded-full bg-[var(--fill-tsp)] px-2 py-0.5 text-[11.5px] text-[var(--text-muted)]">beta</span> : null}+ description={description}+ control={control}+ >+ {hasNotes(s?.version) ? <WhatsNewLink version={s!.version} /> : null}+ {s?.status === 'downloading' ? (+ <div className="h-1 overflow-hidden rounded-full bg-[var(--fill-tsp)]" role="progressbar" aria-valuenow={Math.round(s.progress)} aria-valuemin={0} aria-valuemax={100}>+ <div className="h-full rounded-full bg-[var(--text)] transition-[width]" style={{ width: `${Math.max(2, s.progress)}%` }} />+ </div>+ ) : null}+ </SettingsItem>+ </SettingsGroup>+ );+}++/** What the app's chat shows of each turn: what it changed in the files, and its full log (lib/host.ts `developer`). */function DeveloperSection() {const t = useT();const developer = studioHost?.developer;- const [on, setOn] = React.useState<boolean | null>(null);+ const [prefs, setPrefs] = React.useState<HostDeveloper | null>(null);React.useEffect(() => {if (!developer) return undefined;- void developer.get().then(setOn);- return developer.onChange(setOn);+ void developer.get().then(setPrefs);+ return developer.onChange(setPrefs);}, [developer]);if (!developer) return null;+ const change = (next: Partial<HostDeveloper>) => {+ setPrefs((was) => (was ? { ...was, ...next } : was));+ void developer.set(next);+ };return (<SettingsPage note={t('settings.developer.intro')}><SettingsGroup title={t('settings.developer.group')} footnote={t('settings.developer.where')}>+ {/* drawn once the app has said whether each is on: drawn off first, a switch slid on each time the page opened */}+ <SettingsItem+ title={t('settings.developer.changes')}+ description={t('settings.developer.changesHint')}+ control={prefs ? <SettingsSwitch checked={prefs.changes} label={t('settings.developer.changes')} onChange={(on) => change({ changes: on })} /> : null}+ /><SettingsItemtitle={t('settings.developer.logs')}description={t('settings.developer.logsHint')}- control={<SettingsSwitch checked={on === true} disabled={on === null} label={t('settings.developer.logs')} onChange={(next) => { setOn(next); void developer.set(next); }} />}+ control={prefs ? <SettingsSwitch checked={prefs.logs} label={t('settings.developer.logs')} onChange={(on) => change({ logs: on })} /> : null}/></SettingsGroup>+ {newestVersion() ? (+ <SettingsGroup title={t('settings.developer.releaseGroup')}>+ <SettingsItem+ title={t('settings.developer.previewWhatsNew')}+ description={t('settings.developer.previewWhatsNewHint').replace('{version}', newestVersion()!)}+ control={<SettingsButton onClick={() => showWhatsNew([newestVersion()!])}>{t('settings.developer.preview')}</SettingsButton>}+ />+ </SettingsGroup>+ ) : null}</SettingsPage>);}@@ -347,7 +467,7 @@ function ShortcutsSection() {/* a key as this platform writes it: ⌘⇧B on a Mac, Ctrl+Shift+B elsewhere; ⌫ is Backspace off a Mac */const keyText = (key: ShortcutKey): string => {const name = !mac && key.key === '⌫' ? 'Backspace' : key.key;- const mods = [key.mod ? (mac ? '⌘' : 'Ctrl') : '', key.alt ? alt : '', key.shift ? (mac ? '⇧' : 'Shift') : ''].filter(Boolean);+ const mods = [key.ctrl ? (mac ? '⌃' : 'Ctrl') : '', key.mod ? (mac ? '⌘' : 'Ctrl') : '', key.alt ? alt : '', key.shift ? (mac ? '⇧' : 'Shift') : ''].filter(Boolean);return mac ? `${mods.join('')}${name}` : [...mods, name].filter(Boolean).join('+');};diff --git a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsxindex e326293..c5dce26 100644--- a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx+++ b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx@@ -24,6 +24,7 @@ import type { MediaListing } from '@/lib/workspace-resources';import { followOf, readTimelinePrefs } from '@/lib/timeline-prefs';import { sizeOf, trackHeightsOf, withTrackHeight, TRACK_SIZES, type TrackSize } from '@/lib/track-heights';import type { Player } from '@/editor/player';+import type { OutsideStep } from '@/editor/use-film';import type { ContextMenuEntry } from './ContextMenu';import { ClipMarkers, MarkersButton, RulerMarkers, type MarkerActions } from './TimelineMarkers';@@ -38,7 +39,7 @@ const sounding = (b: TimelineBlock) => Boolean(b.clipId && b.loc && b.src) && () && b.volume !== 0;export function useEditorTools({- projectId, tracks, film, settings, patchSettings, player, timeRef, seek, edit, editModel, selectedClipIds, listing, toast,+ projectId, tracks, film, settings, patchSettings, player, timeRef, seek, edit, record, editModel, selectedClipIds, listing, toast,}: {projectId: string;tracks: readonly TimelineTrack[];@@ -50,6 +51,8 @@ export function useEditorTools({timeRef: React.MutableRefObject<number>;seek: (ms: number) => void;edit: (ops: Op[], label: string) => Promise<string | null>;+ /** Keeps an edit of another file (the markers) as a step of the film's history, so ⌘Z undoes it in turn. */+ record: (label: string, outside: OutsideStep) => void;editModel: () => EditModel;selectedClipIds: readonly string[];/** the project's media and pages, with their lengths as probed */@@ -67,7 +70,8 @@ export function useEditorTools({const filmRef = React.useRef(film);filmRef.current = film;- /* ── markers: read once per project, written whole on each change (one at a time, in order) ── */+ /* ── markers: read once per project, written whole on each change (one at a time, in order), each change a step+ of the history (⌘Z puts the list back as it was) ── */const [markers, setMarkers] = React.useState<Marker[]>([]);const markersRef = React.useRef(markers);markersRef.current = markers;@@ -78,11 +82,18 @@ export function useEditorTools({void api.markers(projectId).then((raw) => { if (live) setMarkers(parseMarkers(raw)); }, () => {});return () => { live = false; };}, [projectId]);- const saveMarkers = React.useCallback((next: Marker[]) => {+ const writeMarkers = React.useCallback((next: Marker[]): Promise<string | null> => {setMarkers(next);markersRef.current = next;- writes.current = writes.current.then(() => api.putMarkers(projectId, next)).catch((e: Error) => toast.showError(e.message));- }, [projectId, toast]);+ const done = writes.current.then(() => api.putMarkers(projectId, next)).then(() => null, (e: Error) => e.message);+ writes.current = done;+ return done;+ }, [projectId]);+ const saveMarkers = React.useCallback((next: Marker[]) => {+ const was = markersRef.current;+ void writeMarkers(next).then((err) => { if (err) toast.showError(err); });+ record('history.stepMarker', { undo: () => writeMarkers(was), redo: () => writeMarkers(next) });+ }, [writeMarkers, record, toast]);const placed = React.useMemo(() => placeMarkers(markers, tracks), [markers, tracks]);const [naming, setNaming] = React.useState<string | null>(null);const onNamed = React.useCallback(() => setNaming(null), []);diff --git a/packages/openfilm/studio/ui/src/components/useBlockDrag.ts b/packages/openfilm/studio/ui/src/components/useBlockDrag.tsindex 7308f1f..592875c 100644--- a/packages/openfilm/studio/ui/src/components/useBlockDrag.ts+++ b/packages/openfilm/studio/ui/src/components/useBlockDrag.ts@@ -1,5 +1,5 @@/**- * Dragging on the timeline: a clip moved, an edge trimmed, a cut rolled, a clip's content slipped or the clip slid+ * Dragging on the timeline: a clip moved (or copied, ⌥), an edge trimmed, a cut rolled* between its neighbors. Press, follow the pointer, write the result to film.html on release.** Clips are a projection of the evaluated film, not data to change freely: release sends an edit and the timeline@@ -45,19 +45,18 @@ import {planMove,planRippleTrim,rollMoves,- slideMoves,sourceLeftMs,type EditMode,type EditModel,type EditPlan,type TrackDest,} from '@/lib/timeline-edit';+import { planCopies } from '@/lib/timeline-clipboard';import { followOf, type TimelinePrefs } from '@/lib/timeline-prefs';-import { snapToFrame } from '@/lib/timecode';import type { TimelineBlock, TimelineTrack } from '@/lib/timeline-layout';-/** What a press on the timeline does: move a clip, trim one of its edges, roll a cut, slip its content, slide it. */-export type GestureMode = DragMode | 'roll' | 'slip' | 'slide';+/** What a press on the timeline does: move a clip, trim one of its edges, roll a cut. */+export type GestureMode = DragMode | 'roll';/*** The tracks as places to drop. `except` are the clips in hand (the dragged one and the selection moving with it):@@ -79,9 +78,9 @@ function dropLanesOf(lanes: readonly TimelineTrack[], except: readonly string[])}));}-/** What the label beside the pointer says while trimming, rolling, slipping or sliding. */+/** What the label beside the pointer says while trimming or rolling. */export interface GestureTip {- kind: 'trim' | 'ripple' | 'roll' | 'slip' | 'slide';+ kind: 'trim' | 'ripple' | 'roll';/** How far the edge, the cut, the content or the clip moved (film ms). */deltaMs: number;/** The clip's length now, for a trim. */@@ -145,7 +144,7 @@ export interface BlockDrag {* Attached to the clip body, its edges and the cuts between clips. `selected`: the clips moving along (a move);* `other`: the clip after the cut (a roll). ⌥ at the press (`e.altKey`) trims or rolls this clip alone.*/- start: (e: React.PointerEvent, block: TimelineBlock, mode: GestureMode, selected?: readonly string[], other?: TimelineBlock, onLift?: () => void) => void;+ start: (e: React.PointerEvent, block: TimelineBlock, mode: GestureMode, selected?: readonly string[], other?: TimelineBlock, onLift?: () => void, copy?: boolean) => void;/** Whether a clip can move / be trimmed: decides handles and cursors. */can: (block: TimelineBlock) => { move: boolean; resize: boolean };dismissError: () => void;@@ -160,9 +159,7 @@ function overHostPanel(ev: PointerEvent): boolean {function stepOf(mode: GestureMode, ripple: boolean, clipId: string): string {const key = mode === 'move' ? 'history.stepMoved': mode === 'roll' ? 'history.stepRolled'- : mode === 'slip' ? 'history.stepSlipped'- : mode === 'slide' ? 'history.stepSlid'- : ripple ? 'history.stepRippleTrimmed' : 'history.stepTrimmed';+ : ripple ? 'history.stepRippleTrimmed' : 'history.stepTrimmed';return `${key}|${clipId}`;}@@ -235,10 +232,12 @@ export function useBlockDrag(opts: {other?: TimelineBlock,/** Called once when the press becomes a drag (a roll selects its clip only then: a click on a cut is the cut's). */onLift?: () => void,+ /** A move that copies (⌥ at the press, as CapCut's): the clips stay, copies land where they are let go. */+ copy = false,) => {if (e.button !== 0) return;const able = can(block);- if (mode === 'move' || mode === 'slide' ? !able.move : !able.resize) return;+ if (mode === 'move' ? !able.move : !able.resize) return;if (mode === 'roll' && (!other || !can(other).resize)) return;cancelGesture.current?.();@@ -259,8 +258,7 @@ export function useBlockDrag(opts: {const startScrollTop = latest.current.scrollEl?.current?.scrollTop ?? 0;/* the film time under the hand at the press: an insert goes before or after the clip under it */const grabMs = block.startMs + (startX - pointerTarget.getBoundingClientRect().left) / pxPerMs;- /* ⌥ at the press: this clip alone, not the clips linked to it (a trim, a roll; for a slip or a slide ⌥ is what- starts it) */+ /* ⌥ at the press: this clip alone, not the clips linked to it (a trim, a roll; for a move ⌥ copies) */const alone = e.altKey && (mode === 'trim-start' || mode === 'trim-end' || mode === 'roll');const geom: Block = { id: block.id, startMs: block.startMs, endMs: block.endMs };@@ -272,8 +270,8 @@ export function useBlockDrag(opts: {const locked = new Set(lanes.filter((lane) => lane.locked).flatMap((lane) => lane.blocks.map((b) => b.id)));const blockOfClip = new Map(allBlocks.flatMap((b) => (b.clipId ? [[b.clipId, b] as const] : [])));const writable = (b: TimelineBlock | undefined): b is TimelineBlock => Boolean(b?.loc && b.clipId && b.anchor?.move && !locked.has(b.id));- /* the clips linked to this one, unless ⌥ or the switch says alone */- const partnersOf = (b: TimelineBlock): TimelineBlock[] => (prefs.linked && !alone && b.clipId+ /* the clips linked to this one, unless ⌥ says alone */+ const partnersOf = (b: TimelineBlock): TimelineBlock[] => (!alone && b.clipId? linkedIds(model, [b.clipId]).filter((id) => id !== b.clipId).map((id) => blockOfClip.get(id)).filter(writable): []);/* a move takes the rest of the selection (and the clips linked to it, when the selection did not already) */@@ -358,25 +356,16 @@ export function useBlockDrag(opts: {atMs: edge === 'end' || ripple ? (own?.endMs ?? geom.endMs) : (own?.startMs ?? geom.startMs), lane: homeLaneIndex,...(left < 1 ? { sourceEnd: true } : {}),};- } else if (mode === 'roll') {+ } else {const out = applyDrag(geom, 'trim-end', deltaMs, targets, pxPerMs);const want = out.endMs - geom.endMs;- plan = planEdges(m, rollMoves(m, block.clipId!, other!.clipId!, p.linked && !alone), want);+ plan = planEdges(m, rollMoves(m, block.clipId!, other!.clipId!, !alone), want);if (plan.deltaMs === want) snappedTo = out.snappedTo;tip = { kind: 'roll', deltaMs: plan.deltaMs, atMs: geom.endMs + plan.deltaMs, lane: homeLaneIndex };- } else if (mode === 'slip') {- plan = planEdges(m, ids.map((id) => ({ id, kind: 'slip' as const })), snapToFrame(deltaMs));- tip = { kind: 'slip', deltaMs: plan.deltaMs, atMs: (geom.startMs + geom.endMs) / 2, lane: homeLaneIndex };- } else {- const out = applyDrag(geom, 'move', deltaMs, targets, pxPerMs);- const want = out.startMs - geom.startMs;- plan = planEdges(m, slideMoves(m, ids, p.linked), want);- if (plan.deltaMs === want) snappedTo = out.snappedTo;- tip = { kind: 'slide', deltaMs: plan.deltaMs, atMs: (geom.startMs + geom.endMs) / 2 + plan.deltaMs, lane: homeLaneIndex };}lastPlan = plan;const own = plan.placed.get(block.clipId!);- document.body.style.cursor = mode === 'slip' || mode === 'slide' ? 'grabbing' : mode === 'roll' ? 'col-resize' : 'ew-resize';+ document.body.style.cursor = mode === 'roll' ? 'col-resize' : 'ew-resize';last = {...base,startMs: own?.startMs ?? geom.startMs,@@ -396,7 +385,14 @@ export function useBlockDrag(opts: {const hit = latest.current.laneHitAtY?.(ev.clientY) ?? { lane: homeLaneIndex, band: 'body' as const };const out = applyDrag(geom, 'move', deltaMs, targets, pxPerMs, block.room, crowd);const grouped = crowd.length > 0 && homeLaneIndex >= 0;- const shift = grouped+ /* a group above every row or below every row: new tracks there, one per track it came from (as one clip does) */+ const onFilm = groupLanes.filter((lane) => lane.docIndex != null);+ const groupOpens = grouped && onFilm.length+ ? hit.lane < 0 ? onFilm[0]!.docIndex! : hit.lane >= latest.current.lanes.length ? onFilm.at(-1)!.docIndex! + 1 : null+ : null;+ const shift = groupOpens != null+ ? { ok: true, delta: 0, moves: [] as { id: string; trackIndex: number }[] }+ : grouped? groupLaneShift([{ id: block.id, laneIndex: homeLaneIndex, startMs: out.startMs, endMs: out.endMs },...crowd.map((b) => {@@ -427,7 +423,7 @@ export function useBlockDrag(opts: {const overlaps = alongOwnTrack && rangeOverlaps(wouldLand, singleLanes[homeLaneIndex]?.occupied ?? []);/* the track it lands on: the magnet inserts on the main track; elsewhere with the magnet it covers nothing (a cliplanding on another goes to a free track, see planMove), ⌥ inserting there */- const landsOn = drop.action === 'move' ? drop.trackIndex : drop.action === 'insert' ? null : homeLane?.docIndex;+ const landsOn = groupOpens != null ? null : drop.action === 'move' ? drop.trackIndex : drop.action === 'insert' ? null : homeLane?.docIndex;const onMain = magnetOn(m, landsOn, p.magnet);const editMode: EditMode = p.magnet && !onMain? (altNow ? 'insert' : 'overwrite')@@ -440,18 +436,15 @@ export function useBlockDrag(opts: {const b = mv.id === block.id ? block : crowd.find((x) => x.id === mv.id);if (b?.clipId) to.set(b.clipId, mv.trackIndex);}+ if (groupOpens != null) for (const b of [block, ...crowd]) if (b.clipId) to.set(b.clipId, { insert: groupOpens });const outside = overHostPanel(ev);- const plan = outside || drop.action === 'refuse' || !shift.ok ? null : planMove(m, {- ids,- deltaMs: out.startMs + (settle?.shiftMs ?? 0) - geom.startMs,- pointerMs: grabMs + deltaMs,- to,- mode: editMode,- magnet: p.magnet,- ...followOf(p),- });+ const moveBy = out.startMs + (settle?.shiftMs ?? 0) - geom.startMs;+ /* ⌥ at the press: copies land there, the clips stay (planCopies) */+ const plan = outside || drop.action === 'refuse' || !shift.ok ? null : copy+ ? planCopies(m, { ids, deltaMs: moveBy, pointerMs: grabMs + deltaMs, to, magnet: p.magnet, ...followOf(p) })+ : planMove(m, { ids, deltaMs: moveBy, pointerMs: grabMs + deltaMs, to, mode: editMode, magnet: p.magnet, ...followOf(p) });lastPlan = plan;- document.body.style.cursor = outside ? 'copy' : 'grabbing';+ document.body.style.cursor = outside || copy ? 'copy' : 'grabbing';const landed = plan?.placed.get(block.clipId!);const landStartMs = landed?.startMs ?? out.startMs;const inHand = new Set([block.id, ...crowd.map((b) => b.id)]);@@ -614,7 +607,8 @@ export function useBlockDrag(opts: {pendingSaves.current += 1;setSaving(true);setPreview(held);- void Promise.resolve().then(() => commit(ops, stepOf(mode, ripple, block.clipId!))).catch((err: unknown) => (+ const label = copy ? `history.stepDuplicated|${block.clipId}` : stepOf(mode, ripple, block.clipId!);+ void Promise.resolve().then(() => commit(ops, label)).catch((err: unknown) => (err instanceof Error ? err.message : String(err))).then((err) => {pendingSaves.current -= 1;diff --git a/packages/openfilm/studio/ui/src/editor/Preview.tsx b/packages/openfilm/studio/ui/src/editor/Preview.tsxindex 783e744..83e41f0 100644--- a/packages/openfilm/studio/ui/src/editor/Preview.tsx+++ b/packages/openfilm/studio/ui/src/editor/Preview.tsx@@ -264,7 +264,9 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde<iframekey={f.key}ref={(el) => { if (el) elements.current.set(f.key, el); else { elements.current.delete(f.key); up.current.delete(f.key); } }}- src={`${folder}film.html?load=${f.key}`}+ /* `film-missing=skip`: a clip whose file is not there keeps its time and plays as nothing, the rest plays on+ (src/timeline.mjs); the timeline marks it and offers to relink it */+ src={`${folder}film.html?load=${f.key}&film-missing=skip`}/* the film's videos play when the person presses play here: another origin needs this to be allowed */allow="autoplay"scrolling="no"diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex eb6eb20..a89a307 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -19,6 +19,18 @@ export const en = {installFailed: 'OpenFilm {version} could not install. Quit OpenFilm and open it again to install it.',installing: 'Restarting…',},+ whatsNew: {+ eyebrow: 'Updated',+ title: 'What’s new in OpenFilm {version}',+ close: 'Close',+ changelog: 'Full changelog',+ ok: 'Got it',+ kind: {+ new: 'New',+ improved: 'Improved',+ fixed: 'Fixed',+ },+ },host: {refer: 'Reference in chat',regionHint: 'Drag a box to reference it in chat',@@ -346,6 +358,7 @@ export const en = {summary: '{n} file(s) · {dur}',approx: 'about',emptyFilm: 'The film is empty — add a clip first.',+ missingMedia: '{n} media file(s) missing: {files}. Relink them first: right-click the red clip on the timeline.',pickPreset: 'Pick at least one platform.',noCaptions: 'This film has no subtitles.',noAudio: 'This film has no sound.',@@ -454,6 +467,7 @@ export const en = {editsRestore: 'Restore them',editsLeaveOut: 'Leave them out',previewFailed: 'The preview couldn\'t be drawn.',+ previewMissing: 'Media not found: {file} · right-click its clip to relink',filmEmptyHint: 'Drag media onto the timeline to start your film, or ask your agent to make one.',filmBroken: 'film.html can’t be read right now, so Studio shows the film as it last was, and edits here can’t be saved until it’s fixed:',filmNotReady: 'The video isn’t ready yet',@@ -495,11 +509,10 @@ export const en = {stepSplit: 'Split {clip}',stepDetachAudio: 'Detached the audio of {clip}',stepRolled: 'Rolled the cut after {clip}',- stepSlipped: 'Slipped {clip}',- stepSlid: 'Slid {clip}',stepRippleTrimmed: 'Ripple trimmed {clip}',stepGapClosed: 'Closed a gap',stepMainClosed: 'Closed up the main track',+ stepGapsClosed: 'Closed the gaps on a track',stepLinked: 'Linked {clip}',stepUnlinked: 'Unlinked {clip}',stepSpeed: 'Changed the speed of {clip}',@@ -513,6 +526,7 @@ export const en = {stepSubtitleRemoved: 'Deleted a subtitle',stepSubtitleText: 'Edited a subtitle',stepSubtitleAdded: 'Added a subtitle',+ stepMarker: 'Changed the markers',stepNormalized: "Normalized loudness to {clip} LUFS",stepFroze: "Froze a frame of {clip}",stepReplaced: "Replaced {clip}",@@ -1170,23 +1184,18 @@ export const en = {zoomFit: 'Fit to width',zoom: 'Zoom',snap: 'Snap',- snapOn: 'On: snaps to clip edges, the playhead and markers',- snapOff: 'Off: drops exactly where you let go',+ snapOn: 'On: drags snap to clip edges, the playhead and markers',+ snapOff: 'Off: clips land exactly where you let go',magnet: 'Main track magnet',- magnetOn: 'On: the main track (the lowest picture track) stays closed up. A clip put down there inserts, delete closes the gap, trims ripple. Other tracks never cover a clip: one put where another is goes to a free track, and delete leaves a gap. Hold Alt while dropping for the other way',- magnetOff: 'Off: the main track is like the others. A clip put down overwrites what is under it. Hold Alt while dropping to insert',+ magnetOn: 'On: clips on the main track stay end to end, with no gaps',+ magnetOff: 'Off: clips on the main track stay where you put them',linkage: 'Linkage',- linkageOn: 'On: when clips on the main track move, the titles, B-roll and sound that start over them move along. A long clip under several shots (a music bed) stays',- linkageOff: 'Off: an edit on the main track moves the main track only',- sync: 'Sync lock',- syncOn: 'On (as Premiere): a ripple on any track moves every unlocked track along, as far as all of them have room',- syncOff: "Off: a ripple moves only the clips' own tracks",- linked: 'Linked clips',- linkedOn: 'On: a video and its detached sound are selected and edited together. Alt-click picks one',- linkedOff: 'Off: linked clips are selected and edited one by one',- rippleShort: "Clips on another track were in the way: {s} s left open so everything stays in sync. Turn off sync lock to close it on this track alone.",+ linkageOn: 'On: titles, overlays and sound move with the main-track clip under them',+ linkageOff: 'Off: editing the main track moves only the main track',+ rippleShort: "Clips on another track were in the way: {s} s left open so everything stays in sync.",gapClosedAlone: 'Clips on other tracks were in the way, so the gap closed on this track alone.',menuCloseGap: 'Close gap',+ menuCloseGaps: 'Close all gaps on this track',menuRippleStart: 'Ripple trim start to playhead',menuRippleEnd: 'Ripple trim end to playhead',menuLink: 'Link',@@ -1196,8 +1205,6 @@ export const en = {trim: 'Trim',ripple: 'Ripple',roll: 'Roll',- slip: 'Slip',- slide: 'Slide',sourceEnd: 'End of the media',},trackLocked: 'Track locked',@@ -1273,6 +1280,22 @@ export const en = {replaceKind: "A picture is replaced by a picture, a sound by a sound",replaceShort: "The new file is shorter: the clip is {s} s shorter",},+ /* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */+ clipAttrs: {+ title: 'Paste attributes',+ picture: 'Picture',+ sound: 'Sound',+ place: 'Position and size',+ blend: 'Blending (opacity, blend mode)',+ volume: 'Volume',+ fade: 'Fade in / fade out',+ paste: 'Paste',+ copy: 'Copy attributes',+ pasteMenu: 'Paste attributes…',+ copied: 'Attributes copied: select clips and press ⌘⇧V to paste them',+ nothing: 'Copy a clip\'s attributes first (⌘⇧C)',+ selectFirst: 'Select a clip first',+ },transitions: {dissolve: 'Cross dissolve','dip-black': 'Dip to black',@@ -1337,6 +1360,11 @@ export const en = {groups: {help: 'Help',},+ links: {+ github: 'GitHub',+ examples: 'Examples',+ site: 'Website',+ },sections: {agents: 'Agents',providers: 'Providers',@@ -1376,9 +1404,18 @@ export const en = {inApp: 'Updates come with the desktop app: OpenFilm → Check for Updates…',howTitle: 'Update',how: 'Run this, or ask your agent to: Studio restarts on the new version.',+ appOff: "This build runs from source and doesn't update itself; the installed app does.",+ appChecked: 'Checked {time}.',+ appDownloading: 'Downloading OpenFilm {version}…',+ appStaging: 'Preparing OpenFilm {version}…',+ appRetry: 'Try again',+ whatsNew: 'What’s new in this version',+ appOffline: 'Could not reach the update service. Check your connection.',+ appUnavailable: 'Updates are unavailable right now. Try again later.',+ appFailed: 'Could not complete the update. Try again later.',},agents: {- intro: 'The agents the chat can use. Codex, Claude Code and the others under Your agents are your own, with their own sign-in; your own key runs on a service of yours.',+ intro: 'The agents the chat can use. Codex, Claude Code and the others under Your agents are your own, on the account signed in on this computer: to use another account, switch accounts in the agent itself, then disconnect and connect it again here. Your own key runs on a service of yours.',byokName: 'Your own key',groupYours: 'Your agents',groupMore: 'More agents you can use',@@ -1386,23 +1423,52 @@ export const en = {recommendedHint: 'The cheapest way: the subscription you already have',ready: 'Connected',off: 'Not connected',- signedOut: 'Signed out',+ signedOut: 'Not signed in',waiting: 'Waiting for the sign-in in Terminal…',waitingHint: 'Finish signing in in the window that opened, then come back.',startAgain: 'Start again',missing: 'Not installed on this computer',claudeSetup: 'Open the Claude app’s Code tab once to install Claude Code',+ locate: 'Locate…',+ locateTitle: 'Choose the {name} program',+ locateButton: 'Use this',+ chosenAt: 'Using the program you chose: {path}',+ automatic: 'Find it automatically',+ notAProgram: 'That is not a program this computer can start. Choose the agent’s program itself (on Windows, the .exe or .cmd file).',+ didNotStart: 'It did not start from there:',+ whyMissing: 'Why isn’t it found?',+ searching: 'Searching…',+ hintChosenMissing: 'The program you chose is not there any more. Choose it again, or find it automatically.',+ hintWsl: 'It is installed in WSL (Linux on Windows), which OpenFilm cannot use. Install it in Windows too, then come back.',+ hintUnusable: 'Files with its name were found, but none of them can be started. Use Locate… to choose the program itself.',+ hintNone: 'It is not in any of the folders searched. If {program} works in your terminal, find where it is there (“where {program}” on Windows, “which {program}” on a Mac) and choose that file with Locate….',+ hintFound: 'Found: {path}',+ reportNote: 'If it still is not found, copy the report and send it with an issue. It lists folders on this computer.',+ copyReport: 'Copy report',+ copied: 'Copied',+ close: 'Close',needsKey: 'Not set up',unavailable: 'Not available yet: coming in an update',checking: 'Checking…',connect: 'Connect',disconnect: 'Disconnect',+ disconnectHint: 'Stops OpenFilm using it; its sign-in stays. To use another account, switch accounts in {name}, then connect it again.',+ accountChatgpt: 'ChatGPT account',+ accountApiKey: 'API key',+ accountConsole: 'Anthropic Console',+ usage: 'Usage',+ usageLoading: 'Reading what is left of the plan…',+ usageFiveHour: '5 hours',+ usageWeek: 'This week',+ usageWindow: '{hours} hours',+ usageUsed: '{percent}% used',+ usageResets: 'resets {time}',signIn: 'Sign in',install: 'Install',setUpKey: 'Set up',change: 'Change',showInChat: 'Show in the chat',- showHint: 'Only the agents switched on show in the chat. Disconnecting one of your agents here leaves its own sign-in as it is.',+ showHint: 'Only the agents switched on show in the chat.',failed: 'That did not work. Try again.',format: 'API format',address: 'Address',@@ -1418,10 +1484,16 @@ export const en = {},developer: {intro: 'For finding out exactly what an agent did, and why: nothing here changes what the agents do.',- group: 'Turn logs',+ group: 'Each turn',+ changes: 'Show what each turn changed',+ changesHint: 'Under each reply, the files the turn added, deleted or changed, with the lines added and removed. Click a file to see its changed lines.',logs: 'Show each turn’s log',- logsHint: 'In the chat, every turn gets a Log button: the prompt and the session it ran in, each tool call with its input and output, every question and answer, and how it ended, as the agent sent them. Under each reply, what the turn changed in film.html, line by line as a diff.',+ logsHint: 'In the chat, every turn gets a Log button: the prompt and the session it ran in, each tool call with its input and output, every question and answer, and how it ended, as the agent sent them.',where: 'Every turn is logged whether or not this is on, in the project’s .film/logs folder, on this computer only.',+ releaseGroup: 'Releases',+ previewWhatsNew: 'What’s new',+ previewWhatsNewHint: 'Shows the notes of {version} as people see them after updating.',+ preview: 'Preview',},shortcuts: {groupMarks: "In and out",@@ -1432,6 +1504,7 @@ export const en = {markIn: "Mark in at the playhead",markOut: "Mark out at the playhead",clearMarks: "Clear in and out",+ rangeClip: "Set in and out to the selected clips",goInOut: "Go to in / out",playRange: "Play from in to out",loop: "Loop playback (the range, else the film)",@@ -1445,14 +1518,20 @@ export const en = {rippleEnd: "Ripple trim the end to the playhead",cut: "Cut selected clips",duplicate: "Duplicate selected clips",+ copyAttrs: "Copy a clip's attributes",+ pasteAttrs: "Paste attributes onto the selected clips",+ speedPanel: "Speed of the selected clip",+ detachAudio: "Detach a video's sound",nudgeClip: "Move selected clips one frame",- toggleMagnet: "Magnet on / off",+ toggleMagnet: "Main track magnet on / off",toggleSnap: "Snapping on / off",+ toggleLinkage: "Linkage on / off",zoomFit: "Zoom to fit the film",frameStep: "Move playhead one frame",- secondStep: "Move playhead one second",+ jumpStep: "Move playhead 10 frames",rippleDelete: "Ripple delete and close the gap",selectAll: "Select unlocked clips (click timeline first)",+ selectSide: "Select every clip before / after the playhead",deselect: "Deselect",zoomIn: "Zoom in on timeline",zoomOut: "Zoom out on timeline",@@ -1476,9 +1555,9 @@ export const en = {remove: 'Delete selected clips',selectMode: 'Select tool',splitMode: 'Split tool',+ splitModeAll: 'With the split tool, click with it held: every track is cut there',editModeSwap: 'Hold while dropping a clip: insert instead of overwrite, or the other way round',- slip: 'Drag a clip with it held: slip (what the clip shows moves, not the clip)',- slide: 'Drag a clip with them held: slide (the clips around it give and take the time)',+ copyDrag: 'Drag a clip with it held: a copy goes where you let go, the clip stays',},providers: {desc: 'Where voices, music, sound effects, transcripts, images and video come from. OpenFilm makes and edits films without any of them: connect one when your agent needs media.',diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex 535499e..6fac505 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -18,6 +18,18 @@ export const es: Words = {installFailed: 'No se pudo instalar OpenFilm {version}. Sal de OpenFilm y vuelve a abrirlo para instalarlo.',installing: 'Reiniciando…',},+ whatsNew: {+ eyebrow: 'Actualizado',+ title: 'Novedades de OpenFilm {version}',+ close: 'Cerrar',+ changelog: 'Registro completo de cambios',+ ok: 'Entendido',+ kind: {+ new: 'Nuevo',+ improved: 'Mejorado',+ fixed: 'Corregido',+ },+ },host: {refer: 'Mencionar en el chat',regionHint: 'Arrastra un recuadro para mencionarlo en el chat',@@ -345,6 +357,7 @@ export const es: Words = {summary: '{n} archivo(s) · {dur}',approx: 'aprox.',emptyFilm: 'La película está vacía: añade primero un clip.',+ missingMedia: 'Faltan {n} archivos de medios: {files}. Vuelve a vincularlos primero: clic derecho en el clip rojo de la línea de tiempo.',pickPreset: 'Elige al menos una plataforma.',noCaptions: 'Esta película no tiene subtítulos.',noAudio: 'Esta película no tiene sonido.',@@ -453,6 +466,7 @@ export const es: Words = {editsRestore: 'Restaurarlas',editsLeaveOut: 'Descartarlas',previewFailed: 'No se pudo dibujar la vista previa.',+ previewMissing: 'Falta el medio: {file} · clic derecho en el clip para revincular',filmEmptyHint: 'Arrastra medios a la línea de tiempo para empezar tu película, o pide a tu agente que haga una.',filmBroken: 'Ahora mismo no se puede leer film.html, así que Studio muestra la película tal como estaba, y las ediciones de aquí no se pueden guardar hasta que se corrija:',filmNotReady: 'El video aún no está listo',@@ -494,11 +508,10 @@ export const es: Words = {stepSplit: 'Dividido {clip}',stepDetachAudio: 'Audio separado de {clip}',stepRolled: 'Corte después de {clip} desplazado',- stepSlipped: 'Contenido de {clip} deslizado',- stepSlid: '{clip} deslizado entre sus vecinos',stepRippleTrimmed: 'Recorte con desplazamiento de {clip}',stepGapClosed: 'Hueco cerrado',stepMainClosed: 'Pista principal cerrada',+ stepGapsClosed: 'Huecos de una pista cerrados',stepLinked: '{clip} vinculado',stepUnlinked: '{clip} desvinculado',stepSpeed: 'Velocidad de {clip} cambiada',@@ -512,6 +525,7 @@ export const es: Words = {stepSubtitleRemoved: 'Subtítulo eliminado',stepSubtitleText: 'Subtítulo editado',stepSubtitleAdded: 'Subtítulo añadido',+ stepMarker: 'Marcadores cambiados',stepNormalized: "Sonoridad normalizada a {clip} LUFS",stepFroze: "Fotograma de {clip} congelado",stepReplaced: "{clip} reemplazado",@@ -1169,23 +1183,18 @@ export const es: Words = {zoomFit: 'Ajustar al ancho',zoom: 'Zoom',snap: 'Ajuste',- snapOn: 'Activado: se ajusta a los bordes de los clips, al cabezal de reproducción y a los marcadores',+ snapOn: 'Activado: se ajusta a los bordes de los clips, al cabezal y a los marcadores',snapOff: 'Desactivado: se coloca justo donde lo sueltas',magnet: 'Imán de la pista principal',- magnetOn: 'Activado: la pista principal (la pista de imagen más baja) queda siempre sin huecos. Un clip soltado ahí se inserta, eliminar cierra el hueco, recortar desplaza. En las demás pistas ningún clip tapa a otro: uno soltado donde ya hay otro pasa a una pista libre, y eliminar deja un hueco. Mantén Alt al soltar para lo contrario',- magnetOff: 'Desactivado: la pista principal es como las demás. Un clip soltado sobrescribe lo que hay debajo. Mantén Alt al soltar para insertar',+ magnetOn: 'Activado: los clips de la pista principal quedan seguidos, sin huecos',+ magnetOff: 'Desactivado: los clips de la pista principal se quedan donde los pones',linkage: 'Vinculación',- linkageOn: 'Activada: cuando se mueven clips de la pista principal, los títulos, el B-roll y el sonido que empiezan sobre ellos se mueven con ellos. Un clip largo bajo varias tomas (una música de fondo) se queda',+ linkageOn: 'Activada: títulos, superposiciones y sonido se mueven con el clip de la pista principal que tienen debajo',linkageOff: 'Desactivada: editar la pista principal mueve solo la pista principal',- sync: 'Bloqueo de sincronía',- syncOn: 'Activado (como en Premiere): un desplazamiento en cualquier pista mueve todas las pistas desbloqueadas, mientras todas tengan espacio',- syncOff: 'Desactivado: un desplazamiento mueve solo las pistas de los clips',- linked: 'Clips vinculados',- linkedOn: 'Activado: un video y su audio separado se seleccionan y editan juntos. Alt-clic elige uno',- linkedOff: 'Desactivado: los clips vinculados se seleccionan y editan uno a uno',- rippleShort: 'Había clips en otra pista: quedan {s} s abiertos para que todo siga sincronizado. Desactiva el bloqueo de sincronía para cerrarlo solo en esta pista.',+ rippleShort: 'Había clips en otra pista: quedan {s} s abiertos para que todo siga sincronizado.',gapClosedAlone: 'Había clips en otras pistas, así que el hueco se cerró solo en esta pista.',menuCloseGap: 'Cerrar hueco',+ menuCloseGaps: 'Cerrar todos los huecos de esta pista',menuRippleStart: 'Recortar inicio hasta el cabezal y desplazar',menuRippleEnd: 'Recortar final hasta el cabezal y desplazar',menuLink: 'Vincular',@@ -1195,8 +1204,6 @@ export const es: Words = {trim: 'Recorte',ripple: 'Desplazar',roll: 'Corte',- slip: 'Contenido',- slide: 'Deslizar',sourceEnd: 'Fin del medio',},trackLocked: 'Pista bloqueada',@@ -1272,6 +1279,22 @@ export const es: Words = {replaceKind: "Una imagen se reemplaza por una imagen, un sonido por un sonido",replaceShort: "El archivo nuevo es más corto: el clip dura {s} s menos",},+ /* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */+ clipAttrs: {+ title: 'Pegar atributos',+ picture: 'Imagen',+ sound: 'Audio',+ place: 'Posición y tamaño',+ blend: 'Fusión (opacidad, modo de fusión)',+ volume: 'Volumen',+ fade: 'Fundido de entrada / salida',+ paste: 'Pegar',+ copy: 'Copiar atributos',+ pasteMenu: 'Pegar atributos…',+ copied: 'Atributos copiados: selecciona clips y pulsa ⌘⇧V para pegarlos',+ nothing: 'Primero copia los atributos de un clip (⌘⇧C)',+ selectFirst: 'Primero selecciona un clip',+ },transitions: {dissolve: 'Disolvencia cruzada','dip-black': 'Fundido a negro',@@ -1336,6 +1359,11 @@ export const es: Words = {groups: {help: 'Ayuda',},+ links: {+ github: 'GitHub',+ examples: 'Ejemplos',+ site: 'Sitio web',+ },sections: {agents: 'Agentes',providers: 'Proveedores',@@ -1375,9 +1403,18 @@ export const es: Words = {inApp: 'Studio se actualiza con la app de escritorio: OpenFilm → Check for Updates…',howTitle: 'Actualizar',how: 'Ejecuta esto, o pídeselo a tu agente: Studio se reinicia con la nueva versión.',+ appOff: 'Esta versión se ejecuta desde el código fuente y no se actualiza sola; la app instalada sí.',+ appChecked: 'Comprobado {time}.',+ appDownloading: 'Descargando OpenFilm {version}…',+ appStaging: 'Preparando OpenFilm {version}…',+ appRetry: 'Reintentar',+ whatsNew: 'Novedades de esta versión',+ appOffline: 'No se pudo conectar con el servicio de actualizaciones. Revisa tu conexión.',+ appUnavailable: 'Las actualizaciones no están disponibles ahora. Inténtalo más tarde.',+ appFailed: 'No se pudo completar la actualización. Inténtalo más tarde.',},agents: {- intro: 'Los agentes que puede usar el chat. Codex, Claude Code y los demás de Tus agentes son tuyos, con su propio inicio de sesión; tu propia clave funciona con un servicio tuyo.',+ intro: 'Los agentes que puede usar el chat. Codex, Claude Code y los demás de Tus agentes son tuyos y usan la cuenta con la que este equipo inició sesión: para usar otra, cambia de cuenta en el propio agente y luego desconéctalo y vuelve a conectarlo aquí. Tu propia clave funciona en un servicio tuyo.',byokName: 'Tu propia clave',groupYours: 'Tus agentes',groupMore: 'Otros agentes que puedes usar',@@ -1385,23 +1422,52 @@ export const es: Words = {recommendedHint: 'La forma más barata: con la suscripción que ya tienes',ready: 'Conectado',off: 'No conectado',- signedOut: 'Sesión cerrada',+ signedOut: 'Sin sesión iniciada',waiting: 'Esperando el inicio de sesión en Terminal…',waitingHint: 'Termina de iniciar sesión en la ventana que se abrió y vuelve aquí.',startAgain: 'Volver a empezar',missing: 'No está instalado en este equipo',claudeSetup: 'Abre una vez la pestaña Code de la app de Claude para instalar Claude Code',+ locate: 'Elegir…',+ locateTitle: 'Elige el programa de {name}',+ locateButton: 'Usar este',+ chosenAt: 'Usando el programa que elegiste: {path}',+ automatic: 'Detectarlo automáticamente',+ notAProgram: 'Ese archivo no es un programa que este equipo pueda abrir. Elige el programa del agente (en Windows, el archivo .exe o .cmd).',+ didNotStart: 'No se pudo iniciar desde ahí:',+ whyMissing: '¿Por qué no se encuentra?',+ searching: 'Buscando…',+ hintChosenMissing: 'El programa que elegiste ya no está. Elígelo de nuevo o vuelve a detectarlo automáticamente.',+ hintWsl: 'Está instalado en WSL (Linux en Windows), que OpenFilm no puede usar. Instálalo también en Windows y vuelve.',+ hintUnusable: 'Se encontraron archivos con su nombre, pero ninguno se puede iniciar. Usa Elegir… para seleccionar el programa.',+ hintNone: 'No está en ninguna de las carpetas revisadas. Si {program} funciona en tu terminal, busca allí dónde está («where {program}» en Windows, «which {program}» en Mac) y elige ese archivo con Elegir….',+ hintFound: 'Encontrado: {path}',+ reportNote: 'Si sigue sin encontrarse, copia el informe y envíalo con un issue. Incluye rutas de carpetas de este equipo.',+ copyReport: 'Copiar informe',+ copied: 'Copiado',+ close: 'Cerrar',needsKey: 'Sin configurar',unavailable: 'Aún no disponible: llegará en una actualización',checking: 'Comprobando…',connect: 'Conectar',disconnect: 'Desconectar',+ disconnectHint: 'Deja de usarlo en OpenFilm; su sesión se mantiene. Para usar otra cuenta, cambia de cuenta en {name} y vuelve a conectarlo.',+ accountChatgpt: 'Cuenta de ChatGPT',+ accountApiKey: 'Clave de API',+ accountConsole: 'Anthropic Console',+ usage: 'Uso',+ usageLoading: 'Leyendo lo que queda del plan…',+ usageFiveHour: '5 horas',+ usageWeek: 'Esta semana',+ usageWindow: '{hours} horas',+ usageUsed: '{percent}% usado',+ usageResets: 'se renueva {time}',signIn: 'Iniciar sesión',install: 'Instalar',setUpKey: 'Configurar',change: 'Cambiar',showInChat: 'Mostrar en el chat',- showHint: 'Solo los agentes activados aparecen en el chat. Desconectar uno de tus agentes aquí no cambia su propio inicio de sesión.',+ showHint: 'Solo los agentes activados aparecen en el chat.',failed: 'No ha funcionado. Inténtalo de nuevo.',format: 'Formato de API',address: 'Dirección',@@ -1417,10 +1483,16 @@ export const es: Words = {},developer: {intro: 'Para saber exactamente qué hizo un agente y por qué: nada de esto cambia lo que hacen los agentes.',- group: 'Registros de turnos',+ group: 'Cada turno',+ changes: 'Mostrar lo que cambió cada turno',+ changesHint: 'Bajo cada respuesta, los archivos que el turno añadió, eliminó o cambió, con las líneas añadidas y quitadas. Haz clic en un archivo para ver sus líneas cambiadas.',logs: 'Mostrar el registro de cada turno',- logsHint: 'En el chat, cada turno tiene un botón Registro: la petición y la sesión en que se ejecutó, cada herramienta con su entrada y su salida, cada pregunta y respuesta, y cómo terminó, tal como lo envió el agente. Bajo cada respuesta, lo que el turno cambió en film.html, línea por línea como un diff.',+ logsHint: 'En el chat, cada turno tiene un botón Registro: la petición y la sesión en que se ejecutó, cada herramienta con su entrada y su salida, cada pregunta y respuesta, y cómo terminó, tal como lo envió el agente.',where: 'Cada turno se registra esté o no activado, en la carpeta .film/logs del proyecto, solo en este ordenador.',+ releaseGroup: 'Versiones',+ previewWhatsNew: 'Novedades',+ previewWhatsNewHint: 'Muestra las notas de {version} tal como se ven tras actualizar.',+ preview: 'Vista previa',},shortcuts: {groupMarks: "Entrada y salida",@@ -1431,6 +1503,7 @@ export const es: Words = {markIn: "Marcar entrada en el cabezal",markOut: "Marcar salida en el cabezal",clearMarks: "Borrar entrada y salida",+ rangeClip: "Entrada y salida en los clips seleccionados",goInOut: "Ir a la entrada / salida",playRange: "Reproducir de la entrada a la salida",loop: "Reproducción en bucle (el rango, si no la película)",@@ -1444,14 +1517,20 @@ export const es: Words = {rippleEnd: "Recorte de rizo del final desde el cabezal",cut: "Cortar los clips seleccionados",duplicate: "Duplicar los clips seleccionados",+ copyAttrs: "Copiar los atributos de un clip",+ pasteAttrs: "Pegar atributos en los clips seleccionados",+ speedPanel: "Velocidad del clip seleccionado",+ detachAudio: "Separar el sonido de un vídeo",nudgeClip: "Mover los clips seleccionados un fotograma",- toggleMagnet: "Activar / desactivar el imán",+ toggleMagnet: "Activar / desactivar el imán de la pista principal",toggleSnap: "Activar / desactivar el ajuste",+ toggleLinkage: "Activar / desactivar la vinculación",zoomFit: "Ajustar el zoom a toda la película",frameStep: 'Mover el cabezal de reproducción un fotograma',- secondStep: 'Mover el cabezal de reproducción un segundo',+ jumpStep: "Mover el cabezal 10 fotogramas",rippleDelete: 'Eliminar con desplazamiento y cerrar el hueco',selectAll: 'Seleccionar los clips desbloqueados (haz clic antes en la línea de tiempo)',+ selectSide: "Seleccionar todos los clips antes / después del cabezal",deselect: 'Deseleccionar',zoomIn: 'Acercar la línea de tiempo',zoomOut: 'Alejar la línea de tiempo',@@ -1475,9 +1554,9 @@ export const es: Words = {remove: 'Eliminar los clips seleccionados',selectMode: 'Herramienta de selección',splitMode: 'Herramienta de división',+ splitModeAll: 'Con la herramienta de corte, haz clic con ella pulsada: se cortan todas las pistas ahí',editModeSwap: 'Mantén al soltar un clip: insertar en vez de sobrescribir, o al revés',- slip: 'Arrastra un clip con ella pulsada: mueve lo que muestra el clip, no el clip',- slide: 'Arrastra un clip con ellas pulsadas: los clips de al lado ceden o toman el tiempo',+ copyDrag: 'Arrastra un clip con ella pulsada: una copia va donde lo sueltas y el clip se queda',},providers: {desc: 'De dónde vienen las voces, la música, los efectos de sonido, las transcripciones, las imágenes y el video. OpenFilm crea y edita películas sin ninguno de ellos: conecta uno cuando tu agente necesite medios.',diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex 60d1784..dadc257 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -18,6 +18,18 @@ export const ja: Words = {installFailed: 'OpenFilm {version} をインストールできませんでした。OpenFilm を終了してもう一度開くとインストールされます。',installing: '再起動しています…',},+ whatsNew: {+ eyebrow: 'アップデート済み',+ title: 'OpenFilm {version} の新機能',+ close: '閉じる',+ changelog: 'すべての変更履歴',+ ok: 'OK',+ kind: {+ new: '新機能',+ improved: '改善',+ fixed: '修正',+ },+ },host: {refer: 'チャットで参照',regionHint: '枠をドラッグしてチャットで参照',@@ -345,6 +357,7 @@ export const ja: Words = {summary: '{n} ファイル · {dur}',approx: '約',emptyFilm: '映像が空です — 先にクリップを追加してください。',+ missingMedia: 'メディアファイルが {n} 個見つかりません:{files}。先にタイムラインの赤いクリップを右クリックして再リンクしてください。',pickPreset: 'プラットフォームを 1 つ以上選んでください。',noCaptions: 'この映像には字幕がありません。',noAudio: 'この映像にはサウンドがありません。',@@ -453,6 +466,7 @@ export const ja: Words = {editsRestore: '元に戻す',editsLeaveOut: '戻さない',previewFailed: 'プレビューを描画できませんでした。',+ previewMissing: 'メディアなし:{file} · クリップを右クリックで再リンク',filmEmptyHint: 'メディアをタイムラインにドラッグして映像を作り始めるか、エージェントに作成を頼んでください。',filmBroken: '現在 film.html を読み込めないため、Studio は最後の状態の映像を表示しています。修正されるまで、ここでの編集は保存できません:',filmNotReady: 'ビデオはまだ準備できていません',@@ -494,11 +508,10 @@ export const ja: Words = {stepSplit: '{clip} を分割',stepDetachAudio: '{clip} のオーディオを切り離し',stepRolled: '{clip} の後のカットをロール',- stepSlipped: '{clip} をスリップ',- stepSlid: '{clip} をスライド',stepRippleTrimmed: '{clip} をリップルトリム',stepGapClosed: '隙間を詰めました',stepMainClosed: 'メイントラックを詰めました',+ stepGapsClosed: 'トラックの隙間を詰めました',stepLinked: '{clip} をリンク',stepUnlinked: '{clip} のリンクを解除',stepSpeed: '{clip} の速度を変更',@@ -512,6 +525,7 @@ export const ja: Words = {stepSubtitleRemoved: '字幕を削除',stepSubtitleText: '字幕を編集',stepSubtitleAdded: '字幕を追加',+ stepMarker: 'マーカーを変更しました',stepNormalized: "ラウドネスを {clip} LUFS にノーマライズ",stepFroze: "{clip} のフレームをフリーズ",stepReplaced: "{clip} を置き換え",@@ -1170,22 +1184,17 @@ export const ja: Words = {zoom: 'ズーム',snap: 'スナップ',snapOn: 'オン:クリップの端、再生ヘッド、マーカーにスナップします',- snapOff: 'オフ:離した位置にそのまま配置します',+ snapOff: 'オフ:離した位置にそのまま置きます',magnet: 'メイントラックマグネット',- magnetOn: 'オン:メイントラック(いちばん下の映像トラック)は常に隙間なく詰まります。置いたクリップは挿入、削除で隙間を詰め、トリムはリップル。ほかのトラックではクリップが重なりません:ほかのクリップの位置に置くと空いているトラックへ移り、削除で隙間が残ります。置くときに Alt で逆',- magnetOff: 'オフ:メイントラックもほかと同じです。置いたクリップは下にあるものを上書きします。置くときに Alt で挿入',+ magnetOn: 'オン:メイントラックのクリップは隙間なく並びます',+ magnetOff: 'オフ:メイントラックのクリップは置いた位置のままです',linkage: '連動',- linkageOn: 'オン:メイントラックのクリップが動くと、その上で始まるテロップ、B-roll、音声も一緒に動きます。いくつものショットにまたがる長いクリップ(BGM など)はそのままです',+ linkageOn: 'オン:テロップ、オーバーレイ、音声が下のメイントラックのクリップと一緒に動きます',linkageOff: 'オフ:メイントラックの編集はメイントラックだけを動かします',- sync: '同期ロック',- syncOn: 'オン(Premiere と同じ):どのトラックのリップルも、ロックされていない全トラックを動かします。全トラックに余裕がある範囲で',- syncOff: 'オフ:リップルはクリップのあるトラックだけを動かします',- linked: 'リンクされたクリップ',- linkedOn: 'オン:ビデオと切り離したオーディオを一緒に選択・編集します。Alt クリックで一つだけ',- linkedOff: 'オフ:リンクされたクリップを一つずつ選択・編集します',- rippleShort: '他のトラックのクリップが邪魔をしています:同期を保つため {s} 秒の隙間が残りました。このトラックだけ詰めるには同期ロックをオフにしてください。',+ rippleShort: '他のトラックのクリップが邪魔をしています:同期を保つため {s} 秒の隙間が残りました。',gapClosedAlone: '他のトラックのクリップが邪魔をしていたため、隙間はこのトラックだけで詰めました。',menuCloseGap: '隙間を詰める',+ menuCloseGaps: 'このトラックの隙間をすべて詰める',menuRippleStart: '再生ヘッドまで先頭をリップルトリム',menuRippleEnd: '再生ヘッドから末尾をリップルトリム',menuLink: 'リンク',@@ -1195,8 +1204,6 @@ export const ja: Words = {trim: 'トリム',ripple: 'リップル',roll: 'ロール',- slip: 'スリップ',- slide: 'スライド',sourceEnd: '素材の端です',},trackLocked: 'トラックはロックされています',@@ -1272,6 +1279,22 @@ export const ja: Words = {replaceKind: "映像は映像で、音は音で置き換えます",replaceShort: "新しいファイルのほうが短いため、クリップが {s} 秒短くなりました",},+ /* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */+ clipAttrs: {+ title: '属性をペースト',+ picture: '映像',+ sound: 'オーディオ',+ place: '位置とサイズ',+ blend: 'ブレンド(不透明度、描画モード)',+ volume: '音量',+ fade: 'フェードイン / フェードアウト',+ paste: 'ペースト',+ copy: '属性をコピー',+ pasteMenu: '属性をペースト…',+ copied: '属性をコピーしました:クリップを選んで ⌘⇧V でペースト',+ nothing: '先にクリップの属性をコピーしてください(⌘⇧C)',+ selectFirst: '先にクリップを選んでください',+ },transitions: {dissolve: 'クロスディゾルブ','dip-black': 'ブラックへディップ',@@ -1336,6 +1359,11 @@ export const ja: Words = {groups: {help: 'ヘルプ',},+ links: {+ github: 'GitHub',+ examples: 'サンプル',+ site: 'ウェブサイト',+ },sections: {agents: 'エージェント',providers: 'プロバイダー',@@ -1375,9 +1403,18 @@ export const ja: Words = {inApp: 'Studio はデスクトップアプリと一緒に更新されます:OpenFilm → Check for Updates…',howTitle: 'アップデート',how: 'このコマンドを実行するか、エージェントに実行を頼んでください。Studio が新しいバージョンで再起動します。',+ appOff: 'ソースから実行している開発版のため自動では更新されません。インストール版は自動で更新されます。',+ appChecked: '前回の確認:{time}。',+ appDownloading: 'OpenFilm {version} をダウンロード中…',+ appStaging: 'OpenFilm {version} を準備中…',+ appRetry: 'もう一度',+ whatsNew: 'このバージョンの新機能',+ appOffline: 'アップデートサービスに接続できません。接続を確認してください。',+ appUnavailable: '現在アップデートを利用できません。しばらくしてからお試しください。',+ appFailed: 'アップデートを完了できませんでした。しばらくしてからお試しください。',},agents: {- intro: 'チャットで使えるエージェントです。Codex や Claude Code など「あなたのエージェント」はご自身のもので、それぞれのサインインを使います。自分のキーはご自身が契約しているサービスで動作します。',+ intro: 'チャットで使えるエージェントです。Codex や Claude Code など「あなたのエージェント」はあなた自身のもので、このコンピューターでサインイン中のアカウントを使います。別のアカウントを使うには、エージェント側でアカウントを切り替え、ここで接続を解除してもう一度接続してください。自分のキーはあなたのサービスで動きます。',byokName: '自分のキー',groupYours: 'あなたのエージェント',groupMore: 'ほかに使えるエージェント',@@ -1385,23 +1422,52 @@ export const ja: Words = {recommendedHint: 'いちばん安上がり:すでにお持ちのサブスクリプションで使えます',ready: '接続済み',off: '未接続',- signedOut: 'サインアウト済み',+ signedOut: 'サインインしていません',waiting: 'ターミナルでのサインインを待っています…',waitingHint: '開いたウィンドウでサインインを完了してから、戻ってきてください。',startAgain: 'やり直す',missing: 'このコンピューターにインストールされていません',claudeSetup: 'Claude アプリの Code タブを一度開くと Claude Code がインストールされます',+ locate: '場所を指定…',+ locateTitle: '{name} のプログラムを選択',+ locateButton: 'これを使う',+ chosenAt: '選択したプログラムを使用中:{path}',+ automatic: '自動検出に戻す',+ notAProgram: 'このコンピュータで起動できるプログラムではありません。エージェントのプログラム自体を選んでください(Windows では .exe または .cmd ファイル)。',+ didNotStart: 'ここからは起動できませんでした:',+ whyMissing: '見つからない理由は?',+ searching: '検索中…',+ hintChosenMissing: '選択したプログラムが見つかりません。もう一度選ぶか、自動検出に戻してください。',+ hintWsl: 'WSL(Windows 上の Linux)にインストールされていますが、OpenFilm からは使えません。Windows にもインストールしてから戻ってください。',+ hintUnusable: '同じ名前のファイルはありましたが、どれも起動できません。「場所を指定…」でプログラム自体を選んでください。',+ hintNone: '検索したフォルダのどこにもありません。ターミナルで {program} が使えるなら、そこで場所を調べ(Windows は「where {program}」、Mac は「which {program}」)、そのファイルを「場所を指定…」で選んでください。',+ hintFound: '見つかりました:{path}',+ reportNote: 'それでも見つからない場合は、レポートをコピーして issue に添えて送ってください。このコンピュータのフォルダのパスが含まれます。',+ copyReport: 'レポートをコピー',+ copied: 'コピーしました',+ close: '閉じる',needsKey: '未設定',unavailable: 'まだ使えません(今後のアップデートで提供)',checking: '確認中…',connect: '接続',disconnect: '接続を解除',+ disconnectHint: 'OpenFilm での利用を止めます。サインインはそのままです。別のアカウントを使うには、{name} でアカウントを切り替えてからもう一度接続してください。',+ accountChatgpt: 'ChatGPT アカウント',+ accountApiKey: 'API キー',+ accountConsole: 'Anthropic Console',+ usage: '使用量',+ usageLoading: '残りの利用枠を読み込み中…',+ usageFiveHour: '5 時間',+ usageWeek: '今週',+ usageWindow: '{hours} 時間',+ usageUsed: '{percent}% 使用',+ usageResets: '{time}にリセット',signIn: 'サインイン',install: 'インストール',setUpKey: '設定',change: '変更',showInChat: 'チャットに表示',- showHint: 'オンにしたエージェントだけがチャットに表示されます。ここであなたのエージェントの接続を解除しても、それぞれのサインインはそのまま残ります。',+ showHint: 'オンにしたエージェントだけがチャットに表示されます。',failed: 'うまくいきませんでした。もう一度お試しください。',format: 'API 形式',address: 'アドレス',@@ -1417,10 +1483,16 @@ export const ja: Words = {},developer: {intro: 'エージェントが何をなぜ行ったかを正確に確かめるためのものです。エージェントの動作は変わりません。',- group: 'ターンのログ',+ group: '各ターン',+ changes: '各ターンの変更を表示',+ changesHint: '各返信の下に、そのターンで追加・削除・変更されたファイルと、増減した行数を表示します。ファイルをクリックすると変更された行を確認できます。',logs: '各ターンのログを表示',- logsHint: 'チャットの各ターンに「ログ」ボタンが付きます。プロンプトと実行したセッション、各ツール呼び出しの入力と出力、すべての質問と回答、終わり方を、エージェントが送ったとおりに確認できます。各返信の下には、そのターンで film.html が変わった箇所も行ごとの差分で表示されます。',+ logsHint: 'チャットの各ターンに「ログ」ボタンが付きます。プロンプトと実行したセッション、各ツール呼び出しの入力と出力、すべての質問と回答、終わり方を、エージェントが送ったとおりに確認できます。',where: 'この設定に関係なく、すべてのターンはプロジェクトの .film/logs フォルダに記録されます(このコンピュータ内のみ)。',+ releaseGroup: 'リリース',+ previewWhatsNew: '新機能のお知らせ',+ previewWhatsNewHint: 'アップデート後に表示されるとおりに {version} のお知らせを表示します。',+ preview: 'プレビュー',},shortcuts: {groupMarks: "イン点とアウト点",@@ -1431,6 +1503,7 @@ export const ja: Words = {markIn: "再生ヘッドにイン点を設定",markOut: "再生ヘッドにアウト点を設定",clearMarks: "イン点とアウト点を消去",+ rangeClip: "選んだクリップにイン点とアウト点を合わせる",goInOut: "イン点 / アウト点へ移動",playRange: "イン点からアウト点まで再生",loop: "ループ再生(範囲があれば範囲、なければ全体)",@@ -1444,14 +1517,20 @@ export const ja: Words = {rippleEnd: "末尾を再生ヘッドからリップルトリム",cut: "選択したクリップをカット",duplicate: "選択したクリップを複製",+ copyAttrs: "クリップの属性をコピー",+ pasteAttrs: "選んだクリップに属性をペースト",+ speedPanel: "選んだクリップの速度",+ detachAudio: "動画の音声を分離",nudgeClip: "選択したクリップを 1 フレーム移動",- toggleMagnet: "マグネットのオン / オフ",+ toggleMagnet: "メイントラックマグネットのオン / オフ",toggleSnap: "スナップのオン / オフ",+ toggleLinkage: "連動のオン / オフ",zoomFit: "全体が収まるようにズーム",frameStep: '再生ヘッドを 1 フレーム移動',- secondStep: '再生ヘッドを 1 秒移動',+ jumpStep: "再生ヘッドを 10 フレーム移動",rippleDelete: 'リップル削除して隙間を詰める',selectAll: 'ロックされていないクリップを選択(先にタイムラインをクリック)',+ selectSide: "再生ヘッドより前 / 後のクリップをすべて選択",deselect: '選択解除',zoomIn: 'タイムラインをズームイン',zoomOut: 'タイムラインをズームアウト',@@ -1475,9 +1554,9 @@ export const ja: Words = {remove: '選択したクリップを削除',selectMode: '選択ツール',splitMode: '分割ツール',+ splitModeAll: '分割ツールで押しながらクリック:すべてのトラックをその位置で分割',editModeSwap: 'クリップを置くときに押す:挿入と上書きを入れ替え',- slip: '押しながらクリップをドラッグ:スリップ(クリップの中身だけが動く)',- slide: '押しながらクリップをドラッグ:スライド(両隣のクリップが時間を譲る・受け取る)',+ copyDrag: '押しながらクリップをドラッグ:離した位置にコピー、元のクリップはそのまま',},providers: {desc: '音声、音楽、効果音、書き起こし、画像、ビデオの提供元です。OpenFilm はこれらがなくても映像の作成・編集ができます。エージェントがメディアを必要とするときに接続してください。',diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex 21274b5..bb3e192 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -18,6 +18,18 @@ export const ko: Words = {installFailed: 'OpenFilm {version}을(를) 설치하지 못했습니다. OpenFilm을 종료했다가 다시 열면 설치됩니다.',installing: '재시작하는 중…',},+ whatsNew: {+ eyebrow: '업데이트됨',+ title: 'OpenFilm {version}의 새로운 기능',+ close: '닫기',+ changelog: '전체 변경 내역',+ ok: '확인',+ kind: {+ new: '새 기능',+ improved: '개선',+ fixed: '수정',+ },+ },host: {refer: '채팅에서 참조',regionHint: '상자를 드래그해 채팅에서 참조',@@ -345,6 +357,7 @@ export const ko: Words = {summary: '파일 {n}개 · {dur}',approx: '약',emptyFilm: '영상이 비어 있습니다. 먼저 클립을 추가하세요.',+ missingMedia: '미디어 파일 {n}개가 없습니다: {files}. 먼저 타임라인의 빨간 클립을 오른쪽 클릭해 다시 연결하세요.',pickPreset: '플랫폼을 하나 이상 선택하세요.',noCaptions: '이 영상에는 자막이 없습니다.',noAudio: '이 영상에는 사운드가 없습니다.',@@ -453,6 +466,7 @@ export const ko: Words = {editsRestore: '복원',editsLeaveOut: '제외',previewFailed: '미리보기를 그릴 수 없습니다.',+ previewMissing: '미디어 없음: {file} · 클립 오른쪽 클릭으로 다시 연결',filmEmptyHint: '미디어를 타임라인으로 끌어와 영상을 시작하거나, 에이전트에게 만들어 달라고 요청하세요.',filmBroken: '지금은 film.html을 읽을 수 없어 Studio가 마지막 상태의 영상을 보여 줍니다. 문제가 해결될 때까지 여기서 한 편집은 저장할 수 없습니다:',filmNotReady: '비디오가 아직 준비되지 않았습니다',@@ -494,11 +508,10 @@ export const ko: Words = {stepSplit: '{clip} 분할',stepDetachAudio: '{clip}의 오디오 분리',stepRolled: '{clip} 뒤의 컷 롤',- stepSlipped: '{clip} 슬립',- stepSlid: '{clip} 슬라이드',stepRippleTrimmed: '{clip} 리플 트림',stepGapClosed: '간격 메움',stepMainClosed: '메인 트랙을 메움',+ stepGapsClosed: '트랙의 간격을 메움',stepLinked: '{clip} 연결',stepUnlinked: '{clip} 연결 해제',stepSpeed: '{clip} 속도 변경',@@ -512,6 +525,7 @@ export const ko: Words = {stepSubtitleRemoved: '자막 삭제',stepSubtitleText: '자막 편집',stepSubtitleAdded: '자막 추가',+ stepMarker: '마커 변경',stepNormalized: "라우드니스를 {clip} LUFS로 정규화",stepFroze: "{clip}의 프레임 고정",stepReplaced: "{clip} 바꿈",@@ -1170,22 +1184,17 @@ export const ko: Words = {zoom: '확대/축소',snap: '스냅',snapOn: '켬: 클립 가장자리, 재생 헤드, 마커에 스냅합니다',- snapOff: '끔: 손을 놓은 정확한 위치에 놓입니다',+ snapOff: '끔: 손을 놓은 자리에 그대로 놓입니다',magnet: '메인 트랙 자석',- magnetOn: '켬: 메인 트랙(가장 아래 화면 트랙)은 항상 빈틈없이 붙어 있습니다. 놓은 클립은 삽입되고, 삭제하면 간격이 메워지며, 트림은 리플됩니다. 다른 트랙에서는 클립이 겹치지 않습니다: 다른 클립 자리에 놓으면 빈 트랙으로 옮겨지고, 삭제하면 간격이 남습니다. 놓을 때 Alt로 반대로',- magnetOff: '끔: 메인 트랙도 다른 트랙과 같습니다. 놓은 클립이 아래 클립을 덮어씁니다. 놓을 때 Alt로 삽입',+ magnetOn: '켬: 메인 트랙의 클립이 빈틈없이 붙어 있습니다',+ magnetOff: '끔: 메인 트랙의 클립이 놓은 자리에 그대로 있습니다',linkage: '연동',- linkageOn: '켬: 메인 트랙의 클립이 움직이면, 그 위에서 시작하는 자막, B-roll, 소리도 함께 움직입니다. 여러 샷에 걸친 긴 클립(배경음악 등)은 그대로 있습니다',+ linkageOn: '켬: 자막, 오버레이, 소리가 아래 메인 트랙 클립과 함께 움직입니다',linkageOff: '끔: 메인 트랙 편집은 메인 트랙만 움직입니다',- sync: '동기 잠금',- syncOn: '켬(Premiere와 같음): 어느 트랙의 리플이든 잠기지 않은 모든 트랙을 함께 움직입니다. 모든 트랙에 공간이 있는 만큼',- syncOff: '끔: 리플이 클립이 있는 트랙만 움직입니다',- linked: '연결된 클립',- linkedOn: '켬: 비디오와 분리한 오디오를 함께 선택하고 편집합니다. Alt 클릭으로 하나만',- linkedOff: '끔: 연결된 클립을 하나씩 선택하고 편집합니다',- rippleShort: '다른 트랙의 클립이 막고 있습니다: 동기를 유지하려고 {s}초 간격이 남았습니다. 이 트랙만 메우려면 동기 잠금을 끄세요.',+ rippleShort: '다른 트랙의 클립이 막고 있습니다: 동기를 유지하려고 {s}초 간격이 남았습니다.',gapClosedAlone: '다른 트랙의 클립이 막고 있어 이 트랙에서만 간격을 메웠습니다.',menuCloseGap: '간격 메우기',+ menuCloseGaps: '이 트랙의 간격 모두 메우기',menuRippleStart: '재생 헤드까지 시작 리플 트림',menuRippleEnd: '재생 헤드부터 끝 리플 트림',menuLink: '연결',@@ -1195,8 +1204,6 @@ export const ko: Words = {trim: '트림',ripple: '리플',roll: '롤',- slip: '슬립',- slide: '슬라이드',sourceEnd: '소스의 끝입니다',},trackLocked: '트랙 잠김',@@ -1272,6 +1279,22 @@ export const ko: Words = {replaceKind: "화면은 화면으로, 소리는 소리로 바꿉니다",replaceShort: "새 파일이 더 짧아 클립이 {s}초 짧아졌습니다",},+ /* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */+ clipAttrs: {+ title: '속성 붙여넣기',+ picture: '화면',+ sound: '오디오',+ place: '위치와 크기',+ blend: '혼합 (불투명도, 혼합 모드)',+ volume: '볼륨',+ fade: '페이드 인 / 페이드 아웃',+ paste: '붙여넣기',+ copy: '속성 복사',+ pasteMenu: '속성 붙여넣기…',+ copied: '속성을 복사했습니다: 클립을 선택하고 ⌘⇧V로 붙여넣으세요',+ nothing: '먼저 클립의 속성을 복사하세요 (⌘⇧C)',+ selectFirst: '먼저 클립을 선택하세요',+ },transitions: {dissolve: '크로스 디졸브','dip-black': '검정으로 딥',@@ -1335,6 +1358,11 @@ export const ko: Words = {groups: {help: '도움말',},+ links: {+ github: 'GitHub',+ examples: '예제',+ site: '웹사이트',+ },sections: {agents: '에이전트',providers: '제공업체',@@ -1374,9 +1402,18 @@ export const ko: Words = {inApp: 'Studio는 데스크톱 앱과 함께 업데이트됩니다: OpenFilm → Check for Updates…',howTitle: '업데이트',how: '이 명령을 실행하거나 에이전트에게 실행을 맡기세요. Studio가 새 버전으로 다시 시작됩니다.',+ appOff: '소스에서 실행 중인 개발 빌드라 자동으로 업데이트되지 않습니다. 설치된 앱은 자동으로 업데이트됩니다.',+ appChecked: '마지막 확인: {time}.',+ appDownloading: 'OpenFilm {version} 다운로드 중…',+ appStaging: 'OpenFilm {version} 준비 중…',+ appRetry: '다시 시도',+ whatsNew: '이번 버전의 새로운 기능',+ appOffline: '업데이트 서비스에 연결할 수 없습니다. 연결을 확인하세요.',+ appUnavailable: '지금은 업데이트를 사용할 수 없습니다. 나중에 다시 시도하세요.',+ appFailed: '업데이트를 완료하지 못했습니다. 나중에 다시 시도하세요.',},agents: {- intro: '채팅에서 사용할 수 있는 에이전트입니다. Codex, Claude Code 등 \'내 에이전트\'는 각자의 로그인으로 쓰는 내 에이전트이고, 내 키는 내가 쓰는 서비스에서 실행됩니다.',+ intro: '채팅에서 쓸 수 있는 에이전트입니다. Codex, Claude Code 등 「내 에이전트」는 나의 것이며 이 컴퓨터에 로그인된 계정을 사용합니다. 다른 계정을 쓰려면 에이전트에서 계정을 바꾼 뒤 여기서 연결을 해제했다가 다시 연결하세요. 내 키는 내 서비스에서 실행됩니다.',byokName: '내 키',groupYours: '내 에이전트',groupMore: '그 밖에 쓸 수 있는 에이전트',@@ -1384,23 +1421,52 @@ export const ko: Words = {recommendedHint: '가장 저렴한 방법: 이미 쓰고 있는 구독으로 사용',ready: '연결됨',off: '연결 안 됨',- signedOut: '로그아웃됨',+ signedOut: '로그인하지 않음',waiting: '터미널에서 로그인을 기다리는 중…',waitingHint: '열린 창에서 로그인을 완료한 뒤 돌아오세요.',startAgain: '다시 시작',missing: '이 컴퓨터에 설치되어 있지 않음',claudeSetup: 'Claude 앱의 Code 탭을 한 번 열면 Claude Code가 설치됩니다',+ locate: '직접 선택…',+ locateTitle: '{name} 프로그램 선택',+ locateButton: '이것 사용',+ chosenAt: '선택한 프로그램 사용 중: {path}',+ automatic: '자동 감지로 되돌리기',+ notAProgram: '이 컴퓨터에서 실행할 수 있는 프로그램이 아닙니다. 에이전트 프로그램 자체를 선택하세요(Windows에서는 .exe 또는 .cmd 파일).',+ didNotStart: '여기서 실행하지 못했습니다:',+ whyMissing: '왜 찾지 못하나요?',+ searching: '찾는 중…',+ hintChosenMissing: '선택한 프로그램이 더 이상 없습니다. 다시 선택하거나 자동 감지로 되돌리세요.',+ hintWsl: 'WSL(Windows의 Linux)에 설치되어 있어 OpenFilm에서 사용할 수 없습니다. Windows에도 설치한 뒤 돌아오세요.',+ hintUnusable: '같은 이름의 파일은 찾았지만 실행할 수 있는 것이 없습니다. “직접 선택…”으로 프로그램 자체를 선택하세요.',+ hintNone: '검색한 폴더 어디에도 없습니다. 터미널에서 {program}이(가) 실행된다면 그곳에서 위치를 확인하고(Windows는 “where {program}”, Mac은 “which {program}”) 그 파일을 “직접 선택…”으로 선택하세요.',+ hintFound: '찾았습니다: {path}',+ reportNote: '그래도 찾지 못하면 보고서를 복사해 issue에 첨부해 보내 주세요. 이 컴퓨터의 폴더 경로가 포함됩니다.',+ copyReport: '보고서 복사',+ copied: '복사됨',+ close: '닫기',needsKey: '설정되지 않음',unavailable: '아직 사용할 수 없습니다. 업데이트로 제공될 예정입니다',checking: '확인 중…',connect: '연결',disconnect: '연결 해제',+ disconnectHint: 'OpenFilm에서 사용을 멈춥니다. 로그인은 그대로입니다. 다른 계정을 쓰려면 {name}에서 계정을 바꾼 뒤 다시 연결하세요.',+ accountChatgpt: 'ChatGPT 계정',+ accountApiKey: 'API 키',+ accountConsole: 'Anthropic Console',+ usage: '사용량',+ usageLoading: '남은 사용량을 읽는 중…',+ usageFiveHour: '5시간',+ usageWeek: '이번 주',+ usageWindow: '{hours}시간',+ usageUsed: '{percent}% 사용',+ usageResets: '{time} 초기화',signIn: '로그인',install: '설치',setUpKey: '설정',change: '변경',showInChat: '채팅에 표시',- showHint: '켜 둔 에이전트만 채팅에 표시됩니다. 여기서 내 에이전트의 연결을 해제해도 각자의 로그인은 그대로 유지됩니다.',+ showHint: '켜 둔 에이전트만 채팅에 표시됩니다.',failed: '실패했습니다. 다시 시도하세요.',format: 'API 형식',address: '주소',@@ -1416,10 +1482,16 @@ export const ko: Words = {},developer: {intro: '에이전트가 무엇을 왜 했는지 정확히 확인하기 위한 기능입니다. 에이전트의 동작은 바뀌지 않습니다.',- group: '턴 로그',+ group: '각 턴',+ changes: '각 턴의 변경 사항 보기',+ changesHint: '각 답변 아래에 이번 턴에서 추가·삭제·변경된 파일과 늘고 줄어든 줄 수를 보여 줍니다. 파일을 누르면 변경된 줄을 볼 수 있습니다.',logs: '각 턴의 로그 보기',- logsHint: '채팅의 모든 턴에 로그 버튼이 생깁니다. 프롬프트와 실행된 세션, 각 도구 호출의 입력과 출력, 모든 질문과 답변, 끝난 방식을 에이전트가 보낸 그대로 볼 수 있습니다. 각 답변 아래에는 이번 턴에서 film.html이 바뀐 부분도 줄 단위 비교로 보여 줍니다.',+ logsHint: '채팅의 모든 턴에 로그 버튼이 생깁니다. 프롬프트와 실행된 세션, 각 도구 호출의 입력과 출력, 모든 질문과 답변, 끝난 방식을 에이전트가 보낸 그대로 볼 수 있습니다.',where: '이 설정과 관계없이 모든 턴은 프로젝트의 .film/logs 폴더에 기록됩니다(이 컴퓨터에만).',+ releaseGroup: '릴리스',+ previewWhatsNew: '새로운 기능 안내',+ previewWhatsNewHint: '업데이트 후 보이는 그대로 {version}의 안내를 보여 줍니다.',+ preview: '미리 보기',},shortcuts: {groupMarks: "시작점과 끝점",@@ -1430,6 +1502,7 @@ export const ko: Words = {markIn: "재생 헤드에 시작점 지정",markOut: "재생 헤드에 끝점 지정",clearMarks: "시작점과 끝점 지우기",+ rangeClip: "선택한 클립으로 시작점과 끝점 설정",goInOut: "시작점 / 끝점으로 이동",playRange: "시작점부터 끝점까지 재생",loop: "반복 재생 (범위가 있으면 범위, 없으면 전체)",@@ -1443,14 +1516,20 @@ export const ko: Words = {rippleEnd: "끝을 재생 헤드부터 리플 트림",cut: "선택한 클립 잘라내기",duplicate: "선택한 클립 복제",+ copyAttrs: "클립 속성 복사",+ pasteAttrs: "선택한 클립에 속성 붙여넣기",+ speedPanel: "선택한 클립의 속도",+ detachAudio: "동영상의 소리 분리",nudgeClip: "선택한 클립을 1프레임 이동",- toggleMagnet: "자석 켜기 / 끄기",+ toggleMagnet: "메인 트랙 자석 켜기 / 끄기",toggleSnap: "스냅 켜기 / 끄기",+ toggleLinkage: "연동 켜기 / 끄기",zoomFit: "전체가 보이게 확대/축소",frameStep: '재생 헤드를 1프레임 이동',- secondStep: '재생 헤드를 1초 이동',+ jumpStep: "재생 헤드 10프레임 이동",rippleDelete: '리플 삭제 후 간격 메우기',selectAll: '잠기지 않은 클립 선택(먼저 타임라인 클릭)',+ selectSide: "재생 헤드 앞 / 뒤의 모든 클립 선택",deselect: '선택 해제',zoomIn: '타임라인 확대',zoomOut: '타임라인 축소',@@ -1474,9 +1553,9 @@ export const ko: Words = {remove: '선택한 클립 삭제',selectMode: '선택 도구',splitMode: '분할 도구',+ splitModeAll: '분할 도구에서 누른 채 클릭: 모든 트랙을 그 자리에서 분할',editModeSwap: '클립을 놓을 때 누르기: 삽입과 덮어쓰기를 바꿈',- slip: '누른 채 클립 드래그: 슬립 (클립 안의 내용만 움직임)',- slide: '누른 채 클립 드래그: 슬라이드 (양옆 클립이 시간을 주고받음)',+ copyDrag: '누른 채 클립 드래그: 놓은 자리에 복사본, 원래 클립은 그대로',},providers: {desc: '음성, 음악, 효과음, 대본, 이미지, 비디오를 가져오는 곳입니다. OpenFilm은 이 서비스 없이도 영상을 만들고 편집합니다. 에이전트에게 미디어가 필요할 때 연결하세요.',diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 0fd800d..ebb4325 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -19,6 +19,18 @@ export const zhCN: Words = {installFailed: 'OpenFilm {version} 暂时无法安装。退出 OpenFilm 后重新打开即可安装。',installing: '正在重启…',},+ whatsNew: {+ eyebrow: '已更新',+ title: 'OpenFilm {version} 有哪些新内容',+ close: '关闭',+ changelog: '完整更新日志',+ ok: '知道了',+ kind: {+ new: '新功能',+ improved: '改进',+ fixed: '修复',+ },+ },host: {refer: '在对话中引用',regionHint: '拖出一个框,在对话中引用',@@ -346,6 +358,7 @@ export const zhCN: Words = {summary: '{n} 个文件 · {dur}',approx: '约',emptyFilm: '影片是空的——请先添加一个片段。',+ missingMedia: '缺少 {n} 个媒体文件:{files}。请先在时间线上右键红色片段重新链接,再导出。',pickPreset: '请至少选择一个平台。',noCaptions: '此影片没有字幕。',noAudio: '此影片没有声音。',@@ -454,6 +467,7 @@ export const zhCN: Words = {editsRestore: '恢复它们',editsLeaveOut: '不恢复',previewFailed: '无法绘制预览。',+ previewMissing: '媒体丢失:{file} · 右键片段重新链接',filmEmptyHint: '把媒体拖到时间轴上开始制作影片,或让智能体帮你做一部。',filmBroken: '目前无法读取 film.html,因此 Studio 显示的是影片上一次的样子;修复之前,这里的编辑无法保存:',filmNotReady: '视频尚未就绪',@@ -495,11 +509,10 @@ export const zhCN: Words = {stepSplit: '分割 {clip}',stepDetachAudio: '分离 {clip} 的音频',stepRolled: '滚动了 {clip} 之后的剪切点',- stepSlipped: '滑移了 {clip}',- stepSlid: '滑动了 {clip}',stepRippleTrimmed: '波纹裁剪了 {clip}',stepGapClosed: '合拢了间隙',stepMainClosed: '合拢了主轨',+ stepGapsClosed: '批量闭合了空隙',stepLinked: '关联了 {clip}',stepUnlinked: '取消关联 {clip}',stepSpeed: '改了 {clip} 的速度',@@ -513,6 +526,7 @@ export const zhCN: Words = {stepSubtitleRemoved: '删除字幕',stepSubtitleText: '修改字幕',stepSubtitleAdded: '添加字幕',+ stepMarker: '修改了标记',stepNormalized: "响度标准化到 {clip} LUFS",stepFroze: "定格了 {clip} 的一帧",stepReplaced: "替换了 {clip}",@@ -1170,23 +1184,18 @@ export const zhCN: Words = {zoomFit: '适应宽度',zoom: '缩放',snap: '吸附',- snapOn: '开:吸附到片段边缘、播放头和标记',- snapOff: '关:在松手的位置精确放置',+ snapOn: '开:拖动时吸附到片段边缘、播放头和标记',+ snapOff: '关:松手在哪就放在哪',magnet: '主轨磁吸',- magnetOn: '开:主轨(最下面的画面轨)始终首尾相接。放到主轨上的片段会插入,删除时合上空隙,裁剪时波纹。其他轨道上片段不会互相覆盖:放到已有片段的位置会自动换到空闲轨,删除留空。放下时按住 Alt 反过来',- magnetOff: '关:主轨和其他轨道一样。放下片段时覆盖下面的片段,放下时按住 Alt 改为插入',+ magnetOn: '开:主轨上的片段自动首尾相接,不留空隙',+ magnetOff: '关:主轨上的片段放在哪就在哪',linkage: '联动',- linkageOn: '开:主轨上的片段移动时,开始在它上面的字幕、画中画和声音跟着一起走。横跨好几个镜头的长片段(比如背景音乐)留在原处',+ linkageOn: '开:字幕、画中画、声音跟着下面的主轨片段一起移动、删除',linkageOff: '关:编辑主轨时只动主轨',- sync: '同步锁定',- syncOn: '开(同 Premiere):任何轨道上的波纹操作都会带上所有未锁定的轨道,只要每条轨都有空间',- syncOff: '关:波纹操作只动片段所在的轨道',- linked: '关联片段',- linkedOn: '开:视频和分离出的音频一起选中、一起编辑。按住 Alt 点击只选一个',- linkedOff: '关:关联的片段逐个选中、逐个编辑',- rippleShort: '其他轨道上有片段挡着:为保持同步,留下了 {s} 秒的空隙。关掉同步锁定即可只在本轨合上。',+ rippleShort: '其他轨道上有片段挡着:为保持同步,留下了 {s} 秒的空隙。',gapClosedAlone: '其他轨道上有片段挡着,间隙只在本轨合上了。',menuCloseGap: '合拢间隙',+ menuCloseGaps: '批量闭合空隙',menuRippleStart: '波纹裁剪开头到播放头',menuRippleEnd: '波纹裁剪结尾到播放头',menuLink: '关联',@@ -1196,8 +1205,6 @@ export const zhCN: Words = {trim: '裁剪',ripple: '波纹',roll: '滚动',- slip: '滑移',- slide: '滑动',sourceEnd: '素材到头了',},trackLocked: '轨道已锁定',@@ -1273,6 +1280,22 @@ export const zhCN: Words = {replaceKind: "画面只能用画面替换,声音只能用声音替换",replaceShort: "新文件更短:片段短了 {s} 秒",},+ /* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */+ clipAttrs: {+ title: '粘贴属性',+ picture: '画面',+ sound: '音频',+ place: '位置大小',+ blend: '混合(不透明度、混合模式)',+ volume: '音量',+ fade: '淡入/淡出',+ paste: '粘贴',+ copy: '复制属性',+ pasteMenu: '粘贴属性…',+ copied: '已复制属性:选中片段后按 ⌘⇧V 粘贴',+ nothing: '请先复制一个片段的属性(⌘⇧C)',+ selectFirst: '请先选中片段',+ },transitions: {dissolve: '交叉溶解','dip-black': '黑场过渡',@@ -1337,6 +1360,11 @@ export const zhCN: Words = {groups: {help: '帮助',},+ links: {+ github: 'GitHub',+ examples: '示例',+ site: '官网',+ },sections: {agents: '智能体',providers: '服务商',@@ -1376,9 +1404,18 @@ export const zhCN: Words = {inApp: 'Studio 随桌面端一起更新:OpenFilm → Check for Updates…',howTitle: '更新',how: '运行这条命令,或让你的智能体运行:Studio 会以新版本重新启动。',+ appOff: '这是从源码运行的开发版,不会自动更新;安装的正式版会自己更新。',+ appChecked: '上次检查:{time}。',+ appDownloading: '正在下载 OpenFilm {version}…',+ appStaging: '正在准备 OpenFilm {version}…',+ appRetry: '重试',+ whatsNew: '查看本次更新内容',+ appOffline: '连不上更新服务,请检查网络。',+ appUnavailable: '更新服务暂时不可用,请稍后再试。',+ appFailed: '更新没能完成,请稍后再试。',},agents: {- intro: '对话可以使用的智能体。Codex、Claude Code 等「你的智能体」是你自己的,使用它们各自的登录;自有密钥则运行在你自己的服务上。',+ intro: '对话可以使用的智能体。Codex、Claude Code 等「你的智能体」是你自己的,使用这台电脑上已登录的账号:想换账号,就在智能体自己那里切换,再回到这里断开、重新连接。自有密钥运行在你自己的服务上。',byokName: '自有密钥',groupYours: '你的智能体',groupMore: '还可以接入的智能体',@@ -1386,23 +1423,52 @@ export const zhCN: Words = {recommendedHint: '最划算:用你已有的订阅',ready: '已连接',off: '未连接',- signedOut: '已退出登录',+ signedOut: '未登录',waiting: '正在等待终端中的登录…',waitingHint: '请在刚打开的窗口中完成登录,然后回到这里。',startAgain: '重新开始',missing: '这台电脑上尚未安装',claudeSetup: '打开一次 Claude 应用的 Code 标签页即可安装 Claude Code',+ locate: '手动选择…',+ locateTitle: '选择 {name} 程序',+ locateButton: '使用这个',+ chosenAt: '正在使用你选择的程序:{path}',+ automatic: '改回自动检测',+ notAProgram: '这不是这台电脑能启动的程序。请选择 agent 程序本身(Windows 上是 .exe 或 .cmd 文件)。',+ didNotStart: '从这里启动失败:',+ whyMissing: '为什么检测不到?',+ searching: '正在查找…',+ hintChosenMissing: '你选择的程序已经不在了。重新选择,或改回自动检测。',+ hintWsl: '它装在 WSL(Windows 里的 Linux)中,OpenFilm 用不了。请在 Windows 里也装一份,然后回到这里。',+ hintUnusable: '找到了同名文件,但都无法启动。请用“手动选择…”选中程序本身。',+ hintNone: '在查找过的文件夹里都没有找到。如果 {program} 在你的终端里能用,在终端里查出它的位置(Windows 用“where {program}”,Mac 用“which {program}”),再用“手动选择…”选中那个文件。',+ hintFound: '已找到:{path}',+ reportNote: '如果还是检测不到,复制诊断信息,附在 issue 里发给我们。里面有这台电脑上的文件夹路径。',+ copyReport: '复制诊断信息',+ copied: '已复制',+ close: '关闭',needsKey: '尚未设置',unavailable: '暂未开放,后续版本推出',checking: '正在检查…',connect: '连接',disconnect: '断开连接',+ disconnectHint: '停止在 OpenFilm 中使用,它的登录保持不变。想用别的账号,先在 {name} 里切换账号,再回来重新连接。',+ accountChatgpt: 'ChatGPT 账号',+ accountApiKey: 'API 密钥',+ accountConsole: 'Anthropic Console',+ usage: '用量',+ usageLoading: '正在读取剩余额度…',+ usageFiveHour: '5 小时',+ usageWeek: '本周',+ usageWindow: '{hours} 小时',+ usageUsed: '已用 {percent}%',+ usageResets: '{time}重置',signIn: '登录',install: '安装',setUpKey: '设置',change: '更改',showInChat: '在对话中显示',- showHint: '只有已开启的智能体会显示在对话中。在这里断开你的智能体,不会影响它们自己的登录。',+ showHint: '只有打开的智能体会显示在对话中。',failed: '没有成功,请重试。',format: 'API 格式',address: '地址',@@ -1418,10 +1484,16 @@ export const zhCN: Words = {},developer: {intro: '用来弄清楚 agent 到底做了什么、为什么这么做;这里的设置不会改变 agent 的行为。',- group: '每轮日志',+ group: '每一轮',+ changes: '显示每一轮的改动',+ changesHint: '每条回复下面列出这一轮新增、删除或修改的文件,以及增减的行数。点开一个文件可以看到改动的行。',logs: '显示每一轮的日志',- logsHint: '打开后,对话里每一轮都有“日志”按钮:提示词和所在会话、每次工具调用的输入和输出、每个提问和回答、这一轮怎么结束的,都按 agent 发来的原样显示。每条回复下面还会列出这一轮对 film.html 的改动,逐行对比。',+ logsHint: '打开后,对话里每一轮都有“日志”按钮:提示词和所在会话、每次工具调用的输入和输出、每个提问和回答、这一轮怎么结束的,都按 agent 发来的原样显示。',where: '不论是否打开,每一轮都会记录在项目的 .film/logs 文件夹里,只保存在这台电脑上。',+ releaseGroup: '发版',+ previewWhatsNew: '更新内容弹窗',+ previewWhatsNewHint: '按用户更新后看到的样子,显示 {version} 的更新内容。',+ preview: '预览',},shortcuts: {groupMarks: "入点和出点",@@ -1432,6 +1504,7 @@ export const zhCN: Words = {markIn: "在播放头处设入点",markOut: "在播放头处设出点",clearMarks: "清除入点和出点",+ rangeClip: "以选中片段设定入点和出点",goInOut: "跳到入点 / 出点",playRange: "从入点播放到出点",loop: "循环播放(有范围时循环范围,否则整片)",@@ -1445,14 +1518,20 @@ export const zhCN: Words = {rippleEnd: "波纹裁剪结尾到播放头",cut: "剪切所选片段",duplicate: "复制一份所选片段",+ copyAttrs: "复制片段属性",+ pasteAttrs: "把属性粘贴到选中的片段",+ speedPanel: "选中片段的变速",+ detachAudio: "分离视频的音频",nudgeClip: "把所选片段移动一帧",- toggleMagnet: "开关磁吸",+ toggleMagnet: "开关主轨磁吸",toggleSnap: "开关吸附",+ toggleLinkage: "开关联动",zoomFit: "缩放到整片",frameStep: '播放头移动一帧',- secondStep: '播放头移动一秒',+ jumpStep: "播放头移动 10 帧",rippleDelete: '波纹删除并合拢间隙',selectAll: '选择未锁定的片段(需先点击时间轴)',+ selectSide: "向左全选 / 向右全选(播放头之前 / 之后的所有片段)",deselect: '取消选择',zoomIn: '放大时间轴',zoomOut: '缩小时间轴',@@ -1476,9 +1555,9 @@ export const zhCN: Words = {remove: '删除所选片段',selectMode: '选择工具',splitMode: '分割工具',+ splitModeAll: '分割工具下按住它点击:所有轨道都在这里切开',editModeSwap: '放下片段时按住:插入改为覆盖,或反过来',- slip: '按住并拖动片段:滑移(片段里的画面移动,片段不动)',- slide: '按住并拖动片段:滑动(两侧的片段让出或补上时间)',+ copyDrag: '按住它拖动片段:在松手处复制一份,原片段不动',},providers: {desc: '配音、音乐、音效、文字稿、图片和视频从哪里来。即使不连接任何服务,OpenFilm 也能制作和编辑影片:等智能体需要素材时再连接即可。',diff --git a/packages/openfilm/studio/ui/src/lib/clip-attrs.test.ts b/packages/openfilm/studio/ui/src/lib/clip-attrs.test.tsnew file mode 100644index 0000000..e47c26a--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/clip-attrs.test.ts@@ -0,0 +1,37 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { attrsOf, groupsOf, pasteAttrs, type AttrClip, type AttrGroup } from './clip-attrs.ts';++const ALL = new Set<AttrGroup>(['place', 'blend', 'volume', 'fade']);+const video = (id: string, more: Partial<AttrClip> = {}): AttrClip => ({ id, src: `${id}.mp4`, ...more } as AttrClip);++test('a clip\'s attributes: its place, its blending, its volume and its fades', () => {+ const red = video('red', { box: { x: 10, y: 20, w: 960, h: 540, r: 5 }, style: 'opacity: 0.5; mix-blend-mode: screen; border-radius: 8px', volume: 0.4, overrides: [{ fade: [0.5, 1] }] as never });+ const attrs = attrsOf(red);+ assert.deepEqual(attrs.place, { x: 10, y: 20, w: 960, h: 540, r: 5 });+ assert.deepEqual(attrs.blend, { opacity: '0.5', mode: 'screen' });+ assert.equal(attrs.volume, 0.4);+ assert.deepEqual(attrs.fade, [0.5, 1]);+ assert.deepEqual(groupsOf(attrs), ['place', 'blend', 'volume', 'fade']);+ assert.deepEqual(groupsOf(attrsOf({ id: 'bed', src: 'bed.wav' } as AttrClip)), ['volume', 'fade'], 'a sound has no picture');+});++test('pasted: the ticked groups, onto clips that can take them; the rest of a style stays; a fade fits the clip', () => {+ const attrs = attrsOf(video('red', { box: { x: 10, y: 20, w: 960, h: 540 }, style: 'opacity: 0.5', volume: 0.4, overrides: [{ fade: [2, 2] }] as never }));+ const blue = { loc: 'film.html#0.2', clip: video('blue', { style: 'filter: blur(2px)' }), lengthS: 6 };+ const bed = { loc: 'film.html#1.0', clip: { id: 'bed', src: 'bed.wav' } as AttrClip, lengthS: 3 };+ assert.deepEqual(pasteAttrs(attrs, ALL, [blue, bed]), [+ { loc: 'film.html#0.2', prop: 'box', value: { x: 10, y: 20, w: 960, h: 540 } },+ { loc: 'film.html#0.2', prop: 'style', value: 'filter: blur(2px); opacity: 0.5' },+ { loc: 'film.html#0.2', prop: 'volume', value: 0.4 },+ { loc: 'film.html#0.2', prop: 'fade', value: [2, 2] },+ { loc: 'film.html#1.0', prop: 'volume', value: 0.4 },+ { loc: 'film.html#1.0', prop: 'fade', value: [1.5, 1.5] },+ ]);+ /* only the place ticked; the clip copied from is left alone */+ assert.deepEqual(pasteAttrs(attrs, new Set(['place']), [blue, { loc: 'film.html#0.0', clip: video('red'), lengthS: 6 }]), [+ { loc: 'film.html#0.2', prop: 'box', value: { x: 10, y: 20, w: 960, h: 540 } },+ ]);+ /* a clip with no place of its own copied: the target's goes too (it is back to its default) */+ assert.deepEqual(pasteAttrs(attrsOf(video('plain')), new Set(['place']), [blue]), [{ loc: 'film.html#0.2', prop: 'box', value: null }]);+});diff --git a/packages/openfilm/studio/ui/src/lib/clip-attrs.ts b/packages/openfilm/studio/ui/src/lib/clip-attrs.tsnew file mode 100644index 0000000..f2be441--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/clip-attrs.ts@@ -0,0 +1,102 @@+/**+ * A clip's attributes copied onto other clips (CapCut's 复制属性 / 粘贴属性, ⌘⇧C / ⌘⇧V): the groups its paste dialog+ * offers, all ticked unless unticked —+ * · `place`: where the picture sits and how big it is, turned (`box`);+ * · `blend`: how it shows through (`opacity`, `mix-blend-mode` in its style; the rest of its style stays);+ * · `volume`: how loud its sound is;+ * · `fade`: its fade in and fade out, shortened to fit a shorter clip.+ * A picture's groups go onto pictures, the sound's onto clips with sound; what a clip cannot take is left out.+ *+ * Pure: the editor reads the copy from film.html and writes the edits it gives back (lib/film-clip-edits).+ */+import { declared, withDeclarations } from './clip-look.ts';+import { fadeMsOf } from './clip-fade.ts';+import { filmSrcKind } from './film.ts';+import type { ClipEdit } from './film-clip-edits';++export type AttrGroup = 'place' | 'blend' | 'volume' | 'fade';++type Box = { x: number; y: number; w?: number; h?: number; r?: number };+/** What a clip's attributes are read from: its row in film.html (lib/film's FilmClip, api's Clip). */+export interface AttrClip {+ id: string;+ src: string;+ sound?: boolean;+ box?: Box;+ style?: string;+ volume?: number;+ overrides?: readonly unknown[];+}+export const ATTR_GROUPS: readonly AttrGroup[] = ['place', 'blend', 'volume', 'fade'];++export interface CopiedAttrs {+ /** The clip copied from, for saying so. */+ from: string;+ picture: boolean;+ sound: boolean;+ place: Box | null;+ blend: { opacity: string | null; mode: string | null };+ volume: number;+ /** Seconds. */+ fade: [number, number];+}++/** What a clip shows and what it plays: a picture (a page, a video, a still), a sound (a video, a sound). */+function sides(clip: Pick<AttrClip, 'src' | 'sound'>): { picture: boolean; sound: boolean } {+ const kind = clip.sound ? 'sound' : filmSrcKind(clip.src);+ return { picture: kind !== 'sound', sound: kind === 'video' || kind === 'sound' };+}++/** The attributes of a clip, as film.html has them. */+export function attrsOf(clip: AttrClip): CopiedAttrs {+ const style = clip.style ?? '';+ const [fadeIn, fadeOut] = fadeMsOf(clip);+ return {+ from: clip.id,+ ...sides(clip),+ place: clip.box ? { ...clip.box } : null,+ blend: { opacity: declared(style, 'opacity') ?? null, mode: declared(style, 'mix-blend-mode') ?? null },+ volume: clip.volume ?? 1,+ fade: [fadeIn / 1000, fadeOut / 1000],+ };+}++/** The groups a copy has anything for: a picture's for a picture, the sound's for a sound. */+export function groupsOf(attrs: CopiedAttrs): AttrGroup[] {+ return ATTR_GROUPS.filter((g) => (g === 'place' || g === 'blend' ? attrs.picture : g === 'volume' ? attrs.sound : true));+}++export interface AttrTarget {+ loc: string;+ clip: AttrClip;+ /** Its length on the film, seconds: a fade longer than the clip is shortened. */+ lengthS: number;+}++/** The fade a clip `lengthS` long can take: the copy's, both ends shortened alike when together they are longer. */+function fitted([fadeIn, fadeOut]: [number, number], lengthS: number): [number, number] {+ const total = fadeIn + fadeOut;+ if (total <= lengthS || total <= 0) return [fadeIn, fadeOut];+ const k = lengthS / total;+ return [Math.floor(fadeIn * k * 1000) / 1000, Math.floor(fadeOut * k * 1000) / 1000];+}++/** The edits that put the ticked groups of a copy onto these clips (not onto the clip copied from). */+export function pasteAttrs(attrs: CopiedAttrs, groups: ReadonlySet<AttrGroup>, targets: readonly AttrTarget[]): ClipEdit[] {+ const out: ClipEdit[] = [];+ for (const { loc, clip, lengthS } of targets) {+ if (clip.id === attrs.from) continue;+ const can = sides(clip);+ if (can.picture && attrs.picture && groups.has('place')) out.push({ loc, prop: 'box', value: attrs.place ? { ...attrs.place } : null });+ if (can.picture && attrs.picture && groups.has('blend')) {+ const style = withDeclarations(clip.style ?? '', { opacity: attrs.blend.opacity, 'mix-blend-mode': attrs.blend.mode });+ if (style !== (clip.style ?? '')) out.push({ loc, prop: 'style', value: style || null });+ }+ if (can.sound && attrs.sound && groups.has('volume')) out.push({ loc, prop: 'volume', value: attrs.volume });+ if (groups.has('fade')) {+ const [fadeIn, fadeOut] = fitted(attrs.fade, lengthS);+ out.push({ loc, prop: 'fade', value: fadeIn > 0 || fadeOut > 0 ? [fadeIn, fadeOut] : null });+ }+ }+ return out;+}diff --git a/packages/openfilm/studio/ui/src/lib/export-spec.test.ts b/packages/openfilm/studio/ui/src/lib/export-spec.test.tsindex 1cdc83f..619f4d1 100644--- a/packages/openfilm/studio/ui/src/lib/export-spec.test.ts+++ b/packages/openfilm/studio/ui/src/lib/export-spec.test.ts@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { exportEstimateBytes, exportFilmPixels, exportFramedDims, exportGifDims, exportGifEstimateBytes, rangeMarks } from './export-spec.ts';+import { exportEstimateBytes, exportFilmPixels, exportFramedDims, exportGifDims, exportGifEstimateBytes, exportPresetsFor, rangeMarks } from './export-spec.ts';import { filmFrameBox } from './film-frame.ts';const stage = { w: 1920, h: 1080 };@@ -67,3 +67,14 @@ test('a frame comes out in its own shape: 16:9 around a 2:1 film is 1920 × 1080assert.deepEqual(exportFramedDims(wide, '4:5', 'contain', 1080), { w: 1080, h: 1350 });assert.deepEqual(exportGifDims(filmFrameBox(wide, '16:9'), 640), { w: 640, h: 360 });});++test('platforms: China\'s first in Chinese, none of them in any other language', () => {+ const zh = exportPresetsFor('zh-CN').map((p) => p.id);+ assert.deepEqual(zh.slice(0, 5), ['bilibili', 'douyin', 'kuaishou', 'channels', 'xiaohongshu']);+ assert.ok(zh.includes('youtube') && zh.includes('tiktok'), 'the others still offered in Chinese');+ for (const language of ['en', 'ja', 'ko', 'es']) {+ assert.ok(!exportPresetsFor(language).some((p) => p.china), language);+ }+ const xhs = exportPresetsFor('zh-CN').find((p) => p.id === 'xiaohongshu');+ assert.deepEqual(exportFramedDims({ w: 1920, h: 1080 }, xhs.frame, 'contain', xhs.shortEdge), { w: 1080, h: 1440 });+});diff --git a/packages/openfilm/studio/ui/src/lib/export-spec.ts b/packages/openfilm/studio/ui/src/lib/export-spec.tsindex 609121a..011ccd1 100644--- a/packages/openfilm/studio/ui/src/lib/export-spec.ts+++ b/packages/openfilm/studio/ui/src/lib/export-spec.ts@@ -45,9 +45,16 @@ export interface ExportPreset {burnSubtitles: boolean;/** The platform's longest video, in seconds. */maxDurationSec?: number;+ /** A platform of mainland China: offered (first) when Studio speaks Chinese, not otherwise. */+ china?: boolean;}export const EXPORT_PRESETS: readonly ExportPreset[] = [+ { id: 'bilibili', name: '哔哩哔哩', group: 'landscape', frame: '16:9', shortEdge: 1080, fps: 60, burnSubtitles: false, china: true },+ { id: 'douyin', name: '抖音', group: 'vertical', frame: '9:16', shortEdge: 1080, fps: 30, burnSubtitles: true, china: true },+ { id: 'kuaishou', name: '快手', group: 'vertical', frame: '9:16', shortEdge: 1080, fps: 30, burnSubtitles: true, china: true },+ { id: 'channels', name: '视频号', group: 'vertical', frame: '9:16', shortEdge: 1080, fps: 30, burnSubtitles: true, china: true },+ { id: 'xiaohongshu', name: '小红书', group: 'feed', frame: '3:4', shortEdge: 1080, fps: 30, burnSubtitles: true, china: true },{ id: 'youtube', name: 'YouTube', group: 'landscape', frame: '16:9', shortEdge: 1080, fps: 60, burnSubtitles: false },{ id: 'youtube-4k', name: 'YouTube 4K', group: 'landscape', frame: '16:9', shortEdge: 2160, fps: 60, burnSubtitles: false },{ id: 'x', name: 'X', group: 'landscape', frame: '16:9', shortEdge: 1080, fps: 30, burnSubtitles: true, maxDurationSec: 140 },@@ -58,6 +65,11 @@ export const EXPORT_PRESETS: readonly ExportPreset[] = [{ id: 'square', name: 'LinkedIn · Facebook', group: 'feed', frame: '1:1', shortEdge: 1080, fps: 30, burnSubtitles: true },];+/** The platforms offered in a language: China's first in Chinese, and none of them in any other. */+export function exportPresetsFor(language: string): readonly ExportPreset[] {+ return language === 'zh-CN' ? [...EXPORT_PRESETS.filter((p) => p.china), ...EXPORT_PRESETS.filter((p) => !p.china)] : EXPORT_PRESETS.filter((p) => !p.china);+}+export function exportPreset(id: string | undefined): ExportPreset | null {return EXPORT_PRESETS.find((p) => p.id === id) ?? null;}diff --git a/packages/openfilm/studio/ui/src/lib/freeze-frame.test.ts b/packages/openfilm/studio/ui/src/lib/freeze-frame.test.tsindex 63fc5b4..bd8b3a2 100644--- a/packages/openfilm/studio/ui/src/lib/freeze-frame.test.ts+++ b/packages/openfilm/studio/ui/src/lib/freeze-frame.test.ts@@ -23,20 +23,20 @@ test('the playhead\'s moment of the clip\'s file: its in point plus the time intassert.equal(freezeSourceMs({ startMs: 10_000, endMs: 14_000 }, 14_000), null);});-test('with the magnet the video is cut at the playhead, the still goes in, and the rest moves on 2 s', () => {+test('with the magnet the video is cut at the playhead, the still goes in, and the rest moves on 3 s', () => {const m = model();const ops = planFreeze(m, { clip: shot as never, track: 0, atMs: 3000, still: 'assets/shot-frame-3s.png', mode: 'insert', sync: true })!;const [picture, sound] = run(m, ops);- assert.deepEqual(picture, ['shot.mp4@0#0,3.graded', 'assets/shot-frame-3s.png@3#0,2.graded', 'shot.mp4@5#3,6.graded', 'next.mp4@8#0,2']);+ assert.deepEqual(picture, ['shot.mp4@0#0,3.graded', 'assets/shot-frame-3s.png@3#0,3.graded', 'shot.mp4@6#3,6.graded', 'next.mp4@9#0,2']);/* a sound already playing at the playhead is not cut (as any insert there, see planRoom) */assert.deepEqual(sound, ['vo.mp3@1#0,8']);});-test('without it the still covers 2 s of the video after the playhead; nothing else moves', () => {+test('without it the still covers 3 s of the video after the playhead; nothing else moves', () => {const m = model();const ops = planFreeze(m, { clip: shot as never, track: 0, atMs: 3000, still: 'f.png', mode: 'overwrite', sync: true })!;const [picture, sound] = run(m, ops);- assert.deepEqual(picture, ['shot.mp4@0#0,3.graded', 'f.png@3#0,2.graded', 'shot.mp4@5#5,6.graded', 'next.mp4@6#0,2']);+ assert.deepEqual(picture, ['shot.mp4@0#0,3.graded', 'f.png@3#0,3.graded', 'next.mp4@6#0,2']);assert.deepEqual(sound, ['vo.mp3@1#0,8']);});diff --git a/packages/openfilm/studio/ui/src/lib/freeze-frame.ts b/packages/openfilm/studio/ui/src/lib/freeze-frame.tsindex 736ea38..0833c18 100644--- a/packages/openfilm/studio/ui/src/lib/freeze-frame.ts+++ b/packages/openfilm/studio/ui/src/lib/freeze-frame.ts@@ -9,8 +9,8 @@ import { planRoom, type EditMode, type EditModel } from './timeline-edit.ts';import { snapToFrame } from './timecode.ts';import type { TimelineBlock } from './timeline-layout';-/** How long a freeze frame lasts. */-export const FREEZE_MS = 2000;+/** How long a freeze frame lasts: 3 s, as CapCut's. */+export const FREEZE_MS = 3000;/** The moment of the clip's file the playhead is on (ms), or null when the playhead is not on the clip. */export function freezeSourceMs(block: Pick<TimelineBlock, 'startMs' | 'endMs' | 'inMs' | 'speed'>, atMs: number): number | null {diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.tsindex dfc26d6..3003f78 100644--- a/packages/openfilm/studio/ui/src/lib/host.ts+++ b/packages/openfilm/studio/ui/src/lib/host.ts@@ -6,6 +6,9 @@ import React from 'react';* editor in, served with `startStudio({ editorDir })`); Studio then leaves out what only makes sense in a browser,* such as the button that introduces the desktop app.*/+/** Settings → Developer, as the app keeps it (`developer` below). */+export interface HostDeveloper { logs: boolean; changes: boolean }+export interface StudioHost {/** the version of this interface the app speaks */version: 1;@@ -61,13 +64,20 @@ export interface StudioHost {/*** The agents the app's chat can use, for Settings → Agents: connected or not, shown in the chat's menu or not, and* the person's own key for the one that takes one. `onChange` tells of every change (a sign-in finished, a key set up)- * and returns a way to stop listening.+ * and returns a way to stop listening. One of the person's own agents not found can be pointed at (`locate`: the+ * system's file dialog, with Studio's words; `{ ok: false }` and no error when cancelled) and set back to being+ * found (`useAutomatic`); `diagnose` says what was searched (an older app has none of these).*/agents?: {list: () => Promise<HostAgent[]>;connect: (id: HostAgentId) => Promise<{ ok: boolean; error?: string }>;disconnect: (id: HostAgentId) => Promise<unknown>;+ /** Codex: what is left of its plan, as it says for the account signed in (null: it can't say; other agents, null) */+ usage?: (id: HostAgentId, fresh?: boolean) => Promise<HostAgentUsage | null>;setShown: (id: HostAgentId, shown: boolean) => Promise<unknown>;+ locate?: (id: HostAgentId, words?: { title?: string; button?: string }) => Promise<{ ok: boolean; error?: string; code?: 'not-a-program' | 'did-not-start' | string }>;+ useAutomatic?: (id: HostAgentId) => Promise<unknown>;+ diagnose?: (id: HostAgentId) => Promise<HostAgentDiagnosis | null>;configureByok: (config: { format: HostByokFormat; baseUrl?: string; models: string[]; key?: string }) => Promise<{ ok: boolean; error?: string; code?: string }>;onChange: (listener: (agents: HostAgent[]) => void) => () => void;};@@ -87,15 +97,19 @@ export interface StudioHost {update?: {onChange: (listener: (update: HostUpdate | null) => void) => () => void;restart: () => Promise<{ ok: boolean; error?: string }>;+ /** Settings → About: the whole state now and on every change, and a check made now (it resolves when it ends) */+ onState?: (listener: (state: HostUpdateState) => void) => () => void;+ check?: () => Promise<HostUpdateState | null>;};/**- * The app's developer mode, for Settings → Developer: on, its chat shows each turn's full log (everything the agent- * sent and was answered, as it happened). `onChange` tells of a change from anywhere and returns a way to stop.+ * The app's chat, for Settings → Developer: `logs`, each turn's full log (everything the agent sent and was+ * answered, as it happened); `changes`, what each turn changed in the project's files, under its reply. `onChange`+ * tells of a change from anywhere and returns a way to stop.*/developer?: {- get: () => Promise<boolean>;- set: (on: boolean) => Promise<unknown>;- onChange: (listener: (on: boolean) => void) => () => void;+ get: () => Promise<HostDeveloper>;+ set: (next: Partial<HostDeveloper>) => Promise<unknown>;+ onChange: (listener: (prefs: HostDeveloper) => void) => () => void;};/*** The app picks folders, and knows where a dropped one is: the Projects list gets "Open…", which asks the app for a@@ -112,17 +126,41 @@ export interface StudioHost {/** A question about spending, worded for the person (see `asks`). */export interface HostAsk { id: string; title: string; body: string | null; allowLabel: string; denyLabel: string }+/**+ * Where the app's update is: `off` (this build never updates) · idle · checking · current · available · downloading+ * (`progress` 0–100) · staging (macOS unpacks it) · ready · installing · error. `availableVersion`: the newer version+ * found; `checkedAt`: when a check last answered (ms); `error`: offline · unavailable · failed (a check or download),+ * agent-busy · exporting · install-failed (a Restart not done).+ */+export interface HostUpdateState {+ status: 'off' | 'idle' | 'checking' | 'current' | 'available' | 'downloading' | 'staging' | 'ready' | 'installing' | 'error';+ version: string;+ channel: 'stable' | 'beta';+ availableVersion: string | null;+ progress: number;+ checkedAt: number | null;+ error: string | null;+}+/** An update of the app, ready to install or installing; `waiting`: why the last Restart did not go ahead. */export type HostUpdate = { status: 'ready' | 'installing'; version: string; waiting?: 'agent-busy' | 'exporting' | 'install-failed' | null };export type HostAgentId = 'codex' | 'claude' | 'gemini' | 'copilot' | 'cursor' | 'opencode' | 'codebuddy' | 'qwen' | 'kimi' | 'byok';+/**+ * What was searched for an agent (`agents.diagnose`): the report to copy, the program's name, where it was found, and+ * when it was not, why: chosen-missing (the program chosen is gone) · wsl (only inside WSL, which the app cannot use) ·+ * unusable (files with its name, none that starts) · none.+ */+export interface HostAgentDiagnosis { found: string | null; program?: string; hint: 'chosen-missing' | 'wsl' | 'unusable' | 'none' | null; text: string }+/** The API a person's own key is for: OpenAI's Responses or Chat Completions, or Anthropic's Messages. */export type HostByokFormat = 'responses' | 'chat' | 'anthropic';/*** One agent as the app has it. `status`: ready · off (disconnected in the app; its own sign-in is kept) · sign-in (its* own sign-in is needed) · waiting (signing in, in Terminal) · missing (not installed: `install` says where from) ·- * key (no key set up) · unavailable (not offered yet) · checking.+ * key (no key set up) · unavailable (not offered yet) · checking. `account`: whose sign-in it uses, as the program says+ * (no key or token).*/export interface HostAgent {id: HostAgentId;@@ -132,10 +170,28 @@ export interface HostAgent {install?: string | null;/** What installing it takes, when `install` is not a download: 'code-tab', Claude Code comes with the Claude app (its Code tab). */setupRequired?: string | null;+ /** The program used (the person's own agents), and the one the person chose for it, if they did. */+ path?: string | null;+ chosen?: string | null;error?: string;+ account?: HostAgentAccount;byok?: { format: HostByokFormat; baseUrl: string; model: string; models?: string[]; last4: string };}+/**+ * What is left of an agent's plan: each window's share used (0–100), how long it is (minutes) and when it resets (ms);+ * `kind`: five_hour · seven_day · window (another length).+ * `account`: whose it is, when the program says it here (Codex's email and plan).+ */+export interface HostAgentUsage {+ plan: string | null;+ windows: Array<{ kind: 'five_hour' | 'seven_day' | 'window'; minutes: number | null; usedPercent: number; resetsAt: number | null }>;+ account?: { email?: string; plan?: string };+}++/** Whose sign-in an agent uses: how (a claude.ai or ChatGPT account, an API key…), and what the program tells of it. */+export interface HostAgentAccount { method: 'claude.ai' | 'console' | 'api-key' | 'chatgpt' | 'other'; email?: string; org?: string; plan?: string }+/** A box on the picture, in the film's stage pixels (the stage is `stage.w` × `stage.h`, film.html's stage). */export interface StageBox { x: number; y: number; w: number; h: number }diff --git a/packages/openfilm/studio/ui/src/lib/picture-files.test.ts b/packages/openfilm/studio/ui/src/lib/picture-files.test.tsnew file mode 100644index 0000000..db00ddd--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/picture-files.test.ts@@ -0,0 +1,14 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { changesPicture } from './picture-files.ts';++test('a page, its styles and code, or a clip\'s own media changes the picture; notes, scripts and other media do not', () => {+ const used = new Set(['assets/video/a.mp4']);+ assert.equal(changesPicture(['mg/title.html'], used), true);+ assert.equal(changesPicture(['shared/style.css', 'notes.md'], used), true);+ assert.equal(changesPicture(['data/points.json'], used), true);+ assert.equal(changesPicture(['assets/video/a.mp4'], used), true);+ assert.equal(changesPicture(['assets/video/b.mp4'], used), false);+ assert.equal(changesPicture(['script.md', 'tools/make_voice.py', 'render.log', 'run.sh'], used), false);+ assert.equal(changesPicture(undefined, used), true);+});diff --git a/packages/openfilm/studio/ui/src/lib/picture-files.ts b/packages/openfilm/studio/ui/src/lib/picture-files.tsnew file mode 100644index 0000000..9280aae--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/picture-files.ts@@ -0,0 +1,19 @@+/**+ * Whether files that changed in the project's folder can change the picture, so the preview draws it again. A page+ * draws from what it loads (styles, code, pictures, data, fonts), and a clip plays its media file; what no page loads+ * (notes, scripts, logs, an agent's own working files) cannot change it, and redrawing the whole film for each of them+ * would make the preview reload over and over while an agent writes them.+ */++/** files no page loads: words to read, programs to run, settings of tools */+const NOT_PICTURE = /\.(md|markdown|txt|log|py|sh|bash|zsh|rb|go|rs|java|c|cc|cpp|h|hpp|swift|kt|toml|ya?ml|ini|cfg|env|lock|patch|diff|bak|tmp|swp)$/i;++/**+ * True when any of `paths` (in the project, with `/`) can change the picture: a page or anything a page may load, or a+ * media file a clip plays (`used`), made again in place. Other media under assets/ are loaded as they are used. No+ * paths (the watcher could not tell): true.+ */+export function changesPicture(paths: readonly string[] | undefined, used: ReadonlySet<string | undefined>): boolean {+ if (!paths) return true;+ return paths.some((path) => (path.startsWith('assets/') ? used.has(path) : !NOT_PICTURE.test(path)));+}diff --git a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.tsindex 96eeb86..248bb45 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.ts@@ -1,7 +1,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { applyOps } from '../../../server/ops.mjs';-import { clipboardItemsOf, clipboardNow, copyLinks, pasteEdit, pastePlan, type TimelinePasteJob } from './timeline-clipboard.ts';+import { clipboardItemsOf, clipboardNow, copyLinks, pasteEdit, pastePlan, planCopies, type TimelinePasteJob } from './timeline-clipboard.ts';import { editModelOf } from './timeline-edit.ts';import type { TimelineBlock, TimelineTrack } from './timeline-layout';@@ -157,22 +157,43 @@ test('a paste in overwrite mode cuts what is under it; a locked track refuses itassert.equal(pasteEdit(copied, locked, editModelOf(locked), 3000, 'doc-0', { mode: 'overwrite', sync: true }), null);});-test('with the magnet, as CapCut: a paste on the main track inserts; off it a copy never covers a clip', () => {+test('with the magnet, as CapCut: a paste covers nothing and pushes nothing', () => {const film: Film = { tracks: [{ clips: [filmClip('t1', 0, 2)] }, { clips: [filmClip('a', 0, 2), filmClip('b', 2, 2)] }] };const tracks = [track(0, [blockOf('t1', 0, 0, 0, 2000)], { role: 'mg' }),track(1, [blockOf('a', 1, 0, 0, 2000), blockOf('b', 1, 1, 2000, 4000)], { role: 'video' }),];const model = editModelOf(tracks);+ const paste = (from: TimelineBlock, atMs: number, lane: string) => spans(applyOps(structuredClone(film) as never,+ pasteEdit(clipboardItemsOf([from], tracks), tracks, model, atMs, lane, { magnet: true, sync: false, linkage: true }) as never) as unknown as Film);/* the title pasted at 1 s over itself: a new title track opens above for the copy */- const title = pasteEdit(clipboardItemsOf([tracks[0]!.blocks[0]!], tracks), tracks, model, 1000, 'doc-0', { magnet: true, sync: false, linkage: true })!;- assert.deepEqual(spans(applyOps(structuredClone(film) as never, title as never) as unknown as Film), [[['t1-2', 1, null]], [['t1', 0, null]], [['a', 0, null], ['b', 2, null]]]);+ assert.deepEqual(paste(tracks[0]!.blocks[0]!, 1000, 'doc-0'), [[['t1-2', 1, null]], [['t1', 0, null]], [['a', 0, null], ['b', 2, null]]]);/* at 3 s its own track is free: it goes there */- const free = pasteEdit(clipboardItemsOf([tracks[0]!.blocks[0]!], tracks), tracks, model, 3000, 'doc-0', { magnet: true, sync: false, linkage: true })!;- assert.deepEqual(spans(applyOps(structuredClone(film) as never, free as never) as unknown as Film)[0], [['t1', 0, null], ['t1-2', 3, null]]);- /* a shot pasted at 2 s on the main track goes in between and pushes b on; the title over a stays */- const shot = pasteEdit(clipboardItemsOf([tracks[1]!.blocks[0]!], tracks), tracks, model, 2000, 'doc-1', { magnet: true, sync: false, linkage: true })!;- assert.deepEqual(spans(applyOps(structuredClone(film) as never, shot as never) as unknown as Film), [[['t1', 0, null]], [['a', 0, null], ['a-2', 2, null], ['b', 4, null]]]);+ assert.deepEqual(paste(tracks[0]!.blocks[0]!, 3000, 'doc-0')[0], [['t1', 0, null], ['t1-2', 3, null]]);+ /* a shot pasted at 2 s, where the main track is taken: the main track is left alone, the copy goes to the free+ picture track above it */+ assert.deepEqual(paste(tracks[1]!.blocks[0]!, 2000, 'doc-1'), [[['t1', 0, null], ['a-2', 2, null]], [['a', 0, null], ['b', 2, null]]]);+ /* at 1 s nothing above is free either: a new track right above the main track */+ assert.deepEqual(paste(tracks[1]!.blocks[0]!, 1000, 'doc-1'), [[['t1', 0, null]], [['a-2', 1, null]], [['a', 0, null], ['b', 2, null]]]);+ /* past the main track's end: onto it, closed up against its last clip */+ assert.deepEqual(paste(tracks[1]!.blocks[0]!, 6000, 'doc-1')[1], [['a', 0, null], ['b', 2, null], ['a-2', 4, null]]);+});++test('⌥-drag copies, as CapCut: the clip stays and a copy lands where it is let go', () => {+ const film: Film = { tracks: [{ clips: [filmClip('t1', 0, 2)] }, { clips: [filmClip('a', 0, 2), filmClip('b', 2, 2)] }] };+ const tracks = [+ track(0, [blockOf('t1', 0, 0, 0, 2000)], { role: 'mg' }),+ track(1, [blockOf('a', 1, 0, 0, 2000), blockOf('b', 1, 1, 2000, 4000)], { role: 'video' }),+ ];+ const model = editModelOf(tracks);+ const run = (plan: { ops: unknown[] } | null) => spans(applyOps(structuredClone(film) as never, plan!.ops as never) as unknown as Film);+ const opts = { magnet: true, sync: false, linkage: true };+ /* b copied onto the first half of a on the main track: it goes in before a, what follows moves on */+ assert.deepEqual(run(planCopies(model, { ids: ['b'], deltaMs: -1500, pointerMs: 500, ...opts }))[1], [['b-2', 0, null], ['a', 2, null], ['b', 4, null]]);+ /* the title copied onto itself 1 s later: off the main track nothing is covered, a new track above takes it */+ assert.deepEqual(run(planCopies(model, { ids: ['t1'], deltaMs: 1000, pointerMs: 1500, ...opts })), [[['t1-2', 1, null]], [['t1', 0, null]], [['a', 0, null], ['b', 2, null]]]);+ /* without the magnet a copy covers what is under it */+ assert.deepEqual(run(planCopies(model, { ids: ['t1'], deltaMs: 1000, pointerMs: 1500, magnet: false, sync: false }))[0], [['t1', 0, null], ['t1-2', 1, null]]);});test('copies of linked clips pasted together are linked to each other, not to the originals', () => {diff --git a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.ts b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.tsindex 666595b..5b0df9a 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.ts@@ -12,7 +12,7 @@ import type { Op } from '../api.ts';import { FILM_DOC_FILE } from './film.ts';import { newTrackSide } from './timeline-drag.ts';-import { freshLink, freeTrackFor, mainTrackOf, planRoom, type EditMode, type EditModel, type Follow, type TrackDest } from './timeline-edit.ts';+import { freshLink, freeTrackFor, insertPointOn, mainTrackOf, planRoom, TOUCH_MS, type EditMode, type EditModel, type EditPlan, type Follow, type TrackDest } from './timeline-edit.ts';import type { TimelineBlock, TimelineTrack } from './timeline-layout';export type TimelineClipboardItem = {@@ -246,9 +246,10 @@ export function copyLinks(clipIds: readonly string[], model: EditModel): Map<str* A paste as an edit in the timeline's mode: copied from one track, the copies go onto the track pointed at* (`forceLane`) if any; from several, each back onto its own. The group's earliest clip lands at `atMs`, the rest* keep their spacing. An insert makes room there (pushing what follows on, with sync lock on every unlocked track);- * an overwrite takes that time off the tracks. With the magnet given (as CapCut's): an insert on the main track, and- * off it a copy whose time is taken goes to a free track or a new one. The copies go in first, so a clip pasted over- * itself is copied whole before it is cut. Null when a track it goes onto is locked or gone.+ * an overwrite takes that time off the tracks. With the magnet given (as CapCut's): nothing is covered or pushed — a+ * copy whose time is taken goes to a free track or a new one, and onto the main track only past its end. The copies+ * go in first, so a clip pasted over itself is copied whole before it is cut. Null when a track it goes onto is locked+ * or gone.*/export function pasteEdit(clipboard: readonly TimelineClipboardItem[],@@ -269,7 +270,7 @@ export function pasteEdit(});if (spans.some((s) => s.track == null || s.locked)) return null;const links = copyLinks(clipboard.map((item) => item.clipId), model);- const insertOf = (s: (typeof spans)[number], track: TrackDest): Op => ({+ const insertOf = (s: Pick<(typeof spans)[number], 'item' | 'startMs'>, track: TrackDest): Op => ({op: 'insert',from: s.item.clipId,at: s.startMs / 1000,@@ -281,33 +282,81 @@ export function pasteEdit(const room = planRoom(model, spans.map((s) => ({ track: s.track!, startMs: s.startMs, endMs: s.endMs })), { mode, sync: opts.sync, linkage: opts.linkage });return [...spans.map((s) => insertOf(s, s.track!)), ...room.ops];}- /* the magnet, as CapCut's: onto the main track an insert (what follows moves on); off it nothing is covered — a- copy whose time is taken goes to a free track, else a new one */+ /* the magnet, as CapCut's: a paste covers nothing and pushes nothing — a copy whose time is taken goes to a free+ track, else a new one (above the main track for a copy from it). On the main track only past its end, closed up */const main = mainTrackOf(model);- const onMain = spans.filter((s) => s.track === main);- const room = planRoom(model, onMain.map((s) => ({ track: s.track!, startMs: s.startMs, endMs: s.endMs })), { mode: 'insert', sync: opts.sync, linkage: opts.linkage });- /* the tracks as the insert left them */- const after: EditModel = model.map((t) => ({- ...t,- clips: t.clips.flatMap((c) => {- if (!room.placed.has(c.id)) return [c];- const at = room.placed.get(c.id);- return at && at.track === t.index ? [{ ...c, startMs: at.startMs, endMs: at.endMs }] : [];- }),- }));+ const mainEnd = Math.max(0, ...(model.find((t) => t.index === main)?.clips ?? []).map((c) => c.endMs));const taken: { track: number; startMs: number; endMs: number }[] = [];const placed = spans.map((s) => {- if (s.track === main) return { s, track: s.track as TrackDest };- const track = freeTrackFor(after, s.track!, s, taken);+ if (s.track === main && s.startMs >= mainEnd - TOUCH_MS) {+ const at = { ...s, startMs: mainEnd, endMs: mainEnd + s.item.durMs };+ return { s: at, track: main as TrackDest };+ }+ const track = freeTrackFor(model, s.track!, s, taken);if (typeof track === 'number') taken.push({ track, startMs: s.startMs, endMs: s.endMs });return { s, track };});/* new tracks last, the lowest place first, so the places of the others hold while they open */const opened = placed.filter((p) => typeof p.track === 'object')- .sort((a, b) => (b.track as { insert: number }).insert - (a.track as { insert: number }).insert);+ .sort((x, y) => (y.track as { insert: number }).insert - (x.track as { insert: number }).insert);return [...placed.filter((p) => typeof p.track === 'number').map((p) => insertOf(p.s, p.track)),- ...room.ops,...opened.map((p) => insertOf(p.s, p.track)),];}++/**+ * Copies of clips put down where a drag lets them go (⌥-drag, as CapCut's): the clips stay, a copy of each lands+ * `deltaMs` later (earlier when negative) on its track or the one in `to`. As a paste does with the magnet: onto the+ * main track an insert at the insert point under the hand (what follows moves on, with linkage what rides on it);+ * off it nothing is covered, a copy whose time is taken going to a free track or a new one. Without the magnet a copy+ * covers what is under it. Copies of clips linked together are linked to each other. Null when a track it goes onto+ * is locked.+ */+export function planCopies(+ model: EditModel,+ spec: Follow & { ids: readonly string[]; deltaMs: number; pointerMs: number; to?: ReadonlyMap<string, TrackDest>; magnet: boolean },+): EditPlan | null {+ const clips = model.flatMap((t) => t.clips.map((c) => ({ c, track: t.index })));+ const picked = spec.ids.flatMap((id) => clips.filter((x) => x.c.id === id));+ if (!picked.length) return null;+ const main = mainTrackOf(model);+ const lead = picked[0]!;+ const offset = Math.max(spec.deltaMs, -Math.min(...picked.map((x) => x.c.startMs)));+ /* the group keeps its shape; on the main track it goes in at the insert point under the hand */+ const leadDest = spec.to?.get(lead.c.id) ?? lead.track;+ let shift = offset;+ if (spec.magnet && leadDest === main) shift = insertPointOn(model, main, spec.pointerMs, lead.c.startMs + offset) - lead.c.startMs;+ const spans = picked.map(({ c, track }) => {+ const startMs = Math.max(0, c.startMs + shift);+ return { id: c.id, startMs, endMs: startMs + c.endMs - c.startMs, dest: spec.to?.get(c.id) ?? (track as TrackDest) };+ });+ if (spans.some((s) => typeof s.dest === 'number' && model.find((t) => t.index === s.dest)?.locked)) return null;+ const onMain = spec.magnet ? spans.filter((s) => s.dest === main) : [];+ const covering = spec.magnet ? [] : spans.filter((s) => typeof s.dest === 'number');+ const room = onMain.length+ ? planRoom(model, onMain.map((s) => ({ track: s.dest as number, startMs: s.startMs, endMs: s.endMs })), { mode: 'insert', sync: spec.sync, linkage: spec.linkage })+ : covering.length+ ? planRoom(model, covering.map((s) => ({ track: s.dest as number, startMs: s.startMs, endMs: s.endMs })), { mode: 'overwrite', sync: spec.sync, linkage: spec.linkage })+ : { ops: [], placed: new Map(), shortMs: 0 };+ const taken: { track: number; startMs: number; endMs: number }[] = [];+ const placed = spans.map((s) => {+ if (typeof s.dest !== 'number' || !spec.magnet || s.dest === main) return { s, track: s.dest };+ const track = freeTrackFor(model, s.dest, s, taken);+ if (typeof track === 'number') taken.push({ track, startMs: s.startMs, endMs: s.endMs });+ return { s, track };+ });+ const links = copyLinks(spec.ids, model);+ const insertOf = ({ s, track }: (typeof placed)[number]): Op => ({+ op: 'insert', from: s.id, at: Math.round(s.startMs) / 1000, track,+ ...(links.has(s.id) ? { link: links.get(s.id)! } : {}),+ });+ /* the copies on tracks there are first; new tracks last, the lowest place first, so the places hold */+ const opened = placed.filter((p) => typeof p.track === 'object')+ .sort((x, y) => (y.track as { insert: number }).insert - (x.track as { insert: number }).insert);+ return {+ ops: [...placed.filter((p) => typeof p.track === 'number').map(insertOf), ...room.ops, ...opened.map(insertOf)],+ placed: room.placed,+ shortMs: room.shortMs,+ };+}diff --git a/packages/openfilm/studio/ui/src/lib/timeline-edit.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-edit.test.tsindex 7ed257c..50fb95d 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-edit.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-edit.test.ts@@ -6,6 +6,7 @@ import {editModelOf,freshLink,gapAt,+ gapsOf,insertPointOn,hostOf,linkedIds,@@ -13,6 +14,7 @@ import {mainTrackOf,planCloseGap,planCloseMainGaps,+ planCloseTrackGaps,planEdges,planLink,planMove,@@ -24,7 +26,6 @@ import {planUnlink,ridesOn,rollMoves,- slideMoves,soundTrackFor,sourceLeftMs,type EditClip,@@ -214,12 +215,19 @@ test('with linkage a ripple delete on the main track carries the titles and soun);const plan = planRemove(m, ['b'], { ripple: true, ...LINK });assert.equal(plan.shortMs, 0);- /* t2 rode on b, which went: it stays where it was, now over c. t3 moves back with c onto it, so it goes to a new- title track above; the sound effect moves back; the bed spans the cut and stays */- assert.deepEqual(after(m, plan), [[['t3', 2.5, 3.5]], [['t2', 2.5, 3.5]], [['a', 0, 2], ['c', 2, 4]], [['bed', 0, 9]], [['sfx', 2, 3]]]);+ /* t2 rode on b, which went: it goes with it. t3 moves back with c; the sound effect moves back; the bed spans the+ cut and stays */+ assert.deepEqual(after(m, plan), [[['t3', 2.5, 3.5]], [['a', 0, 2], ['c', 2, 4]], [['bed', 0, 9]], [['sfx', 2, 3]]]);assert.equal(planRemove(m, ['b'], { ripple: true, sync: true }).shortMs, 1000);});+test('with linkage what rides on a deleted main-track clip goes with it; a bed under several shots stays', () => {+ const m = film([['ta', 0.5, 1.5], ['tb', 2.5, 3.5]], [['a', 0, 2], ['b', 2, 5], ['c', 5, 7]], [['bed', 0, 7]]);+ assert.deepEqual(after(m, planRemove(m, ['b'], { ripple: 'main', ...LINK })), [[['ta', 0.5, 1.5]], [['a', 0, 2], ['c', 2, 4]], [['bed', 0, 7]]]);+ /* without linkage the title stays */+ assert.deepEqual(after(m, planRemove(m, ['b'], { ripple: 'main', sync: false }))[0], [['ta', 0.5, 1.5], ['tb', 2.5, 3.5]]);+});+test('linkage: a carried clip that runs into one that stayed goes to a free track above, else a new one', () => {/* t1 rides on a (stays), t2 on b (moves back 2 s, onto t1) */const m = film([['t1', 0.5, 1.8], ['t2', 2.5, 3.5]], [['a', 0, 1], ['x', 1, 2.5], ['b', 2.5, 5]]);@@ -233,8 +241,8 @@ test('linkage: a carried clip that runs into one that stayed goes to a free tractest('with the magnet a delete closes up the main track only; titles leave a gap', () => {const m = film([['t1', 0, 1], ['t2', 1, 2], ['t3', 2, 3]], [['a', 0, 2], ['b', 2, 4], ['c', 4, 6]]);- const plan = planRemove(m, ['b', 't2'], { ripple: 'main', ...LINK });- /* the title track keeps its gap where t2 was; c closes up and carries nothing (t3 rode on b, which went) */+ const plan = planRemove(m, ['b', 't2'], { ripple: 'main', sync: false });+ /* the title track keeps its gap where t2 was; c closes up (without linkage nothing else moves) */assert.deepEqual(after(m, plan), [[['t1', 0, 1], ['t3', 2, 3]], [['a', 0, 2], ['c', 2, 4]]]);});@@ -304,6 +312,21 @@ test('with the magnet a clip let go on another off the main track covers nothingassert.deepEqual(after(across, moved)[0], [['x', 1, 3]]);});+test('clips moved together to new tracks keep their rows: a new track per track they came from', () => {+ /* a title and a shot dragged above every track */+ const m = model({ role: 'mg', clips: [['t', 1, 3]] }, { role: 'video', clips: [['a', 0, 4], ['b', 4, 8]] });+ const up = planMove(m, { ids: ['t', 'b'], deltaMs: 0, pointerMs: 2000, to: new Map([['t', { insert: 0 }], ['b', { insert: 0 }]]), mode: 'overwrite', magnet: true, ...LINK })!;+ /* two new tracks on top, the title's above the shot's; b's place on the main track closes up */+ assert.deepEqual(after(m, up), [[['t', 1, 3]], [['b', 4, 8]], [['a', 0, 4]]]);+ /* two clips of one track: one new track for both */+ const two = model({ role: 'mg', clips: [['t1', 0, 1], ['t2', 2, 3]] }, { role: 'video', clips: [['a', 0, 4]] });+ const both = planMove(two, { ids: ['t1', 't2'], deltaMs: 0, pointerMs: 500, to: new Map([['t1', { insert: 0 }], ['t2', { insert: 0 }]]), mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(two, both), [[['t1', 0, 1], ['t2', 2, 3]], [['a', 0, 4]]]);+ /* and below every track */+ const down = planMove(m, { ids: ['t', 'b'], deltaMs: 0, pointerMs: 2000, to: new Map([['t', { insert: 2 }], ['b', { insert: 2 }]]), mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(m, down), [[['a', 0, 4]], [['t', 1, 3]], [['b', 4, 8]]]);+});+test('with linkage closing a gap on the main track always closes it whole', () => {const m = film([['t', 3, 4]], [['a', 0, 2], ['b', 3, 5]], [['bed', 0, 9]]);const gap = gapAt(m, 1, 2500)!;@@ -323,6 +346,13 @@ test('turning the magnet on closes up the main track, before its first clip too,assert.deepEqual(planCloseMainGaps(model({ role: 'video', locked: true, clips: [['a', 1, 2]] }), LINK).ops, [], 'locked');});+test('all the gaps on a track closed at once; on a title track only that track moves', () => {+ const m = film([['t1', 1, 2], ['t2', 4, 5]], [['a', 0, 3], ['b', 3, 6]]);+ assert.deepEqual(gapsOf(m, 0), [{ startMs: 0, endMs: 1000 }, { startMs: 2000, endMs: 4000 }]);+ assert.deepEqual(after(m, planCloseTrackGaps(m, 0, LINK)), [[['t1', 0, 1], ['t2', 1, 2]], [['a', 0, 3], ['b', 3, 6]]]);+ assert.deepEqual(planCloseTrackGaps(m, 1, LINK).ops, [], 'no gap on the main track');+});+test('with linkage a slower main-track clip pushes what comes after on every track', () => {const m = film([['tb', 3, 4]], [['a', 0, 2], ['b', 2, 5]], [['bed', 0, 9]]);const plan = planSpeed(m, ['a'], 0.5, { ripple: true, ...LINK });@@ -492,17 +522,6 @@ test('a slip changes what a clip shows, not where or how long, inside its sourceassert.deepEqual(planEdges(still, [{ id: 'p', kind: 'slip' }], 1000).ops, []);});-test('a slide moves a clip between its neighbors, which give and take the time', () => {- const m = model([['a', 0, 2, { sourceMs: 10_000 }], ['b', 2, 4], ['c', 4, 8, { inMs: 1000 }]]);- const plan = planEdges(m, slideMoves(m, ['b']), 500);- assert.deepEqual(after(m, plan), [[['a', 0, 2.5], ['b', 2.5, 4.5], ['c', 4.5, 8]]]);- /* left: as far as c has source before its in point */- assert.equal(planEdges(m, slideMoves(m, ['b']), -5000).deltaMs, -1000);- /* the sound linked to a neighbor keeps its picture's length */- const linked = model([['a', 0, 2, { link: 'a' }], ['b', 2, 4]], [['as', 0, 2, { link: 'a' }]]);- assert.deepEqual(after(linked, planEdges(linked, slideMoves(linked, ['b'], true), -500)), [[['a', 0, 1.5], ['b', 1.5, 3.5]], [['as', 0, 1.5]]]);-});-/* ── ripple trims ── */test('a ripple trim of the tail moves what follows, on every synced track', () => {@@ -626,7 +645,6 @@ test('no plan makes two clips on a track overlap', () => {planMove(m, { ids: ['c'], deltaMs: -5000, pointerMs: 1000, mode: 'insert', sync: true }),planMove(m, { ids: ['a'], deltaMs: 4000, pointerMs: 5000, to: new Map([['a', 1]]), mode: 'insert', sync: false }),planRippleTrim(m, ['b'], 'end', 3000, { sync: true }),- planEdges(m, slideMoves(m, ['b']), -2000),planEdges(m, rollMoves(m, 'a', 'b', true), 2000),planSpeed(m, ['d'], 0.25, { ripple: true, sync: true }),];diff --git a/packages/openfilm/studio/ui/src/lib/timeline-edit.ts b/packages/openfilm/studio/ui/src/lib/timeline-edit.tsindex ef9f67a..000017f 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-edit.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-edit.ts@@ -1,5 +1,5 @@/**- * Edits that change more than one clip: insert and overwrite, ripple, roll, slip and slide, closing gaps, speed, and+ * Edits that change more than one clip: insert and overwrite, ripple, roll, slip, closing gaps, speed, and* linked clips. Each works on a plain model of the tracks (film ms, and each clip's own source ms) and comes back as* the operations film.html takes (studio/server/ops.mjs), in one batch: one write, one undo step.*@@ -46,8 +46,10 @@ export interface EditClip {}export interface EditTrack {- /** Its place in film.html. */+ /** Its place in film.html; below 0 for a track an edit opens (see openTrack). */index: number;+ /** A track an edit opens: what it was opened for. */+ openKey?: string;locked?: boolean;/** What the timeline calls it by the clips on it; a sound taken off a video goes to an `audio` one. */role?: 'mg' | 'video' | 'audio';@@ -167,6 +169,19 @@ export interface Draft {anchored?: Set<string>;}+/**+ * A track this edit opens, at film.html place `insert`, for clips put there: one per `key` (a new track per track the+ * clips came from, say), with an index of its own below 0 so new tracks never share one by accident.+ */+function openTrack(d: Draft, insert: number, key: string, role?: EditTrack['role']): EditTrack {+ const name = `${insert}:${key}`;+ const found = d.tracks.find((t) => t.index < 0 && t.openKey === name);+ if (found) return found;+ const track: EditTrack = { index: Math.min(0, ...d.tracks.map((t) => t.index)) - 1, clips: [], openKey: name, ...(role ? { role } : {}) };+ d.tracks.push(track);+ return track;+}+function draftOf(model: EditModel): Draft {const before = new Map<string, { clip: EditClip; track: number }>();const tracks = model.map((t) => ({ ...t, clips: t.clips.map((c) => ({ ...c })) }));@@ -472,11 +487,10 @@ function settle(d: Draft): void {}const insert = newTrackBeside(from);d.opened.set(c.id, insert);- let opened = d.tracks.find((t) => t.index === -1 - insert);- if (!opened) {- opened = { index: -1 - insert, clips: [], ...(from.role ? { role: from.role } : {}) };- d.tracks.push(opened);- }+ /* clips settled beside one track share a new one while they fit on it */+ let n = 0;+ let opened = openTrack(d, insert, `settle-${from.index}-${n}`, from.role);+ while (opened.clips.some((x) => overlap(x, c))) opened = openTrack(d, insert, `settle-${from.index}-${++n}`, from.role);opened.clips.push(c);};for (const t of [...d.tracks]) {@@ -550,6 +564,23 @@ function planOf(d: Draft): EditPlan {const opened = d.opened.get(id);return opened != null ? { insert: opened } : track;};+ /*+ * A new track takes one clip as it opens (film.html opens a track per clip moved to `{ insert }`); the others on it+ * move onto it in a second step, by the place it has once all are open: the new tracks open in order of place, each+ * before the track that was there, so the i-th (in that order) is at `insert + i`.+ */+ const fresh = d.tracks.filter((t) => t.index < 0 && t.clips.length)+ .map((t) => ({ t, insert: d.opened.get(t.clips[0]!.id)! }))+ .sort((a, b) => a.insert - b.insert);+ const opener = new Set<string>();+ const joins = new Map<string, number>();+ fresh.forEach(({ t, insert }, i) => {+ const [first, ...rest] = [...t.clips].sort((a, b) => a.startMs - b.startMs);+ opener.add(first!.id);+ for (const c of rest) joins.set(c.id, insert + i);+ });+ const openEdits: { clip: string; prop: string; value: PropValue }[] = [];+ const joinEdits: { clip: string; prop: string; value: PropValue }[] = [];for (const [id, was] of d.before) {const cur = now.get(id);if (!cur) {@@ -570,10 +601,16 @@ function planOf(d: Draft): EditPlan {const moved = typeof dest === 'object' || dest !== was.track;if (!Object.keys(fields).length && !moved) continue;for (const [prop, value] of Object.entries(fields)) edits.push({ clip: id, prop, value });- if (moved) edits.push({ clip: id, prop: 'track', value: dest });+ if (joins.has(id)) joinEdits.push({ clip: id, prop: 'track', value: joins.get(id)! });+ else if (opener.has(id)) openEdits.push({ clip: id, prop: 'track', value: dest });+ else if (moved) edits.push({ clip: id, prop: 'track', value: dest });placed.set(id, { startMs: cur.clip.startMs, endMs: cur.clip.endMs, track: dest });}- if (edits.length) ops.push({ op: 'props', edits });+ /* the openers in the order the new tracks open (see above) */+ const openOrder = (clip: string) => fresh.findIndex((f) => f.t.clips.some((c) => c.id === clip));+ openEdits.sort((a, b) => openOrder(a.clip) - openOrder(b.clip));+ if (edits.length || openEdits.length) ops.push({ op: 'props', edits: [...edits, ...openEdits] });+ if (joinEdits.length) ops.push({ op: 'props', edits: joinEdits });ops.push(...removes);return { ops, placed, shortMs: d.shortMs };}@@ -666,37 +703,54 @@ export function planCloseGap(return { ...planOf(alone), alone: true };}-/**- * The main track closed up, as CapCut does when its magnet is turned on: every gap on it, before its first clip too,- * closes, carrying what follows as a ripple does (sync lock, linkage). Nothing on a locked main track.- */-export function planCloseMainGaps(model: EditModel, opts: Follow): EditPlan {- const main = mainTrackOf(model);- const track = model.find((t) => t.index === main);- if (main == null || !track || track.locked) return emptyPlan();+/** The gaps on a track: before its first clip and between clips (not after the last). */+export function gapsOf(model: EditModel, track: number): { startMs: number; endMs: number }[] {const spans: { startMs: number; endMs: number }[] = [];let end = 0;- for (const c of [...track.clips].sort((a, b) => a.startMs - b.startMs)) {+ for (const c of [...(model.find((t) => t.index === track)?.clips ?? [])].sort((x, y) => x.startMs - y.startMs)) {if (c.startMs - end > TOUCH_MS) spans.push({ startMs: end, endMs: c.startMs });end = Math.max(end, c.endMs);}- if (!spans.length) return emptyPlan();+ return spans;+}++/**+ * Every gap on a track closed (CapCut's "批量闭合空隙"), carrying what follows as a ripple does (sync lock, linkage on+ * the main track). Nothing on a locked track.+ */+export function planCloseTrackGaps(model: EditModel, track: number, opts: Follow): EditPlan {+ const spans = gapsOf(model, track);+ if (!spans.length || model.find((t) => t.index === track)?.locked) return emptyPlan();const d = draftOf(model);- closeSpans(d, new Map([[main, spans]]), opts);+ closeSpans(d, new Map([[track, spans]]), opts);return planOf(d);}+/** The main track closed up, as CapCut does when its magnet is turned on (planCloseTrackGaps on the main track). */+export function planCloseMainGaps(model: EditModel, opts: Follow): EditPlan {+ const main = mainTrackOf(model);+ return main == null ? emptyPlan() : planCloseTrackGaps(model, main, opts);+}+/* ── delete ── *//*** Delete clips. With `ripple` the time they took closes after them (each track its own, or with sync lock all the* deleted time on every unlocked track, or with linkage the main track's, carrying the other tracks); `'main'` closes- * only the main track's (the magnet), the others leave a gap; without, they all leave a gap. Clips on locked tracks- * stay.+ * only the main track's (the magnet), the others leave a gap; without, they all leave a gap. With linkage the clips+ * riding on a deleted main-track clip go too. Clips on locked tracks stay.*/export function planRemove(model: EditModel, ids: readonly string[], opts: Follow & { ripple: boolean | 'main' }): EditPlan {const d = draftOf(model);const main = mainTrackOf(model);+ /* with linkage what rides on a main-track clip goes with it, as CapCut's ("随着主轨移动、删除") */+ const mainTrack = model.find((t) => t.index === main);+ if (opts.linkage && !opts.sync && mainTrack && !mainTrack.locked) {+ const gone = new Set(mainTrack.clips.filter((c) => ids.includes(c.id)).map((c) => c.id));+ const riders = model.filter((t) => t !== mainTrack && !t.locked).flatMap((t) => t.clips)+ .filter((c) => gone.size && ridesOn(mainTrack, c) && gone.has(hostOf(mainTrack, c)?.id ?? ''));+ if (riders.length) ids = [...ids, ...riders.map((c) => c.id)];+ }const spans = new Map<number, { startMs: number; endMs: number }[]>();for (const t of d.tracks) {if (t.locked) continue;@@ -870,13 +924,9 @@ export function planMove(model: EditModel, spec: MoveSpec): (EditPlan & { landMsc.startMs = startMs;const dest = destOf(id);if (typeof dest === 'object') {+ /* a new track for each track the clips came from: a group keeps its rows */d.opened.set(id, dest.insert);- let track = d.tracks.find((t) => t.index === -1 - dest.insert);- if (!track) {- track = { index: -1 - dest.insert, clips: [] };- d.tracks.push(track);- }- track.clips.push(c);+ openTrack(d, dest.insert, `from-${d.before.get(id)!.track}`).clips.push(c);continue;}const track = trackAt(d, dest)!;@@ -944,8 +994,8 @@ function applyEdge(c: EditClip, kind: EdgeKind, ms: number): void {/*** Edges moved together by one amount, kept to what every one of them allows: a trim (one edge, and the same edge of- * linked clips), a roll (the end of one clip and the start of the next), a slip (the content of clips), a slide (a- * clip shifted, the end of the one before and the start of the one after). Moves on locked tracks are left out.+ * linked clips), a roll (the end of one clip and the start of the next), a slip (the content of clips, the+ * inspector's source bar), a nudge (clips shifted into free time). Moves on locked tracks are left out.*/export function planEdges(model: EditModel, moves: readonly EdgeMove[], deltaMs: number): EditPlan & { deltaMs: number } {const d = draftOf(model);@@ -1016,38 +1066,6 @@ export function planRippleTrimTo(model: EditModel, ids: readonly string[], edge:return plan.ops.length ? plan : null;}-/** The clip's neighbors that touch it on its track: the one ending where it starts, the one starting where it ends. */-export function touchingOf(model: EditModel, id: string): { prev?: string; next?: string } {- const track = model.find((t) => t.clips.some((c) => c.id === id));- const c = track?.clips.find((x) => x.id === id);- if (!track || !c) return {};- const prev = track.clips.find((x) => x !== c && Math.abs(x.endMs - c.startMs) <= TOUCH_MS);- const next = track.clips.find((x) => x !== c && Math.abs(x.startMs - c.endMs) <= TOUCH_MS);- return { ...(prev ? { prev: prev.id } : {}), ...(next ? { next: next.id } : {}) };-}--/**- * A slide: these clips move along their tracks, the clips touching them give and take the time (with `linked`, so do- * the clips linked to those, keeping a picture and its sound the same length).- */-export function slideMoves(model: EditModel, ids: readonly string[], linked = false): EdgeMove[] {- const moves = ids.flatMap((id) => {- const { prev, next } = touchingOf(model, id);- return [- { id, kind: 'shift' as const },- ...(prev && !ids.includes(prev) ? [{ id: prev, kind: 'end' as const }] : []),- ...(next && !ids.includes(next) ? [{ id: next, kind: 'start' as const }] : []),- ];- });- if (!linked) return moves;- const out = [...moves];- for (const m of moves) {- if (m.kind === 'shift') continue;- for (const id of linkedIds(model, [m.id])) if (!out.some((x) => x.id === id)) out.push({ id, kind: m.kind });- }- return out;-}-/*** A roll of the cut after `leftId`: its end and the next clip's start move together. Linked clips with a cut at the* same place roll too; a linked clip whose edge is elsewhere has it trimmed by the same amount.diff --git a/packages/openfilm/studio/ui/src/lib/timeline-keys.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-keys.test.tsindex 6199413..e3524b4 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-keys.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-keys.test.ts@@ -26,7 +26,7 @@ test('the keys, as Premiere and CapCut have them', () => {assert.equal(mac('ArrowUp'), 'prev-cut');assert.equal(mac('ArrowDown'), 'next-cut');assert.equal(mac('ArrowLeft'), 'frame-back');- assert.equal(mac('ArrowRight', { shiftKey: true }), 'second-forward');+ assert.equal(mac('ArrowRight', { shiftKey: true }), 'jump-forward');assert.equal(mac('ArrowLeft', { altKey: true }), 'nudge-back');assert.equal(mac('ArrowRight', { altKey: true }), 'nudge-forward');assert.equal(mac('Z', { shiftKey: true }), 'zoom-fit');@@ -46,7 +46,22 @@ test('M adds a marker, ⇧M and ⌥M go to the next and the one before (⌥M typassert.equal(keyCommandOf({ ...press('µ', { altKey: true }), code: 'KeyM' }, true), 'prev-marker');assert.equal(win('m', { altKey: true }), 'prev-marker');assert.equal(mac('m', { metaKey: true }), null);- assert.equal(mac('m', { altKey: true, shiftKey: true }), null);+ assert.equal(mac('m', { altKey: true, shiftKey: true }), 'prev-marker', '⌥⇧M too, as CapCut\'s');+});++test('CapCut\'s keys (its Final Cut Pro X set on a Mac): P, ~, ⇧X, ⌥X, ⌘R, ⇧⌃S, ⌘⇧C, ⌘⇧V', () => {+ assert.equal(mac('p'), 'toggle-magnet');+ assert.equal(keyCommandOf({ ...press('`'), code: 'Backquote' }, true), 'toggle-linkage');+ assert.equal(keyCommandOf({ ...press('~', { shiftKey: true }), code: 'Backquote' }, true), 'toggle-linkage');+ assert.equal(mac('X', { shiftKey: true }), 'range-clip');+ assert.equal(keyCommandOf({ ...press('≈', { altKey: true }), code: 'KeyX' }, true), 'clear-range');+ assert.equal(mac('r', { metaKey: true }), 'speed');+ assert.equal(mac('S', { ctrlKey: true, shiftKey: true }), 'detach-audio');+ assert.equal(win('S', { ctrlKey: true, shiftKey: true }), 'detach-audio');+ assert.equal(mac('C', { metaKey: true, shiftKey: true }), 'copy-attrs');+ assert.equal(mac('V', { metaKey: true, shiftKey: true }), 'paste-attrs');+ assert.equal(keyCommandOf({ ...press('['), code: 'BracketLeft' }, true), 'select-left');+ assert.equal(keyCommandOf({ ...press(']'), code: 'BracketRight' }, true), 'select-right');});test('keys that are not the editor\'s stay the browser\'s, and Ctrl is the modifier off a Mac', () => {diff --git a/packages/openfilm/studio/ui/src/lib/timeline-keys.ts b/packages/openfilm/studio/ui/src/lib/timeline-keys.tsindex 7beb267..43d12b3 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-keys.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-keys.ts@@ -1,6 +1,7 @@/**- * The editor's keys, as Premiere and CapCut have them: which key does what (`keyCommandOf`), the list Settings shows- * (`SHORTCUTS`), J / K / L shuttle (`shuttleRate`) and looping a range (`loopBack`, `playStart`).+ * The editor's keys, as CapCut (剪映) has them on a Mac — its keys there are its Final Cut Pro X set — with Premiere's+ * where CapCut has none: which key does what (`keyCommandOf`), the list Settings shows (`SHORTCUTS`), J / K / L shuttle+ * (`shuttleRate`) and looping a range (`loopBack`, `playStart`).** Plain letters are read by the letter they type, so they follow the keyboard's layout; on a layout without Latin* letters (Korean, Russian…) by where the key is on a US keyboard.@@ -12,10 +13,11 @@ export type KeyCommand =| 'loop' | 'play-range'| 'split' | 'split-all' | 'cut' | 'duplicate'| 'prev-cut' | 'next-cut'- | 'frame-back' | 'frame-forward' | 'second-back' | 'second-forward'+ | 'frame-back' | 'frame-forward' | 'jump-back' | 'jump-forward'| 'nudge-back' | 'nudge-forward'| 'start' | 'end'- | 'zoom-fit' | 'toggle-snap' | 'toggle-magnet'+ | 'zoom-fit' | 'toggle-snap' | 'toggle-magnet' | 'toggle-linkage'+ | 'range-clip' | 'speed' | 'detach-audio' | 'copy-attrs' | 'paste-attrs' | 'select-left' | 'select-right'| 'ripple-start' | 'ripple-end'| 'insert-source' | 'overwrite-source'| 'add-marker' | 'next-marker' | 'prev-marker';@@ -37,27 +39,36 @@ export function letterOf(e: Pick<KeyPress, 'key' | 'code'>): string {return code ? code.toLowerCase() : key;}+/** How many frames ⇧← / ⇧→ move the playhead (CapCut's "大幅移动"). */+export const JUMP_FRAMES = 10;+/**- * The command a key press is, or null. `mac`: ⌘ is the modifier there (Ctrl elsewhere). Arrows: ← / → a frame (⇧ a- * second), ⌥ ← / → move the selected clips a frame, ↑ / ↓ the previous / next cut.+ * The command a key press is, or null. `mac`: ⌘ is the modifier there (Ctrl elsewhere). Arrows: ← / → a frame (⇧ ten+ * frames), ⌥ ← / → move the selected clips a frame, ↑ / ↓ the previous / next cut.*/export function keyCommandOf(e: KeyPress, mac: boolean): KeyCommand | null {const mod = mac ? e.metaKey : e.ctrlKey;+ const k = letterOf(e);+ /* ⇧⌃S detaches a video's sound, as CapCut's (on a Mac Ctrl itself, elsewhere Ctrl the modifier) */+ if (k === 's' && e.shiftKey && e.ctrlKey && !e.metaKey && !e.altKey) return 'detach-audio';/* the other platform's modifier (Ctrl on a Mac) is no shortcut here */const other = mac ? e.ctrlKey : e.metaKey;if (other) return null;- const k = letterOf(e);if (mod) {if (e.altKey) return null;if (k === 'b') return e.shiftKey ? 'split-all' : 'split';+ /* ⌘⇧C / ⌘⇧V copy a clip's look, place and sound onto others (CapCut's 复制属性 / 粘贴属性) */+ if (k === 'c' && e.shiftKey) return 'copy-attrs';+ if (k === 'v' && e.shiftKey) return 'paste-attrs';+ if (k === 'r' && !e.shiftKey) return 'speed';if (k === 'k' && !e.shiftKey) return 'split-all';if (k === 'x' && !e.shiftKey) return 'cut';if (k === 'd' && !e.shiftKey) return 'duplicate';return null;}switch (e.key) {- case 'ArrowLeft': return e.altKey ? (e.shiftKey ? null : 'nudge-back') : e.shiftKey ? 'second-back' : 'frame-back';- case 'ArrowRight': return e.altKey ? (e.shiftKey ? null : 'nudge-forward') : e.shiftKey ? 'second-forward' : 'frame-forward';+ case 'ArrowLeft': return e.altKey ? (e.shiftKey ? null : 'nudge-back') : e.shiftKey ? 'jump-back' : 'frame-back';+ case 'ArrowRight': return e.altKey ? (e.shiftKey ? null : 'nudge-forward') : e.shiftKey ? 'jump-forward' : 'frame-forward';case 'ArrowUp': return e.altKey || e.shiftKey ? null : 'prev-cut';case 'ArrowDown': return e.altKey || e.shiftKey ? null : 'next-cut';case 'Home': return e.altKey ? null : 'start';@@ -67,8 +78,13 @@ export function keyCommandOf(e: KeyPress, mac: boolean): KeyCommand | null {case '.': return e.altKey || e.shiftKey ? null : 'overwrite-source';default: break;}- /* ⌥M: the marker before (on a Mac ⌥M types µ: read by where the key is) */- if (e.altKey) return !e.shiftKey && k === 'm' ? 'prev-marker' : null;+ /* [ / ]: every clip before / after the playhead selected (CapCut's 向左全选 / 向右全选), read by where the key is */+ if (!e.shiftKey && !e.altKey && (e.code === 'BracketLeft' || e.key === '[')) return 'select-left';+ if (!e.shiftKey && !e.altKey && (e.code === 'BracketRight' || e.key === ']')) return 'select-right';+ /* ~ (the key left of 1, with ⇧ or without): linkage on / off, as CapCut's */+ if (e.code === 'Backquote' || e.key === '`' || e.key === '~') return e.altKey ? null : 'toggle-linkage';+ /* ⌥M / ⌥⇧M: the marker before; ⌥X: the range cleared (on a Mac ⌥ types another letter: read by where the key is) */+ if (e.altKey) return k === 'm' ? 'prev-marker' : k === 'x' && !e.shiftKey ? 'clear-range' : null;if (e.shiftKey) {switch (k) {case 'i': return 'go-in';@@ -77,6 +93,8 @@ export function keyCommandOf(e: KeyPress, mac: boolean): KeyCommand | null {case 'z': return 'zoom-fit';case 'n': return 'toggle-magnet';case 'm': return 'next-marker';+ /* ⇧X: the range is the selected clips' (CapCut's 以片段选定区域) */+ case 'x': return 'range-clip';default: return null;}}@@ -88,6 +106,7 @@ export function keyCommandOf(e: KeyPress, mac: boolean): KeyCommand | null {case 'o': return 'mark-out';case 'x': return 'clear-range';case 'n': return 'toggle-snap';+ case 'p': return 'toggle-magnet';case 'q': return 'ripple-start';case 'w': return 'ripple-end';case 'm': return 'add-marker';@@ -97,9 +116,10 @@ export function keyCommandOf(e: KeyPress, mac: boolean): KeyCommand | null {/*** Settings' list of keys, in groups: each row's words (a key of settings.shortcuts) and its keys, as `mod` (⌘ / Ctrl),- * `shift` (⇧), `alt` (⌥) and the key. Kept here beside keyCommandOf, so the list says what the keys do.+ * `ctrl` (⌃, Ctrl itself), `shift` (⇧), `alt` (⌥) and the key. Kept here beside keyCommandOf, so the list says what the+ * keys do.*/-export type ShortcutKey = { key: string; mod?: boolean; shift?: boolean; alt?: boolean };+export type ShortcutKey = { key: string; mod?: boolean; ctrl?: boolean; shift?: boolean; alt?: boolean };export type ShortcutRow = { label: string; keys: ShortcutKey[] };const k = (key: string, mods: Omit<ShortcutKey, 'key'> = {}): ShortcutKey => ({ key, ...mods });@@ -112,7 +132,7 @@ export const SHORTCUTS: { group: 'groupPlayback' | 'groupMarks' | 'groupEdit' |{ label: 'shuttle', keys: [k('J'), k('K'), k('L')] },{ label: 'shuttleFrame', keys: [k('K+J'), k('K+L')] },{ label: 'frameStep', keys: [k('←'), k('→')] },- { label: 'secondStep', keys: [k('←', { shift: true }), k('→', { shift: true })] },+ { label: 'jumpStep', keys: [k('←', { shift: true }), k('→', { shift: true })] },{ label: 'cutStep', keys: [k('↑'), k('↓')] },{ label: 'seekEnds', keys: [k('Home'), k('End')] },],@@ -122,7 +142,8 @@ export const SHORTCUTS: { group: 'groupPlayback' | 'groupMarks' | 'groupEdit' |rows: [{ label: 'markIn', keys: [k('I')] },{ label: 'markOut', keys: [k('O')] },- { label: 'clearMarks', keys: [k('X')] },+ { label: 'clearMarks', keys: [k('X'), k('X', { alt: true })] },+ { label: 'rangeClip', keys: [k('X', { shift: true })] },{ label: 'goInOut', keys: [k('I', { shift: true }), k('O', { shift: true })] },{ label: 'playRange', keys: [k('Space', { shift: true })] },{ label: 'loop', keys: [k('L', { shift: true })] },@@ -130,7 +151,7 @@ export const SHORTCUTS: { group: 'groupPlayback' | 'groupMarks' | 'groupEdit' |{ label: 'overwriteSource', keys: [k('.')] },{ label: 'addMedia', keys: [k('Enter')] },{ label: 'addMarker', keys: [k('M')] },- { label: 'markerStep', keys: [k('M', { shift: true }), k('M', { alt: true })] },+ { label: 'markerStep', keys: [k('M', { shift: true }), k('M', { alt: true, shift: true })] },],},{@@ -146,18 +167,24 @@ export const SHORTCUTS: { group: 'groupPlayback' | 'groupMarks' | 'groupEdit' |{ label: 'cut', keys: [k('X', { mod: true })] },{ label: 'paste', keys: [k('V', { mod: true })] },{ label: 'duplicate', keys: [k('D', { mod: true })] },+ { label: 'copyAttrs', keys: [k('C', { mod: true, shift: true })] },+ { label: 'pasteAttrs', keys: [k('V', { mod: true, shift: true })] },+ { label: 'speedPanel', keys: [k('R', { mod: true })] },+ { label: 'detachAudio', keys: [k('S', { ctrl: true, shift: true })] },{ label: 'remove', keys: [k('⌫'), k('Delete')] },{ label: 'rippleDelete', keys: [k('⌫', { shift: true }), k('Delete', { shift: true })] },{ label: 'nudgeClip', keys: [k('←', { alt: true }), k('→', { alt: true })] },{ label: 'selectAll', keys: [k('A', { mod: true })] },+ { label: 'selectSide', keys: [k('['), k(']')] },{ label: 'deselect', keys: [k('Esc')] },{ label: 'selectMode', keys: [k('A'), k('V')] },{ label: 'splitMode', keys: [k('B')] },- { label: 'toggleMagnet', keys: [k('N', { shift: true })] },+ { label: 'splitModeAll', keys: [k('', { shift: true })] },+ { label: 'toggleMagnet', keys: [k('P'), k('N', { shift: true })] },{ label: 'toggleSnap', keys: [k('N')] },+ { label: 'toggleLinkage', keys: [k('~')] },{ label: 'editModeSwap', keys: [k('', { alt: true })] },- { label: 'slip', keys: [k('', { alt: true })] },- { label: 'slide', keys: [k('', { alt: true, shift: true })] },+ { label: 'copyDrag', keys: [k('', { alt: true })] },],},{diff --git a/packages/openfilm/studio/ui/src/lib/timeline-nav.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-nav.test.tsindex 138535c..ee22f27 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-nav.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-nav.test.ts@@ -2,7 +2,7 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import { applyOps } from '../../../server/ops.mjs';import type { Op } from '../api.ts';-import { cutPoints, namedTrack, nextCut, planNudge, splitAllTargets, splitTargets, trackNamesOf } from './timeline-nav.ts';+import { cutPoints, namedTrack, nextCut, planNudge, sideTargets, splitAllTargets, splitTargets, trackNamesOf } from './timeline-nav.ts';import type { EditTrack } from './timeline-edit.ts';import type { TimelineBlock, TimelineTrack } from './timeline-layout';@@ -50,6 +50,18 @@ test('⌘B splits the selected clips under the playhead, else the main track\'s,assert.deepEqual(ids(splitAllTargets(tracks, 2000)), ['top', 'v', 's']);});+test('[ and ] select every clip with a part before or after the playhead, on tracks not locked', () => {+ const tracks = [+ row(0, [['t', 1, 3]]),+ row(1, [['a', 0, 2], ['b', 2, 5], ['c', 5, 8]]),+ row(2, [['l', 0, 8]], { locked: true }),+ ];+ const ids = (bs: TimelineBlock[]) => bs.map((b) => b.clipId);+ assert.deepEqual(ids(sideTargets(tracks, 3000, 1)), ['b', 'c'], 'b plays on past 3 s; t ends right there');+ assert.deepEqual(ids(sideTargets(tracks, 3000, -1)), ['t', 'a', 'b']);+ assert.deepEqual(ids(sideTargets(tracks, 0, -1)), [], 'nothing before the start');+});+const clip = (id: string, s: number, e: number) => ({ id, startMs: s * 1000, endMs: e * 1000, inMs: 0, speed: 1, sourceMs: 60_000 });const filmOf = (m: EditTrack[]) => ({ tracks: m.map((t) => ({ ...(t.locked ? { locked: true } : {}), clips: t.clips.map((c) => ({ id: c.id, src: `${c.id}.mp4`, ...(c.startMs ? { at: c.startMs / 1000 } : {}), time: [c.inMs / 1000, (c.inMs + c.endMs - c.startMs) / 1000] })) })) });const starts = (m: EditTrack[], ops: Op[]) => (applyOps(filmOf(m) as never, ops as never) as { tracks: { clips: { id: string; at?: number }[] }[] }).tracksdiff --git a/packages/openfilm/studio/ui/src/lib/timeline-nav.ts b/packages/openfilm/studio/ui/src/lib/timeline-nav.tsindex 29d1450..4943861 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-nav.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-nav.ts@@ -72,6 +72,15 @@ export function splitTargets(return [];}+/**+ * What [ / ] select (CapCut's 向左全选 / 向右全选): every clip with a part before the playhead (`dir` -1) or after it+ * (`dir` 1), on every track not locked — what to move when the film before or after a point moves along.+ */+export function sideTargets(tracks: readonly TimelineTrack[], atMs: number, dir: -1 | 1): TimelineBlock[] {+ return tracks.filter((tr) => !tr.locked).flatMap((tr) => tr.blocks)+ .filter((b) => Boolean(b.loc) && (dir > 0 ? b.endMs > atMs + 1 : b.startMs < atMs - 1));+}+/** What ⇧⌘B splits: every clip the playhead is inside, on every track not locked. */export function splitAllTargets(tracks: readonly TimelineTrack[], atMs: number): TimelineBlock[] {return tracks.filter((tr) => !tr.locked).flatMap((tr) => tr.blocks).filter((b) => Boolean(b.loc && b.clipId) && splitsAt(b, atMs));diff --git a/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts b/packages/openfilm/studio/ui/src/lib/timeline-prefs.tsindex 6377d6b..3955dee 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts@@ -4,31 +4,29 @@* "it lands exactly where I let go";* · `magnet` (on by default, as CapCut's main-track magnet): the main track (the lowest picture track) stays closed* up — a clip put down on it inserts and pushes what follows, a delete or a clip taken off it closes the gap, a- * trim ripples. Other tracks never: a clip put down there overwrites, a delete leaves a gap. Off, the main track- * is like the others;+ * trim ripples. On other tracks nothing is covered: a clip put where another is goes to a free track, a delete+ * leaves a gap. Off, the main track is like the others;* · `linkage` (on, as CapCut's 联动): an edit of the main track carries the clips on the other tracks along with- * the main-track clips they start over, so titles, B-roll and sound stay with their picture;- * · `sync` (sync lock, off; as Premiere): a ripple on any track moves every unlocked track along, as far as all of- * them have room. It wins over linkage when both are on;- * · `linked` (on): clips sharing a `data-link` (a video and its detached sound) are selected and edited together.+ * the main-track clips they start over, so titles, B-roll and sound stay with their picture.+ *+ * Clips sharing a `data-link` (a video and its detached sound) are always selected and edited together; ⌥-click picks+ * one alone. Premiere's sync lock is not offered: linkage does that job, the CapCut way.** The inspector reads them too (a slower speed pushes the next clip only with the magnet on), so a change is told to* everyone listening.*/import { useSyncExternalStore } from 'react';-export type TimelinePrefs = { snap: boolean; magnet: boolean; linkage: boolean; sync: boolean; linked: boolean };+export type TimelinePrefs = { snap: boolean; magnet: boolean; linkage: boolean };type Pref = keyof TimelinePrefs;-const DEFAULTS: TimelinePrefs = { snap: true, magnet: true, linkage: true, sync: false, linked: true };+const DEFAULTS: TimelinePrefs = { snap: true, magnet: true, linkage: true };const KEY: Record<Pref, string> = {snap: 'openfilm.timeline.snap',/* new keys: the magnet now acts on the main track alone, and sync lock gave way to linkage, so the choices madefor the old switches do not carry over */magnet: 'openfilm.timeline.mainMagnet',linkage: 'openfilm.timeline.linkage',- sync: 'openfilm.timeline.syncLock',- linked: 'openfilm.timeline.linked',};/** Without localStorage (private window), the choices last this session. */@@ -45,7 +43,7 @@ function read(pref: Pref): boolean {}export function readTimelinePrefs(): TimelinePrefs {- current ??= { snap: read('snap'), magnet: read('magnet'), linkage: read('linkage'), sync: read('sync'), linked: read('linked') };+ current ??= { snap: read('snap'), magnet: read('magnet'), linkage: read('linkage') };return current;}@@ -69,6 +67,6 @@ export function useTimelinePrefs(): TimelinePrefs {}/** What a ripple carries along (timeline-edit Follow), from the switches. */-export function followOf(prefs: Pick<TimelinePrefs, 'sync' | 'linkage'>): { sync: boolean; linkage: boolean } {- return { sync: prefs.sync, linkage: prefs.linkage };+export function followOf(prefs: Pick<TimelinePrefs, 'linkage'>): { sync: boolean; linkage: boolean } {+ return { sync: false, linkage: prefs.linkage };}diff --git a/packages/openfilm/studio/ui/src/lib/whats-new.test.ts b/packages/openfilm/studio/ui/src/lib/whats-new.test.tsnew file mode 100644index 0000000..dc62297--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/whats-new.test.ts@@ -0,0 +1,35 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { RELEASES, compareVersions, notesToShow, releaseNotes, type ReleaseNotes } from './whats-new.ts';++const release = (version: string): ReleaseNotes => ({ version, date: '2026-01-01', notes: { en: [], 'zh-CN': [], ja: [], ko: [], es: [] } });++test('versions in order, a pre-release before its release', () => {+ assert.equal(compareVersions('0.1.10', '0.1.9'), 1);+ assert.equal(compareVersions('0.2.0', '0.10.0'), -1);+ assert.equal(compareVersions('1.0.0', '1.0.0'), 0);+ assert.equal(compareVersions('1.0.0-beta.1', '1.0.0'), -1);+ assert.equal(compareVersions('1.0.0-beta.2', '1.0.0-beta.1'), 1);+});++test('after an update: the notes since the version last shown, the newest first; a new install none', () => {+ const list = [release('0.1.6'), release('0.1.7'), release('0.1.8')];+ assert.deepEqual(notesToShow('0.1.5', '0.1.7', list).map((r) => r.version), ['0.1.7', '0.1.6'], 'up to this version, none newer');+ assert.deepEqual(notesToShow('0.1.7', '0.1.7', list), [], 'already seen');+ assert.deepEqual(notesToShow(null, '0.1.8', list), [], 'a new install');+ assert.equal(releaseNotes('0.1.8', list)?.version, '0.1.8');+ assert.equal(releaseNotes('0.2.0', list), null);+});++test('each release says what is new in every language, a few lines each', () => {+ for (const r of RELEASES) {+ assert.match(r.version, /^\d+\.\d+\.\d+$/);+ assert.match(r.date, /^\d{4}-\d{2}-\d{2}$/);+ for (const [language, notes] of Object.entries(r.notes)) {+ assert.ok(notes.length >= 1 && notes.length <= 6, `${r.version} ${language}: 1 to 6 lines`);+ for (const n of notes) assert.ok(n.text.trim().length > 0, `${r.version} ${language}`);+ }+ }+ const versions = RELEASES.map((r) => r.version);+ assert.deepEqual(versions, [...versions].sort((a, b) => compareVersions(b, a)), 'the newest first');+});diff --git a/packages/openfilm/studio/ui/src/lib/whats-new.ts b/packages/openfilm/studio/ui/src/lib/whats-new.tsnew file mode 100644index 0000000..8d2536d--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/whats-new.ts@@ -0,0 +1,98 @@+/**+ * What each release brings, said to the person after an update: a few lines a release, in every language Studio+ * speaks (a release without them all does not compile), grouped as new, improved and fixed. The newest first.+ *+ * Written when a release is made (the "Version packages" pull request): the changesets say everything that changed,+ * for the changelog; these say what a person would notice, in their words, at most six lines.+ *+ * After an update the release notes since the version last shown appear once (lib's notesToShow; Studio's prefs keep+ * `seenVersion`). A new install shows none: there is nothing it was updated from.+ */+import type { Language } from '@/i18n';++export type NoteKind = 'new' | 'improved' | 'fixed';+export interface ReleaseNote { kind: NoteKind; text: string }+export interface ReleaseNotes { version: string; date: string; notes: Record<Language, ReleaseNote[]> }++export const RELEASES: readonly ReleaseNotes[] = [+ {+ version: '0.1.6',+ date: '2026-10-13',+ notes: {+ en: [+ { kind: 'new', text: 'Export › Editing project makes a CapCut draft: your timeline opens on its home screen, ready to keep cutting. Premiere Pro and DaVinci Resolve get the XML.' },+ { kind: 'new', text: 'Settings › Agents shows whose account Claude Code and Codex use, and what is left of the Codex plan, without opening them.' },+ { kind: 'improved', text: 'Settings › About checks for updates by itself, shows the download, and restarts to update.' },+ { kind: 'fixed', text: 'A 16:9 export is exactly 1920 × 1080 (or 3840 × 2160), whatever the film’s own shape.' },+ { kind: 'fixed', text: 'Choosing where exports go opens the folder dialog in front, and it stays open.' },+ ],+ 'zh-CN': [+ { kind: 'new', text: '导出 › 剪辑工程可以生成剪映草稿:时间线直接出现在剪映首页,接着剪;Premiere Pro 和 DaVinci Resolve 仍用 XML。' },+ { kind: 'new', text: '设置 › 智能体 直接显示 Claude Code 和 Codex 当前用的账号,以及 Codex 的剩余额度,不用再打开它们查看。' },+ { kind: 'new', text: '中文界面的社交平台导出新增哔哩哔哩、抖音、快手、视频号和小红书。' },+ { kind: 'improved', text: '设置 › 关于 会自动检查更新,显示下载进度,下载好后点一下即可重启更新。' },+ { kind: 'fixed', text: '16:9 导出准确为 1920 × 1080(4K 为 3840 × 2160),不再受影片自身画幅影响。' },+ { kind: 'fixed', text: '选择导出位置时,文件夹窗口会出现在最前面,不再一闪而过。' },+ ],+ ja: [+ { kind: 'new', text: '書き出し › 編集プロジェクトで CapCut の下書きを作れます。タイムラインがホーム画面に表示され、そのまま編集を続けられます。Premiere Pro と DaVinci Resolve には XML を書き出します。' },+ { kind: 'new', text: '設定 › エージェントで、Claude Code と Codex が使っているアカウントと、Codex の残りの利用枠を、それぞれを開かずに確認できます。' },+ { kind: 'improved', text: '設定 › 情報 でアップデートを自動で確認し、ダウンロードの進み具合を表示します。準備ができたら再起動で更新できます。' },+ { kind: 'fixed', text: '16:9 の書き出しは、映像自体の比率にかかわらず正確に 1920 × 1080(または 3840 × 2160)になります。' },+ { kind: 'fixed', text: '書き出し先を選ぶフォルダーのダイアログが手前に開き、すぐに閉じなくなりました。' },+ ],+ ko: [+ { kind: 'new', text: '내보내기 › 편집 프로젝트에서 CapCut 초안을 만들 수 있습니다. 타임라인이 홈 화면에 바로 나타나 이어서 편집할 수 있습니다. Premiere Pro와 DaVinci Resolve는 XML로 내보냅니다.' },+ { kind: 'new', text: '설정 › 에이전트에서 Claude Code와 Codex가 사용하는 계정과 Codex의 남은 사용량을 각각 열지 않고 볼 수 있습니다.' },+ { kind: 'improved', text: '설정 › 정보에서 업데이트를 자동으로 확인하고 다운로드 진행 상황을 보여 줍니다. 준비되면 다시 시작해 업데이트하세요.' },+ { kind: 'fixed', text: '16:9 내보내기는 영상 자체의 비율과 관계없이 정확히 1920 × 1080(또는 3840 × 2160)입니다.' },+ { kind: 'fixed', text: '내보낼 위치를 고르는 폴더 대화상자가 앞에 열리고, 바로 닫히지 않습니다.' },+ ],+ es: [+ { kind: 'new', text: 'Exportar › Proyecto de edición crea un borrador de CapCut: tu línea de tiempo aparece en su pantalla de inicio, lista para seguir editando. Premiere Pro y DaVinci Resolve reciben el XML.' },+ { kind: 'new', text: 'Ajustes › Agentes muestra qué cuenta usan Claude Code y Codex, y cuánto le queda al plan de Codex, sin abrirlos.' },+ { kind: 'improved', text: 'Ajustes › Acerca de busca actualizaciones por sí solo, muestra la descarga y se reinicia para actualizar.' },+ { kind: 'fixed', text: 'Una exportación 16:9 mide exactamente 1920 × 1080 (o 3840 × 2160), sea cual sea la forma de la película.' },+ { kind: 'fixed', text: 'Al elegir dónde exportar, el diálogo de carpetas se abre delante y no se cierra solo.' },+ ],+ },+ },+];++/** -1, 0 or 1 as `a` is older than, the same as or newer than `b` (x.y.z; a pre-release is older than its release). */+export function compareVersions(a: string, b: string): number {+ const parse = (v: string) => {+ const [core, pre = ''] = v.split('-');+ return { parts: core.split('.').map((n) => Number(n) || 0), pre };+ };+ const x = parse(a), y = parse(b);+ for (let i = 0; i < 3; i++) {+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);+ if (d) return Math.sign(d);+ }+ if (x.pre === y.pre) return 0;+ if (!x.pre) return 1;+ if (!y.pre) return -1;+ return x.pre < y.pre ? -1 : 1;+}++/**+ * The releases to tell of after an update from `seen` to `current`: those newer than `seen`, up to `current`, the+ * newest first. None when nothing was seen before (a new install) or nothing is newer.+ */+export function notesToShow(seen: string | null, current: string, releases: readonly ReleaseNotes[] = RELEASES): ReleaseNotes[] {+ if (!seen) return [];+ return releases.filter((r) => compareVersions(r.version, seen) > 0 && compareVersions(r.version, current) <= 0)+ .sort((a, b) => compareVersions(b.version, a.version));+}++/** The notes of one release, if it has any. */+export function releaseNotes(version: string, releases: readonly ReleaseNotes[] = RELEASES): ReleaseNotes | null {+ return releases.find((r) => compareVersions(r.version, version) === 0) ?? null;+}++/** Said on the window to show releases' notes (Settings → About, Developer's preview): `detail` is the versions. */+export const WHATS_NEW_EVENT = 'openfilm:whats-new';+export function showWhatsNew(versions: string[]): void {+ window.dispatchEvent(new CustomEvent(WHATS_NEW_EVENT, { detail: versions }));+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8430f7c..9afa8bf 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -29,6 +29,9 @@ importers:'@earendil-works/pi-coding-agent':specifier: 1.1.0version: 1.1.0(@aws-sdk/[email protected])(@modelcontextprotocol/[email protected]([email protected]))(@smithy/[email protected])([email protected])([email protected])+ diff:+ specifier: 9.0.0+ version: 9.0.0electron-updater:specifier: 6.8.9version: 6.8.9diff --git a/scripts/audit-public.mjs b/scripts/audit-public.mjsindex bfa39be..030992d 100644--- a/scripts/audit-public.mjs+++ b/scripts/audit-public.mjs@@ -4,8 +4,8 @@* would commit (tracked and untracked, not ignored; every file under the folder when it is not a git checkout), less* node_modules, dist, .dev and .release, and reports:*- * cjk Chinese, Japanese or Korean prose outside the i18n dictionaries and translated docs (README.zh-CN.md):- * comments and text are in English.+ * cjk Chinese, Japanese or Korean prose outside the i18n dictionaries, the release notes (whats-new.ts) and translated docs+ * (README.zh-CN.md): comments and text are in English.* A line is prose when its CJK characters outweigh its Latin words (one character for four letters), so* an English comment that quotes 永 or 2026年10月7日 passes. In tests and fixtures, string literals are* test data and are left out. The dictionaries are counted, not reported.@@ -38,7 +38,7 @@ const { values: opts } = parseArgs({const ROOT = resolve(opts.dir ?? join(import.meta.dirname, '..'));const SKIP_DIR = /(^|\/)(node_modules|dist|\.dev|\.release|\.git)\//;-const LOCALE = /(^|\/)(i18n|locales)\/|\.(zh-CN|ja|ko|es)\.md$/;+const LOCALE = /(^|\/)(i18n|locales)\/|\/whats-new\.ts$|\.(zh-CN|ja|ko|es)\.md$/;const TESTISH = /(\.test\.[cm]?[jt]sx?$|(^|\/)(test|tests|fixtures?|__fixtures__)\/)/;/** A home folder with a real name in it; the placeholders docs and tests use are fine. */