The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
0.2.0: tabs, skills, Saved, own models, faster galleries, and fixes (#58)
riverisbuilding8ca326c24970
diff --git a/.changeset/agent-mcp-filter.md b/.changeset/agent-mcp-filter.mdnew file mode 100644index 0000000..aceabdd--- /dev/null+++ b/.changeset/agent-mcp-filter.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++In OpenFilm an agent keeps its maker's own MCP servers, but the ones you added to it yourself stay off until you turn each on. The switches are in Settings → Agents, under the agent; this covers Claude Code (its claude.ai connectors stay), Codex, OpenCode, Qwen Code, Gemini CLI and Copilot. Your own skills now stay off in Qwen Code and Gemini CLI too, and Copilot and Qwen Code get OpenFilm's skills. Claude Code's skill filter no longer waits for a first session to learn its skills.diff --git a/.changeset/asr-beside-any-recording.md b/.changeset/asr-beside-any-recording.mdnew file mode 100644index 0000000..230d227--- /dev/null+++ b/.changeset/asr-beside-any-recording.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++`openfilm get asr` now keeps the transcript beside any recording in the project, not only those under `assets/`. A file at the top of the project, or a reference video in `references/`, gets its WebVTT too. Before, none was kept and the answer wrongly said the service does not time words. In Studio, making subtitles now works for a clip whose file is outside `assets/`: before, it was transcribed on every try and nothing was kept. Files and folders starting with a dot (`.git`) belong to the tools, so a recording there is refused before anything is sent.diff --git a/.changeset/browser-hint.md b/.changeset/browser-hint.mdnew file mode 100644index 0000000..a955942--- /dev/null+++ b/.changeset/browser-hint.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++When the preview can't be drawn in Safari or Firefox, Studio now says why: films are drawn and exported with Chromium, so a page may use something that browser doesn't have, and Chrome or Edge shows it. The README says which browsers to open Studio in.diff --git a/.changeset/capture-command.md b/.changeset/capture-command.mdnew file mode 100644index 0000000..8f05dd1--- /dev/null+++ b/.changeset/capture-command.md@@ -0,0 +1,5 @@+---+"openfilm": minor+---++`openfilm capture <url> <file.png>` takes a picture of a live web page in the browser OpenFilm draws films in, with nothing to install: a product or a site shown as it is, sharp enough to fill the stage. It can take the whole page, one element, a phone-sized window or the dark theme, and click or hide things first.diff --git a/.changeset/click-through-overlays.md b/.changeset/click-through-overlays.mdnew file mode 100644index 0000000..ae54e42--- /dev/null+++ b/.changeset/click-through-overlays.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: a click on the picture takes what is under a full-frame overlay. When the clip on top has nothing there but a layer filling its page (a letterbox, a vignette, grain laid over the film), the click, the hover outline and a double-click to type go to the title or picture under it in the clip below. Before, the overlay's clip was taken and nothing under it could be picked in the picture.diff --git a/.changeset/codex-newer-and-readable.md b/.changeset/codex-newer-and-readable.mdnew file mode 100644index 0000000..7d21ecd--- /dev/null+++ b/.changeset/codex-newer-and-readable.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: when Codex is installed more than once, as a command installed long ago and the copy inside the Codex or ChatGPT app (or a Microsoft Store app), the newer one is used: the models Codex offers depend on its version, so an old copy showed only a few. On Windows, a reason Codex could not start is readable instead of `������` on a system in Chinese or another non-English language.diff --git a/.changeset/codex-says-why.md b/.changeset/codex-says-why.mdnew file mode 100644index 0000000..458652a--- /dev/null+++ b/.changeset/codex-says-why.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: when Codex is found but can't start, the chat's model menu now says why, in Codex's own words, instead of only "Couldn't start it to read its settings". A Codex older than the chat needs says to update it. Settings → Agents no longer shows Codex as connected when it can't read its own config file, and names the setting it could not read.diff --git a/.changeset/composer-attachment-preview.md b/.changeset/composer-attachment-preview.mdnew file mode 100644index 0000000..3c8e51f--- /dev/null+++ b/.changeset/composer-attachment-preview.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: a file added to the message you are writing opens to look at, as one in a sent message does: click a video to play it, a picture to see it large, a text to read it.diff --git a/.changeset/composer-attachments-whole-rows.md b/.changeset/composer-attachments-whole-rows.mdnew file mode 100644index 0000000..c8e36d5--- /dev/null+++ b/.changeset/composer-attachments-whole-rows.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: the files added to the message you are writing show in whole rows, up to three at once, so a message's twelve files are all in view. Before, the second row was cut in half and had to be scrolled to.diff --git a/.changeset/cut-no-flash.md b/.changeset/cut-no-flash.mdnew file mode 100644index 0000000..b57a2fc--- /dev/null+++ b/.changeset/cut-no-flash.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio's preview no longer flashes at a cut. A page coming on used to show before its frame was drawn, so for a moment it showed how it looked before: its first state, or the frame it drew the last time it was on. Now it shows once that frame is drawn, and the picture before it stays until then. Exports were never affected.diff --git a/.changeset/gallery-at-once.md b/.changeset/gallery-at-once.mdnew file mode 100644index 0000000..b05b51b--- /dev/null+++ b/.changeset/gallery-at-once.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++The Examples and the skills show at once. OpenFilm comes with a copy of the examples index and its posters, and keeps the last index it read, so the Examples tab no longer waits on GitHub (a slow or blocked connection showed nothing); the newest index is read in the background as Studio starts. A gallery opened again shows what it read before while it asks again, skill covers and example posters stay in the browser's cache, and the app reads what the composer's skills need as it starts.diff --git a/.changeset/inspector-words-as-typed.md b/.changeset/inspector-words-as-typed.mdnew file mode 100644index 0000000..670a9a8--- /dev/null+++ b/.changeset/inspector-words-as-typed.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: words typed into a line in the picture show in the inspector as they are typed. Its text box and the layer's name follow each key, and go back to the old words when the edit is given up with Esc. Before, the inspector kept the old words until Enter.diff --git a/.changeset/installer-locked-versions.md b/.changeset/installer-locked-versions.mdnew file mode 100644index 0000000..3c80640--- /dev/null+++ b/.changeset/installer-locked-versions.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: Your own key works again. The 0.1.7 installer carried newer versions of the agent's packages than the ones tested, one of which no longer fit, so every message ended with "ACP connection closed". The installer now carries exactly the versions in the lockfile, and its build stops if any differ.diff --git a/.changeset/locate-when-off.md b/.changeset/locate-when-off.mdnew file mode 100644index 0000000..6bf1758--- /dev/null+++ b/.changeset/locate-when-off.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Settings → Agents: an agent that is connected shows Disconnect alone. Locate… is offered when it is disconnected (beside Connect) or not found.diff --git a/.changeset/meters-theme.md b/.changeset/meters-theme.mdnew file mode 100644index 0000000..3ffe49c--- /dev/null+++ b/.changeset/meters-theme.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: a theme change reaches everything at once. The audio meters beside the timeline and the clips' waveforms are drawn again in the new theme's colors (before, they kept the other theme's, such as dark meter bars in the light theme, until the film played), and every other open page of Studio, such as another tab of the app, takes the theme too.diff --git a/.changeset/mix-many-sounds.md b/.changeset/mix-many-sounds.mdnew file mode 100644index 0000000..b7242eb--- /dev/null+++ b/.changeset/mix-many-sounds.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++A film with hundreds of sounds renders and exports on Windows. Its mix no longer puts everything on one command line, which Windows limits to 32,767 characters: a sound used by many clips is read once, and a long mix's graph goes in a file.diff --git a/.changeset/own-agent-prompt-once.md b/.changeset/own-agent-prompt-once.mdnew file mode 100644index 0000000..6466efc--- /dev/null+++ b/.changeset/own-agent-prompt-once.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Your own key's agent gets a shorter system prompt with no conflicting instructions. It was told both that it already had the manual and that it should print it, and both to open Studio and never to open it. Rules it got two or three times are now said once. Its own part is a third shorter, and the manual is unchanged.diff --git a/.changeset/own-models.md b/.changeset/own-models.mdnew file mode 100644index 0000000..001ae1e--- /dev/null+++ b/.changeset/own-models.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: Your own key is an agent with models of your own, each set up on its own: the name the chat shows, the API format and address of its service, its own key, the model asked for there, and the reasoning efforts it takes. The chat's model menu switches between them, from one service to another, as it does for the other agents. A model on an address already set up can take that model's key. Models set up before become one each, on the service and key they had.diff --git a/.changeset/pin-pi-codemode.md b/.changeset/pin-pi-codemode.mddeleted file mode 100644index 38bf65f..0000000--- a/.changeset/pin-pi-codemode.md+++ /dev/null@@ -1,5 +0,0 @@-----"@openfilm/desktop": patch------The app's own agent starts again: the packaged app had `@earendil-works/pi-coding-agent` 1.1.0 beside `pi-codemode` 1.2.0, which no longer exports `MCP_TYPESCRIPT_PREAMBLE`, so the agent crashed on start and every "Own key" message ended with "ACP connection closed". `pi-codemode` is now a direct dependency at 1.1.0.diff --git a/.changeset/replicate-skill.md b/.changeset/replicate-skill.mdnew file mode 100644index 0000000..c96693a--- /dev/null+++ b/.changeset/replicate-skill.md@@ -0,0 +1,5 @@+---+"openfilm": minor+---++An official skill, `replicate`: give the agent a video and it makes yours like it, keeping its structure, rhythm, look and motion while the content is yours. It watches the reference whole and in stretches with `openfilm look`, starts from an example's source when one fits, writes a plan part by part, and compares the two side by side. It never reuses the reference's footage, music, voice or words.diff --git a/.changeset/saved-and-templates.md b/.changeset/saved-and-templates.mdnew file mode 100644index 0000000..71e56be--- /dev/null+++ b/.changeset/saved-and-templates.md@@ -0,0 +1,8 @@+---+"openfilm": minor+"@openfilm/desktop": minor+---++Saved: your own library, the same in every project. The bookmark button beside Upload switches the media pane to it, and back; it is the same pane, so upload, folders, list and grid, filters, sort, search, rename, move and delete all work there, and anything can go in it: video, pictures, sound, documents, any file. Right-click a clip on the timeline or the picture, or a file of the project, and choose Add to Saved; with several clips selected, save them as one (they come back on tracks of their own, laid out as they were, links kept) or each alone. Drag anything from Saved onto the timeline, or press Enter: a file is imported into the project as one from your computer is, and a saved clip comes back as you saved it, with its place, its look and the changes made in its page, its files copied into the project, so changing it there never changes the saved one. Saved is a folder beside your projects (Movies/OpenFilm/Saved on a Mac), so you can also add to it from Finder. The media pane no longer has a close button: the assets button beside the chat opens and closes it.++Template: select a page clip and the inspector shows what its page lets you change, without opening the page: each of its words, each of its pictures (replace one with a picture of the project, one dropped from the media pane, or one from your computer), and the CSS custom properties its stylesheet sets on `:root` (a color with a color picker, a number with its unit, a font with the font picker, words in quotes as text). Each change is kept for that clip only, and one changed can go back to the page's own. A page saved with such properties is marked as a template in Saved.diff --git a/.changeset/services-page.md b/.changeset/services-page.mdnew file mode 100644index 0000000..f87be87--- /dev/null+++ b/.changeset/services-page.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Settings: Models is now Services (which service makes each kind of media), and your own services moved there as Custom services. One is set up with its name, address, key and a description of what it does and how it is called (or where its API docs are): where the key goes is no longer asked, since your agent puts it where the service's docs say.diff --git a/.changeset/settings-copy.md b/.changeset/settings-copy.mdnew file mode 100644index 0000000..6a188ec--- /dev/null+++ b/.changeset/settings-copy.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Settings say what is there now: Custom services take as many services as you like, and say you can also tell your agent about a service in the chat (one with a key is better set up there, so the key stays out of the conversation). The note pointing to the old "Your own services" is gone, Agents describes your own key as models you set up, Providers says the choice of each kind of media is under Services, and the sign-in wait no longer names Terminal (Windows opens PowerShell).diff --git a/.changeset/skills-cli.md b/.changeset/skills-cli.mdnew file mode 100644index 0000000..f9e4b43--- /dev/null+++ b/.changeset/skills-cli.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Skills: ways of making a kind of film, each a folder with a SKILL.md and the files it brings. `openfilm skills` lists the skills a film can be made with: the project's own (in its `skills/` folder), yours (in `~/Movies/OpenFilm/Skills`), and the official ones. `openfilm skill <name>` prints one for the agent to follow. `openfilm skill add <GitHub address or folder>` adds a skill to yours and lists any scripts it brings. The manual tells agents about them. Studio no longer lists pages inside a project's `skills/` folder.diff --git a/.changeset/skills-desktop.md b/.changeset/skills-desktop.mdnew file mode 100644index 0000000..d2ccf6d--- /dev/null+++ b/.changeset/skills-desktop.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++In the chat, a skill can be named in a message: type `/`, or pick one in the Community; it goes in as a pill and the agent gets the skill's instructions with the message. The composer's Community button opens over your film on the skills (official, yours, this project's), with the examples beside them: point the agent at an example, or a part of one (a segment, or a stretch dragged on its strip), and it reads how that film is made; or start a new film from it, in a tab of its own. Add a skill there from a GitHub link or a folder, or make one with the agent. In OpenFilm an agent keeps its maker's own skills and gets OpenFilm's, but the skills you installed in it yourself stay off until you turn each on in Settings → Agents. This works for Claude Code, Codex, OpenCode and your own key's agent; agents that can't be told say they use all of yours. The context ring is gone: when a conversation is nearly full, a line above the composer offers a new one.diff --git a/.changeset/skills-on-windows.md b/.changeset/skills-on-windows.mdnew file mode 100644index 0000000..2ddad46--- /dev/null+++ b/.changeset/skills-on-windows.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++Desktop on Windows: skills work. The app loaded its skills module by a Windows path, which Node refuses, so the Skills button and gallery could not read skills and agents started without OpenFilm's.diff --git a/.changeset/skills-p0.md b/.changeset/skills-p0.mdnew file mode 100644index 0000000..83977a8--- /dev/null+++ b/.changeset/skills-p0.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Your own skills are kept in `~/Movies/OpenFilm/Skills` (beside Projects and Exports, backed up with them); skills kept in `~/.openfilm/skills` move there on their own. A skill replaced or removed goes to the trash, never deleted, and `openfilm skill remove <name>` moves one there. Adding from a link or a folder shows what came first: each skill, its size, the scripts it brings and any of yours it would replace, then Add or Cancel. The switches for an agent's own skills are in Settings → Agents, beside its MCP servers. OpenFilm's own skill for terminal agents is no longer shown in the app.diff --git a/.changeset/smooth-preview-many-files.md b/.changeset/smooth-preview-many-files.mdnew file mode 100644index 0000000..0da1cff--- /dev/null+++ b/.changeset/smooth-preview-many-files.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: a project with thousands of files plays smoothly as soon as it opens. While its files' lengths and sizes were read, each answer laid out the media pane again (tens of ms with that many files), so the picture stalled again and again for the first minutes. The answers now come in a few times a second, and the pane works out its folders in one pass.diff --git a/.changeset/stop-background-turn.md b/.changeset/stop-background-turn.mdnew file mode 100644index 0000000..de8935d--- /dev/null+++ b/.changeset/stop-background-turn.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Desktop: stopping the agent while a command it ran was still going no longer starts a turn of its own a moment later, "A background task finished; the agent went on", that Stop could not end. The rest of a command from a turn that already ended (its last output, its exit) now stays out of the chat. Stop ends a turn the agent started by itself at once. Such a turn that ends with nothing in it leaves no line behind, including ones already saved.diff --git a/.changeset/storage-locations.md b/.changeset/storage-locations.mdnew file mode 100644index 0000000..7d49dce--- /dev/null+++ b/.changeset/storage-locations.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Choose where new projects go. Settings → General → Storage shows the folder, with the free space on its disk, and lets you change it (or go back to the default), for example to keep large projects off a full system disk. Exports go where you pick when exporting, as before. New projects, including ones fetched with `openfilm open`, go to the folder you choose; projects made before stay where they are and still open from the list. On Windows, the installer now asks where to install the app.diff --git a/.changeset/style-skills.md b/.changeset/style-skills.mdnew file mode 100644index 0000000..a769ab7--- /dev/null+++ b/.changeset/style-skills.md@@ -0,0 +1,11 @@+---+"openfilm": minor+---++Nine more official skills, each with a version, so you can tell which one made a film:+- Workflows: `long-to-short` (a long video cut into shorts that stand alone), `screen-demo` (a screen recording made into a polished demo), `motion-graphics` (studio-level motion graphics), `presenter-pip` (you speaking from a small window while the content fills the screen).+- Styles: `whiteboard` (drawn by hand as a voice explains), `vintage-film` (photos as old film and instant prints), `lyric-video` (a song's lyrics as the picture, every word on the voice), `keynote` (a launch film with your real product on stage), `collage` (cut-paper motion graphics).++A skill's openfilm.json can now give its `version`, its `kind` (`workflow` or `style`), its `order`, an `icon`, a `cover` picture and a `preview` video.++The Community's skills are redesigned: a row of filters at the top (all, yours, this project's, workflows, styles) with adding a skill beside it; yours come first; a note on what skills are for; and a skill opens as a page with its picture or preview on the left and what it is, its version and using it on the right.diff --git a/.changeset/tabs-launcher-examples.md b/.changeset/tabs-launcher-examples.mdnew file mode 100644index 0000000..66109df--- /dev/null+++ b/.changeset/tabs-launcher-examples.md@@ -0,0 +1,6 @@+---+"openfilm": minor+"@openfilm/desktop": minor+---++Tabs: the desktop window keeps each open project in a tab of its own, in Studio's top bar, side by side, the one in front in the panes' color. `+` (⌘T) opens the projects window, and the project picked opens in a new tab (or comes forward, when it is open already). ⌘W closes a tab, ⇧⌘T opens the last one closed again, ⌘1–9 and ⌃Tab switch. A tab shows when an agent is working in it, when one is waiting for your answer, and an export's progress; agents and exports go on in tabs behind. The tabs come back as you left them; with none open, the window shows your projects. The projects window has two views: your projects, and Examples, where example films play their preview under the pointer and open on a page of their own with their parts, to start a new film from. Skills show their own title and summary in your language (a skill's optional `openfilm.json`). An examples index can list each example's `category`, `segments` and a `video` preview; one read from a file has its pictures served by Studio. Studio in a browser keeps its projects window, now with the same two views.diff --git a/.changeset/thumbnails-whole-cells.md b/.changeset/thumbnails-whole-cells.mdnew file mode 100644index 0000000..25be4a0--- /dev/null+++ b/.changeset/thumbnails-whole-cells.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: a short clip's thumbnails fill it. Each picture in a clip's row was squeezed to the clip's width while the pictures kept their places, so the clip's color showed between them and the row looked broken.diff --git a/.changeset/turn-log-everything.md b/.changeset/turn-log-everything.mdnew file mode 100644index 0000000..aadefda--- /dev/null+++ b/.changeset/turn-log-everything.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++A turn's log (Settings → Developer) now shows everything the agent and its model got. A new "Sent to the agent" tab shows how the app started the agent, every word it adds to the agent's own instructions, and each message exactly as the agent got it, with its pictures. Model requests are no longer only your own key's: for Claude Code, Codex and Kimi they are read from each agent's own record. Each request shows its full system prompt, its tools, every message (including what the agent added by itself: project instructions, environment, skill lists, reminders), the answer and its tokens. Subagents' requests are included. Turns from before this change show their requests too, as long as the agent's record is still there.diff --git a/.changeset/turn-log-more-agents.md b/.changeset/turn-log-more-agents.mdnew file mode 100644index 0000000..69377c0--- /dev/null+++ b/.changeset/turn-log-more-agents.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++A turn's log (Settings → Developer) now shows model requests for Gemini CLI, GitHub Copilot, Qwen Code, CodeBuddy and OpenCode too: each request's system prompt, tools, every message (including what the agent added by itself), the answer and its tokens. With Developer mode on, Gemini CLI, Qwen Code, CodeBuddy and OpenCode are started with their own local logging switch, written into a folder of the app's and kept for a week. The app leaves any telemetry you set yourself as it is. CodeBuddy is logged only when its own telemetry is off (`DISABLE_TELEMETRY=1`), since otherwise its traces would name each logged file. Copilot's requests are rebuilt from its own record, which has no tool definitions. Where a log lacks something, the viewer says so, and it explains a turn that has no requests (Cursor makes its prompt on its servers).diff --git a/.changeset/turn-log-skills-row.md b/.changeset/turn-log-skills-row.mdnew file mode 100644index 0000000..47b2fe9--- /dev/null+++ b/.changeset/turn-log-skills-row.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++A turn's log shows how the session's skills and MCP servers were set: OpenFilm's skills, your own skills and servers kept off, and the ones you let in. A thought the agent did not keep in its record now says so, instead of showing 0 characters.diff --git a/.changeset/web-update.md b/.changeset/web-update.mdnew file mode 100644index 0000000..b001b66--- /dev/null+++ b/.changeset/web-update.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio run with npm updates itself: when a newer OpenFilm is out, Update appears in the top bar (and in Settings → About), and a click runs the newest in the background; Studio starts again on it and the page comes back on the new version. `openfilm update` does the same from a terminal, or for an agent asked to update OpenFilm. The desktop app's Studio still updates with the app.diff --git a/.changeset/whats-new-017.md b/.changeset/whats-new-017.mdnew file mode 100644index 0000000..9a1209c--- /dev/null+++ b/.changeset/whats-new-017.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++What's new: 0.1.7's notes, missing when it shipped, so Settings → About and Developer show them, and an update from 0.1.6 shows them once. Every version now has its notes before it can be released.diff --git a/.github/ISSUE_TEMPLATE/skill_feedback.yml b/.github/ISSUE_TEMPLATE/skill_feedback.ymlnew file mode 100644index 0000000..c042ceb--- /dev/null+++ b/.github/ISSUE_TEMPLATE/skill_feedback.yml@@ -0,0 +1,21 @@+name: Skill feedback+description: How a skill worked for you, or a skill you wish there were.+labels: [skills]+body:+ - type: input+ id: skill+ attributes:+ label: The skill+ description: Its name, or its link if you added it from one. Leave it empty for a skill you wish there were.+ - type: textarea+ id: what+ attributes:+ label: What happened+ description: What you asked for, what the agent made with the skill, and what you hoped for.+ validations:+ required: true+ - type: input+ id: agent+ attributes:+ label: The agent+ description: Which agent and model you used, if you know.diff --git a/README.md b/README.mdindex 7467ef3..eda8498 100644--- a/README.md+++ b/README.md@@ -66,6 +66,7 @@ openfilm open [folder | url] # show a film in Studio: a new one, an existinopenfilm look [what] [t | a-b] # check the film, a page or a media file: a contact sheet, one frame, or a rangeopenfilm render [a-b] # the MP4; --4k, --blur (motion blur), --alpha (.webm / .mov)openfilm get [what] # voice-over, music, sound effects, transcripts, images, video, from your services+openfilm capture <url> <file.png> # a picture of a live web page (a product, a site), sharp enough to fill the stage````openfilm <command> --help` lists a command's options; `openfilm get` alone lists what can be made and how to@@ -73,7 +74,8 @@ connect a service in Studio with your own key.## Studio-Studio runs on your machine, in your browser. Everything in the film can be changed: text and layers in the+Studio runs on your machine, in your browser: use one built on Chromium (Chrome, Edge), the engine films are drawn+and exported with, so the preview is what you export. Everything in the film can be changed: text and layers in thepicture, clips on the timeline, their place, look, volume and speed, and the subtitles. Your edits are saved to thefilm's files, so the agent sees and keeps them, and you can save named versions to go back to. Export a video, a GIF,the sound or its stems, subtitles, stills, slides, a transparent video, or the timeline itself for Premiere Pro anddiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 11d2385..74ef9e8 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -65,6 +65,7 @@ openfilm open [folder | url] # 在 Studio 里打开片子:新建、打开openfilm look [what] [t | a-b] # 检查片子、某个页面或媒体文件:缩略图总览、单帧或一段区间openfilm render [a-b] # 渲染成 MP4;--4k、--blur(运动模糊)、--alpha(.webm / .mov)openfilm get [what] # 用你接入的服务生成配音、音乐、音效、字幕转写、图片和视频+openfilm capture <url> <file.png> # 截取正在运行的网页(产品、网站),清晰到能占满画面````openfilm <命令> --help` 列出某个命令的选项;单独运行 `openfilm get` 会列出能生成什么,以及怎么在 Studio 里用你diff --git a/apps/desktop/bench/scenarios.mjs b/apps/desktop/bench/scenarios.mjsindex f5d5459..9a8f266 100644--- a/apps/desktop/bench/scenarios.mjs+++ b/apps/desktop/bench/scenarios.mjs@@ -95,7 +95,7 @@ const press = async (page, code, key) => {/** The own-key agent on the fake model, the only one the chat offers. */async function useFakeAgent(studio, chat, model) {- const done = await studio.evaluate((baseUrl) => window.openfilmHost.agents.configureByok({ format: 'responses', baseUrl, model: 'bench', key: 'bench-key' }), model.baseUrl);+ const done = await studio.evaluate((baseUrl) => window.openfilmHost.agents.saveOwnModel({ format: 'responses', baseUrl, model: 'bench', key: 'bench-key', levels: ['auto'], effort: 'auto' }), model.baseUrl);if (!done?.ok) throw new Error(`setting up the agent: ${done?.error ?? 'no answer'}`);for (const id of ['codex', 'claude']) await studio.evaluate((x) => window.openfilmHost.agents.setShown(x, false), id);await until('the own-key agent ready', () => studio.evaluate(async () => (await window.openfilmHost.agents.list()).find((a) => a.id === 'byok')?.status === 'ready'), 120_000, 500);diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsxindex d146d30..b6e4517 100644--- a/apps/desktop/chat/src/App.tsx+++ b/apps/desktop/chat/src/App.tsx@@ -6,24 +6,26 @@* (lib/local-agent-run's saved turns).*/import React from 'react';-import { ArrowDown, Coins, CornerDownLeft, LibraryBig, Loader2, Play, Plus, ShieldQuestion, Square, SquareSlash, X } from 'lucide-react';+import { ArrowDown, Blocks, 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 { useT, useUiLocale } from '@/i18n';import { ConversationSessionBar } from '@/components/ConversationSessionBar';import { ProjectConversation, primeStoredTranscript } from '@/components/ProjectConversation';import { ProjectStarters } from '@/components/ProjectStarters';+import { AttachmentPreview, type AttachmentPreviewItem } from '@/components/AttachmentPreview';import { ModelPopover } from '@/components/ModelPopover';-import { ContextMeter } from '@/components/ContextMeter';+import { AddSkillDialog, type PickedSkill } from '@/components/AddSkill';import { CardActions, CardButton, ComposerCard } from '@/components/ComposerCard';import { LocalAgentQuestionCard } from '@/components/TurnQuestionCard';import { Tooltip } from '@/components/Tooltip';import { StickToBottomContext, useStickToBottom, useTailSpacer } from '@/components/useStickToBottom';-import { PromptEditor, PromptPill, PromptPillHoverContext, PromptPillRevealContext, fileReferenceId, fileReferencePath, promptReferenceToken, resolvePromptReferences, splitPromptReferenceText, type MentionProvider, type PromptEditorHandle, type PromptEditorState, type PromptPillHover, type PromptReference } from '@/components/prompt-editor';+import { PromptEditor, PromptPill, PromptPillHoverContext, PromptPillRevealContext, activatedSkillIds, fileReferenceId, fileReferencePath, promptReferenceToken, resolvePromptReferences, skillReferenceId, skillReferencePackage, 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 { attachedPictures, attachedText, attachmentBlocker, formatFileSize, turnAttachments, useDesktopAttachments } from '@/lib/desktop-attachments';import { deriveProjectTurns } from '@/lib/project-versions';import { makePlaceholder, mergeAssetLists } from '@/lib/asset-lists';+import { isEmptyBackgroundTurn } from '@/lib/unprompted';import {answerLocalAgentPermission,answerLocalAgentQuestion,@@ -61,7 +63,7 @@ import { useLiveActivityFromStore } from '@/lib/live-activity';import { loadLastSession, loadSessions, newSession, saveLastSession, saveSessions } from '@/lib/local-sessions';import type { ProjectSessionItem } from '@/lib/project-sessions';import type { TranscriptItem } from '@/lib/agent-transcript';-import { app, type FfmpegState, type Project, type StudioRef, type StudioSelection } from './app-bridge';+import { app, type FfmpegState, type Project, type SkillListing, type StudioRef, type StudioSelection } from './app-bridge';import { Divider } from './components/Divider';import { draftRefs, pillCard, refFromPill, refPill, sameStudioThing, selectionMoment, selectionRange, selectionRefs, studioReferencesText } from './studio-refs';import { inChat } from './lib/chat-layer';@@ -75,8 +77,14 @@ const isActive = (turn: Turn | undefined) => turn?.status === 'generating' || tu/** how often a running turn is kept, at most (it changes with every word) */const KEEP_RUNNING_MS = 1500;+/** how full the agent's context gets before the chat says a new conversation would work better */+const CONTEXT_NOTICE_SHARE = 0.85;/** On a video's thumbnail: it plays, it is not a picture. */+/* between the chat's root (the add-skill dialog) and the project's chat: a skill added, a skill to make */+const SKILLS_CHANGED = 'openfilm:skills-changed';+const MAKE_SKILL = 'openfilm:make-skill';+function PlayMark() {return (<span aria-hidden className="pointer-events-none absolute inset-0 m-auto flex h-4 w-4 items-center justify-center rounded-full bg-black/55">@@ -110,6 +118,11 @@ export function App({ initialProject, initialSelection, initialFfmpeg }: {return () => { for (const stop of stops) stop(); };}, []);+ /* "Add a skill" in the examples (on a project or a new tab's launcher): its dialog, here at the root so it opens on+ either; naming the one added and making one with the agent only where a project's chat is */+ const [addingSkill, setAddingSkill] = React.useState(false);+ React.useEffect(() => app.onAddSkill?.(() => setAddingSkill(true)), []);+/* the project's chat record, read from its folder before its conversation shows */const chatReady = useProjectChat(project);const ffState = typeof ffmpeg === 'object' && ffmpeg ? ffmpeg : null;@@ -124,8 +137,14 @@ export function App({ initialProject, initialSelection, initialFfmpeg }: {</>);+ const onProject = Boolean(project) && /^\/projects\//.test(location.pathname);return (<div className={`relative flex h-full flex-col ${assetsOpen ? '' : 'bg-[var(--dock-shell)]'}`}>+ {addingSkill ? (+ <AddSkillDialog onClose={() => setAddingSkill(false)} onAdded={async () => { window.dispatchEvent(new Event(SKILLS_CHANGED)); }}+ onPick={onProject ? (skill) => app.useSkill?.(skill) : undefined}+ onMake={onProject ? () => window.dispatchEvent(new Event(MAKE_SKILL)) : undefined} />+ ) : null}{/* under Studio's top bar (it runs over this, across the window): the seam on the left is the handle */}<Divider /><div className="mb-[6px] ml-[6px] mr-[6px] flex min-h-0 flex-1 flex-col">@@ -182,7 +201,10 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecconst done: Turn = { ...(meta.turn as Turn), ...patch, updatedAt: new Date().toISOString() };primeStoredTranscript(id, turn.items);saveLocalAgentTurn(meta.projectId, done, turn.items);- setTurns((list) => list.map((item) => (item.id === id ? { ...item, ...patch, updatedAt: done.updatedAt } : item)));+ /* a turn the agent started by itself that ended with nothing in it leaves no line behind */+ setTurns((list) => (isEmptyBackgroundTurn(done, turn.items)+ ? list.filter((item) => item.id !== id)+ : list.map((item) => (item.id === id ? { ...item, ...patch, updatedAt: done.updatedAt } : item))));return done;}@@ -259,6 +281,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecconst [queued, setQueued] = React.useState(false);const [followUpError, setFollowUpError] = React.useState<string | null>(null);const composerFiles = useDesktopAttachments();+ /* a file of the message being written, opened to look at */+ const [openedFile, setOpenedFile] = React.useState<AttachmentPreviewItem | null>(null);const attachInputRef = React.useRef<HTMLInputElement>(null);const [dropping, setDropping] = React.useState(false);/** files of the project pointed at with @ (their pills turn back into their paths when sent) */@@ -266,9 +290,11 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecconst 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;+ /** skills named with the Skills button or `/` (each pill turns into the skill's name, its SKILL.md after the message) */+ const [skillRefs, setSkillRefs] = React.useState<PromptReference[]>([]);const composerPills = React.useMemo(- () => [...[...studioRefs.entries()].map(([id, ref]) => refPill(id, ref)), ...fileRefs],- [studioRefs, fileRefs],+ () => [...[...studioRefs.entries()].map(([id, ref]) => refPill(id, ref)), ...fileRefs, ...skillRefs],+ [studioRefs, fileRefs, skillRefs],);/* ── the @ menu: this moment in Studio, and the project's files (asked for when the menu opens) ── */@@ -295,16 +321,81 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec});return pills;}, []);- /* how full the agent's context is in this conversation */+ /* how full the agent's context is in this conversation: said only once it is nearly full */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 [contextNoticeOff, setContextNoticeOff] = React.useState<string | null>(null);+ const contextFull = Boolean(agentContext && agentContext.size > 0 && agentContext.used / agentContext.size >= CONTEXT_NOTICE_SHARE) && contextNoticeOff !== sessionId;++ /* the skills this message can name (the Skills button, and `/`) */+ const [skillListing, setSkillListing] = React.useState<SkillListing | null>(null);+ const reloadSkills = React.useCallback(async () => {+ const next = await app.skills?.list(project.path, agent).catch(() => null);+ if (next) setSkillListing(next);+ }, [project.path, agent]);+ React.useEffect(() => { void reloadSkills(); }, [reloadSkills]);+ /* a skill as people see it, in the language shown: its title, and what its page says (none: its name and the+ agent's description) */+ const locale = useUiLocale();+ const skillWords = React.useCallback((name: string, description = '') => {+ const shown = skillListing?.openfilm.find((s) => s.name === name)?.shown;+ const pick = (words?: Record<string, string>) => (words ? words[locale] ?? words[locale.split('-')[0]!] ?? words.en ?? Object.values(words)[0] : undefined);+ const summary = pick(shown?.summary);+ return {+ title: pick(shown?.title) ?? name,+ summary: summary ?? description,+ text: shown ? [summary, ...(pick(shown.details)?.split('\n') ?? [])].filter((w): w is string => Boolean(w)) : description ? [description] : [],+ };+ }, [skillListing, locale]);+ const skillPill = React.useCallback((skill: PickedSkill): PromptReference => {+ /* its title alone: what it does is in its hover card */+ const pill: PromptReference = { id: skillReferenceId(skill.name), kind: 'skill', label: skillWords(skill.name, skill.description).title };+ setSkillRefs((list) => (list.some((p) => p.id === pill.id) ? list : [...list, pill]));+ return pill;+ }, [skillWords]);+ const pickSkill = React.useCallback((skill: PickedSkill) => {+ const pill = skillPill(skill);+ requestAnimationFrame(() => { composerRef.current?.insertReference(pill); composerRef.current?.focus(); });+ }, [skillPill]);+ /* the skills a message can name: OpenFilm's, and of the agent's own those it has (let in, or all when it cannot be told) */+ const nameableSkills = React.useMemo(() => [+ ...(skillListing?.openfilm ?? []),+ ...(skillListing?.own.skills ?? []).filter((s) => !skillListing?.own.filtered || s.allowed),+ ], [skillListing]);+ /* a skill picked in the examples (Studio's, over the film): named in the message; "Add a skill" there: its dialog */+ React.useEffect(() => app.onUseSkill?.((skill) => pickSkill(skill)), [pickSkill]);+ /* a skill added from the examples (AddSkillDialog, at the chat's root): the list read again; "make one with the+ agent" there: its message put in the composer */+ React.useEffect(() => {+ const changed = () => { void reloadSkills(); };+ const make = () => { composerRef.current?.setText(t('skills.makePrompt').replace('{folder}', skillListing?.mine ?? '')); composerRef.current?.focus(); };+ window.addEventListener(SKILLS_CHANGED, changed);+ window.addEventListener(MAKE_SKILL, make);+ return () => { window.removeEventListener(SKILLS_CHANGED, changed); window.removeEventListener(MAKE_SKILL, make); };+ }, [reloadSkills, skillListing, t]);+ /* the agent's own skills hidden in OpenFilm: not offered among its commands either */+ const hiddenSkills = React.useMemo(() => new Set((skillListing?.own.filtered ? skillListing.own.skills.filter((s) => !s.allowed) : []).map((s) => s.name)), [skillListing]);++ /* the agent's own commands, a `/` at the start of the message, as in its own chat: they go as typed; above them, the+ skills, each a pill */const agentCommands = useAgentCommands(agent);- const commandMenu = React.useMemo(() => (agentCommands.length ? {+ const commandMenu = React.useMemo(() => (agentCommands.length || nameableSkills.length ? {label: t('composer.commands'),- providers: [{+ providers: [...(nameableSkills.length ? [{+ id: 'skills',+ groupLabel: t('skills.button'),+ items: nameableSkills.map((skill) => ({+ id: skillReferenceId(skill.name),+ kind: 'skill' as const,+ icon: Blocks,+ label: skillWords(skill.name).title,+ ...(skillWords(skill.name, skill.description).summary ? { detail: skillWords(skill.name, skill.description).summary, describes: true } : {}),+ keywords: [skill.name, skillWords(skill.name).title],+ select: () => skillPill(skill),+ })),+ }] : []), ...(agentCommands.length ? [{id: 'commands',groupLabel: t('composer.commands'),- items: agentCommands.map((c) => ({+ items: agentCommands.filter((c) => !hiddenSkills.has(c.name)).map((c) => ({id: `command:${c.name}`,kind: 'file' as const,icon: SquareSlash,@@ -315,8 +406,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projeckeywords: [c.name],select: () => ({ text: `/${c.name}` }),})),- }],- } : undefined), [agentCommands, t]);+ }] : [])],+ } : undefined), [agentCommands, nameableSkills, hiddenSkills, skillPill, skillWords, t]);const mentionProviders = React.useMemo<MentionProvider[]>(() => {const picked = selection?.refs ?? [];const range = selection ? selectionRange(selection) : null;@@ -392,8 +483,19 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec};/* a pill's hover card, in the composer and in what was sent; clicking one there takes the person to it in Studio */- const describePill = React.useCallback((pill: { id: string; label: string; target?: Record<string, unknown> }) => pillCard(pill, t), [t]);+ const describePill = React.useCallback((pill: { id: string; label: string; target?: Record<string, unknown> }) => {+ const name = skillReferencePackage(pill.id);+ if (name) {+ const skill = nameableSkills.find((s) => s.name === name);+ const words = skillWords(name, skill?.description);+ return { title: words.title, rows: [], text: words.text };+ }+ return pillCard(pill, t);+ }, [t, nameableSkills, skillWords]);const revealPill = React.useCallback((pill: { id: string; label: string; target?: Record<string, unknown> }) => {+ /* a skill: its page in the Community; anything else: where it is in Studio */+ const name = skillReferencePackage(pill.id);+ if (name) { app.showExamples?.({ kind: 'skill', name }); return; }const ref = refFromPill(pill);if (ref) app.showInStudio(ref);}, []);@@ -451,7 +553,11 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecif (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' }) };+ return {+ turn: opened.turn,+ meta: opened.meta,+ done: (outcome) => settlers.current.get(id)?.(outcome === 'cancelled' ? { status: 'cancelled', cancelReason: 'user' } : { status: 'ready' }),+ };}), [projectKey]);/**@@ -595,7 +701,9 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecif (!ref) return null;used[index - 1] = ref;return `[${index}: ${refPill(pillId, ref).label}]`;- }).trim();+ }, (pillId) => { const name = skillReferencePackage(pillId); return name ? `skill “${name}”` : null; }).trim();+ /* the skills it names: each one's SKILL.md follows the message, for the agent to read */+ const skillNames = activatedSkillIds(followUpRefs);if (!instruction) return;const blocker = attachmentBlocker(composerFiles.files);if (blocker) { setFollowUpError(blocker); return; }@@ -607,14 +715,22 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: ProjecsetFollowUpRefs([]);setStudioRefs(new Map());setFileRefs([]);+ setSkillRefs([]);const files = composerFiles.take();const id = makeLocalAgentTurnId();const said = instruction + attachedText(files);const refs = used.filter(Boolean);const 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: [...attachedPictures(files), ...images] }));+ const skillTexts = skillNames.length ? (app.skills?.texts(project.path, agent, skillNames).catch(() => []) ?? Promise.resolve([])) : Promise.resolve([]);+ /* an example pointed at: its folder fetched now if it is not yet (the turn waits, as it waits for its reply) */+ const withFolders = Promise.all(refs.map(async (ref) => (ref.kind === 'example' && !ref.folder+ ? { ...ref, folder: await app.exampleFolder?.(ref.id).catch(() => undefined) } : ref)));+ const prepared = withFolders.then((ready) => Promise.all([referencePictures(ready, { project: project.path, turnId: id }), skillTexts])+ .then(([{ pictures, images }, skills]) => ({+ text: said + studioReferencesText(ready, { stage, pictures }) + skills.map((s) => `\n\n${s.text}`).join(''),+ 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);@@ -639,6 +755,15 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecconst editComposerCard = (<div className="flex flex-col gap-1">+ {contextFull ? (+ <div className="flex items-center gap-2 rounded-[10px] border border-[var(--border)] bg-[var(--surface-2)] py-1.5 pl-3 pr-1.5 text-[12px] text-[var(--text-muted)]">+ <span className="min-w-0 flex-1">{t('composer.contextFull')}</span>+ <button type="button" onClick={onNewSession}+ className="h-6 shrink-0 rounded-[6px] px-2 text-[12px] font-medium text-[var(--text)] transition hover:bg-[var(--bg-hover)]">{t('composer.contextFullNew')}</button>+ <button type="button" onClick={() => setContextNoticeOff(sessionId)} aria-label={t('project.close')}+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded-[6px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"><X size={12} /></button>+ </div>+ ) : null}<div/* a file from the disk dropped on the card is brought along (it goes into the project); Studio's thingsdropped on it become pills */@@ -676,7 +801,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec}`}>{composerFiles.files.length > 0 && (- <div className="flex max-h-[76px] flex-wrap gap-1.5 overflow-y-auto px-3.5 pt-3">+ /* whole rows: up to three show at once (a message's twelve files fit in two), only more than that scrolls */+ <div className="flex max-h-[144px] flex-wrap gap-1.5 overflow-y-auto px-3.5 pt-3">{composerFiles.files.map((file) => {const Icon = attachmentIcon({ name: file.name, mediaType: file.mediaType });const remove = (@@ -693,17 +819,25 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projecconst busy = file.state === 'importing' ? <Loader2 size={12} className="absolute inset-0 m-auto animate-spin text-white drop-shadow" /> : null;/* a picture shows itself; a video, a frame of itself with a play mark (once one is had) */const picture = file.kind === 'image' ? file.previewUrl : file.thumb;+ /* clicked, it opens to look at: a picture large, a video played, a text read */+ const open = file.previewUrl ? {+ role: 'button' as const,+ tabIndex: 0,+ 'aria-label': t('composer.openAttachment').replace('{name}', file.name),+ onClick: () => setOpenedFile({ name: file.name, kind: file.kind, url: file.previewUrl!, ...(file.mediaType ? { mediaType: file.mediaType } : {}) }),+ onKeyDown: (event: React.KeyboardEvent) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); (event.currentTarget as HTMLElement).click(); } },+ } : {};return picture ? (- <div key={file.id} title={file.error ?? file.name}- className={`group relative h-10 w-10 overflow-hidden rounded-[8px] border bg-[var(--surface-2)] transition ${file.state === 'failed' ? 'border-[var(--danger)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}>+ <div key={file.id} title={file.error ?? file.name} {...open}+ className={`group relative h-10 w-10 overflow-hidden rounded-[8px] border bg-[var(--surface-2)] transition ${file.previewUrl ? 'cursor-pointer' : ''} ${file.state === 'failed' ? 'border-[var(--danger)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}><img src={picture} alt={file.name} className={`h-full w-full object-cover transition ${file.state === 'ready' ? '' : 'opacity-45'}`} />{file.kind !== 'image' && !busy ? <PlayMark /> : null}{busy}{remove}</div>) : (- <div key={file.id} title={file.error ?? file.name}- className={`group relative flex h-10 min-w-0 max-w-[150px] items-center gap-1.5 overflow-hidden rounded-[8px] border bg-[var(--surface-2)] py-1 pl-2 pr-5 transition ${file.state === 'failed' ? 'border-[var(--danger)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}>+ <div key={file.id} title={file.error ?? file.name} {...open}+ className={`group relative flex h-10 min-w-0 max-w-[150px] items-center gap-1.5 overflow-hidden rounded-[8px] border bg-[var(--surface-2)] py-1 pl-2 pr-5 transition ${file.previewUrl ? 'cursor-pointer' : ''} ${file.state === 'failed' ? 'border-[var(--danger)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}>{file.state === 'importing' ? <Loader2 size={13} className="shrink-0 animate-spin text-[var(--text-muted)]" /> : <Icon size={13} className="shrink-0 text-[var(--text-muted)]" />}<span className="flex min-w-0 flex-col"><span className="truncate text-[11.5px] leading-tight text-[var(--text-muted)]">{file.name}</span>@@ -715,6 +849,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec})}</div>)}+ {openedFile ? <AttachmentPreview item={openedFile} onClose={() => setOpenedFile(null)} /> : null}<div className="flex items-end gap-1 py-2.5 pl-3.5 pr-2"><div className="min-w-0 flex-1"><PromptEditor@@ -754,7 +889,6 @@ 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"@@ -767,6 +901,14 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec<Plus size={16} strokeWidth={1.75} /></button></Tooltip>+ {app.showExamples ? (+ <Tooltip label={t('community.tooltip')}>+ <button type="button" onClick={() => app.showExamples?.()} className="openfilm-composer-tool" aria-label={t('community.button')}>+ <Blocks size={16} strokeWidth={1.75} />+ </button>+ </Tooltip>+ ) : null}+<Tooltip label={t('project.assets')}><button type="button" onClick={() => app.setAssetsOpen(!assetsOpen)} aria-pressed={assetsOpen} className="openfilm-composer-tool" aria-label={t('project.assets')}><LibraryBig size={16} strokeWidth={1.75} />diff --git a/apps/desktop/chat/src/app-bridge.ts b/apps/desktop/chat/src/app-bridge.tsindex d1fa5f7..cbcbdfc 100644--- a/apps/desktop/chat/src/app-bridge.ts+++ b/apps/desktop/chat/src/app-bridge.ts@@ -2,7 +2,7 @@* The parts of `window.openfilmDesktop` that are this app's own (src/preload-chat.cjs); the parts the copied chat code* uses (localAgents, pathForFile) are typed in lib/desktop-bridge.ts.*/-import type { StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';+import type { CommunityItem, 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) */@@ -29,6 +29,17 @@ interface AppBridge {onFfmpeg(listener: (state: FfmpegState) => void): () => void;/** take the person to a reference in Studio */showInStudio(ref: StudioRef): void;+ /** an example's folder on this computer, fetched when needed (a reference to one, as its message is sent) */+ exampleFolder?(id: string): Promise<string>;+ /** the examples over the film (Studio's), to point at one or a part of one, or name a skill */+ /** the Community over the film; `open`: on that skill's or example's page */+ showExamples?(open?: CommunityItem): void;+ /** a skill picked in the examples, to be named in the message */+ onUseSkill?(listener: (skill: { name: string; description: string }) => void): () => void;+ /** "Add a skill" in the examples */+ onAddSkill?(listener: () => void): () => void;+ /** name a skill in the message being written (as one picked in the examples) */+ useSkill?(skill: { name: string; description: string }): void;/** the reference with its picture: the viewer as it is now, for one that shows it (lib/host.ts StudioRefImage) */withPicture(ref: StudioRef): Promise<StudioRef>;/** light in Studio what a hovered pill points at, without moving there (null: the pointer left it) */@@ -70,12 +81,56 @@ interface AppBridge {/** 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 };+ /** the composer's Skills button (apps/desktop/src/skills-ipc.mjs) */+ skills: {+ list(project: string, agent: string): Promise<SkillListing>;+ /** the skills a message names, as its agent reads each (its folder and its SKILL.md whole) */+ texts(project: string, agent: string, names: string[]): Promise<Array<{ name: string; text: string }>>;+ /** one of the agent's own skills let into OpenFilm, or not */+ allow(agent: string, name: string, allowed: boolean): Promise<{ ok: boolean }>;+ /** a GitHub or GitLab address fetched to be looked at; then kept (`commit`) or let go (`discard`) */+ preview(url: string): Promise<{ ok: true; id: string; skills: SkillPreview[] } | { ok: false; error: string }>;+ /** a folder on this computer looked at where it is: one dropped (its path), or null: picked in the system's dialog+ with these words (cancelled: nothing to show) */+ previewFolder(path: string | null, words?: { title: string; button: string }): Promise<{ ok: true; id: string; skills: SkillPreview[] } | { ok: false; error: string } | { ok: false; cancelled: true }>;+ commit(id: string): Promise<{ ok: true; skills: SkillInfo[] } | { ok: false; error: string }>;+ discard(id: string): Promise<unknown>;+ reveal(): Promise<unknown>;+ };/** 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 }+/** One of OpenFilm's skills: the project's, the person's own, or official (openfilm/src/skills.mjs). */+export interface SkillInfo {+ name: string;+ description: string;+ source: 'project' | 'mine' | 'official';+ folder: string;+ /** what it brings that an agent could run */+ scripts: string[];+ /** the places with a skill of the same name it takes the place of */+ over?: Array<'project' | 'mine' | 'official'>;+ /** how people see it (its openfilm.json): title, summary and who it is for and what it does, by language */+ shown?: { title: Record<string, string>; summary: Record<string, string>; details?: Record<string, string> };+}++/** A skill fetched from an address, before it is kept: `replaces`, one of the person's has its name. */+export interface SkillPreview { name: string; description: string; scripts: string[]; size: number; replaces: boolean }++/** A skill the person installed in their agent themselves, let into OpenFilm or not. */+export interface OwnSkill { name: string; description: string; folder: string; allowed: boolean }++export interface SkillListing {+ openfilm: SkillInfo[];+ /** `filtered`: the agent's own are hidden unless let in; otherwise it has them all, as in its own terminal */+ own: { agent: string; filtered: boolean; skills: OwnSkill[] };+ /** the person's own skills folder */+ mine: string;+}+/** A question about spending, as Studio words it. */export interface SpendAsk { id: string; title: string; body: string | null; allowLabel: string; denyLabel: string }diff --git a/apps/desktop/chat/src/components/AddSkill.tsx b/apps/desktop/chat/src/components/AddSkill.tsxnew file mode 100644index 0000000..90645b8--- /dev/null+++ b/apps/desktop/chat/src/components/AddSkill.tsx@@ -0,0 +1,195 @@+/**+ * Adding a skill to the person's own (apps/desktop/src/skills-ipc.mjs), in a dialog over the window, opened from the+ * Community's skills (Studio's ExamplesGallery, through the app's bridge). Three ways, one under the other: an address+ * pasted (fetched on Enter), a folder (dropped anywhere on the dialog, or picked), or one made with the agent (a+ * message put in the composer; only where there is a project's chat). What came is looked at before it is kept: each+ * skill, its size, the scripts it brings, one of the same name it would replace. Closing before it is kept lets it go.+ */+import React from 'react';+import { createPortal } from 'react-dom';+import { AlertTriangle, ArrowRight, Blocks, Check, ChevronRight, FolderPlus, Loader2, Sparkles, X } from 'lucide-react';+import { keepFocus } from './Popover';+import { useT } from '@/i18n';+import { chatLayer } from '@/lib/chat-layer';+import { app, type SkillInfo, type SkillPreview } from '../app-bridge';++const QUIET_BUTTON = 'h-9 rounded-[9px] px-3.5 text-[13px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40';+const MAIN_BUTTON = 'flex h-9 items-center gap-1.5 rounded-[9px] bg-[var(--text)] px-4 text-[13px] font-medium text-[var(--bg)] transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40';+const LABEL = 'mb-2 text-[11.5px] font-medium text-[var(--text-faint)]';++/** A folder dragged from the file manager, by its path (the desktop app's bridge), or ''. */+const droppedPath = (e: React.DragEvent) => {+ const file = e.dataTransfer.files[0];+ return file ? (window as unknown as { openfilmDesktop?: { pathForFile?: (f: File) => string } }).openfilmDesktop?.pathForFile?.(file) ?? '' : '';+};+const dragsFiles = (e: React.DragEvent) => e.dataTransfer.types.includes('Files');++/** A skill named in a message, as its pill. */+export interface PickedSkill { name: string; description: string }++/** a size as people read it */+const sizeOf = (bytes: number) => (bytes < 1024 * 1024 ? `${Math.max(1, Math.round(bytes / 1024))} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);++export function AddSkillDialog({ onClose, onAdded, onPick, onMake }: {+ onClose: () => void; onAdded: () => Promise<void>;+ /** naming the one added in the message, and making one with the agent: only where there is a message (a project's chat) */+ onPick?: (skill: PickedSkill) => void; onMake?: () => void;+}) {+ const t = useT();+ const [url, setUrl] = React.useState('');+ const [step, setStep] = React.useState<'choose' | 'fetching' | 'look' | 'adding' | 'added'>('choose');+ const [error, setError] = React.useState<string | null>(null);+ const [fetched, setFetched] = React.useState<{ id: string; skills: SkillPreview[] } | null>(null);+ const [added, setAdded] = React.useState<SkillInfo[]>([]);+ const [dragging, setDragging] = React.useState(false);+ const waiting = React.useRef<string | null>(null);++ const letGo = () => {+ if (waiting.current) void app.skills.discard(waiting.current);+ waiting.current = null;+ setFetched(null);+ };+ const close = () => { letGo(); onClose(); };+ /* closed some other way before it was kept: let go */+ React.useEffect(() => () => { if (waiting.current) void app.skills.discard(waiting.current); }, []);+ React.useEffect(() => {+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); close(); } };+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ });++ const look = async (preview: () => ReturnType<typeof app.skills.previewFolder>) => {+ setStep('fetching');+ setError(null);+ const r = await preview().catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e) }));+ if (!r.ok) { if (!('cancelled' in r)) setError(r.error); setStep('choose'); return; }+ waiting.current = r.id;+ setFetched({ id: r.id, skills: r.skills });+ setStep('look');+ };+ const fetchIt = () => { if (url.trim() && step === 'choose') void look(() => app.skills.preview(url.trim())); };+ const pickFolder = () => { if (step === 'choose') void look(() => app.skills.previewFolder(null, { title: t('skills.folderDialog'), button: t('skills.add') })); };+ const keep = async () => {+ if (!fetched) return;+ setStep('adding');+ const r = await app.skills.commit(fetched.id).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e) }));+ waiting.current = null;+ if (!r.ok) { setError(r.error); setStep('choose'); setFetched(null); return; }+ setAdded(r.skills);+ setStep('added');+ await onAdded();+ };++ const scripts = (fetched?.skills ?? []).reduce((n, s) => n + s.scripts.length, 0);+ const replaces = (fetched?.skills ?? []).filter((s) => s.replaces).map((s) => s.name);+ const item = (s: { name: string; description: string }, facts?: string) => (+ <div key={s.name} className="flex items-start gap-3 rounded-[10px] bg-[var(--surface-2)] px-3 py-2.5">+ <span className="mt-[1px] flex h-8 w-8 shrink-0 items-center justify-center rounded-[8px] bg-[var(--bg-surface)] text-[var(--text-dim)]"><Blocks size={15} strokeWidth={1.75} /></span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[13px] font-medium text-[var(--text)]">{s.name}</span>+ {s.description ? <span className="mt-0.5 line-clamp-2 block text-[12px] leading-[17px] text-[var(--text-muted)]">{s.description}</span> : null}+ {facts ? <span className="mt-1 block text-[11.5px] text-[var(--text-faint)]">{facts}</span> : null}+ </span>+ </div>+ );++ let body: React.ReactNode;+ if (step === 'added') {+ body = (+ <>+ <p className="mb-3 flex items-center gap-1.5 text-[13px] text-[var(--text)]"><Check size={15} className="text-[#3ecf8e]" />{t('skills.addedTitle')}</p>+ <div className="flex flex-col gap-2">{added.map((s) => item(s))}</div>+ <div className="mt-5 flex justify-end gap-2">+ <button type="button" onMouseDown={keepFocus} onClick={onClose} className={QUIET_BUTTON}>{t('skills.done')}</button>+ {added.length === 1 && onPick ? <button type="button" onMouseDown={keepFocus} onClick={() => { onPick({ name: added[0]!.name, description: added[0]!.description }); onClose(); }} className={MAIN_BUTTON}>{t('skills.useIt')}</button> : null}+ </div>+ </>+ );+ } else if ((step === 'look' || step === 'adding') && fetched) {+ body = (+ <>+ <div className="flex max-h-[260px] flex-col gap-2 overflow-y-auto">+ {fetched.skills.map((s) => item(s, [sizeOf(s.size), s.scripts.length ? t('skills.scriptsCount').replace('{n}', String(s.scripts.length)) : null].filter(Boolean).join(' · ')))}+ </div>+ {replaces.length ? <p className="mt-3 text-[12px] leading-[17px] text-[var(--text-muted)]">{t('skills.replaceNote').replace('{names}', replaces.join(', '))}</p> : null}+ {scripts ? (+ <p className="mt-3 flex gap-2 rounded-[10px] bg-[var(--surface-2)] px-3 py-2.5 text-[12px] leading-[17px] text-[var(--text-muted)]">+ <AlertTriangle size={14} className="mt-[1px] shrink-0 text-[var(--warn)]" />+ <span>{t('skills.scriptsWarning').replace('{n}', String(scripts))}</span>+ </p>+ ) : null}+ <div className="mt-5 flex justify-end gap-2">+ <button type="button" onMouseDown={keepFocus} onClick={() => { letGo(); setStep('choose'); }} disabled={step === 'adding'} className={QUIET_BUTTON}>{t('skills.cancel')}</button>+ <button type="button" onMouseDown={keepFocus} onClick={() => void keep()} disabled={step === 'adding'} className={MAIN_BUTTON}>+ {step === 'adding' ? <><Loader2 size={13} className="animate-spin" />{t('skills.adding')}</> : t(replaces.length ? 'skills.replaceAndAdd' : 'skills.add')}+ </button>+ </div>+ </>+ );+ } else {+ const busy = step === 'fetching';+ body = (+ <>+ <div className={LABEL}>{t('skills.fromLink')}</div>+ <form onSubmit={(e) => { e.preventDefault(); fetchIt(); }}+ className="flex h-10 items-center gap-1 rounded-[10px] border border-[var(--border)] bg-[var(--surface-2)] pl-3 pr-1 transition focus-within:border-[var(--border-strong)]">+ <input autoFocus value={url} onChange={(e) => { setUrl(e.target.value); setError(null); }} placeholder="https://github.com/…" disabled={busy} spellCheck={false}+ className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]" />+ <button type="submit" disabled={!url.trim() || busy} aria-label={t('skills.next')}+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-[8px] bg-[var(--text)] text-[var(--bg)] transition hover:opacity-90 disabled:bg-transparent disabled:text-[var(--text-faint)]">+ {busy && url.trim() ? <Loader2 size={14} className="animate-spin text-[var(--text-dim)]" /> : <ArrowRight size={15} />}+ </button>+ </form>+ <p className={`mt-1.5 text-[11.5px] leading-[16px] ${error ? 'text-[var(--err)]' : 'text-[var(--text-faint)]'}`}>{error ?? t('skills.addHint')}</p>++ <div className={`${LABEL} mt-5`}>{t('skills.fromFolderTitle')}</div>+ <button type="button" onMouseDown={keepFocus} onClick={pickFolder} disabled={busy}+ className={`flex h-[92px] w-full flex-col items-center justify-center gap-1.5 rounded-[10px] border border-dashed text-center transition disabled:opacity-50+ ${dragging ? 'border-[var(--text-muted)] bg-[var(--bg-hover)]' : 'border-[var(--border-strong)] hover:bg-[var(--bg-hover)]'}`}>+ <FolderPlus size={18} strokeWidth={1.6} className="text-[var(--text-dim)]" />+ <span className="text-[12.5px] text-[var(--text)]">{t('skills.dropHere')}</span>+ <span className="text-[11.5px] text-[var(--text-faint)]">{t('skills.orPick')}</span>+ </button>++ {onMake ? (+ <>+ <div className={`${LABEL} mt-5`}>{t('skills.makeTitle')}</div>+ <button type="button" onMouseDown={keepFocus} onClick={() => { onMake(); onClose(); }} disabled={busy}+ className="flex w-full items-center gap-3 rounded-[10px] border border-[var(--border)] px-3 py-2.5 text-left transition hover:bg-[var(--bg-hover)] disabled:opacity-50">+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-[8px] bg-[var(--surface-2)] text-[var(--text-dim)]"><Sparkles size={15} strokeWidth={1.75} /></span>+ <span className="min-w-0 flex-1">+ <span className="block text-[13px] text-[var(--text)]">{t('skills.make')}</span>+ <span className="block text-[11.5px] leading-[16px] text-[var(--text-muted)]">{t('skills.makeHint')}</span>+ </span>+ <ChevronRight size={15} className="shrink-0 text-[var(--text-faint)]" />+ </button>+ </>+ ) : null}+ </>+ );+ }++ return createPortal(+ <div className="fixed inset-0 z-[10060] grid place-items-center bg-black/45 p-6" onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>+ <div role="dialog" aria-modal="true" aria-label={t('skills.addTitle')}+ className="relative w-[min(440px,calc(100vw-24px))] rounded-[14px] border border-[var(--border-strong)] bg-[var(--bg-surface)] p-5 shadow-[0_24px_64px_rgba(0,0,0,0.4)]"+ onDragOver={(e) => { if (!dragsFiles(e) || step !== 'choose') return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; setDragging(true); }}+ onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDragging(false); }}+ onDrop={(e) => {+ if (!dragsFiles(e)) return;+ e.preventDefault();+ setDragging(false);+ const path = droppedPath(e);+ if (path && step === 'choose') void look(() => app.skills.previewFolder(path));+ }}>+ <div className="mb-4 flex items-center gap-2">+ <h2 className="min-w-0 flex-1 text-[15px] font-semibold text-[var(--text)]">{t('skills.addTitle')}</h2>+ <button type="button" onMouseDown={keepFocus} onClick={close} aria-label={t('skills.cancel')}+ className="flex h-7 w-7 items-center justify-center rounded-[7px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"><X size={15} /></button>+ </div>+ {body}+ </div>+ </div>,+ chatLayer(),+ );+}diff --git a/apps/desktop/chat/src/components/ContextMeter.tsx b/apps/desktop/chat/src/components/ContextMeter.tsxdeleted file mode 100644index fec7ec8..0000000--- a/apps/desktop/chat/src/components/ContextMeter.tsx+++ /dev/null@@ -1,34 +0,0 @@-/**- * 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/ModelPopover.tsx b/apps/desktop/chat/src/components/ModelPopover.tsxindex 50163cf..750208e 100644--- a/apps/desktop/chat/src/components/ModelPopover.tsx+++ b/apps/desktop/chat/src/components/ModelPopover.tsx@@ -39,6 +39,12 @@ const ROW = `${ROW_BASE} hover:bg-[var(--bg-hover)] focus-visible:bg-[var(--bg-htype Option = { id: string; name: string; category?: string; options?: Array<{ value: unknown; name: string; description?: string }> };+/** Why the agent could not be started for its settings, as it said, on a few lines; none when it started and offered none. */+function failureReason(error: { text: string } | undefined): string | null {+ if (!error || error.text === 'no options') return null;+ return error.text.replace(/\s+/g, ' ').trim().slice(0, 400) || null;+}+/** The options the menu offers, in this order: the model, the reasoning effort, the speed (when the model has one). */const isSpeed = (o: Option) => o.category === 'speed' || /^(fast|fast-mode|speed)$/i.test(o.id) || /\b(fast|speed)\b/i.test(o.name);function menuOptions(options: Option[] | undefined): Option[] {@@ -227,7 +233,13 @@ 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, { retry: true })} className="text-[var(--text)] underline underline-offset-2">{t('project.retry')}</button></>+ ? <>+ {la.optionsError[agent]?.code === 'outdated' ? t('composer.agentOutdated') : 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>+ {/* what the agent said, so the person can fix it (a setting it cannot read) or tell us */}+ {failureReason(la.optionsError[agent]) ? (+ <span className="mt-1 line-clamp-4 block select-text break-words text-[11.5px] text-[var(--text-faint)]" title={la.optionsError[agent]?.text}>{failureReason(la.optionsError[agent])}</span>+ ) : null}+ </>: t('composer.agentLoading')}</p>) : rows.map((o, i) => (diff --git a/apps/desktop/chat/src/components/TurnLog.tsx b/apps/desktop/chat/src/components/TurnLog.tsxindex 734a1c6..22dbd8d 100644--- a/apps/desktop/chat/src/components/TurnLog.tsx+++ b/apps/desktop/chat/src/components/TurnLog.tsx@@ -2,10 +2,14 @@* A turn's log, as the app wrote it while it ran (src/chat-store.mjs), shown in developer mode (Settings → Developer)* from a turn's footer.*- * Model requests (the app's own agent, Pi): each request it made to its model, whole — the system prompt, every- * message (the person's, its own with its thinking and tool calls, each tool's result), the tools — and the answer,- * 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.+ * Model requests: each request the agent made to its model, whole — the system prompt, every message (the person's,+ * its own with its thinking and tool calls, each tool's result, and what the agent put in by itself), the tools — and+ * the answer, with the model, provider and thinking level that made it, its tokens, or its error. The app's own agent+ * (Pi) logs its own; the others' come from their own records, or from the logs they are started with in Developer+ * mode, and what such a log lacks is said beside it. The messages new in that request are open;+ * the ones carried over from before, and the system prompt, are one line each until opened.+ * Sent to the agent: what the app started and opened the agent with (every word it adds to the agent's own, the+ * variables it set), and each message exactly as the agent got it.* 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.@@ -22,6 +26,7 @@ import { BrandLogo } from './BrandLogo';type LogEvent = TurnLogData['events'][number];type T = (key: string) => string;+type Tab = 'calls' | 'sent' | 'events';export function TurnLogButton({ project, turnId, live = false }: { project: string; turnId: string; live?: boolean }) {const t = useT();@@ -38,7 +43,17 @@ export function TurnLogButton({ project, turnId, live = false }: { project: stri);}-const seconds = (ms: number) => (ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}:${String(Math.round((ms % 60_000) / 1000)).padStart(2, '0')}`);+/** the agents started with a logging switch in Developer mode (src/agent-logs.mjs) */+const LOGGED_AGENTS = ['gemini', 'qwen', 'codebuddy', 'opencode'];++/** Why a turn has no model requests, as its agent and what it was started with say. */+function noCallsReason(agent: string | null, log: Item | null | undefined): string {+ if (agent === 'cursor') return 'turnLog.noCallsCursor';+ if (agent && LOGGED_AGENTS.includes(agent)) return log?.none === 'own' ? 'turnLog.logOwn' : log?.none === 'sendsMore' ? 'turnLog.logSendsMore' : log ? 'turnLog.noCalls' : 'turnLog.logOff';+ return 'turnLog.noCalls';+}++const seconds = (ms: number | null) => (ms === null ? '—' : ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}:${String(Math.round((ms % 60_000) / 1000)).padStart(2, '0')}`);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));@@ -48,7 +63,7 @@ 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 [tab, setTab] = React.useState<Tab | null>(null);const [copied, setCopied] = React.useState(false);const load = React.useCallback(() => {void app.chat.log(project, turnId).then((next) => setLog(next && 'same' in next ? undefined : next)).catch(() => setLog(null));@@ -77,7 +92,8 @@ function TurnLogViewer({ project, turnId, live, onClose }: { project: string; tuconst events = log?.events ?? [];const calls = React.useMemo(() => modelCalls((log?.calls ?? []) as RawCall[]), [log]);- const shownTab = tab ?? (calls.length ? 'calls' : 'events');+ const sent = events.filter((e) => e.kind === 'prompt' || e.kind === 'sent' || e.kind === 'steer');+ const shownTab = tab ?? (calls.length ? 'calls' : 'sent');const prompt = events.find((e) => e.kind === 'prompt') as Record<string, any> | undefined;const done = [...events].reverse().find((e) => e.kind === 'done') as Record<string, any> | undefined;const agent = typeof prompt?.agent === 'string' ? prompt.agent : null;@@ -89,10 +105,10 @@ function TurnLogViewer({ project, turnId, live, onClose }: { project: string; tu}, { input: 0, cached: 0, output: 0 });const copy = () => {- void navigator.clipboard?.writeText(JSON.stringify(shownTab === 'calls' ? calls : events, null, 2)).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); });+ void navigator.clipboard?.writeText(JSON.stringify(shownTab === 'calls' ? calls : shownTab === 'sent' ? sent : events, null, 2)).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); });};const button = 'flex h-8 items-center gap-1.5 rounded-[8px] border border-[var(--border)] px-2.5 text-[12.5px] text-[var(--chat-text)] transition hover:bg-[var(--bg-hover)]';- const tabButton = (id: 'calls' | 'events', label: string) => (+ const tabButton = (id: Tab, label: string) => (<button type="button" onClick={() => setTab(id)}className={`h-9 border-b-2 px-1 text-[13px] transition ${shownTab === id ? 'border-[var(--chat-text)] text-[var(--chat-text)]' : 'border-transparent text-[var(--chat-hint)] hover:text-[var(--chat-text)]'}`}>{label}@@ -141,12 +157,13 @@ function TurnLogViewer({ project, turnId, live, onClose }: { project: string; tu<><div className="flex shrink-0 items-center gap-4 border-b border-[var(--border)] px-5">{tabButton('calls', fill(t('turnLog.calls'), { n: calls.length }))}+ {tabButton('sent', t('turnLog.sentTab'))}{tabButton('events', fill(t('turnLog.events'), { n: events.length }))}{log.cut ? <span className="text-[12px] text-[var(--warn)]">{t('turnLog.cut')}</span> : null}</div>{shownTab === 'calls'- ? (calls.length ? <Calls calls={calls} start={prompt?.t ?? calls[0]!.startedAt} t={t} /> : <p className="px-5 py-4 text-[13px] text-[var(--chat-hint)]">{t('turnLog.noCalls')}</p>)- : <Events events={events} t={t} />}+ ? (calls.length ? <Calls calls={calls} start={prompt?.t ?? calls[0]!.startedAt} t={t} /> : <p className="px-5 py-4 text-[13px] text-[var(--chat-hint)]">{t(noCallsReason(agent, prompt?.opened?.log))}</p>)+ : shownTab === 'sent' ? <Sent events={sent} t={t} /> : <Events events={events} t={t} />}</>)}</div>@@ -164,6 +181,7 @@ const ROLE_COLOR: Record<string, string> = {user: 'text-[#3f8fd0]',assistant: 'text-[#4aa36c]',toolResult: 'text-[#a26bd6]',+ context: 'text-[#c0603a]',};const block = 'whitespace-pre-wrap break-words font-mono text-[12px] leading-[1.55] text-[var(--chat-text)]';@@ -195,7 +213,7 @@ function Parts({ message, t }: { message: Item; t: T }) {if (part.type === 'thinking') {return (<details key={i}>- <summary className="cursor-pointer text-[12px] text-[var(--chat-hint)]">{t('turnLog.thought')} · {fill(t('turnLog.chars'), { n: String(part.thinking ?? '').length.toLocaleString() })}</summary>+ <summary className="cursor-pointer text-[12px] text-[var(--chat-hint)]">{t('turnLog.thought')} · {part.thinking ? fill(t('turnLog.chars'), { n: String(part.thinking).length.toLocaleString() }) : t('turnLog.thoughtNotKept')}</summary><div className="mt-1 italic"><Clamped text={String(part.thinking ?? '')} t={t} /></div></details>);@@ -226,6 +244,8 @@ function MessageRow({ message, index, fresh, open: initial, t }: { message: Item<ChevronRight size={12} className={`shrink-0 text-[var(--text-faint)] transition-transform ${open ? 'rotate-90' : ''}`} /><span className="w-6 shrink-0 tabular-nums text-[var(--text-faint)]">{index}</span><b className={`shrink-0 font-semibold ${failed ? 'text-[var(--err)]' : ROLE_COLOR[role] ?? 'text-[var(--chat-hint)]'}`}>{role === 'toolResult' ? String(message.toolName ?? 'tool') : role}</b>+ {role === 'context' || message.label ? <span className="shrink-0 font-mono text-[11px] text-[var(--chat-hint)]" title={t('turnLog.contextHint')}>{[message.label, message.as ? `as ${message.as}` : null].filter(Boolean).join(' · ')}</span> : null}+ {message.meta ? <span className="shrink-0 font-mono text-[11px] text-[var(--chat-hint)]">meta</span> : null}{fresh ? <span className="shrink-0 rounded-[4px] bg-[var(--bg-hover)] px-1 text-[10.5px] text-[var(--chat-text)]">{t('turnLog.fresh')}</span> : null}{message.toolCallId ? <span className="shrink-0 font-mono text-[11px] text-[var(--text-faint)]">{String(message.toolCallId)}</span> : null}<span className={`min-w-0 flex-1 truncate ${open ? 'invisible' : 'text-[var(--chat-hint)]'}`}>{text.replace(/\s+/g, ' ').slice(0, 200)}</span>@@ -264,6 +284,7 @@ function Calls({ calls, start, t }: { calls: ModelCall[]; start: number; t: T })<b className={`text-[12.5px] ${error ? 'text-[var(--err)]' : 'text-[var(--chat-text)]'}`}>#{c.no}</b><span className="tabular-nums text-[var(--text-faint)]">+{seconds(c.startedAt - start)} · {seconds(c.ms)}</span></div>+ {c.thread ? <div className="mt-0.5 truncate text-[11px] text-[#c0603a]">{c.thread.label}</div> : null}<div className="mt-0.5 truncate text-[var(--chat-hint)]">{error ? <span className="text-[var(--err)]">{String(c.answer?.errorMessage ?? '')}</span>: asked.length ? `→ ${asked.join(', ')}` : t('turnLog.answered')}@@ -276,15 +297,22 @@ function Calls({ calls, start, t }: { calls: ModelCall[]; start: number; t: T })<div className="min-w-0 flex-1 overflow-y-auto px-5 py-3"><div className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-[var(--chat-hint)]"><b className="text-[13px] text-[var(--chat-text)]">#{call.no}</b>+ {call.thread ? <span className="text-[#c0603a]">{call.thread.label}</span> : null}{facts.map((f, i) => <span key={i}>{f}</span>)}<span className="tabular-nums">{fill(t('turnLog.tokens'), { input: u.input.toLocaleString(), cached: u.cached.toLocaleString(), output: u.output.toLocaleString() })}{u.reasoning ? ` (${fill(t('turnLog.reasoningTokens'), { n: u.reasoning.toLocaleString() })})` : ''}</span><span className="tabular-nums">{seconds(call.ms)}</span><span className="flex-1" /><button type="button" className={small} onClick={() => setRaw((r) => !r)}>{raw ? t('turnLog.readable') : 'JSON'}</button></div>+ {call.source ? (+ <div className="-mt-1.5 mb-3 truncate text-[11.5px] text-[var(--text-faint)]" title={call.source.file}>+ {fill(t('turnLog.fromRecord'), { file: call.source.file })}+ </div>+ ) : null}+ {call.lacks.map((name) => <p key={name} className="-mt-1.5 mb-3 text-[12px] text-[var(--chat-hint)]">{t(`turnLog.lacks.${name}`)}</p>)}{raw ? (<pre className={`${block} rounded-[8px] border border-[var(--border)] bg-[var(--surface-2)] p-3`}>- {JSON.stringify({ request: { systemPrompt: call.systemPrompt, messages: call.messages, tools: call.tools }, answer: call.answer }, null, 2)}+ {JSON.stringify({ request: { systemPrompt: call.systemPrompt, messages: call.messages, tools: call.tools, ...(call.settings ? { settings: call.settings } : {}) }, answer: call.answer }, null, 2)}</pre>) : (<div className="space-y-5">@@ -316,14 +344,26 @@ function Calls({ calls, start, t }: { calls: ModelCall[]; start: number; t: T })</div></section><section>- <details>- <summary className="cursor-pointer text-[12.5px] font-semibold text-[var(--chat-text)]">{fill(t('turnLog.rest'), { n: tools.length })}</summary>- <div className="mt-2 space-y-2">- <div className="text-[12px] text-[var(--chat-hint)]">{tools.map((tool) => tool.name).join(', ')}</div>- <pre className={`${block} max-h-[480px] overflow-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface-2)] p-3`}>{JSON.stringify(call.tools, null, 2)}</pre>- </div>- </details>+ {call.tools ? (+ <details>+ <summary className="cursor-pointer text-[12.5px] font-semibold text-[var(--chat-text)]">{fill(t('turnLog.rest'), { n: tools.length })}</summary>+ <div className="mt-2 space-y-2">+ <div className="text-[12px] text-[var(--chat-hint)]">{tools.map((tool) => tool.name).join(', ')}</div>+ <pre className={`${block} max-h-[480px] overflow-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface-2)] p-3`}>{JSON.stringify(call.tools, null, 2)}</pre>+ </div>+ </details>+ ) : (+ <p className="text-[12.5px] text-[var(--chat-hint)]">{t(call.toolsUnknown ? 'turnLog.toolsUnknown' : 'turnLog.toolsMissing')}</p>+ )}</section>+ {call.settings ? (+ <section>+ <details>+ <summary className="cursor-pointer text-[12.5px] font-semibold text-[var(--chat-text)]">{t('turnLog.settings')}</summary>+ <pre className={`${block} mt-2 max-h-[480px] overflow-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface-2)] p-3`}>{JSON.stringify(call.settings, null, 2)}</pre>+ </details>+ </section>+ ) : null}</div>)}</div>@@ -331,6 +371,95 @@ function Calls({ calls, start, t }: { calls: ModelCall[]; start: number; t: T }));}+/* ── sent to the agent ──────────────────────────────────────────────────────── */++/** A message's blocks as the agent got them: text, pictures (kept by file), anything else as it was. */+function SentBlocks({ blocks, t }: { blocks: Item[]; t: T }) {+ return (+ <div className="space-y-2">+ {blocks.map((b, i) => (b?.type === 'text' ? <Clamped key={i} text={String(b.text ?? '')} max={20000} t={t} />+ : b?.type === 'image' ? (+ <div key={i} className="font-mono text-[12px] text-[var(--chat-hint)]">+ {fill(t('turnLog.picture'), { type: String(b.mimeType ?? ''), size: k(Number(b.bytes) || 0) })}{b.file ? ` · ${String(b.file)}` : ''}+ </div>+ ) : <Clamped key={i} text={pretty(b)} t={t} />))}+ </div>+ );+}++/** How a session's skills and MCP servers were set (agent-skills.mjs `log`): OpenFilm's, and the person's own hidden or let in. */+function skillsLines(skills: Item, t: T): string[] {+ const list = (v: unknown) => (Array.isArray(v) && v.length ? v.join(', ') : '—');+ return [+ `${t('turnLog.skillsOpenfilm')}: ${list(skills.openfilm)}`,+ skills.filtered ? `${t('turnLog.skillsHidden')}: ${list(skills.hidden)}` : t('turnLog.skillsUnfiltered'),+ ...(skills.mcpFiltered ? [`${t('turnLog.mcpHidden')}: ${list(skills.mcpHidden)}`] : []),+ ...([...(skills.allowed ?? []), ...(skills.mcpAllowed ?? [])].length ? [`${t('turnLog.letIn')}: ${list([...(skills.allowed ?? []), ...(skills.mcpAllowed ?? [])])}`] : []),+ ];+}++function Labeled({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="grid grid-cols-[180px_minmax(0,1fr)] gap-3 border-t border-[var(--border)] py-2 first:border-t-0">+ <div className="text-[12px] text-[var(--chat-hint)]">{label}</div>+ <div className="min-w-0">{children}</div>+ </div>+ );+}++function Sent({ events, t }: { events: LogEvent[]; t: T }) {+ const prompt = events.find((e) => e.kind === 'prompt') as Item | undefined;+ const opened = prompt?.opened as Item | null | undefined;+ const messages = events.filter((e) => e.kind === 'sent' || e.kind === 'steer') as Item[];+ const start = prompt?.t ?? 0;+ const heading = 'mb-2 text-[12.5px] font-semibold text-[var(--chat-text)]';+ const appended = opened?.session?.params?._meta?.systemPrompt?.append;+ const developer = opened?.codexConfig?.developer_instructions;+ return (+ <div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-5 py-4">+ <section>+ <div className={heading}>{t('turnLog.opened')}</div>+ {!opened ? <p className="text-[12.5px] text-[var(--chat-hint)]">{t('turnLog.noOpened')}</p> : (+ <div className="rounded-[8px] border border-[var(--border)] px-3">+ <Labeled label={t('turnLog.program')}>+ <div className={block}>{(opened.command ?? [opened.program]).join(' ')}{opened.adapter ? `\n${fill(t('turnLog.through'), { adapter: String(opened.adapter) })}` : ''}</div>+ </Labeled>+ {typeof appended === 'string' ? <Labeled label={t('turnLog.appended')}><Clamped text={appended} max={20000} t={t} /></Labeled> : null}+ {typeof developer === 'string' ? <Labeled label={t('turnLog.developer')}><Clamped text={developer} max={20000} t={t} /></Labeled> : null}+ {typeof opened.firstMessage === 'string' ? <Labeled label={t('turnLog.firstMessage')}><Clamped text={opened.firstMessage} max={20000} t={t} /></Labeled> : null}+ {opened.skills ? <Labeled label={t('turnLog.skills')}><div className={block}>{skillsLines(opened.skills, t).join('\n')}</div></Labeled> : null}+ <Labeled label={t('turnLog.session')}><Clamped text={pretty(opened.session ?? null)} t={t} /></Labeled>+ <Labeled label={t('turnLog.env')}><Clamped text={pretty({ ...opened.env, PATH: opened.path, fromShell: opened.fromShell })} t={t} /></Labeled>+ <Labeled label={t('turnLog.handshake')}>+ <details>+ <summary className="cursor-pointer text-[12px] text-[var(--chat-hint)]">initialize</summary>+ <div className="mt-1"><Clamped text={pretty(opened.initialize ?? null)} t={t} /></div>+ </details>+ </Labeled>+ </div>+ )}+ </section>+ <section>+ <div className={heading}>{fill(t('turnLog.messages'), { n: messages.length })}</div>+ {messages.length === 0 ? <p className="text-[12.5px] text-[var(--chat-hint)]">{t('turnLog.noSent')}</p> : (+ <div className="space-y-2">+ {messages.map((m, i) => (+ <div key={i} className="rounded-[8px] border border-[var(--border)] px-3 py-2">+ <div className="mb-1.5 flex gap-2 text-[12px] text-[var(--chat-hint)]">+ <b className="text-[var(--chat-text)]">{t(m.kind === 'steer' ? 'turnLog.steered' : 'turnLog.message')}</b>+ <span className="tabular-nums">+{seconds(m.t - start)}</span>+ {m._meta ? <span className="font-mono">_meta {JSON.stringify(m._meta)}</span> : null}+ </div>+ <SentBlocks blocks={(m.prompt ?? [{ type: 'text', text: m.text }]) as Item[]} t={t} />+ </div>+ ))}+ </div>+ )}+ </section>+ </div>+ );+}+/* ── events ────────────────────────────────────────────────────────────────── *//** a line of the log as shown: one event, or a run of text pieces joined */@@ -369,6 +498,7 @@ 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 'sent': return { kind: 'prompt', label: 'sent', summary: str(((event.prompt ?? []) as Item[]).map((b) => (b?.type === 'text' ? b.text : `[${b?.type}]`)).join(' '), 600) };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: '' };diff --git a/apps/desktop/chat/src/components/prompt-editor/PromptPill.tsx b/apps/desktop/chat/src/components/prompt-editor/PromptPill.tsxindex 6adce6c..093618d 100644--- a/apps/desktop/chat/src/components/prompt-editor/PromptPill.tsx+++ b/apps/desktop/chat/src/components/prompt-editor/PromptPill.tsx@@ -12,7 +12,7 @@import React from 'react';import {- Blocks, Brackets, Captions, Clock3, Crop, Film, Mic, MousePointer2, Music, Paperclip,+ Blocks, Brackets, Captions, Clapperboard, Clock3, Crop, Film, Mic, MousePointer2, Music, Paperclip,Quote, Rows3, Shapes, SquareDashed, Video, Waves,} from 'lucide-react';import {@@ -43,6 +43,8 @@ export const PILL_ICON: Record<PromptReferenceKind, React.ComponentType<{ size?:/* A skill: blocks, a piece of craft inserted into the sentence. Other pills point atthings in the film; this one points at a way of working. */skill: Blocks,+ /* An example film (another film, not this one): a clapperboard. */+ example: Clapperboard,/* Timeline clips: the icon follows the clip's kind on the timeline, so the pillmatches the clip the user just picked. */clipMg: Shapes,@@ -100,13 +102,16 @@ const REVEALABLE_PILL_KINDS = new Set<string>([* what it points at (`target`), such as a file dragged in from Studio's assets.*/export function canRevealPill(reference: StoredPromptReference): boolean {- return Boolean(reference.target) || REVEALABLE_PILL_KINDS.has(reference.kind);+ /* a skill opens on its page in the Community */+ return Boolean(reference.target) || REVEALABLE_PILL_KINDS.has(reference.kind) || reference.kind === 'skill';}/** A pill's hover card: what it is, and label/value rows (already translated by the host). */export interface PromptPillCard {title: string;rows: Array<[string, string]>;+ /** paragraphs under the title: what a skill or an example is, as its page says */+ text?: string[];}type PillImage = NonNullable<StoredPromptReference['image']>;@@ -194,11 +199,12 @@ function PillCardPicture({ image }: { image: PillImage }) {function PillCardBody({ card, image, hint }: { card?: PromptPillCard | null; image?: PillImage | null; hint?: string }) {return (- <div className="flex w-[240px] flex-col gap-1.5 whitespace-normal py-0.5 text-left">+ <div className={`flex flex-col gap-1.5 whitespace-normal py-0.5 text-left ${card?.text?.length ? 'w-[300px]' : 'w-[240px]'}`}>{image ? <PillCardPicture image={image} /> : null}{card ? (<><div className="text-[11.5px] font-semibold">{card.title}</div>+ {card.text?.map((line, index) => <p key={index} className="text-[11.5px] font-normal leading-[17px] opacity-80">{line}</p>)}{card.rows.length ? (<dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-0.5 text-[11px] font-normal leading-snug">{card.rows.map(([label, value], index) => (diff --git a/apps/desktop/chat/src/components/prompt-editor/prompt-text.ts b/apps/desktop/chat/src/components/prompt-editor/prompt-text.tsindex a796b5b..f11b242 100644--- a/apps/desktop/chat/src/components/prompt-editor/prompt-text.ts+++ b/apps/desktop/chat/src/components/prompt-editor/prompt-text.ts@@ -43,7 +43,7 @@ export interface PromptReference extends StoredPromptReference {* a voice line in one sentence look different.*/export type PromptReferenceKind =- | 'element' | 'region' | 'time' | 'range' | 'track' | 'subtitle' | 'showcase' | 'file' | 'card' | 'skill'+ | 'element' | 'region' | 'time' | 'range' | 'track' | 'subtitle' | 'showcase' | 'file' | 'card' | 'skill' | 'example'| 'clipMg' | 'clipVideo' | 'clipVoice' | 'clipSfx' | 'clipMusic' | 'clipCaption';/* The id prefix of a file reference, followed by the workspace-relative path, which isdiff --git a/apps/desktop/chat/src/i18n/locales/en-US.ts b/apps/desktop/chat/src/i18n/locales/en-US.tsindex b1798d2..781dbfc 100644--- a/apps/desktop/chat/src/i18n/locales/en-US.ts+++ b/apps/desktop/chat/src/i18n/locales/en-US.ts@@ -120,13 +120,15 @@ export const enUS = {previewFailed: 'This file could not be read',},composer: {+ contextFull: 'This conversation is getting long. A new one will work better.',+ contextFullNew: 'New conversation',commands: 'Commands',- context: 'Context {percent}% full · {used} of {size} tokens',agentLoading: 'Loading…',agentNone: 'Agent',agentNoneShown: 'No agent is switched on for the chat.',agentNotFound: 'Not found',agentOptionsFailed: 'Couldn\'t start it to read its settings.',+ agentOutdated: 'It is older than OpenFilm needs. Update Codex, then',agentOwnKey: 'Your own key',agentPermissionDeny: 'Don’t allow',agentPermissionTitle: '{name} wants to do this',@@ -169,6 +171,7 @@ export const enUS = {track: 'Track',file: 'File',subtitle: 'Subtitle',+ example: 'Example film',},clip: 'Clip',file: 'File',@@ -188,6 +191,8 @@ export const enUS = {length: 'Length',language: 'Language',line: 'Line',+ example: 'Example',+ part: 'Part',},project: {assets: 'Assets',@@ -254,28 +259,85 @@ export const enUS = {skipped: 'Skipped — it carried on with its own call',timedOut: 'No answer in time — it carried on with its own call',},+ /* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */+ community: { button: 'Community', tooltip: 'Community: skills and examples' },+ skills: {+ button: 'Skills',+ addTitle: 'Add a skill',+ addHint: 'Paste the address of a skill, or a folder of skills, on GitHub or GitLab.',+ add: 'Add',+ adding: 'Adding…',+ scriptsWarning: 'It brings {n} scripts the agent can run. Add only skills you trust.',+ done: 'Done',+ useIt: 'Use in message',+ cardDoes: 'What it does',+ next: 'Next',+ cancel: 'Cancel',+ replaceNote: 'You have {names} already: adding it moves the old one to the trash.',+ replaceAndAdd: 'Replace and add',+ scriptsCount: '{n} scripts',+ fromLink: 'From a link',+ folderDialog: 'Add Skills from a Folder',+ make: 'Make one with the agent',+ makeHint: 'It writes down how something was made, into Yours.',+ makePrompt: 'Turn what we did in this conversation into an OpenFilm skill: a folder with a SKILL.md (its name, a description of when to use it, then the steps), saved in {folder}. First tell me what it will cover and what to name it; save it once I agree.',+ fromFolderTitle: 'From a folder',+ dropHere: 'Drop a skill folder here',+ orPick: 'or click to choose one',+ makeTitle: 'Make your own',+ addedTitle: 'Added to your skills',+ },turnLog: {+ thoughtNotKept: 'not kept in the agent\'s record',+ skills: 'Skills and MCP',+ skillsOpenfilm: 'OpenFilm\'s skills',+ skillsHidden: 'Your own skills, off',+ skillsUnfiltered: 'This agent has all your own skills, as in its own app',+ mcpHidden: 'Your own MCP servers, off',+ letIn: 'Let in',answered: 'Answered',+ appended: 'Added to its system prompt',callCount: '{n} requests',calls: 'Model requests {n}',chars: '{n} chars',close: 'Close',collapseAll: 'Collapse all',+ contextHint: 'Put in by the agent itself, not written by you',copied: 'Copied',copy: 'Copy as JSON',cut: 'A long log: these are its last events.',+ developer: 'Codex developer instructions (yours first, then the app\'s)',ended: 'Ended',+ env: 'Variables the app set',events: '{n} events',expandAll: 'Expand all',failed: 'Failed',filter: 'Filter events',+ firstMessage: 'Before the first message',fresh: 'new',+ fromRecord: 'Read from the agent\'s own record: {file}',+ handshake: 'Handshake',joined: 'Join text pieces',+ lacks: {+ copilotRebuilt: 'Rebuilt from Copilot\'s own record: it keeps no tool definitions, and its messages are as it recorded them, not the bytes it sent.',+ opencodeBeforeProvider: 'From OpenCode\'s telemetry: the request as OpenCode handed it to its AI SDK, before the provider\'s last changes (cache marks and the like).',+ },loading: 'Reading the log…',- noCalls: 'No model requests here: only the app\'s own agent (your own key) logs them.',+ logOff: 'This agent\'s requests are logged only in sessions started while Developer mode is on: a new conversation has them.',+ logOwn: 'You set this agent\'s own telemetry or logging, so the app left it as it is and has no log of its requests.',+ logSendsMore: 'CodeBuddy sends its traces to its makers, and with its requests logged each trace would name the request\'s file. The app logs them only when that is off: set DISABLE_TELEMETRY=1 in your shell.',+ message: 'Message',+ messages: 'Messages, as the agent got them · {n}',+ noCalls: 'No model requests here: this agent keeps no record of them that the app can read.',+ noCallsCursor: 'Cursor makes its prompt on its own servers, so what its model got is not on this computer.',noMatch: 'No events match',+ noOpened: 'This turn was logged before the app kept what it started the agent with.',+ noSent: 'No message was logged whole for this turn.',none: 'No log for this turn: it ran before turns were logged.',open: 'Log',+ opened: 'Started and opened with',+ picture: 'Picture · {type} · {size} bytes',+ program: 'Program',readable: 'Readable',reasoningTokens: '{n} thinking',refresh: 'Refresh',@@ -284,10 +346,17 @@ export const enUS = {reveal: 'Show in folder',running: 'Running',sent: 'What the model got · {n} messages, {fresh} new',+ sentTab: 'Sent to the agent',+ session: 'Session',+ settings: 'Turn settings',showAll: 'Show all ({n} chars)',+ steered: 'Sent while it worked',thought: 'Thinking',+ through: 'through {adapter}',title: 'Turn log',tokens: 'in {input} (cached {cached}) · out {output}',+ toolsMissing: 'The record has no tool definitions for this request.',+ toolsUnknown: 'Codex does not keep its tools\' definitions in its record.',},turnFrame: {background: 'A background task finished; the agent went on',diff --git a/apps/desktop/chat/src/i18n/locales/es.ts b/apps/desktop/chat/src/i18n/locales/es.tsindex 56539ea..4ce78a6 100644--- a/apps/desktop/chat/src/i18n/locales/es.ts+++ b/apps/desktop/chat/src/i18n/locales/es.ts@@ -121,13 +121,15 @@ export const es: Words = {previewFailed: 'No se pudo leer este archivo',},composer: {+ contextFull: 'Esta conversación ya es larga. Una nueva funcionará mejor.',+ contextFullNew: 'Nueva conversación',commands: 'Comandos',- context: 'Contexto al {percent}% · {used} de {size} tokens',agentLoading: 'Cargando…',agentNone: 'Agente',agentNoneShown: 'No hay ningún agente activado para el chat.',agentNotFound: 'No encontrado',agentOptionsFailed: 'No se pudo iniciar para leer su configuración.',+ agentOutdated: 'Es más antigua de lo que OpenFilm necesita. Actualiza Codex y luego',agentOwnKey: 'Tu propia clave',agentPermissionDeny: 'No permitir',agentPermissionTitle: '{name} quiere hacer esto',@@ -169,6 +171,7 @@ export const es: Words = {track: 'Pista',file: 'Archivo',subtitle: 'Subtítulo',+ example: 'Película de ejemplo',},clip: 'Clip',file: 'Archivo',@@ -188,6 +191,8 @@ export const es: Words = {length: 'Duración',language: 'Idioma',line: 'Línea',+ example: 'Ejemplo',+ part: 'Parte',},project: {assets: 'Recursos',@@ -254,28 +259,85 @@ export const es: Words = {skipped: 'Omitida: siguió con su propio criterio',timedOut: 'No hubo respuesta a tiempo: siguió con su propio criterio',},+ /* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */+ community: { button: 'Comunidad', tooltip: 'Comunidad: skills y ejemplos' },+ skills: {+ button: 'Skills',+ addTitle: 'Añadir una skill',+ addHint: 'Pega la dirección de una skill, o de una carpeta de skills, en GitHub o GitLab.',+ add: 'Añadir',+ adding: 'Añadiendo…',+ scriptsWarning: 'Incluye {n} scripts que el agente puede ejecutar. Añade solo skills de confianza.',+ done: 'Listo',+ useIt: 'Usar en el mensaje',+ cardDoes: 'Para qué sirve',+ next: 'Siguiente',+ cancel: 'Cancelar',+ replaceNote: 'Ya tienes {names}: al añadirla, la anterior va a la papelera.',+ replaceAndAdd: 'Reemplazar y añadir',+ scriptsCount: '{n} scripts',+ fromLink: 'Desde un enlace',+ folderDialog: 'Añadir skills desde una carpeta',+ make: 'Hacer una con el agente',+ makeHint: 'Pone por escrito cómo se hizo algo, en Tuyas.',+ makePrompt: 'Convierte lo que hicimos en esta conversación en una skill de OpenFilm: una carpeta con un SKILL.md (su nombre, una descripción de cuándo usarla y luego los pasos), guardada en {folder}. Primero dime qué cubrirá y cómo se llamará; guárdala cuando yo esté de acuerdo.',+ fromFolderTitle: 'Desde una carpeta',+ dropHere: 'Suelta aquí una carpeta de skill',+ orPick: 'o haz clic para elegirla',+ makeTitle: 'Hazla tú',+ addedTitle: 'Añadida a tus skills',+ },turnLog: {+ thoughtNotKept: 'no se guarda en el registro del agente',+ skills: 'Skills y MCP',+ skillsOpenfilm: 'Skills de OpenFilm',+ skillsHidden: 'Tus skills, desactivadas',+ skillsUnfiltered: 'Este agente usa todas tus skills, como en su propia app',+ mcpHidden: 'Tus servidores MCP, desactivados',+ letIn: 'Permitidos',answered: 'Respondida',+ appended: 'Añadido a su system prompt',callCount: '{n} solicitudes',calls: 'Solicitudes al modelo {n}',chars: '{n} caracteres',close: 'Cerrar',collapseAll: 'Contraer todo',+ contextHint: 'Lo añadió el propio agente; no lo escribiste tú',copied: 'Copiado',copy: 'Copiar como JSON',cut: 'Registro largo: estos son sus últimos eventos.',+ developer: 'Developer instructions de Codex (primero las tuyas, luego las de la app)',ended: 'Terminado',+ env: 'Variables que puso la app',events: '{n} eventos',expandAll: 'Expandir todo',failed: 'Falló',filter: 'Filtrar eventos',+ firstMessage: 'Antes del primer mensaje',fresh: 'nuevo',+ fromRecord: 'Leído del registro del propio agente: {file}',+ handshake: 'Handshake',joined: 'Unir fragmentos de texto',+ lacks: {+ copilotRebuilt: 'Reconstruido a partir del propio registro de Copilot: no guarda las definiciones de herramientas, y los mensajes son como los registró, no los bytes que envió.',+ opencodeBeforeProvider: 'De la telemetría de OpenCode: la solicitud tal como OpenCode la pasó a su AI SDK, antes de los últimos cambios del proveedor (marcas de caché y similares).',+ },loading: 'Leyendo el registro…',- noCalls: 'No hay solicitudes al modelo: solo el agente propio de la app (tu propia clave) las registra.',+ logOff: 'Las solicitudes de este agente solo se registran en sesiones iniciadas con el modo Desarrollador activado: una conversación nueva las tendrá.',+ logOwn: 'Configuraste tú la telemetría o el registro de este agente, así que la app lo dejó como está y no tiene registro de sus solicitudes.',+ logSendsMore: 'CodeBuddy envía sus trazas a sus creadores, y con las solicitudes registradas cada traza nombraría el archivo de la solicitud. La app solo las registra cuando eso está desactivado: define DISABLE_TELEMETRY=1 en tu shell.',+ message: 'Mensaje',+ messages: 'Mensajes, tal como los recibió el agente · {n}',+ noCalls: 'No hay solicitudes al modelo: este agente no guarda un registro que la app pueda leer.',+ noCallsCursor: 'Cursor crea su prompt en sus propios servidores, así que lo que recibió su modelo no está en este equipo.',noMatch: 'Ningún evento coincide',+ noOpened: 'Este turno se registró antes de que la app guardara con qué inicia al agente.',+ noSent: 'En este turno no se registró completo ningún mensaje enviado.',none: 'Este turno no tiene registro: se ejecutó antes de que se registraran los turnos.',open: 'Registro',+ opened: 'Con qué se inició y abrió',+ picture: 'Imagen · {type} · {size} bytes',+ program: 'Programa',readable: 'Legible',reasoningTokens: '{n} de razonamiento',refresh: 'Actualizar',@@ -284,10 +346,17 @@ export const es: Words = {reveal: 'Mostrar en la carpeta',running: 'En curso',sent: 'Lo que recibió el modelo · {n} mensajes, {fresh} nuevos',+ sentTab: 'Enviado al agente',+ session: 'Sesión',+ settings: 'Ajustes del turno',showAll: 'Mostrar todo ({n} caracteres)',+ steered: 'Enviado mientras trabajaba',thought: 'Razonamiento',+ through: 'a través de {adapter}',title: 'Registro del turno',tokens: 'entrada {input} (caché {cached}) · salida {output}',+ toolsMissing: 'El registro no tiene definiciones de herramientas para esta solicitud.',+ toolsUnknown: 'Codex no guarda en su registro las definiciones de sus herramientas.',},turnFrame: {background: 'Terminó una tarea en segundo plano; el agente siguió',diff --git a/apps/desktop/chat/src/i18n/locales/ja.ts b/apps/desktop/chat/src/i18n/locales/ja.tsindex ad3a046..1848e2c 100644--- a/apps/desktop/chat/src/i18n/locales/ja.ts+++ b/apps/desktop/chat/src/i18n/locales/ja.ts@@ -121,13 +121,15 @@ export const ja: Words = {previewFailed: 'このファイルを読み込めませんでした',},composer: {+ contextFull: 'この会話は長くなっています。新しい会話のほうがうまくいきます。',+ contextFullNew: '新しい会話',commands: 'コマンド',- context: 'コンテキスト {percent}% 使用 · {used} / {size} トークン',agentLoading: '読み込み中…',agentNone: 'エージェント',agentNoneShown: 'チャットで使えるエージェントがオンになっていません。',agentNotFound: '見つかりません',agentOptionsFailed: '設定を読み込むために起動できませんでした。',+ agentOutdated: 'OpenFilm に必要なバージョンより古いです。Codex を更新してから',agentOwnKey: '自分のキー',agentPermissionDeny: '許可しない',agentPermissionTitle: '{name} が次の操作を求めています',@@ -169,6 +171,7 @@ export const ja: Words = {track: 'トラック',file: 'ファイル',subtitle: '字幕',+ example: 'サンプル映像',},clip: 'クリップ',file: 'ファイル',@@ -188,6 +191,8 @@ export const ja: Words = {length: '長さ',language: '言語',line: '行',+ example: 'サンプル',+ part: 'パート',},project: {assets: '素材',@@ -254,28 +259,85 @@ export const ja: Words = {skipped: 'スキップしました — エージェントが自分で判断して続けました',timedOut: '時間内に回答がありませんでした — エージェントが自分で判断して続けました',},+ /* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */+ community: { button: 'コミュニティ', tooltip: 'コミュニティ:スキルとサンプル' },+ skills: {+ button: 'Skills',+ addTitle: 'スキルを追加',+ addHint: 'GitHub か GitLab にあるスキル(またはスキルのフォルダ)のアドレスを貼り付けてください。',+ add: '追加',+ adding: '追加中…',+ scriptsWarning: 'エージェントが実行できるスクリプトが {n} 個含まれています。信頼できるスキルだけを追加してください。',+ done: '完了',+ useIt: 'メッセージで使う',+ cardDoes: '用途',+ next: '次へ',+ cancel: 'キャンセル',+ replaceNote: '{names} はすでにあります。追加すると古いものはゴミ箱に移動します。',+ replaceAndAdd: '置き換えて追加',+ scriptsCount: 'スクリプト {n} 個',+ fromLink: 'リンクから',+ folderDialog: 'フォルダからスキルを追加',+ make: 'エージェントと一緒に作る',+ makeHint: '作り方をスキルにまとめて「自分の」に保存します。',+ makePrompt: 'この会話でやったことを OpenFilm のスキルにまとめてください。SKILL.md を含むフォルダ(名前、いつ使うかの説明、その後に手順)として {folder} に保存します。まず内容と名前を教えてください。私が同意してから保存してください。',+ fromFolderTitle: 'フォルダから',+ dropHere: 'スキルのフォルダをここにドロップ',+ orPick: 'またはクリックして選択',+ makeTitle: '自分で作る',+ addedTitle: '自分のスキルに追加しました',+ },turnLog: {+ thoughtNotKept: 'エージェントの記録には思考内容が保存されていません',+ skills: 'スキルと MCP',+ skillsOpenfilm: 'OpenFilm のスキル',+ skillsHidden: '自分のスキル(オフ)',+ skillsUnfiltered: 'このエージェントは本来のアプリと同じく、自分のスキルをすべて使います',+ mcpHidden: '自分の MCP サーバー(オフ)',+ letIn: '許可済み',answered: '回答済み',+ appended: 'システムプロンプトへの追加',callCount: 'リクエスト {n} 件',calls: 'モデルへのリクエスト {n}',chars: '{n} 文字',close: '閉じる',collapseAll: 'すべて閉じる',+ contextHint: 'エージェント自身が入れたもので、あなたが書いたものではありません',copied: 'コピーしました',copy: 'JSON としてコピー',cut: '長いログのため、最後のイベントを表示しています。',+ developer: 'Codex の developer instructions(あなたのものが先、アプリのものが後)',ended: '終了',+ env: 'アプリが設定した変数',events: '{n} 件のイベント',expandAll: 'すべて開く',failed: 'エラー',filter: 'イベントを絞り込む',+ firstMessage: '最初のメッセージの前',fresh: '新規',+ fromRecord: 'エージェント自身の記録から読み込み:{file}',+ handshake: 'ハンドシェイク',joined: 'テキストの断片をまとめる',+ lacks: {+ copilotRebuilt: 'Copilot 自身の記録から再構成:ツールの定義は保存されず、メッセージは送信したバイトそのものではなく、記録された形です。',+ opencodeBeforeProvider: 'OpenCode のテレメトリから:OpenCode が AI SDK に渡した時点のリクエストで、プロバイダーによる最後の変更(キャッシュ指定など)は含まれません。',+ },loading: 'ログを読み込み中…',- noCalls: 'モデルへのリクエストはありません:記録するのはアプリ自身のエージェント(自分のキー)だけです。',+ logOff: 'このエージェントのリクエストは、開発者モードをオンにした後に始めたセッションでのみ記録されます:新しい会話なら記録されます。',+ logOwn: 'このエージェントのテレメトリやログをご自身で設定しているため、アプリは変更せず、リクエストのログはありません。',+ logSendsMore: 'CodeBuddy はトレースを開発元に送信します。リクエストを記録すると、各トレースにリクエストのファイルの場所が含まれます。アプリが記録するのはそれがオフのときだけです:シェルで DISABLE_TELEMETRY=1 を設定してください。',+ message: 'メッセージ',+ messages: 'エージェントが受け取ったメッセージ · {n}',+ noCalls: 'モデルへのリクエストはありません:このエージェントには、アプリが読める記録がありません。',+ noCallsCursor: 'Cursor はプロンプトを自社のサーバーで作るため、モデルが受け取った内容はこのコンピュータにありません。',noMatch: '一致するイベントはありません',+ noOpened: 'このターンの記録時、アプリはエージェントの起動パラメータを保存していませんでした。',+ noSent: 'このターンでは送信したメッセージが完全には記録されていません。',none: 'このターンのログはありません(ログの記録が始まる前に実行されました)。',open: 'ログ',+ opened: '起動とオープンに使ったもの',+ picture: '画像 · {type} · {size} バイト',+ program: 'プログラム',readable: '読みやすく',reasoningTokens: '思考 {n}',refresh: '更新',@@ -284,10 +346,17 @@ export const ja: Words = {reveal: 'フォルダに表示',running: '実行中',sent: 'モデルに渡した内容 · {n} 件、新規 {fresh} 件',+ sentTab: 'エージェントに送った内容',+ session: 'セッション',+ settings: 'このターンの設定',showAll: 'すべて表示({n} 文字)',+ steered: '作業中に送信',thought: '思考',+ through: '{adapter} 経由',title: 'ターンのログ',tokens: '入力 {input}(キャッシュ {cached})· 出力 {output}',+ toolsMissing: 'このリクエストの記録にはツールの定義がありません。',+ toolsUnknown: 'Codex は記録にツールの定義を保存しません。',},turnFrame: {background: 'バックグラウンドのタスクが終わり、エージェントが続けました',diff --git a/apps/desktop/chat/src/i18n/locales/ko.ts b/apps/desktop/chat/src/i18n/locales/ko.tsindex e44f5dd..ab390c5 100644--- a/apps/desktop/chat/src/i18n/locales/ko.ts+++ b/apps/desktop/chat/src/i18n/locales/ko.ts@@ -121,13 +121,15 @@ export const ko: Words = {previewFailed: '이 파일을 읽을 수 없습니다',},composer: {+ contextFull: '대화가 길어졌습니다. 새 대화를 시작하면 더 잘 됩니다.',+ contextFullNew: '새 대화',commands: '명령',- context: '컨텍스트 {percent}% 사용 · {used} / {size} 토큰',agentLoading: '불러오는 중…',agentNone: '에이전트',agentNoneShown: '채팅에 켜 둔 에이전트가 없습니다.',agentNotFound: '찾을 수 없음',agentOptionsFailed: '설정을 읽으려고 실행했지만 시작하지 못했습니다.',+ agentOutdated: 'OpenFilm에 필요한 버전보다 오래되었습니다. Codex를 업데이트한 다음',agentOwnKey: '내 키',agentPermissionDeny: '허용 안 함',agentPermissionTitle: '{name}이(가) 다음 작업을 하려고 합니다',@@ -169,6 +171,7 @@ export const ko: Words = {track: '트랙',file: '파일',subtitle: '자막',+ example: '예시 영상',},clip: '클립',file: '파일',@@ -188,6 +191,8 @@ export const ko: Words = {length: '길이',language: '언어',line: '줄',+ example: '예시',+ part: '구간',},project: {assets: '에셋',@@ -254,28 +259,85 @@ export const ko: Words = {skipped: '건너뜀 — 에이전트가 스스로 판단해 계속 진행했습니다',timedOut: '시간 안에 답이 없어 에이전트가 스스로 판단해 계속 진행했습니다',},+ /* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */+ community: { button: '커뮤니티', tooltip: '커뮤니티: 스킬과 예시' },+ skills: {+ button: 'Skills',+ addTitle: '스킬 추가',+ addHint: 'GitHub 또는 GitLab에 있는 스킬(또는 스킬 폴더)의 주소를 붙여넣으세요.',+ add: '추가',+ adding: '추가하는 중…',+ scriptsWarning: '에이전트가 실행할 수 있는 스크립트 {n}개가 들어 있습니다. 믿을 수 있는 스킬만 추가하세요.',+ done: '완료',+ useIt: '메시지에 사용',+ cardDoes: '용도',+ next: '다음',+ cancel: '취소',+ replaceNote: '{names}이(가) 이미 있습니다. 추가하면 기존 것은 휴지통으로 이동합니다.',+ replaceAndAdd: '바꾸고 추가',+ scriptsCount: '스크립트 {n}개',+ fromLink: '링크로',+ folderDialog: '폴더에서 스킬 추가',+ make: '에이전트와 함께 만들기',+ makeHint: '만드는 방법을 스킬로 정리해 내 스킬에 저장합니다.',+ makePrompt: '이 대화에서 한 작업을 OpenFilm 스킬로 정리해 주세요. SKILL.md가 들어 있는 폴더(이름, 언제 쓰는지에 대한 설명, 그다음 단계)로 {folder}에 저장합니다. 먼저 무엇을 담을지와 이름을 알려 주고, 제가 동의하면 저장해 주세요.',+ fromFolderTitle: '폴더에서',+ dropHere: '스킬 폴더를 여기에 끌어다 놓기',+ orPick: '또는 클릭해서 선택',+ makeTitle: '직접 만들기',+ addedTitle: '내 스킬에 추가했습니다',+ },turnLog: {+ thoughtNotKept: '에이전트 기록에 생각 내용이 저장되지 않았습니다',+ skills: '스킬과 MCP',+ skillsOpenfilm: 'OpenFilm 스킬',+ skillsHidden: '내 스킬(꺼짐)',+ skillsUnfiltered: '이 에이전트는 자체 앱에서처럼 내 스킬을 모두 사용합니다',+ mcpHidden: '내 MCP 서버(꺼짐)',+ letIn: '허용됨',answered: '응답함',+ appended: '시스템 프롬프트에 추가한 내용',callCount: '요청 {n}개',calls: '모델 요청 {n}',chars: '{n}자',close: '닫기',collapseAll: '모두 접기',+ contextHint: '에이전트가 직접 넣은 것으로, 직접 쓴 내용이 아닙니다',copied: '복사됨',copy: 'JSON으로 복사',cut: '로그가 길어 마지막 이벤트만 표시합니다.',+ developer: 'Codex developer instructions (직접 쓴 것이 먼저, 앱의 것이 뒤)',ended: '종료됨',+ env: '앱이 설정한 변수',events: '이벤트 {n}개',expandAll: '모두 펼치기',failed: '오류',filter: '이벤트 필터',+ firstMessage: '첫 메시지 앞',fresh: '새',+ fromRecord: '에이전트 자체 기록에서 읽음: {file}',+ handshake: '핸드셰이크',joined: '텍스트 조각 합치기',+ lacks: {+ copilotRebuilt: 'Copilot 자체 기록에서 재구성: 도구 정의는 저장되지 않으며, 메시지는 보낸 바이트 그대로가 아니라 기록된 형태입니다.',+ opencodeBeforeProvider: 'OpenCode 텔레메트리에서: OpenCode가 AI SDK에 넘긴 시점의 요청이며, 제공자의 마지막 변경(캐시 표시 등)은 포함되지 않습니다.',+ },loading: '로그를 읽는 중…',- noCalls: '모델 요청이 없습니다: 앱 자체 에이전트(자체 키)만 기록합니다.',+ logOff: '이 에이전트의 요청은 개발자 모드를 켠 뒤 시작한 세션에서만 기록됩니다: 새 대화에는 기록됩니다.',+ logOwn: '이 에이전트의 텔레메트리나 로그를 직접 설정했기 때문에 앱은 그대로 두었고, 요청 로그가 없습니다.',+ logSendsMore: 'CodeBuddy는 트레이스를 개발사에 보내며, 요청을 기록하면 각 트레이스에 요청 파일의 위치가 들어갑니다. 앱은 그 기능이 꺼져 있을 때만 기록합니다: 셸에서 DISABLE_TELEMETRY=1을 설정하세요.',+ message: '메시지',+ messages: '에이전트가 받은 메시지 · {n}',+ noCalls: '모델 요청이 없습니다: 이 에이전트에는 앱이 읽을 수 있는 기록이 없습니다.',+ noCallsCursor: 'Cursor는 프롬프트를 자체 서버에서 만들기 때문에 모델이 받은 내용은 이 컴퓨터에 없습니다.',noMatch: '일치하는 이벤트가 없습니다',+ noOpened: '이 턴이 기록될 때는 앱이 에이전트 시작 매개변수를 저장하지 않았습니다.',+ noSent: '이 턴에서는 보낸 메시지가 완전히 기록되지 않았습니다.',none: '이 턴의 로그가 없습니다: 로그 기록이 시작되기 전에 실행되었습니다.',open: '로그',+ opened: '시작 및 열 때 사용한 것',+ picture: '이미지 · {type} · {size}바이트',+ program: '프로그램',readable: '읽기',reasoningTokens: '생각 {n}',refresh: '새로고침',@@ -284,10 +346,17 @@ export const ko: Words = {reveal: '폴더에서 보기',running: '진행 중',sent: '모델이 받은 내용 · 메시지 {n}개, 새 메시지 {fresh}개',+ sentTab: '에이전트에 보낸 내용',+ session: '세션',+ settings: '이번 턴 설정',showAll: '모두 보기 ({n}자)',+ steered: '작업 중에 보냄',thought: '생각',+ through: '{adapter} 경유',title: '턴 로그',tokens: '입력 {input} (캐시 {cached}) · 출력 {output}',+ toolsMissing: '이 요청의 기록에는 도구 정의가 없습니다.',+ toolsUnknown: 'Codex는 기록에 도구 정의를 저장하지 않습니다.',},turnFrame: {background: '백그라운드 작업이 끝나 에이전트가 이어서 처리했습니다',diff --git a/apps/desktop/chat/src/i18n/locales/zh-CN.ts b/apps/desktop/chat/src/i18n/locales/zh-CN.tsindex 6e59fce..e59c542 100644--- a/apps/desktop/chat/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/chat/src/i18n/locales/zh-CN.ts@@ -121,13 +121,15 @@ export const zhCN: Words = {previewFailed: '无法读取此文件',},composer: {+ contextFull: '这段对话已经很长了,开个新对话效果更好。',+ contextFullNew: '新对话',commands: '命令',- context: '上下文已用 {percent}% · {used} / {size} tokens',agentLoading: '正在加载…',agentNone: '智能体',agentNoneShown: '对话中尚未开启任何智能体。',agentNotFound: '未找到',agentOptionsFailed: '无法启动它来读取设置。',+ agentOutdated: '它的版本比 OpenFilm 需要的旧。请先更新 Codex,然后',agentOwnKey: '自有密钥',agentPermissionDeny: '不允许',agentPermissionTitle: '{name} 想要执行以下操作',@@ -169,6 +171,7 @@ export const zhCN: Words = {track: '轨道',file: '文件',subtitle: '字幕',+ example: '示例影片',},clip: '片段',file: '文件',@@ -188,6 +191,8 @@ export const zhCN: Words = {length: '时长',language: '语言',line: '序号',+ example: '示例',+ part: '片段',},project: {assets: '素材',@@ -254,28 +259,85 @@ export const zhCN: Words = {skipped: '已跳过,它按自己的判断继续了',timedOut: '未及时回答,它按自己的判断继续了',},+ /* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */+ community: { button: '社区', tooltip: '社区:Skill 和示例' },+ skills: {+ button: 'Skills',+ addTitle: '添加 skill',+ addHint: '粘贴 GitHub 或 GitLab 上一个 skill(或一组 skill)的地址。',+ add: '添加',+ adding: '正在添加…',+ scriptsWarning: '它带有 {n} 个 agent 可以运行的脚本。只添加你信任的 skill。',+ done: '完成',+ useIt: '用在消息里',+ cardDoes: '用途',+ next: '下一步',+ cancel: '取消',+ replaceNote: '你已经有 {names},添加后旧的会移到废纸篓。',+ replaceAndAdd: '替换并添加',+ scriptsCount: '{n} 个脚本',+ fromLink: '从链接',+ folderDialog: '从文件夹添加 skill',+ make: '和 agent 一起做一个',+ makeHint: '把一种做法写成 skill,存进“我的”。',+ makePrompt: '把这次对话里的做法整理成一个 OpenFilm skill:一个带 SKILL.md 的文件夹(名字、什么时候用的说明,然后是步骤),存到 {folder}。先告诉我它会包含什么、打算叫什么名字,我同意后再保存。',+ fromFolderTitle: '从文件夹',+ dropHere: '把 skill 文件夹拖到这里',+ orPick: '或点击选择文件夹',+ makeTitle: '自己做',+ addedTitle: '已添加到我的 skill',+ },turnLog: {+ thoughtNotKept: 'agent 的记录里没有保存思考内容',+ skills: 'Skills 和 MCP',+ skillsOpenfilm: 'OpenFilm 的 skill',+ skillsHidden: '你自己的 skill(已关闭)',+ skillsUnfiltered: '这个 agent 带着你自己的全部 skill,和它自己的应用里一样',+ mcpHidden: '你自己的 MCP 服务(已关闭)',+ letIn: '已放行',answered: '已回答',+ appended: '追加到它的系统提示',callCount: '{n} 次请求',calls: '模型请求 {n}',chars: '{n} 字符',close: '关闭',collapseAll: '全部收起',+ contextHint: '由 agent 自己放进去的,不是你写的',copied: '已复制',copy: '复制为 JSON',cut: '日志太长:这里显示的是最后的事件。',+ developer: 'Codex developer instructions(你自己的在前,app 的在后)',ended: '已结束',+ env: 'app 设置的变量',events: '{n} 条事件',expandAll: '全部展开',failed: '出错',filter: '筛选事件',+ firstMessage: '第一条消息前',fresh: '新',+ fromRecord: '读取自 agent 自己的记录:{file}',+ handshake: '握手',joined: '合并文字片段',+ lacks: {+ copilotRebuilt: '根据 Copilot 自己的记录重建:它不保存工具定义,消息是它记下的样子,不是它发出的原始字节。',+ opencodeBeforeProvider: '来自 OpenCode 的遥测:这是 OpenCode 交给 AI SDK 时的请求,服务商最后的改动(缓存标记等)不在其中。',+ },loading: '正在读取日志…',- noCalls: '这里没有模型请求:只有 app 自己的 agent(自有 key)会记录。',+ logOff: '这个 agent 的请求只在开发者模式打开后启动的会话里记录:新开一个对话就有。',+ logOwn: '你自己设置了这个 agent 的遥测或日志,app 没有改动它,所以没有它请求的日志。',+ logSendsMore: 'CodeBuddy 会把它的 trace 发给它的开发方,记录请求后每条 trace 都会写上请求文件的路径。只有关掉这项时 app 才记录:在你的 shell 里设置 DISABLE_TELEMETRY=1。',+ message: '消息',+ messages: '消息,agent 实际收到的 · {n}',+ noCalls: '这里没有模型请求:这个 agent 没有 app 能读取的请求记录。',+ noCallsCursor: 'Cursor 在它自己的服务器上生成提示词,所以它的模型收到了什么不在这台电脑上。',noMatch: '没有匹配的事件',+ noOpened: '这一轮记录时,app 还不保存启动 agent 用的参数。',+ noSent: '这一轮没有完整记录发出的消息。',none: '这一轮没有日志:它发生在开始记录日志之前。',open: '日志',+ opened: '启动和打开时用的',+ picture: '图片 · {type} · {size} 字节',+ program: '程序',readable: '阅读',reasoningTokens: '思考 {n}',refresh: '刷新',@@ -284,10 +346,17 @@ export const zhCN: Words = {reveal: '在文件夹中显示',running: '进行中',sent: '发给模型 · {n} 条消息,新 {fresh} 条',+ sentTab: '发给 agent',+ session: '会话',+ settings: '本轮设置',showAll: '展开全部(共 {n} 字符)',+ steered: '工作中发送',thought: '思考',+ through: '经由 {adapter}',title: '本轮日志',tokens: '输入 {input}(缓存 {cached})· 输出 {output}',+ toolsMissing: '这次请求的记录里没有工具定义。',+ toolsUnknown: 'Codex 的记录里没有保存工具定义。',},turnFrame: {background: '后台任务完成了,agent 接着处理',diff --git a/apps/desktop/chat/src/lib/desktop-attachments.ts b/apps/desktop/chat/src/lib/desktop-attachments.tsindex 18d42d2..8d2635b 100644--- a/apps/desktop/chat/src/lib/desktop-attachments.ts+++ b/apps/desktop/chat/src/lib/desktop-attachments.ts@@ -20,7 +20,7 @@ export interface DesktopAttachment {kind: 'image' | 'document';mediaType: string;size: number;- /** an image's own picture, while it is in the composer */+ /** the file itself, while it is in the composer: an image shows it, and any one opens it to look at (AttachmentPreview) */previewUrl?: string;/** the small picture kept with the message: an image's, or a frame of a video */thumb?: string;@@ -62,7 +62,7 @@ export function useDesktopAttachments() {kind: image ? 'image' : 'document',mediaType: file.type,size: file.size,- ...(image ? { previewUrl: URL.createObjectURL(file) } : {}),+ previewUrl: URL.createObjectURL(file),state: 'importing',};return { item, file };@@ -99,6 +99,8 @@ export function useDesktopAttachments() {current.current = files;const take = React.useCallback((): DesktopAttachment[] => {const taken = current.current;+ /* sent: the message keeps their thumbnails, the files are in the project */+ for (const f of taken) if (f.previewUrl) URL.revokeObjectURL(f.previewUrl);current.current = [];count.current = 0;setFiles([]);diff --git a/apps/desktop/chat/src/lib/desktop-bridge.ts b/apps/desktop/chat/src/lib/desktop-bridge.tsindex 446c136..8a397f1 100644--- a/apps/desktop/chat/src/lib/desktop-bridge.ts+++ b/apps/desktop/chat/src/lib/desktop-bridge.ts@@ -24,11 +24,11 @@ export interface RosterAgent {install?: string | null;setupRequired?: string | null;error?: string;- byok?: {- format: 'responses' | 'chat' | 'anthropic'; baseUrl: string; model: string; models?: string[]; last4: string;- /** per model, the reasoning efforts it offers and the one it starts on (apps/desktop src/pi-config.mjs EFFORTS) */- efforts?: Record<string, { levels: string[]; effort: string }>;- };+ /**+ * The own key's models, each set up on its own (its name, its service, the model asked for there), with the reasoning+ * efforts it offers and the one it starts on (apps/desktop src/pi-config.mjs EFFORTS); the first one to begin with.+ */+ byok?: { models: Array<{ id: string; name: string; format: 'responses' | 'chat' | 'anthropic'; baseUrl: string; model: string; levels: string[]; effort: string; last4: string }> };}export interface LocalAgentState {diff --git a/apps/desktop/chat/src/lib/local-agent-run.ts b/apps/desktop/chat/src/lib/local-agent-run.tsindex 51b1d07..7e86ca3 100644--- a/apps/desktop/chat/src/lib/local-agent-run.ts+++ b/apps/desktop/chat/src/lib/local-agent-run.ts@@ -28,6 +28,7 @@ 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 { isEmptyBackgroundTurn, opensUnprompted } from '@/lib/unprompted';import { reduceTranscript, type TranscriptItem, type TranscriptPlanEntry } from '@/lib/agent-transcript';import {desktopBridge,@@ -613,19 +614,18 @@ export function useAgentContext(projectId: string, conversation: string, agent:command it ran in the background, a subagent), which it takes up by itself, as in its own chat. Its work is shownas a turn of its own in its conversation (`onUnpromptedTurn`, from the page showing the project), which ends withthe 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. ── */+ as soon as the person writes, and at once when they stop it. ── */-/** 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 }+/** What a turn the agent started by itself needs from the page: the turn to fill, the page's way to settle it+ ('cancelled': the person stopped 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: (outcome?: 'cancelled') => 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> }>();@@ -658,16 +658,17 @@ function stillUnprompted(key: string): void {open.timer = setTimeout(() => endUnprompted(key), UNPROMPTED_QUIET_MS);}-function endUnprompted(key: string): void {+function endUnprompted(key: string, outcome?: 'cancelled'): 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);+ turnEndedAt.set(key, Date.now());if (current === open.turn) current = null;void desktopBridge()?.localAgents?.adopt?.(key, null);- open.done();+ open.done(outcome);}/** Whether this turn is one the agent started by itself (it has no run of the page's to wait on). */@@ -739,7 +740,7 @@ function listen(): void {}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);+ const taken = turn ?? (event.kind === 'update' && opensUnprompted(event.update) ? 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,@@ -990,7 +991,12 @@ export async function cancelLocalAgentTurn(turnId: string): Promise<void> {const bridge = desktopBridge()?.localAgents;const turn = turns.get(turnId);if (!bridge || !turn) return;- for (const [key, t] of turnByKey) if (t === turn) await bridge.cancel(key);+ for (const [key, t] of turnByKey) {+ if (t !== turn) continue;+ /* a turn the agent started by itself has no prompt of the page's to end it: it ends here, and the agent is told */+ if (unprompted.get(key)?.turn === turn) endUnprompted(key, 'cancelled');+ await bridge.cancel(key);+ }}export async function answerLocalAgentPermission(turnId: string, optionId: string | null): Promise<void> {@@ -1054,12 +1060,12 @@ const ACTIVE_STATUSES = new Set<Turn['status']>(['generating', 'failing', 'cance/*** 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.+ * and the next message goes on from there. One the agent started by itself and ended with nothing in it is left out.*/export function loadLocalAgentTurns(projectId: string, sessionId: string | null): SavedLocalTurn[] {if (typeof window === 'undefined') return [];return readSaved(projectId)- .filter((x) => !sessionId || x.turn.sessionId === sessionId)+ .filter((x) => (!sessionId || x.turn.sessionId === sessionId) && !isEmptyBackgroundTurn(x.turn, x.items)).map((x) => (ACTIVE_STATUSES.has(x.turn.status) && !runningTurns.has(x.turn.id)? { ...x, turn: { ...x.turn, status: 'error' as const, error: INTERRUPTED } }: x));diff --git a/apps/desktop/chat/src/lib/model-calls.ts b/apps/desktop/chat/src/lib/model-calls.tsindex 6d29a5a..b33b53b 100644--- a/apps/desktop/chat/src/lib/model-calls.ts+++ b/apps/desktop/chat/src/lib/model-calls.ts@@ -1,32 +1,51 @@/**- * The requests the app's own agent (Pi) made to its model in a turn and the answers (the turn's model log,- * src/chat-store.mjs), whole again: a line keeps only what is new since the request before (`prefix` of that one's- * messages, then its own; `systemPrompt` and `tools` when they changed).+ * The requests an agent made to its model in a turn and the answers (the turn's model log, src/chat-store.mjs), whole+ * again: a line keeps only what is new since the request before (`prefix` of that one's messages, then its own;+ * `systemPrompt`, `tools`, `settings`, `source` and `thread` when they changed). The app's own agent (Pi) writes its+ * own; the other agents' are read from their own records (src/agent-records.mjs), or from the logs they are started+ * with in Developer mode (src/agent-logs.mjs).** Messages are Pi's: system (its text in `sections`), user (text or parts), assistant (`thinking`, `text` and- * `toolCall` parts, its usage and why it stopped) and toolResult (`toolCallId`, `toolName`, parts, `isError`).+ * `toolCall` parts, its usage and why it stopped) and toolResult (`toolCallId`, `toolName`, parts, `isError`); from an+ * agent's record also `context`: what the agent put in by itself (`label` says what, `as` the role it went in as).*/type Item = Record<string, any>;export interface RawCall {startedAt: number;- ms: number;+ /** null: the log does not say how long it took (Qwen Code's) */+ ms: number | null;prefix: number;messages: Item[];systemPrompt?: string | null;tools?: Item[] | null;+ /** Codex keeps no tool definitions: `tools` is not known, not empty */+ toolsUnknown?: boolean;+ /** the turn's settings as the agent kept them (Codex: model, effort, permissions) */+ settings?: Item | null;+ /** read from this agent's own record */+ source?: { agent: string; file: string } | null;+ /** a subagent's request (Claude Code), named */+ thread?: { id: string; label: string } | null;+ /** what the log this was read from does not have, by name (the turn log says each: turnLog.lacks.<name>) */+ lacks?: string[];answer: Item | null;}export interface ModelCall {no: number;startedAt: number;- ms: number;+ ms: number | null;systemPrompt: string | null;/** every message the model got, in order; from `fresh` on, the ones new in this request */messages: Item[];fresh: number;tools: Item[] | null;+ toolsUnknown: boolean;+ settings: Item | null;+ source: { agent: string; file: string } | null;+ thread: { id: string; label: string } | null;+ lacks: string[];answer: Item | null;}@@ -34,11 +53,17 @@ export function modelCalls(raw: RawCall[]): ModelCall[] {let messages: Item[] = [];let systemPrompt: string | null = null;let tools: Item[] | null = null;+ let settings: Item | null = null;+ let source: ModelCall['source'] = null;+ let thread: ModelCall['thread'] = null;return raw.map((call, i) => {messages = [...messages.slice(0, call.prefix), ...(call.messages ?? [])];if ('systemPrompt' in call) systemPrompt = call.systemPrompt ?? null;if ('tools' in call) tools = call.tools ?? null;- return { no: i + 1, startedAt: call.startedAt, ms: call.ms, systemPrompt, messages, fresh: call.prefix, tools, answer: call.answer };+ if ('settings' in call) settings = call.settings ?? null;+ if ('source' in call) source = call.source ?? null;+ if ('thread' in call) thread = call.thread ?? null;+ return { no: i + 1, startedAt: call.startedAt, ms: call.ms, systemPrompt, messages, fresh: call.prefix, tools, toolsUnknown: call.toolsUnknown === true, settings, source, thread, lacks: call.lacks ?? [], answer: call.answer };});}diff --git a/apps/desktop/chat/src/lib/unprompted.ts b/apps/desktop/chat/src/lib/unprompted.tsnew file mode 100644index 0000000..bf96df0--- /dev/null+++ b/apps/desktop/chat/src/lib/unprompted.ts@@ -0,0 +1,27 @@+/**+ * Turns the agent starts by itself: a background task of its own came back after its turn (a command it ran in the+ * background, a subagent), and it takes it up, as in its own chat (lib/local-agent-run onUnpromptedTurn).+ *+ * Pure: no React, no bridge, so `node --test` runs it (src/unprompted.test.mjs).+ */++/**+ * The updates that mean the agent has gone on working: it writes, thinks, starts a tool or plans. Not an update of a+ * call (`tool_call_update`): that is the rest of a call already shown, such as a command still running as its turn+ * ended (it was stopped, or ended without waiting), whose output and exit come after.+ */+const OPENS_A_TURN = new Set(['agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'plan']);++/** Whether this update, with no turn open, is the agent working by itself. */+export function opensUnprompted(update: { sessionUpdate?: unknown }): boolean {+ return typeof update.sessionUpdate === 'string' && OPENS_A_TURN.has(update.sessionUpdate);+}++/** A turn the agent started by itself that ended with nothing in it: not shown, a line with nothing under it. */+export function isEmptyBackgroundTurn(+ turn: { origin?: unknown; status?: unknown; error?: unknown },+ items: readonly unknown[],+): boolean {+ const settled = turn.status === 'ready' || turn.status === 'cancelled';+ return turn.origin === 'background' && settled && !turn.error && items.length === 0;+}diff --git a/apps/desktop/chat/src/state/local-agent-store.ts b/apps/desktop/chat/src/state/local-agent-store.tsindex 69ee1b6..2a373d0 100644--- a/apps/desktop/chat/src/state/local-agent-store.ts+++ b/apps/desktop/chat/src/state/local-agent-store.ts@@ -35,8 +35,11 @@ interface LocalAgentStore extends Persisted {hydrated: boolean;/** The roster as the app last told it; null = not told yet (or not in the app). */roster: RosterAgent[] | null;- /** Asking an agent for its option list failed (its adapter would not start): the menu says so. */- optionsError: Partial<Record<LocalAgentId, string>>;+ /**+ * Asking an agent for its option list failed (its adapter would not start): the menu says so, with what it said+ * (`text`) and why, when known (`code`: 'outdated', a Codex older than the chat needs).+ */+ optionsError: Partial<Record<LocalAgentId, { text: string; code?: string }>>;hydrate(): void;refresh(): Promise<void>;pick(agent: LocalAgentId): void;@@ -77,11 +80,20 @@ function save(s: Persisted): void {} catch { /* private mode */ }}-/** The own key's models, as Settings names them (the first one to begin with). */-function byokModels(roster: RosterAgent[] | null): string[] {- const byok = roster?.find((a) => a.id === 'byok')?.byok;- if (!byok) return [];- return byok.models?.length ? byok.models : [byok.model].filter(Boolean);+type OwnModel = NonNullable<RosterAgent['byok']>['models'][number];++/** The own key's models, as Settings sets them up (the first one to begin with). */+function byokModels(roster: RosterAgent[] | null): OwnModel[] {+ return roster?.find((a) => a.id === 'byok')?.byok?.models ?? [];+}++/**+ * Which own model a pick is: its id, or, picked before each model was set up on its own, the model's name at the+ * service (that model kept its name there). Null for one no longer set up.+ */+function ownModelPicked(models: OwnModel[], picked: unknown): OwnModel | null {+ const value = String(picked ?? '');+ return models.find((m) => m.id === value) ?? models.find((m) => m.model === value) ?? null;}const EFFORT_NAMES: Record<string, string> = { auto: 'Auto', off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' };@@ -95,13 +107,11 @@ export function agentOptions(state: Pick<LocalAgentStore, 'options' | 'roster'>if (agent !== 'byok') return state.options[agent];const models = byokModels(state.roster);if (!models.length) return undefined;- const picked = String(state.prefs?.byok?.model ?? '');- const model = models.includes(picked) ? picked : models[0]!;- const options: ConfigOptions = [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: model, options: models.map((m) => ({ value: m, name: m })) }];- const effort = state.roster?.find((a) => a.id === 'byok')?.byok?.efforts?.[model];- if (effort && effort.levels.length > 1) {- options.push({ id: 'effort', name: 'Effort', category: 'thought_level', type: 'select', currentValue: effort.effort,- options: effort.levels.map((l) => ({ value: l, name: EFFORT_NAMES[l] ?? l })) });+ const model = ownModelPicked(models, state.prefs?.byok?.model) ?? models[0]!;+ const options: ConfigOptions = [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: model.id, options: models.map((m) => ({ value: m.id, name: m.name })) }];+ if (model.levels.length > 1) {+ options.push({ id: 'effort', name: 'Effort', category: 'thought_level', type: 'select', currentValue: model.effort,+ options: model.levels.map((l) => ({ value: l, name: EFFORT_NAMES[l] ?? l })) });}return options;}@@ -160,7 +170,7 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({const now = roster.find((a) => a.id === before.id);if (before.status === 'ready' && now?.status !== 'ready') forgetLocalAgentSessions(before.id);/* other models (the own key's): its sessions were closed for the next ones to use them */- else if (String(byokModels([before])) !== String(byokModels(now ? [now] : []))) forgetLocalAgentSessions(before.id);+ else if (JSON.stringify(byokModels([before])) !== JSON.stringify(byokModels(now ? [now] : []))) forgetLocalAgentSessions(before.id);}set({ roster });});@@ -198,11 +208,11 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({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) }));+ const r = await api.probe(agent).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e), code: undefined }));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);/* 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 } });+ else if (!kept) set({ optionsError: { ...get().optionsError, [agent]: r.ok ? { text: 'no options' } : { text: r.error, ...(r.code ? { code: r.code } : {}) } } });} finally {probing.delete(agent);}@@ -226,12 +236,11 @@ const AGENT_FORCED_PREFS: Partial<Record<LocalAgentId, Record<string, unknown>>>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). 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.+ * The options in effect for an agent: the person's picks, then the ones the app sets. 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. The own key's model+ * picked by its name at the service (before each model was set up on its own) is its id now.*/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 owncurrent value stands instead. A mode picked once (plan mode, offered for a while) is not kept: every agent workswith full access. A pick the agent no longer offers (a model gone in its update, one the own key no longer names)@@ -241,10 +250,10 @@ export function effectivePrefs(prefs: Persisted['prefs'], agent: LocalAgentId, rreturn !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' && !DROPPED_PREFS.has(id) && offers(id, value)- && !(models && id === 'model' && !models.includes(String(value)))));- return { ...kept, ...(AGENT_FORCED_PREFS[claudeHarness ? 'claude' : agent] ?? {}) };+ const own = Object.entries(prefs[agent] ?? {}).map(([id, value]): [string, unknown] => (models && id === 'model' ? [id, ownModelPicked(models, value)?.id ?? null] : [id, value]));+ const kept = Object.fromEntries(own+ .filter(([id, value]) => value !== 'default' && value !== null && !DROPPED_PREFS.has(id) && offers(id, value)));+ return { ...kept, ...(AGENT_FORCED_PREFS[agent] ?? {}) };}/** An option's current value (the person's pick first, else the value the session reports). */diff --git a/apps/desktop/chat/src/studio-refs.ts b/apps/desktop/chat/src/studio-refs.tsindex 58b5818..ed1356f 100644--- a/apps/desktop/chat/src/studio-refs.ts+++ b/apps/desktop/chat/src/studio-refs.ts@@ -40,6 +40,7 @@ const idOf = (ref: StudioRef): string => {case 'track': return `studio:track:${ref.track}`;case 'file': return `studio:file:${ref.path}`;case 'subtitle': return `studio:subtitle:${ref.start}-${ref.end}${ref.lang ? `:${ref.lang}` : ''}`;+ case 'example': return `studio:example:${ref.id}${ref.end ? `:${ref.start ?? 0}-${ref.end}` : ''}`;}};@@ -70,6 +71,8 @@ export function refPill(id: string | undefined, ref: StudioRef): PromptReference...(ref.w && ref.h ? { detail: `${ref.w}×${ref.h}` } : ref.duration ? { detail: clock(ref.duration) } : {}),};case 'subtitle': return { ...base, kind: 'subtitle', label: clipped(ref.text, 40) || span(ref.start, ref.end) };+ /* an example: its title, and the part when one was picked */+ case 'example': return { ...base, kind: 'example', label: clipped(ref.title, 40), ...(ref.segment ? { detail: ref.segment } : ref.end ? { detail: `${clock(ref.start ?? 0)}–${clock(ref.end)}` } : {}) };}}@@ -123,6 +126,7 @@ export function sameStudioThing(a: StudioRef, b: StudioRef): boolean {case 'track': return b.kind === 'track' && a.track === b.track;case 'file': return b.kind === 'file' && a.path === b.path;case 'subtitle': return b.kind === 'subtitle' && near(a.start, b.start) && near(a.end, b.end) && (a.lang ?? null) === (b.lang ?? null);+ case 'example': return b.kind === 'example' && a.id === b.id && near(a.start ?? 0, b.start ?? 0) && near(a.end ?? 0, b.end ?? 0);}}@@ -219,8 +223,14 @@ export function pillCard(pill: { id: string; label: string; target?: Record<strirow('language', ref.lang);row('line', ref.index);break;+ case 'example':+ row('example', ref.title);+ row('part', ref.segment ?? (ref.end ? span(ref.start ?? 0, ref.end) : null));+ row('path', ref.folder ?? null);+ break;}- return { title: t(`refCard.title.${ref.kind}`), rows };+ /* an example: what it is, as its page says */+ return { title: t(`refCard.title.${ref.kind}`), rows, ...(ref.kind === 'example' && ref.description ? { text: [ref.description] } : {}) };}/* the agent's numbers: seconds to the millisecond, as film.html writes them */@@ -267,6 +277,13 @@ function refLine(ref: StudioRef): string {`subtitle ${ref.start.toFixed(3)}–${ref.end.toFixed(3)} s ${quote(ref.text, 300)}${ref.lang ? ` (${ref.lang})` : ''}`,typeof ref.index === 'number' ? `line ${ref.index}` : null,].filter(Boolean).join(' · ');+ /* not this film: another OpenFilm film, whose source shows how it is made */+ case 'example': return [+ `example film ${quote(ref.title, 80)} (another OpenFilm film, not this one: read its film.html and pages for how it is made)`,+ ref.folder ? `folder ${ref.folder}` : 'its folder could not be fetched: read it at its source',+ ref.end ? `its ${ref.start?.toFixed(3) ?? '0.000'}–${ref.end.toFixed(3)} s${ref.segment ? ` (${quote(ref.segment, 60)})` : ''}` : 'the whole film',+ `source ${ref.url}`,+ ].join(' · ');}}diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 423ecce..7b4ce12 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -9,7 +9,7 @@"scripts": {"start": "node scripts/start.mjs","build:shell": "vite build --config shell/vite.config.ts",- "test": "node --test src/*.test.mjs",+ "test": "node --test src/*.test.mjs scripts/*.test.mjs","bench": "node bench/run.mjs","typecheck": "tsc -p chat && tsc -p shell","release": "node scripts/release.mjs"diff --git a/apps/desktop/scripts/locked-versions.mjs b/apps/desktop/scripts/locked-versions.mjsnew file mode 100644index 0000000..d762bbb--- /dev/null+++ b/apps/desktop/scripts/locked-versions.mjs@@ -0,0 +1,94 @@+/**+ * The versions the lockfile has, for the installer's `npm install` (release.mjs). The installer's node_modules is made+ * by npm, which does not read pnpm's lockfile: left to itself it takes the latest version each range allows, so a+ * dependency published after the lockfile was written ships untried (pi-codemode 1.2.0 broke the own key's agent in+ * 0.1.7). These npm `overrides` pin each package to what pnpm installed and the tests ran with.+ */++import { readFileSync, readdirSync } from 'node:fs';+import { join } from 'node:path';++const SEMVER = /^\d+\.\d+\.\d+(?:-[\w.]+)?$/;++/**+ * npm `overrides` from `pnpm list --prod --depth Infinity --json` of the package (its first entry). A package locked at+ * one version is pinned to it; one locked at several is pinned under each package that depends on it. The package's+ * own dependencies are not pinned themselves: they are exact in its package.json already, and npm refuses an override+ * of one.+ * @param {{ dependencies?: Record<string, any> }} tree+ */+export function lockedOverrides(tree) {+ /** @type {Map<string, Set<string>>} */+ const versions = new Map();+ /** @type {Array<[string, string, string]>} parent, child, child's version */+ const edges = [];+ const walk = (deps, parent) => {+ for (const [name, dep] of Object.entries(deps ?? {})) {+ if (SEMVER.test(dep?.version ?? '')) {+ if (!versions.has(name)) versions.set(name, new Set());+ versions.get(name).add(dep.version);+ if (parent) edges.push([parent, name, dep.version]);+ }+ walk(dep?.dependencies, name);+ }+ };+ walk(tree.dependencies, null);+ const direct = new Set(Object.keys(tree.dependencies ?? {}));++ /** @type {Record<string, string | Record<string, string>>} */+ const overrides = {};+ for (const [name, set] of versions) if (set.size === 1 && !direct.has(name)) overrides[name] = [...set][0];+ for (const [parent, child, version] of edges) {+ if (versions.get(child).size === 1) continue;+ const parents = versions.get(parent);+ let entry = overrides[parent];+ if (typeof entry !== 'object') entry = overrides[parent] = parents.size === 1 && !direct.has(parent) ? { '.': [...parents][0] } : {};+ /* the same parent name wanting two versions of it (two versions of the parent): left to npm */+ if (entry[child] && entry[child] !== version) entry[child] = null;+ else if (entry[child] !== null) entry[child] = version;+ }+ for (const [name, entry] of Object.entries(overrides)) {+ if (typeof entry !== 'object') continue;+ for (const [k, v] of Object.entries(entry)) if (v === null) delete entry[k];+ if (!Object.keys(entry).some((k) => k !== '.')) overrides[name] = entry['.'] ?? null;+ if (overrides[name] === null) delete overrides[name];+ }+ return overrides;+}++/**+ * What an installed node_modules has that the lockfile does not: `[{ name, version, locked }]` for each package found+ * at a version the lockfile does not have for it (release.mjs stops on any).+ * @param {{ dependencies?: Record<string, any> }} tree @param {string} nodeModules+ */+export function versionsOffLock(tree, nodeModules) {+ /** @type {Map<string, Set<string>>} */+ const locked = new Map();+ const walk = (deps) => {+ for (const [name, dep] of Object.entries(deps ?? {})) {+ if (SEMVER.test(dep?.version ?? '')) {+ if (!locked.has(name)) locked.set(name, new Set());+ locked.get(name).add(dep.version);+ }+ walk(dep?.dependencies);+ }+ };+ walk(tree.dependencies);+ const off = [];+ const scan = (dir) => {+ let entries = [];+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const path = join(dir, entry.name);+ if (entry.name.startsWith('@')) { scan(path); continue; }+ try {+ const { name, version } = JSON.parse(readFileSync(join(path, 'package.json'), 'utf8'));+ if (locked.has(name) && !locked.get(name).has(version)) off.push({ name, version, locked: [...locked.get(name)] });+ } catch { /* not a package */ }+ scan(join(path, 'node_modules'));+ }+ };+ scan(nodeModules);+ return off;+}diff --git a/apps/desktop/scripts/locked-versions.test.mjs b/apps/desktop/scripts/locked-versions.test.mjsnew file mode 100644index 0000000..74f59a7--- /dev/null+++ b/apps/desktop/scripts/locked-versions.test.mjs@@ -0,0 +1,39 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { lockedOverrides, versionsOffLock } from './locked-versions.mjs';++/* the shape of `pnpm list --prod --depth Infinity --json` */+const tree = {+ dependencies: {+ '@earendil-works/pi-coding-agent': { version: '1.1.0', dependencies: {+ '@earendil-works/pi-codemode': { version: '1.1.0' },+ diff: { version: '8.0.4' },+ } },+ '@agentclientprotocol/codex-acp': { version: '1.13.1', dependencies: { diff: { version: '9.0.0' } } },+ diff: { version: '9.0.0' },+ openfilm: { version: 'link:../../packages/openfilm', dependencies: { 'playwright-core': { version: '1.50.0' } } },+ },+};++test("the installer's npm install is pinned to the lockfile's versions", () => {+ assert.deepEqual(lockedOverrides(tree), {+ '@earendil-works/pi-codemode': '1.1.0',+ 'playwright-core': '1.50.0',+ /* two versions of diff: each under what depends on it; the package's own (exact) is not overridden */+ '@earendil-works/pi-coding-agent': { diff: '8.0.4' },+ '@agentclientprotocol/codex-acp': { diff: '9.0.0' },+ });+});++test('a package installed at a version the lockfile does not have is named', () => {+ const nm = mkdtempSync(join(tmpdir(), 'of-nm-'));+ const put = (dir, name, version) => { mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, version })); };+ put(join(nm, '@earendil-works/pi-coding-agent'), '@earendil-works/pi-coding-agent', '1.1.0');+ put(join(nm, '@earendil-works/pi-codemode'), '@earendil-works/pi-codemode', '1.2.0');+ put(join(nm, '@earendil-works/pi-coding-agent/node_modules/diff'), 'diff', '8.0.4');+ put(join(nm, 'diff'), 'diff', '9.0.0');+ assert.deepEqual(versionsOffLock(tree, nm), [{ name: '@earendil-works/pi-codemode', version: '1.2.0', locked: ['1.1.0'] }]);+});diff --git a/apps/desktop/scripts/release.mjs b/apps/desktop/scripts/release.mjsindex eec083b..bd3e9d7 100644--- a/apps/desktop/scripts/release.mjs+++ b/apps/desktop/scripts/release.mjs@@ -39,6 +39,7 @@ import { createRequire } from 'node:module';import { createHash } from 'node:crypto';import { basename, dirname, join, resolve } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';+import { lockedOverrides, versionsOffLock } from './locked-versions.mjs';const require = createRequire(import.meta.url);const desktop = resolve(dirname(fileURLToPath(import.meta.url)), '..');@@ -88,6 +89,8 @@ cpSync(join(desktop, 'src'), join(stage, 'src'), { recursive: true, filter: (frocpSync(join(desktop, 'shell/dist'), join(stage, 'shell/dist'), { recursive: true });const pack = (dir) => execFileSync('npm', ['pack', '--ignore-scripts', '--pack-destination', work, '--silent'], { cwd: dir, encoding: 'utf8' }).trim().split('\n').pop();const dependencies = { ...pkg.dependencies, openfilm: `file:../${pack(protocol)}` };+/* npm takes the versions pnpm's lockfile has (locked-versions.mjs): what the tests ran with, not the latest */+const lockedTree = JSON.parse(execFileSync('pnpm', ['list', '--prod', '--depth', 'Infinity', '--json'], { cwd: desktop, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 }))[0];writeFileSync(join(stage, 'package.json'), `${JSON.stringify({name: 'openfilm-desktop',productName: NAME,@@ -100,8 +103,13 @@ writeFileSync(join(stage, 'package.json'), `${JSON.stringify({type: 'module',main: 'src/main.mjs',dependencies,+ overrides: lockedOverrides(lockedTree),}, null, 2)}\n`);run('npm', ['install', '--omit=dev', '--omit=optional', '--no-audit', '--no-fund', '--no-package-lock', '--loglevel=error'], { cwd: stage });+const offLock = versionsOffLock(lockedTree, join(stage, 'node_modules'));+if (offLock.length) {+ throw new Error(`The installer's packages are not the lockfile's:\n${offLock.map((p) => ` ${p.name} ${p.version} (locked: ${p.locked.join(', ')})`).join('\n')}`);+}/* the build's product file */cpSync(productFile, join(stage, 'node_modules/openfilm/product.json'));@@ -138,7 +146,9 @@ await builder.build({artifactName: `${NAME.replace(' ', '-')}-Setup-\${arch}.\${ext}`,},nsis: {- oneClick: true,+ /* the installer asks where to put the app (the person's own folder by default), so it need not live on C: */+ oneClick: false,+ allowToChangeInstallationDirectory: true,perMachine: false,installerIcon: join(desktop, 'build/icon.ico'),uninstallerIcon: join(desktop, 'build/icon.ico'),diff --git a/apps/desktop/shell/bridge.ts b/apps/desktop/shell/bridge.tsindex e17f307..a12cccc 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, HostUpdateState, StudioCommand, StudioHost, StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';+import type { CommunityItem, HostAgent, HostAsk, HostUpdate, HostUpdateState, StudioCommand, StudioHost, StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';type Listener<T> = (value: T) => void;type Stop = () => void;@@ -25,9 +25,13 @@ interface Native {pickFolder(options?: { title?: string; button?: string; at?: string }): Promise<string | null>;capture(rect: { x: number; y: number; width: number; height: number }): Promise<string | null>;agents: NonNullable<StudioHost['agents']>;+ /* the window's tabs (src/tabs.mjs) */+ tabs: NonNullable<StudioHost['tabs']>;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>>;+ /* the composer's Skills button (src/skills-ipc.mjs) */+ skills: Record<string, (...args: never[]) => Promise<unknown>>;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;@@ -70,8 +74,10 @@ const shownWidth = () => (layout.open ? Math.max(Math.min(layout.width, innerWidconst panelState = () => ({ open: layout.open, width: shownWidth(), assets: { open: assets.open && layout.open, bottom: assets.bottom } });const panelListeners = new Set<Listener<ReturnType<typeof panelState>>>();+/** The page shows a project (not a new tab's launcher): only then is there a chat to show. */+const onProject = () => /^\/projects\/[\w-]+/.test(location.pathname);function place() {- column.hidden = !layout.open;+ column.hidden = !layout.open || !onProject();column.style.width = `${shownWidth()}px`;column.style.top = `${TOP_BAR}px`;/* the column never moves or resizes for the assets: the chat shows only its composer then, and the rest of the@@ -137,14 +143,17 @@ async function follow() {}for (const method of ['pushState', 'replaceState'] as const) {const original = history[method].bind(history);- history[method] = (...args: Parameters<History['pushState']>) => { original(...args); projectReady = follow(); };+ history[method] = (...args: Parameters<History['pushState']>) => { original(...args); projectReady = follow(); place(); };}-addEventListener('popstate', () => { projectReady = follow(); });+addEventListener('popstate', () => { projectReady = follow(); place(); });projectReady = follow();/* ── between Studio and the chat: what is selected, what is referenced, what Studio is asked to show ── */const selection = signal<StudioSelection | null>(null);const refer = events<StudioRef>();+/* a skill picked in the examples (Studio's ExamplesDialog), to be named in the message; and "Add a skill" there */+const skillPicked = events<{ name: string; description: string }>();+const skillAdd = events<void>();/** what the pointer is over in Studio (null: nothing), for the chat to light its pills that point at it */const hover = signal<StudioRef | null>(null);let command: ((command: StudioCommand) => void) | null = null;@@ -271,6 +280,9 @@ const host: StudioHost = {developer,update,folders: { pick: native.pickFolder, pathOf: native.pathForFile },+ tabs: native.tabs,+ useSkill: (skill) => skillPicked.set(skill),+ skills: { add: () => skillAdd.set(undefined) },};(window as unknown as { openfilmHost: StudioHost }).openfilmHost = host;@@ -302,6 +314,8 @@ function commandFor(ref: StudioRef): StudioCommand {case 'track': return { type: 'show-track', track: ref.track };case 'file': return { type: 'show-file', path: ref.path };case 'subtitle': return { type: 'show-subtitle', start: ref.start, end: ref.end };+ /* another film: the examples, where it came from */+ case 'example': return { type: 'show-examples', open: { kind: 'example', id: ref.id } };}}const uploadName = (name: string) => name.split(/[\\/]/).pop()!.replace(/[\u0000-\u001f]+/g, '').slice(0, 200) || 'file';@@ -337,6 +351,18 @@ const uploadName = (name: string) => name.split(/[\\/]/).pop()!.replace(/[\u0000onSelection: (listener: Listener<StudioSelection>) => selection.on((s) => { if (s) listener(s); }),onFfmpeg: native.onFfmpeg,showInStudio: (ref: StudioRef) => command?.(commandFor(ref)),+ /* an example's folder on this computer (Studio fetches it when needed), for a reference to one in a message sent */+ async exampleFolder(id: string) {+ const res = await fetch(`/api/examples/${encodeURIComponent(id)}/folder`, { method: 'POST' });+ const body = await res.json().catch(() => ({})) as { folder?: string; error?: string };+ if (!res.ok || !body.folder) throw new Error(body.error ?? `Studio answered ${res.status}`);+ return body.folder;+ },+ /* the composer's examples button: the examples over the film, to point at one or name a skill */+ showExamples: (open?: CommunityItem) => command?.({ type: 'show-examples', ...(open ? { open } : {}) }),+ onUseSkill: skillPicked.on,+ onAddSkill: skillAdd.on,+ useSkill: (skill: { name: string; description: string }) => skillPicked.set(skill),/* a reference made in the chat (⌘L there, the @ menu) gets its picture as Studio's own do */withPicture: (ref: StudioRef) => { const done = pictured.then(() => withPicture(ref)); pictured = done.then(() => {}); return done; },/* what a pill hovered in the chat points at, lit in Studio while it is (null: none); and the references of the@@ -378,6 +404,7 @@ const uploadName = (name: string) => name.split(/[\\/]/).pop()!.replace(/[\u0000setMenuOpen() {},/* the chat's record of each project, in its .film/chat and .film/logs */chat: native.chat,+ skills: native.skills,asks: { get: asks.get, onChange: asks.on, answer: (id: string, allow: boolean) => answerAsk(id, allow) },developer,};diff --git a/apps/desktop/src/agent-installation.mjs b/apps/desktop/src/agent-installation.mjsindex fc97187..1a110d8 100644--- a/apps/desktop/src/agent-installation.mjs+++ b/apps/desktop/src/agent-installation.mjs@@ -5,6 +5,7 @@* 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 { execFileSync } from 'node:child_process';import { accessSync, closeSync, constants, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';import { homedir } from 'node:os';import { delimiter, dirname, isAbsolute, join } from 'node:path';@@ -102,6 +103,44 @@ export function claudeVersion(file) {return real.split(/[\\/]/).reverse().find((part) => /^\d+\.\d+\.\d+$/.test(part)) ?? null;}+/** What versions of Codex said of themselves (`codex --version`), by program and its time: each asked once. */+const codexAsked = new Map();++/** What a Codex program says its version is (`codex-cli 0.163.0`); null when it says nothing in two seconds. */+function askCodexVersion(/** @type {string} */ file) {+ /* a `.cmd` shim cannot be started without a shell; npm's says its version in its package.json anyway */+ if (/\.(cmd|bat)$/i.test(file)) return null;+ try {+ const out = execFileSync(file, ['--version'], { encoding: 'utf8', timeout: 2000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });+ return /(\d+\.\d+\.\d+)/.exec(out)?.[1] ?? null;+ } catch {+ return null;+ }+}++/**+ * Which Codex a program is: npm's says it in its package.json (`@openai/codex`, or the platform package its program+ * is in), Homebrew's folder is named for it (`Caskroom/codex/0.163.0/…`); a copy inside an app (Codex.app,+ * ChatGPT.app, a Store app) says it when asked (`--version`), once. Null when it can't be told.+ * @param {string} file @param {{ ask?: (file: string) => string | null }} [o]+ */+export function codexVersion(file, { ask = askCodexVersion } = {}) {+ let real;+ try { real = realpathSync(file); } catch { return null; }+ for (let dir = dirname(real), up = 0; up < 6; dir = dirname(dir), up += 1) {+ try {+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));+ if (typeof pkg.name === 'string' && pkg.name.startsWith('@openai/codex') && typeof pkg.version === 'string') return pkg.version.replace(/-.*$/, '');+ } catch { /* not here */ }+ }+ const named = real.split(/[\\/]/).reverse().find((part) => /^\d+\.\d+\.\d+$/.test(part));+ if (named) return named;+ let key;+ try { key = `${real}\0${statSync(real).mtimeMs}`; } catch { return null; }+ if (!codexAsked.has(key)) codexAsked.set(key, ask(real));+ return codexAsked.get(key) ?? null;+}+/** Whether version `a` is later than `b` (dotted numbers); false when either is unknown. */export function laterVersion(a, b) {if (!a || !b) return false;@@ -226,6 +265,11 @@ function existsFile(path) {/* where Codex is inside Codex.app and ChatGPT.app */const CODEX_IN_APP = ['Contents/Resources/codex', 'Contents/Resources/codex-cli/bin/codex'];+/** The copies of Codex inside Codex.app and ChatGPT.app in these folders, Codex.app's first. */+function codexInApps(/** @type {string[]} */ applicationDirs) {+ return applicationDirs.flatMap((dir) => ['Codex.app', 'ChatGPT.app'].flatMap((app) => CODEX_IN_APP.map((p) => join(dir, app, p)))).filter(executableFile);+}+/*** 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.@@ -256,7 +300,7 @@ export function chosenProgram(path, { names = [], win = windows } = {}) {* 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')], chosen = null, others = [], win = windows } = {}) {+ applicationDirs = ['/Applications', join(home, 'Applications')], chosen = null, others = [], win = windows, codexVersionOf = codexVersion } = {}) {const program = AGENT_PROGRAMS[id] ?? { names: [id] };const install = AGENT_DOWNLOADS[id] ?? null;const picked = chosen ? chosenProgram(chosen, { names: program.names, win }) : null;@@ -269,11 +313,21 @@ export function detectAgentInstallation(id, { home = homedir(), env = process.enown up to date: the later one, whose models are the current ones. One whose version can't be told stays. */const inApp = id === 'claude' ? claudeAppCli(home) : null;if (inApp && laterVersion(claudeVersion(inApp), claudeVersion(cli))) return { installed: true, cli: inApp, source: 'app', install };+ /* Codex the same: one installed by npm long ago beside the copy in Codex.app, ChatGPT.app or a Store app, which+ keep theirs up to date. Its models are the ones its version is offered, so the later one is used */+ if (id === 'codex') {+ const copies = [...codexInApps(applicationDirs), ...others.filter((file) => (win ? presentFile(file) : executableFile(file)))];+ const mine = copies.length ? codexVersionOf(cli) : null;+ let newest = null;+ for (const copy of copies) {+ const version = codexVersionOf(copy);+ if (laterVersion(version, newest?.version ?? mine)) newest = { copy, version };+ }+ if (newest) return { installed: true, cli: newest.copy, source: 'app', install };+ }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 (id === 'codex') cli = codexInApps(applicationDirs)[0] ?? null;if (!cli && id === 'claude') cli = claudeAppCli(home);if (!cli) cli = others.find((file) => (win ? presentFile(file) : executableFile(file))) ?? null;return { installed: Boolean(cli), cli, source: cli ? 'app' : null, install };diff --git a/apps/desktop/src/agent-installation.test.mjs b/apps/desktop/src/agent-installation.test.mjsindex 84e7859..6291019 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, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { chosenProgram, claudeAppCli, claudeVersion, cmdTarget, consoleProgram, detectAgentInstallation, findExecutable, laterVersion, searchReport, windowsBinDirs } from './agent-installation.mjs';+import { chosenProgram, claudeAppCli, claudeVersion, cmdTarget, codexVersion, consoleProgram, detectAgentInstallation, findExecutable, laterVersion, 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-'));@@ -225,3 +225,41 @@ test('Claude Code on the PATH and in the Claude app: the later one is used, toldassert.equal(laterVersion('2.1.10', '2.1.9'), true);assert.equal(laterVersion('2.1.9', '2.1.9'), false);});++test('which Codex a program is: npm\'s package, Homebrew\'s folder, else what it says when asked, once', () => {+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const pkg = join(home, 'npm', 'node_modules', '@openai', 'codex');+ put(join(pkg, 'package.json'), JSON.stringify({ name: '@openai/codex', version: '0.42.0' }));+ const script = put(join(pkg, 'bin', 'codex.js'));+ assert.equal(codexVersion(script), '0.42.0');+ /* its program in the platform package npm puts beside it */+ const plat = join(home, 'npm', 'node_modules', '@openai', 'codex-win32-x64');+ put(join(plat, 'package.json'), JSON.stringify({ name: '@openai/codex-win32-x64', version: '0.150.0-win32-x64' }));+ assert.equal(codexVersion(put(join(plat, 'vendor', 'x86_64-pc-windows-msvc', 'bin', 'codex.exe'))), '0.150.0');+ assert.equal(codexVersion(put(join(home, 'Caskroom', 'codex', '0.163.0', 'codex-aarch64-apple-darwin'))), '0.163.0');+ let asked = 0;+ const inApp = put(join(home, 'Codex.app', 'Contents', 'Resources', 'codex'));+ const ask = () => { asked += 1; return '0.170.1'; };+ assert.equal(codexVersion(inApp, { ask }), '0.170.1');+ assert.equal(codexVersion(inApp, { ask }), '0.170.1');+ assert.equal(asked, 1, 'asked once while the program is the same');+ assert.equal(codexVersion(join(home, 'gone')), null);+});++test('Codex installed long ago beside the copy an app keeps up to date: the later one is used', () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const bin = join(home, 'bin');+ const onPath = put(join(bin, 'codex'), '', 0o755);+ const apps = join(home, 'Applications');+ const inApp = put(join(apps, 'ChatGPT.app', 'Contents', 'Resources', 'codex'), '', 0o755);+ const store = put(join(home, 'Store', 'codex.exe'), '', 0o755);+ const versions = (map) => (file) => map[file] ?? null;+ const opts = { home, env: { PATH: bin }, pathDirs: [], applicationDirs: [apps] };+ assert.deepEqual(detectAgentInstallation('codex', { ...opts, codexVersionOf: versions({ [onPath]: '0.42.0', [inApp]: '0.163.0' }) }),+ { installed: true, cli: inApp, source: 'app', install: 'https://developers.openai.com/codex' });+ assert.equal(detectAgentInstallation('codex', { ...opts, others: [store], codexVersionOf: versions({ [onPath]: '0.42.0', [inApp]: '0.163.0', [store]: '0.170.0' }) }).cli, store, 'the latest of them');+ assert.equal(detectAgentInstallation('codex', { ...opts, codexVersionOf: versions({ [onPath]: '0.170.0', [inApp]: '0.163.0' }) }).cli, onPath, 'the one on the PATH is the later');+ assert.equal(detectAgentInstallation('codex', { ...opts, codexVersionOf: versions({ [inApp]: '0.163.0' }) }).cli, onPath, 'one whose version can\'t be told stays');+ assert.equal(detectAgentInstallation('codex', { ...opts, chosen: onPath, codexVersionOf: versions({ [onPath]: '0.1.0', [inApp]: '0.163.0' }) }).cli, onPath, 'the one chosen, whatever its version');+});diff --git a/apps/desktop/src/agent-logs.mjs b/apps/desktop/src/agent-logs.mjsnew file mode 100644index 0000000..0346cf1--- /dev/null+++ b/apps/desktop/src/agent-logs.mjs@@ -0,0 +1,608 @@+/**+ * What the person's own Gemini CLI, Qwen Code, CodeBuddy and OpenCode sent their models in a turn. Their own records+ * keep the conversation without the system prompt or the tools, so each is started with its own logging switch+ * (official, local only), writing into a folder of the app's for that one process, and a turn's requests are read+ * from there once it ends, in the shape agent-records.mjs gives Claude Code's, Codex's, Kimi's and Copilot's.+ *+ * Gemini CLI its telemetry to a local file (GEMINI_TELEMETRY_TARGET=local, _OUTFILE): records of pretty JSON one+ * after the other. Each `gemini_cli.api_request` has the contents as sent (`request_text`), its+ * `llm_call` span (the same span id) the system instructions and the tools, the next+ * `gemini_cli.api_response` of its prompt id the answer's chunks and the usage. Prompts are in the+ * records by Gemini CLI's own default (logPrompts), which the app leaves as the person has it.+ * Qwen Code `--openai-logging --openai-logging-dir`: one JSON per request, the body sent (OpenAI's chat format:+ * its system message, messages, tools) and the answer whole, with the session it was for.+ * CodeBuddy its raw request and response bodies to files (OTEL_LOG_RAW_API_BODIES=file:<dir>), with an+ * index naming each request's session; only when its own telemetry is off (see sendsMore).+ * OpenCode its OpenTelemetry (`experimental.openTelemetry`) sent to a receiver of the app's on 127.0.0.1, which+ * keeps only the AI SDK's request spans: each has the prompt as OpenCode gave it (system, messages),+ * the tools, the answer and the usage, by session.+ *+ * Only for a session started while Developer mode is on, and only when the person has set none of the agent's+ * telemetry themselves: theirs is never changed. Nothing here goes off the computer, and none of it is on the agent's+ * stdout (its ACP channel). A process's folder goes after LOG_KEEP_DAYS; the turn log keeps what was read from it.+ *+ * None of these is a public format either: read for what it has, and whatever is not understood is left out. A+ * request's messages are as the log has them; `lacks` names what a log does not have, for the turn log to say.+ *+ * Reads no Electron module, so `node --test` can use it.+ */+import { randomBytes } from 'node:crypto';+import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';+import { createServer } from 'node:http';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { gunzipSync } from 'node:zlib';++/** The agents started with a logging switch. */+export const LOGGED_AGENTS = Object.freeze(['gemini', 'qwen', 'codebuddy', 'opencode']);++/** a process's logs are kept this long */+const LOG_KEEP_DAYS = 7;+/** a log longer than this is not read */+const LOG_MAX = 256 * 1024 * 1024;+/** what the receiver takes in one request (a span carries the whole conversation) */+const RECEIVE_MAX = 64 * 1024 * 1024;++/**+ * How long after a turn its requests are all in the log: Gemini CLI writes them in batches (every few seconds),+ * OpenCode sends them so; Qwen Code and CodeBuddy as each answer ends.+ */+export const LOG_SETTLE_MS = Object.freeze({ gemini: 6000, opencode: 6000 });++const str = (v) => (typeof v === 'string' ? v : v == null ? '' : JSON.stringify(v));+const parse = (v, fallback = null) => { if (typeof v !== 'string') return v ?? fallback; try { return JSON.parse(v); } catch { return fallback; } };+const ms = (iso) => { const t = Date.parse(String(iso ?? '')); return Number.isFinite(t) ? t : null; };+const picture = (mimeType, data) => ({ type: 'image', mimeType: String(mimeType || 'image/png'), data: String(data ?? '') });+const text = (t) => ({ type: 'text', text: String(t ?? '') });+const readText = (file) => {+ try { return statSync(file).size > LOG_MAX ? '' : readFileSync(file, 'utf8'); } catch { return ''; }+};+const jsonLines = (file) => readText(file).split('\n').flatMap((line) => { try { return line ? [JSON.parse(line)] : []; } catch { return []; } });+const files = (dir) => { try { return readdirSync(dir).sort(); } catch { return []; } };++/* ── the switches ─────────────────────────────────────────────────────────── */++/** a setting of the person's own: any of these variables in their shell */+const setInShell = (shell, re) => Object.keys(shell ?? {}).some((k) => re.test(k));+const mentions = (file, re) => { try { return re.test(readFileSync(file, 'utf8')); } catch { return false; } };++/** Whether the person has set the agent's telemetry or logging themselves: then the app leaves it as it is. */+export function ownLogging(agent, { shell = {}, home = homedir(), cwd = '' } = {}) {+ switch (agent) {+ case 'gemini':+ return setInShell(shell, /^(GEMINI_TELEMETRY_|OTEL_)/)+ || [join(home, '.gemini', 'settings.json'), cwd && join(cwd, '.gemini', 'settings.json')].some((f) => f && mentions(f, /"telemetry"\s*:/));+ case 'qwen':+ return [join(home, '.qwen', 'settings.json'), cwd && join(cwd, '.qwen', 'settings.json')].some((f) => f && mentions(f, /"enableOpenAILogging"\s*:\s*true/));+ case 'codebuddy': return setInShell(shell, /^OTEL_LOG_RAW_API_BODIES$/);+ case 'opencode': return setInShell(shell, /^(OTEL_|OPENCODE_CONFIG_CONTENT$)/);+ default: return true;+ }+}++/**+ * Whether the switch would have the agent send more off the computer than it does by itself. CodeBuddy sends its+ * traces to its makers unless told not to, and with its bodies kept in files each request's trace names its file and+ * size: so only when the person has turned that off (DISABLE_TELEMETRY, or no trace exporter).+ */+const sendsMore = (agent, shell = {}) => agent === 'codebuddy'+ && !/^(1|true|yes|on)$/i.test(String(shell.DISABLE_TELEMETRY ?? '').trim()) && String(shell.OTEL_TRACES_EXPORTER ?? '').trim().toLowerCase() !== 'none';++/** Remove the process folders under `dir` older than LOG_KEEP_DAYS. */+function prune(dir, now = Date.now()) {+ for (const name of files(dir)) {+ const at = join(dir, name);+ try { if (now - statSync(at).mtimeMs > LOG_KEEP_DAYS * 86_400_000) rmSync(at, { recursive: true, force: true }); } catch { /* in use, or gone */ }+ }+}++/**+ * The agent's logging switch, for one process: `{ args, env, log, close }` (`log`: where it writes, kept in the turn+ * log's `opened` so the turn's requests are found), or null for an agent with none. When the app leaves it off,+ * `log.none` says why: 'own' (the person set its telemetry), 'sendsMore' (it would send more to its makers).+ * `base`: the app's folder for these logs.+ */+export async function logSwitches(agent, { base, shell = {}, home = homedir(), cwd = '' }) {+ if (!base || !LOGGED_AGENTS.includes(agent)) return null;+ const none = { args: [], env: {}, close: () => {} };+ if (ownLogging(agent, { shell, home, cwd })) return { ...none, log: { agent, none: 'own' } };+ if (sendsMore(agent, shell)) return { ...none, log: { agent, none: 'sendsMore' } };+ const parent = join(base, agent);+ prune(parent);+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');+ const dir = join(parent, `${stamp}-${randomBytes(3).toString('hex')}`);+ mkdirSync(dir, { recursive: true });+ const on = { ...none, log: { agent, dir } };+ switch (agent) {+ case 'gemini':+ return { ...on, env: { GEMINI_TELEMETRY_ENABLED: 'true', GEMINI_TELEMETRY_TARGET: 'local', GEMINI_TELEMETRY_OUTFILE: join(dir, 'telemetry.log'), GEMINI_TELEMETRY_TRACES_ENABLED: 'true' } };+ case 'qwen':+ return { ...on, args: ['--openai-logging', '--openai-logging-dir', dir] };+ case 'codebuddy':+ return { ...on, env: { OTEL_LOG_RAW_API_BODIES: `file:${dir}` } };+ case 'opencode': {+ const receiver = await spanReceiver(join(dir, 'spans.jsonl'));+ return {+ ...on,+ env: { OTEL_EXPORTER_OTLP_ENDPOINT: receiver.url, OPENCODE_CONFIG_CONTENT: JSON.stringify({ experimental: { openTelemetry: true } }) },+ close: receiver.close,+ };+ }+ default: return null;+ }+}++/** an OpenTelemetry attribute's value (OTLP's JSON), as it was */+function otlpValue(v) {+ if (!v || typeof v !== 'object') return v;+ if ('stringValue' in v) return v.stringValue;+ if ('intValue' in v) return Number(v.intValue);+ if ('doubleValue' in v) return v.doubleValue;+ if ('boolValue' in v) return v.boolValue;+ if ('arrayValue' in v) return (v.arrayValue?.values ?? []).map(otlpValue);+ if ('kvlistValue' in v) return Object.fromEntries((v.kvlistValue?.values ?? []).map((kv) => [kv.key, otlpValue(kv.value)]));+ return null;+}++/** The AI SDK's spans of one request to a model (streamText's or generateText's): the ones kept. */+const isModelSpan = (name) => /^ai\.(streamText|generateText|streamObject|generateObject)\.do(Stream|Generate)$/.test(String(name));++/**+ * A receiver of OpenTelemetry's HTTP export (OTLP, JSON) on 127.0.0.1: of what it is sent it keeps the model+ * requests' spans, a line each in `file` (`{ name, start, end, attributes }`), and answers everything else with+ * nothing to say. `{ url, close }`.+ */+export function spanReceiver(file) {+ const server = createServer((req, res) => {+ const chunks = [];+ let size = 0;+ req.on('data', (d) => { size += d.length; if (size <= RECEIVE_MAX) chunks.push(d); });+ req.on('end', () => {+ try {+ if (req.method === 'POST' && req.url?.startsWith('/v1/traces') && size <= RECEIVE_MAX && /json/.test(String(req.headers['content-type']))) {+ let body = Buffer.concat(chunks);+ if (req.headers['content-encoding'] === 'gzip') body = gunzipSync(body);+ const kept = [];+ for (const rs of JSON.parse(body.toString('utf8')).resourceSpans ?? []) {+ for (const ss of rs.scopeSpans ?? []) {+ for (const span of ss.spans ?? []) {+ if (!isModelSpan(span.name)) continue;+ kept.push(JSON.stringify({+ name: span.name,+ start: Number(BigInt(span.startTimeUnixNano ?? 0) / 1_000_000n),+ end: Number(BigInt(span.endTimeUnixNano ?? 0) / 1_000_000n),+ attributes: Object.fromEntries((span.attributes ?? []).map((a) => [a.key, otlpValue(a.value)])),+ }));+ }+ }+ }+ if (kept.length) appendFileSync(file, `${kept.join('\n')}\n`);+ }+ } catch { /* not understood: nothing kept */ }+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ });+ return new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());+ resolve({ url: `http://127.0.0.1:${port}`, close: () => server.close() });+ });+ });+}++/* ── OpenAI's chat format (Qwen Code, and CodeBuddy's OpenAI-like services) ──── */++/** A chat message's content (a string, or parts: text, image_url), as the turn log has it. */+function chatParts(content) {+ if (typeof content === 'string') return content ? [text(content)] : [];+ return (Array.isArray(content) ? content : []).map((p) => {+ if (typeof p?.text === 'string') return text(p.text);+ if (p?.type === 'image_url') {+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(String(p.image_url?.url ?? p.image_url ?? ''));+ return m ? picture(m[1], m[2]) : text(`[image ${str(p.image_url?.url ?? p.image_url).slice(0, 200)}]`);+ }+ return { type: 'other', value: p };+ });+}++/** An assistant's message (or a whole answer's), as parts: its thinking, its words, its tool calls. */+function chatAssistant(m) {+ const out = [];+ const thought = m?.reasoning_content ?? m?.reasoning;+ if (typeof thought === 'string' && thought) out.push({ type: 'thinking', thinking: thought });+ out.push(...chatParts(m?.content));+ for (const call of m?.tool_calls ?? []) {+ out.push({ type: 'toolCall', id: String(call?.id ?? ''), name: String(call?.function?.name ?? ''), arguments: parse(call?.function?.arguments, call?.function?.arguments ?? {}) });+ }+ return out;+}++/**+ * A chat request's messages: its leading system messages as its system prompt, the rest as the turn log has them+ * (a later system message is context the agent put in).+ */+export function chatMessages(messages) {+ const system = [];+ const out = [];+ const names = new Map();+ for (const m of Array.isArray(messages) ? messages : []) {+ if (m?.role === 'system' || m?.role === 'developer') {+ const said = chatParts(m.content).map((p) => p.text ?? '').join('\n');+ if (!out.length) system.push(said);+ else out.push({ role: 'context', as: m.role, label: m.role, content: [text(said)] });+ } else if (m?.role === 'assistant') {+ const content = chatAssistant(m);+ for (const p of content) if (p.type === 'toolCall') names.set(p.id, p.name);+ out.push({ role: 'assistant', content });+ } else if (m?.role === 'tool') {+ out.push({ role: 'toolResult', toolCallId: String(m.tool_call_id ?? ''), toolName: names.get(m.tool_call_id) ?? String(m.name ?? 'tool'), content: chatParts(m.content), isError: false });+ } else if (m) {+ /* what the agent puts in the person's message by itself (CodeBuddy's memory, Qwen's reminders): context */+ let own = [];+ for (const part of chatParts(m.content)) {+ const tag = typeof part.text === 'string' ? /^\s*<(system-reminder)\b/.exec(part.text)?.[1] : null;+ if (!tag) { own.push(part); continue; }+ if (own.length) out.push({ role: 'user', content: own });+ own = [];+ out.push({ role: 'context', as: 'user', label: tag, content: [part] });+ }+ if (own.length) out.push({ role: 'user', content: own });+ }+ }+ return { systemPrompt: system.length ? system.join('\n\n') : null, messages: out };+}++/** A chat request's tools (`{ type: 'function', function: { name, description, parameters } }`). */+const chatTools = (tools) => (Array.isArray(tools) ? tools.map((t) => {+ const f = t?.function ?? t;+ return { name: f?.name, description: f?.description, parameters: f?.parameters };+}) : null);++/** OpenAI's chat usage as the turn log counts it (its prompt tokens count the cached ones too). */+const chatUsage = (u = {}) => {+ const cached = Number(u.prompt_tokens_details?.cached_tokens ?? u.prompt_cache_hit_tokens) || 0;+ return {+ input: Math.max(0, (Number(u.prompt_tokens) || 0) - cached),+ cacheRead: cached,+ cacheWrite: 0,+ output: Number(u.completion_tokens) || 0,+ reasoning: Number(u.completion_tokens_details?.reasoning_tokens) || 0,+ };+};++/** A chat completion (or the error in its place) as the turn log's answer. */+function chatAnswer(response, error) {+ if (!response && !error) return null;+ if (!response) return { role: 'assistant', content: [], stopReason: 'error', errorMessage: str(error.message ?? error) };+ const choice = response?.choices?.[0] ?? {};+ return {+ role: 'assistant', content: chatAssistant(choice.message ?? {}), usage: chatUsage(response?.usage),+ stopReason: choice.finish_reason ?? null, ...(response?.model ? { responseModel: String(response.model) } : {}),+ };+}++/* ── Qwen Code ───────────────────────────────────────────────────────────── */++/**+ * The requests in a Qwen Code log folder written between `from` and `to` (ms), each whole. Its own requests and its+ * subagents' carry the session's id (`context.sessionId`; a subagent's is named in `promptId`); the few it makes for+ * itself (`forked_query` and the like) carry none, and are the folder's process's all the same.+ */+export function qwenCalls(dir, { sessionId, from = 0, to = Infinity } = {}) {+ const calls = [];+ for (const name of files(dir).filter((n) => /^openai-.*\.json$/.test(n))) {+ const entry = parse(readText(join(dir, name)));+ if (!entry?.request) continue;+ const at = ms(entry.timestamp);+ if (at === null || at < from || at > to) continue;+ const context = entry.context ?? {};+ if (context.sessionId && sessionId && context.sessionId !== sessionId) continue;+ const { systemPrompt, messages } = chatMessages(entry.request.messages);+ const { messages: _m, tools, ...settings } = entry.request;+ const promptId = String(context.promptId ?? '');+ const sub = /^[^#]+#([^#]+)#\d+$/.exec(promptId)?.[1] ?? (context.sessionId ? null : promptId || null);+ calls.push({+ /* the file is written once its answer has come: when it was asked is not kept */+ startedAt: at, ms: null, messages, systemPrompt, tools: chatTools(tools), answer: chatAnswer(entry.response, entry.error), settings,+ ...(sub ? { thread: { id: sub, label: sub } } : {}),+ });+ }+ return calls.sort((a, b) => a.startedAt - b.startedAt);+}++/* ── CodeBuddy ───────────────────────────────────────────────────────────── */++/** A Responses API request's input (messages, function calls and their output) as the turn log has it. */+function responsesMessages(input) {+ const out = [];+ const names = new Map();+ for (const item of typeof input === 'string' ? [{ type: 'message', role: 'user', content: input }] : Array.isArray(input) ? input : []) {+ if (item?.type === 'function_call') {+ names.set(item.call_id ?? item.callId, item.name);+ const call = { type: 'toolCall', id: String(item.call_id ?? item.callId ?? ''), name: String(item.name ?? ''), arguments: parse(item.arguments, item.arguments ?? {}) };+ const last = out[out.length - 1];+ if (last?.role === 'assistant') last.content.push(call); else out.push({ role: 'assistant', content: [call] });+ } else if (item?.type === 'function_call_output') {+ const id = item.call_id ?? item.callId;+ out.push({ role: 'toolResult', toolCallId: String(id ?? ''), toolName: names.get(id) ?? 'tool', content: [text(str(item.output))], isError: false });+ } else if (item?.role) {+ const content = typeof item.content === 'string' ? [text(item.content)] : (item.content ?? []).map((p) => (typeof p?.text === 'string' ? text(p.text) : { type: 'other', value: p }));+ out.push(item.role === 'assistant' ? { role: 'assistant', content } : item.role === 'user' ? { role: 'user', content } : { role: 'context', as: String(item.role), label: String(item.role), content });+ }+ }+ return out;+}++/** CodeBuddy's answer as it keeps it (its own words, `output`: messages and function calls; its usage). */+function codebuddyAnswer(response, model) {+ const content = [];+ for (const item of response?.output ?? []) {+ if (item?.type === 'function_call') content.push({ type: 'toolCall', id: String(item.callId ?? item.call_id ?? ''), name: String(item.name ?? ''), arguments: parse(item.arguments, item.arguments ?? {}) });+ else if (item?.type === 'reasoning') content.push({ type: 'thinking', thinking: (item.content ?? item.summary ?? []).map((s) => s?.text ?? '').join('\n') });+ else for (const p of item?.content ?? []) content.push(typeof p?.text === 'string' ? text(p.text) : { type: 'other', value: p });+ }+ const u = response?.usage ?? {};+ const cached = Number(u.inputTokensDetails?.cached_tokens) || 0;+ return {+ role: 'assistant', content,+ usage: { input: Math.max(0, (Number(u.inputTokens) || 0) - cached), cacheRead: cached, cacheWrite: 0, output: Number(u.outputTokens) || 0, reasoning: Number(u.outputTokensDetails?.reasoning_tokens) || 0 },+ ...(response?.model ?? model ? { responseModel: String(response?.model ?? model) } : {}),+ };+}++/**+ * The requests of one session in a CodeBuddy raw bodies folder that began between `from` and `to` (ms): its+ * `index.jsonl` names each request's files and the session it was for (`root_session_id`, the ACP session's id; a+ * call it makes for itself, a title for one, is a session of its own under it).+ */+export function codebuddyCalls(dir, { sessionId, from = 0, to = Infinity } = {}) {+ const calls = [];+ for (const entry of jsonLines(join(dir, 'index.jsonl'))) {+ if (sessionId && entry?.root_session_id !== sessionId && entry?.session_id !== sessionId) continue;+ const name = (f) => (typeof f === 'string' && /^[\w.-]+$/.test(f) ? join(dir, f) : null);+ const request = parse(readText(name(entry.request_file) ?? ''));+ const response = parse(readText(name(entry.response_file) ?? ''));+ if (!request) continue;+ const at = Number(response?.started_at) || ms(entry.timestamp) || 0;+ if (at < from || at > to) continue;+ const chat = Array.isArray(request.messages) ? chatMessages(request.messages)+ : { systemPrompt: typeof request.instructions === 'string' ? request.instructions : null, messages: responsesMessages(request.input) };+ const { messages: _m, input: _i, instructions: _s, tools, ...settings } = request;+ const own = entry.session_id && entry.session_id !== entry.root_session_id;+ calls.push({+ startedAt: at, ms: Math.max(0, (Number(response?.completed_at) || at) - at), ...chat,+ tools: chatTools(tools) ?? [], answer: response ? codebuddyAnswer(response, entry.model) : null, settings,+ ...(own ? { thread: { id: String(entry.session_id), label: String(entry.query_source ?? 'helper') } } : {}),+ });+ }+ return calls.sort((a, b) => a.startedAt - b.startedAt);+}++/* ── Gemini CLI ──────────────────────────────────────────────────────────── */++/** The records of a Gemini CLI telemetry file: JSON values one after the other, each split where its braces close. */+export function splitRecords(raw) {+ const out = [];+ let depth = 0;+ let inString = false;+ let escaped = false;+ let start = -1;+ for (let i = 0; i < raw.length; i += 1) {+ const c = raw[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (c === '\\') escaped = true;+ else if (c === '"') inString = false;+ continue;+ }+ if (c === '"') inString = true;+ else if (c === '{' || c === '[') { if (depth++ === 0) start = i; }+ else if ((c === '}' || c === ']') && depth > 0 && --depth === 0) {+ try { out.push(JSON.parse(raw.slice(start, i + 1))); } catch { /* a record cut short */ }+ }+ }+ return out;+}++/** a span's time ([seconds, nanoseconds]) in ms */+const hrMs = (t) => (Array.isArray(t) ? Number(t[0]) * 1000 + Math.round(Number(t[1]) / 1e6) : null);++/** Gemini's content parts, as the turn log has them; a function's response is a message of its own. */+function geminiMessages(contents) {+ const out = [];+ for (const c of Array.isArray(contents) ? contents : []) {+ let own = [];+ const results = [];+ for (const p of c?.parts ?? []) {+ /* what Gemini CLI puts first by itself: the date, the system, the folder */+ if (c.role !== 'model' && typeof p?.text === 'string' && /^\s*<session_context>/.test(p.text)) {+ if (own.length) out.push({ role: 'user', content: own });+ own = [];+ out.push({ role: 'context', as: 'user', label: 'session_context', content: [text(p.text)] });+ } else if (typeof p?.text === 'string') own.push(p.thought ? { type: 'thinking', thinking: p.text } : text(p.text));+ else if (p?.functionCall) own.push({ type: 'toolCall', id: String(p.functionCall.id ?? ''), name: String(p.functionCall.name ?? ''), arguments: p.functionCall.args ?? {} });+ else if (p?.functionResponse) {+ const r = p.functionResponse;+ const said = r.response?.output ?? r.response?.error ?? r.response;+ results.push({ role: 'toolResult', toolCallId: String(r.id ?? ''), toolName: String(r.name ?? 'tool'), content: [text(str(said))], isError: r.response?.error != null });+ } else if (p?.inlineData) own.push(picture(p.inlineData.mimeType, p.inlineData.data));+ else if (p) own.push({ type: 'other', value: p });+ }+ if (own.length) out.push({ role: c.role === 'model' ? 'assistant' : 'user', content: own });+ out.push(...results);+ }+ return out;+}++/** An answer's chunks (a stream's, as Gemini CLI keeps them) joined into its parts. */+function geminiAnswer(chunks) {+ const parts = [];+ let finish = null;+ for (const chunk of Array.isArray(chunks) ? chunks : [chunks]) {+ const candidate = chunk?.candidates?.[0];+ if (candidate?.finishReason) finish = candidate.finishReason;+ for (const p of candidate?.content?.parts ?? []) {+ const last = parts[parts.length - 1];+ if (typeof p?.text === 'string') {+ const kind = p.thought ? 'thinking' : 'text';+ if (last?.type === kind) last[kind] += p.text;+ else parts.push(kind === 'thinking' ? { type: 'thinking', thinking: p.text } : text(p.text));+ } else if (p?.functionCall) parts.push({ type: 'toolCall', id: String(p.functionCall.id ?? ''), name: String(p.functionCall.name ?? ''), arguments: p.functionCall.args ?? {} });+ else if (p) parts.push({ type: 'other', value: p });+ }+ }+ return { parts, finish };+}++/** Gemini's tools (`[{ functionDeclarations: [...] }]`), each as the turn log has it. */+const geminiTools = (tools) => (Array.isArray(tools) ? tools.flatMap((t) => (Array.isArray(t?.functionDeclarations)+ ? t.functionDeclarations.map((f) => ({ name: f?.name, description: f?.description, parameters: f?.parametersJsonSchema ?? f?.parameters }))+ : [{ name: Object.keys(t ?? {})[0] ?? 'tool', description: '', parameters: t }])) : null);++/**+ * The requests of one session in Gemini CLI's telemetry records whose asking was between `from` and `to` (ms).+ * Calls Gemini CLI makes for itself (which model to use: role `utility_router`) are named as its own.+ */+export function geminiCallsOf(records, { sessionId, from = 0, to = Infinity } = {}) {+ const spans = new Map();+ for (const r of records) if (r?._spanContext?.spanId && r.name === 'llm_call') spans.set(r._spanContext.spanId, r);+ const logs = records.filter((r) => typeof r?.attributes?.['event.name'] === 'string' && (!sessionId || r.attributes['session.id'] === sessionId));+ const calls = [];+ logs.forEach((r, i) => {+ const a = r.attributes;+ if (a['event.name'] !== 'gemini_cli.api_request') return;+ const at = ms(a['event.timestamp']) ?? hrMs(r.hrTime) ?? 0;+ if (at < from || at > to) return;+ /* its answer (or its error): the next of its prompt id after it */+ const reply = logs.slice(i + 1).find((x) => x.attributes.prompt_id === a.prompt_id && /^gemini_cli\.api_(response|error)$/.test(x.attributes['event.name']));+ const span = spans.get(r.spanContext?.spanId);+ const sa = span?.attributes ?? {};+ const system = parse(sa['gen_ai.system_instructions']);+ const ra = reply?.attributes ?? {};+ const { parts, finish } = geminiAnswer(parse(ra.response_text, []));+ const input = Number(ra.input_token_count) || 0;+ const cached = Number(ra.cached_content_token_count) || 0;+ const thoughts = Number(ra.thoughts_token_count) || 0;+ const answer = ra['event.name'] === 'gemini_cli.api_error'+ ? { role: 'assistant', content: [], stopReason: 'error', errorMessage: str(ra.error ?? ra.error_message ?? 'error') }+ : reply ? {+ role: 'assistant', content: parts,+ usage: { input: Math.max(0, input - cached), cacheRead: cached, cacheWrite: 0, output: (Number(ra.output_token_count) || 0) + thoughts, reasoning: thoughts },+ stopReason: finish ?? (Array.isArray(ra.finish_reasons) ? ra.finish_reasons[0] : null) ?? null, ...(ra.model ? { responseModel: String(ra.model) } : {}),+ } : null;+ const role = String(a.role ?? 'main');+ calls.push({+ startedAt: at, ms: Number(ra.duration_ms) || (ms(ra['event.timestamp']) ?? at) - at,+ messages: geminiMessages(parse(a.request_text, [])),+ systemPrompt: typeof system === 'string' ? system : system ? str(system) : null,+ tools: span ? geminiTools(parse(sa['gen_ai.tool.definitions'], [])) : null,+ answer, settings: { model: a.model ?? null, auth: a.auth_type ?? null },+ ...(role !== 'main' ? { thread: { id: role, label: role } } : {}),+ });+ });+ return calls;+}++export const geminiCalls = (file, opts) => geminiCallsOf(splitRecords(readText(file)), opts);++/* ── OpenCode ────────────────────────────────────────────────────────────── */++/** The AI SDK's prompt (system, user, assistant, tool messages, each its parts), as the turn log has it. */+function aiSdkMessages(prompt) {+ const system = [];+ const out = [];+ const part = (p) => {+ switch (p?.type) {+ case 'text': return text(p.text);+ case 'reasoning': return { type: 'thinking', thinking: String(p.text ?? '') };+ case 'tool-call': return { type: 'toolCall', id: String(p.toolCallId ?? ''), name: String(p.toolName ?? ''), arguments: parse(p.input ?? p.args, p.input ?? p.args ?? {}) };+ case 'file': case 'image':+ return /^image\//.test(String(p.mediaType ?? p.mimeType ?? 'image/')) && typeof (p.data ?? p.image) === 'string' && !/^https?:/.test(p.data ?? p.image)+ ? picture(p.mediaType ?? p.mimeType, p.data ?? p.image) : { type: 'other', value: p };+ default: return { type: 'other', value: p };+ }+ };+ for (const m of Array.isArray(prompt) ? prompt : []) {+ const content = typeof m?.content === 'string' ? [text(m.content)] : (m?.content ?? []);+ if (m?.role === 'system') {+ const said = content.map((p) => p.text ?? '').join('\n');+ if (!out.length) system.push(said);+ else out.push({ role: 'context', as: 'system', label: 'system', content: [text(said)] });+ } else if (m?.role === 'tool') {+ for (const r of content) {+ const o = r?.output ?? {};+ const said = o.type === 'content' && Array.isArray(o.value) ? o.value.map((v) => (v.type === 'text' ? text(v.text) : v.type === 'media' || v.type === 'image-data' ? picture(v.mediaType, v.data) : { type: 'other', value: v }))+ : [text(typeof o.value === 'string' ? o.value : str(o.value ?? r?.result ?? o))];+ out.push({ role: 'toolResult', toolCallId: String(r?.toolCallId ?? ''), toolName: String(r?.toolName ?? 'tool'), content: said, isError: /^error/.test(String(o.type)) });+ }+ } else if (m) {+ out.push({ role: m.role === 'assistant' ? 'assistant' : 'user', content: content.map(part) });+ }+ }+ return { systemPrompt: system.length ? system.join('\n\n') : null, messages: out };+}++/** The AI SDK's tools (each a JSON string: a function's name, description, input schema; or a provider's own). */+const aiSdkTools = (tools) => (Array.isArray(tools) ? tools.map((t) => {+ const tool = parse(t, t) ?? {};+ return { name: tool.name ?? tool.id, description: tool.description, parameters: tool.inputSchema ?? tool.parameters ?? tool.args };+}) : null);++/**+ * The requests in the spans the receiver kept of an OpenCode process whose asking was between `from` and `to` (ms).+ * One process is one ACP session; a request of another session in it is a subagent's (a session of its own).+ */+export function opencodeCallsOf(spans, { sessionId, from = 0, to = Infinity } = {}) {+ return spans.filter((s) => isModelSpan(s?.name) && s.start >= from && s.start <= to).map((s) => {+ const a = s.attributes ?? {};+ const { systemPrompt, messages } = aiSdkMessages(parse(a['ai.prompt.messages'], []));+ const answer = [];+ const reasoning = a['ai.response.reasoning'];+ if (typeof reasoning === 'string' && reasoning) answer.push({ type: 'thinking', thinking: reasoning });+ if (typeof a['ai.response.text'] === 'string' && a['ai.response.text']) answer.push(text(a['ai.response.text']));+ for (const c of parse(a['ai.response.toolCalls'], []) ?? []) {+ answer.push({ type: 'toolCall', id: String(c?.toolCallId ?? ''), name: String(c?.toolName ?? ''), arguments: parse(c?.input ?? c?.args, c?.input ?? c?.args ?? {}) });+ }+ const inputAll = Number(a['ai.usage.inputTokens']) || 0;+ const cacheRead = Number(a['ai.usage.inputTokenDetails.cacheReadTokens'] ?? a['ai.usage.cachedInputTokens']) || 0;+ const cacheWrite = Number(a['ai.usage.inputTokenDetails.cacheWriteTokens']) || 0;+ const session = a['session.id'] ?? a['ai.telemetry.metadata.sessionId'] ?? null;+ return {+ startedAt: s.start, ms: Math.max(0, (s.end || s.start) - s.start), messages, systemPrompt,+ tools: aiSdkTools(a['ai.prompt.tools']) ?? [],+ answer: {+ role: 'assistant', content: answer,+ usage: { input: Number(a['ai.usage.inputTokenDetails.noCacheTokens'] ?? Math.max(0, inputAll - cacheRead - cacheWrite)) || 0, cacheRead, cacheWrite, output: Number(a['ai.usage.outputTokens']) || 0, reasoning: Number(a['ai.usage.reasoningTokens']) || 0 },+ stopReason: a['ai.response.finishReason'] ?? null,+ ...(a['ai.response.model'] ?? a['ai.model.id'] ? { responseModel: String(a['ai.response.model'] ?? a['ai.model.id']) } : {}),+ ...(a['ai.model.provider'] ? { provider: String(a['ai.model.provider']) } : {}),+ },+ ...(a['ai.prompt.toolChoice'] ? { settings: { toolChoice: parse(a['ai.prompt.toolChoice']) } } : {}),+ ...(session && sessionId && session !== sessionId ? { thread: { id: String(session), label: `subagent ${session}` } } : {}),+ lacks: ['opencodeBeforeProvider'],+ };+ }).sort((a, b) => a.startedAt - b.startedAt);+}++export const opencodeCalls = (file, opts) => opencodeCallsOf(jsonLines(file), opts);++/* ── all ─────────────────────────────────────────────────────────────────── */++/**+ * A turn's requests, read from the log its agent was started with (`log`: the `opened.log` of its turn log):+ * `{ file, calls }` in time order, or null when there is none to read.+ */+export function agentLogCalls({ agent, sessionId, log, from = 0, to = Infinity }) {+ const dir = typeof log?.dir === 'string' && log.agent === agent ? log.dir : null;+ if (!dir || !existsSync(dir)) return null;+ const opts = { sessionId, from, to };+ switch (agent) {+ case 'gemini': return { file: join(dir, 'telemetry.log'), calls: geminiCalls(join(dir, 'telemetry.log'), opts) };+ case 'qwen': return { file: dir, calls: qwenCalls(dir, opts) };+ case 'codebuddy': return { file: join(dir, 'index.jsonl'), calls: codebuddyCalls(dir, opts) };+ case 'opencode': return { file: join(dir, 'spans.jsonl'), calls: opencodeCalls(join(dir, 'spans.jsonl'), opts) };+ default: return null;+ }+}diff --git a/apps/desktop/src/agent-logs.test.mjs b/apps/desktop/src/agent-logs.test.mjsnew file mode 100644index 0000000..cf66dae--- /dev/null+++ b/apps/desktop/src/agent-logs.test.mjs@@ -0,0 +1,242 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, utimesSync, writeFileSync } from 'node:fs';+import { request } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { gzipSync } from 'node:zlib';+import { agentLogCalls, codebuddyCalls, geminiCallsOf, logSwitches, opencodeCalls, ownLogging, qwenCalls, spanReceiver, splitRecords } from './agent-logs.mjs';+import { agentRecordCalls } from './agent-records.mjs';++const at = (s) => new Date(Date.UTC(2026, 9, 15, 10, 0, s)).toISOString();+const t = (s) => Date.parse(at(s));+const temp = (name) => mkdtempSync(join(tmpdir(), `of-${name}-`));+const jsonl = (rows) => `${rows.map((r) => JSON.stringify(r)).join('\n')}\n`;++test('each agent is started with its own logging switch into a folder of its process, never over a setting of the person\'s', async () => {+ const base = temp('logs');+ const home = temp('home');+ const gemini = await logSwitches('gemini', { base, home });+ assert.equal(gemini.log.agent, 'gemini');+ assert.ok(gemini.log.dir.startsWith(join(base, 'gemini')) && existsSync(gemini.log.dir));+ assert.deepEqual(gemini.env, { GEMINI_TELEMETRY_ENABLED: 'true', GEMINI_TELEMETRY_TARGET: 'local', GEMINI_TELEMETRY_OUTFILE: join(gemini.log.dir, 'telemetry.log'), GEMINI_TELEMETRY_TRACES_ENABLED: 'true' });+ assert.ok(!('GEMINI_TELEMETRY_LOG_PROMPTS' in gemini.env), 'prompt logging as the person has it (on by Gemini CLI\'s default)');+ const qwen = await logSwitches('qwen', { base, home });+ assert.deepEqual(qwen.args, ['--openai-logging', '--openai-logging-dir', qwen.log.dir], 'its folder given, never the project\'s logs/openai');+ const codebuddy = await logSwitches('codebuddy', { base, home, shell: { DISABLE_TELEMETRY: '1' } });+ assert.deepEqual(codebuddy.env, { OTEL_LOG_RAW_API_BODIES: `file:${codebuddy.log.dir}` });++ assert.deepEqual((await logSwitches('codebuddy', { base, home })).log, { agent: 'codebuddy', none: 'sendsMore' }, 'its traces go to its makers: they would name each file');+ assert.deepEqual((await logSwitches('codebuddy', { base, home, shell: { OTEL_TRACES_EXPORTER: 'none' } })).log.dir ? 'on' : 'off', 'on');+ assert.deepEqual((await logSwitches('gemini', { base, home, shell: { OTEL_EXPORTER_OTLP_ENDPOINT: 'http://x' } })).log, { agent: 'gemini', none: 'own' });+ assert.deepEqual((await logSwitches('opencode', { base, home, shell: { OPENCODE_CONFIG_CONTENT: '{}' } })).log, { agent: 'opencode', none: 'own' });+ mkdirSync(join(home, '.gemini'), { recursive: true });+ writeFileSync(join(home, '.gemini', 'settings.json'), '{ "telemetry": { "enabled": true, "target": "gcp" } }');+ assert.equal(ownLogging('gemini', { home }), true, 'their own telemetry settings are left as they are');+ mkdirSync(join(home, '.qwen'), { recursive: true });+ writeFileSync(join(home, '.qwen', 'settings.json'), '{ "model": { "enableOpenAILogging": true } }');+ assert.equal(ownLogging('qwen', { home }), true);+ assert.equal(await logSwitches('cursor', { base, home }), null, 'no switch: Cursor makes its prompt on its servers');+ assert.equal(await logSwitches('qwen', { base: null, home }), null, 'Developer mode off');++ /* a process's folder from long ago goes as another starts */+ const old = join(base, 'qwen', 'old-process');+ mkdirSync(old);+ const long = (Date.now() - 30 * 86_400_000) / 1000;+ utimesSync(old, long, long);+ await logSwitches('qwen', { base, home: temp('home') });+ assert.equal(existsSync(old), false);+ assert.ok(existsSync(qwen.log.dir), 'a recent one stays');+});++test("Qwen Code's log: one request a file, its system message as the system prompt, the session's own and its subagents'", () => {+ const dir = temp('qwen');+ const sid = 'aaaa-1111';+ const file = (name, s, context, request, response) => writeFileSync(join(dir, `openai-${name}.json`), JSON.stringify({ timestamp: at(s), request, response, error: null, context, system: {} }));+ const tools = [{ type: 'function', function: { name: 'run_shell_command', description: 'Run', parameters: { type: 'object' } } }];+ file('1', 2, { sessionId: sid, promptId: `${sid}########1` }, {+ model: 'qwen-x', stream: true, tools,+ messages: [{ role: 'system', content: 'You are Qwen Code.' }, { role: 'user', content: [{ type: 'text', text: '<system-reminder>today</system-reminder>' }, { type: 'text', text: 'Make a title' }] }],+ }, { model: 'qwen-x', choices: [{ message: { role: 'assistant', content: null, reasoning_content: 'plan', tool_calls: [{ id: 'c1', type: 'function', function: { name: 'run_shell_command', arguments: '{"command":"openfilm look"}' } }] }, finish_reason: 'tool_calls' }], usage: { prompt_tokens: 120, completion_tokens: 9, prompt_tokens_details: { cached_tokens: 100 } } });+ file('2', 5, { sessionId: sid, promptId: `${sid}########1` }, {+ model: 'qwen-x', tools,+ messages: [{ role: 'system', content: 'You are Qwen Code.' }, { role: 'user', content: 'Make a title' },+ { role: 'assistant', content: '', tool_calls: [{ id: 'c1', type: 'function', function: { name: 'run_shell_command', arguments: '{}' } }] },+ { role: 'tool', tool_call_id: 'c1', content: 'frames saved' }],+ }, { choices: [{ message: { role: 'assistant', content: 'Done.' }, finish_reason: 'stop' }], usage: { prompt_tokens: 10, completion_tokens: 2 } });+ file('3', 6, { sessionId: sid, promptId: `${sid}#memory-extractor-1#0` }, { model: 'qwen-x', messages: [{ role: 'system', content: 'Extract.' }, { role: 'user', content: 'x' }] }, { choices: [{ message: { content: 'ok' } }] });+ file('4', 7, { promptId: 'forked_query' }, { model: 'qwen-x', messages: [{ role: 'user', content: 'y' }] }, null);+ file('5', 8, { sessionId: 'another', promptId: 'another########1' }, { model: 'qwen-x', messages: [] }, null);++ const calls = qwenCalls(dir, { sessionId: sid });+ assert.equal(calls.length, 4, 'not another session\'s');+ const [first, second, sub, own] = calls;+ assert.equal(first.systemPrompt, 'You are Qwen Code.');+ assert.deepEqual(first.tools, [{ name: 'run_shell_command', description: 'Run', parameters: { type: 'object' } }]);+ assert.deepEqual(first.messages, [+ { role: 'context', as: 'user', label: 'system-reminder', content: [{ type: 'text', text: '<system-reminder>today</system-reminder>' }] },+ { role: 'user', content: [{ type: 'text', text: 'Make a title' }] },+ ], 'what it put in the person\'s message by itself, apart');+ assert.deepEqual(first.answer.content, [{ type: 'thinking', thinking: 'plan' }, { type: 'toolCall', id: 'c1', name: 'run_shell_command', arguments: { command: 'openfilm look' } }]);+ assert.deepEqual(first.answer.usage, { input: 20, cacheRead: 100, cacheWrite: 0, output: 9, reasoning: 0 });+ assert.equal(first.ms, null, 'how long is not in the log');+ assert.deepEqual(first.settings, { model: 'qwen-x', stream: true });+ assert.deepEqual(second.messages[2], { role: 'toolResult', toolCallId: 'c1', toolName: 'run_shell_command', content: [{ type: 'text', text: 'frames saved' }], isError: false });+ assert.equal(sub.thread.label, 'memory-extractor-1');+ assert.equal(own.thread.label, 'forked_query');+ assert.equal(own.answer, null);+ assert.equal(qwenCalls(dir, { sessionId: sid, from: t(4), to: t(5) }).length, 1, 'only the turn\'s');+});++test("Gemini CLI's telemetry: records split, each request whole from its log record, its span and its response", () => {+ const sid = 'gem-1234';+ const span = (spanId, promptId, extra) => ({ _spanContext: { traceId: 'tr', spanId }, name: 'llm_call', startTime: [1, 0], endTime: [2, 0], attributes: {+ 'gen_ai.prompt.name': promptId, 'gen_ai.conversation.id': sid,+ 'gen_ai.system_instructions': JSON.stringify('You are Gemini CLI. Never "}" a brace.'),+ 'gen_ai.tool.definitions': JSON.stringify([{ functionDeclarations: [{ name: 'run_shell_command', description: 'Run', parametersJsonSchema: { type: 'object' } }] }]),+ ...extra } });+ const log = (name, s, attributes, spanId) => ({ hrTime: [0, 0], ...(spanId ? { spanContext: { traceId: 'tr', spanId } } : {}), attributes: { 'session.id': sid, 'event.name': name, 'event.timestamp': at(s), ...attributes }, _body: name });+ const records = [+ log('gemini_cli.config', 0, { 'session.id': 'the-process' }),+ log('gemini_cli.api_request', 1, { role: 'utility_router', prompt_id: 'classifier-1', model: 'flash', request_text: JSON.stringify([{ role: 'user', parts: [{ text: 'route' }] }]) }, 's0'),+ log('gemini_cli.api_response', 1, { role: 'utility_router', prompt_id: 'classifier-1', model: 'flash', duration_ms: 5, response_text: '[]' }),+ log('gemini_cli.api_request', 2, { role: 'main', prompt_id: 'p1', model: 'pro', auth_type: 'oauth', request_text: JSON.stringify([{ role: 'user', parts: [{ text: '<session_context>\nToday is…</session_context>' }, { text: 'Make a title' }] }]) }, 's1'),+ log('gemini_cli.api_response', 4, { role: 'main', prompt_id: 'p1', model: 'pro', duration_ms: 1800, input_token_count: 120, cached_content_token_count: 100, output_token_count: 9, thoughts_token_count: 4,+ response_text: JSON.stringify([{ candidates: [{ content: { role: 'model', parts: [{ text: 'pl', thought: true }, { text: 'an', thought: true }] } }] },+ { candidates: [{ content: { role: 'model', parts: [{ functionCall: { id: 'f1', name: 'run_shell_command', args: { command: 'openfilm look' } } }] }, finishReason: 'STOP' }] }]) }),+ log('gemini_cli.api_request', 6, { role: 'main', prompt_id: 'p1', model: 'pro', request_text: JSON.stringify([+ { role: 'user', parts: [{ text: 'Make a title' }] },+ { role: 'model', parts: [{ functionCall: { id: 'f1', name: 'run_shell_command', args: {} } }] },+ { role: 'user', parts: [{ functionResponse: { id: 'f1', name: 'run_shell_command', response: { output: 'frames saved' } } }] }]) }, 's2'),+ log('gemini_cli.api_error', 7, { role: 'main', prompt_id: 'p1', error: 'quota' }),+ log('gemini_cli.api_request', 8, { 'session.id': 'other', role: 'main', prompt_id: 'p9', request_text: '[]' }, 's9'),+ span('s0', 'classifier-1'), span('s1', 'p1'), span('s2', 'p1'),+ { scopeMetrics: [{ metrics: [] }] },+ ];+ /* as Gemini CLI writes them: pretty JSON, one after the other */+ const raw = records.map((r) => JSON.stringify(r, null, 2)).join('\n');+ assert.equal(splitRecords(raw).length, records.length, 'split where each closes, a brace in a string kept');++ const calls = geminiCallsOf(splitRecords(raw), { sessionId: sid });+ assert.equal(calls.length, 3, 'not another session\'s');+ const [router, first, second] = calls;+ assert.equal(router.thread.label, 'utility_router', 'its own call, named');+ assert.equal(first.systemPrompt, 'You are Gemini CLI. Never "}" a brace.');+ assert.deepEqual(first.tools, [{ name: 'run_shell_command', description: 'Run', parameters: { type: 'object' } }]);+ assert.deepEqual(first.messages, [+ { role: 'context', as: 'user', label: 'session_context', content: [{ type: 'text', text: '<session_context>\nToday is…</session_context>' }] },+ { role: 'user', content: [{ type: 'text', text: 'Make a title' }] },+ ]);+ assert.deepEqual(first.answer.content, [{ type: 'thinking', thinking: 'plan' }, { type: 'toolCall', id: 'f1', name: 'run_shell_command', arguments: { command: 'openfilm look' } }], 'a stream\'s chunks joined');+ assert.deepEqual(first.answer.usage, { input: 20, cacheRead: 100, cacheWrite: 0, output: 13, reasoning: 4 });+ assert.equal(first.answer.stopReason, 'STOP');+ assert.equal(first.ms, 1800);+ assert.equal(first.startedAt, t(2));+ assert.deepEqual(first.settings, { model: 'pro', auth: 'oauth' });+ assert.deepEqual(second.messages[2], { role: 'toolResult', toolCallId: 'f1', toolName: 'run_shell_command', content: [{ type: 'text', text: 'frames saved' }], isError: false });+ assert.equal(second.answer.stopReason, 'error');+ assert.equal(second.answer.errorMessage, 'quota');+ assert.equal(geminiCallsOf(splitRecords(raw), { sessionId: sid, from: t(5), to: t(9) }).length, 1);+});++test("CodeBuddy's raw bodies: its index names each request's files and session; its helpers' named", () => {+ const dir = temp('codebuddy');+ const root = 'root-1234';+ const pair = (id, request, response) => {+ writeFileSync(join(dir, `${id}.request.json`), JSON.stringify(request));+ writeFileSync(join(dir, `${id}.response.json`), JSON.stringify(response));+ };+ pair('m1', { model: 'cb', messages: [{ role: 'system', content: 'Title it.' }, { role: 'user', content: 'hi' }] },+ { output: [{ type: 'message', content: [{ type: 'output_text', text: 'Greeting' }] }], usage: { inputTokens: 5, outputTokens: 1 }, started_at: t(1), completed_at: t(1) + 30 });+ pair('m2', { model: 'cb', max_tokens: 100, tools: [{ type: 'function', function: { name: 'Read', description: 'Read a file', parameters: { type: 'object' } } }],+ messages: [{ role: 'system', content: 'You are CodeBuddy Code.' }, { role: 'user', content: [{ type: 'text', text: '<system-reminder data-role="memory">notes</system-reminder>' }, { type: 'text', text: 'hi' }], conversationRequestId: 'r1' }] },+ { output: [{ type: 'function_call', name: 'Read', arguments: '{"file_path":"film.html"}', callId: 'k1' }], usage: { inputTokens: 50, outputTokens: 7, inputTokensDetails: { cached_tokens: 40 } }, model: 'cb', started_at: t(2), completed_at: t(2) + 600 });+ writeFileSync(join(dir, 'index.jsonl'), jsonl([+ { timestamp: at(1), session_id: 'title-1', root_session_id: root, model: 'cb', message_id: 'm1', request_file: 'm1.request.json', response_file: 'm1.response.json' },+ { timestamp: at(2), session_id: root, root_session_id: root, query_source: 'conversation', model: 'cb', message_id: 'm2', request_file: 'm2.request.json', response_file: 'm2.response.json' },+ { timestamp: at(3), session_id: 'x', root_session_id: 'another', request_file: '../../etc/passwd', response_file: 'm2.response.json' },+ ]));+ const calls = codebuddyCalls(dir, { sessionId: root });+ assert.equal(calls.length, 2);+ assert.equal(calls[0].thread.id, 'title-1', 'a call it made for itself');+ assert.equal(calls[1].thread, undefined);+ assert.equal(calls[1].systemPrompt, 'You are CodeBuddy Code.');+ assert.deepEqual(calls[1].messages.map((m) => [m.role, m.label ?? null]), [['context', 'system-reminder'], ['user', null]]);+ assert.deepEqual(calls[1].tools, [{ name: 'Read', description: 'Read a file', parameters: { type: 'object' } }]);+ assert.deepEqual(calls[1].answer.content, [{ type: 'toolCall', id: 'k1', name: 'Read', arguments: { file_path: 'film.html' } }]);+ assert.deepEqual(calls[1].answer.usage, { input: 10, cacheRead: 40, cacheWrite: 0, output: 7, reasoning: 0 });+ assert.equal(calls[1].ms, 600);+ assert.deepEqual(calls[1].settings, { model: 'cb', max_tokens: 100 });+});++/** OTLP's JSON export of spans, as OpenCode's exporter sends it */+const exportOf = (spans) => JSON.stringify({ resourceSpans: [{ resource: { attributes: [] }, scopeSpans: [{ scope: { name: 'opencode' }, spans }] }] });+const otlpSpan = (name, s, attrs) => ({+ traceId: 't', spanId: name, name, kind: 1, startTimeUnixNano: String(BigInt(t(s)) * 1_000_000n), endTimeUnixNano: String(BigInt(t(s) + 2500) * 1_000_000n),+ attributes: Object.entries(attrs).map(([key, v]) => ({ key, value: Array.isArray(v) ? { arrayValue: { values: v.map((x) => ({ stringValue: x })) } } : typeof v === 'number' ? { intValue: v } : { stringValue: v } })),+});+const post = (url, body, headers) => new Promise((resolve, reject) => {+ const req = request(`${url}/v1/traces`, { method: 'POST', headers: { 'content-type': 'application/json', ...headers } }, (res) => { res.resume(); res.on('end', () => resolve(res.statusCode)); });+ req.on('error', reject);+ req.end(body);+});++test("OpenCode's telemetry: the app's receiver on 127.0.0.1 keeps only its model requests, each read whole", async () => {+ const dir = temp('opencode');+ const file = join(dir, 'spans.jsonl');+ const receiver = await spanReceiver(file);+ try {+ assert.match(receiver.url, /^http:\/\/127\.0\.0\.1:\d+$/);+ const prompt = [+ { role: 'system', content: 'You are opencode.' },+ { role: 'system', content: 'Here is some useful information.' },+ { role: 'user', content: [{ type: 'text', text: 'Make a title' }] },+ { role: 'assistant', content: [{ type: 'reasoning', text: 'look' }, { type: 'tool-call', toolCallId: 'o1', toolName: 'bash', input: { command: 'openfilm look' } }] },+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'o1', toolName: 'bash', output: { type: 'text', value: 'frames saved' } }] },+ ];+ assert.equal(await post(receiver.url, exportOf([+ otlpSpan('sql.execute', 1, { 'db.statement': 'select' }),+ otlpSpan('ai.streamText.doStream', 2, {+ 'session.id': 'ses_1', 'ai.model.id': 'm1', 'ai.model.provider': 'fake.chat', 'ai.prompt.messages': JSON.stringify(prompt),+ 'ai.prompt.tools': [JSON.stringify({ type: 'function', name: 'bash', description: 'Run', inputSchema: { type: 'object' } })],+ 'ai.prompt.toolChoice': '{"type":"auto"}', 'ai.response.text': 'Done.', 'ai.response.finishReason': 'stop',+ 'ai.usage.inputTokens': 120, 'ai.usage.inputTokenDetails.noCacheTokens': 20, 'ai.usage.inputTokenDetails.cacheReadTokens': 100, 'ai.usage.outputTokens': 3,+ }),+ ])), 200);+ assert.equal(await post(receiver.url, gzipSync(exportOf([otlpSpan('ai.streamText.doStream', 5, { 'session.id': 'ses_child', 'ai.prompt.messages': '[]', 'ai.response.toolCalls': JSON.stringify([{ toolCallId: 'o2', toolName: 'read', input: '{"path":"film.html"}' }]) })])), { 'content-encoding': 'gzip' }), 200);+ assert.equal(await post(receiver.url, 'not json'), 200, 'anything else answered, nothing kept');++ const calls = opencodeCalls(file, { sessionId: 'ses_1' });+ assert.equal(calls.length, 2, 'only the model requests\' spans');+ const [call, child] = calls;+ assert.equal(call.systemPrompt, 'You are opencode.\n\nHere is some useful information.');+ assert.deepEqual(call.messages, [+ { role: 'user', content: [{ type: 'text', text: 'Make a title' }] },+ { role: 'assistant', content: [{ type: 'thinking', thinking: 'look' }, { type: 'toolCall', id: 'o1', name: 'bash', arguments: { command: 'openfilm look' } }] },+ { role: 'toolResult', toolCallId: 'o1', toolName: 'bash', content: [{ type: 'text', text: 'frames saved' }], isError: false },+ ]);+ assert.deepEqual(call.tools, [{ name: 'bash', description: 'Run', parameters: { type: 'object' } }]);+ assert.deepEqual(call.answer.content, [{ type: 'text', text: 'Done.' }]);+ assert.deepEqual(call.answer.usage, { input: 20, cacheRead: 100, cacheWrite: 0, output: 3, reasoning: 0 });+ assert.equal(call.startedAt, t(2));+ assert.equal(call.ms, 2500);+ assert.deepEqual(call.settings, { toolChoice: { type: 'auto' } });+ assert.deepEqual(call.lacks, ['opencodeBeforeProvider']);+ assert.equal(child.thread.id, 'ses_child', 'a subagent\'s session, named');+ assert.deepEqual(child.answer.content, [{ type: 'toolCall', id: 'o2', name: 'read', arguments: { path: 'film.html' } }]);+ } finally {+ receiver.close();+ }+});++test('a turn reads its requests from the log its agent was started with, named by it', async () => {+ const base = temp('logs');+ const switches = await logSwitches('qwen', { base, home: temp('home') });+ writeFileSync(join(switches.log.dir, 'openai-1.json'), JSON.stringify({ timestamp: at(2), request: { messages: [{ role: 'user', content: 'hi' }] }, response: null, context: { sessionId: 's-12345678' } }));+ const read = agentRecordCalls({ agent: 'qwen', sessionId: 's-12345678', log: switches.log, from: t(1), to: t(3) });+ assert.equal(read.calls.length, 1);+ assert.deepEqual(read.calls[0].source, { agent: 'qwen', file: switches.log.dir });+ assert.equal(agentLogCalls({ agent: 'qwen', sessionId: 's-12345678', log: { agent: 'gemini', dir: switches.log.dir } }), null, 'another agent\'s log is not read');+ assert.equal(agentRecordCalls({ agent: 'qwen', sessionId: 's-12345678', log: { agent: 'qwen', none: 'own' } }), null);+ assert.deepEqual(readdirSync(join(base, 'qwen')).length, 1);+});diff --git a/apps/desktop/src/agent-prompt.md b/apps/desktop/src/agent-prompt.mdindex a9b22c2..01131ec 100644--- a/apps/desktop/src/agent-prompt.md+++ b/apps/desktop/src/agent-prompt.md@@ -1,42 +1,39 @@You are the agent inside the OpenFilm desktop app. You make films with the person: launch films, explainers,-ads, social clips, music videos, edits of their own footage. You make them as web pages cut together in film.html, as-the manual at the end of this prompt describes. It is the manual `openfilm` prints: you need not print it again.+ads, social clips, music videos, edits of their own footage. A film is web pages cut together in film.html, as the+manual at the end of this prompt describes.-## Your tools--- `bash`: run commands in the project folder: `openfilm look`, `openfilm get`, `ffmpeg`, `ffprobe`, scripts you write.-- `read`: read a file. Reading a picture (a frame `openfilm look` saved, an image in assets/) shows it to you: look at- what you made, never guess how it looks.-- `edit`, `write`: change and create files.-- `ask`: ask the person, with options to choose from (see Asking).--`openfilm get` makes voice, music, sound effects, transcripts, pictures and video only through the services the person-has connected with their own keys in Studio's Settings → Providers. When none of them can make what the film needs,-make it in code (pages, SVG, canvas, ffmpeg), or ask whether they have a key for a service that can, and have them-connect it there.+Beside this chat the person sees Studio, the video editor, already open on the project in your working directory: it+shows each file as you save it. Never run `openfilm open` or open Studio in a browser. Work only in the project folder;+touch nothing outside it.## How you work1. Understand the request. When it names a product, a brand, a person or a file, learn about it first: the project'sfiles, then the web.2. Plan the film shot by shot before you write pages: what each shot shows, for how long, what is said and heard.- Make what the request needs, not more.-3. Make it: media, pages, film.html.-4. Look at it: run `openfilm look` and read the frames. Check every shot against the plan and the manual: text inside- the frame and readable, nothing overlapping by accident, timing and sound where they belong. Fix what is wrong and- look again.+ Make what the request needs, not more: generating video, pictures, voice and music can cost the person money.+3. Make it: media, pages, film.html, in steps the person can watch. Do not stop halfway to ask whether to go on.+4. Look at it: run `openfilm look` and read the frames it saves (reading a picture shows it to you). Check every shot+ against the plan and the manual: text inside the frame and readable, nothing overlapping by accident, timing and+ sound where they belong. Fix what is wrong and look again.5. Tell the person what you made.-Work in steps the person can watch: Studio shows each file as you save it. Do not stop halfway to ask whether to go on.+## Media and the web++When no service the person connected can make what the film needs, make it in code (pages, SVG, canvas, ffmpeg), or+ask whether they have a key for a service that can.++To search the web, run `openfilm get web-search --query "…"`; to read a page, `openfilm get web-fetch --url …` (it+saves the page's text in the project). Both work once the person has connected a web search service (Brave Search or+Tavily); until then, read public pages with `curl`.## Asking-Most requests are enough to start: make sensible choices yourself and say what you chose. Use `ask` only when you-cannot make a choice well and a wrong guess wastes the person's time or money: their product or brand when the project-and the web do not say, which of their files to use, a direction between clearly different options, paid generation-beyond what they asked for. Ask one to three questions at once, each with two to five short options; the person can-also answer in their own words. Never ask what you can find in the project or on the web, and never ask permission to-do what you were asked to do. When the person skips a question, decide yourself and say what you chose.+Most requests are enough to start: make sensible choices yourself and say what you chose. Use `ask` only when a wrong+guess wastes the person's time or money: their product or brand when the project and the web do not say, which of+their files to use, a direction between clearly different options, paid generation beyond what they asked for. Never+ask what you can find out, and never ask permission to do what you were asked to do. When the person skips a question,+decide yourself and say what you chose.## Talking with the person@@ -46,10 +43,3 @@ do what you were asked to do. When the person skips a question, decide yourself- Be brief: what you made or changed, and anything you are unsure of, in a few lines.- Never say something works or looks right before you have looked at it.- When something fails (a service, a key), say what happened and what the person can do, in a sentence.--## Care--- Work only in the project folder; touch nothing outside it.-- What the person made or changed in Studio is theirs: keep it unless they ask you to change it.-- Generating video, pictures, voice or music can cost the person money: generate what the film needs, not variations- nobody asked for.diff --git a/apps/desktop/src/agent-prompt.test.mjs b/apps/desktop/src/agent-prompt.test.mjsnew file mode 100644index 0000000..b726a2d--- /dev/null+++ b/apps/desktop/src/agent-prompt.test.mjs@@ -0,0 +1,20 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { INSTRUCTIONS, STUDIO_REFERENCES, ownAgentPrompt } from './agents.mjs';++const count = (text, part) => text.split(part).length - 1;++test("the app's own agent's prompt says each thing once and never tells it to go and print the manual it carries", () => {+ const prompt = ownAgentPrompt();+ assert.equal(count(prompt, '<manual>'), 1);+ assert.ok(!prompt.includes('npx openfilm'), 'the command on its PATH, as the manual reads for it');+ assert.ok(!prompt.includes(INSTRUCTIONS), 'not the words for another agent');+ assert.ok(!/run\s+`openfilm`\s+with no arguments/.test(prompt), 'no telling it to print the manual it already has');+ assert.equal(count(prompt, STUDIO_REFERENCES), 1, 'how Studio is pointed at, once');+ assert.equal(count(prompt, 'Reply in the language'), 1);+ assert.match(prompt, /Never run `openfilm open`/, 'Studio is open beside it, whatever the manual says of `open`');+});++test('every agent is told how to point at Studio', () => {+ assert.ok(INSTRUCTIONS.endsWith(STUDIO_REFERENCES));+});diff --git a/apps/desktop/src/agent-records.mjs b/apps/desktop/src/agent-records.mjsnew file mode 100644index 0000000..76be786--- /dev/null+++ b/apps/desktop/src/agent-records.mjs@@ -0,0 +1,604 @@+/**+ * What the person's own Claude Code, Codex and Kimi sent their models in a turn, read from the record each keeps of its+ * sessions, as the turn log shows the app's own agent's requests (chat-store.mjs `<turn>.model.jsonl`): each request+ * with its system prompt, every message it carried (the person's, the agent's own, each tool's result, and what the+ * agent put in by itself: project instructions, its environment, reminders), its tools, and the answer.+ *+ * Claude Code <CLAUDE_CONFIG_DIR or ~/.claude>/projects/<the folder, as a name>/<session>.jsonl, and its subagents'+ * in <session>/subagents/agent-*.jsonl. Each line is one entry of a chain (`parentUuid`): the person's+ * messages, each block of an answer (one request's blocks share `message.id`), each tool's result, and+ * each piece of context it attached, with the words it put in (`rendered`). A `prompt_snapshot`+ * attachment holds the system prompt (`cliPrefix`, `systemPrompt`) and the tools, when they change.+ * Codex <CODEX_HOME or ~/.codex>/sessions/YYYY/MM/DD/rollout-…-<session>.jsonl. `session_meta` holds the+ * base instructions; `response_item`s are the conversation as the model takes it (developer and user+ * messages, reasoning, tool calls and their output); a `token_usage_record` (or, older, an+ * `event_msg` token_count) closes each request. Codex does not keep its tools' definitions.+ * Kimi ~/.kimi-code/sessions/<folder>/session_<id>/agents/<main or a subagent>/wire.jsonl, found by+ * ~/.kimi-code/session_index.jsonl. Each request is an `llm.request` (model, effort, how many+ * messages) closed by a `step.end` (usage); the system prompt and the tools are kept as they change.+ * Copilot <COPILOT_HOME or ~/.copilot>/session-state/<session>/events.jsonl: the system prompt+ * (`system.message`), each message as the model got it (`user.message` transformedContent), each answer+ * (`assistant.message`, its tool requests) and each tool's result; a `session.usage_record` for each+ * request. No tools' definitions: Copilot does not keep them, and its OpenTelemetry makes no spans+ * over ACP.+ *+ * Gemini CLI, Qwen Code, CodeBuddy and OpenCode keep the conversation without the system prompt or the tools:+ * theirs are read from the logs they are started with (agent-logs.mjs). Cursor's prompt is made on its servers.+ *+ * Neither record is a public format: read for what it has, and whatever is not understood is left out, never a+ * failure. A request's messages are rebuilt from the record, as the agent keeps them: not the bytes on the wire.+ *+ * Reads no Electron module, so `node --test` can use it.+ */+import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { LOGGED_AGENTS, agentLogCalls } from './agent-logs.mjs';++/** The agents whose records (or logs) are read. */+export const RECORDED_AGENTS = Object.freeze(['claude', 'codex', 'kimi', 'copilot', ...LOGGED_AGENTS]);++/** a record longer than this is not read: one turn's requests are not worth reading hundreds of megabytes */+const RECORD_MAX = 256 * 1024 * 1024;++const lines = (file) => {+ try {+ if (statSync(file).size > RECORD_MAX) return [];+ return readFileSync(file, 'utf8').split('\n').flatMap((line) => { try { return line ? [JSON.parse(line)] : []; } catch { return []; } });+ } catch { return []; }+};+const ms = (iso) => { const t = Date.parse(String(iso ?? '')); return Number.isFinite(t) ? t : null; };+const str = (v) => (typeof v === 'string' ? v : v == null ? '' : JSON.stringify(v));+/** a picture as the turn log shows it: its type and its data (base64) */+const picture = (mimeType, data) => ({ type: 'image', mimeType: String(mimeType || 'image/png'), data: String(data ?? '') });++/* ── Claude Code ─────────────────────────────────────────────────────────── */++/** Claude Code's name for a folder's sessions: every character but a letter or a digit a dash. */+export const claudeProjectName = (cwd) => String(cwd).replace(/[^a-zA-Z0-9]/g, '-');++/**+ * The record of a Claude Code session, or null: in the folder named for `cwd`, else wherever it is (a long or unusual+ * path is named differently).+ */+export function findClaudeRecord({ sessionId, cwd, env = {} }) {+ if (!/^[\w-]{8,80}$/.test(String(sessionId ?? ''))) return null;+ const projects = join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');+ const named = join(projects, claudeProjectName(cwd ?? ''), `${sessionId}.jsonl`);+ if (existsSync(named)) return named;+ let dirs = [];+ try { dirs = readdirSync(projects); } catch { return null; }+ for (const dir of dirs) {+ const file = join(projects, dir, `${sessionId}.jsonl`);+ if (existsSync(file)) return file;+ }+ return null;+}++/** Claude's usage as the turn log counts it (input is what was not read from the cache). */+const claudeUsage = (u = {}) => ({+ input: Number(u.input_tokens) || 0,+ cacheRead: Number(u.cache_read_input_tokens) || 0,+ cacheWrite: Number(u.cache_creation_input_tokens) || 0,+ output: Number(u.output_tokens) || 0,+ reasoning: Number(u.output_tokens_details?.thinking_tokens) || 0,+});++/** A block of a message's content, as the turn log has it. */+function claudePart(block, entry) {+ if (typeof block === 'string') return { type: 'text', text: block };+ switch (block?.type) {+ case 'text': return { type: 'text', text: String(block.text ?? '') };+ case 'thinking': return { type: 'thinking', thinking: String(block.thinking ?? '') };+ case 'redacted_thinking': return { type: 'thinking', thinking: '[redacted]' };+ case 'tool_use': case 'server_tool_use':+ /* the input as the model wrote it, when Claude Code keeps that apart from the one it ran */+ return { type: 'toolCall', id: String(block.id ?? ''), name: String(block.name ?? ''), arguments: entry?.wireToolInputs?.[block.id] ?? block.input ?? {} };+ case 'image': return picture(block.source?.media_type, block.source?.data);+ default: return { type: 'other', value: block };+ }+}++/** A tool's result's content: its text and its pictures. */+const resultContent = (content) => (typeof content === 'string' ? [{ type: 'text', text: content }]+ : Array.isArray(content) ? content.map((b) => claudePart(b)) : [{ type: 'text', text: str(content) }]);++/**+ * The messages of one entry of the chain, as the model took them: a person's message (its tool results each a+ * message of their own), a piece of context Claude Code attached (role `context`, as the role it went in as, with the+ * words it put in), or a block of an answer (joined with its others by `message.id` afterwards). `tools` names each+ * tool call by its id, for its result.+ */+function claudeMessages(entry, tools) {+ if (entry.type === 'attachment') {+ const rendered = Array.isArray(entry.rendered) ? entry.rendered.map((r) => str(r?.content ?? r)).join('\n') : null;+ if (!rendered) return [];+ return [{ role: 'context', as: String(entry.renderedRole ?? 'user'), label: String(entry.attachment?.type ?? 'attachment'), content: [{ type: 'text', text: rendered }] }];+ }+ const message = entry.message ?? {};+ if (entry.type === 'assistant') {+ const content = (Array.isArray(message.content) ? message.content : [message.content]).filter(Boolean).map((b) => claudePart(b, entry));+ for (const part of content) if (part.type === 'toolCall') tools.set(part.id, part.name);+ return [{ role: 'assistant', id: String(message.id ?? entry.requestId ?? entry.uuid), content, responseModel: message.model,+ stopReason: message.stop_reason ?? null, usage: claudeUsage(message.usage), ...(entry.effort ? { thinkingLevel: entry.effort } : {}) }];+ }+ if (entry.type === 'user') {+ const content = typeof message.content === 'string' ? [message.content] : Array.isArray(message.content) ? message.content : [];+ const out = [];+ let own = [];+ const flush = () => { if (own.length) out.push({ role: 'user', content: own, ...(entry.isMeta ? { meta: true } : {}), ...(entry.isCompactSummary ? { label: 'compact summary' } : {}) }); own = []; };+ for (const block of content) {+ if (block?.type === 'tool_result') {+ flush();+ out.push({ role: 'toolResult', toolCallId: String(block.tool_use_id ?? ''), toolName: tools.get(block.tool_use_id) ?? 'tool', content: resultContent(block.content), isError: block.is_error === true });+ } else own.push(claudePart(block));+ }+ flush();+ return out;+ }+ return [];+}++/** The system prompt and tools in effect, from the snapshots along a chain (each may hold only what changed). */+function claudeSnapshot(chain) {+ let system = null;+ let prefix = '';+ let tools = null;+ for (const entry of chain) {+ const a = entry.type === 'attachment' ? entry.attachment : null;+ if (a?.type !== 'prompt_snapshot') continue;+ if (Array.isArray(a.systemPrompt)) system = a.systemPrompt.map(str);+ if (typeof a.cliPrefix === 'string' && a.cliPrefix) prefix = a.cliPrefix;+ if (Array.isArray(a.tools)) tools = a.tools.map((t) => ({ name: t?.name, description: t?.description, parameters: t?.schema ?? t?.input_schema ?? t?.parameters }));+ }+ return { systemPrompt: system ? [prefix, ...system].filter(Boolean).join('\n\n') : null, tools };+}++/**+ * The requests in one Claude Code record whose answers began between `from` and `to` (ms), each whole: its system+ * prompt, its messages, its tools, its answer. `thread`: a subagent's, named.+ */+export function claudeCallsOf(entries, { from = 0, to = Infinity, thread = null } = {}) {+ const byUuid = new Map();+ const answerNext = new Map();+ for (const e of entries) {+ if (typeof e?.uuid === 'string') byUuid.set(e.uuid, e);+ if (e?.type === 'assistant' && typeof e.parentUuid === 'string') answerNext.set(e.parentUuid, e);+ }+ /* each request: the first of its answer's blocks (they share message.id) */+ const firsts = [];+ const seen = new Set();+ for (const e of entries) {+ if (e?.type !== 'assistant' || e.isApiErrorMessage) continue;+ const id = e.message?.id ?? e.requestId;+ if (!id || seen.has(id)) continue;+ seen.add(id);+ const at = ms(e.timestamp);+ if (at !== null && at >= from && at <= to) firsts.push(e);+ }+ return firsts.map((first) => {+ /* what the model had: the chain up to the request, as it is in the record */+ const chain = [];+ for (let e = byUuid.get(first.parentUuid); e && chain.length < 100_000; e = byUuid.get(e.parentUuid)) chain.push(e);+ chain.reverse();+ const id = first.message?.id ?? first.requestId;+ /* the answer's blocks: the first, and each after it of the same request */+ const answerBlocks = [first];+ for (let e = answerNext.get(first.uuid); e && (e.message?.id ?? e.requestId) === id; e = answerNext.get(e.uuid)) answerBlocks.push(e);+ const tools = new Map();+ const messages = [];+ const join = (list, m) => {+ const last = list[list.length - 1];+ if (m.role === 'assistant' && last?.role === 'assistant' && last.id === m.id) {+ last.content.push(...m.content);+ Object.assign(last, { stopReason: m.stopReason, usage: m.usage });+ } else list.push(m);+ };+ for (const entry of chain) for (const m of claudeMessages(entry, tools)) join(messages, m);+ const answered = [];+ for (const block of answerBlocks) for (const m of claudeMessages(block, tools)) join(answered, m);+ const { id: _id, ...answer } = answered[0] ?? { role: 'assistant', content: [] };+ for (const m of messages) delete m.id;+ const { systemPrompt, tools: toolList } = claudeSnapshot(chain);+ const sent = ms(chain[chain.length - 1]?.timestamp) ?? ms(first.timestamp) ?? 0;+ const done = ms(answerBlocks[answerBlocks.length - 1].timestamp) ?? sent;+ return {+ startedAt: sent, ms: Math.max(0, done - sent), messages, systemPrompt, tools: toolList, answer,+ ...(thread ? { thread } : {}),+ };+ });+}++/** Every request of a Claude Code session, and of the subagents it ran, between `from` and `to`, in time order. */+export function claudeCalls(file, { from = 0, to = Infinity } = {}) {+ const calls = claudeCallsOf(lines(file), { from, to });+ const subagents = join(file.replace(/\.jsonl$/, ''), 'subagents');+ let names = [];+ try { names = readdirSync(subagents).filter((n) => /^agent-[\w-]+\.jsonl$/.test(n)); } catch { /* none */ }+ for (const name of names) {+ let meta = {};+ try { meta = JSON.parse(readFileSync(join(subagents, name.replace(/\.jsonl$/, '.meta.json')), 'utf8')); } catch { /* unnamed */ }+ const thread = { id: name.slice('agent-'.length, -'.jsonl'.length), label: [meta.agentType, meta.description].filter(Boolean).join(' · ') || 'subagent' };+ calls.push(...claudeCallsOf(lines(join(subagents, name)), { from, to, thread }));+ }+ return calls.sort((a, b) => a.startedAt - b.startedAt);+}++/* ── Codex ───────────────────────────────────────────────────────────────── */++/** The rollout of a Codex session, or null: in its sessions (newest days first), or archived. */+export function findCodexRecord({ sessionId, env = {} }) {+ if (!/^[\w-]{8,80}$/.test(String(sessionId ?? ''))) return null;+ const home = env.CODEX_HOME || join(homedir(), '.codex');+ const suffix = `-${sessionId}.jsonl`;+ const sorted = (dir) => { try { return readdirSync(dir).sort().reverse(); } catch { return []; } };+ const sessions = join(home, 'sessions');+ for (const y of sorted(sessions)) {+ for (const m of sorted(join(sessions, y))) {+ for (const d of sorted(join(sessions, y, m))) {+ const hit = sorted(join(sessions, y, m, d)).find((n) => n.endsWith(suffix));+ if (hit) return join(sessions, y, m, d, hit);+ }+ }+ }+ const archived = sorted(join(home, 'archived_sessions')).find((n) => n.endsWith(suffix));+ return archived ? join(home, 'archived_sessions', archived) : null;+}++/** OpenAI's usage as the turn log counts it (its input counts the cached part too). */+const codexUsage = (u = {}) => {+ const cached = Number(u.cached_input_tokens) || 0;+ return {+ input: Math.max(0, (Number(u.input_tokens) || 0) - cached),+ cacheRead: cached,+ cacheWrite: Number(u.cache_write_input_tokens) || 0,+ output: Number(u.output_tokens) || 0,+ reasoning: Number(u.reasoning_output_tokens) || 0,+ };+};++/** A message's content parts (input_text, output_text, input_image), as the turn log has them. */+function codexParts(content) {+ if (typeof content === 'string') return [{ type: 'text', text: content }];+ return (Array.isArray(content) ? content : []).map((p) => {+ if (typeof p?.text === 'string') return { type: 'text', text: p.text };+ if (p?.type === 'input_image') {+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(String(p.image_url ?? ''));+ return m ? picture(m[1], m[2]) : { type: 'text', text: `[image ${str(p.image_url).slice(0, 200)}]` };+ }+ return { type: 'other', value: p };+ });+}++/* what Codex puts in as the person's words by itself: its environment, the project's AGENTS.md and the like */+const CODEX_CONTEXT = [+ [/^\s*<environment_context>/, 'environment_context'],+ [/^\s*# AGENTS\.md instructions/, 'AGENTS.md'],+ [/^\s*<user_instructions>/, 'user_instructions'],+ [/^\s*<turn_aborted>/, 'turn_aborted'],+];++/** An output of a request (what the model said or asked for), as a part of its answer; null for anything else. */+function codexOutput(item) {+ switch (item?.type) {+ case 'message': return item.role === 'assistant' ? codexParts(item.content) : null;+ case 'reasoning': {+ const said = [...(item.summary ?? []), ...(item.content ?? [])].map((s) => s?.text).filter((t) => typeof t === 'string');+ return [{ type: 'thinking', thinking: said.length ? said.join('\n\n') : item.encrypted_content ? '[encrypted]' : '' }];+ }+ case 'function_call': {+ let args = item.arguments;+ try { args = JSON.parse(item.arguments); } catch { /* as written */ }+ return [{ type: 'toolCall', id: String(item.call_id ?? item.id ?? ''), name: String(item.name ?? ''), arguments: args ?? {} }];+ }+ case 'custom_tool_call': return [{ type: 'toolCall', id: String(item.call_id ?? item.id ?? ''), name: String(item.name ?? ''), arguments: item.input ?? '' }];+ case 'local_shell_call': return [{ type: 'toolCall', id: String(item.call_id ?? item.id ?? ''), name: 'local_shell', arguments: item.action ?? {} }];+ case 'web_search_call': return [{ type: 'toolCall', id: String(item.id ?? ''), name: 'web_search', arguments: item.action ?? {} }];+ case 'image_generation_call': return [{ type: 'toolCall', id: String(item.id ?? ''), name: 'image_generation', arguments: { prompt: item.revised_prompt ?? '' } }];+ default: return null;+ }+}++/** An input of a request (a message to the model, a tool's output), as a message; null for anything else. */+function codexInput(item, tools) {+ if (item?.type === 'message' && item.role !== 'assistant') {+ const content = codexParts(item.content);+ if (item.role === 'user') {+ const text = content.map((p) => p.text ?? '').join('');+ const known = CODEX_CONTEXT.find(([re]) => re.test(text));+ if (known) return { role: 'context', as: 'user', label: known[1], content };+ return { role: 'user', content };+ }+ return { role: 'context', as: String(item.role), label: String(item.role), content };+ }+ if (/_call_output$/.test(String(item?.type))) {+ const out = item.output;+ const content = typeof out === 'string' ? [{ type: 'text', text: out }]+ : Array.isArray(out) ? codexParts(out)+ : typeof out?.content === 'string' ? [{ type: 'text', text: out.content }] : [{ type: 'text', text: str(out) }];+ return { role: 'toolResult', toolCallId: String(item.call_id ?? ''), toolName: tools.get(item.call_id) ?? 'tool', content, isError: out?.success === false };+ }+ return null;+}++/**+ * The requests in one Codex rollout that ended between `from` and `to` (ms), each whole: the base instructions as+ * its system prompt, everything before it as its messages, what it said and asked for as its answer, its usage, and+ * the turn's settings (model, effort, permissions). No tools: Codex does not keep them.+ */+export function codexCallsOf(entries, { from = 0, to = Infinity } = {}) {+ let systemPrompt = null;+ let settings = null;+ const history = [];+ const tools = new Map();+ let out = [];+ let sentAt = null;+ const calls = [];+ const usageRecords = entries.some((e) => e?.type === 'token_usage_record');+ const close = (at, usage) => {+ if (!out.length && !usage) return;+ const answer = { role: 'assistant', content: out, usage: codexUsage(usage ?? {}),+ ...(settings?.model ? { responseModel: settings.model } : {}), ...(settings?.effort ? { thinkingLevel: settings.effort } : {}) };+ for (const part of out) if (part.type === 'toolCall') tools.set(part.id, part.name);+ const started = sentAt ?? at ?? 0;+ if ((at ?? started) >= from && (at ?? started) <= to) {+ calls.push({ startedAt: started, ms: Math.max(0, (at ?? started) - started), messages: history.map((m) => ({ ...m })), systemPrompt, tools: null, toolsUnknown: true, answer, ...(settings ? { settings } : {}) });+ }+ if (out.length) history.push({ role: 'assistant', content: out });+ out = [];+ sentAt = null;+ };+ for (const e of entries) {+ const p = e?.payload ?? {};+ const at = ms(e?.timestamp);+ if (e?.type === 'session_meta') {+ const base = p.base_instructions ?? p.instructions;+ systemPrompt = typeof base === 'string' ? base : typeof base?.text === 'string' ? base.text : systemPrompt;+ } else if (e?.type === 'turn_context') {+ settings = p;+ } else if (e?.type === 'compacted') {+ close(at, null);+ history.length = 0;+ const kept = Array.isArray(p.replacement_history) ? p.replacement_history.map((i) => codexInput(i, tools) ?? (codexOutput(i) ? { role: 'assistant', content: codexOutput(i) } : null)).filter(Boolean) : [];+ history.push(...(kept.length ? kept : [{ role: 'context', as: 'user', label: 'compaction summary', content: [{ type: 'text', text: str(p.message) }] }]));+ } else if (e?.type === 'response_item') {+ const said = codexOutput(p);+ if (said) { sentAt ??= at; out.push(...said); continue; }+ const input = codexInput(p, tools);+ if (!input) continue;+ /* an input while an answer is open: that answer ended without its usage being kept */+ if (out.length) close(at, null);+ history.push(input);+ sentAt = at;+ } else if (e?.type === 'token_usage_record' || (!usageRecords && e?.type === 'event_msg' && p.type === 'token_count' && p.info?.last_token_usage)) {+ close(at, e.type === 'token_usage_record' ? p.usage : p.info.last_token_usage);+ }+ }+ close(null, null);+ return calls;+}++export const codexCalls = (file, { from = 0, to = Infinity } = {}) => codexCallsOf(lines(file), { from, to });++/* ── Kimi ────────────────────────────────────────────────────────────────── */++/**+ * The folder of a Kimi session, or null: as ~/.kimi-code/session_index.jsonl names it (`session_<uuid>`, its ACP id+ * with or without the prefix).+ */+export function findKimiRecord({ sessionId, home = homedir() }) {+ const id = String(sessionId ?? '');+ if (!/^[\w-]{8,90}$/.test(id)) return null;+ const want = new Set([id, id.startsWith('session_') ? id : `session_${id}`]);+ for (const line of lines(join(home, '.kimi-code', 'session_index.jsonl'))) {+ if (want.has(line?.sessionId) && typeof line.sessionDir === 'string' && existsSync(join(line.sessionDir, 'agents', 'main', 'wire.jsonl'))) return line.sessionDir;+ }+ return null;+}++/** Kimi's usage as the turn log counts it. */+const kimiUsage = (u = {}) => ({+ input: Number(u.inputOther) || 0,+ cacheRead: Number(u.inputCacheRead) || 0,+ cacheWrite: Number(u.inputCacheCreation) || 0,+ output: Number(u.output) || 0,+ reasoning: 0,+});++/**+ * The requests in one agent's `wire.jsonl` of a Kimi session that began between `from` and `to` (ms), each whole:+ * the system prompt in effect (`config.update`), the tools (`llm.tools_snapshot`), the conversation so far, the answer+ * (its thinking, words and tool calls, `content.part` and `tool.call`) and its usage (`step.end`). `settings`: the+ * request's model and effort, and how many messages Kimi says it sent (`messageCount`).+ */+export function kimiCallsOf(entries, { from = 0, to = Infinity, thread = null } = {}) {+ let systemPrompt = null;+ let tools = null;+ const history = [];+ const names = new Map();+ let open = null;+ let results = [];+ const calls = [];+ const close = (at, end) => {+ if (!open) return;+ const answer = { role: 'assistant', content: open.out, usage: kimiUsage(end?.usage), stopReason: end?.finishReason ?? null,+ ...(open.request.model ? { responseModel: open.request.modelAlias || open.request.model } : {}),+ ...(open.request.provider ? { provider: open.request.provider } : {}), ...(open.request.thinkingEffort ? { thinkingLevel: open.request.thinkingEffort } : {}) };+ if (open.at >= from && open.at <= to) {+ const { type: _t, time: _time, ...settings } = open.request;+ /* the model's own time, as Kimi measured it: the step's end comes after the tools it asked for have run */+ const took = Number(end?.llmFirstTokenLatencyMs ?? 0) + Number(end?.llmStreamDurationMs ?? 0) || Math.max(0, (open.last ?? at ?? open.at) - open.at);+ calls.push({ startedAt: open.at, ms: took, messages: open.messages, systemPrompt, tools, answer, settings, ...(thread ? { thread } : {}) });+ }+ if (open.out.length) history.push({ role: 'assistant', content: open.out });+ history.push(...results);+ results = [];+ open = null;+ };+ for (const e of entries) {+ const at = Number(e?.time) || null;+ switch (e?.type) {+ case 'config.update': if (typeof e.systemPrompt === 'string') systemPrompt = e.systemPrompt; break;+ case 'llm.tools_snapshot': if (Array.isArray(e.tools)) tools = e.tools.map((t) => ({ name: t?.name, description: t?.description, parameters: t?.parameters })); break;+ case 'llm.request':+ close(at, null);+ open = { at: at ?? 0, request: e, messages: history.map((m) => ({ ...m })), out: [] };+ break;+ case 'context.append_message': {+ const m = e.message ?? {};+ const content = codexParts(m.content);+ history.push(m.role === 'user' ? { role: 'user', content } : { role: 'context', as: String(m.role ?? 'user'), label: String(m.role ?? 'message'), content });+ break;+ }+ case 'context.append_loop_event': {+ const ev = e.event ?? {};+ if (open && (ev.type === 'content.part' || ev.type === 'tool.call')) open.last = at ?? open.last;+ if (ev.type === 'content.part' && open) {+ const part = ev.part ?? {};+ if (typeof part.think === 'string') open.out.push({ type: 'thinking', thinking: part.think });+ else if (typeof part.text === 'string') open.out.push({ type: 'text', text: part.text });+ else open.out.push({ type: 'other', value: part });+ } else if (ev.type === 'tool.call' && open) {+ names.set(ev.toolCallId, ev.name);+ open.out.push({ type: 'toolCall', id: String(ev.toolCallId ?? ''), name: String(ev.name ?? ''), arguments: ev.args ?? {} });+ } else if (ev.type === 'tool.result') {+ const r = ev.result ?? {};+ const said = typeof r.output === 'string' ? r.output : str(r.output ?? r);+ const result = { role: 'toolResult', toolCallId: String(ev.toolCallId ?? ''), toolName: names.get(ev.toolCallId) ?? 'tool', content: [{ type: 'text', text: said }], isError: r.isError === true || r.error != null };+ if (open) results.push(result); else history.push(result);+ } else if (ev.type === 'step.end') close(at, ev);+ break;+ }+ default: break;+ }+ }+ close(null, null);+ return calls;+}++/** Every request of a Kimi session, and of its subagents, between `from` and `to`, in time order. */+export function kimiCalls(sessionDir, { from = 0, to = Infinity } = {}) {+ let agents = [];+ try { agents = readdirSync(join(sessionDir, 'agents')); } catch { return []; }+ return agents.flatMap((name) => kimiCallsOf(lines(join(sessionDir, 'agents', name, 'wire.jsonl')), { from, to, thread: name === 'main' ? null : { id: name, label: `subagent ${name}` } }))+ .sort((a, b) => a.startedAt - b.startedAt);+}++/* ── Copilot ─────────────────────────────────────────────────────────────── */++/** The events of a Copilot session, or null: in its session state, by its ACP id. */+export function findCopilotRecord({ sessionId, env = {}, home = homedir() }) {+ if (!/^[\w-]{8,80}$/.test(String(sessionId ?? ''))) return null;+ const file = join(env.COPILOT_HOME || join(home, '.copilot'), 'session-state', sessionId, 'events.jsonl');+ return existsSync(file) ? file : null;+}++/**+ * The requests in a Copilot session's events whose answers came between `from` and `to` (ms), rebuilt from them:+ * each `session.usage_record` is one request, its answer the `assistant.message` of the same API call, and what+ * came before it its messages. `settings`: the request's model, and how big Copilot says its body was.+ */+export function copilotCallsOf(entries, { from = 0, to = Infinity } = {}) {+ let systemPrompt = null;+ const history = [];+ const names = new Map();+ const calls = [];+ /** answers by their API call: an answer's message may come just before its usage record, or just after */+ const answers = new Map();+ for (const e of entries) {+ if (e?.type === 'assistant.message' && e.data?.apiCallId) answers.set(e.data.apiCallId, e.data);+ }+ const said = (d) => [+ ...(typeof d?.reasoningText === 'string' && d.reasoningText ? [{ type: 'thinking', thinking: d.reasoningText }] : []),+ ...(typeof d?.content === 'string' && d.content ? [{ type: 'text', text: d.content }] : []),+ ...(d?.toolRequests ?? []).map((r) => ({ type: 'toolCall', id: String(r?.toolCallId ?? ''), name: String(r?.name ?? ''), arguments: r?.arguments ?? {} })),+ ];+ for (const e of entries) {+ const d = e?.data ?? {};+ switch (e?.type) {+ case 'system.message': if (typeof d.content === 'string') systemPrompt = d.content; break;+ case 'user.message': history.push({ role: 'user', content: [{ type: 'text', text: String(d.transformedContent ?? d.content ?? '') }] }); break;+ case 'assistant.message': {+ const content = said(d);+ for (const part of content) if (part.type === 'toolCall') names.set(part.id, part.name);+ if (content.length) history.push({ role: 'assistant', content });+ break;+ }+ case 'tool.execution_complete': {+ const r = d.result ?? {};+ history.push({ role: 'toolResult', toolCallId: String(d.toolCallId ?? ''), toolName: names.get(d.toolCallId) ?? 'tool',+ content: [{ type: 'text', text: typeof r.content === 'string' ? r.content : str(r.content ?? d.error ?? r) }], isError: d.success === false });+ break;+ }+ case 'session.usage_record': {+ const u = d.usage ?? {};+ const at = ms(e.timestamp) ?? 0;+ if (at < from || at > to) break;+ const took = Number(u.duration) || 0;+ const reply = answers.get(u.apiCallId);+ const cacheRead = Number(u.cacheReadTokens) || 0;+ const cacheWrite = Number(u.cacheWriteTokens) || 0;+ calls.push({+ startedAt: at - took, ms: took, messages: history.map((m) => ({ ...m })), systemPrompt, tools: null,+ answer: { role: 'assistant', content: reply ? said(reply) : [],+ usage: { input: Math.max(0, (Number(u.inputTokens) || 0) - cacheRead - cacheWrite), cacheRead, cacheWrite, output: Number(u.outputTokens) || 0, reasoning: Number(u.reasoningTokens) || 0 },+ ...(u.model ? { responseModel: String(u.model) } : {}) },+ settings: { model: u.model ?? null, initiator: u.initiator ?? null, requestBodyBytes: u.requestBodyBytes ?? null, availableToolCount: u.availableToolCount ?? null },+ lacks: ['copilotRebuilt'],+ });+ break;+ }+ default: break;+ }+ }+ return calls;+}++export const copilotCalls = (file, { from = 0, to = Infinity } = {}) => copilotCallsOf(lines(file), { from, to });++/* ── all ─────────────────────────────────────────────────────────────────── */++/**+ * A turn's requests, read from the agent's own record: `{ file, calls }` (calls whole, in time order), or null when+ * the agent keeps none this can read. `from`/`to`: the turn's start and end (ms); `env`: where the person's agent keeps+ * its records (CLAUDE_CONFIG_DIR, CODEX_HOME), as their shell sets it; `home`, theirs (Kimi's are in it); `log`: the+ * log an agent of agent-logs.mjs was started with (its turn log's `opened.log`).+ */+export function agentRecordCalls({ agent, sessionId, cwd, from, to, env = {}, home = homedir(), log = null }) {+ if (LOGGED_AGENTS.includes(agent)) {+ const read = agentLogCalls({ agent, sessionId, log, from, to });+ return read ? { file: read.file, calls: read.calls.map((c) => ({ ...c, source: { agent, file: read.file } })) } : null;+ }+ const file = agent === 'claude' ? findClaudeRecord({ sessionId, cwd, env })+ : agent === 'codex' ? findCodexRecord({ sessionId, env })+ : agent === 'kimi' ? findKimiRecord({ sessionId, home })+ : agent === 'copilot' ? findCopilotRecord({ sessionId, env, home }) : null;+ if (!file) return null;+ const read = { claude: claudeCalls, codex: codexCalls, kimi: kimiCalls, copilot: copilotCalls }[agent];+ const calls = read(file, { from, to });+ return { file, calls: calls.map((c) => ({ ...c, source: { agent, file } })) };+}++/**+ * Calls as the turn log keeps them: each line only what is new since the one before (`prefix`: how many of that+ * one's messages come first, then its own), its system prompt, tools, settings and source only when they changed.+ * Read back whole by the chat's lib/model-calls.ts.+ */+export function compactCalls(calls) {+ let keys = [];+ const last = { systemPrompt: 'null', tools: 'null', settings: 'null', source: 'null', thread: 'null' };+ return calls.map((call) => {+ const all = call.messages.map((m) => JSON.stringify(m));+ let prefix = 0;+ while (prefix < keys.length && prefix < all.length && keys[prefix] === all[prefix]) prefix += 1;+ keys = all;+ const line = { startedAt: call.startedAt, ms: call.ms, prefix, messages: call.messages.slice(prefix), answer: call.answer ?? null };+ for (const field of /** @type {const} */ (['systemPrompt', 'tools', 'settings', 'source', 'thread'])) {+ const key = JSON.stringify(call[field] ?? null);+ if (key !== last[field]) { line[field] = call[field] ?? null; last[field] = key; }+ }+ if (call.toolsUnknown) line.toolsUnknown = true;+ if (call.lacks?.length) line.lacks = call.lacks;+ return line;+ });+}diff --git a/apps/desktop/src/agent-records.test.mjs b/apps/desktop/src/agent-records.test.mjsnew file mode 100644index 0000000..c813bc1--- /dev/null+++ b/apps/desktop/src/agent-records.test.mjs@@ -0,0 +1,241 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { agentRecordCalls, claudeCallsOf, claudeProjectName, codexCallsOf, compactCalls, copilotCallsOf, findClaudeRecord, findCodexRecord, findCopilotRecord, findKimiRecord, kimiCallsOf } from './agent-records.mjs';++const at = (s) => new Date(Date.UTC(2026, 9, 15, 10, 0, s)).toISOString();+const jsonl = (rows) => `${rows.map((r) => JSON.stringify(r)).join('\n')}\n`;++/** A Claude Code session: a message, its context, two requests (the first asking for a tool), a reply. */+function claudeSession() {+ return [+ { type: 'queue-operation', operation: 'enqueue', timestamp: at(0) },+ { type: 'user', uuid: 'u1', parentUuid: null, timestamp: at(1), message: { role: 'user', content: [{ type: 'text', text: 'Make a title' }] } },+ { type: 'attachment', uuid: 'a1', parentUuid: 'u1', timestamp: at(1), attachment: { type: 'instructions', files: [] }, rendered: [{ content: '<CLAUDE.md>be brief</CLAUDE.md>' }], renderedRole: 'user' },+ { type: 'attachment', uuid: 'a2', parentUuid: 'a1', timestamp: at(1), attachment: { type: 'credential_org', organizationUuid: 'x' } },+ { type: 'attachment', uuid: 's1', parentUuid: 'a2', timestamp: at(1), attachment: { type: 'prompt_snapshot', systemPrompt: ['You are an agent.', 'You are inside OpenFilm.'], tools: null } },+ { type: 'assistant', uuid: 'r1a', parentUuid: 's1', timestamp: at(3), requestId: 'req1', effort: 'high',+ message: { id: 'msg1', model: 'claude-x', role: 'assistant', content: [{ type: 'thinking', thinking: 'plan' }], stop_reason: null, usage: { input_tokens: 5, cache_read_input_tokens: 100, cache_creation_input_tokens: 10, output_tokens: 1 } } },+ { type: 'assistant', uuid: 'r1b', parentUuid: 'r1a', timestamp: at(4), requestId: 'req1',+ wireToolInputs: { tu1: { command: 'openfilm look', description: 'as written' } },+ message: { id: 'msg1', model: 'claude-x', role: 'assistant', content: [{ type: 'tool_use', id: 'tu1', name: 'Bash', input: { command: 'openfilm look' } }], stop_reason: 'tool_use', usage: { input_tokens: 5, cache_read_input_tokens: 100, cache_creation_input_tokens: 10, output_tokens: 40, output_tokens_details: { thinking_tokens: 12 } } } },+ { type: 'user', uuid: 'u2', parentUuid: 'r1b', timestamp: at(6), message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tu1', content: 'frames saved', is_error: false }] } },+ { type: 'attachment', uuid: 's2', parentUuid: 'u2', timestamp: at(6), attachment: { type: 'prompt_snapshot', systemPrompt: ['You are an agent.', 'You are inside OpenFilm.'], cliPrefix: 'You are Claude Code.', tools: [{ name: 'Bash', description: 'Run a command', schema: { type: 'object' } }] } },+ { type: 'assistant', uuid: 'r2', parentUuid: 's2', timestamp: at(9), requestId: 'req2',+ message: { id: 'msg2', model: 'claude-x', role: 'assistant', content: [{ type: 'text', text: 'Done.' }], stop_reason: 'end_turn', usage: { input_tokens: 2, cache_read_input_tokens: 150, output_tokens: 3 } } },+ { type: 'last-prompt', lastPrompt: 'Make a title' },+ ];+}++test("Claude Code's record: each request whole, with its system prompt, the context it attached, its tools and its answer", () => {+ const calls = claudeCallsOf(claudeSession());+ assert.equal(calls.length, 2, 'one call per request, not per block');+ const [first, second] = calls;+ assert.equal(first.systemPrompt, 'You are an agent.\n\nYou are inside OpenFilm.');+ assert.equal(first.tools, null, 'no tools in the record yet');+ assert.deepEqual(first.messages, [+ { role: 'user', content: [{ type: 'text', text: 'Make a title' }] },+ { role: 'context', as: 'user', label: 'instructions', content: [{ type: 'text', text: '<CLAUDE.md>be brief</CLAUDE.md>' }] },+ ], 'the person\'s words and what Claude Code put in; nothing it did not send (credential_org, snapshots)');+ assert.deepEqual(first.answer.content, [+ { type: 'thinking', thinking: 'plan' },+ { type: 'toolCall', id: 'tu1', name: 'Bash', arguments: { command: 'openfilm look', description: 'as written' } },+ ], 'the request\'s blocks joined; the tool input as the model wrote it');+ assert.equal(first.answer.stopReason, 'tool_use');+ assert.deepEqual(first.answer.usage, { input: 5, cacheRead: 100, cacheWrite: 10, output: 40, reasoning: 12 });+ assert.equal(first.answer.thinkingLevel, 'high');+ assert.equal(first.startedAt, Date.parse(at(1)));+ assert.equal(first.ms, 3000, 'from what it was sent to its last block');++ assert.equal(second.systemPrompt, 'You are Claude Code.\n\nYou are an agent.\n\nYou are inside OpenFilm.', 'the CLI prefix first');+ assert.deepEqual(second.tools, [{ name: 'Bash', description: 'Run a command', parameters: { type: 'object' } }]);+ assert.equal(second.messages.length, 4);+ assert.equal(second.messages[2].role, 'assistant');+ assert.equal(second.messages[2].content.length, 2, 'the earlier answer, whole');+ assert.deepEqual(second.messages[3], { role: 'toolResult', toolCallId: 'tu1', toolName: 'Bash', content: [{ type: 'text', text: 'frames saved' }], isError: false });+ assert.deepEqual(second.answer.content, [{ type: 'text', text: 'Done.' }]);+});++test("Claude Code's record: only the requests whose answers began in the turn", () => {+ const calls = claudeCallsOf(claudeSession(), { from: Date.parse(at(5)), to: Date.parse(at(10)) });+ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].answer.content, [{ type: 'text', text: 'Done.' }]);+});++test("Codex's rollout: base instructions, what Codex put in, each request closed by its usage, tool calls and their output", () => {+ const rows = [+ { timestamp: at(0), type: 'session_meta', payload: { id: 'th1', base_instructions: { text: 'You are Codex.' } } },+ { timestamp: at(0), type: 'turn_context', payload: { model: 'gpt-x', effort: 'high', approval_policy: 'never' } },+ { timestamp: at(1), type: 'response_item', payload: { type: 'message', role: 'developer', content: [{ type: 'input_text', text: 'You are inside OpenFilm.' }] } },+ { timestamp: at(1), type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: '<environment_context>cwd</environment_context>' }] } },+ { timestamp: at(1), type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Make a title' }] } },+ { timestamp: at(3), type: 'response_item', payload: { type: 'reasoning', summary: [{ type: 'summary_text', text: 'look first' }], encrypted_content: 'zzz' } },+ { timestamp: at(3), type: 'response_item', payload: { type: 'function_call', name: 'exec', arguments: '{"cmd":"openfilm look"}', call_id: 'c1' } },+ { timestamp: at(4), type: 'token_usage_record', payload: { usage: { input_tokens: 120, cached_input_tokens: 100, output_tokens: 9, reasoning_output_tokens: 4 } } },+ { timestamp: at(4), type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 999 } } } },+ { timestamp: at(6), type: 'response_item', payload: { type: 'function_call_output', call_id: 'c1', output: 'frames saved' } },+ { timestamp: at(8), type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'Done.' }] } },+ { timestamp: at(9), type: 'token_usage_record', payload: { usage: { input_tokens: 150, cached_input_tokens: 120, output_tokens: 3 } } },+ ];+ const calls = codexCallsOf(rows);+ assert.equal(calls.length, 2, 'a token_count beside a usage record is not a request of its own');+ const [first, second] = calls;+ assert.equal(first.systemPrompt, 'You are Codex.');+ assert.equal(first.tools, null);+ assert.equal(first.toolsUnknown, true);+ assert.deepEqual(first.settings, { model: 'gpt-x', effort: 'high', approval_policy: 'never' });+ assert.deepEqual(first.messages.map((m) => [m.role, m.label ?? null]), [['context', 'developer'], ['context', 'environment_context'], ['user', null]]);+ assert.deepEqual(first.answer.content, [{ type: 'thinking', thinking: 'look first' }, { type: 'toolCall', id: 'c1', name: 'exec', arguments: { cmd: 'openfilm look' } }]);+ assert.deepEqual(first.answer.usage, { input: 20, cacheRead: 100, cacheWrite: 0, output: 9, reasoning: 4 }, 'input without the cached part');+ assert.equal(first.answer.responseModel, 'gpt-x');+ assert.deepEqual(second.messages.slice(3), [+ { role: 'assistant', content: first.answer.content },+ { role: 'toolResult', toolCallId: 'c1', toolName: 'exec', content: [{ type: 'text', text: 'frames saved' }], isError: false },+ ]);+ assert.deepEqual(second.answer.content, [{ type: 'text', text: 'Done.' }]);+ assert.equal(second.startedAt, Date.parse(at(6)), 'sent with the tool\'s output');+ assert.equal(second.ms, 3000);+});++test("Codex's rollout: an older one closes requests by token_count; a compaction starts the history again", () => {+ const rows = [+ { timestamp: at(1), type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'one' }] } },+ { timestamp: at(2), type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'a' }] } },+ { timestamp: at(2), type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 10, output_tokens: 1 } } } },+ { timestamp: at(3), type: 'compacted', payload: { message: 'they asked for one' } },+ { timestamp: at(4), type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'two' }] } },+ { timestamp: at(5), type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'b' }] } },+ { timestamp: at(5), type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 4, output_tokens: 1 } } } },+ ];+ const calls = codexCallsOf(rows);+ assert.equal(calls.length, 2);+ assert.equal(calls[0].answer.usage.input, 10);+ assert.deepEqual(calls[1].messages, [+ { role: 'context', as: 'user', label: 'compaction summary', content: [{ type: 'text', text: 'they asked for one' }] },+ { role: 'user', content: [{ type: 'text', text: 'two' }] },+ ]);+});++test('records are found where each agent keeps them, and a turn reads its own requests from them', () => {+ const home = mkdtempSync(join(tmpdir(), 'of-records-'));+ const cwd = '/Users/me/Movies/OpenFilm/My film';+ assert.equal(claudeProjectName(cwd), '-Users-me-Movies-OpenFilm-My-film');+ const claudeDir = join(home, 'claude', 'projects', claudeProjectName(cwd));+ mkdirSync(join(claudeDir, 'sess-1234', 'subagents'), { recursive: true });+ writeFileSync(join(claudeDir, 'sess-1234.jsonl'), jsonl(claudeSession()));+ /* a subagent's request, named by its meta */+ writeFileSync(join(claudeDir, 'sess-1234', 'subagents', 'agent-abc.jsonl'), jsonl([+ { type: 'user', uuid: 'x1', parentUuid: null, timestamp: at(7), isSidechain: true, message: { role: 'user', content: 'search' } },+ { type: 'assistant', uuid: 'x2', parentUuid: 'x1', timestamp: at(8), isSidechain: true, message: { id: 'm9', role: 'assistant', content: [{ type: 'text', text: 'found' }], usage: {} } },+ ]));+ writeFileSync(join(claudeDir, 'sess-1234', 'subagents', 'agent-abc.meta.json'), JSON.stringify({ agentType: 'Explore', description: 'Find files' }));+ const env = { CLAUDE_CONFIG_DIR: join(home, 'claude'), CODEX_HOME: join(home, 'codex') };+ assert.ok(findClaudeRecord({ sessionId: 'sess-1234', cwd, env }));+ assert.ok(findClaudeRecord({ sessionId: 'sess-1234', cwd: '/elsewhere', env }), 'found by its id when the folder is named differently');+ assert.equal(findClaudeRecord({ sessionId: '../../etc', cwd, env }), null);++ const read = agentRecordCalls({ agent: 'claude', sessionId: 'sess-1234', cwd, env, from: Date.parse(at(5)), to: Date.parse(at(10)) });+ assert.deepEqual(read.calls.map((c) => c.thread?.label ?? 'main'), ['main', 'Explore · Find files'], 'in time order, the subagent\'s named');+ assert.equal(read.calls[0].source.agent, 'claude');++ const day = join(home, 'codex', 'sessions', '2026', '10', '15');+ mkdirSync(day, { recursive: true });+ writeFileSync(join(day, 'rollout-2026-10-15T10-00-00-th-56789.jsonl'), jsonl([+ { timestamp: at(1), type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'hi' }] } },+ { timestamp: at(2), type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'hello' }] } },+ { timestamp: at(2), type: 'token_usage_record', payload: { usage: {} } },+ ]));+ assert.ok(findCodexRecord({ sessionId: 'th-56789', env }));+ assert.equal(agentRecordCalls({ agent: 'codex', sessionId: 'th-56789', env, from: 0, to: Infinity }).calls.length, 1);+ assert.equal(agentRecordCalls({ agent: 'gemini', sessionId: 'x', env }), null, 'an agent whose record is not read');+});++test("Kimi's wire: each request from llm.request to step.end, with the system prompt and tools in effect and the model's own time", () => {+ const t = (s) => Date.parse(at(s));+ const rows = [+ { type: 'config.update', systemPrompt: 'You are Kimi.', time: t(0) },+ { type: 'turn.prompt', input: [{ type: 'text', text: 'Make a title' }], time: t(1) },+ { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'Make a title' }] }, time: t(1) },+ { type: 'llm.tools_snapshot', tools: [{ name: 'Bash', description: 'Run', parameters: { type: 'object' } }], time: t(1) },+ { type: 'llm.request', model: 'k2', thinkingEffort: 'high', messageCount: 1, time: t(1) },+ { type: 'context.append_loop_event', event: { type: 'content.part', part: { type: 'think', think: 'plan' } }, time: t(2) },+ { type: 'context.append_loop_event', event: { type: 'tool.call', toolCallId: 'k1', name: 'Bash', args: { command: 'openfilm look' } }, time: t(3) },+ { type: 'context.append_loop_event', event: { type: 'tool.result', toolCallId: 'k1', result: { output: 'frames saved' } }, time: t(30) },+ { type: 'context.append_loop_event', event: { type: 'step.end', usage: { inputOther: 20, inputCacheRead: 100, output: 9 }, finishReason: 'tool_calls', llmFirstTokenLatencyMs: 500, llmStreamDurationMs: 1500 }, time: t(30) },+ { type: 'llm.request', model: 'k2', messageCount: 3, time: t(31) },+ { type: 'context.append_loop_event', event: { type: 'content.part', part: { type: 'text', text: 'Done.' } }, time: t(32) },+ { type: 'context.append_loop_event', event: { type: 'step.end', usage: { inputOther: 5, output: 2 } }, time: t(32) },+ ];+ const calls = kimiCallsOf(rows);+ assert.equal(calls.length, 2);+ assert.equal(calls[0].systemPrompt, 'You are Kimi.');+ assert.deepEqual(calls[0].tools, [{ name: 'Bash', description: 'Run', parameters: { type: 'object' } }]);+ assert.equal(calls[0].ms, 2000, 'the model\'s own time, not the tool\'s');+ assert.deepEqual(calls[0].answer.content, [{ type: 'thinking', thinking: 'plan' }, { type: 'toolCall', id: 'k1', name: 'Bash', arguments: { command: 'openfilm look' } }]);+ assert.deepEqual(calls[0].answer.usage, { input: 20, cacheRead: 100, cacheWrite: 0, output: 9, reasoning: 0 });+ assert.equal(calls[1].messages.length, calls[1].settings.messageCount, 'as many messages as Kimi says it sent');+ assert.deepEqual(calls[1].messages[2], { role: 'toolResult', toolCallId: 'k1', toolName: 'Bash', content: [{ type: 'text', text: 'frames saved' }], isError: false });++ const home = mkdtempSync(join(tmpdir(), 'of-kimi-'));+ const dir = join(home, '.kimi-code', 'sessions', 'wd_film_1', 'session_abc-12345');+ mkdirSync(join(dir, 'agents', 'main'), { recursive: true });+ writeFileSync(join(dir, 'agents', 'main', 'wire.jsonl'), jsonl(rows));+ writeFileSync(join(home, '.kimi-code', 'session_index.jsonl'), jsonl([{ sessionId: 'session_abc-12345', sessionDir: dir, workDir: '/film' }]));+ assert.equal(findKimiRecord({ sessionId: 'session_abc-12345', home }), dir);+ assert.equal(findKimiRecord({ sessionId: 'abc-12345', home }), dir, 'its ACP id without the prefix too');+ assert.equal(agentRecordCalls({ agent: 'kimi', sessionId: 'abc-12345', home, from: t(20), to: t(40) }).calls.length, 1);+});++test("Copilot's events: a request for each usage record, its answer by its API call, the system prompt it keeps; no tools", () => {+ const rows = [+ { type: 'session.start', data: { sessionId: 'cop-12345' }, timestamp: at(0) },+ { type: 'user.message', data: { content: 'Make a title', transformedContent: '<current_datetime>now</current_datetime>\n\nMake a title' }, timestamp: at(1) },+ { type: 'system.message', data: { role: 'system', content: 'You are GitHub Copilot.' }, timestamp: at(1) },+ { type: 'session.usage_record', data: { usage: { model: 'gpt-x', inputTokens: 120, cacheReadTokens: 100, outputTokens: 9, duration: 2000, apiCallId: 'a1', initiator: 'user', requestBodyBytes: 41569 } }, timestamp: at(4) },+ { type: 'assistant.message', data: { content: '', apiCallId: 'a1', toolRequests: [{ toolCallId: 'k1', name: 'bash', arguments: { command: 'openfilm look' } }] }, timestamp: at(4) },+ { type: 'tool.execution_complete', data: { toolCallId: 'k1', success: true, result: { content: 'frames saved' } }, timestamp: at(6) },+ { type: 'session.usage_record', data: { usage: { model: 'gpt-x', inputTokens: 10, outputTokens: 2, duration: 1000, apiCallId: 'a2', initiator: 'agent' } }, timestamp: at(8) },+ { type: 'assistant.message', data: { content: 'Done.', apiCallId: 'a2', toolRequests: [] }, timestamp: at(8) },+ ];+ const calls = copilotCallsOf(rows);+ assert.equal(calls.length, 2);+ const [first, second] = calls;+ assert.equal(first.systemPrompt, 'You are GitHub Copilot.');+ assert.equal(first.tools, null);+ assert.deepEqual(first.lacks, ['copilotRebuilt']);+ assert.deepEqual(first.messages, [{ role: 'user', content: [{ type: 'text', text: '<current_datetime>now</current_datetime>\n\nMake a title' }] }], 'as the model got it');+ assert.deepEqual(first.answer.content, [{ type: 'toolCall', id: 'k1', name: 'bash', arguments: { command: 'openfilm look' } }]);+ assert.deepEqual(first.answer.usage, { input: 20, cacheRead: 100, cacheWrite: 0, output: 9, reasoning: 0 });+ assert.equal(first.startedAt, Date.parse(at(2)));+ assert.equal(first.ms, 2000);+ assert.equal(first.settings.requestBodyBytes, 41569);+ assert.deepEqual(second.messages.slice(1), [+ { role: 'assistant', content: first.answer.content },+ { role: 'toolResult', toolCallId: 'k1', toolName: 'bash', content: [{ type: 'text', text: 'frames saved' }], isError: false },+ ]);+ assert.deepEqual(second.answer.content, [{ type: 'text', text: 'Done.' }]);++ const home = mkdtempSync(join(tmpdir(), 'of-copilot-'));+ mkdirSync(join(home, '.copilot', 'session-state', 'cop-12345'), { recursive: true });+ writeFileSync(join(home, '.copilot', 'session-state', 'cop-12345', 'events.jsonl'), jsonl(rows));+ assert.ok(findCopilotRecord({ sessionId: 'cop-12345', home }));+ assert.equal(findCopilotRecord({ sessionId: '../../x', home }), null);+ assert.equal(agentRecordCalls({ agent: 'copilot', sessionId: 'cop-12345', home, from: Date.parse(at(7)), to: Date.parse(at(9)) }).calls.length, 1);+});++test('compactCalls keeps each request only as far as it is new, and reads back whole', () => {+ const calls = claudeCallsOf(claudeSession());+ const lines = compactCalls(calls);+ assert.equal(lines[0].prefix, 0);+ assert.equal(lines[1].prefix, 2, 'the two messages carried over');+ assert.equal(lines[1].messages.length, 2);+ assert.ok('systemPrompt' in lines[1], 'the system prompt changed (the CLI prefix)');+ /* read back as the chat's lib/model-calls.ts does */+ let messages = [];+ for (const [i, line] of lines.entries()) {+ messages = [...messages.slice(0, line.prefix), ...line.messages];+ assert.deepEqual(messages, calls[i].messages);+ }+});diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjsindex 04e3209..db65c57 100644--- a/apps/desktop/src/agent-roster.mjs+++ b/apps/desktop/src/agent-roster.mjs@@ -8,28 +8,31 @@* 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. Codex is* connected from the start, Claude Code once the person connects it.- * · 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 with the reasoning efforts the person says it takes and the one it starts on (`efforts`;- * `auto` alone, sending no reasoning setting, when they said nothing). 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.+ * · byok — the app's own agent (Pi, pi-agent.mjs) on the person's own models, each set up on its own: the name the+ * chat's menu shows, its service (an address 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), its own key, the model asked for there, and the reasoning efforts the person+ * says it takes and the one it starts on (`auto` alone, sending no reasoning setting, when they said nothing). 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 one up sends it one small request with a picture, 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`).+ * byok-keys (each own model's key by its id, sealed with the system's keychain by the caller's `seal`/`unseal`; byok.key,+ * the one key of a version before, is the key of the models set up then).** State per agent: ready · off (disconnected here) · 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) · checking (not known yet).** Reads no Electron module, so `node --test` can use it.*/+import { randomBytes } from 'node:crypto';import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';-import { PI_APIS, modelEfforts } from './pi-config.mjs';+import { PI_APIS, modelEffort } from './pi-config.mjs';/** The person's own agents, as agents.mjs AGENTS has them. */export const OWN_AGENT_IDS = Object.freeze(['codex', 'claude', 'gemini', 'copilot', 'cursor', 'opencode', 'codebuddy', 'qwen', 'kimi']);@@ -69,9 +72,8 @@ export function readChoices(dataDir) {const raw = readJson(join(dataDir, 'agents.json'), {});const shown = { ...DEFAULT_SHOWN };for (const id of AGENT_IDS) if (typeof raw.shown?.[id] === 'boolean') shown[id] = raw.shown[id];- const byok = raw.byok && typeof raw.byok === 'object' && Object.hasOwn(BYOK_FORMATS, raw.byok.format)- ? byokChoice(raw.byok)- : null;+ const models = ownModels(raw.byok);+ const byok = models.length ? { models } : 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 {@@ -82,10 +84,31 @@ export function readChoices(dataDir) {};}-/** The own key's choice as kept: its models (one kept before there could be several is the one), the first the default. */-function byokChoice(raw) {- const models = modelList(Array.isArray(raw.models) && raw.models.length ? raw.models : [raw.model]);- return { format: raw.format, baseUrl: String(raw.baseUrl ?? ''), model: models[0] ?? '', models, efforts: modelEfforts(raw.efforts, models), last4: String(raw.last4 ?? '') };+/**+ * The person's own models as kept: `[{ id, name, format, baseUrl, model, levels, effort, last4 }]`, the first the one a+ * conversation starts on. One without a known format, an address or a model is left out. Kept before each model was set+ * up on its own (one service, its models by name, `efforts` by name): each of those models on that service (`m1`, `m2`…),+ * on the key kept then.+ */+export function ownModels(raw) {+ if (!raw || typeof raw !== 'object') return [];+ const list = Array.isArray(raw.models) && raw.models.some((m) => m && typeof m === 'object')+ ? raw.models+ : Object.hasOwn(BYOK_FORMATS, raw.format)+ ? modelList(Array.isArray(raw.models) && raw.models.length ? raw.models : [raw.model]).map((model, i) => ({+ id: `m${i + 1}`, name: model, format: raw.format, baseUrl: raw.baseUrl, model, last4: raw.last4,+ levels: raw.efforts?.[model]?.levels, effort: raw.efforts?.[model]?.effort,+ }))+ : [];+ const ids = new Set();+ return list.flatMap((m) => {+ const model = String(m?.model ?? '').trim();+ const baseUrl = String(m?.baseUrl ?? '').trim();+ const id = String(m?.id ?? '');+ if (!model || !baseUrl || !Object.hasOwn(BYOK_FORMATS, m?.format) || !/^[a-z0-9]+$/.test(id) || ids.has(id)) return [];+ ids.add(id);+ return [{ id, name: String(m.name ?? '').trim() || model, format: m.format, baseUrl, model, ...modelEffort(m.levels, m.effort), last4: String(m.last4 ?? '') }];+ });}/** Model names, from a list or text (separated by commas or new lines): trimmed, each once, in order. */@@ -154,7 +177,7 @@ export async function probeModel({ format, baseUrl, key, model, fetch: fetchImpl** @param {{* dataDir: string,- * localAgents: () => Promise<Array<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, install: string | null, setupRequired: string | null }>>,+ * localAgents: () => Promise<Array<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, 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>,@@ -174,10 +197,23 @@ export function createRoster(deps) {const live = { waiting: {}, errors: {} };let local = null;- const keyFile = join(dataDir, 'byok.key');- const byokKey = () => {- try { return existsSync(keyFile) ? deps.unseal(readFileSync(keyFile)) : null; } catch { return null; }+ /* each own model's key by its id; the one key of a version before is the key of the models set up then */+ const keysFile = join(dataDir, 'byok-keys');+ const legacyKeyFile = join(dataDir, 'byok.key');+ const byokKeys = () => {+ try { return existsSync(keysFile) ? JSON.parse(deps.unseal(readFileSync(keysFile))) : {}; } catch { return {}; }+ };+ const keyOf = (/** @type {string} */ id) => {+ const key = byokKeys()[id];+ if (typeof key === 'string' && key) return key;+ try { return existsSync(legacyKeyFile) ? deps.unseal(readFileSync(legacyKeyFile)) : null; } catch { return null; }};+ const writeKeys = (keys) => {+ mkdirSync(dataDir, { recursive: true });+ writeFileSync(keysFile, deps.seal(JSON.stringify(keys)), { mode: 0o600 });+ };+ /** The own models that have a key: the ones the agent can use. */+ const keyed = () => (choices.byok?.models ?? []).filter((m) => keyOf(m.id));function stateOf(id) {if (isOwn(id)) {@@ -187,10 +223,10 @@ export function createRoster(deps) {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 } } : {}) };+ return { status: 'ready', ...where, ...(found.account ? { account: { ...found.account } } : {}), ...(found.problem ? { problem: found.problem } : {}) };}if (choices.disconnected.includes(id)) return { status: 'off' };- if (!choices.byok || !byokKey()) return { status: 'key' };+ if (!keyed().length) return { status: 'key' };return { status: 'ready' };}@@ -201,7 +237,7 @@ export function createRoster(deps) {shown: choices.shown[id] ?? false,...stateOf(id),...(live.errors[id] ? { error: live.errors[id] } : {}),- ...(id === 'byok' && choices.byok ? { byok: { ...choices.byok, models: [...choices.byok.models], efforts: modelEfforts(choices.byok.efforts, choices.byok.models) } } : {}),+ ...(id === 'byok' && choices.byok ? { byok: { models: choices.byok.models.map((m) => ({ ...m, levels: [...m.levels] })) } } : {}),}));}@@ -311,50 +347,70 @@ export function createRoster(deps) {},/**- * The person's own key: checked (key accepted, each model reads pictures) before it is kept. A key left empty keeps- * the one kept already (the models or the address changed). `models`: a list, or text with the names separated by- * commas or new lines (`model`, one name, as before). `efforts`: per model, the efforts it takes and the one it- * starts on (pi-config.mjs EFFORTS; `auto` alone for a model not named there).- * @param {{ format: string, baseUrl?: string, models?: string[] | string, model?: string, efforts?: Record<string, { levels?: string[], effort?: string }>, key?: string }} config+ * One of the person's own models, set up or changed (`id` names one already set up): its name (the model, when+ * none), its API format, the service's address, the model asked for there, its key, and its efforts (pi-config.mjs+ * EFFORTS: the ones it takes and the one it starts on). A key left empty keeps the one it has, or takes the key of+ * another model on the same address. Checked first (the key is taken, the model reads pictures).+ * @param {{ id?: string, name?: string, format: string, baseUrl?: string, model: string, key?: string, levels?: string[], effort?: string }} config+ * @returns {Promise<{ ok: true, id: string } | { ok: false, error: string, code?: string }>}*/- async configureByok(config) {+ async saveOwnModel(config) {const format = BYOK_FORMATS[config?.format];if (!format) return { ok: false, error: 'Choose the API format.' };const baseUrl = String(config.baseUrl || format.baseUrl).trim().replace(/\/+$/, '');if (!/^https?:\/\/[^\s]+$/.test(baseUrl)) return { ok: false, error: 'The address has to start with https:// (or http:// for one on this computer).' };- const models = modelList(config.models ?? config.model);- if (!models.length) return { ok: false, error: 'Name the model.' };- const key = String(config.key ?? '').trim() || byokKey();+ const model = String(config.model ?? '').trim();+ if (!model) return { ok: false, error: 'Name the model.' };+ const models = choices.byok?.models ?? [];+ const before = config.id ? models.find((m) => m.id === config.id) : null;+ if (config.id && !before) return { ok: false, error: 'That model is no longer set up.' };+ const sameService = models.find((m) => m.id !== config.id && m.baseUrl === baseUrl && keyOf(m.id));+ const key = String(config.key ?? '').trim() || (before ? keyOf(before.id) : null) || (sameService ? keyOf(sameService.id) : null);if (!key) return { ok: false, error: 'Paste the key.' };- const probes = await Promise.all(models.map((model) => probeModel({ format: config.format, baseUrl, key, model, fetch: deps.fetch })));- const failed = probes.findIndex((p) => !p.ok);- if (failed >= 0) return models.length > 1 ? { ...probes[failed], error: `${models[failed]}: ${probes[failed].error}` } : probes[failed];- mkdirSync(dataDir, { recursive: true });- writeFileSync(keyFile, deps.seal(key), { mode: 0o600 });+ const probe = await probeModel({ format: config.format, baseUrl, key, model, fetch: deps.fetch });+ if (!probe.ok) return probe;+ let id = before?.id;+ while (!id || models.some((m) => m.id === id && m !== before)) id = randomBytes(4).toString('hex');+ const entry = { id, name: String(config.name ?? '').trim() || model, format: config.format, baseUrl, model, ...modelEffort(config.levels, config.effort), last4: key.slice(-4) };+ writeKeys({ ...byokKeys(), [id]: key });delete live.errors.byok;save({...choices,shown: { ...choices.shown, byok: true },disconnected: choices.disconnected.filter((a) => a !== 'byok'),- byok: { format: config.format, baseUrl, model: models[0], models, efforts: modelEfforts(config.efforts, models), last4: key.slice(-4) },+ byok: { models: before ? models.map((m) => (m.id === id ? entry : m)) : [...models, entry] },});deps.closeSessions('byok');- changed();- return { ok: true };+ return { ok: true, id };+ },++ /** One of the person's own models no longer set up, and its key gone with it. */+ removeOwnModel(id) {+ const models = choices.byok?.models ?? [];+ if (!models.some((m) => m.id === id)) return;+ const { [id]: _, ...keys } = byokKeys();+ writeKeys(keys);+ const left = models.filter((m) => m.id !== id);+ save({ ...choices, byok: left.length ? { models: left } : null });+ deps.closeSessions('byok');},/**- * What a session of the app's own agent runs with (pi-agent.mjs): Pi's own folder, the service (Pi's provider:- * its API, address and the variable its key is in), the models (`model` the one it starts on), and the key itself- * (`env`).+ * What a session of the app's own agent runs with (pi-agent.mjs): Pi's own folder, the person's models that have a+ * key (pi-config.mjs OwnModel: each its own service, its key in a variable of its own), the one it starts on, and+ * the keys themselves (`env`).*/harness(id) {if (id !== 'byok') return null;- const key = byokKey();- if (!choices.byok || !key) return null;- const { format, baseUrl, model, models, efforts } = choices.byok;- const provider = { id: 'byok', api: PI_APIS[format], baseUrl, apiKeyEnv: 'OPENFILM_BYOK_KEY' };- return { home: join(dataDir, 'agents', 'byok', 'pi'), provider, model, models: [...models], efforts: modelEfforts(efforts, models), env: { OPENFILM_BYOK_KEY: key } };+ const models = keyed();+ if (!models.length) return null;+ const env = {};+ const own = models.map((m, i) => {+ const keyEnv = `OPENFILM_BYOK_KEY_${i + 1}`;+ env[keyEnv] = keyOf(m.id);+ return { id: m.id, name: m.name, api: PI_APIS[m.format], baseUrl: m.baseUrl, keyEnv, model: m.model, levels: [...m.levels], effort: m.effort };+ });+ return { home: join(dataDir, 'agents', 'byok', 'pi'), models: own, model: own[0].id, env };},};}diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjsindex fcd5e76..8c135f4 100644--- a/apps/desktop/src/agent-roster.test.mjs+++ b/apps/desktop/src/agent-roster.test.mjs@@ -30,89 +30,87 @@ test('each API format is asked in its own shape, with a picture', () => {assert.equal(a.body.messages[0].content[0].type, 'image');});-test('a key is kept only once the service took it with a picture; a model that cannot read one is refused', async () => {+test('a model is kept only once its service took the key with a picture; one that cannot read it is refused', async () => {const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));let answer = { status: 400, body: { error: { message: 'This model does not support image input.' } } };const fetch = async () => new Response(JSON.stringify(answer.body), { status: answer.status });const r = roster(dir, fetch);- const refused = await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'text-only', key: 'sk-1234' });+ const refused = await r.saveOwnModel({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'text-only', key: 'sk-1234' });assert.equal(refused.ok, false);assert.equal(refused.code, 'no-images');assert.equal(readChoices(dir).byok, null, 'nothing kept');answer = { status: 401, body: {} };- assert.match((await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'm', key: 'bad' })).error, /did not accept/);+ assert.match((await r.saveOwnModel({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'm', key: 'bad' })).error, /did not accept/);answer = { status: 200, body: { choices: [] } };- assert.deepEqual(await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1/', model: 'vision', key: 'sk-good-9876' }), { ok: true });- assert.deepEqual(readChoices(dir).byok, { format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'vision', models: ['vision'], efforts: { vision: { levels: ['auto'], effort: 'auto' } }, last4: '9876' });+ const saved = await r.saveOwnModel({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1/', model: 'vision', key: 'sk-good-9876' });+ assert.equal(saved.ok, true);+ assert.deepEqual(readChoices(dir).byok.models, [+ { id: saved.id, name: 'vision', format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'vision', levels: ['auto'], effort: 'auto', last4: '9876' },+ ], 'named for its model when given no name');assert.equal(readChoices(dir).shown.byok, true, 'set up: shown in the chat');- assert.equal(readFileSync(join(dir, 'byok.key'), 'utf8'), 'sealed:sk-good-9876', 'the key sealed');+ assert.deepEqual(JSON.parse(readFileSync(join(dir, 'byok-keys'), 'utf8').replace(/^sealed:/, '')), { [saved.id]: 'sk-good-9876' }, 'the key sealed, by the model');assert.equal(JSON.stringify(readChoices(dir)).includes('sk-good'), false, 'never in the choices file');});-test('each format is Pi\'s provider on that API, the key in its own variable', async () => {+test('each model is its own service with its own key; a key left empty is the one of another model on that address', async () => {const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));- const ok = async () => new Response('{}', { status: 200 });- const r = roster(dir, ok);- await r.configureByok({ format: 'responses', baseUrl: '', model: 'gpt-x', key: 'sk-a' });- let h = r.harness('byok');- assert.deepEqual(h.provider, { id: 'byok', api: 'openai-responses', baseUrl: 'https://api.openai.com/v1', apiKeyEnv: 'OPENFILM_BYOK_KEY' }, 'the official address when none is given');- assert.equal(h.model, 'gpt-x');- assert.deepEqual(h.env, { OPENFILM_BYOK_KEY: 'sk-a' });- assert.equal(h.home, join(dir, 'agents', 'byok', 'pi'), 'its own folder, never the person\'s ~/.pi');-- await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'ds', key: '' });- h = r.harness('byok');- assert.equal(h.provider.api, 'openai-completions');- assert.equal(h.provider.baseUrl, 'https://api.deepseek.com/v1');- assert.equal(h.env.OPENFILM_BYOK_KEY, 'sk-a', 'an empty key keeps the one kept');-- await r.configureByok({ format: 'anthropic', baseUrl: '', model: 'claude-x', key: 'sk-ant' });- h = r.harness('byok');- assert.equal(h.provider.api, 'anthropic-messages');- assert.equal(h.provider.baseUrl, 'https://api.anthropic.com');- assert.equal(h.model, 'claude-x');-});+ const r = roster(dir, async () => new Response('{}', { status: 200 }));+ const gpt = await r.saveOwnModel({ name: 'GPT', format: 'responses', baseUrl: '', model: 'gpt-x', key: 'sk-a', levels: ['high', 'auto', 'medium', 'turbo'], effort: 'medium' });+ const flash = await r.saveOwnModel({ name: 'DeepSeek Flash', format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat', key: 'sk-d' });+ const pro = await r.saveOwnModel({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1/', model: 'deepseek-reasoner' });+ assert.equal(pro.ok, true, 'no key: the one of the model on the same address');+ assert.equal((await r.saveOwnModel({ format: 'anthropic', model: 'claude-x' })).error, 'Paste the key.', 'a new address needs its key');-test('a key may name several models: each is asked with a picture, the first is the one a session starts on', async () => {- const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));- const asked = [];- const fetch = async (_url, init) => {- const { model } = JSON.parse(init.body);- asked.push(model);- return model === 'text-only'- ? new Response(JSON.stringify({ error: { message: 'This model does not support image input.' } }), { status: 400 })- : new Response('{}', { status: 200 });- };- const r = roster(dir, fetch);- const refused = await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', models: 'vision, text-only', key: 'sk-1234' });- assert.equal(refused.ok, false);- assert.match(refused.error, /^text-only: /, 'says which model');- assert.equal(readChoices(dir).byok, null, 'nothing kept');- asked.length = 0;- assert.deepEqual(await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', models: 'vision\n big , vision,', key: 'sk-1234' }), { ok: true });- assert.deepEqual(asked.sort(), ['big', 'vision']);- assert.deepEqual(readChoices(dir).byok.models, ['vision', 'big'], 'trimmed, each once, in order');const h = r.harness('byok');- assert.equal(h.model, 'vision');- assert.deepEqual(h.models, ['vision', 'big']);- assert.deepEqual(r.list().find((a) => a.id === 'byok').byok.models, ['vision', 'big']);+ assert.equal(h.home, join(dir, 'agents', 'byok', 'pi'), 'its own folder, never the person\'s ~/.pi');+ assert.equal(h.model, gpt.id, 'the first one to begin with');+ assert.deepEqual(h.models, [+ { id: gpt.id, name: 'GPT', api: 'openai-responses', baseUrl: 'https://api.openai.com/v1', keyEnv: 'OPENFILM_BYOK_KEY_1', model: 'gpt-x', levels: ['auto', 'medium', 'high'], effort: 'medium' },+ { id: flash.id, name: 'DeepSeek Flash', api: 'openai-completions', baseUrl: 'https://api.deepseek.com/v1', keyEnv: 'OPENFILM_BYOK_KEY_2', model: 'deepseek-chat', levels: ['auto'], effort: 'auto' },+ { id: pro.id, name: 'deepseek-reasoner', api: 'openai-completions', baseUrl: 'https://api.deepseek.com/v1', keyEnv: 'OPENFILM_BYOK_KEY_3', model: 'deepseek-reasoner', levels: ['auto'], effort: 'auto' },+ ], 'the official address when none is given; known efforts, in order');+ assert.deepEqual(h.env, { OPENFILM_BYOK_KEY_1: 'sk-a', OPENFILM_BYOK_KEY_2: 'sk-d', OPENFILM_BYOK_KEY_3: 'sk-d' });+ assert.deepEqual(r.list().find((a) => a.id === 'byok').byok.models.map((m) => m.name), ['GPT', 'DeepSeek Flash', 'deepseek-reasoner']);});-test('each model keeps the efforts the person gave it and the one it starts on; one given none offers Auto alone', async () => {+test('a model changed keeps its place, its id and, given none, its key; one removed takes its key with it', async () => {const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));- const r = roster(dir, async () => new Response('{}', { status: 200 }));- assert.deepEqual(await r.configureByok({ format: 'responses', models: ['gpt-a', 'mine'], key: 'sk-1234',- efforts: { 'gpt-a': { levels: ['high', 'auto', 'medium', 'turbo'], effort: 'medium' }, mine: { levels: [], effort: 'high' }, gone: { levels: ['max'] } } }), { ok: true });- const efforts = { 'gpt-a': { levels: ['auto', 'medium', 'high'], effort: 'medium' }, mine: { levels: ['auto'], effort: 'auto' } };- assert.deepEqual(readChoices(dir).byok.efforts, efforts, 'known efforts in order; nothing for a model not named');- assert.deepEqual(r.harness('byok').efforts, efforts);- assert.deepEqual(r.list().find((a) => a.id === 'byok').byok.efforts, efforts);+ const closed = [];+ const r = roster(dir, async () => new Response('{}', { status: 200 }), { closeSessions: (id) => closed.push(id) });+ const a = await r.saveOwnModel({ format: 'responses', model: 'gpt-a', key: 'sk-a' });+ const b = await r.saveOwnModel({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'ds', key: 'sk-d' });+ assert.deepEqual(await r.saveOwnModel({ id: a.id, name: 'Mine', format: 'responses', model: 'gpt-b', levels: ['low', 'max'], effort: 'max' }), { ok: true, id: a.id });+ assert.deepEqual(readChoices(dir).byok.models.map((m) => [m.id, m.name, m.model, m.effort]), [[a.id, 'Mine', 'gpt-b', 'max'], [b.id, 'ds', 'ds', 'auto']]);+ assert.equal(r.harness('byok').env.OPENFILM_BYOK_KEY_1, 'sk-a');+ assert.equal((await r.saveOwnModel({ id: 'gone', format: 'responses', model: 'x' })).ok, false);++ r.removeOwnModel(b.id);+ assert.deepEqual(r.harness('byok').models.map((m) => m.id), [a.id]);+ assert.equal(readFileSync(join(dir, 'byok-keys'), 'utf8').includes('sk-d'), false, 'its key gone');+ r.removeOwnModel(a.id);+ assert.equal(readChoices(dir).byok, null);+ assert.equal(r.harness('byok'), null);+ assert.equal(r.list().find((x) => x.id === 'byok').status, 'key');+ assert.equal(closed.filter((id) => id === 'byok').length, 5, 'its sessions closed on each change: they run on the models set up');});-test('a key kept with one model, before there could be several, reads as that one', () => {+test('one service with several models, kept before each model was set up on its own, is those models on it, on its key', async () => {const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));+ writeFileSync(join(dir, 'agents.json'), JSON.stringify({ byok: { format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'a', models: ['a', 'b'],+ efforts: { b: { levels: ['auto', 'high'], effort: 'high' } }, last4: 'abcd' } }));+ writeFileSync(join(dir, 'byok.key'), 'sealed:sk-old-abcd');+ assert.deepEqual(readChoices(dir).byok.models, [+ { id: 'm1', name: 'a', format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'a', levels: ['auto'], effort: 'auto', last4: 'abcd' },+ { id: 'm2', name: 'b', format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'b', levels: ['auto', 'high'], effort: 'high', last4: 'abcd' },+ ]);+ /* the oldest, with one model and no list */writeFileSync(join(dir, 'agents.json'), JSON.stringify({ byok: { format: 'responses', baseUrl: 'https://api.openai.com/v1', model: 'gpt-x', last4: 'abcd' } }));- assert.deepEqual(readChoices(dir).byok, { format: 'responses', baseUrl: 'https://api.openai.com/v1', model: 'gpt-x', models: ['gpt-x'], efforts: { 'gpt-x': { levels: ['auto'], effort: 'auto' } }, last4: 'abcd' });+ assert.deepEqual(readChoices(dir).byok.models.map((m) => [m.id, m.model]), [['m1', 'gpt-x']]);++ writeFileSync(join(dir, 'agents.json'), JSON.stringify({ byok: { format: 'chat', baseUrl: 'https://api.deepseek.com/v1', models: ['a', 'b'], last4: 'abcd' } }));+ const r = roster(dir, async () => new Response('{}', { status: 200 }));+ await r.saveOwnModel({ format: 'responses', model: 'gpt', key: 'sk-new' });+ assert.deepEqual(Object.values(r.harness('byok').env), ['sk-old-abcd', 'sk-old-abcd', 'sk-new'], 'the ones from before on the key kept then');});test("Codex and Claude Code are shown in the chat from the start, the person's other agents once connected or switched on", async () => {@@ -192,6 +190,18 @@ test('disconnecting only stops OpenFilm using an agent; connecting again uses thassert.deepEqual(closed, ['claude', 'claude', 'claude'], 'its sessions closed each time: none goes on with the old account');});+test("Codex found but unable to read its own settings says so, with what it said", async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));+ const problem = 'Error loading configuration: config.toml:2:16: unknown variant `full`';+ const r = roster(dir, undefined, {+ localAgents: async () => [{ id: 'codex', cli: { path: '/bin/codex' }, signedIn: null, account: null, problem, install: null, setupRequired: null }],+ });+ await r.refresh();+ const codex = r.list().find((a) => a.id === 'codex');+ assert.equal(codex.status, 'ready');+ assert.equal(codex.problem, problem);+});+test('Codex is connected from the start, Claude Code once the person connects it; a choice kept stays as it is', () => {const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));assert.deepEqual(readChoices(dir).disconnected, ['claude']);diff --git a/apps/desktop/src/agent-skills.mjs b/apps/desktop/src/agent-skills.mjsnew file mode 100644index 0000000..b980149--- /dev/null+++ b/apps/desktop/src/agent-skills.mjs@@ -0,0 +1,312 @@+/**+ * What an agent has in the chat besides its own program: its maker's skills and MCP servers (never touched),+ * OpenFilm's skills (the project's, the person's own and the official ones: openfilm/src/skills.mjs), and of the skills+ * and MCP servers the person installed in the agent themselves only those they let into OpenFilm, one by one. Each+ * agent is told by its own switch, for that session only: the person's own configuration is never written, nor the+ * folder the agent signs in from.+ *+ * Claude Code `_meta.claudeCode.options`: OpenFilm's skills as a local plugin (`plugins`, named openfilm:<name>);+ * `settings` (for that session, above the person's own): `skillOverrides` turning each of the person's+ * own skills off, and `deniedMcpServers` their own MCP servers (claude.ai's connectors stay).+ * Codex OpenFilm's through ACP `additionalDirectories` (Codex reads `<dir>/.agents/skills`); CODEX_CONFIG+ * turning each of the person's own skills off by its file (`skills.config`), and their own MCP servers+ * (`mcp_servers.<name>.enabled: false`, the rest of each left as it is).+ * OpenCode OPENCODE_CONFIG_CONTENT: OpenFilm's folder in `skills.paths`, `permission.skill` denying every skill+ * but its own, OpenFilm's and those let in, and `mcp.<name>.enabled: false` (merged with the person's).+ * Qwen Code a system-defaults file of the app's (QWEN_CODE_SYSTEM_DEFAULTS_PATH): `skills.disabled`,+ * `skills.directories` (OpenFilm's), `mcp.excluded`. Its lists merge with the person's own.+ * Gemini CLI the same (GEMINI_CLI_SYSTEM_DEFAULTS_PATH): `skills.disabled`, `mcp.excluded`; it takes no other+ * skills folder, so OpenFilm's reach it when named in a message.+ * Copilot OpenFilm's through COPILOT_SKILLS_DIRS and `--disable-mcp-server` for the person's own servers; it+ * has no way to hide a skill, so it keeps all of the person's.+ * Pi OpenFilm's only.+ * CodeBuddy, Cursor and Kimi are not told anything: they have the person's skills and servers as in their own terminal,+ * and OpenFilm's skills when named in a message. A system-defaults file the person set themselves is left as it is.+ *+ * Which are the person's own is read from where each agent keeps them; its maker's are elsewhere or marked (Claude+ * Code's skills/synced/ from claude.ai and its claude.ai connectors, Codex's .system skills, OpenAI's plugins and the+ * servers its own apps put in its configuration).+ *+ * A session's OpenFilm skills are a folder of the app's, links to each skill's own folder (agent-skills/<id>/skills),+ * as each agent reads a plugin or a skills folder. Reads no Electron module, so `node --test` can use it.+ */+import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { basename, dirname, join, resolve } from 'node:path';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';++const require = createRequire(import.meta.url);+/* by its file URL: import() takes no Windows path (`D:\…`) */+const skillsLib = () => import(pathToFileURL(require.resolve('openfilm/skills')).href);++/** The agents whose own skills can be hidden in OpenFilm (byok: the app's own agent, Pi). */+export const FILTERED_AGENTS = Object.freeze(['claude', 'codex', 'opencode', 'qwen', 'gemini', 'byok']);+/** The agents whose own MCP servers can be hidden in OpenFilm. */+export const MCP_AGENTS = Object.freeze(['claude', 'codex', 'opencode', 'qwen', 'gemini', 'copilot']);++/** a session's folder of links is kept this long (a conversation resumed later makes a new one) */+const KEEP_MS = 2 * 24 * 60 * 60_000;++/* ── what the person let in ──────────────────────────────────────────────── */++/**+ * The app's record (`<dataDir>/skills.json`): `allowed[agent]`, the person's own skills let into OpenFilm, and+ * `mcp[agent]`, their own MCP servers let in, each by name.+ */+export function skillStore(dataDir) {+ const file = join(dataDir, 'skills.json');+ const read = () => { try { const raw = JSON.parse(readFileSync(file, 'utf8')); return { allowed: raw.allowed ?? {}, mcp: raw.mcp ?? {} }; } catch { return { allowed: {}, mcp: {} }; } };+ const names = (list) => (Array.isArray(list) ? list.filter((n) => typeof n === 'string') : []);+ const set = (field, agent, name, on) => {+ const data = read();+ const now = new Set(names(data[field][agent]));+ if (on) now.add(name); else now.delete(name);+ data[field][agent] = [...now].sort();+ mkdirSync(dataDir, { recursive: true });+ writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`);+ };+ return {+ allowed: (agent) => names(read().allowed[agent]),+ setAllowed: (agent, name, on) => set('allowed', agent, name, on),+ mcpAllowed: (agent) => names(read().mcp[agent]),+ setMcpAllowed: (agent, name, on) => set('mcp', agent, name, on),+ };+}++/* ── the person's own skills, as each agent keeps them ───────────────────── */++const isDir = (p) => { try { return statSync(p).isDirectory(); } catch { return false; } };+const readJson = (file) => { try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; } };+/** JSON with comments (OpenCode's .jsonc) */+const readJsonc = (file) => {+ let text;+ try { text = readFileSync(file, 'utf8'); } catch { return null; }+ try { return JSON.parse(text.replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, s) => s ?? '').replace(/,(\s*[}\]])/g, '$1')); } catch { return null; }+};+/** each folder in `dir` with a SKILL.md, read (name, description, folder, file) */+async function skillFolders(dir, { except = [] } = {}) {+ const { readSkill } = await skillsLib();+ let names = [];+ try { names = readdirSync(dir); } catch { return []; }+ return names.filter((n) => !n.startsWith('.') && !except.includes(n)).flatMap((n) => {+ const folder = join(dir, n);+ if (!isDir(folder)) return [];+ const skill = readSkill(folder, 'mine');+ return skill ? [{ name: skill.name, dirName: n, description: skill.description, folder, file: skill.file, ...(isOurs(skill) ? { ours: true } : {}) }] : [];+ });+}++/**+ * OpenFilm's own skill for agents in a terminal (the repository's skills/openfilm: "run `npx openfilm`, read the+ * manual"), installed in an agent: in the app it is never wanted, as the app tells the agent the same, and its `npx`+ * would contradict it. Never shown, never let in.+ */+export const isOurs = (skill) => skill.name === 'openfilm' && /\bOpenFilm\b/.test(skill.description ?? '');+/** the folder and each above it, to the root */+const upFrom = (cwd) => { const out = []; for (let up = resolve(cwd); ; up = dirname(up)) { out.push(up); if (up === dirname(up)) break; } return out; };+const subdirs = (dir) => { try { return readdirSync(dir); } catch { return []; } };++/**+ * The skills the person installed in an agent themselves (not its maker's), for the project in `cwd`: `[{ name,+ * dirName, description, folder, file }]`, each once by name. `env`: the person's shell (CLAUDE_CONFIG_DIR, CODEX_HOME…).+ */+export async function ownSkills(agent, { cwd = '', env = {}, home = homedir() } = {}) {+ const claudeHome = env.CLAUDE_CONFIG_DIR || join(home, '.claude');+ const codexHome = env.CODEX_HOME || join(home, '.codex');+ const project = (subs) => (cwd ? upFrom(cwd) : []).filter((d) => d !== home).flatMap((d) => subs.map((s) => join(d, s)));+ /** @type {string[]} */+ let dirs = [];+ switch (agent) {+ case 'claude':+ dirs = [join(claudeHome, 'skills'), ...project(['.claude/skills'])];+ break;+ case 'codex': {+ dirs = [join(codexHome, 'skills'), join(home, '.agents', 'skills'), ...project(['.agents/skills', '.codex/skills'])];+ /* plugins from marketplaces not OpenAI's: cache/<marketplace>/<plugin>/<version>/skills */+ const cache = join(codexHome, 'plugins', 'cache');+ for (const market of subdirs(cache).filter((m) => !/^openai/i.test(m))) {+ for (const plugin of subdirs(join(cache, market))) for (const version of subdirs(join(cache, market, plugin))) dirs.push(join(cache, market, plugin, version, 'skills'));+ }+ break;+ }+ case 'opencode': {+ const config = join(env.XDG_CONFIG_HOME || join(home, '.config'), 'opencode');+ dirs = [join(home, '.claude', 'skills'), join(home, '.agents', 'skills'), join(config, 'skill'), join(config, 'skills'),+ ...project(['.claude/skills', '.agents/skills', '.opencode/skill', '.opencode/skills'])];+ break;+ }+ case 'qwen': dirs = [join(env.QWEN_HOME || join(home, '.qwen'), 'skills'), join(home, '.agents', 'skills'), ...project(['.qwen/skills', '.agents/skills'])]; break;+ case 'gemini': dirs = [join(home, '.gemini', 'skills'), join(home, '.agents', 'skills'), ...project(['.gemini/skills', '.agents/skills'])]; break;+ case 'copilot': dirs = [join(env.COPILOT_HOME || join(home, '.copilot'), 'skills'), join(home, '.agents', 'skills'), ...project(['.github/skills', '.agents/skills', '.claude/skills'])]; break;+ default: return [];+ }+ const seen = new Map();+ for (const dir of dirs) {+ /* Claude Code's synced/ is claude.ai's (Anthropic's), and Codex's .system its own: their makers' */+ for (const skill of await skillFolders(dir, { except: ['synced'] })) if (!seen.has(skill.name)) seen.set(skill.name, skill);+ }+ return [...seen.values()].sort((a, b) => a.name.localeCompare(b.name));+}++/* ── the person's own MCP servers ────────────────────────────────────────── */++/** what a server is, in a few words: the program it runs, or the host it is at */+function serverDetail(config) {+ if (typeof config?.url === 'string' || typeof config?.httpUrl === 'string') { try { return new URL(config.url ?? config.httpUrl).host; } catch { return String(config.url ?? config.httpUrl).slice(0, 60); } }+ const command = Array.isArray(config?.command) ? config.command[0] : config?.command;+ return typeof command === 'string' ? basename(command) : '';+}++/** Codex's config.toml: each `[mcp_servers.<name>]` and its command and url (its other keys and its tables left). */+export function codexServers(toml) {+ const out = [];+ let current = null;+ for (const line of String(toml ?? '').split(/\r?\n/)) {+ const head = /^\s*\[\s*mcp_servers\.("(?:[^"\\]|\\.)*"|[\w-]+)\s*\]\s*$/.exec(line);+ if (head) { current = { name: head[1].startsWith('"') ? JSON.parse(head[1]) : head[1], config: {} }; out.push(current); continue; }+ if (/^\s*\[/.test(line)) { current = null; continue; }+ const kv = current && /^\s*(command|url)\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')/.exec(line);+ if (kv) current.config[kv[1]] = kv[2].startsWith('"') ? JSON.parse(kv[2]) : kv[2].slice(1, -1);+ }+ return out;+}++/* a server Codex's own apps (Codex, ChatGPT) put in its configuration, or that runs from its own folders: its maker's */+const OPENAI_SERVER = /(?:^|\/)(?:Codex|ChatGPT)[^/]*\.app(?:\/|$)|\/\.codex\/|codex-runtimes/i;++/**+ * The MCP servers the person added to an agent themselves (not its maker's), as its settings have them for the+ * project in `cwd`: `[{ name, detail }]` (detail: the program it runs, or its host), each once by name.+ */+export function ownMcpServers(agent, { cwd = '', env = {}, home = homedir() } = {}) {+ /** @type {Array<[string, any]>} */+ let found = [];+ const entries = (obj) => (obj && typeof obj === 'object' && !Array.isArray(obj) ? Object.entries(obj) : []);+ switch (agent) {+ case 'claude': {+ const state = readJson(env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(home, '.claude.json'));+ found = [...entries(state?.mcpServers), ...entries(cwd ? state?.projects?.[resolve(cwd)]?.mcpServers : null), ...entries(cwd ? readJson(join(cwd, '.mcp.json'))?.mcpServers : null)];+ break;+ }+ case 'codex': {+ let toml = '';+ try { toml = readFileSync(join(env.CODEX_HOME || join(home, '.codex'), 'config.toml'), 'utf8'); } catch { /* none */ }+ found = codexServers(toml).filter((s) => !OPENAI_SERVER.test(`${s.config.command ?? ''} ${s.config.url ?? ''}`)).map((s) => [s.name, s.config]);+ break;+ }+ case 'opencode': {+ const config = join(env.XDG_CONFIG_HOME || join(home, '.config'), 'opencode');+ const files = [join(config, 'opencode.json'), join(config, 'opencode.jsonc'), ...(cwd ? [join(cwd, 'opencode.json'), join(cwd, 'opencode.jsonc')] : [])];+ found = files.flatMap((f) => entries(readJsonc(f)?.mcp));+ break;+ }+ case 'qwen': found = [join(env.QWEN_HOME || join(home, '.qwen'), 'settings.json'), ...(cwd ? [join(cwd, '.qwen', 'settings.json')] : [])].flatMap((f) => entries(readJson(f)?.mcpServers)); break;+ case 'gemini': found = [join(home, '.gemini', 'settings.json'), ...(cwd ? [join(cwd, '.gemini', 'settings.json')] : [])].flatMap((f) => entries(readJson(f)?.mcpServers)); break;+ case 'copilot': found = entries(readJson(join(env.COPILOT_HOME || join(home, '.copilot'), 'mcp-config.json'))?.mcpServers); break;+ default: return [];+ }+ const seen = new Map();+ for (const [name, config] of found) if (name && !seen.has(name)) seen.set(name, { name, detail: serverDetail(config) });+ return [...seen.values()].sort((a, b) => a.name.localeCompare(b.name));+}++/* ── a session's switches ────────────────────────────────────────────────── */++/** A folder of links to OpenFilm's skills, as a Claude Code plugin and as a skills folder (`skills`, `.agents/skills`). */+function linkFolder(base, skills) {+ mkdirSync(base, { recursive: true });+ for (const name of subdirs(base)) {+ try { if (Date.now() - statSync(join(base, name)).mtimeMs > KEEP_MS) rmSync(join(base, name), { recursive: true, force: true }); } catch { /* in use */ }+ }+ const dir = join(base, `${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);+ const link = process.platform === 'win32' ? 'junction' : 'dir';+ mkdirSync(join(dir, '.claude-plugin'), { recursive: true });+ mkdirSync(join(dir, 'skills'));+ mkdirSync(join(dir, '.agents'));+ writeFileSync(join(dir, '.claude-plugin', 'plugin.json'), `${JSON.stringify({ name: 'openfilm', description: 'OpenFilm skills', version: '1.0.0' }, null, 2)}\n`);+ for (const skill of skills) {+ if (!/^[\w.-]+$/.test(skill.name)) continue;+ try { symlinkSync(skill.folder, join(dir, 'skills', skill.name), link); } catch { /* one that cannot be linked is left out */ }+ }+ symlinkSync(join(dir, 'skills'), join(dir, '.agents', 'skills'), link);+ return dir;+}++/** A system-defaults file of the app's for this session (Qwen Code's, Gemini CLI's), beside its links. */+function defaultsFile(dir, name, settings) {+ const file = join(dir, name);+ writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);+ return file;+}++/**+ * What a session of `agent` is started with for its skills and MCP servers: `{ claude?, codexConfig?,+ * additionalDirectories?, env?, args?, piSkills?, log }` (agents.mjs puts each where it goes). `log`: what the turn log+ * says of it (agents.mjs `opened.skills`). `allowed`, `mcpAllowed`: the person's own let in, by name.+ * @param {string} agent+ * `mine`: the person's own skills folder (openfilm/skills mySkillsDir).+ * @param {{ cwd: string, env?: Record<string, string>, dataDir: string, mine?: string, allowed?: string[],+ * mcpAllowed?: string[], home?: string }} o+ */+export async function sessionSkills(agent, { cwd, env = {}, dataDir, mine, allowed = [], mcpAllowed = [], home = homedir() }) {+ const { listSkills, mySkillsDir } = await skillsLib();+ const openfilm = listSkills({ project: cwd, mine: mine ?? mySkillsDir() });+ const names = openfilm.map((s) => s.name);+ const filtered = FILTERED_AGENTS.includes(agent);+ const base = { openfilm: names, allowed: [...allowed], mcpAllowed: [...mcpAllowed], filtered, mcpFiltered: MCP_AGENTS.includes(agent) };+ if (!filtered && !MCP_AGENTS.includes(agent)) return { log: base };+ const hidden = filtered && agent !== 'byok' ? (await ownSkills(agent, { cwd, env, home })).filter((s) => s.ours || !allowed.includes(s.name)) : [];+ const mcpHidden = MCP_AGENTS.includes(agent) ? ownMcpServers(agent, { cwd, env, home }).filter((s) => !mcpAllowed.includes(s.name)).map((s) => s.name) : [];+ const dir = linkFolder(join(dataDir, 'agent-skills'), openfilm);+ const log = { ...base, folder: dir, hidden: hidden.map((s) => s.name), mcpHidden };+ switch (agent) {+ case 'claude': {+ /* by its folder's name, as Claude Code names the person's own skills: its front matter's name may be one of its+ maker's too (a skill-creator of the person's beside Anthropic's), and that one stays */+ const skillOverrides = Object.fromEntries(hidden.map((s) => [s.dirName, 'off']));+ const settings = { skillOverrides, deniedMcpServers: mcpHidden.map((serverName) => ({ serverName })) };+ return { claude: { plugins: [{ type: 'local', path: dir }], settings }, log: { ...log, settings } };+ }+ case 'codex':+ return {+ codexConfig: { skills: { config: hidden.map((s) => ({ path: s.file, enabled: false })) }, ...Object.fromEntries(mcpHidden.map((n) => [`mcp_servers.${n}.enabled`, false])) },+ additionalDirectories: [dir],+ log,+ };+ case 'opencode': {+ const skill = { '*': 'deny', 'customize-opencode': 'allow', ...Object.fromEntries([...names, ...allowed].map((n) => [n, 'allow'])) };+ const mcp = Object.fromEntries(mcpHidden.map((n) => [n, { enabled: false }]));+ return { env: { OPENCODE_CONFIG_CONTENT: JSON.stringify({ skills: { paths: [join(dir, 'skills')] }, permission: { skill }, ...(mcpHidden.length ? { mcp } : {}) }) }, log };+ }+ case 'qwen':+ case 'gemini': {+ const variable = agent === 'qwen' ? 'QWEN_CODE_SYSTEM_DEFAULTS_PATH' : 'GEMINI_CLI_SYSTEM_DEFAULTS_PATH';+ if (env[variable]) return { log: { ...log, filtered: false, mcpFiltered: false, unfiltered: `${variable} is the person's own` } };+ const settings = {+ skills: { disabled: hidden.map((s) => s.name), ...(agent === 'qwen' ? { directories: [join(dir, 'skills')] } : {}) },+ ...(mcpHidden.length ? { mcp: { excluded: mcpHidden } } : {}),+ };+ return { env: { [variable]: defaultsFile(dir, `${agent}-defaults.json`, settings) }, log: { ...log, settings } };+ }+ case 'copilot':+ return {+ env: { COPILOT_SKILLS_DIRS: [env.COPILOT_SKILLS_DIRS, join(dir, 'skills')].filter(Boolean).join(',') },+ args: mcpHidden.flatMap((n) => ['--disable-mcp-server', n]),+ log,+ };+ case 'byok':+ return { piSkills: { paths: [join(dir, 'skills')], names }, log };+ default:+ return { log };+ }+}++/** Two JSON configurations as one: objects merged key by key, the second's other values winning. */+export function mergeConfig(a, b) {+ if (!a || typeof a !== 'object' || Array.isArray(a)) return b;+ if (!b || typeof b !== 'object' || Array.isArray(b)) return b ?? a;+ const out = { ...a };+ for (const [k, v] of Object.entries(b)) out[k] = k in out ? mergeConfig(out[k], v) : v;+ return out;+}diff --git a/apps/desktop/src/agent-skills.test.mjs b/apps/desktop/src/agent-skills.test.mjsnew file mode 100644index 0000000..74e137d--- /dev/null+++ b/apps/desktop/src/agent-skills.test.mjs@@ -0,0 +1,166 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { codexServers, mergeConfig, ownMcpServers, ownSkills, sessionSkills, skillStore } from './agent-skills.mjs';++const skill = (dir, name, description = `${name} skill`) => {+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n---\n\nBody.\n`);+ return dir;+};++/** A person's home with skills of their own beside their agents' makers', and a project with skills of its own. */+function world() {+ const root = mkdtempSync(join(tmpdir(), 'of-agent-skills-'));+ const home = join(root, 'home');+ const project = join(home, 'Movies', 'film');+ mkdirSync(project, { recursive: true });+ writeFileSync(join(project, 'film.html'), '<!doctype html>');+ /* Claude Code: the person's own, and claude.ai's synced ones (Anthropic's) */+ skill(join(home, '.claude', 'skills', 'chatcut-voice'), 'voice');+ skill(join(home, '.claude', 'skills', 'research'), 'research');+ skill(join(home, '.claude', 'skills', 'synced', 'bucket', 'pdf'), 'pdf');+ skill(join(project, '.claude', 'skills', 'team-style'), 'team-style');+ /* Codex: its own .system, the person's, ~/.agents, a plugin from OpenAI's marketplace and one not */+ skill(join(home, '.codex', 'skills', '.system', 'imagegen'), 'imagegen');+ skill(join(home, '.codex', 'skills', 'old-openfilm'), 'openfilm');+ skill(join(home, '.agents', 'skills', 'notes'), 'notes');+ skill(join(home, '.codex', 'plugins', 'cache', 'openai-curated', 'sites', '1.0', 'skills', 'sites'), 'sites');+ skill(join(home, '.codex', 'plugins', 'cache', 'someone', 'pets', '0.1', 'skills', 'pet'), 'pet');+ /* MCP servers: Claude Code's (the person's, and one local to the project), Codex's (two its own apps put there, one+ of the person's), OpenCode's, Qwen Code's, Gemini CLI's, Copilot's */+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ mcpServers: { chatcut: { type: 'stdio', command: '/Apps/ChatCut/chatcut-mcp' }, notes: { type: 'http', url: 'http://127.0.0.1:9/mcp' } },+ projects: { [project]: { mcpServers: { local: { command: 'node' } } } } }));+ mkdirSync(join(home, '.codex'), { recursive: true });+ writeFileSync(join(home, '.codex', 'config.toml'), [+ 'model = "x"', '[mcp_servers.node_repl]', 'command = "/Applications/ChatGPT.app/Contents/Resources/node_repl"', 'args = []',+ '[mcp_servers.node_repl.env]', 'A = "b"', '[mcp_servers.computer-use]', 'command = "./Codex Computer Use.app/Contents/MacOS/client"',+ '[mcp_servers."my-db"]', 'url = "http://127.0.0.1:8/mcp"', 'http_headers = { "Authorization" = "Bearer secret" }', '[plugins."x"]', 'enabled = true',+ ].join('\n'));+ mkdirSync(join(home, '.config', 'opencode'), { recursive: true });+ writeFileSync(join(home, '.config', 'opencode', 'opencode.jsonc'), '{\n // mine\n "mcp": { "search": { "type": "remote", "url": "https://s.example.com/mcp" }, },\n}');+ mkdirSync(join(home, '.qwen'), { recursive: true });+ writeFileSync(join(home, '.qwen', 'settings.json'), JSON.stringify({ mcpServers: { qtool: { command: 'qtool' } } }));+ mkdirSync(join(home, '.gemini'), { recursive: true });+ writeFileSync(join(home, '.gemini', 'settings.json'), JSON.stringify({ mcpServers: { gtool: { httpUrl: 'https://g.example.com/mcp' } } }));+ skill(join(home, '.gemini', 'skills', 'gem-notes'), 'gem-notes');+ mkdirSync(join(home, '.copilot'), { recursive: true });+ writeFileSync(join(home, '.copilot', 'mcp-config.json'), JSON.stringify({ mcpServers: { ctool: { command: 'ctool' } } }));+ /* OpenFilm's: the project's and the person's own */+ const openfilmHome = join(home, '.openfilm');+ skill(join(project, 'skills', 'brand'), 'brand');+ skill(join(openfilmHome, 'skills', 'lyric-pv'), 'lyric-pv');+ return { root, home, project, openfilmHome, dataDir: join(root, 'data') };+}++test("the person's own skills, as each agent keeps them, never its maker's", async () => {+ const { home, project } = world();+ assert.deepEqual((await ownSkills('claude', { cwd: project, home })).map((s) => [s.name, s.dirName]),+ [['research', 'research'], ['team-style', 'team-style'], ['voice', 'chatcut-voice']], 'not claude.ai\'s synced ones');+ assert.deepEqual((await ownSkills('codex', { cwd: project, home })).map((s) => s.name), ['notes', 'openfilm', 'pet'], 'not .system, not OpenAI\'s plugins');+ assert.deepEqual((await ownSkills('gemini', { cwd: project, home })).map((s) => s.name), ['gem-notes', 'notes']);+ assert.deepEqual((await ownSkills('cursor', { cwd: project, home })), [], 'an agent whose skills are not read');+});++test("Claude Code: OpenFilm's skills as a plugin; the person's own skills and MCP servers off but those let in", async () => {+ const w = world();+ const s = await sessionSkills('claude', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), allowed: ['research'], mcpAllowed: ['notes'] });+ assert.equal(s.claude.plugins[0].type, 'local');+ const dir = s.claude.plugins[0].path;+ assert.deepEqual(JSON.parse(readFileSync(join(dir, '.claude-plugin', 'plugin.json'), 'utf8')).name, 'openfilm');+ assert.equal(realpathSync(join(dir, 'skills', 'brand')), realpathSync(join(w.project, 'skills', 'brand')), 'linked to the skill\'s own folder');+ assert.ok(existsSync(join(dir, '.agents', 'skills', 'lyric-pv', 'SKILL.md')), 'and readable as a skills folder');+ assert.deepEqual(s.claude.settings.skillOverrides, { 'team-style': 'off', 'chatcut-voice': 'off' }, 'by its folder\'s name, as Claude Code names it; the one let in left on');+ assert.deepEqual(s.claude.settings.deniedMcpServers, [{ serverName: 'chatcut' }, { serverName: 'local' }], 'its connectors not among them: they are not the person\'s');+ assert.deepEqual(s.log.hidden, ['team-style', 'voice']);+ assert.deepEqual(s.log.mcpHidden, ['chatcut', 'local']);+});++test("Codex: each of the person's own not let in turned off by its file, OpenFilm's as an extra folder", async () => {+ const w = world();+ const s = await sessionSkills('codex', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), allowed: ['notes'] });+ assert.deepEqual(s.codexConfig.skills.config.map((c) => [c.path, c.enabled]),+ [[join(w.home, '.codex/skills/old-openfilm/SKILL.md'), false], [join(w.home, '.codex/plugins/cache/someone/pets/0.1/skills/pet/SKILL.md'), false]]);+ assert.equal(s.codexConfig['mcp_servers.my-db.enabled'], false, 'the person\'s server turned off by itself, the rest of it left');+ assert.ok(!('mcp_servers.node_repl.enabled' in s.codexConfig), 'the servers its own apps put there stay');+ assert.equal(s.additionalDirectories.length, 1);+ assert.ok(existsSync(join(s.additionalDirectories[0], '.agents', 'skills', 'brand', 'SKILL.md')));+});++test("OpenCode: every skill denied but its own, OpenFilm's and those let in; Pi: OpenFilm's only; the others unfiltered", async () => {+ const w = world();+ const oc = await sessionSkills('opencode', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), allowed: ['research'] });+ const config = JSON.parse(oc.env.OPENCODE_CONFIG_CONTENT);+ /* with the project's brand and lyric-pv: the official skills that come with the package */+ const official = readdirSync(new URL('../../../packages/openfilm/skills/', import.meta.url), { withFileTypes: true }).filter((e) => e.isDirectory());+ const names = [...official.map((e) => e.name), 'brand', 'lyric-pv'].sort();+ assert.deepEqual(config.permission.skill, { '*': 'deny', 'customize-opencode': 'allow', ...Object.fromEntries([...names, 'research'].sort().map((n) => [n, 'allow'])) });+ assert.deepEqual(config.mcp, { search: { enabled: false } });+ assert.match(config.skills.paths[0], /agent-skills[\\/].+[\\/]skills$/);+ const pi = await sessionSkills('byok', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills') });+ assert.deepEqual(pi.piSkills.names, names);+ const kimi = await sessionSkills('kimi', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills') });+ assert.deepEqual(kimi.log, { openfilm: names, allowed: [], mcpAllowed: [], filtered: false, mcpFiltered: false });+ /* a link (a junction on Windows) to the project's own folder */+ assert.equal(realpathSync(join(pi.piSkills.paths[0], 'brand')), realpathSync(join(w.project, 'skills', 'brand')));+});++test("OpenFilm's own skill for terminal agents is known, never offered, and always off in the app", async () => {+ const w = world();+ skill(join(w.home, '.claude', 'skills', 'openfilm'), 'openfilm', 'Make videos as web pages with OpenFilm.');+ const own = await ownSkills('claude', { cwd: w.project, home: w.home });+ assert.equal(own.find((s) => s.name === 'openfilm')?.ours, true);+ assert.equal(own.find((s) => s.name === 'research')?.ours, undefined);+ const s = await sessionSkills('claude', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), allowed: ['openfilm', 'research'] });+ assert.equal(s.claude.settings.skillOverrides.openfilm, 'off', 'off even when it was let in');+ assert.equal(s.claude.settings.skillOverrides.research, undefined);+});++test('Qwen Code and Gemini CLI: a system-defaults file of the app\'s; Copilot: OpenFilm\'s folder and its servers off', async () => {+ const w = world();+ const qwen = await sessionSkills('qwen', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills') });+ const q = JSON.parse(readFileSync(qwen.env.QWEN_CODE_SYSTEM_DEFAULTS_PATH, 'utf8'));+ assert.deepEqual(q.mcp, { excluded: ['qtool'] });+ assert.match(q.skills.directories[0], /agent-skills[\\/].+[\\/]skills$/);+ const gemini = await sessionSkills('gemini', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills') });+ const g = JSON.parse(readFileSync(gemini.env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH, 'utf8'));+ assert.deepEqual(g, { skills: { disabled: ['gem-notes', 'notes'] }, mcp: { excluded: ['gtool'] } }, 'no other skills folder for it to take');+ const own = await sessionSkills('gemini', { cwd: w.project, home: w.home, dataDir: w.dataDir, env: { GEMINI_CLI_SYSTEM_DEFAULTS_PATH: '/theirs.json' } });+ assert.equal(own.env, undefined, 'a defaults file of the person\'s own is left as it is');+ assert.equal(own.log.filtered, false);+ const copilot = await sessionSkills('copilot', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), env: { COPILOT_SKILLS_DIRS: '/mine' } });+ assert.match(copilot.env.COPILOT_SKILLS_DIRS, /^\/mine,.+[\\/]skills$/);+ assert.deepEqual(copilot.args, ['--disable-mcp-server', 'ctool']);+ assert.deepEqual(copilot.log.hidden, [], 'Copilot cannot hide a skill: it keeps the person\'s');+});++test("the person's own MCP servers, as each agent keeps them, never its maker's", () => {+ const { home, project } = world();+ assert.deepEqual(ownMcpServers('claude', { cwd: project, home }), [{ name: 'chatcut', detail: 'chatcut-mcp' }, { name: 'local', detail: 'node' }, { name: 'notes', detail: '127.0.0.1:9' }]);+ assert.deepEqual(ownMcpServers('codex', { home }), [{ name: 'my-db', detail: '127.0.0.1:8' }]);+ assert.deepEqual(ownMcpServers('opencode', { home }), [{ name: 'search', detail: 's.example.com' }]);+ assert.deepEqual(ownMcpServers('gemini', { home }), [{ name: 'gtool', detail: 'g.example.com' }]);+ assert.deepEqual(ownMcpServers('cursor', { home }), []);+ assert.deepEqual(codexServers('[mcp_servers.a]\ncommand = "x"\n[mcp_servers.a.env]\ncommand = "not this"\n').map((s) => s.config), [{ command: 'x' }], 'a server\'s own tables are not servers');+});++test('the record of skills and MCP servers let in', () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-skill-store-'));+ const store = skillStore(dir);+ assert.deepEqual(store.allowed('claude'), []);+ store.setAllowed('claude', 'research', true);+ store.setAllowed('claude', 'notes', true);+ store.setAllowed('claude', 'notes', false);+ store.setMcpAllowed('codex', 'my-db', true);+ assert.deepEqual(skillStore(dir).allowed('claude'), ['research']);+ assert.deepEqual(skillStore(dir).mcpAllowed('codex'), ['my-db']);+ assert.deepEqual(skillStore(dir).mcpAllowed('claude'), []);+});++test('two configurations as one', () => {+ assert.deepEqual(mergeConfig({ skills: { paths: ['a'] }, permission: { skill: { '*': 'deny' } } }, { experimental: { openTelemetry: true }, skills: { urls: ['u'] } }),+ { skills: { paths: ['a'], urls: ['u'] }, permission: { skill: { '*': 'deny' } }, experimental: { openTelemetry: true } });+ assert.deepEqual(mergeConfig({ developer_instructions: 'x' }, { skills: { config: [] } }), { developer_instructions: 'x', skills: { config: [] } });+});diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjsindex 89b980f..1b14191 100644--- a/apps/desktop/src/agents.mjs+++ b/apps/desktop/src/agents.mjs@@ -32,7 +32,9 @@ import { Readable, Writable } from 'node:stream';import { fileURLToPath } from 'node:url';import * as acp from '@agentclientprotocol/sdk';import { PATH_SEP, childEnvironment, lastPathSource, loginShellEnvironment, loginShellVariables, shellSubset } from './environment.mjs';-import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, consoleProgram, detectAgentInstallation, searchReport } from './agent-installation.mjs';+import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, codexVersion, consoleProgram, detectAgentInstallation, laterVersion, searchReport } from './agent-installation.mjs';+import { logSwitches } from './agent-logs.mjs';+import { mergeConfig, sessionSkills } from './agent-skills.mjs';import { nodeBinary } from './node-runtime.mjs';import { outOfBalance } from './pi-config.mjs';@@ -64,7 +66,7 @@ export const AGENTS = Object.freeze({codex: {label: 'Codex',adapter: '@agentclientprotocol/codex-acp',- env: (path) => ({ CODEX_PATH: path }),+ env: (path) => codexLaunchEnv(path),auth: ['login', 'status'],login: ['login'],systemPrompt: true,@@ -84,6 +86,14 @@ export const isAgentId = (id) => typeof id === 'string' && Object.hasOwn(AGENTS,export const HARNESS_AGENTS = Object.freeze(['byok']);export const isChatAgent = (id) => isAgentId(id) || HARNESS_AGENTS.includes(id);+/** How the person points at things in Studio, and how the agent points back: told to every agent, the app's own too. */+export const STUDIO_REFERENCES = `When the person mentions something in Studio, they may name a clip, a page or a moment (as seconds); find it in+film.html and the project's files.++In your replies you can point at things in Studio for the person: [[clip:ID]] (a clip, by its id in film.html),+[[t:SECONDS]] (a moment), [[range:START-END]] (a stretch, in seconds), [[track:N]] (a track, 0 is the first) and+[[file:PATH]] (a file of the project). They show as links that open it in Studio.`;+/** What the agent is told about where it is, on top of its own instructions. */export const INSTRUCTIONS = `You are working inside OpenFilm, a desktop app for making videos. Beside this chat the person sees OpenFilm Studio,the video editor, showing the project in your working directory; it updates live as you save files.@@ -95,30 +105,19 @@ project: you never need \`openfilm open\` and never open Studio in a browser. Ruto see what you made. Render the MP4 only when the person asks for it; they can also export from Studio. Reply in thelanguage 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 in-film.html and the project's files.--In your replies you can point at things in Studio for the person: [[clip:ID]] (a clip, by its id in film.html),-[[t:SECONDS]] (a moment), [[range:START-END]] (a stretch, in seconds), [[track:N]] (a track, 0 is the first) and-[[file:PATH]] (a file of the project). They show as links that open it in Studio.`;--/**- * For the app's own agent, which has no web tools of its own: web search and web pages from a service the person- * connected (Brave Search or Tavily), like any other media (`openfilm get` lists them for an agent with OPENFILM_GET_WEB=1).- */-export const WEB_INSTRUCTIONS = `To search the web, run \`openfilm get web-search --query "…"\`; to read a page, \`openfilm get web-fetch --url …\`-(it saves the page's text in the project). Both work once the person has connected a web search service (Brave Search-or Tavily) with their own key; until then, read public pages with \`curl\`.`;+${STUDIO_REFERENCES}`;/**- * The app's own agent's whole system prompt, in place of Pi's (a coding assistant's, with Pi's own docs): who it is- * and how it works with the person (agent-prompt.md), where it is (INSTRUCTIONS, WEB_INSTRUCTIONS), and the manual- * `openfilm` prints, so it starts knowing it.+ * The app's own agent's whole system prompt, in place of Pi's (a coding assistant's, with Pi's own docs): who it is,+ * where it is and how it works with the person (agent-prompt.md: written for it, so not INSTRUCTIONS, which tell+ * another agent to go and read the manual), how the person points at Studio (STUDIO_REFERENCES), and the manual+ * `openfilm` prints, so it starts knowing it. Each thing is said once: what the manual says (`openfilm get`'s+ * services, rendering, the person's changes) and what Pi's tools say of themselves are not said again.*/export function ownAgentPrompt() {const prompt = readFileSync(new URL('./agent-prompt.md', import.meta.url), 'utf8').trim();const manual = readFileSync(join(dirname(require.resolve('openfilm/package.json')), 'MANUAL.md'), 'utf8').replaceAll('npx openfilm', 'openfilm').trim();- return `${prompt}\n\n## Where you are\n\n${INSTRUCTIONS}\n\n${WEB_INSTRUCTIONS}\n\n<manual>\n${manual}\n</manual>`;+ return `${prompt}\n\n## Pointing at Studio\n\n${STUDIO_REFERENCES}\n\n<manual>\n${manual}\n</manual>`;}/**@@ -156,6 +155,28 @@ export function setChosenPaths(paths) {}const windows = process.platform === 'win32';++/**+ * How the Codex adapter is told where Codex is. On Windows it starts it through cmd.exe, whose own messages (a program+ * not found, access refused) are in the console's code page, which the adapter reads as UTF-8: on a Chinese Windows+ * the reason came out as `������`. There Codex is started through a script that turns the console to UTF-8 first, made+ * on disk (the app's own files are in an archive cmd.exe cannot run from); Codex's own messages are UTF-8 already.+ */+export const CODEX_UTF8_CMD = '@echo off\r\nchcp 65001 >nul\r\n"%OPENFILM_CODEX%" %*\r\n';+export function codexLaunchEnv(/** @type {string} */ path, { win = windows, dir = join(tmpdir(), 'openfilm-codex') } = {}) {+ if (!win) return { CODEX_PATH: path };+ try {+ const script = join(dir, 'codex-utf8.cmd');+ if (!existsSync(script) || readFileSync(script, 'utf8') !== CODEX_UTF8_CMD) {+ mkdirSync(dir, { recursive: true });+ writeFileSync(script, CODEX_UTF8_CMD);+ }+ return { CODEX_PATH: script, OPENFILM_CODEX: path };+ } catch {+ /* no room for the script: Codex as before, its reasons maybe unreadable */+ return { CODEX_PATH: path };+ }+}/** 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;@@ -311,7 +332,7 @@ export async function agentSignedIn(id, cliPath) {/*** 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 }>}+ * @returns {Promise<{ signedIn: boolean | null, account: AgentAccount | null, problem?: string }>}*/export async function agentStatus(id, cliPath) {const spec = AGENTS[id];@@ -325,7 +346,8 @@ export async function agentStatus(id, cliPath) {/*** @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 }}+ * `problem`: why it could not say, when that is something the person can fix (its settings it cannot read).+ * @returns {{ signedIn: boolean | null, account: AgentAccount | null, problem?: string }}*/export function readAgentStatus(id, stdout, out) {if (id === 'claude') {@@ -338,6 +360,9 @@ export function readAgentStatus(id, stdout, out) {return { signedIn: true, account: { method, email: text(s.email), org: text(s.orgName), plan: text(s.subscriptionType) } };} catch { /* not JSON: read the words */ }}+ /* settings it cannot read (a value only a later version knows): it can't say, nor start a session, until fixed */+ const broken = /error loading config(?:uration)?\b[:\s]*(.*)/i.exec(out);+ if (broken) return { signedIn: null, account: null, problem: broken[0].trim().slice(0, 500) };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';@@ -485,10 +510,14 @@ export async function openAgentSignIn(id) {export async function listAgents() {/* 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?.())]);+ /* the slower search (Windows): always, as it finds Codex inside a Store app, which may be later than one on the PATH+ (resolveAgentCli takes the later); waited for, a few seconds at most, when one is not found the quick way. What it+ finds later is there on the next look */+ if (windows) {+ const slow = windowsSlowSearch();+ if (Object.keys(AGENTS).some((id) => !resolveAgentCli(id, { pathDirs }))) {+ await Promise.race([slow, new Promise((done) => setTimeout(done, 3000).unref?.())]);+ }}return Promise.all(Object.entries(AGENTS).map(async ([id, spec]) => {const cli = resolveAgentCli(id, { pathDirs });@@ -611,10 +640,31 @@ const CLIENT_INFO = { name: 'openfilm-desktop', title: 'OpenFilm', version: '0.1/** ACP's auth_required: the agent wants its own sign-in first. */const AUTH_REQUIRED = -32000;-/** A session refused for the agent's sign-in, said so (`code: 'sign-in'`); any other error as it was. */-function signInError(label, e) {- if (e?.code !== AUTH_REQUIRED) return e;- return Object.assign(new Error(`${label} is not signed in. Sign in under Settings → Agents.`), { code: 'sign-in' });+/** The oldest Codex the chat was tried with: an older one may have an app server the adapter can't talk to. */+export const CODEX_TESTED = '0.132.0';++/**+ * A Codex that did not start, older than the ones tried: its reason, and that updating it is the likely fix (an old+ * one's app server goes away as the session opens, "connection got disposed", and says nothing more).+ * @param {string} agent @param {string | undefined} path @param {any} e @param {(file: string) => string | null} [versionOf]+ */+export function codexTooOld(agent, path, e, versionOf = codexVersion) {+ if (agent !== 'codex' || !path || e?.code === 'sign-in' || e?.code === 'not-installed') return e;+ const version = versionOf(path);+ if (!version || !laterVersion(CODEX_TESTED, version)) return e;+ const why = e instanceof Error ? e.message : String(e);+ return Object.assign(new Error(`Codex ${version} is older than OpenFilm needs (${CODEX_TESTED} or later): update Codex, then try again. ${why}`.trim()), { code: 'outdated' });+}++/**+ * A session refused for the agent's sign-in, said so (`code: 'sign-in'`); any other error with its reason: an error+ * the agent sends as "Internal error" carries the reason in its `data` (Codex's settings it cannot read, for one).+ */+export function signInError(label, e) {+ if (e?.code === AUTH_REQUIRED) return Object.assign(new Error(`${label} is not signed in. Sign in under Settings → Agents.`), { code: 'sign-in' });+ const data = e?.data;+ const why = typeof data === 'string' ? data : [data?.message, data?.details].find((v) => typeof v === 'string') ?? '';+ return why.trim() ? Object.assign(new Error(why.trim()), { code: e.code }) : e;}/** The answer that lets it go ahead (for good, where it offers that), or null when none does. */@@ -645,13 +695,22 @@ export function legacyOptions(session) {*/export class AgentSession {/**- * `harness` (for 'byok'): agent-roster.mjs's `harness(id)`, Pi's folder, its service and its model.+ * `harness` (for 'byok'): agent-roster.mjs's `harness(id)`, Pi's folder, the person's models (each its own service)+ * and the one it starts on.* @param {{ agent: string, cwd: string, resume?: string | null, binDir?: string | null, fallbackDir?: string | null,* harness?: any,- * env?: Record<string, string>,+ * env?: Record<string, string>, logDir?: string | null,+ * skills?: { dataDir: string, mine?: string, allowed?: string[], mcpAllowed?: string[] } | null,* onUpdate?: (update: any) => void, onPermission?: (params: any) => Promise<string | null>,* onQuestion?: (ask: { message: string, toolCallId: string | null, questions: any[] }) => Promise<Record<string, { label?: string, text?: string }> | null>,- * onExit?: (info: { code: number | null, stderr: string }) => void }} opts+ * onExit?: (info: { code: number | null, stderr: string }) => void,+ * onSend?: (sent: { prompt: any[], _meta?: any }) => void }} opts+ * `onSend` hears each message as it goes to the agent, whole (the app's words before the first one's, for an agent+ * told them there); `opened`, once started, says what it was started and opened with.+ * `skills`: the session has its maker's skills and MCP servers, OpenFilm's skills, and of the person's own only those+ * let in (`allowed`, `mcpAllowed`), each agent told by its own switch (agent-skills.mjs); `opened.skills` says how.+ * `logDir` (Developer mode): an agent whose own record lacks what its model got is started with its own logging+ * switch, writing under this folder (agent-logs.mjs); `opened.log` says where.*/constructor(opts) {if (!isChatAgent(opts.agent)) throw new Error(`Unknown agent: ${String(opts.agent)}`);@@ -672,10 +731,19 @@ export class AgentSession {* `openfilm` first on its PATH; the app's ffmpeg (`fallbackDir`) last, for a computer that has none of its own.*/async start() {+ try {+ return await this.open();+ } catch (e) {+ throw codexTooOld(this.opts.agent, this.cli?.path, e);+ }+ }++ async open() {const shell = agentShell(this.opts.agent, 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 computer.`), { code: 'not-installed' });+ this.cli = cli;const node = nodeRuntime();const path = [this.opts.binDir, shell.PATH, this.opts.fallbackDir].filter(Boolean).join(PATH_SEP);const instructions = INSTRUCTIONS;@@ -684,15 +752,27 @@ export class AgentSession {const own = !harness ? {} : {...harness.env,OPENFILM_GET_WEB: '1',- OPENFILM_PI: JSON.stringify({ agentDir: harness.home, provider: harness.provider, model: harness.model, models: harness.models ?? [harness.model], efforts: harness.efforts ?? {}, systemPrompt: ownAgentPrompt() }),};+ /* its skills and MCP servers: its maker's, OpenFilm's skills, and the person's own only those let in (agent-skills.mjs) */+ const skills = this.opts.skills+ ? await sessionSkills(this.opts.agent, { cwd: this.opts.cwd, env: shell, ...this.opts.skills }).catch(() => null) : null;+ if (harness) own.OPENFILM_PI = JSON.stringify({ agentDir: harness.home, models: harness.models, model: harness.model, systemPrompt: ownAgentPrompt(), skills: skills?.piSkills ?? null });+ /* Developer mode: the agent's own logging switch, so the turn log has what its model got; none when the person+ set its telemetry themselves (agent-logs.mjs) */+ this.logging = this.opts.logDir && cli && !this.spec.adapter+ ? await logSwitches(this.opts.agent, { base: this.opts.logDir, shell, cwd: this.opts.cwd }).catch(() => null) : null;/* an agent that speaks ACP itself: its own program, started as the registry starts it */- 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 native = cli && !this.spec.adapter ? starting(cli.path, [...this.spec.args, ...(this.logging?.args ?? []), ...(skills?.args ?? [])]) : null;+ const extra = { ...this.opts.env, ...(native ? native.env : node.env), ...(cli && this.spec.env ? this.spec.env(cli.path) : {}), ...own, ...skills?.env, ...this.logging?.env };+ /* OpenCode's inline configuration carries both its skills and, in Developer mode, its logging */+ if (skills?.env?.OPENCODE_CONFIG_CONTENT && this.logging?.env?.OPENCODE_CONFIG_CONTENT) {+ extra.OPENCODE_CONFIG_CONTENT = JSON.stringify(mergeConfig(JSON.parse(skills.env.OPENCODE_CONFIG_CONTENT), JSON.parse(this.logging.env.OPENCODE_CONFIG_CONTENT)));+ }+ const env = childEnvironment({ shell: { ...shell, PATH: path }, extra });const claude = this.spec.adapter === AGENTS.claude.adapter;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 });+ env.CODEX_CONFIG = JSON.stringify(mergeConfig({ developer_instructions: theirs ? `${theirs}\n\n${instructions}` : instructions }, skills?.codexConfig ?? {}));}/* the others have no place for it: the session's first message carries it */this.instructions = harness || this.spec.systemPrompt ? null : instructions;@@ -727,12 +807,13 @@ export class AgentSession {protocolVersion: acp.PROTOCOL_VERSION,clientCapabilities: CLIENT_CAPABILITIES,clientInfo: CLIENT_INFO,- });+ }).catch((e) => { throw signInError(this.spec.label, e); });const params = {cwd: this.opts.cwd,mcpServers: [],- ...(claude ? { _meta: { systemPrompt: { append: instructions } } } : {}),+ ...(skills?.additionalDirectories ? { additionalDirectories: skills.additionalDirectories } : {}),+ ...(claude ? { _meta: { systemPrompt: { append: instructions }, ...(skills?.claude ? { claudeCode: { options: skills.claude } } : {}) } } : {}),};/* the program's own sign-in, taken up (Cursor asks for this before any session) */if (this.spec.authenticate && (init.authMethods ?? []).some((m) => m.id === this.spec.authenticate)) {@@ -767,6 +848,25 @@ export class AgentSession {/* a message sent while it works joins the turn it is in (steer), as in its own chat */steering: init._meta?.steering?.supported === true,};+ this.noteModel(this.info.configOptions);+ /* what the agent was started and opened with, for the turn log: every word the app adds to its own, and the+ variables the app set (a key's value never: it reads "(hidden)") */+ const secret = new Set(Object.keys(harness?.env ?? {}));+ this.opened = {+ program: harness ? 'pi' : cli.path,+ /* the command line the agent's process was started with: its own program, or the app's Node running its adapter (or Pi) */+ command: native ? [native.cmd, ...native.args] : [node.command, ...(node.env.ELECTRON_RUN_AS_NODE ? [AS_NODE] : []), script],+ adapter: this.spec.adapter ?? null,+ env: Object.fromEntries(Object.entries(extra).map(([k, v]) => [k, secret.has(k) || /KEY|TOKEN|SECRET|PASSWORD/i.test(k) ? '(hidden)' : k === 'OPENFILM_PI' ? JSON.parse(v) : v])),+ ...(env.CODEX_CONFIG ? { codexConfig: JSON.parse(env.CODEX_CONFIG) } : {}),+ path: { first: this.opts.binDir ?? null, last: this.opts.fallbackDir ?? null },+ fromShell: this.spec.fromShell ? Object.keys(shell).sort() : 'all',+ initialize: { request: { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: CLIENT_CAPABILITIES, clientInfo: CLIENT_INFO }, response: init },+ session: { method: !resumed ? 'session/new' : caps.sessionCapabilities?.resume ? 'session/resume' : 'session/load', params: { ...params, ...(resumed ? { sessionId: resume } : {}) } },+ firstMessage: this.instructions,+ log: this.logging?.log ?? null,+ skills: skills?.log ?? null,+ };return this.info;}@@ -779,10 +879,13 @@ export class AgentSession {const meta = this.opts.harness && turnId ? { _meta: { openfilm: { turnId, cwd: this.opts.cwd } } } : {};const told = this.instructions ? [{ type: 'text', text: this.instructions }] : [];this.instructions = null;+ /* the message exactly as the agent gets it, for the turn log */+ this.opts.onSend?.({ prompt: [...told, ...blocks], ...meta });const r = await this.conn.agent.request(acp.methods.agent.session.prompt, { sessionId: this.sessionId, prompt: [...told, ...blocks], ...meta }).catch((e) => {/* the app's own agent: a service with no balance left is said the same for every service, with its page */- const broke = this.opts.harness ? outOfBalance(this.opts.harness.provider, e) : null;+ const own = this.opts.harness?.models?.find((m) => m.id === this.modelNow) ?? this.opts.harness?.models?.[0];+ const broke = own ? outOfBalance({ id: own.name, baseUrl: own.baseUrl }, e) : null;if (broke) throw broke;if (!isAgentId(this.opts.agent)) throw e;const said = signInError(this.spec.label, e);@@ -812,7 +915,15 @@ export class AgentSession {async setConfigOption(configId, value) {if (this.legacy && configId === 'mode') return this.setMode(value);if (this.legacy && configId === 'model') return this.conn.agent.request('session/set_model', { sessionId: this.sessionId, modelId: value });- return this.conn.agent.request(acp.methods.agent.session.setConfigOption, { sessionId: this.sessionId, configId, value });+ const r = await this.conn.agent.request(acp.methods.agent.session.setConfigOption, { sessionId: this.sessionId, configId, value });+ this.noteModel(r?.configOptions);+ return r;+ }++ /** The model the session is on (its `model` option's value): the app's own agent names the service a failure was on by it. */+ noteModel(configOptions) {+ const model = (configOptions ?? []).find((o) => o?.id === 'model');+ if (model) this.modelNow = model.currentValue;}async setMode(modeId) {@@ -822,5 +933,6 @@ export class AgentSession {close() {try { this.conn?.close(); } catch { /* gone already */ }if (this.child && this.child.exitCode === null) this.child.kill('SIGTERM');+ this.logging?.close();}}diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjsindex 2cde62c..c35cfb9 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 { CLIENT_CAPABILITIES, agentShell, allowOption, codexDeveloperInstructions, legacyOptions, powerShellScript, readAgentStatus } from './agents.mjs';+import { CLIENT_CAPABILITIES, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, legacyOptions, powerShellScript, readAgentStatus, signInError, codexTooOld } 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 = [@@ -37,6 +37,26 @@ test('whose sign-in it is, as each program says it, never a key', () => {assert.deepEqual(readAgentStatus('codex', 'Not logged in\n', 'Not logged in\n'), { signedIn: false, account: null });});+test('settings Codex cannot read: it cannot say whether it is signed in, and says why', () => {+ const out = '\nError loading configuration: ~/.codex/config.toml:2:16: unknown variant `full`, expected one of `read-only`, `workspace-write`, `danger-full-access`\n';+ assert.deepEqual(readAgentStatus('codex', '', out), {+ signedIn: null, account: null,+ problem: 'Error loading configuration: ~/.codex/config.toml:2:16: unknown variant `full`, expected one of `read-only`, `workspace-write`, `danger-full-access`',+ });+});++test('an error the agent sends as "Internal error" carries its reason; a sign-in refused is said so', () => {+ const why = 'failed to load configuration: config.toml:1:26: unknown variant `ultra`';+ const e = signInError('Codex', Object.assign(new Error('Internal error'), { code: -32603, data: `${why}\n` }));+ assert.equal(e.message, why);+ assert.equal(e.code, -32603);+ assert.equal(signInError('Codex', Object.assign(new Error('Internal error'), { code: -32603, data: { message: why } })).message, why);+ assert.equal(signInError('Codex', Object.assign(new Error('Internal error'), { code: -32603, data: { details: 'connection got disposed' } })).message, 'connection got disposed');+ const plain = new Error('Codex process has exited with code 1');+ assert.equal(signInError('Codex', plain), plain);+ assert.equal(signInError('Codex', Object.assign(new Error('Authentication required'), { code: -32000 })).code, 'sign-in');+});+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');@@ -83,3 +103,36 @@ test('a Windows sign-in is a PowerShell script: each path whole however it is spassert.equal(lines[1], "& 'C:\\Program Files\\OpenFilm\\OpenFilm.exe' 'C:\\Program Files\\OpenFilm\\app.asar\\src\\as-node.mjs' "+ "'D:\\用户\\it''s\\index.js' '--cli' 'auth' 'login' '--claudeai'");});++test('on Windows, Codex is started through a script that turns the console to UTF-8, so a reason comes out readable', async () => {+ const { mkdtempSync, readFileSync, writeFileSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const exe = 'C:\\Users\\李\\AppData\\Roaming\\npm\\codex.exe';+ assert.deepEqual(codexLaunchEnv('/usr/local/bin/codex', { win: false }), { CODEX_PATH: '/usr/local/bin/codex' });+ const dir = join(mkdtempSync(join(tmpdir(), 'of-codex-')), 'launch');+ const env = codexLaunchEnv(exe, { win: true, dir });+ assert.deepEqual(env, { CODEX_PATH: join(dir, 'codex-utf8.cmd'), OPENFILM_CODEX: exe });+ assert.equal(readFileSync(env.CODEX_PATH, 'utf8'), CODEX_UTF8_CMD);+ assert.match(CODEX_UTF8_CMD, /^@echo off\r\nchcp 65001 >nul\r\n"%OPENFILM_CODEX%" %\*\r\n$/, 'UTF-8 first, then Codex with what the adapter asks (app-server, login)');+ /* a script changed since: written again */+ writeFileSync(env.CODEX_PATH, 'echo old');+ codexLaunchEnv(exe, { win: true, dir });+ assert.equal(readFileSync(env.CODEX_PATH, 'utf8'), CODEX_UTF8_CMD);+ /* nowhere to write it: Codex as before */+ const blocked = join(mkdtempSync(join(tmpdir(), 'of-codex-')), 'file');+ writeFileSync(blocked, '');+ assert.deepEqual(codexLaunchEnv(exe, { win: true, dir: join(blocked, 'launch') }), { CODEX_PATH: exe });+});++test('a Codex older than the ones tried, that did not start, is said to need an update; a later one, or a sign-in, as it was', () => {+ const failed = new Error('Pending response rejected since connection got disposed');+ const old = codexTooOld('codex', '/usr/local/bin/codex', failed, () => '0.104.0');+ assert.equal(old.code, 'outdated');+ assert.match(old.message, /^Codex 0\.104\.0 is older than OpenFilm needs \(0\.132\.0 or later\): update Codex, then try again\. Pending response/);+ assert.equal(codexTooOld('codex', '/usr/local/bin/codex', failed, () => '0.163.0'), failed);+ assert.equal(codexTooOld('codex', '/usr/local/bin/codex', failed, () => null), failed, 'a version it cannot tell');+ const signIn = Object.assign(new Error('Codex is not signed in.'), { code: 'sign-in' });+ assert.equal(codexTooOld('codex', '/usr/local/bin/codex', signIn, () => '0.104.0'), signIn);+ assert.equal(codexTooOld('claude', '/usr/local/bin/claude', failed, () => '0.104.0'), failed);+});diff --git a/apps/desktop/src/chat-ipc.mjs b/apps/desktop/src/chat-ipc.mjsindex ca820fa..be593a4 100644--- a/apps/desktop/src/chat-ipc.mjs+++ b/apps/desktop/src/chat-ipc.mjs@@ -5,6 +5,8 @@* desktop:chat:sessions { project, sessions, last }* desktop:chat:turn { project, turn, items }* desktop:chat:log { project, turnId, unless? } → { file, cut, size, callsSize, events, calls } | { same } | null+ * a turn of another agent with no model log yet (running, or from before there was one) has+ * its requests read from the agent's own record (or log) as it is now (agent-records.mjs)* 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:chat:unsaved { project, except? } → [{ turnId, events }] turns with a log and no saved record@@ -17,9 +19,42 @@*/import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join, resolve } from 'node:path';+import { RECORDED_AGENTS, agentRecordCalls, compactCalls } from './agent-records.mjs';import { chatDir, loadChat, readLog, saveRefImage, saveSessions, saveTurn, unsavedTurns } from './chat-store.mjs';+import { loginShellVariables } from './environment.mjs';import { changes, snapshot } from './file-changes.mjs';+/** a turn's requests are those its agent's record has from a moment before it began to a moment after it ended */+const RECORD_MARGIN_MS = 1000;++/**+ * A log with no model requests, of a turn of an agent whose record (or log, `opened.log`) is read: its requests from+ * there, read now. The log as it was when there is none to read.+ */+export async function withAgentRecord(found) {+ if (!found || 'same' in found || found.calls?.length) return found;+ const prompt = found.events.find((e) => e.kind === 'prompt');+ const done = [...found.events].reverse().find((e) => e.kind === 'done');+ const sessionId = prompt?.session?.sessionId;+ if (!RECORDED_AGENTS.includes(prompt?.agent) || !sessionId) return found;+ const read = agentRecordCalls({+ agent: prompt.agent, sessionId, cwd: prompt.cwd, env: await loginShellVariables({ staleOk: true }), log: prompt.opened?.log ?? null,+ from: prompt.t - RECORD_MARGIN_MS, to: done ? done.t + RECORD_MARGIN_MS : Date.now() + RECORD_MARGIN_MS,+ });+ return read?.calls.length ? { ...found, calls: compactCalls(read.calls) } : found;+}++/**+ * The app's own preferences (`<dataDir>/preferences.json`): `developer`, each turn's log shown, and agents started with+ * their logging switches (off unless turned on); `changes`, what each turn changed, under its reply (on).+ */+export function readPreferences(dataDir) {+ try {+ const raw = JSON.parse(readFileSync(join(dataDir, 'preferences.json'), 'utf8'));+ return { developer: raw.developer === true, changes: raw.changes !== false };+ } catch { return { developer: false, changes: true }; }+}+/** 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;@@ -50,9 +85,9 @@ export function registerChatIpc(ipcMain, { trusted, projects, dataDir, reveal, thandle('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, {+ handle('desktop:chat:log', async ({ project: path, turnId, unless }) => withAgentRecord(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 }) => {@@ -80,13 +115,7 @@ 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, changes: raw.changes !== false };- } catch { return { developer: false, changes: true }; }- };+ const read = () => readPreferences(dataDir);handle('desktop:prefs', async () => read());handle('desktop:prefs:set', async (next) => {const prefs = { ...read() };diff --git a/apps/desktop/src/chat-store.mjs b/apps/desktop/src/chat-store.mjsindex c629d8e..0cdd52d 100644--- a/apps/desktop/src/chat-store.mjs+++ b/apps/desktop/src/chat-store.mjs@@ -11,10 +11,12 @@* <turn>.jsonl each turn as it happened, one event a line, untouched: the prompt and its settings, every* update the agent sent (what it said and thought, each tool call with its input and output),* every question and permission and the answer, how it ended; for whoever needs every detail- * <turn>.model.jsonl each request the app's own agent made to its model in that turn (pi-agent.mjs): the- * whole context, as Pi sends it, and the answer. A request carries the whole conversation, so a+ * <turn>.model.jsonl each request the agent made to its model in that turn, and the answer: the app's own+ * agent's as Pi sends it (pi-agent.mjs); Claude Code's and Codex's read from their own records+ * once the turn ends (agent-records.mjs). A request carries the whole conversation, so a* line keeps only what is new: `prefix`, how many of the last request's messages come first,* then its own; `systemPrompt` and `tools` only when they changed+ * images/<sha1>.<ext> each picture a message carried to its agent, by its content (the log names the file)** the pictures a message's references point at, `.film/refs/`:* <turn>-<n>.jpg the picture of the message's reference [n] (a frame, or the part of it pointed at), for its@@ -23,6 +25,7 @@* `.film/` is Studio's own (its projects.mjs says what else is there): a film never reads it, and nothing in it is* served. Reads no Electron module, so `node --test` can use it.*/+import { createHash } from 'node:crypto';import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';import { join } from 'node:path';@@ -149,6 +152,39 @@ export function unsavedTurns(project, { except = [] } = {}) {return out;}+const IMAGE_EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif' };++/**+ * Keep a picture a message carried (base64) in the logs, named by its content, so a turn's log can say which picture+ * went without carrying its bytes; → its path in the project (`.film/logs/images/<sha1>.<ext>`), or null.+ */+export function saveLogImage(project, data, mimeType) {+ try {+ const bytes = Buffer.from(String(data ?? ''), 'base64');+ if (!bytes.length) return null;+ const name = `${createHash('sha1').update(bytes).digest('hex')}.${IMAGE_EXT[mimeType] ?? 'bin'}`;+ const dir = join(logsDir(project), 'images');+ mkdirSync(dir, { recursive: true });+ if (!existsSync(join(dir, name))) writeAtomic(join(dir, name), bytes);+ return `.film/logs/images/${name}`;+ } catch { return null; }+}++/** A message's blocks as the log keeps them: each picture's bytes kept apart (saveLogImage), the rest as it went. */+export function loggedBlocks(project, blocks) {+ return (Array.isArray(blocks) ? blocks : []).map((b) => (b?.type === 'image' && typeof b.data === 'string'+ ? { type: 'image', mimeType: b.mimeType, bytes: Buffer.byteLength(b.data, 'base64'), file: saveLogImage(project, b.data, b.mimeType) }+ : b));+}++/** Write a turn's model requests whole (lines as agent-records.mjs compactCalls makes them), in place of any before. */+export function writeModelLog(project, turnId, lines) {+ if (typeof turnId !== 'string' || !ID.test(turnId)) return;+ const dir = logsDir(project);+ mkdirSync(dir, { recursive: true });+ writeAtomic(join(dir, `${fileOf(turnId)}.model.jsonl`), lines.map((line) => `${JSON.stringify(line)}\n`).join(''));+}+/*** A turn's log, written as it happens: `write(kind, fields)` adds a line `{ t, kind, …fields }`, `end()` closes it.* Never throws: a log that cannot be written does not stop the turn. `part` '.model': its model requests' log.diff --git a/apps/desktop/src/environment.mjs b/apps/desktop/src/environment.mjsindex 15fedff..1074c39 100644--- a/apps/desktop/src/environment.mjs+++ b/apps/desktop/src/environment.mjs@@ -249,7 +249,7 @@ export async function loginShellEnvironment(options = {}) {}/** What scripts/start.mjs passes on to Electron besides the OS identity: this app's own switches. */-export const LAUNCHER_FLAGS = ['OPENFILM_DESKTOP_FLAVOR', 'OPENFILM_DESKTOP_CAPTURE', 'ELECTRON_ENABLE_LOGGING', 'ELECTRON_ENABLE_STACK_DUMPING'];+export const LAUNCHER_FLAGS = ['OPENFILM_DESKTOP_FLAVOR', 'OPENFILM_DESKTOP_CAPTURE', 'OPENFILM_EXAMPLES_INDEX', 'ELECTRON_ENABLE_LOGGING', 'ELECTRON_ENABLE_STACK_DUMPING'];/** Electron's environment when run from source: the OS identity, the login shell's PATH, LAUNCHER_FLAGS. */export function launcherEnvironment(source, path) {diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjsindex 82ef3c3..c2f4797 100644--- a/apps/desktop/src/local-agents-ipc.mjs+++ b/apps/desktop/src/local-agents-ipc.mjs@@ -38,12 +38,20 @@* 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.+ * the prompt and the session it ran in (what the agent was started and opened with, `opened`), each message exactly+ * as the agent got it (`sent`: the app's words before the first one's too; pictures kept apart, by file), every event+ * above, each answer the page gave, how it ended. Once a turn ends, the requests the agent made to its model are read+ * from its own record (agent-records.mjs), or from the log it was started with in Developer mode (agent-logs.mjs),+ * into `.film/logs/<turn>.model.jsonl`, as the app's own agent writes its own.*/import { randomUUID } from 'node:crypto';import { homedir } from 'node:os';+import { LOG_SETTLE_MS } from './agent-logs.mjs';+import { RECORDED_AGENTS, agentRecordCalls, compactCalls } from './agent-records.mjs';+import { skillStore } from './agent-skills.mjs';import { AgentSession, HARNESS_AGENTS, isAgentId, isChatAgent, listAgents, openAgentSignIn } from './agents.mjs';-import { openLog } from './chat-store.mjs';+import { loggedBlocks, openLog, writeModelLog } from './chat-store.mjs';+import { loginShellVariables } from './environment.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 */@@ -53,11 +61,32 @@ 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;+/** how long after its turn a session whose skills changed closes: the page has settled the turn by then */+const STALE_CLOSE_MS = 3000;/** 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;const IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);+/** how long after a turn the agent's own record is read: its last lines may still be on their way to the file */+const RECORD_SETTLE_MS = 800;++/**+ * The agent's requests to its model from `from` to `to` (ms), read from its own record (or `agentLog`, the log it was+ * started with) into the turn's model log. Never throws: a record that cannot be read leaves the turn without one.+ */+export async function keepAgentRecord({ agent, sessionId, cwd, turnId, from, to, agentLog = null, log = () => {}, settleMs = LOG_SETTLE_MS[agent] ?? RECORD_SETTLE_MS }) {+ if (!RECORDED_AGENTS.includes(agent) || !sessionId || !turnId) return;+ try {+ await new Promise((done) => setTimeout(done, settleMs));+ const env = await loginShellVariables({ staleOk: true });+ const found = agentRecordCalls({ agent, sessionId, cwd, from, to, env, log: agentLog });+ if (found?.calls.length) writeModelLog(cwd, turnId, compactCalls(found.calls));+ } catch (e) {+ log(`agent record ${turnId}: ${e instanceof Error ? e.message : String(e)}\n`);+ }+}+/** The page's pictures as ACP image blocks; anything not one is left out. */function imageBlocks(images) {if (!Array.isArray(images)) return [];@@ -71,17 +100,27 @@ function imageBlocks(images) {* @param {import('electron').IpcMain} ipcMain* `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.+ * `onWorking` hears the folders agents are working in (a turn running there) each time they change; `onAsking` the+ * folders where an agent waits for the person's answer.+ * `logDir()`, as each session starts: the folder for the logs an agent is started with (Developer mode on), or null.+ * `skills`: where the app keeps its record of skills (`dataDir`) and the person's own skills (`mine`): each session has its maker's skills and MCP servers, OpenFilm's skills, and of the person's own those let+ * in (agent-skills.mjs).* @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+ * harness?: (id: string) => Promise<any>, onWorking?: (folders: string[]) => void, onAsking?: (folders: string[]) => void, logDir?: () => string | null,+ * skills?: { dataDir: string, mine: string } | null }} opts*/-export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbackDir = null, env = {}, harness = async () => null, log = () => {}, onWorking = () => {} }) {+export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbackDir = null, env = {}, harness = async () => null, log = () => {}, onWorking = () => {}, onAsking = () => {}, logDir = () => null, skills = null }) {const harnessFor = async (agent) => (HARNESS_AGENTS.includes(agent) ? harness(agent) : undefined);+ const skillRecord = skills ? skillStore(skills.dataDir) : null;+ /** a session's skills and MCP servers: OpenFilm's, and of the person's own those let in (agent-skills.mjs) */+ const skillsFor = (agent) => (skills && skillRecord ? { ...skills, allowed: skillRecord.allowed(agent), mcpAllowed: skillRecord.mcpAllowed(agent) } : null);/** @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();let activePrompts = 0;/** the folders a turn is running in now: what a project cannot be deleted from under */const working = () => [...new Set([...sessions.values()].filter((entry) => entry.running > 0).map((entry) => entry.cwd))];+ /** the folders where an agent waits for the person's answer (a permission, a question): told on each change */+ const tellAsking = () => onAsking([...new Set([...sessions.values()].filter((entry) => entry.pending.size > 0).map((entry) => entry.cwd))]);const handle = (channel, fn) => ipcMain.handle(channel, (event, opts) => {if (!trusted(event)) throw new Error('not the chat');return fn(event, opts);@@ -178,19 +217,27 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacbinDir,fallbackDir,env,+ logDir: logDir(),+ skills: skillsFor(agent),harness: await harnessFor(agent),onUpdate: (update) => send(entry, key, { kind: 'update', update }),onPermission: (params) => new Promise((resolve) => {const requestId = randomUUID();- pending.set(requestId, (optionId) => { pending.delete(requestId); resolve(optionId); });+ pending.set(requestId, (optionId) => { pending.delete(requestId); tellAsking(); resolve(optionId); });send(entry, key, { kind: 'permission', requestId, params });+ tellAsking();}),onQuestion: (ask) => new Promise((resolve) => {const requestId = randomUUID();- pending.set(requestId, (answers) => { pending.delete(requestId); resolve(answers); });+ pending.set(requestId, (answers) => { pending.delete(requestId); tellAsking(); resolve(answers); });send(entry, key, { kind: 'question', requestId, ...ask });+ tellAsking();}),onExit: (info) => { send(entry, key, { kind: 'exit', ...info }); sessions.delete(key); if (entry.running > 0) onWorking(working()); },+ onSend: (sent) => {+ const file = entry.turn && !entry.turn.done ? entry.turn.file : entry.adopted;+ file?.write('sent', { ...sent, prompt: loggedBlocks(cwd, sent.prompt) });+ },});sessions.set(key, entry);event.sender.once('destroyed', () => close(key));@@ -216,8 +263,9 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacentry.between = [];if (turn) {entry.turn = turn;- file.write('prompt', { agent: entry.agent, cwd: entry.cwd, session: entry.info ?? null, meta, text, images: images.length });+ file.write('prompt', { agent: entry.agent, cwd: entry.cwd, session: entry.info ?? null, opened: entry.session.opened ?? null, meta, text, images: images.length });}+ const from = Date.now();activePrompts++;entry.running = (entry.running ?? 0) + 1;onWorking(working());@@ -238,6 +286,10 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacturn.file.write('done', result.ok ? result : { ...result, stderr: String(entry.session?.stderr ?? '').slice(-8000) });turn.file.end();turn.done = result;+ entry.turnEnded = Date.now();+ /* its skills changed while it worked: closed now its turn is over (refreshSkills) */+ if (entry.stale) setTimeout(() => { if (sessions.get(key) === entry && !(entry.running > 0)) close(key); }, STALE_CLOSE_MS);+ void keepAgentRecord({ agent: entry.agent, sessionId: entry.info?.sessionId, cwd: entry.cwd, turnId: meta.turnId, from, to: entry.turnEnded, agentLog: entry.session.opened?.log, log });/* the page that asked may be gone (reloaded): say it on the channel too */if (!entry.sender.isDestroyed()) entry.sender.send('desktop:local-agents:event', { key, kind: 'done', turnId: meta.turnId, ...result });}@@ -266,7 +318,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacif (!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 });+ noted(opts, 'steer', { text, images: images.length, prompt: loggedBlocks(entry.cwd, [{ type: 'text', text }, ...images]) });const outcome = await entry.session.steer([{ type: 'text', text }, ...images]);noted(opts, 'steer-answer', { outcome });return { ok: outcome === 'injected', outcome };@@ -275,14 +327,17 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbachandle('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();+ if (entry.adopted) {+ entry.adopted.write('done', { ok: true, unprompted: true });+ entry.adopted.end();+ void keepAgentRecord({ agent: entry.agent, sessionId: entry.info?.sessionId, cwd: entry.cwd, turnId: entry.adopted.turnId, from: entry.adopted.from, to: Date.now(), agentLog: entry.session?.opened?.log, log });+ }entry.adopted = null;if (typeof opts?.turnId === 'string') {- entry.adopted = openLog(entry.cwd, opts.turnId, (e) => log(`turn log ${opts.turnId}: ${e.message}\n`));+ entry.adopted = Object.assign(openLog(entry.cwd, opts.turnId, (e) => log(`turn log ${opts.turnId}: ${e.message}\n`)), { turnId: opts.turnId, from: entry.turnEnded ?? Date.now() });/* `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: '' });+ entry.adopted.write('prompt', { agent: entry.agent, cwd: entry.cwd, session: entry.info ?? null, opened: entry.session?.opened ?? null, meta, unprompted: true, text: '' });for (const { kind, ...fields } of entry.between ?? []) entry.adopted.write(kind, fields);}entry.between = [];@@ -340,5 +395,15 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbaccloseAll: () => [...sessions.keys()].forEach(close),/** an agent disconnected in Settings: its sessions close */closeAgent: (agent) => { for (const [key, entry] of [...sessions]) if (entry.agent === agent) close(key); },+ /**+ * The skills or MCP servers let in changed for an agent: its sessions close (one at work once its turn ends), and the next message+ * takes each conversation up again with them.+ */+ refreshSkills: (agent) => {+ for (const [key, entry] of [...sessions]) {+ if (entry.agent !== agent) continue;+ if (entry.running > 0) entry.stale = true; else close(key);+ }+ },};}diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjsindex 07d213a..91402e3 100644--- a/apps/desktop/src/main.mjs+++ b/apps/desktop/src/main.mjs@@ -1,5 +1,7 @@/**- * OpenFilm for desktop: one window, Studio on the left and a chat on the right, one page.+ * OpenFilm for desktop: one window of tabs, a project in each, Studio on the left and a chat on the right, one page+ * per tab (tabs.mjs). A project is picked in Studio's projects window (the tabs' `+`), and its tab opens; with no tab+ * open, the window's page is the projects (HOME).** Studio is the open-source one (the `openfilm` package), run in a utility process (studio.mjs). It serves the* window's page: Studio's editor, built together with the chat beside it (shell/), on Studio's own origin, so the@@ -9,7 +11,7 @@*/import { BaseWindow, Menu, WebContentsView, app, dialog, ipcMain, nativeTheme, safeStorage, screen, shell } from 'electron';import { appendFileSync, createReadStream, existsSync, mkdirSync, statSync } from 'node:fs';-import { basename, join } from 'node:path';+import { basename, dirname, join } from 'node:path';import { Readable } from 'node:stream';import { fileURLToPath } from 'node:url';import { FLAVOR, IDENTITY, PRODUCT_NAME } from './flavor.mjs';@@ -19,7 +21,8 @@ import { startWindowStudio } from './studio.mjs';import { CHAT_MIN, STUDIO_MIN, WINDOW_MIN, placeOnDisplays, readWindowState, writeWindowState } from './window-state.mjs';import { applicationMenu } from './menu.mjs';import { registerLocalAgentIpc } from './local-agents-ipc.mjs';-import { registerChatIpc } from './chat-ipc.mjs';+import { readPreferences, registerChatIpc } from './chat-ipc.mjs';+import { registerSkillsIpc } from './skills-ipc.mjs';import { createRoster } from './agent-roster.mjs';import { checkAgentProgram, diagnoseAgent, listAgents, openAgentSignIn, setChosenPaths } from './agents.mjs';import { agentUsage, forgetAgentUsage } from './agent-usage.mjs';@@ -27,6 +30,7 @@ import { installOpenfilmCommand } from './openfilm-command.mjs';import { startUpdates } from './updates.mjs';import { ensureFfmpeg, ffmpegDir, ffmpegDownloadable, ffmpegIn, ffmpegOnPath } from './ffmpeg-runtime.mjs';import { PATH_SEP } from './environment.mjs';+import { createTabs } from './tabs.mjs';const here = (path) => fileURLToPath(new URL(path, import.meta.url));const mac = process.platform === 'darwin';@@ -57,8 +61,19 @@ if (!app.requestSingleInstanceLock()) {/** @type {BaseWindow | null} */let win = null;-/** @type {WebContentsView | null} */-let view = null;+/** @type {ReturnType<typeof createTabs> | null} */+let tabs = null;+/** the page of each tab that has one (a tab left behind long enough has none until it is shown again) */+/** @type {Map<string, WebContentsView>} */+const views = new Map();+/** the page in front */+const activeView = () => (tabs ? views.get(tabs.activeId() ?? HOME) ?? null : null);+/** something every page is told (the theme, an update, the agents…) */+const broadcast = (channel, value) => { for (const v of views.values()) if (!v.webContents.isDestroyed()) v.webContents.send(channel, value); };+/** the tab whose page this is, or null */+const tabOf = (contents) => { for (const [id, v] of views) if (v.webContents === contents) return id; return null; };+/** a tab behind for this long lets its page go (it comes back when shown), unless an agent works in it or it exports */+const IDLE_PAGE_MS = 5 * 60_000;/** @type {Awaited<ReturnType<typeof startWindowStudio>> | null} */let studio = null;let state = readWindowState(DATA);@@ -67,7 +82,7 @@ let theme = 'dark';let ffmpegFound = null;/** ffmpeg is being downloaded (ffmpeg-runtime.mjs): Studio's "not found" at its start is not the last word */let ffmpegFetching = false;-const tellFfmpeg = (state) => { ffmpegFound = state; view?.webContents.send('desktop:ffmpeg', state); };+const tellFfmpeg = (state) => { ffmpegFound = state; broadcast('desktop:ffmpeg', state); };/** @type {ReturnType<typeof startUpdates> | null} */let updates = null;let quitting = false;@@ -86,17 +101,17 @@ function focusWindow() {win.focus();}-/** The page fills the window. */+/** Each page fills the window (only the one in front shows). */function layout() {- if (!win || !view) return;+ if (!win) return;const { width, height } = win.getContentBounds();- view.setBounds({ x: 0, y: 0, width, height });+ for (const v of views.values()) v.setBounds({ x: 0, y: 0, width, height });}function saveState() {if (!win) return;const maximized = win.isMaximized() || win.isFullScreen();- state = { ...state, maximized, bounds: maximized ? state.bounds : win.getNormalBounds() };+ state = { ...state, maximized, bounds: maximized ? state.bounds : win.getNormalBounds(), ...(tabs ? { tabs: tabs.saved() } : {}) };try { writeWindowState(DATA, state); } catch { /* kept until next time */ }}@@ -114,8 +129,137 @@ function guard(contents, allowed) {contents.on('will-attach-webview', (event) => event.preventDefault());}-/** IPC only from the page's own main frame. */-const fromPage = (event) => Boolean(view) && event.sender === view.webContents && event.senderFrame === view.webContents.mainFrame;+/** IPC only from a tab's page, its own main frame. */+const fromPage = (event) => tabOf(event.sender) != null && event.senderFrame === event.sender.mainFrame;++/** A page for a tab: Studio's editor at its project (or its launcher), on Studio's origin. */+function makeView(tabId) {+ const v = new WebContentsView({+ webPreferences: {+ preload: here('./preload.cjs'),+ contextIsolation: true,+ sandbox: true,+ nodeIntegration: false,+ spellcheck: true,+ autoplayPolicy: 'no-user-gesture-required',+ devTools: !app.isPackaged,+ },+ });+ v.setBackgroundColor(BACKGROUND[theme]);+ views.set(tabId, v);+ win.contentView.addChildView(v);+ const { width, height } = win.getContentBounds();+ v.setBounds({ x: 0, y: 0, width, height });+ guard(v.webContents, (url) => Boolean(studio) && url.startsWith(`${studio.origin}/`));+ /* what went wrong with the page, for the log (logs/studio.log) */+ v.webContents.on('render-process-gone', (_event, details) => log(`page: renderer gone (${details.reason}, ${details.exitCode})\n`));+ v.webContents.on('did-fail-load', (_event, code, description, url, mainFrame) => { if (mainFrame) log(`page: ${description} (${code}) loading ${url.replace(/key=[^&]+/, 'key=…')}\n`); });+ v.webContents.on('unresponsive', () => log('page: not responding\n'));+ /* the page gone (a crash): it comes back where it was; the agents' turns go on in this process meanwhile */+ v.webContents.on('render-process-gone', (_event, details) => { if (details.reason !== 'clean-exit' && !quitting) setTimeout(() => { if (!v.webContents.isDestroyed()) v.webContents.reload(); }, 500); });+ return v;+}++/** The page shown when no tab is open: Studio's projects (`/` with tabs). */+const HOME = 'home';+/** Where a tab's page opens: its project (no tab: the projects). */+const pageAddress = (tab, path = null) => `${studio.origin}/open?key=${studio.key}&to=${encodeURIComponent(path ?? (tab ? `/projects/${encodeURIComponent(tab.projectId)}` : '/'))}`;++/** Every page told of the tabs as they are now; kept for next time. */+function tellTabs() {+ if (!tabs) return;+ broadcast('desktop:tabs', tabs.list());+ saveState();+}++/** Show a page: a tab's (made again when it has none), or HOME. Once a tab shows, HOME's page goes. */+function showPage(id) {+ if (!win || !studio) return;+ let v = views.get(id);+ if (!v) { v = makeView(id); void v.webContents.loadURL(pageAddress(id === HOME ? null : tabs?.get(id))); }+ for (const [other, page] of views) page.setVisible(other === id);+ v.webContents.focus();+ if (id !== HOME) dropView(HOME);+}++/** Bring a tab to the front. */+function showTab(id) {+ if (!tabs || !tabs.activate(id)) return;+ showPage(id);+ tellTabs();+}++/** A project's tab (in front if it is open already). */+function newTab(projectId) {+ if (!tabs || typeof projectId !== 'string' || !projectId) return;+ showTab(tabs.open({ projectId }).id);+}++/** Let a tab's page go: closed, or behind too long (the tab stays). */+function dropView(id) {+ const v = views.get(id);+ if (!v) return;+ views.delete(id);+ win?.contentView.removeChildView(v);+ if (!v.webContents.isDestroyed()) v.webContents.close();+}++/** Close a tab; one whose agent is still at work, only once the person says so. */+async function closeTab(id) {+ if (!tabs || !win) return;+ const tab = tabs.get(id);+ if (!tab) return;+ if (tab.working) {+ const { response } = await dialog.showMessageBox(win, {+ type: 'warning', buttons: ['Close Tab', 'Cancel'], defaultId: 1, cancelId: 1,+ message: 'An agent is still working in this project.', detail: 'Closing the tab stops it.',+ });+ if (response !== 0) return;+ }+ dropView(id);+ const next = tabs.close(id);+ if (next) showTab(next.id);+ else { showPage(HOME); tellTabs(); }+}++/**+ * Studio's "open this project" (`openfilm open`, File › Open Project…), heard by every page at once: once only. Its+ * tab comes to the front, opened if it is not.+ */+let lastOpen = { to: '', at: 0 };+function openInTabs(to) {+ if (!tabs || typeof to !== 'string') return;+ if (to === lastOpen.to && Date.now() - lastOpen.at < 2000) return;+ lastOpen = { to, at: Date.now() };+ const projectId = /^\/projects\/([\w-]+)/.exec(to)?.[1] ?? null;+ if (projectId) newTab(projectId);+}++/** The tabs open when the window opens: those left last time, else the last project's; none: the projects. */+async function openTabs() {+ const projects = (await studioApi('/api/projects').catch(() => ({ projects: [] }))).projects.filter((p) => !p.missing);+ tabs = createTabs({ saved: state.tabs?.tabs?.length ? state.tabs : null });+ /* a tab of a project no longer there is left out */+ const known = new Set(projects.map((p) => p.id));+ for (const t of tabs.list()) if (!known.has(t.projectId)) tabs.close(t.id);+ if (!tabs.list().length && !state.tabs?.tabs?.length && projects[0]) tabs.open({ projectId: projects[0].id, title: projects[0].name });+ const front = tabs.activeId();+ if (front) showTab(front);+ else { showPage(HOME); tellTabs(); }+}++/** The projects the chat's agents work in, and wait for an answer in, by Studio's ids (from their folders), on each tab. */+let projectPaths = new Map();+const agentFolders = { working: /** @type {string[]} */ ([]), asking: /** @type {string[]} */ ([]) };+async function tellTabsWorking({ working = agentFolders.working, asking = agentFolders.asking } = {}) {+ Object.assign(agentFolders, { working, asking });+ if (!tabs) return;+ if ([...working, ...asking].some((f) => !projectPaths.has(f))) {+ projectPaths = new Map((await studioApi('/api/projects').catch(() => ({ projects: [] }))).projects.map((p) => [p.path, p.id]));+ }+ const ids = (folders) => folders.map((f) => projectPaths.get(f)).filter(Boolean);+ if (tabs.setAgents(ids(agentFolders.working), ids(agentFolders.asking))) tellTabs();+}async function studioApi(path, method = 'GET', body = undefined) {const res = await fetch(`${studio.origin}${path}`, {@@ -160,13 +304,14 @@ function setTheme(next) {theme = next === 'dark' ? 'dark' : 'light';nativeTheme.themeSource = theme;win?.setBackgroundColor(BACKGROUND[theme]);- view?.setBackgroundColor(BACKGROUND[theme]);+ for (const v of views.values()) v.setBackgroundColor(BACKGROUND[theme]);if (windows) win?.setTitleBarOverlay?.(overlayColours(theme));}/** Tell Studio which folders the chat's agents are working in now. */function tellWorking(/** @type {string[]} */ folders) {studio?.child.postMessage({ type: 'working', folders });+ void tellTabsWorking({ working: folders });}async function runStudio(env) {@@ -183,7 +328,7 @@ async function runStudio(env) {},onBrowser: (message) => {if (message.type === 'ffmpeg') { if (!ffmpegFetching) tellFfmpeg(message.found); }- else view?.webContents.send('desktop:studio-browser', message);+ else broadcast('desktop:studio-browser', message);},onExit: (code) => {if (quitting) return;@@ -193,10 +338,12 @@ async function runStudio(env) {});/* a Studio started again hears where the agents are working */tellWorking(localAgents?.working() ?? []);- /* the page Studio shows at `/` is the last project; a page already open (Studio restarted) stays where it was */- const at = view.webContents.getURL();- const to = at.startsWith('http') ? new URL(at).pathname : '/';- await view.webContents.loadURL(`${studio.origin}/open?key=${studio.key}&to=${encodeURIComponent(to)}`);+ /* the first time, the tabs; a Studio started again: each page stays where it was */+ if (!tabs) { await openTabs(); return; }+ for (const [id, v] of views) {+ const at = v.webContents.getURL();+ await v.webContents.loadURL(pageAddress(tabs.get(id), at.startsWith('http') ? new URL(at).pathname : null));+ }}async function start() {@@ -209,6 +356,8 @@ async function start() {/* the app names Studio's home, which would put exports inside it (Studio's rule for a home kept apart): theDesktop, where `openfilm` puts them, unless this is a flavour with a home of its own */...(IDENTITY.studioHome || process.env.OPENFILM_EXPORTS ? {} : { OPENFILM_EXPORTS: app.getPath('desktop') }),+ /* another examples index (a file, to try one), passed through when run from source */+ ...(process.env.OPENFILM_EXAMPLES_INDEX ? { OPENFILM_EXAMPLES_INDEX: process.env.OPENFILM_EXAMPLES_INDEX } : {}),},});@@ -244,36 +393,13 @@ async function start() {});if (state.maximized) win.maximize();- view = new WebContentsView({- webPreferences: {- preload: here('./preload.cjs'),- contextIsolation: true,- sandbox: true,- nodeIntegration: false,- spellcheck: true,- autoplayPolicy: 'no-user-gesture-required',- devTools: !app.isPackaged,- },- });- view.setBackgroundColor(BACKGROUND[theme]);- win.contentView.addChildView(view);- layout();-- guard(view.webContents, (url) => Boolean(studio) && url.startsWith(`${studio.origin}/`));- /* what went wrong with the page, for the log (logs/studio.log) */- view.webContents.on('render-process-gone', (_event, details) => log(`page: renderer gone (${details.reason}, ${details.exitCode})\n`));- view.webContents.on('did-fail-load', (_event, code, description, url, mainFrame) => { if (mainFrame) log(`page: ${description} (${code}) loading ${url.replace(/key=[^&]+/, 'key=…')}\n`); });- view.webContents.on('unresponsive', () => log('page: not responding\n'));- /* the page gone (a crash): it comes back where it was; the agents' turns go on in this process meanwhile */- view.webContents.on('render-process-gone', (_event, details) => { if (details.reason !== 'clean-exit' && !quitting) setTimeout(() => view?.webContents.reload(), 500); });-win.on('resize', layout);win.on('resized', saveState);win.on('moved', saveState);- win.on('enter-full-screen', () => view?.webContents.send('desktop:full-screen', true));- win.on('leave-full-screen', () => view?.webContents.send('desktop:full-screen', false));+ win.on('enter-full-screen', () => broadcast('desktop:full-screen', true));+ win.on('leave-full-screen', () => broadcast('desktop:full-screen', false));win.on('close', saveState);- win.on('closed', () => { win = null; view = null; app.quit(); });+ win.on('closed', () => { win = null; views.clear(); app.quit(); });ipcMain.on('desktop:theme', (event, next) => { if (fromPage(event)) setTheme(next); });ipcMain.handle('desktop:hello', (event) => {@@ -293,21 +419,65 @@ async function start() {projects: async () => (await studioApi('/api/projects')).projects.filter((p) => !p.missing).map((p) => p.path),dataDir: DATA,reveal: (path) => shell.showItemInFolder(path),- tell: (channel, value) => view?.webContents.send(channel, value),+ tell: (channel, value) => broadcast(channel, value),log,});+ /* the tabs, drawn by each page in Studio's top bar: asked for, and told of every change (tellTabs) */+ const tabHandle = (channel, fn) => ipcMain.handle(channel, (event, opts) => {+ if (!fromPage(event)) throw new Error('not the window\'s page');+ return fn(tabOf(event.sender), opts ?? {});+ });+ tabHandle('desktop:tabs:list', (self) => ({ self, tabs: tabs?.list() ?? [] }));+ tabHandle('desktop:tabs:new', (_self, { projectId }) => { newTab(projectId); return { ok: true }; });+ tabHandle('desktop:tabs:show', (_self, { id }) => { showTab(String(id)); return { ok: true }; });+ tabHandle('desktop:tabs:close', (self, { id }) => { void closeTab(typeof id === 'string' ? id : self); return { ok: true }; });+ tabHandle('desktop:tabs:move', (_self, { id, index }) => { if (tabs?.move(String(id), Number(index))) tellTabs(); return { ok: true }; });+ /* what a page shows now: its project's title, an export's progress; or its project gone */+ tabHandle('desktop:tabs:report', (self, { title, exporting, gone }) => {+ if (!tabs) return { ok: false };+ /* its project deleted (in this page or another): its tab closes */+ if (gone === true) { void closeTab(self); return { ok: true }; }+ tabs.report(self, { ...(typeof title === 'string' ? { title: title.slice(0, 200) } : {}), ...(exporting !== undefined ? { exporting: typeof exporting === 'number' ? exporting : null } : {}) });+ tellTabs();+ return { ok: true };+ });+ /* Studio's "open this project", heard by each page: settled once here */+ tabHandle('desktop:tabs:open', (_self, { to }) => { openInTabs(to); return { ok: true }; });+ /* a tab left behind long enough lets its page go; it comes back when shown */+ setInterval(() => { for (const id of tabs?.idle(IDLE_PAGE_MS) ?? []) dropView(id); }, 60_000).unref?.();+/* the agents: Studio's home and library go with them, so the `openfilm` they run finds this window's Studio */+ /* the person's own skills: Skills/ beside this app's projects (~/Movies/OpenFilm/Skills), as its `openfilm` finds them */+ const mySkills = process.env.OPENFILM_SKILLS || (env.OPENFILM_LIBRARY ? join(dirname(env.OPENFILM_LIBRARY), 'Skills') : (await import('openfilm/skills')).mySkillsDir());localAgents = registerLocalAgentIpc(ipcMain, {trusted: fromPage,log,/* Studio refuses to delete a project an agent is working in */onWorking: tellWorking,+ /* a tab says when its agent waits for the person's answer */+ onAsking: (folders) => void tellTabsWorking({ asking: folders }),/* the `openfilm` command first (with the app's ffmpeg and browser in it); the app's ffmpeg last, for a computerthat 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,+ /* Developer mode: an agent whose own record lacks what its model got logs it here (agent-logs.mjs) */+ logDir: () => (readPreferences(DATA).developer ? join(DATA, 'agent-logs') : null),+ /* each session's skills: its maker's, OpenFilm's, and of the person's own those let in (agent-skills.mjs) */+ skills: { dataDir: DATA, mine: mySkills },+ });+ /* the composer's Skills button */+ registerSkillsIpc(ipcMain, {+ trusted: fromPage,+ projects: async () => (await studioApi('/api/projects')).projects.filter((p) => !p.missing).map((p) => p.path),+ dataDir: DATA,+ mine: mySkills,+ oldMine: join(env.OPENFILM_HOME, 'skills'),+ reveal: (path) => { void shell.openPath(path); },+ pickFolder: (words) => pickFolder(words),+ refreshSkills: (agent) => localAgents?.refreshSkills(agent),+ log,});/* Settings → Agents (in Studio's page) and the chat's agent menu: one roster, both told of every change */roster = createRoster({@@ -318,7 +488,7 @@ async function start() {closeSessions: (id) => { forgetAgentUsage(id); localAgents?.closeAgent(id); },seal,unseal,- onChange: (list) => view?.webContents.send('desktop:agents', list),+ onChange: (list) => broadcast('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) => {@@ -341,7 +511,8 @@ async function start() {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));+ agentHandle('desktop:agents:own-model', ({ config }) => roster.saveOwnModel(config));+ agentHandle('desktop:agents:own-model-remove', ({ id }) => { roster.removeOwnModel(String(id)); return { ok: true }; });/* a file on the disk brought into the chat goes into the project the page names, through Studio's own import (itshows in Studio's media at once, and the import is in the project's history); one without a path the page sendsitself */@@ -367,7 +538,7 @@ async function start() {if (!fromPage(event) || !rect || typeof rect !== 'object') return null;const box = { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) };if (!Object.values(box).every((n) => Number.isFinite(n)) || box.width < 2 || box.height < 2 || box.width > 8000 || box.height > 8000) return null;- const image = await view.webContents.capturePage(box).catch(() => null);+ const image = await event.sender.capturePage(box).catch(() => null);return image && !image.isEmpty() ? image.toJPEG(88).toString('base64') : null;});@@ -376,7 +547,7 @@ async function start() {dataDir: DATA,productName: PRODUCT_NAME,getWindow: () => win,- onState: (next) => view?.webContents.send('desktop:update', next),+ onState: (next) => broadcast('desktop:update', next),prepareRestart: async () => {if (localAgents?.isBusy()) return { ok: false, error: 'agent-busy' };/* Studio's quit-when-idle answers 409 while it exports; otherwise the window's Studio stays (studio-process.mjs@@ -391,7 +562,7 @@ async function start() {beforeInstall: async () => {quitting = true;localAgents?.closeAll();- view?.webContents.on('will-prevent-unload', (event) => event.preventDefault());+ for (const v of views.values()) v.webContents.on('will-prevent-unload', (event) => event.preventDefault());await studio?.quit();updates?.close();},@@ -404,10 +575,22 @@ async function start() {Menu.setApplicationMenu(applicationMenu({productName: PRODUCT_NAME,packaged: app.isPackaged,- toggleChat: () => view?.webContents.send('desktop:toggle-chat'),+ toggleChat: () => activeView()?.webContents.send('desktop:toggle-chat'),openProject: () => void openProjectFolder(),- reload: () => view?.webContents.reload(),- devTools: () => view?.webContents.toggleDevTools(),+ reload: () => activeView()?.webContents.reload(),+ devTools: () => activeView()?.webContents.toggleDevTools(),+ tabs: {+ /* the projects window, in the page in front, to pick the project a new tab shows */+ open: () => activeView()?.webContents.send('desktop:tabs:pick') ?? views.get(HOME)?.webContents.focus(),+ close: () => { if (tabs?.activeId()) void closeTab(tabs.activeId()); },+ reopen: () => { const tab = tabs?.reopen(); if (tab) showTab(tab.id); },+ step: (by) => {+ const list = tabs?.list() ?? [];+ const i = list.findIndex((t) => t.active);+ if (list.length > 1) showTab(list[(i + by + list.length) % list.length].id);+ },+ pick: (n) => { const list = tabs?.list() ?? []; const tab = n === 9 ? list.at(-1) : list[n - 1]; if (tab) showTab(tab.id); },+ },updates: updates.packaged ? {check: () => updates.manualCheck(),beta: updates.channel() === 'beta',@@ -429,7 +612,8 @@ async function start() {await runStudio(env);} catch (error) {log(`Studio did not start: ${error.stack ?? error}\n`);- void view.webContents.loadFile(here('./failed.html'), { query: { message: String(error.message ?? error) } });+ const v = makeView('failed');+ void v.webContents.loadFile(here('./failed.html'), { query: { message: String(error.message ?? error) } });}}diff --git a/apps/desktop/src/menu.mjs b/apps/desktop/src/menu.mjsindex acec9cc..bc14008 100644--- a/apps/desktop/src/menu.mjs+++ b/apps/desktop/src/menu.mjs@@ -1,4 +1,4 @@-/** The menu bar. Studio's own shortcuts live in its page; these are the window's. */+/** The menu bar. Studio's own shortcuts live in its page; these are the window's, its tabs' among them. */import { Menu } from 'electron';const mac = process.platform === 'darwin';@@ -6,11 +6,14 @@ const mac = process.platform === 'darwin';/*** `updates`: the packaged app's (updates.mjs), for "Check for Updates…" (the app menu on macOS, Help on Windows) and* "Beta Updates" (builds before they go to everyone); null from source, which has none.+ * `tabs`: a new tab (its launcher), the one in front closed, the one closed last opened again, the next or previous,+ * the nth (9: the last).* @param {{ productName: string, packaged: boolean, toggleChat: () => void, openProject: () => void, reload: () => void,* devTools: () => void,+ * tabs: { open: () => void, close: () => void, reopen: () => void, step: (by: number) => void, pick: (n: number) => void },* updates?: { check: () => Promise<void>, beta: boolean, setBeta: (on: boolean) => void } | null }} actions*/-export function applicationMenu({ productName, packaged, toggleChat, openProject, reload, devTools, updates = null }) {+export function applicationMenu({ productName, packaged, toggleChat, openProject, reload, devTools, tabs, updates = null }) {/** @type {Electron.MenuItemConstructorOptions[]} */const updateItems = updates ? [{@@ -42,7 +45,13 @@ export function applicationMenu({ productName, packaged, toggleChat, openProject}] : []),{label: 'File',- submenu: [{ label: 'Open Project…', accelerator: 'CmdOrCtrl+O', click: openProject }],+ submenu: [+ { label: 'New Tab', accelerator: 'CmdOrCtrl+T', click: () => tabs.open() },+ { label: 'Open Project…', accelerator: 'CmdOrCtrl+O', click: openProject },+ { type: 'separator' },+ { label: 'Close Tab', accelerator: 'CmdOrCtrl+W', click: () => tabs.close() },+ { label: 'Reopen Closed Tab', accelerator: 'CmdOrCtrl+Shift+T', click: () => tabs.reopen() },+ ],},{ role: 'editMenu' },{@@ -62,7 +71,19 @@ export function applicationMenu({ productName, packaged, toggleChat, openProject]),],},- { role: 'windowMenu' },+ {+ label: 'Window',+ submenu: [+ { role: 'minimize' },+ { role: 'zoom' },+ { type: 'separator' },+ { label: 'Show Next Tab', accelerator: 'Control+Tab', click: () => tabs.step(1) },+ { label: 'Show Previous Tab', accelerator: 'Control+Shift+Tab', click: () => tabs.step(-1) },+ /* ⌘1–⌘9, as in a browser: each a tab, 9 the last */+ ...Array.from({ length: 9 }, (_, i) => ({ label: `Tab ${i + 1}`, accelerator: `CmdOrCtrl+${i + 1}`, visible: false, acceleratorWorksWhenHidden: true, click: () => tabs.pick(i + 1) })),+ ...(mac ? [{ type: 'separator' }, { role: 'front' }] : []),+ ],+ },...(!mac && updateItems.length ? [{ role: 'help', submenu: updateItems }] : []),];return Menu.buildFromTemplate(template);diff --git a/apps/desktop/src/pi-agent.mjs b/apps/desktop/src/pi-agent.mjsindex 65c6bb2..866bece 100644--- a/apps/desktop/src/pi-agent.mjs+++ b/apps/desktop/src/pi-agent.mjs@@ -4,11 +4,11 @@* (agents.mjs starts it with Electron as Node).** What it runs with comes in OPENFILM_PI (JSON; pi-config.mjs): its own folder (`agentDir`: Pi's models and settings,- * never the person's ~/.pi), the service (`provider`), its models (`model` the one a session starts on; the chat- * switches between them with the session's `model` option), each model's reasoning efforts (`efforts`: the session's- * `effort` option, for a model offering more than one; `auto` sends none), and its whole system prompt (agents.mjs- * ownAgentPrompt), in place of Pi's. Of the project's instructions only its own AGENTS.md (or CLAUDE.md) is read, not- * the folders above it; no skills, no SYSTEM.md. Besides Pi's read, bash, edit and write it has `ask`: questions for+ * never the person's ~/.pi), the person's models (`models`, each its own service with its key in a variable, its name,+ * the model asked for and its reasoning efforts: pi-config.mjs OwnModel; `model` the id of the one a session starts+ * on; the chat switches between them with the session's `model` option, and a model's efforts with `effort`, for one+ * offering more than one; `auto` sends none), and its whole system prompt (agents.mjs ownAgentPrompt), in place of Pi's. Of the project's instructions only its own AGENTS.md (or CLAUDE.md) is read, not+ * the folders above it; no SYSTEM.md; of skills only OpenFilm's (`skills`: their folder and names, agent-skills.mjs). Besides Pi's read, bash, edit and write it has `ask`: questions for* the person, with options, shown in the chat as Claude Code's and Codex's are (an ACP form).** A conversation's session is kept with the project it is about (chat-store.mjs: `.film/chat/agent/`), so it goes@@ -25,34 +25,47 @@ import { Readable, Writable } from 'node:stream';import * as acp from '@agentclientprotocol/sdk';import { DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, createAgentSession } from '@earendil-works/pi-coding-agent';import { agentSessionsDir, openLog } from './chat-store.mjs';-import { THINKING, contextUsed, effortOption, modelEfforts, modelOption, modelsJson, stopReason, toolCall, toolContent } from './pi-config.mjs';+import { THINKING, contextUsed, effortOption, modelOption, modelsJson, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';/* stdout is the protocol's: anything else Pi or a library prints goes to stderr */console.log = console.info = console.warn = console.debug = (...args) => process.stderr.write(`${args.map(String).join(' ')}\n`);const config = JSON.parse(process.env.OPENFILM_PI ?? '{}');+/** OpenFilm's skills for this session (agent-skills.mjs): Pi loads these and no others */+const ownSkills = { paths: Array.isArray(config.skills?.paths) ? config.skills.paths : [], names: Array.isArray(config.skills?.names) ? config.skills.names : [] };const VERSION = '1.1.0';-const models = Array.isArray(config.models) && config.models.length ? config.models : [config.model];-const efforts = modelEfforts(config.efforts, models);+/** @type {import('./pi-config.mjs').OwnModel[]} */+const models = Array.isArray(config.models) ? config.models : [];+const byId = new Map(models.map((m) => [m.id, m]));+const startModel = byId.has(config.model) ? config.model : models[0]?.id;mkdirSync(config.agentDir, { recursive: true });const modelsPath = join(config.agentDir, 'models.json');-writeFileSync(modelsPath, JSON.stringify(modelsJson(config.provider, models, efforts), null, 2));+writeFileSync(modelsPath, JSON.stringify(modelsJson(models), null, 2));const modelRuntime = await ModelRuntime.create({ authPath: join(config.agentDir, 'auth.json'), modelsPath });-/** Each open session: Pi's, the turn being logged, and its model and effort as the chat names them. */+/** Each open session: Pi's, the turn being logged, and its model (the id) and effort as the chat names them. */const sessions = new Map();-/** Pi's model for a model and an effort: the service as itself for `auto` (no reasoning setting), else the thinking one. */+/** Pi's model for one of the person's and an effort: its service as itself for `auto` (no reasoning setting), else thinking. */function piModel(/** @type {string} */ id, /** @type {string} */ effort) {- const model = modelRuntime.getModel(effort === 'auto' ? config.provider.id : THINKING(config.provider.id), id);- if (!model) throw new Error(`No model ${id} at ${config.provider.id}.`);+ const own = byId.get(id);+ const model = own && modelRuntime.getModel(effort === 'auto' ? providerOf(id) : THINKING(providerOf(id)), own.model);+ if (!model) throw new Error(`No model ${own?.name ?? id}.`);return model;}+/** Which of the person's models Pi's model is (a conversation taken up again names its provider), and whether thinking. */+function ownOf(/** @type {any} */ piModelNow) {+ const provider = String(piModelNow?.provider ?? '');+ const thinking = models.some((m) => provider === THINKING(providerOf(m.id)));+ const own = models.find((m) => provider === providerOf(m.id) || provider === THINKING(providerOf(m.id)));+ return { id: own?.id ?? null, thinking };+}+/** The session's options: the model, and its effort when it offers more than one. */const optionsOf = (/** @type {{ model: string, effort: string }} */ entry) =>- [modelOption(models, entry.model), effortOption(efforts[entry.model]?.levels ?? ['auto'], entry.effort)].filter(Boolean);+ [modelOption(models, entry.model), effortOption(byId.get(entry.model)?.levels ?? ['auto'], entry.effort)].filter(Boolean);/** Put a session on a model and an effort. */async function use(/** @type {any} */ entry, /** @type {string} */ model, /** @type {string} */ effort) {@@ -99,7 +112,10 @@ async function open(client, cwd, resumeId) {/* the session's id, once it has one: the questions `ask` puts are the session's */let sessionId = null;const resourceLoader = new DefaultResourceLoader({- cwd, agentDir: config.agentDir, settingsManager, noExtensions: true, noPromptTemplates: true, noThemes: true, noSkills: true,+ cwd, agentDir: config.agentDir, settingsManager, noExtensions: true, noPromptTemplates: true, noThemes: true,+ /* OpenFilm's skills, and no other Pi would find (in the project, or its own folders) */+ noSkills: !ownSkills.names.length, additionalSkillPaths: ownSkills.paths,+ skillsOverride: (base) => ({ ...base, skills: base.skills.filter((skill) => ownSkills.names.includes(skill.name)) }),systemPromptOverride: () => config.systemPrompt,appendSystemPromptOverride: () => [],agentsFilesOverride: ({ agentsFiles }) => ({ agentsFiles: agentsFiles.filter((f) => dirname(resolve(f.path)) === resolve(cwd)) }),@@ -111,18 +127,20 @@ async function open(client, cwd, resumeId) {],});await resourceLoader.reload();- const startEffort = efforts[config.model]?.effort ?? 'auto';+ const startEffort = byId.get(startModel)?.effort ?? 'auto';const { session } = await createAgentSession({- cwd, agentDir: config.agentDir, modelRuntime, model: piModel(config.model, startEffort),+ cwd, agentDir: config.agentDir, modelRuntime, model: piModel(startModel, startEffort),...(startEffort !== 'auto' ? { thinkingLevel: startEffort } : {}),resourceLoader, sessionManager, settingsManager, tools: ['read', 'bash', 'edit', 'write', 'ask'],});/* what it runs on now, as the chat names it (a conversation taken up again may be on another model and effort) */- const onModel = models.includes(session.model?.id) ? session.model.id : config.model;- const levels = efforts[onModel]?.levels ?? ['auto'];- const thinking = session.model?.provider === THINKING(config.provider.id);+ const now = ownOf(session.model);+ const onModel = now.id ?? startModel;+ const levels = byId.get(onModel)?.levels ?? ['auto'];const entry = { session, log: null, model: onModel,- effort: thinking && levels.includes(session.thinkingLevel) ? session.thinkingLevel : !thinking && levels.includes('auto') ? 'auto' : efforts[onModel]?.effort ?? 'auto' };+ effort: now.thinking && levels.includes(session.thinkingLevel) ? session.thinkingLevel : !now.thinking && levels.includes('auto') ? 'auto' : byId.get(onModel)?.effort ?? 'auto' };+ /* a conversation taken up again on a model no longer set up: on the one a session starts on */+ if (!now.id) await use(entry, onModel, entry.effort);sessionId = session.sessionId;const send = (update) => { void client.sessionUpdate({ sessionId, update }).catch(() => {}); };@@ -269,13 +287,13 @@ const connection = new acp.AgentSideConnection((client) => ({if (!entry) throw new Error('This conversation has ended.');if (params.configId === 'model') {const model = String(params.value);- if (!models.includes(model)) throw new Error(`No model ${model} at ${config.provider.id}.`);+ const own = byId.get(model);+ if (!own) throw new Error(`No model ${model}.`);/* the effort it was on, when this model takes it; else the one this model starts on */- const levels = efforts[model]?.levels ?? ['auto'];- await use(entry, model, levels.includes(entry.effort) ? entry.effort : efforts[model]?.effort ?? 'auto');+ await use(entry, model, own.levels.includes(entry.effort) ? entry.effort : own.effort);} else if (params.configId === 'effort') {const effort = String(params.value);- if (!(efforts[entry.model]?.levels ?? []).includes(effort)) throw new Error(`${entry.model} does not take the effort ${effort}.`);+ if (!(byId.get(entry.model)?.levels ?? []).includes(effort)) throw new Error(`${byId.get(entry.model)?.name ?? entry.model} does not take the effort ${effort}.`);await use(entry, entry.model, effort);} else throw new Error(`No option ${params.configId}.`);return { configOptions: optionsOf(entry) };diff --git a/apps/desktop/src/pi-agent.test.mjs b/apps/desktop/src/pi-agent.test.mjsindex d99cae1..0c03416 100644--- a/apps/desktop/src/pi-agent.test.mjs+++ b/apps/desktop/src/pi-agent.test.mjs@@ -6,10 +6,11 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { AgentSession } from './agents.mjs';-/** A service on the Chat Completions API that answers "ok" and notes the model each request named (and each request). */-async function service() {+/** A service on the Chat Completions API that answers "ok" and notes the model each request named (and each request, and its key). */+async function service({ broke = false } = {}) {const asked = [];const bodies = [];+ const keys = [];const server = createServer((req, res) => {let body = '';req.on('data', (d) => { body += d; });@@ -17,6 +18,8 @@ async function service() {const { model } = JSON.parse(body || '{}');asked.push(model);bodies.push(JSON.parse(body || '{}'));+ keys.push(String(req.headers.authorization ?? ''));+ if (broke) { res.writeHead(402, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: { message: 'Insufficient Balance' } })); return; }res.writeHead(200, { 'content-type': 'text/event-stream' });const chunk = (choice, extra = {}) => `data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', created: 0, model, choices: [choice], ...extra })}\n\n`;res.end(chunk({ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: null })@@ -25,36 +28,42 @@ async function service() {});});await new Promise((done) => server.listen(0, '127.0.0.1', done));- return { asked, bodies, url: `http://127.0.0.1:${server.address().port}/v1`, close: () => server.close() };+ return { asked, bodies, keys, url: `http://127.0.0.1:${server.address().port}/v1`, close: () => server.close() };}-test('the own key\'s agent offers its models as the session\'s model option, and a turn after a switch goes to that model', { timeout: 60_000 }, async () => {- const svc = await service();+/** One of the person's own models, as the roster's harness gives it (pi-config.mjs OwnModel). */+const own = (id, url, over = {}) => ({ id, name: id, api: 'openai-completions', baseUrl: url, keyEnv: `OPENFILM_BYOK_KEY_${id}`, model: id, levels: ['auto'], effort: 'auto', ...over });++test("the own key's models, each on its own service and key, are the session's model option; a turn after a switch goes to the other service", { timeout: 60_000 }, async () => {+ const first = await service();+ const second = await service();const session = new AgentSession({agent: 'byok',cwd: mkdtempSync(join(tmpdir(), 'of-pi-')),harness: {home: mkdtempSync(join(tmpdir(), 'of-pi-home-')),- provider: { id: 'byok', api: 'openai-completions', baseUrl: svc.url, apiKeyEnv: 'OPENFILM_BYOK_KEY' },- model: 'vision', models: ['vision', 'big'],- env: { OPENFILM_BYOK_KEY: 'sk-test' },+ models: [own('a', first.url, { name: 'Vision', model: 'vision' }), own('b', second.url, { name: 'Big', model: 'big' })],+ model: 'a',+ env: { OPENFILM_BYOK_KEY_a: 'sk-first', OPENFILM_BYOK_KEY_b: 'sk-second' },},});try {const info = await session.start();const option = info.configOptions.find((o) => o.id === 'model');assert.equal(option.category, 'model');- assert.equal(option.currentValue, 'vision', 'the first model to begin with');- assert.deepEqual(option.options.map((o) => o.value), ['vision', 'big']);+ assert.equal(option.currentValue, 'a', 'the first model to begin with');+ assert.deepEqual(option.options, [{ value: 'a', name: 'Vision' }, { value: 'b', name: 'Big' }], 'by their names');await session.prompt([{ type: 'text', text: 'hi' }]);- const switched = await session.setConfigOption('model', 'big');- assert.equal(switched.configOptions[0].currentValue, 'big');+ const switched = await session.setConfigOption('model', 'b');+ assert.equal(switched.configOptions[0].currentValue, 'b');await session.prompt([{ type: 'text', text: 'again' }]);- assert.deepEqual(svc.asked, ['vision', 'big']);- await assert.rejects(session.setConfigOption('model', 'other'), 'a model the key does not name is refused');+ assert.deepEqual([first.asked, first.keys], [['vision'], ['Bearer sk-first']], 'the first on its own service, with its key');+ assert.deepEqual([second.asked, second.keys], [['big'], ['Bearer sk-second']], 'the other on its own, with its own');+ await assert.rejects(session.setConfigOption('model', 'other'), 'a model not set up is refused');} finally {session.close();- svc.close();+ first.close();+ second.close();}});@@ -65,10 +74,9 @@ test('a model\'s efforts are the session\'s effort option: Auto sends no reasonicwd: mkdtempSync(join(tmpdir(), 'of-pi-')),harness: {home: mkdtempSync(join(tmpdir(), 'of-pi-home-')),- provider: { id: 'byok', api: 'openai-completions', baseUrl: svc.url, apiKeyEnv: 'OPENFILM_BYOK_KEY' },- model: 'thinker', models: ['thinker', 'plain'],- efforts: { thinker: { levels: ['auto', 'off', 'low', 'high'], effort: 'low' } },- env: { OPENFILM_BYOK_KEY: 'sk-test' },+ models: [own('thinker', svc.url, { levels: ['auto', 'off', 'low', 'high'], effort: 'low' }), own('plain', svc.url)],+ model: 'thinker',+ env: { OPENFILM_BYOK_KEY_thinker: 'sk-test', OPENFILM_BYOK_KEY_plain: 'sk-test' },},});const effortOf = (options) => options.find((o) => o.id === 'effort');@@ -101,3 +109,29 @@ test('a model\'s efforts are the session\'s effort option: Auto sends no reasonisvc.close();}});++test('a service with no balance left is named for the model the turn was on, not the first one', { timeout: 60_000 }, async () => {+ const first = await service();+ const second = await service({ broke: true });+ const session = new AgentSession({+ agent: 'byok',+ cwd: mkdtempSync(join(tmpdir(), 'of-pi-')),+ harness: {+ home: mkdtempSync(join(tmpdir(), 'of-pi-home-')),+ models: [own('a', first.url), own('b', second.url)],+ model: 'a',+ env: { OPENFILM_BYOK_KEY_a: 'sk-first', OPENFILM_BYOK_KEY_b: 'sk-second' },+ },+ });+ try {+ await session.start();+ await session.setConfigOption('model', 'b');+ const error = await session.prompt([{ type: 'text', text: 'hi' }]).then(() => null, (e) => e);+ assert.equal(error?.code, 'balance');+ assert.equal(error.balance.provider, new URL(second.url).host);+ } finally {+ session.close();+ first.close();+ second.close();+ }+});diff --git a/apps/desktop/src/pi-config.mjs b/apps/desktop/src/pi-config.mjsindex b1efc40..b4dd6e0 100644--- a/apps/desktop/src/pi-config.mjs+++ b/apps/desktop/src/pi-config.mjs@@ -1,8 +1,9 @@/*** What the app's own agent (Pi, src/pi-agent.mjs) runs with, and how what it does reads in the chat (ACP).*- * The service is one provider in Pi's `models.json`: the person's own key on one of three APIs, with the models they- * named; the chat's menu switches between them (`modelOption`).+ * The person's own models, each set up on its own (agent-roster.mjs): its name, its service (an address on one of three+ * APIs, and its own key), the model asked for there and its reasoning efforts. Each is a provider of its own in Pi's+ * `models.json`, so the chat's menu switches between them (`modelOption`), one service to another.** Reads no Electron module, so `node --test` can use it.*/@@ -26,20 +27,24 @@ export function effortLevels(value) {}/**- * Each model's efforts, for the models named: the ones it offers (`levels`) and the one a conversation starts on- * (`effort`, one of them; the first when the one asked is not).- * @param {unknown} raw @param {string[]} models- * @returns {Record<string, { levels: string[], effort: string }>}+ * A model's efforts: the ones it offers (`levels`) and the one a conversation starts on (`effort`, one of them; the+ * first when the one asked is not).+ * @returns {{ levels: string[], effort: string }}*/-export function modelEfforts(raw, models) {- const all = raw && typeof raw === 'object' ? /** @type {Record<string, any>} */ (raw) : {};- return Object.fromEntries(models.map((model) => {- const levels = effortLevels(all[model]?.levels);- const effort = levels.includes(String(all[model]?.effort)) ? String(all[model].effort) : levels[0];- return [model, { levels, effort }];- }));+export function modelEffort(/** @type {unknown} */ levels, /** @type {unknown} */ effort) {+ const offered = effortLevels(levels);+ return { levels: offered, effort: offered.includes(String(effort)) ? String(effort) : offered[0] };}+/**+ * One of the person's own models as the agent runs it: `id` (the app's, never shown), `name` (the menu's), Pi's `api`,+ * the service's `baseUrl`, the variable its key is in (`keyEnv`), the `model` asked for there and its efforts.+ * @typedef {{ id: string, name: string, api: string, baseUrl: string, keyEnv: string, model: string, levels: string[], effort: string }} OwnModel+ */++/** Pi's provider for one of the person's own models: each its own service. */+export const providerOf = (/** @type {string} */ id) => `byok-${id}`;+/** The provider that thinks: the same service, its models told which levels they take. */export const THINKING = (/** @type {string} */ id) => `${id}-thinking`;@@ -50,37 +55,36 @@ const wire = (/** @type {string} */ api, /** @type {string} */ level) => (levelconst CONTEXT = 128_000;/**- * Pi's `models.json` for the service and its models. The service twice: as itself, where no model is told to reason- * (`auto`: no reasoning setting is sent), and as THINKING(id) with the models that offer levels, each told exactly- * which (Pi sends the one picked; the others are not there).- * @param {{ id: string, api: string, baseUrl: string, apiKeyEnv: string }} provider @param {string[] | string} models- * @param {Record<string, { levels: string[] }>} [efforts]+ * Pi's `models.json` for the person's own models: each its own provider (its address and key), twice when it offers+ * levels: as itself, told not to reason (`auto`: no reasoning setting is sent), and as THINKING(provider) told exactly+ * which levels it takes (Pi sends the one picked; the others are not there).+ * @param {OwnModel[]} models*/-export function modelsJson(provider, models, efforts = {}) {- const names = [models].flat();- const entry = (/** @type {string} */ model, /** @type {string[] | null} */ levels) => ({- id: model,- name: model,+export function modelsJson(models) {+ const entry = (/** @type {OwnModel} */ m, /** @type {string[] | null} */ levels) => ({+ id: m.model,+ name: m.name,input: ['text', 'image'],contextWindow: CONTEXT,maxTokens: Math.floor(CONTEXT / 4),reasoning: Boolean(levels),- ...(levels ? { thinkingLevelMap: Object.fromEntries(EFFORTS.slice(1).map((l) => [l, levels.includes(l) ? wire(provider.api, l) : null])) } : {}),+ ...(levels ? { thinkingLevelMap: Object.fromEntries(EFFORTS.slice(1).map((l) => [l, levels.includes(l) ? wire(m.api, l) : null])) } : {}),cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },});- const service = { baseUrl: provider.baseUrl, api: provider.api, apiKey: `$${provider.apiKeyEnv}` };- const thinking = names.map((m) => [m, (efforts[m]?.levels ?? []).filter((l) => l !== 'auto')]).filter(([, levels]) => levels.length);- return {- providers: {- [provider.id]: { ...service, models: names.map((m) => entry(m, null)) },- ...(thinking.length ? { [THINKING(provider.id)]: { ...service, models: thinking.map(([m, levels]) => entry(/** @type {string} */ (m), /** @type {string[]} */ (levels))) } } : {}),- },- };+ /** @type {Record<string, any>} */+ const providers = {};+ for (const m of models) {+ const service = { baseUrl: m.baseUrl, api: m.api, apiKey: `$${m.keyEnv}` };+ const levels = m.levels.filter((l) => l !== 'auto');+ providers[providerOf(m.id)] = { ...service, models: [entry(m, null)] };+ if (levels.length) providers[THINKING(providerOf(m.id))] = { ...service, models: [entry(m, levels)] };+ }+ return { providers };}-/** The model as a config option the chat's menu reads (ACP): the models named, and the one a session runs. */-export function modelOption(models, current) {- return { id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: current, options: models.map((m) => ({ value: m, name: m })) };+/** The model as a config option the chat's menu reads (ACP): the person's models by their names, and the one a session runs. */+export function modelOption(/** @type {Array<{ id: string, name: string }>} */ models, /** @type {string} */ current) {+ return { id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: current, options: models.map((m) => ({ value: m.id, name: m.name })) };}const EFFORT_NAMES = { auto: 'Auto', off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' };diff --git a/apps/desktop/src/pi-config.test.mjs b/apps/desktop/src/pi-config.test.mjsindex 61eec18..d3a6de6 100644--- a/apps/desktop/src/pi-config.test.mjs+++ b/apps/desktop/src/pi-config.test.mjs@@ -1,26 +1,31 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { THINKING, contextUsed, effortOption, modelEfforts, modelOption, modelsJson, outOfBalance, stopReason, toolCall, toolContent } from './pi-config.mjs';+import { THINKING, contextUsed, effortOption, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';-test('the person\'s own key is one provider in Pi\'s models.json, with the one model they named', () => {- const p = modelsJson({ id: 'byok', api: 'openai-completions', baseUrl: 'https://api.deepseek.com/v1', apiKeyEnv: 'K' }, 'vision').providers.byok;- assert.equal(p.apiKey, '$K', 'the key from its variable, never written down');- assert.equal(p.baseUrl, 'https://api.deepseek.com/v1');- assert.equal(p.api, 'openai-completions');- const [model] = p.models;- assert.equal(p.models.length, 1);- assert.equal(model.id, 'vision');+/** One of the person's own models, as the roster's harness gives it. */+const own = (id, over = {}) => ({ id, name: id.toUpperCase(), api: 'openai-completions', baseUrl: `https://${id}.test/v1`, keyEnv: `K_${id}`, model: `${id}-model`, levels: ['auto'], effort: 'auto', ...over });++test("each of the person's models is a provider of its own in Pi's models.json: its address, its key's variable, its model", () => {+ const json = modelsJson([own('a'), own('b', { api: 'anthropic-messages' })]);+ assert.deepEqual(Object.keys(json.providers), [providerOf('a'), providerOf('b')], 'nobody thinks: no thinking services');+ const a = json.providers[providerOf('a')];+ assert.equal(a.apiKey, '$K_a', 'the key from its variable, never written down');+ assert.equal(a.baseUrl, 'https://a.test/v1');+ assert.equal(a.api, 'openai-completions');+ assert.equal(json.providers[providerOf('b')].api, 'anthropic-messages');+ const [model] = a.models;+ assert.equal(a.models.length, 1);+ assert.equal(model.id, 'a-model', 'the model as the service names it');+ assert.equal(model.name, 'A');assert.deepEqual(model.input, ['text', 'image']);assert.equal(model.contextWindow, 128_000, 'a length when the service gives none');assert.equal(model.reasoning, false);});-test('several models are each one of the provider\'s, and the chat\'s menu reads them as the model option', () => {- const p = modelsJson({ id: 'byok', api: 'openai-responses', baseUrl: 'https://api.openai.com/v1', apiKeyEnv: 'K' }, ['gpt-a', 'gpt-b']).providers.byok;- assert.deepEqual(p.models.map((m) => m.id), ['gpt-a', 'gpt-b']);- assert.deepEqual(modelOption(['gpt-a', 'gpt-b'], 'gpt-b'), {- id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'gpt-b',- options: [{ value: 'gpt-a', name: 'gpt-a' }, { value: 'gpt-b', name: 'gpt-b' }],+test("the chat's menu reads the person's models by their names, each picked by its id", () => {+ assert.deepEqual(modelOption([own('a'), own('b')], 'b'), {+ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'b',+ options: [{ value: 'a', name: 'A' }, { value: 'b', name: 'B' }],});});@@ -56,19 +61,19 @@ test('no balance left, as each service says it, is one outcome with the service\"DeepSeek doesn't have enough balance for this. Top it up there, or switch to another service, then try again.");});-test('the service twice: as itself (no reasoning setting) and thinking, each model told only the levels it was given', () => {- const efforts = modelEfforts({ a: { levels: ['auto', 'off', 'low', 'max'], effort: 'low' } }, ['a', 'b']);- assert.deepEqual(efforts.b, { levels: ['auto'], effort: 'auto' });- const json = modelsJson({ id: 'byok', api: 'openai-responses', baseUrl: 'https://x/v1', apiKeyEnv: 'K' }, ['a', 'b'], efforts);- assert.deepEqual(json.providers.byok.models.map((m) => [m.id, m.reasoning]), [['a', false], ['b', false]]);- const thinking = json.providers[THINKING('byok')].models;- assert.deepEqual(thinking.map((m) => m.id), ['a'], 'only a model given levels thinks');+test('a model given levels is its service twice: as itself (no reasoning setting) and thinking, told only those levels', () => {+ assert.deepEqual(modelEffort(['max', 'auto', 'off', 'turbo', 'low'], 'low'), { levels: ['auto', 'off', 'low', 'max'], effort: 'low' });+ assert.deepEqual(modelEffort([], 'high'), { levels: ['auto'], effort: 'auto' }, 'none given: Auto alone');+ assert.deepEqual(modelEffort(['low', 'high'], 'max'), { levels: ['low', 'high'], effort: 'low' }, 'one not offered: the first');+ const json = modelsJson([own('a', { api: 'openai-responses', ...modelEffort(['auto', 'off', 'low', 'max'], 'low') }), own('b')]);+ assert.equal(json.providers[providerOf('a')].models[0].reasoning, false);+ const thinking = json.providers[THINKING(providerOf('a'))].models;+ assert.deepEqual(thinking.map((m) => m.id), ['a-model']);assert.deepEqual(thinking[0].thinkingLevelMap, { off: 'none', minimal: null, low: 'low', medium: null, high: null, xhigh: null, max: 'max' });+ assert.equal(json.providers[THINKING(providerOf('b'))], undefined, 'only a model given levels thinks');/* Anthropic's API is told off as off */- const claude = modelsJson({ id: 'byok', api: 'anthropic-messages', baseUrl: 'https://x', apiKeyEnv: 'K' }, ['a'], efforts);- assert.equal(claude.providers[THINKING('byok')].models[0].thinkingLevelMap.off, 'off');- /* nobody thinks: no thinking service */- assert.equal(modelsJson({ id: 'byok', api: 'openai-responses', baseUrl: 'https://x/v1', apiKeyEnv: 'K' }, ['b'], efforts).providers[THINKING('byok')], undefined);+ const claude = modelsJson([own('c', { api: 'anthropic-messages', ...modelEffort(['off'], 'off') })]);+ assert.equal(claude.providers[THINKING(providerOf('c'))].models[0].thinkingLevelMap.off, 'off');});test('the effort option: for a model offering more than one, its levels named', () => {diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjsindex c0ddc46..d5ef43a 100644--- a/apps/desktop/src/preload.cjs+++ b/apps/desktop/src/preload.cjs@@ -26,6 +26,19 @@ contextBridge.exposeInMainWorld('openfilmNative', {/* part of the window as a JPEG (base64), for a reference's picture: null when it could not be taken */capture: (rect) => ipcRenderer.invoke('desktop:capture', rect),+ /* the window's tabs (tabs.mjs), drawn by the page in Studio's top bar */+ tabs: {+ list: () => ipcRenderer.invoke('desktop:tabs:list'),+ onChange: on('desktop:tabs'),+ show: (id) => ipcRenderer.invoke('desktop:tabs:show', { id }),+ close: (id) => ipcRenderer.invoke('desktop:tabs:close', { id }),+ open: (projectId) => ipcRenderer.invoke('desktop:tabs:new', { projectId }),+ move: (id, index) => ipcRenderer.invoke('desktop:tabs:move', { id, index }),+ report: (state) => ipcRenderer.invoke('desktop:tabs:report', state ?? {}),+ openRequest: (to) => ipcRenderer.invoke('desktop:tabs:open', { to }),+ onPick: on('desktop:tabs:pick'),+ },+/* the roster (agent-roster.mjs): Settings → Agents and the chat's menu */agents: {list: () => ipcRenderer.invoke('desktop:agents:list'),@@ -36,7 +49,14 @@ contextBridge.exposeInMainWorld('openfilmNative', {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 }),+ saveOwnModel: (config) => ipcRenderer.invoke('desktop:agents:own-model', { config }),+ removeOwnModel: (id) => ipcRenderer.invoke('desktop:agents:own-model-remove', { id }),+ /* the MCP servers the person added to it themselves, each let into OpenFilm or not (skills-ipc.mjs) */+ mcp: (id) => ipcRenderer.invoke('desktop:agents:mcp', { id }),+ /* the skills the person installed in it themselves, each let into OpenFilm or not */+ skills: (id) => ipcRenderer.invoke('desktop:agents:skills', { id }),+ allowSkill: (id, name, allowed) => ipcRenderer.invoke('desktop:skills:allow', { agent: id, name, allowed: allowed === true }),+ allowMcp: (id, name, allowed) => ipcRenderer.invoke('desktop:agents:mcp-allow', { id, name, allowed: allowed === true }),onChange: on('desktop:agents'),},/* the agents' turns (local-agents-ipc.mjs) */@@ -71,6 +91,18 @@ contextBridge.exposeInMainWorld('openfilmNative', {snapshot: (project, turnId) => ipcRenderer.invoke('desktop:chat:snapshot', { project, turnId }),changes: (project, turnId) => ipcRenderer.invoke('desktop:chat:changes', { project, turnId }),},+ /* the composer's Skills button (skills-ipc.mjs) */+ skills: {+ list: (project, agent) => ipcRenderer.invoke('desktop:skills:list', { project, agent }),+ texts: (project, agent, names) => ipcRenderer.invoke('desktop:skills:texts', { project, agent, names }),+ allow: (agent, name, allowed) => ipcRenderer.invoke('desktop:skills:allow', { agent, name, allowed }),+ preview: (url) => ipcRenderer.invoke('desktop:skills:preview', { url }),+ /* a folder dropped (its path), or null: one picked in the system's dialog, with the page's words { title, button } */+ previewFolder: (path, words) => ipcRenderer.invoke('desktop:skills:preview', { folder: typeof path === 'string' ? path : null, words }),+ commit: (id) => ipcRenderer.invoke('desktop:skills:commit', { id }),+ discard: (id) => ipcRenderer.invoke('desktop:skills:discard', { id }),+ reveal: () => ipcRenderer.invoke('desktop:skills:reveal'),+ },/* the app's own preferences (Settings → Developer) */prefs: {get: () => ipcRenderer.invoke('desktop:prefs'),diff --git a/apps/desktop/src/skills-ipc.mjs b/apps/desktop/src/skills-ipc.mjsnew file mode 100644index 0000000..bb9a146--- /dev/null+++ b/apps/desktop/src/skills-ipc.mjs@@ -0,0 +1,180 @@+/**+ * The skills and MCP servers the chat and Settings show (apps/desktop/src/agent-skills.mjs, openfilm/skills).+ *+ * For the composer's Skills button:+ * desktop:skills:list { project, agent } → { openfilm: [Skill], own: { agent, filtered, skills: [OwnSkill] }, mine }+ * OpenFilm's skills (the project's, the person's own, the official ones), and the agent's+ * own skills with whether each is let in (`filtered` false: it has them all, as in its own+ * terminal). OpenFilm's own skill for terminal agents is never among them (agent-skills isOurs).+ * desktop:skills:texts { project, agent, names } → [{ name, text }] skills named in a message, as the agent reads+ * each (its folder and its SKILL.md whole)+ * desktop:skills:preview { url } | { folder } → { ok, id, skills: [{ name, description, scripts, size, replaces }] }+ * | { ok: false, error } | { ok: false, cancelled } a GitHub or GitLab address fetched beside+ * the person's skills, or a folder on this computer (one dropped, or `folder` null: picked+ * in the system's dialog, with the page's `words` { title, button }) looked at where it is, to be looked at first+ * desktop:skills:commit { id } → { ok, skills: [Skill] } | { ok: false, error } kept: added to the person's own+ * (a folder copied), one of the same name to the trash+ * desktop:skills:discard { id } let go+ * desktop:skills:reveal the person's own skills folder in the file manager+ * For Settings → Agents:+ * desktop:agents:skills { id } → { filtered, skills: [{ name, description, allowed }] } the skills the person+ * installed in an agent, each let into OpenFilm or not+ * desktop:skills:allow { agent, name, allowed } → { ok } one let in, or not: the agent's sessions take it up+ * desktop:agents:mcp { id } → { filtered, servers: [{ name, detail, allowed }] } the same for MCP servers+ * desktop:agents:mcp-allow { id, name, allowed } → { ok }+ *+ * `project` is a folder Studio has as a project, as for the chat's record (chat-ipc.mjs). The person's own skills kept+ * in Studio's home before are moved beside the projects as this starts (openfilm/skills migrateMySkills).+ * Reads no Electron module, so `node --test` can use it.+ */+import { createRequire } from 'node:module';+import { mkdirSync } from 'node:fs';+import { isAbsolute, resolve } from 'node:path';+import { randomUUID } from 'node:crypto';+import { pathToFileURL } from 'node:url';+import { FILTERED_AGENTS, MCP_AGENTS, ownMcpServers, ownSkills, skillStore } from './agent-skills.mjs';+import { loginShellVariables } from './environment.mjs';++const require = createRequire(import.meta.url);+/* by their file URLs: import() takes no Windows path (`D:\…`) */+const lib = () => import(pathToFileURL(require.resolve('openfilm/skills')).href);+const cli = () => import(pathToFileURL(require.resolve('openfilm/skills-cli')).href);++/** A skill as the page shows it. */+const shown = (s) => ({ name: s.name, description: s.description, source: s.source, folder: s.folder, scripts: s.scripts ?? [], ...(s.over ? { over: s.over } : {}), ...(s.shown ? { shown: s.shown } : {}) });++/**+ * @param {import('electron').IpcMain} ipcMain+ * @param {{ trusted: (event: any) => boolean, projects: () => Promise<string[]>, dataDir: string, mine: string,+ * oldMine?: string, reveal: (path: string) => void, pickFolder: (words: unknown) => Promise<string | null>,+ * refreshSkills: (agent: string) => void, log: (line: string) => void }} opts+ * `mine`: the person's own skills folder; `oldMine`: where they were kept before, moved from as this starts;+ * `pickFolder`: a folder of skills picked in the system's dialog (null: cancelled)+ */+export function registerSkillsIpc(ipcMain, { trusted, projects, dataDir, mine, oldMine, reveal, pickFolder, refreshSkills, log }) {+ const store = skillStore(dataDir);+ /* read as the app starts, so the composer's first list does not wait on them: the skills' module, and the login+ shell the agents' own skills are found with */+ void lib().catch(() => {});+ void loginShellVariables({ staleOk: true });+ if (oldMine) void lib().then(({ migrateMySkills }) => {+ const moved = migrateMySkills({ from: oldMine, to: mine });+ if (moved.length) log(`skills moved to ${mine}: ${moved.join(', ')}\n`);+ }).catch((e) => log(`skills: ${e.message}\n`));+ let known = new Set();+ const project = async (path) => {+ if (typeof path !== 'string' || !path) return null;+ const want = resolve(path);+ if (!known.has(want)) known = new Set((await projects()).map((p) => resolve(p)));+ if (!known.has(want)) throw new Error('not a project of Studio\'s');+ return want;+ };+ const handle = (channel, fn) => ipcMain.handle(channel, async (event, opts) => {+ if (!trusted(event)) throw new Error('not the window\'s page');+ try { return await fn(opts ?? {}); } catch (e) { log(`${channel}: ${e.message}\n`); throw e; }+ });+ /* the skills the person installed in the agent (OpenFilm's own for terminal agents never among them) */+ const agentOwn = async (agent, cwd) => (agent && agent !== 'byok'+ ? (await ownSkills(agent, { cwd: cwd ?? '', env: await loginShellVariables({ staleOk: true }) })).filter((s) => !s.ours) : []);++ handle('desktop:skills:list', async ({ project: path, agent }) => {+ const cwd = await project(path);+ const { listSkills } = await lib();+ const allowed = new Set(store.allowed(agent));+ return {+ openfilm: listSkills({ project: cwd, mine }).map(shown),+ own: { agent, filtered: FILTERED_AGENTS.includes(agent), skills: (await agentOwn(agent, cwd)).map((s) => ({ name: s.name, description: s.description, folder: s.folder, allowed: allowed.has(s.name) })) },+ mine,+ };+ });++ handle('desktop:skills:texts', async ({ project: path, agent, names }) => {+ const cwd = await project(path);+ const { listSkills, readSkill, skillText } = await lib();+ const wanted = Array.isArray(names) ? names.filter((n) => typeof n === 'string') : [];+ const openfilm = new Map(listSkills({ project: cwd, mine }).map((s) => [s.name, s]));+ const own = new Map((await agentOwn(agent, cwd)).map((s) => [s.name, s]));+ return wanted.flatMap((name) => {+ const skill = openfilm.get(name) ?? (own.has(name) ? readSkill(own.get(name).folder, 'mine') : null);+ return skill ? [{ name, text: skillText(skill) }] : [];+ });+ });++ /* adding from an address or a folder: looked at, then kept or let go; each waiting by its id (an address's fetch, or+ the folder to copy) */+ const waiting = new Map();+ const looked = (skills) => skills.map((s) => ({ name: s.name, description: s.description, scripts: s.scripts, size: s.size, replaces: s.replaces }));+ handle('desktop:skills:preview', async ({ url, folder, words }) => {+ try {+ if (folder !== undefined) {+ const path = folder === null ? await pickFolder(words) : String(folder);+ if (!path) return { ok: false, cancelled: true };+ if (!isAbsolute(path)) return { ok: false, error: 'Drop a folder that holds a SKILL.md.' };+ const { previewFolder } = await cli();+ const { folder: src, skills } = previewFolder(path, { mine });+ const id = randomUUID();+ waiting.set(id, { folder: src });+ return { ok: true, id, skills: looked(skills) };+ }+ const address = String(url ?? '').trim();+ if (!/^https:\/\//i.test(address)) return { ok: false, error: 'Paste the https address of a skill on GitHub or GitLab.' };+ const { previewSkills } = await cli();+ const { staging, skills } = await previewSkills(address, { mine });+ const id = randomUUID();+ waiting.set(id, { staging });+ return { ok: true, id, skills: looked(skills) };+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : String(e) };+ }+ });+ handle('desktop:skills:commit', async ({ id }) => {+ const what = waiting.get(id);+ waiting.delete(id);+ if (!what) return { ok: false, error: 'Nothing is waiting to be added.' };+ try {+ const kept = what.folder ? await (await lib()).addSkills(what.folder, { mine }) : await (await cli()).commitSkills(what.staging, { mine });+ return { ok: true, skills: kept.map(shown) };+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : String(e) };+ }+ });+ handle('desktop:skills:discard', async ({ id }) => {+ const what = waiting.get(id);+ waiting.delete(id);+ if (what?.staging) await (await cli()).discardSkills(what.staging, { mine });+ return { ok: true };+ });++ handle('desktop:agents:skills', async ({ id }) => {+ const agent = String(id ?? '');+ const allowed = new Set(store.allowed(agent));+ return { filtered: FILTERED_AGENTS.includes(agent), skills: (await agentOwn(agent, '')).map((s) => ({ name: s.name, description: s.description, allowed: allowed.has(s.name) })) };+ });++ handle('desktop:skills:allow', async ({ agent, name, allowed }) => {+ if (typeof agent !== 'string' || typeof name !== 'string' || !name) return { ok: false };+ store.setAllowed(agent, name, allowed === true);+ refreshSkills(agent);+ return { ok: true };+ });++ handle('desktop:agents:mcp', async ({ id }) => {+ const agent = String(id ?? '');+ const allowed = new Set(store.mcpAllowed(agent));+ const servers = MCP_AGENTS.includes(agent) ? ownMcpServers(agent, { env: await loginShellVariables({ staleOk: true }) }) : [];+ return { filtered: MCP_AGENTS.includes(agent), servers: servers.map((s) => ({ ...s, allowed: allowed.has(s.name) })) };+ });++ handle('desktop:agents:mcp-allow', async ({ id, name, allowed }) => {+ if (typeof id !== 'string' || typeof name !== 'string' || !name) return { ok: false };+ store.setMcpAllowed(id, name, allowed === true);+ refreshSkills(id);+ return { ok: true };+ });++ handle('desktop:skills:reveal', async () => {+ mkdirSync(mine, { recursive: true });+ reveal(mine);+ return { ok: true };+ });+}diff --git a/apps/desktop/src/studio-refs.test.mjs b/apps/desktop/src/studio-refs.test.mjsindex 18f168a..5c765b0 100644--- a/apps/desktop/src/studio-refs.test.mjs+++ b/apps/desktop/src/studio-refs.test.mjs@@ -134,3 +134,17 @@ test('the message being written numbers its references as the agent will: each oassert.deepEqual(draftRefs(['b', 'file:assets/x.png', 'a', 'b', 'c', 'gone'], known), [layer, clip, region]);assert.deepEqual(draftRefs([], known), []);});++test('an example, or a part of it: its pill names it and the part, the agent reads another film\'s folder', () => {+ const part = { kind: 'example', id: 'openfilm-intro', title: 'OpenFilm intro', url: 'https://github.com/openfilm/examples/tree/main/openfilm-intro', folder: '/cache/examples/openfilm-intro', start: 16.12, end: 31.6, segment: 'S4-Studio' };+ const whole = { kind: 'example', id: 'one-prompt', title: 'One Prompt', url: 'https://github.com/openfilm/examples/tree/main/one-prompt', folder: '/cache/examples/one-prompt' };+ const pill = refPill(undefined, part);+ assert.deepEqual([pill.id, pill.kind, pill.label, pill.detail], ['studio:example:openfilm-intro:16.12-31.6', 'example', 'OpenFilm intro', 'S4-Studio']);+ assert.equal(refPill(undefined, whole).detail, undefined);+ const text = studioReferencesText([part, whole]);+ assert.match(text, /\[1\] example film "OpenFilm intro" \(another OpenFilm film, not this one: read its film\.html and pages for how it is made\) · folder \/cache\/examples\/openfilm-intro · its 16\.120–31\.600 s \("S4-Studio"\) · source https:\/\/github\.com\//);+ assert.match(text, /\[2\] example film "One Prompt" .* · the whole film · source /);+ assert.match(studioReferencesText([{ ...whole, folder: undefined }]), /could not be fetched: read it at its source · the whole film · source https:/, 'not fetched: its source said instead');+ assert.ok(sameStudioThing(part, { ...part }) && !sameStudioThing(part, whole));+ assert.equal(pillCard(pill, (k) => k).title, 'refCard.title.example');+});diff --git a/apps/desktop/src/tabs.mjs b/apps/desktop/src/tabs.mjsnew file mode 100644index 0000000..1f90702--- /dev/null+++ b/apps/desktop/src/tabs.mjs@@ -0,0 +1,149 @@+// @ts-check+/**+ * The window's tabs: one per project the person has open. Only what the tabs are, in order, which is in front and what+ * each says (its project's title, an agent working in it, an export, a question waiting); main.mjs gives each a page.+ * Reads no Electron module, so `node --test` can use it.+ *+ * Rules: a project is in one tab at most; a tab is always a project's (a project is picked first, in the projects+ * window, and its tab opens); with none open, the window shows the projects; a tab closed can be opened again, last+ * closed first.+ */+import { randomUUID } from 'node:crypto';++/**+ * @typedef {{ id: string, projectId: string, title: string, working: boolean, asking: boolean,+ * exporting: number | null, shown: number }} Tab+ * @typedef {{ tabs: Array<{ projectId: string, title?: string }>, active: number }} SavedTabs+ */++const REOPEN_KEPT = 20;++/**+ * @param {{ saved?: SavedTabs | null, now?: () => number, newId?: () => string }} [opts]+ */+export function createTabs({ saved = null, now = Date.now, newId = randomUUID } = {}) {+ /** @type {Tab[]} */+ let tabs = [];+ /** @type {string | null} */+ let active = null;+ /** @type {Array<{ projectId: string, title: string, at: number }>} */+ const closed = [];++ const make = (/** @type {string} */ projectId, title = '') => ({ id: newId(), projectId, title, working: false, asking: false, exporting: null, shown: now() });+ const indexOf = (/** @type {string} */ id) => tabs.findIndex((t) => t.id === id);++ /* the tabs as last left; a project in two of them (an older save) once */+ if (saved && Array.isArray(saved.tabs)) {+ const seen = new Set();+ for (const t of saved.tabs) {+ const projectId = typeof t?.projectId === 'string' && t.projectId ? t.projectId : null;+ if (!projectId || seen.has(projectId)) continue;+ seen.add(projectId);+ tabs.push(make(projectId, typeof t?.title === 'string' ? t.title : ''));+ }+ active = tabs[Math.min(Math.max(0, Number(saved.active) || 0), tabs.length - 1)]?.id ?? null;+ }++ const api = {+ /** The tabs in order, as the pages draw them. */+ list: () => tabs.map((t) => ({ id: t.id, projectId: t.projectId, title: t.title, active: t.id === active, working: t.working, asking: t.asking, exporting: t.exporting })),+ activeId: () => active,+ /** @param {string} id */+ get: (id) => tabs.find((t) => t.id === id) ?? null,+ /** @param {string} projectId */+ byProject: (projectId) => tabs.find((t) => t.projectId === projectId) ?? null,+ /**+ * A project's tab, right of the one in front (the one it is in, if it is open already). → the tab+ * @param {{ projectId: string, title?: string }} opts+ */+ open({ projectId, title = '' }) {+ const there = api.byProject(projectId);+ if (there) { api.activate(there.id); return there; }+ const tab = make(projectId, title);+ const at = active ? indexOf(active) + 1 : tabs.length;+ tabs.splice(at, 0, tab);+ api.activate(tab.id);+ return tab;+ },+ /** @param {string} id */+ activate(id) {+ const tab = api.get(id);+ if (!tab) return false;+ active = id;+ tab.shown = now();+ return true;+ },+ /**+ * Close a tab: the one to its right comes to the front (else its left). → the tab in front now (null: none left)+ * @param {string} id+ */+ close(id) {+ const i = indexOf(id);+ if (i < 0) return api.get(active ?? '');+ const [gone] = tabs.splice(i, 1);+ closed.push({ projectId: gone.projectId, title: gone.title, at: i });+ if (closed.length > REOPEN_KEPT) closed.shift();+ if (!tabs.length) active = null;+ else if (active === id) api.activate(tabs[Math.min(i, tabs.length - 1)].id);+ return api.get(active ?? '');+ },+ /** The tab closed last, open again where it was (its project in front if it is open already). → the tab, or null */+ reopen() {+ while (closed.length) {+ const last = closed.pop();+ if (!last) break;+ const there = api.byProject(last.projectId);+ if (there) { api.activate(there.id); return there; }+ const tab = make(last.projectId, last.title);+ tabs.splice(Math.min(last.at, tabs.length), 0, tab);+ api.activate(tab.id);+ return tab;+ }+ return null;+ },+ /** @param {string} id @param {number} index */+ move(id, index) {+ const i = indexOf(id);+ if (i < 0) return false;+ const [tab] = tabs.splice(i, 1);+ tabs.splice(Math.max(0, Math.min(index, tabs.length)), 0, tab);+ return true;+ },+ /**+ * What a tab's page says it shows now: its project's title, an export's progress.+ * @param {string} id @param {{ title?: string, exporting?: number | null }} state → whether there was such a tab+ */+ report(id, { title, exporting }) {+ const tab = api.get(id);+ if (!tab) return false;+ if (typeof title === 'string') tab.title = title;+ if (exporting !== undefined) tab.exporting = typeof exporting === 'number' ? Math.max(0, Math.min(1, exporting)) : null;+ return true;+ },+ /**+ * The projects an agent is working in, and those where one waits for an answer. → whether a tab changed+ * @param {Iterable<string>} working @param {Iterable<string>} [asking]+ */+ setAgents(working, asking = []) {+ const w = new Set(working); const a = new Set(asking);+ let changed = false;+ for (const t of tabs) {+ const nw = w.has(t.projectId); const na = a.has(t.projectId);+ if (nw !== t.working || na !== t.asking) { t.working = nw; t.asking = na; changed = true; }+ }+ return changed;+ },+ /**+ * Tabs behind for `ms` or more whose pages may be let go (they come back when shown): none with an agent working+ * or an export running.+ * @param {number} ms+ */+ idle(ms) {+ const t0 = now();+ return tabs.filter((t) => t.id !== active && t0 - t.shown >= ms && !t.working && t.exporting == null).map((t) => t.id);+ },+ /** As kept for next time. @returns {SavedTabs} */+ saved: () => ({ tabs: tabs.map((t) => ({ projectId: t.projectId, title: t.title })), active: Math.max(0, indexOf(active ?? '')) }),+ };+ return api;+}diff --git a/apps/desktop/src/tabs.test.mjs b/apps/desktop/src/tabs.test.mjsnew file mode 100644index 0000000..91aef2a--- /dev/null+++ b/apps/desktop/src/tabs.test.mjs@@ -0,0 +1,54 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createTabs } from './tabs.mjs';++const ids = () => { let n = 0; return () => `t${++n}`; };++test('a tab per project, new ones beside the one in front, a project already open brought to the front instead', () => {+ const tabs = createTabs({ newId: ids() });+ assert.deepEqual(tabs.list(), [], 'none until a project is picked');+ const a = tabs.open({ projectId: 'A', title: 'Launch' });+ tabs.open({ projectId: 'B' });+ assert.deepEqual(tabs.list().map((t) => [t.projectId, t.active]), [['A', false], ['B', true]]);+ assert.equal(tabs.open({ projectId: 'A' }).id, a.id, 'A is open already');+ assert.equal(tabs.activeId(), a.id);+ tabs.open({ projectId: 'C' });+ assert.deepEqual(tabs.list().map((t) => t.projectId), ['A', 'C', 'B'], 'right of the one in front');+ assert.equal(tabs.report(tabs.byProject('B').id, { title: 'Chapter 2' }), true);+ assert.equal(tabs.list().find((t) => t.projectId === 'B').title, 'Chapter 2');+});++test('closing: the next to the right comes forward; the last closed leaves none; a closed one opens again', () => {+ const tabs = createTabs({ newId: ids() });+ const a = tabs.open({ projectId: 'A' }); const b = tabs.open({ projectId: 'B' }); const c = tabs.open({ projectId: 'C' });+ tabs.activate(b.id);+ assert.equal(tabs.close(b.id).id, c.id);+ assert.equal(tabs.close(c.id).id, a.id, 'none to the right: the left');+ assert.equal(tabs.close(a.id), null, 'none left');+ assert.equal(tabs.activeId(), null);+ assert.equal(tabs.reopen().projectId, 'A');+ assert.equal(tabs.reopen().projectId, 'C');+ assert.deepEqual(tabs.list().map((t) => t.projectId), ['A', 'C'], 'each back where it was');+ tabs.open({ projectId: 'B' });+ tabs.close(tabs.byProject('B').id);+ tabs.open({ projectId: 'B' });+ assert.equal(tabs.reopen()?.projectId, 'B', 'a closed project open again already: brought forward');+});++test('saved and restored, moved; agents and exports keep a page from being let go', () => {+ let t = 0;+ const tabs = createTabs({ newId: ids(), now: () => t });+ tabs.open({ projectId: 'A', title: 'One' }); tabs.open({ projectId: 'B', title: 'Two' }); tabs.open({ projectId: 'C' });+ tabs.move(tabs.byProject('B').id, 0);+ assert.deepEqual(tabs.saved(), { tabs: [{ projectId: 'B', title: 'Two' }, { projectId: 'A', title: 'One' }, { projectId: 'C', title: '' }], active: 2 });+ const again = createTabs({ newId: ids(), saved: { tabs: [{ projectId: 'B' }, { projectId: 'B' }, { projectId: null }, { projectId: 'C' }], active: 9 } });+ assert.deepEqual(again.list().map((x) => [x.projectId, x.active]), [['B', false], ['C', true]], 'a project twice: once; none without a project; the active index kept in range');+ t = 10 * 60_000;+ tabs.setAgents(['A']);+ tabs.report(tabs.byProject('B').id, { exporting: 0.4 });+ assert.deepEqual(tabs.idle(5 * 60_000), [], 'A works, B exports, C is in front');+ tabs.setAgents([]);+ assert.deepEqual(tabs.idle(5 * 60_000), [tabs.byProject('A').id]);+ assert.equal(tabs.setAgents([], ['A']), true);+ assert.equal(tabs.list().find((x) => x.projectId === 'A').asking, true);+});diff --git a/apps/desktop/src/turn-log.test.mjs b/apps/desktop/src/turn-log.test.mjsnew file mode 100644index 0000000..1583b80--- /dev/null+++ b/apps/desktop/src/turn-log.test.mjs@@ -0,0 +1,100 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { AgentSession, INSTRUCTIONS, setChosenPaths } from './agents.mjs';+import { loggedBlocks, readLog, writeModelLog } from './chat-store.mjs';++/** An agent speaking ACP that keeps every prompt it is sent in `out`, one JSON line each. */+function fakeAgent(out) {+ const dir = mkdtempSync(join(tmpdir(), 'of-fake-agent-'));+ const file = join(dir, 'gemini.mjs');+ writeFileSync(file, `+import { appendFileSync } from 'node:fs';+import { Readable, Writable } from 'node:stream';+import * as acp from ${JSON.stringify(import.meta.resolve('@agentclientprotocol/sdk'))};+const connection = new acp.AgentSideConnection(() => ({+ async initialize() { return { protocolVersion: acp.PROTOCOL_VERSION, agentCapabilities: { promptCapabilities: { image: true } }, agentInfo: { name: 'fake', version: '1' }, authMethods: [] }; },+ async newSession() { return { sessionId: 'fake-session' }; },+ async prompt(params) { appendFileSync(${JSON.stringify(out)}, JSON.stringify({ argv: process.argv.slice(2), prompt: params.prompt }) + '\\n'); return { stopReason: 'end_turn' }; },+ async cancel() {},+}), acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));+await connection.closed;+`);+ return file;+}++test('the turn log has what the agent was started with and each message as it got it: the app\'s words before the first, no key\'s value', { timeout: 60_000 }, async () => {+ const out = join(mkdtempSync(join(tmpdir(), 'of-fake-out-')), 'prompts.jsonl');+ setChosenPaths({ gemini: fakeAgent(out) });+ const sent = [];+ const session = new AgentSession({+ agent: 'gemini',+ cwd: mkdtempSync(join(tmpdir(), 'of-project-')),+ binDir: '/app/bin',+ env: { OPENFILM_HOME: '/data', SOME_API_KEY: 'sk-secret' },+ onSend: (message) => sent.push(message),+ });+ try {+ await session.start();+ const opened = session.opened;+ assert.deepEqual(opened.command.slice(-3), ['--acp', '--approval-mode', 'yolo'], 'started as the registry starts it');+ assert.equal(opened.firstMessage, INSTRUCTIONS, 'an agent with no place for them is told in its first message');+ assert.equal(opened.env.OPENFILM_HOME, '/data');+ assert.equal(opened.env.SOME_API_KEY, '(hidden)', 'a key is named, never its value');+ assert.ok(!JSON.stringify(opened).includes('sk-secret'));+ assert.equal(opened.path.first, '/app/bin');+ assert.equal(opened.session.method, 'session/new');+ assert.deepEqual(opened.session.params.mcpServers, []);+ assert.equal(opened.initialize.response.agentInfo.name, 'fake');++ await session.prompt([{ type: 'text', text: 'Make a title' }]);+ await session.prompt([{ type: 'text', text: 'Shorter' }]);+ const got = readFileSync(out, 'utf8').trim().split('\n').map((l) => JSON.parse(l));+ assert.deepEqual(sent.map((m) => m.prompt), got.map((g) => g.prompt), 'logged exactly as the agent got it');+ assert.deepEqual(got[0].prompt, [{ type: 'text', text: INSTRUCTIONS }, { type: 'text', text: 'Make a title' }]);+ assert.deepEqual(got[1].prompt, [{ type: 'text', text: 'Shorter' }], 'told once');+ } finally {+ session.close();+ setChosenPaths({});+ }+});++test('in Developer mode an agent is started with its own logging switch, and the turn log says where it writes', { timeout: 60_000 }, async () => {+ const out = join(mkdtempSync(join(tmpdir(), 'of-fake-out-')), 'prompts.jsonl');+ setChosenPaths({ qwen: fakeAgent(out) });+ const logDir = mkdtempSync(join(tmpdir(), 'of-agent-logs-'));+ const session = new AgentSession({ agent: 'qwen', cwd: mkdtempSync(join(tmpdir(), 'of-project-')), logDir });+ try {+ await session.start();+ const { log, command } = session.opened;+ assert.equal(log.agent, 'qwen');+ assert.ok(log.dir.startsWith(join(logDir, 'qwen')));+ assert.deepEqual(command.slice(-6), ['--acp', '--approval-mode', 'yolo', '--openai-logging', '--openai-logging-dir', log.dir], 'its own flags, then the switch');+ await session.prompt([{ type: 'text', text: 'hi' }]);+ const [got] = readFileSync(out, 'utf8').trim().split('\n').map((l) => JSON.parse(l));+ assert.deepEqual(got.argv.slice(-3), ['--openai-logging', '--openai-logging-dir', log.dir]);+ } finally {+ session.close();+ setChosenPaths({});+ }+});++test('a message\'s pictures are kept in the logs by their content and named in its blocks; a turn\'s model log is written whole', () => {+ const project = mkdtempSync(join(tmpdir(), 'of-log-'));+ const data = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]).toString('base64');+ const blocks = loggedBlocks(project, [{ type: 'text', text: 'this one' }, { type: 'image', mimeType: 'image/jpeg', data }, { type: 'image', mimeType: 'image/jpeg', data }]);+ assert.deepEqual(blocks[0], { type: 'text', text: 'this one' });+ assert.match(blocks[1].file, /^\.film\/logs\/images\/[0-9a-f]{40}\.jpg$/);+ assert.equal(blocks[1].file, blocks[2].file, 'the same picture kept once');+ assert.equal(blocks[1].bytes, 7);+ assert.ok(!('data' in blocks[1]));+ assert.ok(existsSync(join(project, blocks[1].file)));++ const turn = 'local:t1';+ writeModelLog(project, turn, [{ startedAt: 1, ms: 2, prefix: 0, messages: [], answer: null }]);+ writeModelLog(project, turn, [{ startedAt: 3, ms: 4, prefix: 0, messages: [], answer: null }]);+ writeFileSync(join(project, '.film', 'logs', 'local-t1.jsonl'), `${JSON.stringify({ t: 0, kind: 'prompt' })}\n`);+ assert.deepEqual(readLog(project, turn).calls.map((c) => c.startedAt), [3], 'in place of the one before');+});diff --git a/apps/desktop/src/unprompted.test.mjs b/apps/desktop/src/unprompted.test.mjsnew file mode 100644index 0000000..dae838f--- /dev/null+++ b/apps/desktop/src/unprompted.test.mjs@@ -0,0 +1,40 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { isEmptyBackgroundTurn, opensUnprompted } from '../chat/src/lib/unprompted.ts';++test('the agent writing, thinking, starting a tool or planning opens a turn of its own', () => {+ for (const sessionUpdate of ['agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'plan']) {+ assert.equal(opensUnprompted({ sessionUpdate }), true, sessionUpdate);+ }+});++test('the late output and exit of a command from a turn already ended open no turn', () => {+ /* as Codex sent them 2.6 s after a stopped turn: `openfilm look` still running, then done */+ const late = [+ { sessionUpdate: 'tool_call_update', toolCallId: 'exec-1', _meta: { terminal_output_delta: { data: 'film 1920×1080\n' } } },+ { sessionUpdate: 'tool_call_update', toolCallId: 'exec-1', status: 'completed', _meta: { terminal_exit: { exit_code: 0 } } },+ ];+ for (const update of late) assert.equal(opensUnprompted(update), false);+});++test('lists, settings and usage open no turn', () => {+ for (const sessionUpdate of ['available_commands_update', 'session_info_update', 'usage_update', 'config_option_update', undefined]) {+ assert.equal(opensUnprompted({ sessionUpdate }), false, String(sessionUpdate));+ }+});++test('a background turn that ended with nothing in it is empty', () => {+ assert.equal(isEmptyBackgroundTurn({ origin: 'background', status: 'ready', error: null }, []), true);+ assert.equal(isEmptyBackgroundTurn({ origin: 'background', status: 'cancelled' }, []), true);+});++test('a background turn with something in it, still running, or failed is kept', () => {+ assert.equal(isEmptyBackgroundTurn({ origin: 'background', status: 'ready' }, [{ type: 'text' }]), false);+ assert.equal(isEmptyBackgroundTurn({ origin: 'background', status: 'generating' }, []), false);+ assert.equal(isEmptyBackgroundTurn({ origin: 'background', status: 'error', error: 'OpenFilm closed while the agent was working on this.' }, []), false);+});++test('a turn the person started is never dropped, even with nothing in it', () => {+ assert.equal(isEmptyBackgroundTurn({ status: 'cancelled' }, []), false);+ assert.equal(isEmptyBackgroundTurn({ status: 'ready' }, []), false);+});diff --git a/apps/desktop/src/window-state.mjs b/apps/desktop/src/window-state.mjsindex c9547cd..d36417d 100644--- a/apps/desktop/src/window-state.mjs+++ b/apps/desktop/src/window-state.mjs@@ -1,5 +1,6 @@/**- * What the window looked like when it was last closed: where it was, how wide the chat was, whether it was shown.+ * What the window looked like when it was last closed: where it was, how wide the chat was, whether it was shown,+ * which tabs were open.* Kept in the app's data folder. Reads no Electron module, so `node --test` can use it.*/import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';@@ -25,6 +26,8 @@ export function readWindowState(dir) {maximized: raw.maximized === true,chatWidth: finite(raw.chatWidth) ? Math.max(CHAT_MIN, Math.round(raw.chatWidth)) : CHAT_DEFAULT,chatOpen: raw.chatOpen !== false,+ /* the tabs as left (tabs.mjs reads them with care) */+ tabs: raw.tabs && typeof raw.tabs === 'object' && Array.isArray(raw.tabs.tabs) ? { tabs: raw.tabs.tabs.slice(0, 50), active: Number(raw.tabs.active) || 0 } : null,};}diff --git a/apps/desktop/src/window-state.test.mjs b/apps/desktop/src/window-state.test.mjsindex a0bb720..8b7e6ea 100644--- a/apps/desktop/src/window-state.test.mjs+++ b/apps/desktop/src/window-state.test.mjs@@ -7,11 +7,12 @@ import { CHAT_DEFAULT, CHAT_MIN, placeOnDisplays, readWindowState, writeWindowSttest('a first launch has the defaults; a saved state comes back; odd values are made sensible', () => {const dir = mkdtempSync(join(tmpdir(), 'of-window-'));- assert.deepEqual(readWindowState(dir), { bounds: null, maximized: false, chatWidth: CHAT_DEFAULT, chatOpen: true });- writeWindowState(dir, { bounds: { x: 10, y: 20, width: 1400, height: 900 }, maximized: false, chatWidth: 500, chatOpen: false });- assert.deepEqual(readWindowState(dir), { bounds: { x: 10, y: 20, width: 1400, height: 900 }, maximized: false, chatWidth: 500, chatOpen: false });- writeFileSync(join(dir, 'window.json'), JSON.stringify({ bounds: { x: 0, y: 0, width: 10, height: 'tall' }, chatWidth: 12 }));- assert.deepEqual(readWindowState(dir), { bounds: null, maximized: false, chatWidth: CHAT_MIN, chatOpen: true });+ assert.deepEqual(readWindowState(dir), { bounds: null, maximized: false, chatWidth: CHAT_DEFAULT, chatOpen: true, tabs: null });+ const tabs = { tabs: [{ projectId: 'a', title: 'Launch' }, { projectId: null, title: '' }], active: 1 };+ writeWindowState(dir, { bounds: { x: 10, y: 20, width: 1400, height: 900 }, maximized: false, chatWidth: 500, chatOpen: false, tabs });+ assert.deepEqual(readWindowState(dir), { bounds: { x: 10, y: 20, width: 1400, height: 900 }, maximized: false, chatWidth: 500, chatOpen: false, tabs });+ writeFileSync(join(dir, 'window.json'), JSON.stringify({ bounds: { x: 0, y: 0, width: 10, height: 'tall' }, chatWidth: 12, tabs: 'many' }));+ assert.deepEqual(readWindowState(dir), { bounds: null, maximized: false, chatWidth: CHAT_MIN, chatOpen: true, tabs: null });});test('a window off every display comes back centered, keeping its size', () => {diff --git a/package.json b/package.jsonindex b25bbf7..fccc861 100644--- a/package.json+++ b/package.json@@ -16,7 +16,9 @@"typecheck": "pnpm -r --if-present typecheck","audit:public": "node scripts/audit-public.mjs","check:pack": "node scripts/check-pack.mjs",- "changeset": "changeset"+ "skills:sync": "node scripts/sync-skills.mjs",+ "changeset": "changeset",+ "examples:sync": "node scripts/sync-examples.mjs"},"devDependencies": {"@changesets/changelog-github": "0.5.2",diff --git a/packages/openfilm/MANUAL.md b/packages/openfilm/MANUAL.mdindex 6569e5a..dc49973 100644--- a/packages/openfilm/MANUAL.md+++ b/packages/openfilm/MANUAL.md@@ -78,6 +78,7 @@ Run them in the film's folder. Each one's `--help` lists its options:- `npx openfilm look`: a contact sheet of the whole film with its sound, and a check that the same t draws the same picture. `look 4.5` is one frame at full size, `look 3-6` a stretch, `look assets/a.mp4` a media file.- `npx openfilm render`: the MP4, beside film.html (30 fps unless `--fps`). Only when the person asks for the file: you check with `look`, and the person exports from Studio.- `npx openfilm get`: voice-over, music, sound effects, transcripts, images, image search, video and web search. Each kind works only once the person has connected a service that makes it, with their own key, in Studio (Settings → Providers); Studio's subtitle translation too. Run it alone to see what works now and which services make the rest. When a kind is not connected, tell the person which services make it and where they connect one. A video clip costs a lot: the person confirms it in Studio first.+- `npx openfilm skills`: the skills this film can be made with, each a way of making a kind of film. When the person names one, or one fits what they ask, `npx openfilm skill <name>` prints it: read it whole and follow it. Its folder is only read: copy what the film uses into the project.The words of a sound or a video are a WebVTT beside it with the same name (`vo/1.wav` → `vo/1.vtt`): a cue per subtitle line, a timestamp tag at each word. Studio makes the film's subtitles from them; never draw subtitles in a page.diff --git a/packages/openfilm/README.md b/packages/openfilm/README.mdindex 255be36..9f4e3a3 100644--- a/packages/openfilm/README.md+++ b/packages/openfilm/README.md@@ -4,7 +4,7 @@ The open source AI video agent: films as web pages, the manual that teaches your`openfilm` command, and Studio, the editor to change anything in them.Ask Codex, Claude Code or any coding agent to make a film. It writes the film as web pages (`film.html` cuts them-together with footage, pictures and sound), and Studio, a local editor in your browser, shows it taking shape. Then+together with footage, pictures and sound), and Studio, a local editor in your browser (Chrome or Edge: films are drawn with Chromium), shows it taking shape. Thenchange anything you like, by hand or by asking.## Install@@ -26,6 +26,7 @@ openfilm open [folder | url] # show a film in Studio (a GitHub address fetcopenfilm look [what] [t | a-b] # check the film, a page or a media fileopenfilm render [a-b] # the MP4; --4k, --blur, --alphaopenfilm get [what] # voice-over, music, sound effects, transcripts, images, video, from your services+openfilm capture <url> <file.png> # a picture of a live web page, to show a product as it is````MANUAL.md` (in this package) is what `openfilm` tells your agent, and `SPEC.md` is the film format, for anyonediff --git a/packages/openfilm/SPEC.md b/packages/openfilm/SPEC.mdindex 9979835..d73e5b3 100644--- a/packages/openfilm/SPEC.md+++ b/packages/openfilm/SPEC.md@@ -75,7 +75,8 @@ where, and CSS that says how each looks. A page draws a shot.- `overrides` are the person's changes made in Studio, as JSON, a list of entries. An entry with `at` (a CSSselector), on a page clip only, tweaks an element of the page, applied by the host after each frame: optional `n`(which match, from 1), `t` (translate px), `s` (scale), `r` (rotate degrees) as the independent CSS transform- properties so they compose with the page's own animation, `style` (CSS properties, applied with priority), `text`+ properties so they compose with the page's own animation, `style` (CSS properties, camelCase or custom+ `--name`, applied with priority), `text`(replaces the element's own text: all of it when it has no child elements or only `<br>`s, a line break in `text`being a `<br>`; with other inline children, its first run of text, the children kept), `lock` (`true`: an editor keeps the element from being selected or moved; it changesnothing in the picture). An entry without `at`, at most one, on any clip, is the clip's own: `fade: [in, out]`,diff --git a/packages/openfilm/bin/openfilm.mjs b/packages/openfilm/bin/openfilm.mjsindex b0bcb39..200862b 100755--- a/packages/openfilm/bin/openfilm.mjs+++ b/packages/openfilm/bin/openfilm.mjs@@ -3,10 +3,13 @@ import { parseArgs } from 'node:util';const USAGE = `openfilm — a film is a function of time: given t, it draws that moment- openfilm open [folder | url] start or open a project; Studio shows it to the person- openfilm look [what] [t | a-b] check the film and draw it: a contact sheet with its sound and loudness- openfilm render [a-b] the MP4, saved beside film.html- openfilm get [what] [--options] voice-over, music, sound effects, transcripts, images, video, from a connected service+ openfilm open [folder | url] start or open a project; Studio shows it to the person+ openfilm look [what] [t | a-b] check the film and draw it: a contact sheet with its sound and loudness+ openfilm render [a-b] the MP4, saved beside film.html+ openfilm get [what] [--options] voice-over, music, sound effects, transcripts, images, video, from a connected service+ openfilm capture <url> <file.png> a picture of a live web page, to show a product or a site as it is+ openfilm skills the skills this film can be made with; \`openfilm skill <name>\` prints one+ openfilm update the newest OpenFilm; Studio starts again on itRun with no arguments for the manual; \`openfilm <command> --help\` for one command's options; --version for the version.look, render and get work on the project around the current folder.@@ -28,6 +31,27 @@ const COMMAND_HELP = {Starts OpenFilm Studio if it is not running and prints its address. A Studio page already open, in any browser,switches to the project, and nothing more opens; otherwise open the address in your built-in browser, and if nopage connects within 15 s, Studio opens the person's browser (OPENFILM_NO_BROWSER=1: never).`,+ skills: `openfilm skills++ The skills the project around the current folder can be made with: ways of making a kind of film, each a folder with+ a SKILL.md (its name, what it is for, how to work) and the files it brings. Looked for in the project's skills/,+ then yours (Skills/ beside the projects, ~/Movies/OpenFilm/Skills on macOS), then the official ones; the first+ holding a name wins.`,+ skill: `openfilm skill <name>+openfilm skill add <GitHub address | folder>+openfilm skill remove <name>++ <name> print the skill: where its files are, and its SKILL.md whole+ add add a skill (or a folder of skills) to yours: a folder on this computer, or a repository or a folder in one+ on github.com or gitlab.com, fetched without its git history. One of the same name goes to the trash.+ remove move one of yours to the trash, where you can take it back++ Yours are kept in Skills/ beside the projects (~/Movies/OpenFilm/Skills on macOS; OPENFILM_SKILLS names another).`,+ update: `openfilm update++ The newest OpenFilm from npm, and Studio started again on it once nothing is being exported or made; pages open on+ it come back on the new version. The desktop app's Studio updates with the app, a source checkout with git pull:+ each is said instead.`,look: `openfilm look [what] [t | a-b]what the project (default), a web page (.html), or a media file (video, image, sound)@@ -51,6 +75,19 @@ const COMMAND_HELP = {--4k 3840 px wide --scale <n> any device pixel ratio--blur motion blur (8 samples) --samples <n> --shutter <0..1>--alpha transparent background --workers <n> parallel browsers`,+ capture: `openfilm capture <url> <file.png>++ A picture of a live web page (a product, a site) as it is, sharp enough to fill the stage, taken in the browser+ OpenFilm draws films in: nothing to install. Prints the picture's path and its size in pixels.++ --size <w>x<h> the window, in px (1440x900; a phone: 390x844)+ --scale <n> pixels per px (2)+ --full the whole page, top to bottom, for a scroll in the film+ --selector <css> only this element (a panel, a card)+ --click <css> click it first (a tab, a menu); give it again for more, in order+ --hide <css> remove it first (a cookie banner, a chat bubble); give it again for more+ --dark the page in its dark theme+ --wait <ms> time for the page to settle before the picture (1500)`,};/* `openfilm` alone: the manual, the whole of what an agent needs to know. `get` takes any options its verb has,@@ -66,7 +103,7 @@ const RUN = process.env.OPENFILM_RUN || (process.env.npm_command === 'exec' ? 'n*/const updateNotice = async (network) => {const latest = await (await import('../studio/client.mjs')).newerOpenfilm({ network }).catch(() => null);- if (latest) console.error(`openfilm ${latest} is out (this is an older one): run commands as \`npx -y openfilm@latest …\` to use it; it updates Studio too.`);+ if (latest) console.error(`openfilm ${latest} is out (this is an older one): \`${RUN} update\` updates it, and Studio with it.`);};if (RAW.length === 0) {const { readFileSync } = await import('node:fs');@@ -79,7 +116,7 @@ if (RAW.length === 1 && (RAW[0] === '--version' || RAW[0] === '-v')) {console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);process.exit(0);}-await updateNotice(RAW[0] === 'open');+if (RAW[0] !== 'update') await updateNotice(RAW[0] === 'open');if (RAW[0] === 'get') {let result;try { result = await (await import('../studio/client.mjs')).getMedia(RAW.slice(1), (line) => console.error(line)); }@@ -98,6 +135,8 @@ try {count: { type: 'string' }, out: { type: 'string', short: 'o' }, '4k': { type: 'boolean' }, scale: { type: 'string' },blur: { type: 'boolean' }, samples: { type: 'string' }, shutter: { type: 'string' }, alpha: { type: 'boolean' },fps: { type: 'string' }, workers: { type: 'string' }, help: { type: 'boolean', short: 'h' },+ size: { type: 'string' }, full: { type: 'boolean' }, wait: { type: 'string' }, dark: { type: 'boolean' },+ click: { type: 'string', multiple: true }, hide: { type: 'string', multiple: true }, selector: { type: 'string' },},});} catch (e) {@@ -124,6 +163,10 @@ const commands = {open: () => open(args[0] ?? null),look: () => import('../src/look.mjs').then((m) => m.look(args, opts)),render: () => import('../src/render.mjs').then((m) => m.render(args, opts)),+ capture: () => import('../src/capture.mjs').then((m) => m.capture(args, opts)),+ update: () => import('../studio/client.mjs').then((m) => m.updateOpenfilm((line) => console.error(line))),+ skills: () => import('../src/skills-cli.mjs').then((m) => m.skillsCommand(RUN)),+ skill: () => import('../src/skills-cli.mjs').then((m) => m.skillCommand(args, RUN)),};/*** Show a project in Studio; `.film/opened` marks a project Studio has shown. A folder named is made a project when it isdiff --git a/packages/openfilm/examples-index/SOURCE b/packages/openfilm/examples-index/SOURCEnew file mode 100644index 0000000..b385bf7--- /dev/null+++ b/packages/openfilm/examples-index/SOURCE@@ -0,0 +1,2 @@+https://github.com/openfilm/examples/commit/2e8f47866bc2d32305cd5d97adcffd7480df2297+Copied by `pnpm examples:sync`. Change the examples in https://github.com/openfilm/examples, not here.diff --git a/packages/openfilm/examples-index/examples.json b/packages/openfilm/examples-index/examples.jsonnew file mode 100644index 0000000..39b0c21--- /dev/null+++ b/packages/openfilm/examples-index/examples.json@@ -0,0 +1,20 @@+{+ "repo": "https://github.com/openfilm/examples",+ "branch": "main",+ "examples": [+ {+ "folder": "one-prompt",+ "title": "One Prompt",+ "description": "A 90-second lyric music video where every frame is code.",+ "poster": "one-prompt/look.jpg",+ "duration": "1:31"+ },+ {+ "folder": "openfilm-intro",+ "title": "OpenFilm intro",+ "description": "The 1:42 film that introduces OpenFilm, made with OpenFilm: footage, app recordings and motion graphics cut to a Chinese voice-over.",+ "poster": "openfilm-intro/look.jpg",+ "duration": "1:42"+ }+ ]+}diff --git a/packages/openfilm/examples-index/one-prompt/look.jpg b/packages/openfilm/examples-index/one-prompt/look.jpgnew file mode 100644index 0000000..264c85fBinary files /dev/null and b/packages/openfilm/examples-index/one-prompt/look.jpg differdiff --git a/packages/openfilm/examples-index/openfilm-intro/look.jpg b/packages/openfilm/examples-index/openfilm-intro/look.jpgnew file mode 100644index 0000000..189062eBinary files /dev/null and b/packages/openfilm/examples-index/openfilm-intro/look.jpg differdiff --git a/packages/openfilm/package.json b/packages/openfilm/package.jsonindex 9326de6..311a7ea 100644--- a/packages/openfilm/package.json+++ b/packages/openfilm/package.json@@ -31,6 +31,8 @@"./shared": "./src/shared.mjs","./look": "./src/look.mjs","./render": "./src/render.mjs",+ "./skills": "./src/skills.mjs",+ "./skills-cli": "./src/skills-cli.mjs","./studio": "./studio/server/server.mjs","./studio-ui/*": "./studio/ui/src/*","./package.json": "./package.json"@@ -41,6 +43,7 @@"TRADEMARK.md","bin","skills",+ "examples-index","src","!src/*.test.mjs","MANUAL.md",diff --git a/packages/openfilm/scripts/dev.mjs b/packages/openfilm/scripts/dev.mjsindex f879b1b..b584cbe 100644--- a/packages/openfilm/scripts/dev.mjs+++ b/packages/openfilm/scripts/dev.mjs@@ -17,8 +17,12 @@ import { fileURLToPath } from 'node:url';const ROOT = fileURLToPath(new URL('..', import.meta.url));const DEV = join(ROOT, '.dev');+/* the official skills from a checkout of openfilm/skills beside this repository, when there is one, so a change to a+ skill shows at once; without one, the copy this package releases */+const SKILLS = join(ROOT, '..', '..', '..', 'skills', 'skills');const env = {...process.env,+ ...(existsSync(SKILLS) && !process.env.OPENFILM_OFFICIAL_SKILLS ? { OPENFILM_OFFICIAL_SKILLS: SKILLS } : {}),OPENFILM_HOME: join(DEV, 'home'),OPENFILM_LIBRARY: join(DEV, 'projects'),OPENFILM_EXPORTS: join(DEV, 'exports'),@@ -48,7 +52,7 @@ process.on('exit', () => {const BIN = join(DEV, 'bin');mkdirSync(BIN, { recursive: true });const CLI = join(ROOT, 'bin', 'openfilm.mjs');-const SHARED = ['OPENFILM_HOME', 'OPENFILM_LIBRARY', 'OPENFILM_EXPORTS', 'OPENFILM_STUDIO_PORT', 'OPENFILM_NO_UPDATE_CHECK'];+const SHARED = ['OPENFILM_HOME', 'OPENFILM_LIBRARY', 'OPENFILM_EXPORTS', 'OPENFILM_STUDIO_PORT', 'OPENFILM_NO_UPDATE_CHECK', 'OPENFILM_OFFICIAL_SKILLS'].filter((k) => env[k]);const sh = join(BIN, 'openfilm');writeFileSync(sh, `#!/bin/sh\n${SHARED.map((k) => `export ${k}='${env[k]}'`).join('\n')}\nOPENFILM_RUN="${sh}" exec '${process.execPath}' '${CLI}' "$@"\n`);chmodSync(sh, 0o755);diff --git a/packages/openfilm/skills/SOURCE b/packages/openfilm/skills/SOURCEnew file mode 100644index 0000000..8b79ec7--- /dev/null+++ b/packages/openfilm/skills/SOURCE@@ -0,0 +1,2 @@+https://github.com/openfilm/skills/commit/702f16944c14d64a87fc5149cb865bd5c95c895f+Copied by `pnpm skills:sync`. Change the skills in https://github.com/openfilm/skills, not here.diff --git a/packages/openfilm/skills/collage/SKILL.md b/packages/openfilm/skills/collage/SKILL.mdnew file mode 100644index 0000000..d082e0a--- /dev/null+++ b/packages/openfilm/skills/collage/SKILL.md@@ -0,0 +1,34 @@+---+name: collage+description: Make motion graphics in a cut-paper collage style, with photos, paper and print cut out and put together by hand. Use for explainers, promos, stories, intros and social posts, or when the person asks for a collage, cut-paper, scrapbook, zine or mixed-media look (剪贴风, 拼贴, 手账风, 杂志拼贴).+---++# Collage++Make a collage film an art director would sign: pictures cut from real material and put together by hand, so that what+they make together says what none of them says alone. Surprise us; the expected version is not the goal.++## What has to be true++- **Every piece says something.** Each picture, word and scrap is there for what it means in this film, not to fill+ space. If the same pieces could tell another story, it is not done yet.+- **Every picture's source is clear**: the person's own, licensed, public domain, or made for this film. A made one is+ never passed off as a real person, place or record.+- **People as they are**: their photos are cut, cropped, colored and printed, never their faces changed.+- **Words spelled right**, and readable, in the titles, labels and clippings.+- **It holds up next to the best collage work you know.** Watch the whole film as a viewer would, and keep refining+ until it does.++## What you have++Anything you can make pictures and motion with: the web platform and any library on it, Blender or any renderer whose+output becomes a clip, the person's photos and scans, any font whose license allows it, images and image search from+`npx openfilm get`, your own built-in tools, and services the person has keys for. OpenFilm's own rules still hold: the+picture at t depends on t alone, a page has no sound, and what you render elsewhere enters as a clip under `assets/`+with the script that made it. Ask before downloading anything large onto the person's computer.++## With the person++What they ask for comes before anything here. What it is about, their photos and material (a photo of a ticket, a note+or a page counts), and where it will be shown. Ask without holding up the work. When done, tell them in a few lines+the idea, where each picture came from, and what of theirs would make it better.diff --git a/packages/openfilm/skills/collage/cover.jpg b/packages/openfilm/skills/collage/cover.jpgnew file mode 100644index 0000000..439e331Binary files /dev/null and b/packages/openfilm/skills/collage/cover.jpg differdiff --git a/packages/openfilm/skills/collage/openfilm.json b/packages/openfilm/skills/collage/openfilm.jsonnew file mode 100644index 0000000..6714829--- /dev/null+++ b/packages/openfilm/skills/collage/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/collage",+ "kind": "style",+ "order": 10,+ "icon": "layers",+ "cover": "cover.jpg",+ "title": {+ "en": "Cut-paper collage",+ "zh-CN": "剪贴风 MG",+ "ja": "切り貼りコラージュ",+ "ko": "콜라주 모션그래픽",+ "es": "Collage de papel"+ },+ "summary": {+ "en": "Motion graphics made of photos, paper and print, cut out and put together by hand.",+ "zh-CN": "用照片、纸张和印刷品剪下来、亲手拼成的 MG 动画。",+ "ja": "写真や紙、印刷物を切り抜き、手で組み合わせてつくるモーショングラフィックス。",+ "ko": "사진, 종이, 인쇄물을 오려 손으로 붙여 만든 모션그래픽.",+ "es": "Motion graphics hechos con fotos, papel e impresos, recortados y unidos a mano."+ },+ "details": {+ "zh-CN": "适合:讲解、宣传、故事短片、片头和社媒帖子,想要手作感的时候。\n它会:把图片剪开、拼在一起,让组合本身说出意思;每张图的来源清楚,你照片里的人不被改动。",+ "en": "Best for: explainers, promos, stories, intros and posts that want a hand-made feel.\nWhat it does: cuts and combines pictures so that together they say something, with every picture’s source clear and the people in your photos unchanged.",+ "ja": "こんなときに:解説、プロモ、ストーリー、オープニング、SNS投稿で手作り感がほしいとき。\nすること:写真を切り抜いて組み合わせ、組み合わせそのものに意味を語らせます。どの写真も出どころがはっきりしていて、あなたの写真の人物は変えません。",+ "ko": "이럴 때: 손맛이 필요한 설명, 홍보, 스토리, 인트로, SNS 게시물.\n하는 일: 사진을 오리고 붙여 조합 자체가 의미를 말하게 합니다. 모든 사진의 출처가 분명하고, 당신 사진 속 사람은 바꾸지 않습니다.",+ "es": "Ideal para: explicativos, promos, historias, intros y publicaciones con aire artesanal.\nQué hace: recorta y combina imágenes para que juntas digan algo, con el origen de cada imagen claro y sin cambiar a las personas de tus fotos."+ }+}diff --git a/packages/openfilm/skills/keynote/SKILL.md b/packages/openfilm/skills/keynote/SKILL.mdnew file mode 100644index 0000000..a45dee3--- /dev/null+++ b/packages/openfilm/skills/keynote/SKILL.md@@ -0,0 +1,35 @@+---+name: keynote+description: Make a product film in the style of a big tech launch keynote: the real product on stage, one confident claim at a time. Use for app, website, software and gadget launches, feature announcements and product intros, or when the person asks for a keynote, launch event, premium or minimal tech style (发布会, 产品发布, 新品, 高级感).+---++# Keynote++Make the launch film this product deserves: the real product on stage, each moment making one claim and showing the+proof, so the viewer leaves knowing what it is and wanting it. Surprise us; the expected version is not the goal.++## What has to be true++- **The real product.** Its own screens, words, name and logo, from the person or captured from the live product; never+ a redrawn interface. Where a screen must be simpler, crop and zoom into the real one.+- **Every claim true.** What is shown has shipped, or is said to be coming; numbers, comparisons, customers, prices and+ dates come from the person or the product's own pages, never made up. A demo sped up or put together says so.+- **One claim at a time**, with its proof on screen, readable at the size it will be watched.+- **It holds up next to the best launch films you know.** Watch the whole film as a viewer would, and keep refining+ until it does. If it could launch another product, it is not done yet.+- **It stays editable**: the person can change any word later.++## What you have++OpenFilm's own headless browser captures the live product with nothing to install: `npx openfilm capture --help`.+Anything you can make pictures and motion with: the web platform and any library on it, Blender or any renderer whose+output becomes a clip, any font whose license allows it, music and sound from `npx openfilm get`, your own built-in+tools, and services the person has keys for. OpenFilm's own rules still hold: the picture at t depends on t alone, a+page has no sound, and what you render elsewhere enters as a clip under `assets/` with the script that made it. Ask+before downloading anything large onto the person's computer.++## With the person++What they ask for comes before anything here. The product (its address, screenshots or recordings, its logo), what is+new, and where the film will be shown. A fact you do not have is a question, or left out. When done, tell them in a few+lines what you made, where every claim came from, and what of theirs would make it better.diff --git a/packages/openfilm/skills/keynote/cover.jpg b/packages/openfilm/skills/keynote/cover.jpgnew file mode 100644index 0000000..02ac936Binary files /dev/null and b/packages/openfilm/skills/keynote/cover.jpg differdiff --git a/packages/openfilm/skills/keynote/openfilm.json b/packages/openfilm/skills/keynote/openfilm.jsonnew file mode 100644index 0000000..b278385--- /dev/null+++ b/packages/openfilm/skills/keynote/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/keynote",+ "kind": "style",+ "order": 9,+ "icon": "presentation",+ "cover": "cover.jpg",+ "title": {+ "en": "Keynote",+ "zh-CN": "发布会风格",+ "ja": "発表会スタイル",+ "ko": "발표회 스타일",+ "es": "Estilo keynote"+ },+ "summary": {+ "en": "A launch film like a big tech keynote: your real product on stage, one claim at a time.",+ "zh-CN": "像科技大厂发布会那样介绍产品:真实的产品上台,一次只讲一件事。",+ "ja": "大手テック企業の発表会のような紹介動画。実際の製品がステージに立ち、一度にひとつだけ伝えます。",+ "ko": "빅테크 발표회 같은 출시 영상: 실제 제품이 무대에 오르고, 한 번에 하나씩 말합니다.",+ "es": "Un vídeo de lanzamiento como una gran keynote: tu producto real en el escenario, una idea cada vez."+ },+ "details": {+ "zh-CN": "适合:App、网站、软件、硬件的发布片和产品介绍。\n它会:先拿到产品的真实界面(截图或录屏,绝不重画),每个时刻只讲一个卖点并拿出证明;数字和说法都来自你或产品官网,不编造。",+ "en": "Best for: launch films and intros for apps, websites, software and gadgets.\nWhat it does: gets your product’s real screens first (screenshots or recordings, never redrawn) and gives each moment one claim with its proof. Every number and claim comes from you or your product’s own pages.",+ "ja": "こんなときに:アプリ、Webサイト、ソフト、ハードウェアの発表動画や紹介。\nすること:まず製品の実際の画面(スクリーンショットや収録。描き直しはしません)を用意し、各場面でひとつの主張とその証拠を見せます。数字や主張はすべて、あなたか製品の公式ページから。",+ "ko": "이럴 때: 앱, 웹사이트, 소프트웨어, 하드웨어의 출시 영상과 제품 소개.\n하는 일: 먼저 제품의 실제 화면(스크린샷이나 녹화, 다시 그리지 않음)을 가져오고, 장면마다 하나의 주장과 그 증거를 보여 줍니다. 숫자와 주장은 모두 당신이나 제품 공식 페이지에서 가져옵니다.",+ "es": "Ideal para: vídeos de lanzamiento y presentaciones de apps, webs, software y dispositivos.\nQué hace: primero obtiene las pantallas reales de tu producto (capturas o grabaciones, nunca redibujadas) y da a cada momento una idea con su prueba. Cada cifra y afirmación viene de ti o de las páginas de tu producto."+ }+}diff --git a/packages/openfilm/skills/long-to-short/SKILL.md b/packages/openfilm/skills/long-to-short/SKILL.mdnew file mode 100644index 0000000..31df2be--- /dev/null+++ b/packages/openfilm/skills/long-to-short/SKILL.md@@ -0,0 +1,36 @@+---+name: long-to-short+description: Turn a long video (a talk, podcast, interview, lesson, livestream or vlog) into short vertical clips that each stand alone and hold attention from the first second. Use when the person gives a long recording and asks for clips, shorts, highlights or cut-downs for Douyin, Reels, Shorts or similar (长视频转短视频, 切片, 剪短视频, 高光, 拆条).+---++# Long video to shorts++Find the moments in this recording that people would stop scrolling for, and make each one a short a channel would post+as it is: it opens on its strongest real line, ends on its point, and makes sense to someone who never saw the long+video. The speaker, watching it, would say: yes, that is what I meant.++## What has to be true++- **The speaker's meaning, intact.** Nothing said in different places is joined into a claim they did not make; an+ "if", a "not" or an "in some cases" is never cut away; an answer keeps its question. A title or any other text on+ screen says only what the recording says, or is plainly yours.+- **It stands alone**: a viewer knows who is speaking and what they are answering.+- **Every word exact.** The transcript says exactly what was said; names, numbers and terms you cannot confirm are named+ in your reply. Each cut falls in a pause: no clip starts on a clipped word or stops mid-thought.+- **Made for a phone**: the one who is speaking well framed at every moment, and nothing that matters where the app's+ buttons and captions sit.+- **Worth posting**: each one holds up next to the best clips on the platform, as long as its moment needs and no+ longer. Watch each as a viewer would; a clip you would scroll past is not done.++## What you have++The recording's transcript with every word's time (`npx openfilm get asr`, a WebVTT beside it), from which Studio draws+the subtitles; the person sets how they look. A short is the same recording trimmed (`#t=`) and framed with CSS, never+cut or re-encoded into new files; a page can also play the recording, silent, with its time set from t, when the+picture has to move over it. Anything you can make titles and motion with, and your own built-in tools.++## With the person++What they ask for comes before anything here. The recording, where the shorts will go, and how many they want (else the+few best). Ask whether there are moments they must keep or must not use, without holding up the work. When done, list+the shorts: for each, its length, its first line, and why you chose it.diff --git a/packages/openfilm/skills/long-to-short/cover.jpg b/packages/openfilm/skills/long-to-short/cover.jpgnew file mode 100644index 0000000..cd27b4dBinary files /dev/null and b/packages/openfilm/skills/long-to-short/cover.jpg differdiff --git a/packages/openfilm/skills/long-to-short/openfilm.json b/packages/openfilm/skills/long-to-short/openfilm.jsonnew file mode 100644index 0000000..d5861cf--- /dev/null+++ b/packages/openfilm/skills/long-to-short/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/long-to-short",+ "kind": "workflow",+ "order": 2,+ "icon": "scissors",+ "cover": "cover.jpg",+ "title": {+ "en": "Long video to shorts",+ "zh-CN": "长视频转短视频",+ "ja": "長尺動画をショートに",+ "ko": "긴 영상을 쇼츠로",+ "es": "De vídeo largo a cortos"+ },+ "summary": {+ "en": "A talk, podcast or livestream cut into vertical clips that each stand alone and hook from the first second.",+ "zh-CN": "把讲座、播客、直播这类长视频,切成一条条能单独发的竖版短视频,开头就抓人。",+ "ja": "講演、ポッドキャスト、配信を、それぞれ単体で見られる縦型ショートに。最初の一秒から引き込みます。",+ "ko": "강연, 팟캐스트, 라이브를 각각 따로 올릴 수 있는 세로 쇼츠로. 첫 순간부터 붙잡습니다.",+ "es": "Una charla, un pódcast o un directo en clips verticales que funcionan solos y enganchan desde el primer segundo."+ },+ "details": {+ "zh-CN": "适合:讲座、播客、访谈、直播、课程这类长视频。\n它会:从整段里挑出最值得分享的时刻,切成一条条能单独发布的竖版短视频;开头就抓人,结尾落在要点上,不断章取义,字幕来自原声。",+ "en": "Best for: talks, podcasts, interviews, livestreams and lessons.\nWhat it does: finds the moments most worth sharing across the whole recording and cuts each into a vertical short that stands alone, hooking from the start, ending on its point, never changing what the speaker meant, with captions from the speech.",+ "ja": "こんなときに:講演、ポッドキャスト、インタビュー、配信、授業などの長い動画。\nすること:全体から共有したくなる瞬間を選び、それぞれ単独で見られる縦型ショートに。冒頭で引き込み、要点で終わり、話し手の意図は変えません。字幕は音声から作ります。",+ "ko": "이럴 때: 강연, 팟캐스트, 인터뷰, 라이브, 강의 같은 긴 영상.\n하는 일: 전체에서 공유할 만한 순간을 골라 각각 따로 올릴 수 있는 세로 쇼츠로 자릅니다. 첫 순간에 붙잡고 요점에서 끝나며, 말한 사람의 뜻은 바꾸지 않습니다. 자막은 음성에서 만듭니다.",+ "es": "Ideal para: charlas, pódcasts, entrevistas, directos y clases.\nQué hace: encuentra los momentos que más vale la pena compartir y corta cada uno en un vertical que funciona solo: engancha desde el inicio, termina en su idea, nunca cambia lo que quiso decir quien habla y lleva subtítulos de la voz."+ }+}diff --git a/packages/openfilm/skills/lyric-video/SKILL.md b/packages/openfilm/skills/lyric-video/SKILL.mdnew file mode 100644index 0000000..ca5f084--- /dev/null+++ b/packages/openfilm/skills/lyric-video/SKILL.md@@ -0,0 +1,37 @@+---+name: lyric-video+description: Make a lyric video for a song that the artist would release as the official one — a piece made for this one song, every word landing exactly on the voice. Use when the person gives a song (with its lyrics or an .lrc file) and asks for a lyric video, a music video with words, karaoke-style lyrics or a song post (歌词视频, 动态歌词, 歌词 MV, 卡拉OK).+---++# Lyric video++You are the director this song has been waiting for. Make its lyric video: the one the artist releases as the official+video, that people play again and send to friends because of how it makes the song feel. It belongs to this song and+no other. Surprise us; the expected version is not the goal.++In a lyric video the sung words are the heart of the picture: they live in the image and move with the voice. Lyrics+shown as subtitles are not a lyric video.++## What has to be true++- **The words live on the voice.** Each word arrives the moment it is sung, within two frames. Measure it against the+ audio, check it independently of whatever made the times, and report honestly, in numbers, how close it is.+- **The lyrics are the person's**, word for word and line for line, in their language.+- **It holds up next to the best lyric videos you know.** Watch the whole film as a viewer would, and keep refining+ until it does. If the same film could carry any other song, it is not done yet.+- **It stays editable**: the person can change a word or a time later.++## What you have++Anything you can make pictures and motion with: the web platform and any library on it, Blender or any renderer whose+output becomes a clip, the person's footage and photos, any font whose license allows it, images, video and sound from+`npx openfilm get`, your own built-in tools, services the person has keys for, and the song itself to analyse.+OpenFilm's own rules still hold: the picture at t depends on t alone, a page has no sound, what you render elsewhere+enters as a clip under `assets/` with the script that made it, and Studio shows a WebVTT beside a sound as subtitles+over the film. Ask before downloading anything large onto the person's computer.++## With the person++The song and its lyrics; the title and artist from the LRC or the file name, or ask. Their cover, photos, footage or a+mood they have in mind make it theirs: ask, without holding up the work. When done, tell them in a few lines what you+made and why it fits the song, how close the timing is, and what of theirs would make it better.diff --git a/packages/openfilm/skills/lyric-video/cover.jpg b/packages/openfilm/skills/lyric-video/cover.jpgnew file mode 100644index 0000000..b33550eBinary files /dev/null and b/packages/openfilm/skills/lyric-video/cover.jpg differdiff --git a/packages/openfilm/skills/lyric-video/openfilm.json b/packages/openfilm/skills/lyric-video/openfilm.jsonnew file mode 100644index 0000000..9fa6ed3--- /dev/null+++ b/packages/openfilm/skills/lyric-video/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/lyric-video",+ "kind": "style",+ "order": 8,+ "icon": "music",+ "cover": "cover.jpg",+ "title": {+ "en": "Lyric video",+ "zh-CN": "动态歌词 MV",+ "ja": "歌詞動画",+ "ko": "가사 영상",+ "es": "Vídeo con letra"+ },+ "summary": {+ "en": "Give it a song and its lyrics: a lyric video made for this one song, every word landing on the voice.",+ "zh-CN": "给一首歌和歌词,做出像官方 MV 一样的歌词视频:为这首歌量身定做,每个字都落在歌声上。",+ "ja": "曲と歌詞を渡すと、その曲のためだけの歌詞動画に。言葉はすべて歌声にぴったり重なります。",+ "ko": "노래와 가사를 주면, 이 노래만을 위한 가사 영상을 만듭니다. 모든 단어가 노랫소리에 정확히 맞습니다.",+ "es": "Dale una canción y su letra: un vídeo con letra hecho para esa canción, cada palabra justo sobre la voz."+ },+ "details": {+ "zh-CN": "适合:给一首歌做歌词视频,发 B 站、抖音或音乐平台。\n它会:读懂这首歌,做出只属于它的画面;每个字在唱出的那一刻出现(实测对齐,不是估算)。",+ "en": "Best for: a lyric video for a song, for video sites or music platforms.\nWhat it does: reads the song and makes something only it could have, each word arriving the moment it is sung (measured, not estimated).",+ "ja": "こんなときに:曲の歌詞動画を作って、動画サイトや音楽配信に出すとき。\nすること:曲を読み取り、その曲だけの映像に。言葉は歌われた瞬間に現れます(実測で合わせます)。",+ "ko": "이럴 때: 노래의 가사 영상을 만들어 영상 사이트나 음원 플랫폼에 올릴 때.\n하는 일: 노래를 이해하고 이 노래만의 화면을 만듭니다. 단어는 부르는 순간 나타납니다(측정해서 맞춥니다).",+ "es": "Ideal para: un vídeo con letra para una canción, para plataformas de vídeo o de música.\nQué hace: entiende la canción y crea algo que solo ella podría tener; cada palabra aparece justo cuando se canta (medido, no estimado)."+ }+}diff --git a/packages/openfilm/skills/motion-graphics/SKILL.md b/packages/openfilm/skills/motion-graphics/SKILL.mdnew file mode 100644index 0000000..1d770d0--- /dev/null+++ b/packages/openfilm/skills/motion-graphics/SKILL.md@@ -0,0 +1,34 @@+---+name: motion-graphics+description: Make premium motion graphics (an explainer, a promo, a title sequence or a data story) designed and animated at the level of a top studio, for this subject alone. Use when the person asks for motion graphics, an MG animation, an animated explainer, a promo or an intro that should look high end (高级 MG, 动效, 动画视频, 片头, 宣传动画).+---++# Motion graphics++Make the piece a top motion studio would put in its reel: an idea for this subject, designed and moved with intent,+that makes people understand it or want it. Surprise us; the expected version is not the goal.++## What has to be true++- **It belongs to this subject.** The idea, the pictures and the motion come from what it is about; nothing in it could+ be moved into another company's film.+- **The person's facts and brand.** Every number, name, quote and claim as they gave it, none made up; a chart's shapes+ match its values, with units and where the data comes from; when there is a voice, the picture shows what it says as+ it says it. Their logo, colors and type are used as given, never redrawn.+- **It holds up next to the best motion work you know.** Watch the whole film as a viewer would, and keep refining until+ it does.+- **It stays editable**: the person can change any word or number later.++## What you have++Anything you can make pictures and motion with: the web platform and any library on it, Blender or any renderer whose+output becomes a clip, the person's footage, photos and data, any font whose license allows it, images, video, music and+sound from `npx openfilm get`, your own built-in tools, and services the person has keys for. OpenFilm's own rules+still hold: the picture at t depends on t alone, a page has no sound, and what you render elsewhere enters as a clip+under `assets/` with the script that made it. Ask before downloading anything large onto the person's computer.++## With the person++What they ask for comes before anything here. What it is about, who it is for, where it will be shown, and their+material: a logo, colors, product shots, data, a script. Ask without holding up the work. When done, tell them in a few+lines the idea and why it fits, where every number came from, and what of theirs would make it better.diff --git a/packages/openfilm/skills/motion-graphics/cover.jpg b/packages/openfilm/skills/motion-graphics/cover.jpgnew file mode 100644index 0000000..aac1f1fBinary files /dev/null and b/packages/openfilm/skills/motion-graphics/cover.jpg differdiff --git a/packages/openfilm/skills/motion-graphics/openfilm.json b/packages/openfilm/skills/motion-graphics/openfilm.jsonnew file mode 100644index 0000000..9f40af8--- /dev/null+++ b/packages/openfilm/skills/motion-graphics/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/motion-graphics",+ "kind": "workflow",+ "order": 4,+ "icon": "shapes",+ "cover": "cover.jpg",+ "title": {+ "en": "Premium motion graphics",+ "zh-CN": "高级 MG 动画",+ "ja": "ハイエンドなモーショングラフィックス",+ "ko": "고급 모션그래픽",+ "es": "Motion graphics de alto nivel"+ },+ "summary": {+ "en": "An explainer, promo or intro designed and animated at studio level, with a visual system made for its subject.",+ "zh-CN": "讲解、宣传、片头这类 MG 动画,按顶级工作室的水准设计和制作,视觉体系为主题量身定做。",+ "ja": "解説、プロモ、オープニングを、テーマに合わせたビジュアルシステムでスタジオ品質に。",+ "ko": "설명, 홍보, 인트로를 주제에 맞춘 비주얼 시스템으로 스튜디오 수준에 맞게.",+ "es": "Un explicativo, una promo o una intro diseñados y animados a nivel de estudio, con un sistema visual propio."+ },+ "details": {+ "zh-CN": "适合:产品讲解、品牌宣传、片头、数据故事。\n它会:为你的主题找一个只属于它的创意,按顶级工作室的标准设计和制作动画;你的数字、事实和品牌原样使用,不编造。",+ "en": "Best for: product explainers, brand promos, intros and data stories.\nWhat it does: finds an idea that belongs to your subject alone, then designs and animates it to a top studio’s standard. Your numbers, facts and brand are used exactly as you gave them.",+ "ja": "こんなときに:製品解説、ブランドプロモーション、オープニング、データストーリー。\nすること:そのテーマだけのアイデアを見つけ、一流スタジオの基準でデザインとアニメーションを仕上げます。数字、事実、ブランドは渡されたとおりに使い、作り話はしません。",+ "ko": "이럴 때: 제품 설명, 브랜드 홍보, 인트로, 데이터 스토리.\n하는 일: 주제에만 어울리는 아이디어를 찾아 최고 스튜디오 수준으로 디자인하고 움직입니다. 숫자, 사실, 브랜드는 받은 그대로 쓰고 지어내지 않습니다.",+ "es": "Ideal para: explicativos de producto, promos de marca, intros e historias con datos.\nQué hace: encuentra una idea que solo pertenece a tu tema y la diseña y anima al nivel de un gran estudio. Tus cifras, datos y marca se usan tal como los diste."+ }+}diff --git a/packages/openfilm/skills/presenter-pip/SKILL.md b/packages/openfilm/skills/presenter-pip/SKILL.mdnew file mode 100644index 0000000..bf412a5--- /dev/null+++ b/packages/openfilm/skills/presenter-pip/SKILL.md@@ -0,0 +1,34 @@+---+name: presenter-pip+description: Make a talking-head video where the content fills the screen and the presenter speaks from a small window: slides, screens, charts and pictures that follow what they say, their face always there. Use when the person gives a recording of themselves talking (with slides, a screen, data or notes) and asks for a lesson, a knowledge video, a business review, a commentary or a presentation with them in a corner (小窗人物口播, 画中画, 口播, 讲解视频).+---++# Presenter in a window++Make the video that keeps the person present and puts what they talk about in charge: each thing they mention fills+the screen the moment they say it, and they speak from a window that never gets in its way.++## What has to be true++- **The picture follows their words.** Each slide, screen, chart, number or picture arrives as they say it and leaves+ when they move on. Check it in the frames against the transcript's word times, and say how close it is.+- **The window never covers what matters**: the content, the subtitles, or a phone app's buttons; their face is never+ cut badly.+- **Their words and meaning.** Cuts fall in pauses; ums and false starts go only when they ask; nothing appears that they+ did not say or give. A number on screen is the one they say, from their data or its source.+- **It holds up next to the best explainers you know.** Watch the whole film as a viewer would, and keep refining until+ it does.++## What you have++Their recording, cut by its in and out points, never re-encoded, its window shaped with CSS; its transcript with every+word's time (`npx openfilm get asr`), from which Studio draws the subtitles. A version you treat (its background+removed, its sound cleaned) is a new file under `assets/`, and the cuts stay trims of it. Their slides as pictures or+rebuilt as pages, anything you can make charts, pictures and motion with, images and sound from `get`, your own+built-in tools, and services the person has keys for. Ask before downloading anything large onto the person's computer.++## With the person++What they ask for comes before anything here. The recording, their slides, data or notes, where it will be watched, and+whether ums and pauses should go. Ask without holding up the work. When done, tell them in a few lines what you made,+how close the content is to their words, and what of theirs would make it better.diff --git a/packages/openfilm/skills/presenter-pip/cover.jpg b/packages/openfilm/skills/presenter-pip/cover.jpgnew file mode 100644index 0000000..e795d0eBinary files /dev/null and b/packages/openfilm/skills/presenter-pip/cover.jpg differdiff --git a/packages/openfilm/skills/presenter-pip/openfilm.json b/packages/openfilm/skills/presenter-pip/openfilm.jsonnew file mode 100644index 0000000..52bbf02--- /dev/null+++ b/packages/openfilm/skills/presenter-pip/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/presenter-pip",+ "kind": "workflow",+ "order": 5,+ "icon": "pip",+ "cover": "cover.jpg",+ "title": {+ "en": "Presenter in a window",+ "zh-CN": "小窗人物口播",+ "ja": "ワイプで話す解説",+ "ko": "작은 창 진행자",+ "es": "Presentador en ventana"+ },+ "summary": {+ "en": "Your talking recording with the content filling the screen as you say it, and you speaking from a small window.",+ "zh-CN": "你的口播录像:讲到什么,画面就满屏展示什么,人在小窗里一直在场。",+ "ja": "話している映像に、話した内容を全画面で。あなたは小さなワイプからずっと話します。",+ "ko": "말하는 영상에, 말하는 내용이 화면을 채우고, 당신은 작은 창에서 계속 이야기합니다.",+ "es": "Tu grabación hablando, con el contenido llenando la pantalla cuando lo dices y tú en una ventana pequeña."+ },+ "details": {+ "zh-CN": "适合:知识讲解、课程、评论、带 PPT 的口播。\n它会:讲到什么,画面就满屏展示什么(图、表、页面、录屏),你在小窗里一直在场;停顿和口误可以剪掉,字幕来自原声。",+ "en": "Best for: knowledge videos, lessons, commentary and talks with slides.\nWhat it does: whatever you mention fills the screen as you say it (pictures, charts, slides, screens) while you stay in a small window; pauses and slips can go, captions come from your voice.",+ "ja": "こんなときに:解説、授業、コメンタリー、スライド付きのトーク。\nすること:話した内容(画像、グラフ、スライド、画面)がその瞬間に全画面で映り、あなたは小さなワイプにずっといます。間や言い間違いはカットでき、字幕は音声から作ります。",+ "ko": "이럴 때: 지식 영상, 강의, 코멘터리, 슬라이드가 있는 발표.\n하는 일: 말하는 내용(이미지, 차트, 슬라이드, 화면)이 그 순간 화면을 채우고 당신은 작은 창에 계속 있습니다. 쉬는 부분과 말실수는 잘라낼 수 있고, 자막은 음성에서 만듭니다.",+ "es": "Ideal para: vídeos de divulgación, clases, comentarios y charlas con diapositivas.\nQué hace: lo que mencionas llena la pantalla en ese momento (imágenes, gráficos, diapositivas, pantallas) mientras tú sigues en una ventana pequeña; se pueden quitar pausas y errores, y los subtítulos salen de tu voz."+ }+}diff --git a/packages/openfilm/skills/replicate/SKILL.md b/packages/openfilm/skills/replicate/SKILL.mdnew file mode 100644index 0000000..eacfeb3--- /dev/null+++ b/packages/openfilm/skills/replicate/SKILL.md@@ -0,0 +1,40 @@+---+name: replicate+description: Remake a reference video in OpenFilm, as close as the person wants it, from frame for frame to its structure, rhythm, look and motion carrying their own content. Use when the person gives a video, as a file or a link, and asks for an exact copy of it, one like it, its style or pacing, or a remake for their product or topic (复刻, 照着做, 做个同款, 一模一样, 仿这个视频).+---++# Replicate a video++Remake a video the person admires, as close as they want it: the same film frame for frame, or its form (the parts,+the rhythm, the look, the way things move) carrying their own content. When their words do not say which, ask. Either+way it is made again in OpenFilm, so every part of it can be changed.++## What has to be true++- **The same moments.** Where the reference cuts, a word appears, something moves or a sound hits, the film does too,+ scaled when the lengths differ; for an exact copy, each frame matches the reference's frame at the same time. Compare+ the two at the same times with `npx openfilm look`, and report honestly, in numbers, how close it is.+- **Made again.** The reference stays in `references/` and is never a clip of the film: what the film shows is made+ anew, and the reference's own music, footage or voice go in only when the person asks for them.+- **Their version is theirs**: when they want their own content, every part carries their topic, product, words and+ material, and a part they have nothing for takes a job that fits their film. A template with new words in it is not+ done.+- **It holds up next to the reference**, as well made at every moment. Watch the whole film as a viewer would, and keep+ refining until it does.++## What you have++`references/` sits beside the film but not in it: `assets/` holds only what the film uses. Anything you can make+pictures, motion and sound with: the web platform and any library on it, renderers whose output becomes a clip, the+person's footage and photos, any font whose license allows it, images, video, music and voice from `npx openfilm get`,+your own built-in tools, and services the person has keys for. OpenFilm's own rules still hold: the picture at t+depends on t alone, a page has no sound, and what you render elsewhere enters as a clip under `assets/` with the script+that made it. Ask before downloading anything large onto the person's computer.++## With the person++What they ask for comes before anything here. The reference (a file, or a link you can download), how close they want+it, what their version is about and the material they have (footage, product shots, a logo, their voice), and where it+will be posted. Ask without holding up the work. When done, tell them in a few lines what was kept, what changed and+why, how close it is, and, if they will post it, which parts belong to someone else (footage, music, voice, faces, a+logo, words, typefaces).diff --git a/packages/openfilm/skills/replicate/cover.jpg b/packages/openfilm/skills/replicate/cover.jpgnew file mode 100644index 0000000..e6a5403Binary files /dev/null and b/packages/openfilm/skills/replicate/cover.jpg differdiff --git a/packages/openfilm/skills/replicate/openfilm.json b/packages/openfilm/skills/replicate/openfilm.jsonnew file mode 100644index 0000000..401d976--- /dev/null+++ b/packages/openfilm/skills/replicate/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/replicate",+ "kind": "workflow",+ "order": 1,+ "icon": "copy",+ "cover": "cover.jpg",+ "title": {+ "en": "Replicate a video",+ "zh-CN": "视频复刻",+ "ja": "動画を再現",+ "ko": "영상 따라 만들기",+ "es": "Replicar un vídeo"+ },+ "summary": {+ "en": "Give it a video and it is remade in OpenFilm: frame for frame, or with your own content.",+ "zh-CN": "给它一条视频,在 OpenFilm 里重做一遍:可以逐帧一模一样,也可以换成你的内容。",+ "ja": "動画を渡すと、OpenFilm で作り直します。1コマずつ同じにも、あなたの内容に置き換えることもできます。",+ "ko": "영상을 주면 OpenFilm에서 다시 만듭니다. 프레임까지 똑같이, 또는 당신의 내용으로.",+ "es": "Dale un vídeo y se rehace en OpenFilm: fotograma a fotograma, o con tu propio contenido."+ },+ "details": {+ "zh-CN": "适合:看到一条喜欢的视频,想做一条一模一样的,或者做一条自己的同款。\n它会:在 OpenFilm 里把它重新做出来,每个时刻都对上(实测,不是估);做出来的每一部分你都能再改。",+ "en": "Best for: a video you love that you want copied exactly, or one like it with your content.\nWhat it does: remakes it in OpenFilm with every moment matched (measured, not guessed), so you can change any part of it afterwards.",+ "ja": "こんなときに:気に入った動画をそっくり作りたいとき、または自分の内容で同じような動画を作りたいとき。\nすること:OpenFilm で作り直し、すべての瞬間を合わせます(実測で確認)。できあがった部分はどれも後から変えられます。",+ "ko": "이럴 때: 마음에 드는 영상을 똑같이 만들고 싶거나, 내 내용으로 비슷한 영상을 만들고 싶을 때.\n하는 일: OpenFilm에서 다시 만들어 모든 순간을 맞춥니다(측정해서 확인). 만들어진 모든 부분은 나중에 바꿀 수 있습니다.",+ "es": "Ideal para: un vídeo que te encanta y quieres copiar tal cual, o uno parecido con tu contenido.\nQué hace: lo rehace en OpenFilm con cada momento igualado (medido, no estimado), para que puedas cambiar cualquier parte después."+ }+}diff --git a/packages/openfilm/skills/screen-demo/SKILL.md b/packages/openfilm/skills/screen-demo/SKILL.mdnew file mode 100644index 0000000..c00d35c--- /dev/null+++ b/packages/openfilm/skills/screen-demo/SKILL.md@@ -0,0 +1,36 @@+---+name: screen-demo+description: Turn a screen recording into a polished product demo or tutorial: the view follows the action, dead time is gone, every step is easy to see, and the product looks as good as it is. Use when the person gives a screen recording (or a product to capture) and asks for a demo, walkthrough, tutorial, feature video or how-to (录屏演示, 产品演示, 教程, 操作视频, 功能介绍).+---++# Screen demo++Make the demo that shows this product at its best and is effortless to follow: the viewer always knows where to look,+sees each step land, never waits, and could do the same in the product today.++## What has to be true++- **The real product.** Its own screens, actions and results, from the person's recording or captured from the live+ product; never a redrawn interface or a result that did not happen. Where it must be simpler, crop and zoom into the+ real thing.+- **Clear where to look**, at the size it will be watched: the action, its text and its result readable on that+ screen, a phone too when the demo is vertical.+- **Nothing private in any frame**: keys, tokens, passwords, emails, names, customer data, notifications, other tabs+ and bookmarks are hidden, or that part is recorded again.+- **Honest time.** Waiting can go; where speed is what the product sells, the real time stays or the speed-up is shown.+- **It holds up next to the best product demos you know.** Watch the whole film as a viewer would, and keep refining+ until it does.++## What you have++The recording, cut by its in and out points and sped up with `speed`, never re-encoded; a page can also play it,+silent, with its time set from t, so the picture can move over it. OpenFilm's own headless browser captures the live+product with nothing to install: `npx openfilm capture --help`. A voice from `npx openfilm get tts`,+music and sound from `get`, your own built-in tools, services the person has keys for, and anything you can make+pictures and motion with.++## With the person++What they ask for comes before anything here. The recording or the product (its address, and an account to show it+with), who the demo is for, and the one thing it must show. Ask without holding up the work. When done, tell them in a+few lines what it shows, what you sped up or left out, and what you hid.diff --git a/packages/openfilm/skills/screen-demo/cover.jpg b/packages/openfilm/skills/screen-demo/cover.jpgnew file mode 100644index 0000000..a005e15Binary files /dev/null and b/packages/openfilm/skills/screen-demo/cover.jpg differdiff --git a/packages/openfilm/skills/screen-demo/openfilm.json b/packages/openfilm/skills/screen-demo/openfilm.jsonnew file mode 100644index 0000000..55ae40b--- /dev/null+++ b/packages/openfilm/skills/screen-demo/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/screen-demo",+ "kind": "workflow",+ "order": 3,+ "icon": "monitor",+ "cover": "cover.jpg",+ "title": {+ "en": "Screen demo",+ "zh-CN": "录屏演示",+ "ja": "画面収録デモ",+ "ko": "화면 녹화 데모",+ "es": "Demo de pantalla"+ },+ "summary": {+ "en": "A screen recording made into a polished demo: the camera follows the action, the waiting is gone, every step lands.",+ "zh-CN": "把录屏做成精致的产品演示或教程:镜头跟着操作走,等待的地方剪掉,每一步都看得清。",+ "ja": "画面収録を洗練されたデモに。カメラが操作を追い、待ち時間はカット、各ステップがはっきり伝わります。",+ "ko": "화면 녹화를 완성도 높은 데모로: 카메라가 동작을 따라가고, 기다림은 없애고, 모든 단계가 분명하게.",+ "es": "Una grabación de pantalla convertida en una demo pulida: la cámara sigue la acción, sin esperas, cada paso se entiende."+ },+ "details": {+ "zh-CN": "适合:产品演示、软件教程、功能介绍。\n它会:用你的真实录屏做成精致的演示片:画面跟着操作走,等待剪掉,每一步都看得清;界面不重画,密钥和隐私信息会遮掉,需要时配上讲解。",+ "en": "Best for: product demos, software tutorials and feature videos.\nWhat it does: turns your real screen recording into a polished demo: the view follows the action, the waiting is cut, every step is clear. The interface is never redrawn, keys and private details are hidden, and there is a voice-over when you want one.",+ "ja": "こんなときに:製品デモ、ソフトのチュートリアル、機能紹介。\nすること:実際の画面収録を洗練されたデモに。画面が操作を追い、待ち時間はカットし、各ステップがはっきり見えます。画面を描き直すことはなく、キーや個人情報は隠します。必要ならナレーションも。",+ "ko": "이럴 때: 제품 데모, 소프트웨어 튜토리얼, 기능 소개.\n하는 일: 실제 화면 녹화를 완성도 높은 데모로. 화면이 동작을 따라가고 기다림은 자르며 모든 단계가 분명하게 보입니다. 화면을 다시 그리지 않고, 키와 개인 정보는 가립니다. 원하면 내레이션도 넣습니다.",+ "es": "Ideal para: demos de producto, tutoriales de software y vídeos de funciones.\nQué hace: convierte tu grabación de pantalla real en una demo pulida: la imagen sigue la acción, se cortan las esperas y cada paso se ve claro. La interfaz nunca se redibuja, las claves y los datos privados se ocultan, y hay voz en off si la quieres."+ }+}diff --git a/packages/openfilm/skills/vintage-film/SKILL.md b/packages/openfilm/skills/vintage-film/SKILL.mdnew file mode 100644index 0000000..461c0e9--- /dev/null+++ b/packages/openfilm/skills/vintage-film/SKILL.md@@ -0,0 +1,38 @@+---+name: vintage-film+description: Make the person's photos and clips into a memory film that looks shot on old film or kept as instant photos and prints. Use for memories and recaps (a trip, a birthday, a graduation, a wedding, a year, a child growing up) or when the person asks for a retro, film, analog, Polaroid or instant-photo look (复古, 胶片, 拍立得, 回忆, 相册, 年度回顾).+---++# Vintage film++Make the memory film the people in these pictures will watch again and send to each other: their own photos and clips,+as if found on an old reel or in a box of prints. Surprise us; the expected version is not the goal.++The pictures are the film. The film look is how they were taken and printed, part of each picture rather than a filter+laid over it, and it never changes who or what is in them.++## What has to be true++- **The people and moments untouched.** Faces, bodies, who was there and what was behind them stay as they were: what a+ darkroom could do (crop, scale, color, grain, light) and nothing more. No face restored, no picture extended, no+ person made to move or smile, unless the person asks; then say it is generated.+- **Only true words.** Dates, places and names come from the person or the pictures' own metadata, never guessed; the+ real order is kept unless they want another.+- **Everyone who matters stays in the frame**, through every move.+- **It holds up next to the best memory films you know.** Watch the whole film as a viewer would, and keep refining+ until it does. If anyone's photos could be dropped into it, it is not done yet.++## What you have++The pictures and their metadata, the person's own song or music from `npx openfilm get`, and anything you can make+pictures and motion with: the web platform and any library on it, renderers whose output becomes a clip, any font whose+license allows it, your own built-in tools, and services the person has keys for. OpenFilm's own rules still hold: the+picture at t depends on t alone, a page has no sound, and what you render elsewhere enters as a clip under `assets/`+with the script that made it. Ask before downloading anything large onto the person's computer.++## With the person++What they ask for comes before anything here. The photos and clips, who and what it is about, where it will be watched+(a post, a screen at a party), and a song if they have one. Ask without holding up the work. When done, tell them in a+few lines what you made, how many pictures you used (the rest can come back), where each date and place came from, and+what of theirs would make it better.diff --git a/packages/openfilm/skills/vintage-film/cover.jpg b/packages/openfilm/skills/vintage-film/cover.jpgnew file mode 100644index 0000000..ca31de1Binary files /dev/null and b/packages/openfilm/skills/vintage-film/cover.jpg differdiff --git a/packages/openfilm/skills/vintage-film/openfilm.json b/packages/openfilm/skills/vintage-film/openfilm.jsonnew file mode 100644index 0000000..ed2d8b4--- /dev/null+++ b/packages/openfilm/skills/vintage-film/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/vintage-film",+ "kind": "style",+ "order": 7,+ "icon": "film",+ "cover": "cover.jpg",+ "title": {+ "en": "Vintage film",+ "zh-CN": "复古胶片相册",+ "ja": "フィルム風アルバム",+ "ko": "필름 감성 앨범",+ "es": "Película antigua"+ },+ "summary": {+ "en": "Your photos and clips as a memory film, as if found on an old reel or in a box of prints.",+ "zh-CN": "把照片和视频做成回忆短片,像从老胶卷或一盒旧照片里找出来的。",+ "ja": "写真と動画を、古いフィルムや焼き増し写真の箱から見つけたような思い出の映像に。",+ "ko": "사진과 영상을 오래된 필름이나 사진 상자에서 찾아낸 듯한 추억 영상으로.",+ "es": "Tus fotos y clips como una película de recuerdos, como encontrada en un viejo rollo o en una caja de copias."+ },+ "details": {+ "zh-CN": "适合:旅行、生日、毕业、婚礼、年度回顾这类照片回忆。\n它会:挑出撑得起故事的照片,做出胶片和老照片的质感;照片里的人和事不改动,日期和地点不编造。",+ "en": "Best for: memories from a trip, a birthday, a graduation, a wedding or a year.\nWhat it does: picks the pictures that carry the story and gives them the look of film and prints, never changing the people in them or making up dates and places.",+ "ja": "こんなときに:旅行、誕生日、卒業、結婚式、一年の振り返りなど写真の思い出。\nすること:物語になる写真を選び、フィルムや焼き増し写真の質感に。写っている人や出来事は変えず、日付や場所を作りません。",+ "ko": "이럴 때: 여행, 생일, 졸업, 결혼식, 한 해 돌아보기 같은 사진 추억.\n하는 일: 이야기를 이끄는 사진을 골라 필름과 인화 사진의 질감으로 만듭니다. 사진 속 사람과 일은 바꾸지 않고, 날짜와 장소를 지어내지 않습니다.",+ "es": "Ideal para: recuerdos de un viaje, un cumpleaños, una graduación, una boda o un año.\nQué hace: elige las fotos que cuentan la historia y les da el aspecto de la película y las copias en papel, sin cambiar a las personas ni inventar fechas o lugares."+ }+}diff --git a/packages/openfilm/skills/whiteboard/SKILL.md b/packages/openfilm/skills/whiteboard/SKILL.mdnew file mode 100644index 0000000..5a5c81b--- /dev/null+++ b/packages/openfilm/skills/whiteboard/SKILL.md@@ -0,0 +1,40 @@+---+name: whiteboard+description: Make an explainer drawn on a board while a voice explains, every drawing and word drawn out as it is spoken. Use for lessons, micro-lectures, training, how-it-works and concept explainers, when the person turns a document, slides or notes into an explainer, or asks for a whiteboard, hand-drawn, sketch or doodle style (白板, 手绘, 讲解, 微课, 课件).+---++# Whiteboard explainer++Make the explainer a great teacher would draw: a voice explains and the board grows with it, so the viewer watches the+idea being built and remembers it.++The drawing is the explanation: each mark is drawn as the words that name it are spoken. A finished picture that fades+or slides in is not a whiteboard explainer.++## What has to be true++- **Drawn as it is said.** Each mark starts when the voice reaches it and is done before the next idea. Check it in the+ frames against the voice's word times, and report how close it is.+- **True to the source.** Every fact, number, term and example as the person's document has it. What you add is your own+ sentence, never a new fact; what you correct, you say.+- **Words on the board spelled right**, and readable at the size it will be watched.+- **It holds up next to the best explainers you know**, its drawings made for this subject. Watch the whole film as a+ viewer would, and keep refining until it does.+- **It stays editable**: the person can change the script, or put their own voice in its place, and the drawing still+ lands on the words.++## What you have++A voice from `npx openfilm get tts`, with a WebVTT beside it that times every word; the person's own recording gets the+same from `get asr`. Anything you can draw and move with: the web platform and any library on it, renderers whose+output becomes a clip, any font whose license allows it, images from `get`, your own built-in tools, and services the+person has keys for. OpenFilm's own rules still hold: the picture at t depends on t alone, a page has no sound, and what+you render elsewhere enters as a clip under `assets/` with the script that made it. Ask before downloading anything+large onto the person's computer.++## With the person++What they ask for comes before anything here. The document, slides or notes, who will watch, and their own voice if+they have recorded it. Without a voice service, make a placeholder voice and say which services make a real one. When+done, tell them in a few lines what the boards show, how close the drawing is to the voice, and where the script is so+they can change it.diff --git a/packages/openfilm/skills/whiteboard/cover.jpg b/packages/openfilm/skills/whiteboard/cover.jpgnew file mode 100644index 0000000..d905f41Binary files /dev/null and b/packages/openfilm/skills/whiteboard/cover.jpg differdiff --git a/packages/openfilm/skills/whiteboard/openfilm.json b/packages/openfilm/skills/whiteboard/openfilm.jsonnew file mode 100644index 0000000..f202b67--- /dev/null+++ b/packages/openfilm/skills/whiteboard/openfilm.json@@ -0,0 +1,29 @@+{+ "version": "0.1.0",+ "repository": "https://github.com/openfilm/skills/tree/main/skills/whiteboard",+ "kind": "style",+ "order": 6,+ "icon": "pen",+ "cover": "cover.jpg",+ "title": {+ "en": "Whiteboard explainer",+ "zh-CN": "手绘白板风格",+ "ja": "ホワイトボード解説",+ "ko": "화이트보드 설명",+ "es": "Explicación en pizarra"+ },+ "summary": {+ "en": "A voice explains while the board is drawn, mark by mark, as it speaks. Turns a document, slides or notes into a lesson.",+ "zh-CN": "边讲边画的白板讲解:配音讲到哪,画面就画到哪。文稿、课件、笔记都能做成讲解视频。",+ "ja": "声で説明しながら、その場でホワイトボードに描いていきます。資料やスライドから解説動画に。",+ "ko": "목소리가 설명하는 대로 화이트보드에 그려집니다. 문서, 슬라이드, 노트로 강의 영상을.",+ "es": "Una voz explica mientras se dibuja en la pizarra, trazo a trazo. Convierte documentos o diapositivas en una lección."+ },+ "details": {+ "zh-CN": "适合:微课、培训、科普,把文稿、课件、笔记讲清楚。\n它会:配音讲到哪,白板上就画到哪(对着配音实测对齐);文稿里的事实、数字和术语原样保留,不编造。",+ "en": "Best for: micro-lessons, training and explainers, from a document, slides or notes.\nWhat it does: draws on the board exactly what the voice is saying, as it says it (checked against the voice), and keeps every fact, number and term of your document as written.",+ "ja": "こんなときに:ミニ授業、研修、解説。資料、スライド、ノートを分かりやすく。\nすること:ナレーションが話すそのときに、話している内容をボードに描きます(声と照らして確認)。資料の事実、数字、用語はそのまま守ります。",+ "ko": "이럴 때: 짧은 강의, 교육, 설명 영상. 문서, 슬라이드, 노트를 쉽게.\n하는 일: 내레이션이 말하는 그 순간에 그 내용을 보드에 그립니다(목소리와 맞춰 확인). 문서의 사실, 숫자, 용어는 그대로 지킵니다.",+ "es": "Ideal para: microclases, formación y divulgación, desde un documento, diapositivas o notas.\nQué hace: dibuja en la pizarra justo lo que dice la voz, en el momento en que lo dice (comprobado con la voz), y respeta cada dato, cifra y término de tu documento."+ }+}diff --git a/packages/openfilm/src/capture.mjs b/packages/openfilm/src/capture.mjsnew file mode 100644index 0000000..6ff4885--- /dev/null+++ b/packages/openfilm/src/capture.mjs@@ -0,0 +1,51 @@+// openfilm capture: a picture of a live web page (a product, a site), sharp enough to fill a stage, taken in the browser+// OpenFilm draws films in, so a film can show the real thing instead of a drawing of it.+import { mkdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { launch } from './host.mjs';+import { shown, UsageError } from './shared.mjs';++/** The window when none is asked: a laptop's. */+const SIZE = '1440x900';++/**+ * One picture: the page loads and settles (its network idle, or 10 s at most), loses the elements asked hidden, gets+ * the clicks asked, in order, waits, and is taken: the window, the whole page (`full`) or one element (`selector`).+ * @param {string[]} args the address and the PNG to write+ * @param {{ size?: string, scale?: number, full?: boolean, wait?: string, dark?: boolean, click?: string[],+ * hide?: string[], selector?: string, launch?: Parameters<typeof launch>[0] }} [opts]+ */+export async function capture(args, opts = {}) {+ const [url, out, ...more] = args;+ if (!url || !out || more.length) throw new UsageError('give the address and the picture to write: capture <url> <file.png>');+ if (!/^(https?|file):\/\//i.test(url)) throw new UsageError(`${url} is not a web address: give it whole, with https://`);+ if (!/\.png$/i.test(out)) throw new UsageError(`${out}: the picture is a .png`);+ const size = /^(\d{2,5})x(\d{2,5})$/.exec(opts.size ?? SIZE);+ if (!size) throw new UsageError(`--size is width x height in px, such as ${SIZE}, not ${opts.size}`);+ const wait = opts.wait === undefined ? 1500 : Number(opts.wait);+ if (!Number.isInteger(wait) || wait < 0 || wait > 60_000) throw new UsageError(`--wait is milliseconds from 0 to 60000, not ${opts.wait}`);+ const file = resolve(out);+ const browser = await launch(opts.launch);+ try {+ const page = await browser.newPage({+ viewport: { width: Number(size[1]), height: Number(size[2]) },+ deviceScaleFactor: opts.scale ?? 2,+ colorScheme: opts.dark ? 'dark' : 'light',+ });+ await page.goto(url, { waitUntil: 'load', timeout: 60_000 });+ /* a page that keeps a connection open never goes idle: wait a while, not forever */+ await page.waitForLoadState('networkidle', { timeout: 10_000 }).catch(() => {});+ /* a banner that is not there has nothing to hide; a click that cannot happen is an error: the view would be wrong */+ for (const sel of opts.hide ?? []) await page.locator(sel).evaluateAll((els) => els.forEach((el) => el.remove())).catch(() => {});+ for (const sel of opts.click ?? []) { await page.locator(sel).first().click({ timeout: 10_000 }); await page.waitForTimeout(600); }+ await page.waitForTimeout(wait);+ mkdirSync(dirname(file), { recursive: true });+ const png = opts.selector+ ? await page.locator(opts.selector).first().screenshot({ path: file, timeout: 10_000 })+ : await page.screenshot({ path: file, fullPage: Boolean(opts.full) });+ /* a PNG's width and height are the first two numbers of its header */+ return { ok: true, lines: [`${shown(file)} ${png.readUInt32BE(16)} × ${png.readUInt32BE(20)} px`] };+ } finally {+ await browser.close();+ }+}diff --git a/packages/openfilm/src/capture.test.mjs b/packages/openfilm/src/capture.test.mjsnew file mode 100644index 0000000..974e7ed--- /dev/null+++ b/packages/openfilm/src/capture.test.mjs@@ -0,0 +1,46 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { capture } from './capture.mjs';+import { UsageError } from './shared.mjs';++const BIN = fileURLToPath(new URL('../bin/openfilm.mjs', import.meta.url));++test('a capture asked wrong is a usage error, said before any browser starts', async () => {+ await assert.rejects(capture(['https://example.com']), UsageError);+ await assert.rejects(capture(['example.com', 'a.png']), /not a web address/);+ await assert.rejects(capture(['https://example.com', 'a.jpg']), /is a \.png/);+ await assert.rejects(capture(['https://example.com', 'a.png'], { size: 'big' }), /--size/);+ await assert.rejects(capture(['https://example.com', 'a.png'], { wait: '-1' }), /--wait/);+});++test('the window at its scale, the whole page, one element, and a banner removed that is not there', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'openfilm-capture-'));+ try {+ writeFileSync(join(dir, 'page.html'), '<!doctype html><body style="margin:0;height:1000px;background:#fff">'+ + '<div id="card" style="position:absolute;left:50px;top:40px;width:300px;height:200px;background:#e33"></div></body>');+ const url = pathToFileURL(join(dir, 'page.html')).href;+ const fast = { size: '400x300', wait: '0' };+ const window = await capture([url, join(dir, 'out', 'window.png')], { ...fast, scale: 1 });+ assert.match(window.lines[0], /400 × 300 px$/);+ assert.ok(existsSync(join(dir, 'out', 'window.png')), 'the folder for the picture is made');+ assert.match((await capture([url, join(dir, 'whole.png')], { ...fast, scale: 1, full: true })).lines[0], /400 × 1000 px$/);+ assert.match((await capture([url, join(dir, 'card.png')], { ...fast, selector: '#card' })).lines[0], /600 × 400 px$/);+ assert.match((await capture([url, join(dir, 'clean.png')], { ...fast, scale: 1, hide: ['#cookie-banner'] })).lines[0], /400 × 300 px$/);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test('openfilm capture is a command: its help, and a wrong address exits 2', () => {+ const help = spawnSync(process.execPath, [BIN, 'capture', '--help'], { encoding: 'utf8' });+ assert.equal(help.status, 0);+ assert.match(help.stdout, /--selector <css>/);+ const wrong = spawnSync(process.execPath, [BIN, 'capture', 'example.com', 'a.png'], { encoding: 'utf8' });+ assert.equal(wrong.status, 2);+ assert.match(wrong.stderr, /not a web address/);+});diff --git a/packages/openfilm/src/film-doc.mjs b/packages/openfilm/src/film-doc.mjsindex 05fd718..ebf7ee1 100644--- a/packages/openfilm/src/film-doc.mjs+++ b/packages/openfilm/src/film-doc.mjs@@ -104,6 +104,8 @@ const KEPT_ATTRIBUTE = /^(alt|title|lang|dir|data-[a-z0-9-]+|aria-[a-z]+)$/;/** What a track keeps of its element that says nothing to the film: a name, a class, a description. */const KEPT_TRACK_ATTRIBUTE = /^(id|class|title|lang|dir|data-[a-z0-9-]+|aria-[a-z]+)$/;const OVERRIDE_FIELDS = ['at', 'n', 't', 's', 'r', 'style', 'lock', 'text', 'fade'];+/** A key of an override's style: a CSS property in camelCase, or a custom property as CSS writes it (`--accent`). */+const STYLE_KEY = /^(?:[a-zA-Z]{1,40}|--[A-Za-z0-9_-]{1,60})$/;const BOX_FIELDS = ['x', 'y', 'w', 'h', 'r'];/** The largest side a page is laid out at (`size`): a stage's. */const PAGE_SIZE_MAX = 8192;@@ -152,8 +154,8 @@ function checkOverride(o, where, problems, kind) {const entries = isObject(o.style) ? Object.entries(o.style) : null;/* a value up to 2000 characters: a mask's inline SVG (`mask-image: url("data:image/svg+xml,…")`) runs to a few hundred */if (!entries || entries.length > 24- || !entries.every(([k, v]) => /^[a-zA-Z]{1,40}$/.test(k) && ((typeof v === 'string' && v.length <= 2000) || isFinite(v)))) {- problems.push(`${where}style has to be at most 24 camelCase properties, each text or a number.`);+ || !entries.every(([k, v]) => STYLE_KEY.test(k) && ((typeof v === 'string' && v.length <= 2000) || isFinite(v)))) {+ problems.push(`${where}style has to be at most 24 properties, camelCase or custom (--name), each text or a number.`);}}if (o.lock !== undefined && o.lock !== true) problems.push(`${where}lock is true, or not written.`);diff --git a/packages/openfilm/src/film-doc.test.mjs b/packages/openfilm/src/film-doc.test.mjsindex 4001d0a..28829c8 100644--- a/packages/openfilm/src/film-doc.test.mjs+++ b/packages/openfilm/src/film-doc.test.mjs@@ -312,3 +312,11 @@ test('a clip named after its file has no dashes at its ends, however many thereassert.equal(clipIdFor(`a${'-'.repeat(200_000)}b`, []), `a${'-'.repeat(200_000)}b`);assert.equal(clipIdFor('----.mp4', []), 'clip');});++test('an override\'s style takes CSS properties in camelCase and custom properties as CSS names them', () => {+ const page = (style) => film({ src: 't.html', overrides: [{ at: ':root', style }] });+ assert.equal(problems(page({ color: '#fff', '--accent': '#ff5746', '--bar_width2': '640px', '--n': 3 })), '');+ for (const bad of [{ 'font-size': '12px' }, { '-x': '1' }, { '--': '1' }, { '--a b': '1' }, { [`--${'x'.repeat(61)}`]: '1' }]) {+ assert.match(problems(page(bad)), /style has to be at most 24 properties, camelCase or custom/, JSON.stringify(bad));+ }+});diff --git a/packages/openfilm/src/locations.mjs b/packages/openfilm/src/locations.mjsnew file mode 100644index 0000000..020d82d--- /dev/null+++ b/packages/openfilm/src/locations.mjs@@ -0,0 +1,99 @@+// @ts-check+/**+ * Where OpenFilm keeps the person's work on this computer: the projects library (where new projects go) and the+ * exports folder. The library has a default and may be moved in Studio's Settings → General: Studio's `prefs.json`+ * (`projectsFolder`), read by Studio and by the `openfilm` command alike, so a project fetched from the command line+ * lands where Studio's go. OPENFILM_LIBRARY sets the default (a build, or a Studio kept apart); what the person chose+ * comes first. Projects made before stay where they are: the projects list knows them by their folder. Exports go to+ * the folder picked when exporting (the export dialog keeps the last one), else to the exports default.+ *+ * Reads no Studio module, so the command can use it.+ */+import { accessSync, constants, existsSync, mkdirSync, readFileSync, statfsSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, isAbsolute, join, resolve, sep } from 'node:path';++/** Studio's own home (its settings and keys, not the person's work): OPENFILM_HOME, else ~/.openfilm. */+export const studioHomeDir = () => process.env.OPENFILM_HOME || join(homedir(), '.openfilm');++/** Where new projects go unless the person chose: OPENFILM_LIBRARY, else ~/Movies/OpenFilm/Projects on macOS, ~/Videos/OpenFilm/Projects elsewhere. */+export const libraryDefault = () => process.env.OPENFILM_LIBRARY+ || join(homedir(), process.platform === 'darwin' ? 'Movies' : 'Videos', 'OpenFilm', 'Projects');++/**+ * Where exports go unless a folder is picked when exporting: OPENFILM_EXPORTS, else `exports` in OPENFILM_HOME when+ * that is set (a Studio kept apart, for work on OpenFilm itself, leaves nothing in the person's own folder), else the+ * Desktop.+ */+export const exportsDefault = () => process.env.OPENFILM_EXPORTS+ || (process.env.OPENFILM_HOME ? join(process.env.OPENFILM_HOME, 'exports') : '')+ || join(homedir(), 'Desktop');++/**+ * Where what the person saved goes (clips and files kept to use again in any project, studio/server/saved.mjs): beside+ * the projects' default folder, `Saved` (~/Movies/OpenFilm/Saved on macOS), else OPENFILM_SAVED. Not moved with the+ * projects folder: what was saved stays where it was found.+ */+export const savedRoot = () => process.env.OPENFILM_SAVED || join(dirname(libraryDefault()), 'Saved');++/** The folders the person can choose, by their key in prefs.json. */+export const LOCATION_KEYS = /** @type {const} */ ({ projects: 'projectsFolder' });++/** A folder the person chose, as kept in prefs.json: an absolute path, or null (none chosen, or not one). */+export function chosenFolder(/** @type {'projectsFolder'} */ key) {+ try {+ const value = JSON.parse(readFileSync(join(studioHomeDir(), 'prefs.json'), 'utf8'))?.[key];+ return typeof value === 'string' && isAbsolute(value) ? resolve(value) : null;+ } catch {+ return null;+ }+}++/** Where new projects go: the folder the person chose, else the default. */+export const libraryRoot = () => chosenFolder('projectsFolder') ?? libraryDefault();++/** Where exports go when no folder is picked. */+export const exportsRoot = () => exportsDefault();++/** The free space, in bytes, on the disk a folder is on (the folder, or the nearest one above it that is there), or null. */+export function freeSpace(/** @type {string} */ folder) {+ let at = resolve(folder);+ while (!existsSync(at) && dirname(at) !== at) at = dirname(at);+ try {+ const s = statfsSync(at);+ return s.bavail * s.bsize;+ } catch {+ return null;+ }+}++/**+ * Each folder the person can choose, for Settings: where it is now, its default, whether it was chosen, and the free+ * space on its disk.+ */+export function locations() {+ const one = (/** @type {string} */ path, /** @type {string} */ fallback, /** @type {boolean} */ chosen) => ({ path, default: fallback, chosen, free: freeSpace(path) });+ return {+ projects: one(libraryRoot(), libraryDefault(), chosenFolder('projectsFolder') !== null),+ };+}++/**+ * A folder offered for new projects, as it will be kept: absolute, not a disk's root, not inside Studio's own+ * home; made if it is not there yet. Throws a sentence the person can read.+ * @param {unknown} value @returns {string}+ */+export function usableFolder(value) {+ if (typeof value !== 'string' || !isAbsolute(value)) throw new Error('Choose a folder by its full path.');+ const path = resolve(value);+ if (dirname(path) === path) throw new Error('Choose a folder on that disk, not the disk itself.');+ const home = resolve(studioHomeDir());+ if (path === home || path.startsWith(home + sep)) throw new Error('OpenFilm keeps its own settings there: choose another folder.');+ try {+ mkdirSync(path, { recursive: true });+ accessSync(path, constants.W_OK);+ } catch {+ throw new Error('That folder cannot be written to: choose another one.');+ }+ return path;+}diff --git a/packages/openfilm/src/locations.test.mjs b/packages/openfilm/src/locations.test.mjsnew file mode 100644index 0000000..8a6d7c7--- /dev/null+++ b/packages/openfilm/src/locations.test.mjs@@ -0,0 +1,64 @@+import { test, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { exportsRoot, libraryDefault, libraryRoot, locations, usableFolder } from './locations.mjs';++const KEYS = ['OPENFILM_HOME', 'OPENFILM_LIBRARY', 'OPENFILM_EXPORTS'];+let saved;+let home;+beforeEach(() => {+ saved = Object.fromEntries(KEYS.map((k) => [k, process.env[k]]));+ home = mkdtempSync(join(tmpdir(), 'of-locations-'));+ process.env.OPENFILM_HOME = home;+ delete process.env.OPENFILM_LIBRARY;+ delete process.env.OPENFILM_EXPORTS;+});+afterEach(() => {+ for (const k of KEYS) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; }+});+const prefs = (value) => writeFileSync(join(home, 'prefs.json'), JSON.stringify(value));++test('new projects go to the folder chosen, before any default', () => {+ process.env.OPENFILM_LIBRARY = join(home, 'lib');+ assert.equal(libraryRoot(), join(home, 'lib'), 'the default: what the build set');+ const projects = join(tmpdir(), 'D', 'OpenFilm', 'Projects');+ prefs({ proxies: { on: true }, projectsFolder: projects });+ assert.equal(libraryRoot(), projects);+ assert.equal(libraryDefault(), join(home, 'lib'), 'the default stays what it was');+ /* a value that is not a full path is no choice */+ prefs({ projectsFolder: 'relative/folder' });+ assert.equal(libraryRoot(), join(home, 'lib'));+});++test('exports go to the default: no folder kept in prefs.json moves them (the export dialog picks one)', () => {+ process.env.OPENFILM_EXPORTS = join(home, 'out');+ prefs({ exportsFolder: join(tmpdir(), 'D', 'OpenFilm', 'Exports') });+ assert.equal(exportsRoot(), join(home, 'out'));+});++test('without a choice or a build\'s own: a Studio kept apart exports into its home; the person\'s own to the Desktop', () => {+ assert.equal(exportsRoot(), join(home, 'exports'));+ assert.match(libraryRoot(), /OpenFilm[\\/]Projects$/);+});++test('each folder for Settings: where it is, its default, whether chosen, and free space on its disk', () => {+ const projects = join(home, 'work', 'Projects');+ prefs({ projectsFolder: projects });+ const now = locations();+ assert.equal(now.projects.path, projects);+ assert.equal(now.projects.chosen, true);+ assert.notEqual(now.projects.default, projects);+ assert.ok(now.projects.free > 0, 'measured on the disk above a folder not made yet');+ assert.deepEqual(Object.keys(now), ['projects'], 'only where new projects go is a setting');+});++test('a folder offered is made and kept by its full path; a disk, Studio\'s own home or a relative path is refused', () => {+ const folder = join(home, '..', `of-pick-${process.pid}`, 'Projects');+ const kept = usableFolder(folder);+ assert.ok(existsSync(kept));+ assert.throws(() => usableFolder('Projects'), /full path/);+ assert.throws(() => usableFolder(process.platform === 'win32' ? 'C:\\' : '/'), /not the disk itself/);+ assert.throws(() => usableFolder(join(home, 'inside')), /own settings/);+});diff --git a/packages/openfilm/src/official-skills.test.mjs b/packages/openfilm/src/official-skills.test.mjsnew file mode 100644index 0000000..762c877--- /dev/null+++ b/packages/openfilm/src/official-skills.test.mjs@@ -0,0 +1,36 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { parseSkillFile } from './skills.mjs';++const SKILLS = join(import.meta.dirname, '..', 'skills');+const NAMES = readdirSync(SKILLS, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);++test('every official skill: a SKILL.md named as its folder, with a description, and a title and summary in five languages', () => {+ assert.ok(NAMES.length > 0);+ for (const name of NAMES) {+ const { fields } = parseSkillFile(readFileSync(join(SKILLS, name, 'SKILL.md'), 'utf8'));+ assert.equal(fields.name, name);+ assert.ok(fields.description.length > 80, `${name} says when to use it`);+ const shown = JSON.parse(readFileSync(join(SKILLS, name, 'openfilm.json'), 'utf8'));+ assert.equal(shown.repository, `https://github.com/openfilm/skills/tree/main/skills/${name}`);+ for (const lang of ['en', 'zh-CN', 'ja', 'ko', 'es']) {+ assert.ok(shown.title[lang], `${name} title ${lang}`);+ assert.ok(shown.summary[lang], `${name} summary ${lang}`);+ }+ }+});++test('every file a skill names in its own folder is there', () => {+ for (const name of NAMES) {+ const md = readFileSync(join(SKILLS, name, 'SKILL.md'), 'utf8');+ for (const [, file] of md.matchAll(/<this skill's folder>\/([\w.-]+)/g)) {+ assert.ok(existsSync(join(SKILLS, name, file)), `${name} names ${file}`);+ }+ }+});++test('the official skills are a copy of openfilm/skills, and say of which commit', () => {+ assert.match(readFileSync(join(SKILLS, 'SOURCE'), 'utf8'), /^https:\/\/github\.com\/openfilm\/skills\/commit\/[0-9a-f]{40}\n/);+});diff --git a/packages/openfilm/src/overrides.mjs b/packages/openfilm/src/overrides.mjsindex 0068f9b..0ab3445 100644--- a/packages/openfilm/src/overrides.mjs+++ b/packages/openfilm/src/overrides.mjs@@ -29,6 +29,8 @@ export function override(c, list = []) {if (o.s != null) set(el, 'scale', Array.isArray(o.s) ? `${o.s[0]} ${o.s[1]}` : String(o.s));if (o.r != null) set(el, 'rotate', `${o.r}deg`);for (const [k, v] of Object.entries(o.style ?? {})) {+ /* a custom property (`--accent`) is set as it is named, its value as it is: what a number means is the page's */+ if (k.startsWith('--')) { set(el, k, String(v), 'important'); continue; }const prop = k.replace(/[A-Z]/g, (ch) => '-' + ch.toLowerCase());set(el, prop, typeof v === 'number' && !/opacity|z-index|font-weight|line-height|flex/.test(prop) ? v + 'px' : String(v), 'important');}diff --git a/packages/openfilm/src/overrides.test.mjs b/packages/openfilm/src/overrides.test.mjsnew file mode 100644index 0000000..8c06f14--- /dev/null+++ b/packages/openfilm/src/overrides.test.mjs@@ -0,0 +1,29 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { override, restore } from './overrides.mjs';++/** An element as override() uses it: its inline style, set and read back by name. */+function element() {+ const props = new Map();+ return {+ childNodes: [], children: [],+ style: {+ setProperty: (name, value, priority = '') => props.set(name, [value, priority]),+ removeProperty: (name) => props.delete(name),+ getPropertyValue: (name) => props.get(name)?.[0] ?? '',+ getPropertyPriority: (name) => props.get(name)?.[1] ?? '',+ },+ props,+ };+}++test('a custom property is set as it is named, its value as it is; a camelCase one as CSS names it', () => {+ const root = element();+ const c = { win: { document: { querySelectorAll: (at) => (at === ':root' ? [root] : []) } }, touched: new Map(), found: [] };+ override(c, [{ at: ':root', style: { '--accentColor': '#ff5746', '--count': 3, fontSize: 48 } }]);+ assert.deepEqual(root.props.get('--accentColor'), ['#ff5746', 'important'], 'case kept: custom properties are case-sensitive');+ assert.deepEqual(root.props.get('--count'), ['3', 'important'], 'no unit added');+ assert.deepEqual(root.props.get('font-size'), ['48px', 'important']);+ restore(c);+ assert.equal(root.props.size, 0, 'taken away, nothing left behind');+});diff --git a/packages/openfilm/src/shared.d.mts b/packages/openfilm/src/shared.d.mtsindex 654c6dc..fc839c1 100644--- a/packages/openfilm/src/shared.d.mts+++ b/packages/openfilm/src/shared.d.mts@@ -4,6 +4,10 @@ export interface MixClip { file: string; at: number; from: number; to?: number;export declare function audioClips(root: string, entry: string, clips: Array<{ src: string; at?: number; from?: number; to?: number; volume?: number; speed?: number; fade?: readonly [number, number] }> | undefined, from?: number): MixClip[];export declare function fadeFilter(fade: MixFade | undefined): string;export declare function mix(clips: MixClip[], duration: number, file: string, codec?: string[]): Promise<void>;+/** A mix's inputs and filter graph: a file used by several clips is one input, split. */+export declare function mixGraph(clips: MixClip[], duration: number): { inputs: string[]; filter: string };+/** How long a mix's command may be before its graph goes in a file. */+export declare const COMMAND_ROOM: number;/** A film opened in a browser to be drawn: what `look` and `render` start from. */export interface OpenFilm {root: string; entry: string; dir: string; name: string;diff --git a/packages/openfilm/src/shared.mjs b/packages/openfilm/src/shared.mjsindex 59965a9..7fa8408 100644--- a/packages/openfilm/src/shared.mjs+++ b/packages/openfilm/src/shared.mjs@@ -1,6 +1,6 @@import { spawn, spawnSync } from 'node:child_process';import { createHash } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, dirname, join, relative, resolve, sep } from 'node:path';import { FilmPage, FrameError, launch, serve } from './host.mjs';import { FILM_FILE, readFilmFile } from './film-doc.mjs';@@ -238,20 +238,79 @@ export function fadeFilter(fade) {}/** Mix clips into one track of `duration` seconds. */-export function mix(clips, duration, file, codec = ['-c:a', 'aac', '-b:a', '192k']) {- /* each input seeks to its part (-ss/-t): a clip from deep inside a long recording is not decoded from the start */- const inputs = clips.flatMap((c) => [...(c.from > 0 ? ['-ss', String(c.from)] : []), ...(c.to != null ? ['-t', String(c.to - c.from)] : []), '-vn', '-i', c.file]);+export async function mix(clips, duration, file, codec = ['-c:a', 'aac', '-b:a', '192k']) {+ const { inputs, filter } = mixGraph(clips, duration);+ /* a mix takes seconds; one that has not ended in minutes never will */+ const timeoutMs = (120 + duration * 2) * 1000;+ /* a long graph goes in a file of its own: a command line has a limit (32,767 characters on Windows), and a film of+ hundreds of sounds passes it */+ const long = filter.length + inputs.reduce((n, a) => n + a.length + 3, 0) > COMMAND_ROOM;+ const script = long ? `${file}.${process.pid}.filter` : null;+ if (script) writeFileSync(script, filter);+ try {+ const graph = script ? [await filterScriptOption(), script] : ['-filter_complex', filter];+ await ffmpeg([...inputs, ...graph, '-map', '[out]', '-t', String(duration), ...codec, file], { timeoutMs, what: 'mixing the sound' }).done;+ } finally {+ if (script) rmSync(script, { force: true });+ }+}++/** How long a mix's command may be before its graph goes in a file: well under Windows' limit, with room for the rest. */+export const COMMAND_ROOM = 24_000;++/**+ * The inputs and the filter graph of a mix. A file used by one sound is an input that seeks to its part (-ss/-t: a+ * clip deep inside a long recording is not decoded from the start); one used by several is read once and split, each+ * part cut from it, so a film that uses one sound a hundred times has one input, not a hundred.+ */+export function mixGraph(clips, duration) {+ /** @type {Map<string, number[]>} */+ const uses = new Map();+ clips.forEach((c, i) => uses.set(c.file, [...(uses.get(c.file) ?? []), i]));+ const inputs = [];+ const splits = [];+ /** @type {string[]} */+ const source = [];+ for (const [path, at] of uses) {+ const n = inputs.filter((a) => a === '-i').length;+ if (at.length === 1) {+ const c = clips[at[0]];+ inputs.push(...(c.from > 0 ? ['-ss', String(c.from)] : []), ...(c.to != null ? ['-t', String(c.to - c.from)] : []), '-vn', '-i', path);+ source[at[0]] = `[${n}:a]`;+ } else {+ inputs.push('-vn', '-i', path);+ splits.push(`[${n}:a]asplit=${at.length}${at.map((i) => `[s${i}]`).join('')}`);+ for (const i of at) {+ const c = clips[i];+ const cut = c.from > 0 || c.to != null ? `atrim=${c.from > 0 ? `start=${c.from}` : ''}${c.from > 0 && c.to != null ? ':' : ''}${c.to != null ? `end=${c.to}` : ''},` : '';+ source[i] = `[s${i}]${cut}`;+ }+ }+ }const chains = clips.map((c, i) => {const fade = fadeFilter(c.fade);const trim = `asetpts=PTS-STARTPTS${c.speed && c.speed !== 1 ? `,${tempo(c.speed)}` : ''}${fade ? `,${fade}` : ''}`;const delay = Math.round(c.at * 1000);- return `[${i}:a]${trim},volume=${c.volume},adelay=${delay}:all=1,aresample=48000,aformat=channel_layouts=stereo[a${i}]`;+ return `${source[i]}${trim},volume=${c.volume},adelay=${delay}:all=1,aresample=48000,aformat=channel_layouts=stereo[a${i}]`;});/* padded to the film's length and no further, and cut there: the mix always ends */const sum = `${clips.map((_, i) => `[a${i}]`).join('')}amix=inputs=${clips.length}:normalize=0:dropout_transition=0,apad=whole_dur=${duration},atrim=0:${duration}[out]`;- /* a mix takes seconds; one that has not ended in minutes never will */- const timeoutMs = (120 + duration * 2) * 1000;- return ffmpeg([...inputs, '-filter_complex', [...chains, sum].join(';'), '-map', '[out]', '-t', String(duration), ...codec, file], { timeoutMs, what: 'mixing the sound' }).done;+ return { inputs, filter: [...splits, ...chains, sum].join(';') };+}++/** @type {Promise<string> | null} */+let scriptOption = null;+/**+ * The option that reads a filter graph from a file: `-/filter_complex` since ffmpeg 7, `-filter_complex_script` before+ * (the one older builds know; newer ones drop it).+ */+function filterScriptOption() {+ scriptOption ??= new Promise((done) => {+ const r = spawnSync('ffmpeg', ['-hide_banner', '-version'], { encoding: 'utf8', windowsHide: true });+ const major = Number(/^ffmpeg version n?(\d+)\./m.exec(String(r.stdout ?? ''))?.[1]);+ done(Number.isFinite(major) && major < 7 ? '-filter_complex_script' : '-/filter_complex');+ });+ return scriptOption;}/**diff --git a/packages/openfilm/src/shared.test.mjs b/packages/openfilm/src/shared.test.mjsindex 3a00795..3f7ddb8 100644--- a/packages/openfilm/src/shared.test.mjs+++ b/packages/openfilm/src/shared.test.mjs@@ -1,10 +1,10 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { spawnSync } from 'node:child_process';-import { audioClips, checkSound, fadeFilter, ffmpeg, fileOf, mix } from './shared.mjs';+import { COMMAND_ROOM, audioClips, checkSound, fadeFilter, ffmpeg, fileOf, mix, mixGraph } from './shared.mjs';import { addLinkedPlaces } from './media-links.mjs';test('an ffmpeg that does not end is stopped, and says what did not finish', { timeout: 20_000 }, async () => {@@ -140,3 +140,44 @@ test('checkSound: a sound\'s numbers are numbers before they reach ffmpeg', () =assert.throws(() => checkSound({ ...sound, src: 7 }), /src must be a path/);assert.throws(() => audioClips('/nowhere', 'film.html', [{ ...sound, speed: 'fast' }]), /speed must be a number/);});++test('a sound used by many clips is one input, split and cut in the graph: the same mix as one input each', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'openfilm-mix-shared-'));+ try {+ const tone = join(dir, 'tone.wav');+ spawnSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=330:duration=2:sample_rate=48000', tone]);+ copyFileSync(tone, join(dir, 'copy.wav'));+ const parts = [{ at: 0, from: 0.25, to: 0.75 }, { at: 1, from: 1, to: 1.5 }, { at: 2, from: 0, to: 0.5, fade: { in: 0.1, out: 0.1, length: 0.5, skip: 0 } }];+ const clip = (file, p) => ({ file, volume: 1, speed: 1, ...p });+ const shared = parts.map((p) => clip(tone, p));+ const { inputs } = mixGraph(shared, 3);+ assert.equal(inputs.filter((a) => a === '-i').length, 1, 'one input for one file');+ const one = join(dir, 'one.wav'), each = join(dir, 'each.wav');+ await mix(shared, 3, one, ['-c:a', 'pcm_s16le']);+ /* the same parts, each from a file of its own: each its own input, seeking to its part */+ await mix([clip(tone, parts[0]), clip(join(dir, 'copy.wav'), parts[1]), clip(join(dir, 'tone-3.wav'), parts[2])].map((c, i) => (i === 2 ? { ...c, file: (copyFileSync(tone, join(dir, 'tone-3.wav')), join(dir, 'tone-3.wav')) } : c)), 3, each, ['-c:a', 'pcm_s16le']);+ for (const t of [0.2, 0.5, 1.25, 1.7, 2.05, 2.25, 2.6]) assert.ok(Math.abs(levelAt(one, t) - levelAt(each, t)) < 0.01, `the same sound at ${t} s`);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test('a mix of hundreds of sounds keeps its command short: its graph goes in a file, gone once mixed', { timeout: 120_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'openfilm-mix-many-'));+ try {+ const tick = join(dir, 'tick.wav');+ spawnSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=880:duration=0.1:sample_rate=48000', tick]);+ const clips = Array.from({ length: 300 }, (_, i) => ({ file: tick, at: i * 0.05, from: 0, to: 0.05, volume: 0.5, speed: 1 }));+ const { inputs, filter } = mixGraph(clips, 15);+ assert.ok(filter.length > COMMAND_ROOM, 'too long for one command line');+ assert.ok(inputs.join(' ').length < 1000, 'one input, not three hundred');+ const out = join(dir, 'many.wav');+ await mix(clips, 15, out, ['-c:a', 'pcm_s16le']);+ const seconds = Number(spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', out], { encoding: 'utf8' }).stdout);+ assert.ok(Math.abs(seconds - 15) < 0.01, `${seconds} s`);+ assert.ok(levelAt(out, 7.525) > 0.01 && levelAt(out, 7.575) < levelAt(out, 7.525) * 2, 'a tick where one plays');+ assert.deepEqual(readdirSync(dir).filter((f) => f.endsWith('.filter')), [], 'the graph file is gone');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/packages/openfilm/src/skills-cli.mjs b/packages/openfilm/src/skills-cli.mjsnew file mode 100644index 0000000..2657b8e--- /dev/null+++ b/packages/openfilm/src/skills-cli.mjs@@ -0,0 +1,174 @@+// @ts-check+/**+ * `openfilm skills`, `openfilm skill <name>`, `openfilm skill add <address | folder>` and `openfilm skill remove+ * <name>` (src/skills.mjs): the skills a film can be made with, one read whole, one added to the person's own, one of+ * theirs moved to the trash. Each resolves to `{ ok, lines, usage? }`. Skills kept where they used to be are moved+ * first (migrateMySkills).+ *+ * Adding from an address is two steps for an app to show what came before it is kept: previewSkills fetches it into+ * a folder of its own beside the person's skills, commitSkills keeps it, discardSkills lets it go. A folder on this+ * computer is looked at where it is (previewFolder) and copied in when kept (addSkills).+ */+import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';+import { mkdir, mkdtemp, rm } from 'node:fs/promises';+import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { FILM_FILE } from './film-doc.mjs';+import { addSkills, findSkill, folderSize, holdsSkills, listSkills, migrateMySkills, mySkillsDir, readSkill, removeSkill, skillText, skillsIn, PROJECT_SKILLS } from './skills.mjs';++/** The project around a folder (the nearest film.html above), or null. @param {string} from */+export function projectAround(from) {+ for (let up = resolve(from); up !== dirname(up); up = dirname(up)) if (existsSync(join(up, FILM_FILE))) return up;+ return null;+}++const SOURCE = { project: 'this project', mine: 'yours', official: 'official' };+/** a path as the person reads it: from the current folder when it is under it */+const shown = (/** @type {string} */ p) => { const r = relative(process.cwd(), p); return r && !r.startsWith('..') ? r : p; };++/** `openfilm skills`: every skill the project around here (if any) can be made with. @param {string} run */+export function skillsCommand(run, { cwd = process.cwd() } = {}) {+ migrateMySkills();+ const project = projectAround(cwd);+ const skills = listSkills({ project });+ if (!skills.length) {+ return { ok: true, lines: [`No skills yet. \`${run} skill add <GitHub address or folder>\` adds one to yours (${shown(mySkillsDir())}).`] };+ }+ const width = Math.min(28, Math.max(...skills.map((s) => s.name.length)));+ return {+ ok: true,+ lines: [+ `Skills${project ? ' for this film' : ''}. \`${run} skill <name>\` prints one: read it whole before you follow it.`,+ '',+ ...skills.flatMap((s) => [+ ` ${s.name.padEnd(width)} ${SOURCE[s.source]}${s.over ? ` (in place of the ${s.over.map((o) => SOURCE[o]).join(' and ')} one)` : ''} · ${shown(s.folder)}`,+ ...(s.description ? [` ${' '.repeat(width)} ${s.description}`] : []),+ ]),+ ],+ };+}++/** The skills in a folder: it one, or each in it (or in its skills/). @param {string} dir */+const skillsAt = (dir) => { const one = readSkill(dir, 'mine'); return one ? [one] : [...skillsIn(dir, 'mine'), ...skillsIn(join(dir, PROJECT_SKILLS), 'mine')]; };++/**+ * Fetch skills from a GitHub or GitLab address into a folder of their own beside the person's skills (never among+ * them), to be looked at before they are kept: `{ staging, skills }`, each skill with its size and whether one of the+ * same name is the person's already (`replaces`). Nothing fetched: the folder is gone and this throws.+ * @param {string} url @param {{ mine?: string, fetch?: (url: string, into: string) => Promise<string> }} [opts]+ */+export async function previewSkills(url, { mine = mySkillsDir(), fetch = fetchSkill } = {}) {+ await mkdir(mine, { recursive: true });+ const work = await mkdtemp(join(mine, '.adding-'));+ try {+ const staging = await fetch(url, work);+ /* the address, for commitSkills to keep as where they came from */+ writeFileSync(join(work, '.from'), url);+ const found = skillsAt(staging);+ if (!found.length || !holdsSkills(staging)) throw new Error(`There is no SKILL.md in ${url}: it is not a skill.`);+ return { staging: work, skills: looked(found, mine) };+ } catch (e) {+ await rm(work, { recursive: true, force: true }).catch(() => {});+ throw e;+ }+}++/** Skills as they are looked at before they are kept: each with its size and whether it replaces one of the person's. */+const looked = (/** @type {import('./skills.mjs').Skill[]} */ found, /** @type {string} */ mine) => {+ const mineNow = new Set(skillsIn(mine, 'mine').map((s) => s.name));+ return found.map((s) => ({ ...s, size: folderSize(s.folder), replaces: mineNow.has(s.name) }));+};++/**+ * The skills in a folder on this computer, looked at where they are before they are copied in (addSkills): as+ * previewSkills gives them (a SKILL.md given: its folder). A folder that is not a skill, or one of the person's own+ * already, throws.+ * @param {string} folder @param {{ mine?: string }} [opts]+ */+export function previewFolder(folder, { mine = mySkillsDir() } = {}) {+ /* a skill's SKILL.md stands for its folder */+ const src = basename(folder) === 'SKILL.md' ? dirname(resolve(folder)) : resolve(folder);+ const inside = relative(resolve(mine), src);+ if (!inside || (!inside.startsWith('..') && !isAbsolute(inside))) throw new Error('This folder is among your skills already.');+ let found = [];+ try { if (statSync(src).isDirectory()) found = skillsAt(src); } catch { /* not there */ }+ if (!found.length) throw new Error(`There is no SKILL.md in ${folder}: it is not a skill.`);+ return { folder: src, skills: looked(found, mine) };+}++/** A fetched folder (previewSkills' `staging`) only: one in the person's skills folder, made for a fetch. */+const ownFetch = (/** @type {string} */ staging, /** @type {string} */ mine) => resolve(dirname(staging)) === resolve(mine) && /^\.adding-/.test(staging.split(/[\\/]/).pop() ?? '');++/** Keep what previewSkills fetched: added to the person's own (one of the same name to the trash). → the skills kept. */+export async function commitSkills(/** @type {string} */ staging, { mine = mySkillsDir() } = {}) {+ if (!ownFetch(staging, mine)) throw new Error('Nothing is waiting to be added.');+ try {+ const [fetched] = readdirSync(staging).filter((n) => !n.startsWith('.')).map((n) => join(staging, n));+ if (!fetched) throw new Error('Nothing is waiting to be added.');+ let address = '';+ try { address = readFileSync(join(staging, '.from'), 'utf8').trim(); } catch { /* fetched before addresses were kept */ }+ return await addSkills(fetched, { mine, ...(address ? { origin: { from: 'link', address } } : {}) });+ } finally {+ await rm(staging, { recursive: true, force: true }).catch(() => {});+ }+}++/** Let go of what previewSkills fetched (it was never the person's). */+export async function discardSkills(/** @type {string} */ staging, { mine = mySkillsDir() } = {}) {+ if (ownFetch(staging, mine)) await rm(staging, { recursive: true, force: true }).catch(() => {});+}++/**+ * Add skills to the person's own from a GitHub or GitLab address (fetched without its history) or a folder on this+ * computer (copied): one skill, or a folder of them. → the skills added.+ * @param {string} from @param {{ cwd?: string, mine?: string, fetch?: (url: string, into: string) => Promise<string> }} [opts]+ */+export async function addSkillFrom(from, { cwd = process.cwd(), mine = mySkillsDir(), fetch = fetchSkill } = {}) {+ if (!/^https?:\/\//i.test(from)) {+ if (!existsSync(resolve(cwd, from))) throw Object.assign(new Error(`there is no folder ${from}`), { code: 'url' });+ return addSkills(resolve(cwd, from), { mine });+ }+ const { staging } = await previewSkills(from, { mine, fetch });+ return commitSkills(staging, { mine });+}++/**+ * `openfilm skill <name>`, or `openfilm skill add <address | folder>`.+ * @param {string[]} args @param {string} run @param {Parameters<typeof addSkillFrom>[1]} [opts]+ */+export async function skillCommand(args, run, opts = {}) {+ migrateMySkills();+ const [first, second] = args;+ if (!first) return { ok: false, usage: true, lines: [`${run} skill <name> prints a skill; ${run} skill add <GitHub address or folder> adds one. ${run} skills lists them.`] };+ if (first === 'add') {+ if (!second) return { ok: false, usage: true, lines: [`${run} skill add <GitHub address or folder>`] };+ try {+ const added = await addSkillFrom(second, opts);+ return {+ ok: true,+ lines: added.flatMap((s) => [+ `Added ${s.name}${s.description ? `: ${s.description}` : ''}`,+ ` ${shown(s.folder)}`,+ ...(s.scripts.length ? [` It brings scripts an agent can run: ${s.scripts.join(', ')}`] : []),+ ]).concat(added.some((s) => s.scripts.length) ? ['A skill\'s scripts run with your agent\'s access: keep only skills you trust.'] : []),+ };+ } catch (e) {+ const code = /** @type {any} */ (e)?.code;+ return { ok: false, usage: code === 'url' || code === 'host', lines: [`${run} skill add: ${e instanceof Error ? e.message : String(e)}`] };+ }+ }+ if (first === 'remove') {+ if (!second) return { ok: false, usage: true, lines: [`${run} skill remove <name>`] };+ const gone = await removeSkill(second, opts.mine ? { mine: opts.mine } : {});+ return gone ? { ok: true, lines: [`Moved ${second} to the trash: you can take it back from there.`] }+ : { ok: false, usage: true, lines: [`${run} skill remove: ${second} is not one of yours (${shown(opts.mine ?? mySkillsDir())}).`] };+ }+ const skill = findSkill(first, { project: projectAround(opts.cwd ?? process.cwd()), ...(opts.mine ? { mine: opts.mine } : {}) });+ if (!skill) return { ok: false, usage: true, lines: [`${run} skill: no skill ${first}. \`${run} skills\` lists them.`] };+ return { ok: true, lines: [skillText(skill)] };+}++/** A skill on GitHub or GitLab, fetched into a folder of `into` (src/../studio/server/fetch-repo.mjs). */+async function fetchSkill(/** @type {string} */ url, /** @type {string} */ into) {+ const { fetchFilm, parseRepoUrl } = await import('../studio/server/fetch-repo.mjs');+ return fetchFilm(parseRepoUrl(url), { library: into, skill: true });+}diff --git a/packages/openfilm/src/skills.mjs b/packages/openfilm/src/skills.mjsnew file mode 100644index 0000000..e9eac0e--- /dev/null+++ b/packages/openfilm/src/skills.mjs@@ -0,0 +1,348 @@+// @ts-check+/**+ * Skills: ways of making a kind of film that an agent takes up when asked. A skill is a folder in the Agent Skills+ * format (agentskills.io): a `SKILL.md` whose front matter names it and says what it is for (`name`, `description`),+ * its body the way to work, and any files it brings (scripts, templates, libraries). A skill never changes OpenFilm+ * itself: what it makes is pages and media in the project, like anything else an agent writes.+ *+ * Three places hold them, the first a name is found in winning:+ * project `<project>/skills/<name>/`, kept with the project, so a film carries the ways it was made+ * mine `Skills/` beside the projects library (~/Movies/OpenFilm/Skills on macOS, ~/Videos/OpenFilm/Skills+ * elsewhere; OPENFILM_SKILLS to name another): the person's own, and those they added. In sight beside+ * their Projects and Exports, backed up with them, and never in Studio's own folder, which a reset clears.+ * Skills kept in Studio's home before (~/.openfilm/skills) are moved there (migrateMySkills).+ * official `skills/` in this package, released with OpenFilm+ *+ * Nothing here deletes a skill outright: one replaced or removed goes to the system's trash.+ *+ * `openfilm skills` lists them and `openfilm skill <name>` prints one, as `openfilm` prints the manual: that is how any+ * agent reads a skill. The desktop app's chat offers the same list (apps/desktop).+ */+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { cp, mkdir, rename, rm } from 'node:fs/promises';+import { homedir } from 'node:os';+import { basename, dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { moveToTrash } from '../studio/server/trash.mjs';+import { libraryDefault } from './locations.mjs';++const mkdirSyncSafe = (/** @type {string} */ dir) => mkdirSync(dir, { recursive: true });+/** a folder moved to another place: renamed, else (another disk) copied and then removed */+function renameSyncSafe(/** @type {string} */ from, /** @type {string} */ to) {+ try { renameSync(from, to); } catch (e) {+ if (/** @type {any} */ (e)?.code !== 'EXDEV') throw e;+ cpSync(from, to, { recursive: true });+ rmSync(from, { recursive: true, force: true });+ }+}++export const SKILL_FILE = 'SKILL.md';+/** The project's own skills, beside film.html. */+export const PROJECT_SKILLS = 'skills';+/** The places skills are looked for, the first winning a name. */+export const SKILL_SOURCES = /** @type {const} */ (['project', 'mine', 'official']);+/** @typedef {typeof SKILL_SOURCES[number]} SkillSource */++/**+ * The official skills, released with this package (a copy of openfilm/skills: `pnpm skills:sync`).+ * OPENFILM_OFFICIAL_SKILLS names another folder of them: a checkout's skills/, while they are being changed.+ */+export const officialSkillsDir = () => process.env.OPENFILM_OFFICIAL_SKILLS || join(dirname(fileURLToPath(import.meta.url)), '..', 'skills');+/**+ * The person's own skills: OPENFILM_SKILLS, else `Skills/` beside the default projects library (OPENFILM_LIBRARY, else+ * ~/Movies/OpenFilm/Projects on macOS, ~/Videos/OpenFilm/Projects elsewhere: locations.mjs libraryDefault). They stay+ * there when new projects are set to go elsewhere.+ */+export const mySkillsDir = () => process.env.OPENFILM_SKILLS || join(dirname(libraryDefault()), 'Skills');+/** Where the person's own skills were kept before: `skills/` in Studio's home. */+export const oldSkillsDir = () => join(process.env.OPENFILM_HOME || join(homedir(), '.openfilm'), 'skills');++/** A note left where the skills were, saying where they went. */+const MOVED_NOTE = 'README.txt';++/**+ * Move the person's own skills from where they were kept before (Studio's home) to their place beside the projects.+ * Each skill whose name is free there goes; one whose name is taken stays, and the note left says so. Run whenever the+ * skills are listed; it does nothing once they have moved. → the names moved.+ * @param {{ from?: string, to?: string }} [where]+ */+export function migrateMySkills({ from = oldSkillsDir(), to = mySkillsDir() } = {}) {+ if (resolve(from) === resolve(to) || !existsSync(from)) return [];+ const waiting = skillsIn(from, 'mine');+ if (!waiting.length) return [];+ /** @type {string[]} */+ const moved = [];+ /** @type {string[]} */+ const kept = [];+ try { mkdirSyncSafe(to); } catch { return []; }+ for (const skill of waiting) {+ const target = join(to, basename(skill.folder));+ if (existsSync(target)) { kept.push(basename(skill.folder)); continue; }+ try { renameSyncSafe(skill.folder, target); moved.push(skill.name); } catch { kept.push(basename(skill.folder)); }+ }+ try {+ writeFileSync(join(from, MOVED_NOTE), `Your OpenFilm skills are kept in ${to} now.+${kept.length ? `These stayed here, as a skill of the same name is there: ${kept.join(', ')}.+` : ''}`);+ } catch { /* the note is only a courtesy */ }+ return moved;+}++/** a skill's name, as the format allows it: lowercase letters, digits and dashes */+export const SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;++/**+ * The front matter of a SKILL.md: its flat `key: value` lines, values plain, quoted, or a block (`|`, `>`) of the+ * lines indented under them. Enough for `name` and `description`; anything else is kept as text.+ * @param {string} text+ * @returns {{ fields: Record<string, string>, body: string }}+ */+export function parseSkillFile(text) {+ const m = /^?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);+ if (!m) return { fields: {}, body: text.trim() };+ /** @type {Record<string, string>} */+ const fields = {};+ const lines = m[1].split(/\r?\n/);+ for (let i = 0; i < lines.length; i++) {+ const kv = /^([A-Za-z][\w-]*):(.*)$/.exec(lines[i]);+ if (!kv) continue;+ const [, key, raw] = kv;+ let value = raw.trim();+ if (/^[|>][+-]?$/.test(value)) {+ const block = [];+ while (i + 1 < lines.length && (/^\s/.test(lines[i + 1]) || lines[i + 1] === '')) block.push(lines[++i]);+ const indent = Math.min(...block.filter((l) => l.trim()).map((l) => /^\s*/.exec(l)?.[0].length ?? 0));+ const kept = block.map((l) => l.slice(Number.isFinite(indent) ? indent : 0));+ value = (value.startsWith('>') ? kept.join(' ').replace(/\s+/g, ' ') : kept.join('\n')).trim();+ } else if (/^"(?:[^"\\]|\\.)*"$/.test(value)) {+ try { value = JSON.parse(value); } catch { value = value.slice(1, -1); }+ } else if (/^'.*'$/.test(value)) {+ value = value.slice(1, -1).replace(/''/g, "'");+ } else {+ /* a plain value may go on over the lines indented under it */+ while (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1])) value += ` ${lines[++i].trim()}`;+ }+ fields[key] = value;+ }+ return { fields, body: text.slice(m[0].length).trim() };+}++/**+ * @typedef {{ name: string, description: string, folder: string, source: SkillSource, file: string,+ * scripts: string[], over?: SkillSource[], shown?: SkillShown, version?: string } & SkillLook} Skill+ * `over`: the places that had a skill of the same name, which this one takes the place of. `version`: its+ * openfilm.json's, else its front matter's.+ * @typedef {{ title: Record<string, string>, summary: Record<string, string>, details?: Record<string, string> }} SkillShown+ * how people see it in an app (openfilm.json beside SKILL.md, optional): a title, a one-line summary and a few lines+ * on who it is for and what it does, by language (`en`, `zh-CN`…); the SKILL.md's description is for the agent+ * @typedef {{ kind?: 'workflow' | 'style', order?: number, icon?: string, cover?: string, preview?: string, repository?: string }} SkillLook+ * where an app shows it (openfilm.json, each optional): `kind` a way of working or a look, `order` among its kind,+ * `icon` a mark's name, `cover` a picture and `preview` a video in its folder, `repository` where its source is read+ */++/** The words of an openfilm.json field: a string (any language), or one per language; anything else is none. */+const byLanguage = (/** @type {unknown} */ v, max = 200) => (typeof v === 'string' && v.trim() ? { en: v.trim().slice(0, max) }+ : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).filter(([k, w]) => /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(k) && typeof w === 'string' && w.trim()).map(([k, w]) => [k, String(w).trim().slice(0, max)])) : {});++/** A file named by openfilm.json, when it is one in the skill's folder. @param {string} folder @param {unknown} name */+const fileIn = (folder, name) => (typeof name === 'string' && /^[\w./-]{1,200}$/.test(name) && !name.split('/').includes('..')+ && existsSync(join(folder, name)) ? name : undefined);++/**+ * A skill's openfilm.json: how people see it and where an app shows it (anything missing or wrong left out).+ * @param {string} folder @returns {{ shown?: SkillShown, version?: string } & SkillLook}+ */+function openfilmJson(folder) {+ let raw;+ try { raw = JSON.parse(readFileSync(join(folder, 'openfilm.json'), 'utf8')); } catch { return {}; }+ const details = byLanguage(raw?.details, 1000);+ /** @type {SkillShown} */+ const shown = { title: byLanguage(raw?.title), summary: byLanguage(raw?.summary), ...(Object.keys(details).length ? { details } : {}) };+ /** @type {{ shown?: SkillShown, version?: string } & SkillLook} */+ const out = {};+ if (Object.keys(shown.title).length || Object.keys(shown.summary).length) out.shown = shown;+ if (typeof raw?.version === 'string' && VERSION.test(raw.version)) out.version = raw.version;+ if (raw?.kind === 'workflow' || raw?.kind === 'style') out.kind = raw.kind;+ if (Number.isFinite(raw?.order)) out.order = raw.order;+ if (typeof raw?.icon === 'string' && /^[a-z][a-z0-9-]{0,23}$/.test(raw.icon)) out.icon = raw.icon;+ if (typeof raw?.repository === 'string' && /^https:\/\/[^\s]{4,300}$/.test(raw.repository)) out.repository = raw.repository;+ const cover = fileIn(folder, raw?.cover), preview = fileIn(folder, raw?.preview);+ if (cover) out.cover = cover;+ if (preview) out.preview = preview;+ return out;+}++const VERSION = /^\d+\.\d+(\.\d+)?([-+][\w.]+)?$/;++/**+ * The skill in one folder, or null when it has no SKILL.md. Its name is the front matter's, else the folder's.+ * @param {string} folder @param {SkillSource} source @returns {Skill | null}+ */+export function readSkill(folder, source) {+ const file = join(folder, SKILL_FILE);+ let text;+ try { text = readFileSync(file, 'utf8'); } catch { return null; }+ const { fields } = parseSkillFile(text);+ const name = (fields.name || basename(folder)).trim();+ const extra = openfilmJson(folder);+ if (!extra.version && fields.version && VERSION.test(fields.version.trim())) extra.version = fields.version.trim();+ return { name, description: (fields.description ?? '').trim(), folder, source, file, scripts: scriptsIn(folder), ...extra };+}++/** The scripts a skill brings (any file under scripts/, and executables anywhere), for the person to see. */+function scriptsIn(/** @type {string} */ folder) {+ /** @type {string[]} */+ const found = [];+ const walk = (/** @type {string} */ dir, /** @type {string} */ rel, depth = 0) => {+ if (depth > 4 || found.length >= 50) return;+ let entries = [];+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }+ for (const e of entries) {+ if (e.name.startsWith('.') || e.name === 'node_modules') continue;+ const path = rel ? `${rel}/${e.name}` : e.name;+ if (e.isDirectory()) walk(join(dir, e.name), path, depth + 1);+ else if (rel.split('/')[0] === 'scripts' || /\.(sh|py|mjs|cjs|js|ts|rb|pl|ps1|bat|cmd)$/i.test(e.name)) found.push(path);+ }+ };+ walk(folder, '');+ return found.sort();+}++/** The skills in one place: each folder in it with a SKILL.md. @param {string} dir @param {SkillSource} source */+export function skillsIn(dir, source) {+ let names = [];+ try { names = readdirSync(dir); } catch { return []; }+ return names.filter((n) => !n.startsWith('.')).flatMap((n) => {+ const folder = join(dir, n);+ try { if (!statSync(folder).isDirectory()) return []; } catch { return []; }+ const skill = readSkill(folder, source);+ return skill ? [skill] : [];+ });+}++/**+ * Every skill available to a project (or none: only the person's own and the official ones), by name, the first+ * place holding a name winning; sorted by name.+ * @param {{ project?: string | null, mine?: string, official?: string }} [where]+ * @returns {Skill[]}+ */+export function listSkills({ project = null, mine = mySkillsDir(), official = officialSkillsDir() } = {}) {+ /** @type {Map<string, Skill>} */+ const byName = new Map();+ const places = /** @type {Array<[string | null, SkillSource]>} */ ([[project ? join(project, PROJECT_SKILLS) : null, 'project'], [mine, 'mine'], [official, 'official']]);+ for (const [dir, source] of places) {+ if (!dir) continue;+ for (const skill of skillsIn(dir, source)) {+ const first = byName.get(skill.name);+ if (first) first.over = [...(first.over ?? []), source];+ else byName.set(skill.name, skill);+ }+ }+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));+}++/** One skill by name, as listSkills finds it, or null. @param {string} name @param {Parameters<typeof listSkills>[0]} [where] */+export function findSkill(name, where) {+ return listSkills(where).find((s) => s.name === name) ?? null;+}++/**+ * A skill as an agent reads it: its name, where its files are (only read: what a film uses is copied into the+ * project), and its SKILL.md whole.+ * @param {Skill} skill+ */+export function skillText(skill) {+ return `<skill name="${skill.name}" folder="${skill.folder}">\n${readFileSync(skill.file, 'utf8').trim()}\n</skill>`;+}++/**+ * Add a skill to the person's own (`mine`): a folder on this computer, copied; or one fetched by the caller into+ * `from` (a GitHub or GitLab address, studio/server/fetch-repo.mjs). A folder holding several skills (each a folder+ * with a SKILL.md) adds them all. One of the same name is replaced. → the skills added.+ * Where each came from is kept beside them (skillOrigins).+ * @param {string} from @param {{ mine?: string, move?: boolean, origin?: SkillOrigin }} [opts] `move`: the folder is a+ * download of the caller's; `origin`: where it came from (default: the folder)+ * @returns {Promise<Skill[]>}+ */+export async function addSkills(from, { mine = mySkillsDir(), move = false, origin = { from: 'folder', address: resolve(from) } } = {}) {+ const src = resolve(from);+ const one = readSkill(src, 'mine');+ const found = one ? [one] : skillsIn(src, 'mine').concat(skillsIn(join(src, PROJECT_SKILLS), 'mine'));+ if (!found.length) throw new Error(`There is no ${SKILL_FILE} in ${from}: it is not a skill.`);+ await mkdir(mine, { recursive: true });+ /** @type {Skill[]} */+ const added = [];+ for (const skill of found) {+ const name = SKILL_NAME.test(skill.name) ? skill.name : basename(skill.folder).toLowerCase().replace(/[^a-z0-9-]+/g, '-').split('-').filter(Boolean).join('-') || 'skill';+ const to = join(mine, name);+ const staging = `${to}.adding-${process.pid}`;+ await rm(staging, { recursive: true, force: true });+ if (move && found.length === 1) await rename(skill.folder, staging);+ else await cp(skill.folder, staging, { recursive: true, filter: (p) => basename(p) !== '.git' });+ /* one of the same name is replaced: the one there goes to the trash, never deleted */+ if (existsSync(to)) await moveToTrash(to);+ await rename(staging, to);+ const kept = readSkill(to, 'mine');+ if (kept) added.push(kept);+ }+ noteOrigins(mine, Object.fromEntries(added.map((k) => [basename(k.folder), { ...origin, added: new Date().toISOString() }])));+ return added;+}++/**+ * @typedef {{ from: 'link' | 'folder', address: string, added?: string }} SkillOrigin+ * where one of the person's skills came from: a GitHub or GitLab address, or a folder on this computer. One with+ * none was made where it is (with the agent, or by hand).+ */++const ORIGINS = '.origins.json';++/** Where each of the person's skills came from, by its folder's name. @param {string} [mine] @returns {Record<string, SkillOrigin>} */+export function skillOrigins(mine = mySkillsDir()) {+ try {+ const raw = JSON.parse(readFileSync(join(mine, ORIGINS), 'utf8'));+ return Object.fromEntries(Object.entries(raw ?? {}).filter(([, o]) => (o?.from === 'link' || o?.from === 'folder') && typeof o.address === 'string'));+ } catch { return {}; }+}++/** Keep (or with null, forget) where skills came from. @param {string} mine @param {Record<string, SkillOrigin | null>} changes */+function noteOrigins(mine, changes) {+ const all = { ...skillOrigins(mine), ...changes };+ for (const [k, v] of Object.entries(all)) if (!v) delete all[k];+ try { writeFileSync(join(mine, ORIGINS), `${JSON.stringify(all, null, 2)}\n`); } catch { /* a skill without its origin is still a skill */ }+}++/**+ * Remove one of the person's own skills: to the system's trash, where it can be taken back. → whether it was there.+ * @param {string} name @param {{ mine?: string }} [where]+ */+export async function removeSkill(name, { mine = mySkillsDir() } = {}) {+ const skill = skillsIn(mine, 'mine').find((s) => s.name === name);+ if (!skill || resolve(dirname(skill.folder)) !== resolve(mine)) return false;+ await moveToTrash(skill.folder);+ noteOrigins(mine, { [basename(skill.folder)]: null });+ return true;+}++/** How many bytes a folder holds (its .git left out). @param {string} dir */+export function folderSize(dir) {+ let total = 0;+ const walk = (/** @type {string} */ d) => {+ let entries = [];+ try { entries = readdirSync(d, { withFileTypes: true }); } catch { return; }+ for (const e of entries) {+ if (e.name === '.git') continue;+ const p = join(d, e.name);+ if (e.isDirectory()) walk(p);+ else { try { total += statSync(p).size; } catch { /* gone */ } }+ }+ };+ walk(dir);+ return total;+}++/** Whether a folder holds a skill, or skills (each a folder with a SKILL.md, or under skills/). @param {string} dir */+export function holdsSkills(dir) {+ if (existsSync(join(dir, SKILL_FILE))) return true;+ return skillsIn(dir, 'mine').length > 0 || skillsIn(join(dir, PROJECT_SKILLS), 'mine').length > 0;+}diff --git a/packages/openfilm/src/skills.test.mjs b/packages/openfilm/src/skills.test.mjsnew file mode 100644index 0000000..b5830f6--- /dev/null+++ b/packages/openfilm/src/skills.test.mjs@@ -0,0 +1,236 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { cpSync, mkdirSync, mkdtempSync, writeFileSync, existsSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { addSkills, findSkill, listSkills, migrateMySkills, mySkillsDir, parseSkillFile, readSkill, removeSkill, skillOrigins, skillText } from './skills.mjs';+import { commitSkills, discardSkills, previewFolder, previewSkills, skillCommand, skillsCommand } from './skills-cli.mjs';++const skill = (dir, name, description, body = 'How to make it.', extra = {}) => {+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}\n`);+ for (const [file, text] of Object.entries(extra)) {+ mkdirSync(join(dir, file, '..'), { recursive: true });+ writeFileSync(join(dir, file), text);+ }+ return dir;+};++test('a SKILL.md front matter: plain, quoted and block values; the body after it', () => {+ const { fields, body } = parseSkillFile([+ '---',+ 'name: lyric-pv',+ 'description: "Lyric videos: words on the beat"',+ 'license: \'MIT\'',+ 'when: |',+ ' a song',+ ' with words',+ 'note: >',+ ' folded',+ ' into one',+ 'long: starts here',+ ' and goes on',+ '---',+ '',+ '# Lyric PV',+ ].join('\n'));+ assert.deepEqual(fields, { name: 'lyric-pv', description: 'Lyric videos: words on the beat', license: 'MIT', when: 'a song\nwith words', note: 'folded into one', long: 'starts here and goes on' });+ assert.equal(body, '# Lyric PV');+ assert.deepEqual(parseSkillFile('no front matter').fields, {});+});++test('skills are listed from the project, then yours, then the official ones, the first holding a name winning', () => {+ const root = mkdtempSync(join(tmpdir(), 'of-skills-'));+ const project = join(root, 'film');+ const mine = join(root, 'mine');+ const official = join(root, 'official');+ skill(join(project, 'skills', 'brand'), 'brand', 'This film\'s brand');+ skill(join(mine, 'brand'), 'brand', 'My brand');+ skill(join(mine, 'lyric-pv'), 'lyric-pv', 'Lyric videos', 'Use the engine.', { 'scripts/build.sh': 'echo', 'lib/engine.js': '' });+ skill(join(official, 'brand'), 'brand', 'Official brand');+ mkdirSync(join(mine, 'not-a-skill'), { recursive: true });+ const all = listSkills({ project, mine, official });+ assert.deepEqual(all.map((s) => [s.name, s.source, s.description]), [['brand', 'project', 'This film\'s brand'], ['lyric-pv', 'mine', 'Lyric videos']]);+ assert.deepEqual(all[0].over, ['mine', 'official']);+ assert.deepEqual(all[1].scripts, ['lib/engine.js', 'scripts/build.sh'], 'what an agent could run, for the person to see');+ assert.equal(listSkills({ mine, official }).find((s) => s.name === 'brand').source, 'mine', 'without a project, yours first');+ assert.equal(findSkill('nothing', { mine, official }), null);+ const text = skillText(all[1]);+ assert.match(text, /^<skill name="lyric-pv" folder=".*mine[\\/]lyric-pv">\n---/);+ assert.match(text, /Use the engine\.\n<\/skill>$/);+});++test('a skill is named by its front matter, else its folder', () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-skill-'));+ mkdirSync(join(dir, 'kinetic'));+ writeFileSync(join(dir, 'kinetic', 'SKILL.md'), 'Just words.');+ assert.equal(readSkill(join(dir, 'kinetic'), 'mine').name, 'kinetic');+});++test('adding a skill copies it into yours (a folder of skills adds each), the one of the same name to the trash', async () => {+ const root = mkdtempSync(join(tmpdir(), 'of-add-'));+ const mine = join(root, 'mine');+ process.env.OPENFILM_TRASH_DIR = join(root, 'trash');+ skill(join(mine, 'brand'), 'brand', 'Old');+ const one = skill(join(root, 'src', 'brand-kit'), 'brand', 'New', 'b', { '.git/HEAD': 'x' });+ const added = await addSkills(one, { mine });+ assert.deepEqual(added.map((s) => [s.name, s.description]), [['brand', 'New']]);+ assert.ok(!existsSync(join(mine, 'brand', '.git')), 'no git history');+ assert.ok(existsSync(one), 'a folder of the person\'s is copied, not moved');+ assert.match(readFileSync(join(root, 'trash', 'brand', 'SKILL.md'), 'utf8'), /Old/, 'the one replaced is in the trash');+ assert.equal(await removeSkill('brand', { mine }), true);+ assert.ok(!existsSync(join(mine, 'brand')));+ assert.ok(existsSync(join(root, 'trash', 'brand 2')), 'removed: to the trash too');+ assert.equal(await removeSkill('nothing', { mine }), false);++ const pack = join(root, 'pack');+ skill(join(pack, 'skills', 'a'), 'a', 'A');+ skill(join(pack, 'skills', 'b'), 'b', 'B');+ assert.deepEqual((await addSkills(pack, { mine })).map((s) => s.name).sort(), ['a', 'b']);+ await assert.rejects(addSkills(join(root, 'src'), { mine: join(root, 'other') }).then(() => addSkills(mkdtempSync(join(tmpdir(), 'empty-')), { mine })), /not a skill/);+ delete process.env.OPENFILM_TRASH_DIR;+});++test('yours are kept beside the projects, and those kept in Studio\'s home before move there', () => {+ const before = { library: process.env.OPENFILM_LIBRARY, skills: process.env.OPENFILM_SKILLS };+ const root = mkdtempSync(join(tmpdir(), 'of-mine-'));+ delete process.env.OPENFILM_SKILLS;+ process.env.OPENFILM_LIBRARY = join(root, 'OpenFilm', 'Projects');+ try {+ assert.equal(mySkillsDir(), join(root, 'OpenFilm', 'Skills'));+ const old = join(root, 'home', 'skills');+ skill(join(old, 'brand'), 'brand', 'Mine');+ skill(join(old, 'kinetic'), 'kinetic', 'Old copy');+ skill(join(root, 'OpenFilm', 'Skills', 'kinetic'), 'kinetic', 'Already there');+ assert.deepEqual(migrateMySkills({ from: old, to: mySkillsDir() }), ['brand']);+ assert.ok(existsSync(join(mySkillsDir(), 'brand', 'SKILL.md')));+ assert.match(readFileSync(join(mySkillsDir(), 'kinetic', 'SKILL.md'), 'utf8'), /Already there/, 'one there already is not overwritten');+ assert.match(readFileSync(join(old, 'README.txt'), 'utf8'), /kept in .*Skills now[\s\S]*kinetic/);+ assert.deepEqual(migrateMySkills({ from: old, to: mySkillsDir() }), [], 'once moved, nothing more');+ } finally {+ if (before.library === undefined) delete process.env.OPENFILM_LIBRARY; else process.env.OPENFILM_LIBRARY = before.library;+ if (before.skills !== undefined) process.env.OPENFILM_SKILLS = before.skills;+ }+});++test('adding from an address is looked at first: kept, or let go', async () => {+ const root = mkdtempSync(join(tmpdir(), 'of-preview-'));+ const mine = join(root, 'mine');+ skill(join(mine, 'lyric-pv'), 'lyric-pv', 'Mine');+ const fetch = async (_url, into) => { skill(join(into, 'pack', 'skills', 'lyric-pv'), 'lyric-pv', 'Theirs', 'x', { 'scripts/a.py': 'print(1)' }); skill(join(into, 'pack', 'skills', 'charts'), 'charts', 'Charts'); return join(into, 'pack'); };+ const seen = await previewSkills('https://github.com/x/y', { mine, fetch });+ assert.deepEqual(seen.skills.map((s) => [s.name, s.replaces, s.scripts.length]).sort(), [['charts', false, 0], ['lyric-pv', true, 1]]);+ assert.ok(seen.skills.every((s) => s.size > 0));+ assert.deepEqual(listSkills({ mine, official: join(root, 'none') }).map((s) => s.description), ['Mine'], 'nothing kept yet');+ process.env.OPENFILM_TRASH_DIR = join(root, 'trash');+ const kept = await commitSkills(seen.staging, { mine });+ delete process.env.OPENFILM_TRASH_DIR;+ assert.deepEqual(kept.map((s) => s.name).sort(), ['charts', 'lyric-pv']);+ assert.ok(!existsSync(seen.staging), 'the fetch is cleared');+ const again = await previewSkills('https://github.com/x/y', { mine, fetch });+ await discardSkills(again.staging, { mine });+ assert.ok(!existsSync(again.staging));+ await assert.rejects(commitSkills(join(root, 'elsewhere'), { mine }), /Nothing is waiting/);+});++test('a folder on this computer looked at where it is; one already among the person\'s own, or not a skill, refused', () => {+ const root = mkdtempSync(join(tmpdir(), 'of-folder-'));+ const mine = join(root, 'mine');+ skill(join(mine, 'charts'), 'charts', 'Mine');+ const pack = join(root, 'pack');+ skill(join(pack, 'charts'), 'charts', 'Theirs', 'x', { 'scripts/a.py': 'print(1)' });+ skill(join(pack, 'captions'), 'captions', 'Captions');+ const seen = previewFolder(pack, { mine });+ assert.deepEqual(seen.skills.map((s) => [s.name, s.replaces, s.scripts.length]).sort(), [['captions', false, 0], ['charts', true, 1]]);+ assert.deepEqual(previewFolder(join(pack, 'captions'), { mine }).skills.map((s) => s.name), ['captions'], 'one skill\'s own folder');+ assert.deepEqual(previewFolder(join(pack, 'captions', 'SKILL.md'), { mine }), previewFolder(join(pack, 'captions'), { mine }), 'its SKILL.md for it');+ assert.equal(readSkill(join(mine, 'charts'), 'mine')?.description, 'Mine', 'nothing copied yet');+ assert.throws(() => previewFolder(join(mine, 'charts'), { mine }), /among your skills/);+ assert.throws(() => previewFolder(mine, { mine }), /among your skills/);+ assert.throws(() => previewFolder(root + '-none', { mine }), /no SKILL\.md/);+ mkdirSync(join(root, 'empty'));+ assert.throws(() => previewFolder(join(root, 'empty'), { mine }), /no SKILL\.md/);+});++test('openfilm skills and skill: the list, one printed whole, one added from an address', async () => {+ const root = mkdtempSync(join(tmpdir(), 'of-cli-'));+ const home = join(root, 'home');+ const film = join(root, 'film');+ mkdirSync(film);+ writeFileSync(join(film, 'film.html'), '<!doctype html>');+ skill(join(film, 'skills', 'brand'), 'brand', 'This film\'s brand');+ const before = process.env.OPENFILM_SKILLS;+ const beforeHome = process.env.OPENFILM_HOME;+ process.env.OPENFILM_SKILLS = join(home, 'skills');+ /* the skills kept in Studio's home before, moved as the commands run: a scratch home, never the person's */+ process.env.OPENFILM_HOME = join(root, 'studio-home');+ try {+ const listed = skillsCommand('openfilm', { cwd: film });+ assert.ok(listed.lines.some((l) => /brand\s+this project/.test(l)));+ assert.ok(listed.lines.some((l) => l.includes('This film\'s brand')));+ /* outside a project: none of this film's, only what comes with OpenFilm */+ const outside = skillsCommand('openfilm', { cwd: root }).lines;+ assert.match(outside[0], /^Skills\. /);+ assert.ok(!outside.some((l) => /this project/.test(l)) && outside.some((l) => /replicate\s+official/.test(l)));++ const printed = await skillCommand(['brand'], 'openfilm', { cwd: film });+ assert.ok(printed.ok);+ assert.match(printed.lines[0], /^<skill name="brand"/);+ const missing = await skillCommand(['nope'], 'openfilm', { cwd: film });+ assert.deepEqual([missing.ok, missing.usage], [false, true]);++ /* an address: fetched (here, made) into a folder of the one it is given */+ const fetched = await skillCommand(['add', 'https://github.com/someone/skills/tree/main/lyric-pv'], 'openfilm', {+ cwd: film,+ fetch: async (_url, into) => skill(join(into, 'lyric-pv'), 'lyric-pv', 'Lyric videos', 'x', { 'scripts/make.py': '' }),+ });+ assert.ok(fetched.ok, fetched.lines.join('\n'));+ assert.match(fetched.lines.join('\n'), /Added lyric-pv: Lyric videos[\s\S]*scripts\/make\.py[\s\S]*only skills you trust/);+ assert.ok(readFileSync(join(home, 'skills', 'lyric-pv', 'SKILL.md'), 'utf8').includes('Lyric videos'));+ assert.deepEqual(listSkills({ mine: join(home, 'skills'), official: join(root, 'none') }).map((s) => s.name), ['lyric-pv'], 'nothing left from the fetch');+ } finally {+ if (before === undefined) delete process.env.OPENFILM_SKILLS; else process.env.OPENFILM_SKILLS = before;+ if (beforeHome === undefined) delete process.env.OPENFILM_HOME; else process.env.OPENFILM_HOME = beforeHome;+ }+});++test('a skill as people see it: its openfilm.json title and summary by language; none, or not one, read as nothing', () => {+ const root = mkdtempSync(join(tmpdir(), 'of-shown-'));+ const dir = skill(join(root, 'replicate'), 'replicate', 'For the agent.');+ writeFileSync(join(dir, 'openfilm.json'), JSON.stringify({ title: { en: 'Replicate a video', 'zh-CN': '复刻视频', bad: 1, 'not a lang': 'x' }, summary: 'One line.' }));+ assert.deepEqual(readSkill(dir, 'official').shown, { title: { en: 'Replicate a video', 'zh-CN': '复刻视频' }, summary: { en: 'One line.' } });+ writeFileSync(join(dir, 'openfilm.json'), '{ not json');+ assert.equal(readSkill(dir, 'official').shown, undefined);+ assert.equal(readSkill(skill(join(root, 'plain'), 'plain', 'x'), 'mine').shown, undefined);+});++test("a skill's openfilm.json: its version, kind, order, mark and media; anything wrong left out; else the front matter's version", () => {+ const root = mkdtempSync(join(tmpdir(), 'of-skill-look-'));+ const a = skill(join(root, 'a'), 'a', 'Does a.', 'How.', {+ 'openfilm.json': JSON.stringify({ version: '0.2.0', kind: 'style', order: 3, icon: 'film', cover: 'cover.jpg', preview: 'none.mp4' }),+ 'cover.jpg': 'jpeg',+ });+ assert.deepEqual((({ version, kind, order, icon, cover, preview }) => ({ version, kind, order, icon, cover, preview }))(readSkill(a, 'official')),+ { version: '0.2.0', kind: 'style', order: 3, icon: 'film', cover: 'cover.jpg', preview: undefined });+ const b = skill(join(root, 'b'), 'b', 'Does b.', 'How.', { 'openfilm.json': JSON.stringify({ version: 'latest', kind: 'other', order: 'first', icon: 'Big Icon', cover: '../x.jpg' }) });+ const read = readSkill(b, 'mine');+ for (const key of ['version', 'kind', 'order', 'icon', 'cover']) assert.equal(read?.[key], undefined, key);+ mkdirSync(join(root, 'c'));+ writeFileSync(join(root, 'c', 'SKILL.md'), '---\nname: c\ndescription: Does c.\nversion: 1.4\n---\nHow.\n');+ assert.equal(readSkill(join(root, 'c'), 'mine')?.version, '1.4');+});++test('where the person\'s skills came from: a folder, or the address commitSkills was given; forgotten when removed', async () => {+ const root = mkdtempSync(join(tmpdir(), 'of-skill-origin-'));+ const mine = join(root, 'mine');+ const src = skill(join(root, 'src', 'cards'), 'cards', 'Makes cards.');+ await addSkills(src, { mine });+ assert.deepEqual((({ from, address }) => ({ from, address }))(skillOrigins(mine).cards), { from: 'folder', address: src });+ const fetched = skill(join(root, 'net', 'lyrics'), 'lyrics', 'Makes lyric videos.');+ const { staging } = await previewSkills('https://github.com/someone/lyrics', { mine, fetch: async (_url, into) => { const to = join(into, 'lyrics'); cpSync(fetched, to, { recursive: true }); return to; } });+ await commitSkills(staging, { mine });+ assert.deepEqual((({ from, address }) => ({ from, address }))(skillOrigins(mine).lyrics), { from: 'link', address: 'https://github.com/someone/lyrics' });+ await removeSkill('cards', { mine });+ assert.equal(skillOrigins(mine).cards, undefined);+ assert.ok(skillOrigins(mine).lyrics);+});diff --git a/packages/openfilm/src/timeline.mjs b/packages/openfilm/src/timeline.mjsindex 1fc5598..3470802 100644--- a/packages/openfilm/src/timeline.mjs+++ b/packages/openfilm/src/timeline.mjs@@ -108,7 +108,8 @@ function dress(c, row) {wear(c, row.style ?? '');if (c.kind === 'page' && !c.el.style.border) c.el.style.border = '0';c.el.style.zIndex = String(doc.tracks.length - c.ti); // track 0 on top- c.el.style.visibility = c.shown ? 'visible' : 'hidden';+ /* a page coming on shows once it is drawn (see draw) */+ c.el.style.visibility = c.shown && !c.coming ? 'visible' : 'hidden';place(c, row.box);}@@ -601,6 +602,9 @@ const loading = (async () => {`ready`: until it does, that is not an error nobody handled */loading.catch(() => {});+/** the latest frame drawn for a person watching: an earlier one that finishes after it does not change what shows */+let watched = 0;+/*** Draw the film at t. `live`: a person is watching (an editor, or the film opened as a page), so videos play by* themselves while frames come in order, and a scrub's frame does not wait for its video to be on screen; otherwise@@ -617,51 +621,69 @@ async function draw(t, live) {lastLive = live ? { t, at: now } : { t: -Infinity, at: 0 };clearTimeout(settleNear);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 && !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';- if (on) fadeAt(c, t);- if (!on) {- if (c.kind !== 'video') return;- if (playing && c.awake && c.at > t && c.at - t < CUE_AHEAD) getReady(c, c.at - t);- else { if (!c.el.paused) c.el.pause(); c.lastWant = c.cued = undefined; }- return;- }- if (c.kind === 'still') return;- if (c.kind === 'video') {- const want = sourceAt(c.span, t - c.at, c.row);- if (playing) { if (c.held) step(c, want); else roll(c, want); return; }- c.held = false;- if (live) { await glance(c, want); return; }- if (!c.el.paused) c.el.pause();- c.lastWant = want;- await loaded(c);- /* a video coming on: shown before it is sought. A frame made current in the moment it turns visible is said to- be presented, yet the picture keeps the frame it had for a second or so (Chromium, its frames sent apart from- the page's): the same t drew two pictures */- if (appears) await frames(2);- 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;+ /* watched, a page coming on shows once its frame is drawn, and the pictures going off stay until then: shown first,+ it showed what it held before (its own first state, or the frame it drew the last time it was on) for as long as+ its frame took, a flash at the cut. An exact frame is taken when all of it is drawn, so it shows each at once. */+ const turn = live ? ++watched : 0;+ const coming = [], going = [];+ try {+ await Promise.all(clips.map((c) => drawClip(c, t, live, playing, turn, coming, going)));+ } finally {+ for (const c of coming) if (c.coming === turn) c.coming = 0;+ if (live && turn === watched) {+ for (const c of going) if (!c.shown) c.el.style.visibility = 'hidden';+ for (const c of coming) if (c.shown) c.el.style.visibility = 'visible';}- 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 */- try { await c.child.frame(local); }- catch (e) { throw new Error(`clip "${c.id}" (${c.src}) at its ${Number(local.toFixed(3))}s: ${e?.message ?? e}`); }- c.win.filmHost?.settle?.(local);- if (!live) await mediaShown(c.win.document);- c.drawn = true;- override(c, c.preview ?? c.overrides);- }));+ }+}++/** One clip's part of a frame (see draw): a page coming on while watched is put in `coming`, a picture going off in `going`. */+async function drawClip(c, t, live, playing, turn, coming, going) {+ if (c.kind === 'sound') return;+ const on = !c.hidden && !c.missing && t >= c.at && t < c.end;+ c.shown = on;+ const appears = on && c.el.style.visibility !== 'visible';+ if (live && appears && c.kind === 'page') { c.coming = turn; coming.push(c); }+ else if (live && !on && c.el.style.visibility === 'visible') going.push(c);+ else c.el.style.visibility = on ? 'visible' : 'hidden';+ if (on) fadeAt(c, t);+ if (!on) {+ if (c.kind !== 'video') return;+ if (playing && c.awake && c.at > t && c.at - t < CUE_AHEAD) getReady(c, c.at - t);+ else { if (!c.el.paused) c.el.pause(); c.lastWant = c.cued = undefined; }+ return;+ }+ if (c.kind === 'still') return;+ if (c.kind === 'video') {+ const want = sourceAt(c.span, t - c.at, c.row);+ if (playing) { if (c.held) step(c, want); else roll(c, want); return; }+ c.held = false;+ if (live) { await glance(c, want); return; }+ if (!c.el.paused) c.el.pause();+ c.lastWant = want;+ await loaded(c);+ /* a video coming on: shown before it is sought. A frame made current in the moment it turns visible is said to+ be presented, yet the picture keeps the frame it had for a second or so (Chromium, its frames sent apart from+ the page's): the same t drew two pictures */+ if (appears) await frames(2);+ 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 */+ try { await c.child.frame(local); }+ catch (e) { throw new Error(`clip "${c.id}" (${c.src}) at its ${Number(local.toFixed(3))}s: ${e?.message ?? e}`); }+ c.win.filmHost?.settle?.(local);+ if (!live) await mediaShown(c.win.document);+ c.drawn = true;+ override(c, c.preview ?? c.overrides);}window.film = {diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjsindex 848accc..c718b3c 100644--- a/packages/openfilm/src/timeline.test.mjs+++ b/packages/openfilm/src/timeline.test.mjs@@ -760,3 +760,36 @@ test('a clip\'s look changed (an inspector\'s value, an edit) keeps its fade onawait s.close();}});++test('watched, a page coming on shows once its frame is drawn, the picture going off staying until then; a later frame keeps what it shows', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-cut-'));+ writeFileSync(join(dir, 'a.html'), page('a', 1));+ /* a page whose frame takes a while, and that looks unlike its frame before it is drawn */+ writeFileSync(join(dir, 'b.html'), `<!doctype html><body style="margin:0;background:#f00"><script>window.seen=[];+window.film={duration:1,width:320,height:180,async frame(t){const look=()=>[frameElement.style.visibility,parent.document.getElementById('a').style.visibility];+window.seen.push(look());await new Promise((r)=>setTimeout(r,150));window.seen.push(look());document.body.style.background='#0f0'}}</script></body>`);+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [+ { src: 'a.html', id: 'a' }, { src: 'b.html', id: 'b', at: 1 },+ ] }] }));+ const s = await open(dir);+ const shown = () => s.film.page.evaluate(() => ['a', 'b'].map((id) => document.getElementById(id).style.visibility));+ try {+ await s.film.page.evaluate(() => window.__filmEditor.watch(0.5));+ await s.film.page.evaluate(() => window.__filmEditor.watch(1.25));+ const seen = await s.film.page.evaluate(() => document.getElementById('b').contentWindow.seen);+ assert.deepEqual(seen, [['hidden', 'visible'], ['hidden', 'visible']], 'while its frame was drawn, it was out of sight and the one before on screen');+ assert.deepEqual(await shown(), ['hidden', 'visible'], 'drawn: it shows, the one before has gone');+ /* back before the cut: the earlier frame, still drawing, does not put its picture back over the later one */+ await s.film.page.evaluate(() => window.__filmEditor.watch(0.5));+ const order = await s.film.page.evaluate(async () => {+ const slow = window.__filmEditor.watch(1.5);+ await new Promise((r) => setTimeout(r, 30));+ await window.__filmEditor.watch(0.75);+ await slow;+ return ['a', 'b'].map((id) => document.getElementById(id).style.visibility);+ });+ assert.deepEqual(order, ['visible', 'hidden']);+ } finally {+ await s.close();+ }+});diff --git a/packages/openfilm/studio/client.mjs b/packages/openfilm/studio/client.mjsindex 3c03ef0..babeb98 100644--- a/packages/openfilm/studio/client.mjs+++ b/packages/openfilm/studio/client.mjs@@ -5,7 +5,7 @@* project.*/import { createHash } from 'node:crypto';-import { spawn } from 'node:child_process';+import { spawn, spawnSync } from 'node:child_process';import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs';import { request } from 'node:http';import { dirname, join, resolve } from 'node:path';@@ -14,8 +14,10 @@ import { studioHome, studioKey } from './server/projects.mjs';const MAIN = fileURLToPath(new URL('./server/main.mjs', import.meta.url));const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;+/** A source checkout (Studio's editor source is here): git pull updates it, not npm. */+export const FROM_SOURCE = existsSync(new URL('./ui/src', import.meta.url));-/** @typedef {{ pid?: number, supervisor?: number, origin: string, filmOrigin: string, key: string, version?: string }} Running */+/** @typedef {{ pid?: number, supervisor?: number, origin: string, filmOrigin: string, key: string, version?: string, app?: boolean }} Running *//** What a Studio says about itself, or null when nothing (or something else) answers at `origin`. */async function health(/** @type {string} */ origin, ms = 1500) {@@ -36,14 +38,14 @@ async function running() {try { run = JSON.parse(readFileSync(join(studioHome(), 'run.json'), 'utf8')); } catch { /* none advertised */ }if (run) {const said = await health(run.origin);- if (said) return { ...run, version: said.version };+ if (said) return { ...run, version: said.version, ...(said.app ? { app: true } : {}) };}const given = Number(process.env.OPENFILM_STUDIO_PORT);const origin = `http://127.0.0.1:${Number.isInteger(given) && given > 0 ? given : 4747}`;const said = await health(origin);/* it says which home it serves as a hash of the path (the path itself is not told to anyone who asks) */if (said?.home !== createHash('sha256').update(studioHome()).digest('hex') || !said.filmOrigin) return null;- return { origin, filmOrigin: said.filmOrigin, key: studioKey(), version: said.version };+ return { origin, filmOrigin: said.filmOrigin, key: studioKey(), version: said.version, ...(said.app ? { app: true } : {}) };}/**@@ -184,6 +186,40 @@ export async function ensureStudio(say = () => {}, { fresh = false } = {}) {throw new Error(`Studio did not start; see ${join(logs, 'studio.log')}`);}+/**+ * `openfilm update`: the newest openfilm, and Studio on it. This one is the newest, or the newest is run to do it+ * (`npx -y openfilm@<latest> update` fetches it); then a Studio on an older one is started again on it once it is+ * idle, and the pages open on it come back on the new version. The desktop app's Studio updates with the app, and a+ * source checkout with git pull: each is said instead. `ok` false when it could not be done (offline, Studio busy).+ * @param {(line: string) => void} [say] @returns {Promise<{ ok: boolean, lines: string[] }>}+ */+export async function updateOpenfilm(say = () => {}) {+ if (FROM_SOURCE) return { ok: true, lines: [`openfilm ${VERSION} runs from a source checkout: git pull updates it.`] };+ const found = (await running()) ?? (await restarting());+ if (found?.app) return { ok: true, lines: ['Studio is the OpenFilm app\'s: it updates with the app (OpenFilm → Check for Updates…).'] };+ const { latest } = await npmOpenfilm({ force: true, waitMs: 8000 });+ if (!latest) return { ok: false, lines: ['Could not reach npm to learn the newest openfilm: try again when online.'] };+ if (olderThanThis(VERSION, latest)) {+ /* the newest does it, fetched by npx; it ran already and is still not the newest: npx gave another */+ if (process.env.OPENFILM_UPDATING) return { ok: false, lines: [`npx ran openfilm ${VERSION}, not ${latest}.`] };+ say(`Getting openfilm ${latest}…`);+ const r = spawnSync('npx', ['-y', `openfilm@${latest}`, 'update'], {+ stdio: 'inherit', env: { ...process.env, OPENFILM_UPDATING: '1' }, shell: process.platform === 'win32', windowsHide: true,+ });+ if (r.error) return { ok: false, lines: [`Could not run npx (it comes with Node.js): ${r.error.message}`] };+ /* an `openfilm` installed with npm -g is not npx's: it stays as it is until npm updates it */+ const installed = process.env.npm_command !== 'exec' && !process.env.OPENFILM_RUN;+ return { ok: r.status === 0, lines: installed && r.status === 0 ? [`The \`openfilm\` command installed here is still ${VERSION}: \`npm install -g openfilm@latest\` updates it.`] : [] };+ }+ if (!found) return { ok: true, lines: [`openfilm ${VERSION} is the newest. Studio starts on it the next time it opens.`] };+ if (!olderThanThis(found.version)) return { ok: true, lines: [`openfilm ${VERSION} is the newest, and Studio runs it.`] };+ say(`Updating OpenFilm Studio from ${found.version} to ${VERSION}…`);+ const replaced = await replace(found);+ if ('stays' in replaced) return { ok: false, lines: [`Studio keeps running ${found.version} for now: ${replaced.stays}. Update again once that is done.`] };+ await ensureStudio(say);+ return { ok: true, lines: [`Studio runs openfilm ${VERSION} now${replaced.pages ? `: the ${replaced.pages === 1 ? 'page' : `${replaced.pages} pages`} open on it come back on it` : ''}.`] };+}+/*** Open `folder` in Studio (none: the project opened last, else the Projects window) and show it in a browser: the* person's opens it `fallback` seconds on unless a page opened the address first (an agent's own browser), or at oncediff --git a/packages/openfilm/studio/client.test.mjs b/packages/openfilm/studio/client.test.mjsindex dd20939..8e1a04b 100644--- a/packages/openfilm/studio/client.test.mjs+++ b/packages/openfilm/studio/client.test.mjs@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';import { createServer } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { ensureStudio, olderThanThis, openInStudio } from './client.mjs';+import { ensureStudio, olderThanThis, openInStudio, updateOpenfilm } from './client.mjs';const freePort = () => new Promise((resolve) => {const probe = createServer().listen(0, '127.0.0.1', () => { const { port } = probe.address(); probe.close(() => resolve(port)); });@@ -129,3 +129,9 @@ test('a newer openfilm on npm is told from what was learnt (no network when notif (wasOff !== undefined) process.env.OPENFILM_NO_UPDATE_CHECK = wasOff;}});++test('`openfilm update` in a source checkout says git pull updates it, and touches nothing', async () => {+ const said = await updateOpenfilm();+ assert.equal(said.ok, true);+ assert.match(said.lines[0], /source checkout: git pull updates it/);+});diff --git a/packages/openfilm/studio/server/closure.mjs b/packages/openfilm/studio/server/closure.mjsindex 602caf3..912913d 100644--- a/packages/openfilm/studio/server/closure.mjs+++ b/packages/openfilm/studio/server/closure.mjs@@ -4,7 +4,7 @@* follows the film and nothing else:** film.html and what its own head loads (styles, fonts, scripts)- * every clip's file video, sound, picture or page+ * every clip's file video, sound, picture or page, and a picture an override draws in a page (`url()`)* what a page loads relative `src` / `href` / `srcset` and the like in its HTML, `url()` and `@import` in* its CSS, imports in its scripts (an import map is followed), and any string in its* scripts and JSON that names a file of the project (`fetch('lib/plan.json')`); a@@ -291,8 +291,14 @@ export async function filmClosure(view) {let value = null;try { value = readFilmFile(filmText).value; } catch { /* read as HTML below */ }for (const track of value?.tracks ?? []) {- for (const clip of /** @type {{ src?: unknown }[]} */ (track.clips ?? [])) {- if (typeof clip?.src === 'string') await ref(clip.src, [''], FILM_FILE);+ for (const clip of /** @type {{ src?: unknown, overrides?: unknown }[]} */ (track.clips ?? [])) {+ if (typeof clip?.src !== 'string') continue;+ await ref(clip.src, [''], FILM_FILE);+ /* a picture the person put in a page's place (an override's `url()`), named from the page's folder */+ const dir = posix.dirname(clip.src) === '.' ? '' : posix.dirname(clip.src);+ for (const o of Array.isArray(clip.overrides) ? clip.overrides : []) {+ for (const v of Object.values(o?.style ?? {})) if (typeof v === 'string') for (const r of cssRefs(v)) await ref(r, [dir], clip.src);+ }}}/* and the film read as the page it is: its head, and any clip the reading above did not take */diff --git a/packages/openfilm/studio/server/closure.test.mjs b/packages/openfilm/studio/server/closure.test.mjsindex edb54c8..7760985 100644--- a/packages/openfilm/studio/server/closure.test.mjs+++ b/packages/openfilm/studio/server/closure.test.mjs@@ -129,3 +129,21 @@ test('a reference made a project path, or nothing', () => {assert.equal(projectPath('../../out.png', 'scenes'), null, 'outside the folder');for (const ref of ['https://x.test/a.png', '//x.test/a.png', 'data:image/png;base64,AA', '#id', '', 'mailto:a@b']) assert.equal(projectPath(ref, ''), null, ref);});++test('a picture an override draws in a page is the film\'s, named from the page\'s folder', async () => {+ const root = folder({+ 'film.html': `<meta name="viewport" content="width=1920, height=1080">+<section>+ <iframe src="pages/lower.html" overrides='[{"at":"img.logo","style":{"content":"url(\\"../assets/new-logo.png\\")"}},{"at":".card","style":{"backgroundImage":"url(bg.jpg)"}}]'></iframe>+</section>+`,+ 'pages/lower.html': '<img class="logo" src="logo.png"><div class="card"></div>',+ 'pages/logo.png': 'old',+ 'pages/bg.jpg': 'bg',+ 'assets/new-logo.png': 'new',+ 'assets/unused.png': 'unused',+ });+ const held = await filmClosure(folderView(root));+ for (const path of ['pages/lower.html', 'pages/logo.png', 'assets/new-logo.png', 'pages/bg.jpg']) assert.ok(held.has(path), path);+ assert.ok(!held.has('assets/unused.png'));+});diff --git a/packages/openfilm/studio/server/custom-services.mjs b/packages/openfilm/studio/server/custom-services.mjsindex d74e6de..78899c1 100644--- a/packages/openfilm/studio/server/custom-services.mjs+++ b/packages/openfilm/studio/server/custom-services.mjs@@ -6,7 +6,9 @@** `openfilm get call` sends a request to one through Studio, which adds the key (the agent never sees it) and lands* what comes back: a file under assets/<service>/, or text and JSON as they are, for the agent to read. OpenFilm knows- * nothing about what a service answers; the agent does, from the person's words and the service's own docs.+ * nothing about what a service answers; the agent does, from the person's words and the service's own docs. The key+ * goes where the agent writes {key} (a header, the path's query), as the docs say; else as `Authorization: Bearer`+ * (or where the person once said, `auth`).** A request goes only to the address the person gave (a path under it, never another host), and carries only the* project's own files.@@ -30,6 +32,8 @@ export const DEFAULT_AUTH = 'Authorization: Bearer {key}';const MAX_SEND_BYTES = 200 << 20;/** Text longer than this is saved as a file, its start shown. */const MAX_SHOWN_CHARS = 20_000;+/** The most the person's words about a service may be: what it does, how it is called, or its docs. */+const MAX_NOTE_CHARS = 2000;/** How long a service has to answer. */export const CALL_TIMEOUT_SEC = 600;@@ -99,10 +103,12 @@ export function withService(services, id, input) {let newId = was?.id ?? idOf(name);for (let n = 2; others.some((s) => s.id === newId); n++) newId = `${idOf(name)}-${n}`;const note = plainText(input.note);- if (note.length > 600) throw bad('Say what it does in a few lines (600 characters at most)');+ if (note.length > MAX_NOTE_CHARS) throw bad(`Say what it does and how it is called, or where its docs are (${MAX_NOTE_CHARS} characters at most)`);const key = input.key === undefined ? was?.key : plainText(input.key) ? cleanServiceKey(plainText(input.key)) : undefined;+ /* where the key goes, when Settings says (it no longer asks: the agent writes {key} where the docs want it) */+ const auth = input.auth === undefined ? (was?.auth ?? DEFAULT_AUTH) : cleanAuth(input.auth);/** @type {CustomService} */- const service = { ...(was ? unknownOf(was) : {}), id: newId, name, url: cleanAddress(input.url), ...(key ? { key } : {}), auth: cleanAuth(input.auth), note };+ const service = { ...(was ? unknownOf(was) : {}), id: newId, name, url: cleanAddress(input.url), ...(key ? { key } : {}), auth, note };return was ? services.map((s) => (s === was ? service : s)) : [...services, service];}@@ -166,7 +172,11 @@ const isText = (/** @type {string} */ type) => /^text\/|[/+]json$|\/xml$|[/+]xml* @param {AbortSignal} signal*/export async function callService(root, service, args, signal) {- const url = targetOf(service.url, args.path ?? '/');+ /* {key}: where the agent wants the key, filled in here (it never has it); with none, the usual header */+ const placed = [args.path ?? '', ...(args.header ?? [])].some((v) => v.includes('{key}'));+ if (placed && !service.key) throw bad(`${service.name} has no key in Settings, so {key} has nothing to stand for`);+ const fill = (/** @type {string} */ v, encode = false) => (service.key ? v.replaceAll('{key}', encode ? encodeURIComponent(service.key) : service.key) : v);+ const url = targetOf(service.url, fill(args.path ?? '/', true));const forms = args.form ?? [], files = args.file ?? [];const kinds = [args.json !== undefined, forms.length + files.length > 0, args.body !== undefined].filter(Boolean).length;if (kinds > 1) throw bad('Send one kind of body: --json, or --form and --file, or --body');@@ -197,9 +207,9 @@ export async function callService(root, service, args, signal) {const name = at > 0 ? line.slice(0, at).trim() : '';if (!/^[A-Za-z0-9-]+$/.test(name) || /[\r\n]/.test(line)) throw bad('--header is written "Name: value"');if (/^(host|content-length|connection|transfer-encoding)$/i.test(name)) throw bad(`--header ${name} is set by Studio`);- headers[name.toLowerCase()] = line.slice(at + 1).trim();+ headers[name.toLowerCase()] = fill(line.slice(at + 1).trim());}- if (service.key) {+ if (service.key && !placed) {const at = service.auth.indexOf(':');headers[service.auth.slice(0, at).trim().toLowerCase()] = service.auth.slice(at + 1).trim().replaceAll('{key}', service.key);}diff --git a/packages/openfilm/studio/server/custom-services.test.mjs b/packages/openfilm/studio/server/custom-services.test.mjsindex 3249a70..436f5d1 100644--- a/packages/openfilm/studio/server/custom-services.test.mjs+++ b/packages/openfilm/studio/server/custom-services.test.mjs@@ -110,3 +110,26 @@ test('a service that is not running says so', async () => {const [s] = withService([], null, { name: 'Off', url: `http://127.0.0.1:${port}` });await assert.rejects(callService(project(), s, { path: '/' }, signal), new RegExp(`not answering at http://127\\.0\\.0\\.1:${port}: is it running\\?`));});++test('the key goes where the agent writes {key}, as the service\'s docs say; with none, as the usual header', async () => {+ const root = project();+ const [s] = withService([], null, { name: 'Odd', url: `${base}/v1`, key: 'odd+key&1' });+ await callService(root, s, { path: '/words?token={key}' }, signal);+ assert.equal(seen.at(-1).url, '/v1/words?token=odd%2Bkey%261', 'in the query, encoded');+ assert.equal(seen.at(-1).headers.authorization, undefined, 'and nowhere else');+ await callService(root, s, { path: '/words', header: ['X-Auth-Token: Token {key}'] }, signal);+ assert.equal(seen.at(-1).headers['x-auth-token'], 'Token odd+key&1');+ assert.equal(seen.at(-1).headers.authorization, undefined);+ await callService(root, s, { path: '/words' }, signal);+ assert.equal(seen.at(-1).headers.authorization, 'Bearer odd+key&1');+ const [none] = withService([], null, { name: 'Open', url: base });+ await assert.rejects(callService(root, none, { path: '/words?token={key}' }, signal), (e) => e.status === 400 && /no key/.test(e.message));+});++test('a service changed without saying where its key goes keeps where it went', () => {+ const [s] = withService([], null, { name: 'Della', url: base, auth: 'x-api-key: {key}', key: 'della-key' });+ const [changed] = withService([s], s.id, { name: 'Della', url: base, note: 'Speaks in my voice' });+ assert.equal(changed.auth, 'x-api-key: {key}');+ assert.equal(changed.note, 'Speaks in my voice');+ assert.equal(withService([], null, { name: 'New', url: base })[0].auth, 'Authorization: Bearer {key}');+});diff --git a/packages/openfilm/studio/server/examples.mjs b/packages/openfilm/studio/server/examples.mjsindex 3cadbc2..e5cefe9 100644--- a/packages/openfilm/studio/server/examples.mjs+++ b/packages/openfilm/studio/server/examples.mjs@@ -8,10 +8,23 @@* { "repo": "https://github.com/openfilm/examples", "branch": "main",* "examples": [{ "folder": "one-prompt", "title": "…", "description": "…", "poster": "one-prompt/look.png", "duration": "1:29" }] }*- * `repo` and `branch` default to the repository the index is read from; `poster` is an address, or a path in the- * repository; `duration` is seconds or "m:ss".+ * An index read from a file on this computer (trying a new one) has its posters and previews served by Studio from+ * the folder it is in (`/api/examples/file/<path>`), so they show before the repository has them.+ *+ * GitHub's index shows at once: OpenFilm comes with a copy of it and its posters (examples-index, `pnpm examples:sync`),+ * and the last one read is kept in Studio's home. Those are shown while GitHub is asked in the background (Studio asks+ * as it starts), and a poster the copy has is served from it, so a slow or blocked GitHub costs no wait.+ *+ * `repo` and `branch` default to the repository the index is read from; `poster` (and `video`, a short preview played+ * under the pointer) is an address, or a path in the repository; `duration` is seconds or "m:ss". Optional:+ * `category` (what kind of film it is, as the examples window groups them: a short word such as "launch" or+ * "explainer"), `segments` (its parts, so one can be pointed at: `[{ "title": "S2-Hook", "from": 12, "to": 30 }]`).*/-import { readFile } from 'node:fs/promises';+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { mkdir, mkdtemp, readFile, rename, rm } from 'node:fs/promises';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { studioHomeDir } from '../../src/locations.mjs';export const EXAMPLES_INDEX = 'https://raw.githubusercontent.com/openfilm/examples/main/examples.json';const DEFAULT_REPO = { owner: 'openfilm', repo: 'examples', branch: 'main' };@@ -19,8 +32,16 @@ const DEFAULT_REPO = { owner: 'openfilm', repo: 'examples', branch: 'main' };const KEEP_MS = 10 * 60 * 1000;const RETRY_MS = 60 * 1000;const NAME = /^[\w.-]+$/;+/** The copy of GitHub's index and its posters that comes with OpenFilm (`pnpm examples:sync`). */+export const BUNDLED_INDEX = fileURLToPath(new URL('../../examples-index/', import.meta.url));+/** Where the last index read from GitHub is kept, for the next start. */+const savedIndex = (/** @type {string} */ home) => join(home, 'cache', 'examples-index.json');-/** @typedef {{ id: string, title: string, description: string, poster: string | null, duration: number | null, url: string }} Example */+/**+ * @typedef {{ title: string, from: number, to: number }} ExampleSegment+ * @typedef {{ id: string, title: string, description: string, poster: string | null, video: string | null,+ * duration: number | null, url: string, category: string | null, segments: ExampleSegment[] }} Example+ *//** "1:29" or 89 → 89; anything else → null. @param {unknown} value */export function exampleSeconds(value) {@@ -51,30 +72,82 @@ export function readExamples(raw, source = EXAMPLES_INDEX) {const out = [];for (const entry of index.examples.slice(0, 50)) {if (!entry || typeof entry !== 'object' || !repoPath(entry.folder) || typeof entry.title !== 'string' || !entry.title.trim()) continue;- const poster = typeof entry.poster === 'string' && /^https:\/\//.test(entry.poster) ? entry.poster- : repoPath(entry.poster) ? `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${entry.poster}` : null;+ const local = !/^https?:\/\//.test(source);+ /* GitHub's index: a poster the copy that came with OpenFilm has is served from it */+ const bundled = source === EXAMPLES_INDEX ? (/** @type {string} */ v) => existsSync(join(BUNDLED_INDEX, ...v.split('/'))) : () => false;+ const media = (/** @type {unknown} */ v) => (typeof v === 'string' && /^https:\/\//.test(v) ? v+ : !repoPath(v) ? null+ : local || bundled(String(v)) ? `/api/examples/file/${String(v).split('/').map(encodeURIComponent).join('/')}`+ : `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${v}`);+ const segments = Array.isArray(entry.segments) ? entry.segments.slice(0, 40).flatMap((/** @type {any} */ g) => {+ const [from, to] = [exampleSeconds(g?.from) ?? (g?.from === 0 ? 0 : null), exampleSeconds(g?.to)];+ return typeof g?.title === 'string' && g.title.trim() && from != null && to != null && to > from ? [{ title: g.title.trim().slice(0, 60), from, to }] : [];+ }) : [];out.push({id: entry.folder,title: entry.title.trim().slice(0, 80),description: typeof entry.description === 'string' ? entry.description.trim().slice(0, 300) : '',- poster,+ poster: media(entry.poster),+ video: media(entry.video),duration: exampleSeconds(entry.duration),url: `https://github.com/${owner}/${repo}/tree/${branch}/${entry.folder}`,+ category: typeof entry.category === 'string' && /^[\w-]{1,30}$/.test(entry.category) ? entry.category : null,+ segments,});}return out;}+/**+ * A file beside an index read from this computer (its posters and previews), or null: a path inside its folder only.+ * @param {string} path @param {{ source?: string }} [options]+ */+export function exampleFile(path, { source = process.env.OPENFILM_EXAMPLES_INDEX || EXAMPLES_INDEX } = {}) {+ if (!repoPath(path)) return null;+ /* GitHub's index: the posters of the copy that came with OpenFilm */+ if (source === EXAMPLES_INDEX) return existsSync(join(BUNDLED_INDEX, ...path.split('/'))) ? join(BUNDLED_INDEX, ...path.split('/')) : null;+ if (/^https?:\/\//.test(source)) return null;+ return join(dirname(source), ...path.split('/'));+}+/** @type {Map<string, { at: number, ok: boolean, examples: Example[] }>} */const cache = new Map();+/** @type {Map<string, Promise<Example[]>>} */+const reading = new Map();++/** An index kept on disk (the last read, or the copy that came with OpenFilm), as examples; null when there is none. @param {string} file */+function indexAt(file) {+ try { return readExamples(JSON.parse(readFileSync(file, 'utf8')), EXAMPLES_INDEX); } catch { return null; }+}+/*** The examples, read from the index (cached a while). Never fails: an index that cannot be read is no examples.- * @param {{ source?: string, fetchImpl?: typeof fetch }} [options]+ * GitHub's index never waits on GitHub when there is one to show: the last read (here, then in Studio's home), else+ * the copy that came with OpenFilm, while GitHub is asked in the background.+ * @param {{ source?: string, fetchImpl?: typeof fetch, home?: string }} [options]*/-export async function listExamples({ source = process.env.OPENFILM_EXAMPLES_INDEX || EXAMPLES_INDEX, fetchImpl = fetch } = {}) {+export async function listExamples({ source = process.env.OPENFILM_EXAMPLES_INDEX || EXAMPLES_INDEX, fetchImpl = fetch, home = studioHomeDir() } = {}) {const kept = cache.get(source);if (kept && Date.now() - kept.at < (kept.ok ? KEEP_MS : RETRY_MS)) return kept.examples;+ if (source === EXAMPLES_INDEX) {+ const now = kept?.ok ? kept.examples : indexAt(savedIndex(home)) ?? indexAt(join(BUNDLED_INDEX, 'examples.json'));+ const asked = readIndex(source, fetchImpl, home);+ if (now?.length) { asked.catch(() => {}); return now; }+ return asked;+ }+ return readIndex(source, fetchImpl, home);+}++/** The index read now (one read at a time), kept here and, read from GitHub, in Studio's home. */+function readIndex(/** @type {string} */ source, /** @type {typeof fetch} */ fetchImpl, /** @type {string} */ home) {+ if (!reading.has(source)) {+ reading.set(source, fetchIndex(source, fetchImpl, home).finally(() => reading.delete(source)));+ }+ return /** @type {Promise<Example[]>} */ (reading.get(source));+}++async function fetchIndex(/** @type {string} */ source, /** @type {typeof fetch} */ fetchImpl, /** @type {string} */ home) {let examples = /** @type {Example[]} */ ([]);let ok = false;try {@@ -83,7 +156,47 @@ export async function listExamples({ source = process.env.OPENFILM_EXAMPLES_INDE: JSON.parse(await readFile(source, 'utf8'));examples = readExamples(raw, source);ok = raw != null;+ if (ok && source === EXAMPLES_INDEX && examples.length) {+ try { mkdirSync(dirname(savedIndex(home)), { recursive: true }); writeFileSync(savedIndex(home), JSON.stringify(raw)); } catch { /* kept here only */ }+ }} catch { /* offline, private, or not an index: none */ }+ /* a failed read keeps the last good one */+ const kept = cache.get(source);+ if (!ok && kept?.ok) { kept.at = Date.now() - KEEP_MS + RETRY_MS; return kept.examples; }cache.set(source, { at: Date.now(), ok, examples });return examples;}++const DAY = 24 * 60 * 60 * 1000;++/**+ * An example's folder on this computer, for an agent to read how it is made (a part of it pointed at from the chat):+ * fetched from its repository into Studio's cache (`<home>/cache/examples/<id>`, fetched again after a day), or, for an+ * index read from a file, its folder beside the index. Throws when there is no such example or it cannot be fetched.+ * @param {string} id+ * @param {{ home: string, source?: string, fetchFolder: (url: string, into: string) => Promise<string>, now?: () => number }} options+ * `fetchFolder`: a repository folder's address fetched into a folder (fetch-repo.mjs), → where it landed+ */+export async function exampleFolder(id, { home, source = process.env.OPENFILM_EXAMPLES_INDEX || EXAMPLES_INDEX, fetchFolder, now = Date.now }) {+ if (!repoPath(id) || id.includes('/')) throw new Error('There is no such example.');+ if (!/^https?:\/\//.test(source)) {+ const dir = join(dirname(source), id);+ if (existsSync(join(dir, 'film.html'))) return dir;+ throw new Error('There is no such example.');+ }+ const example = (await listExamples({ source })).find((e) => e.id === id);+ if (!example) throw new Error('There is no such example.');+ const cache = join(home, 'cache', 'examples');+ const dir = join(cache, id);+ try { if (now() - statSync(dir).mtimeMs < DAY && existsSync(join(dir, 'film.html'))) return dir; } catch { /* not kept yet */ }+ await mkdir(cache, { recursive: true });+ const work = await mkdtemp(join(cache, `.${id}-`));+ try {+ const landed = await fetchFolder(example.url, work);+ await rm(dir, { recursive: true, force: true });+ await rename(landed, dir);+ return dir;+ } finally {+ await rm(work, { recursive: true, force: true }).catch(() => {});+ }+}diff --git a/packages/openfilm/studio/server/examples.test.mjs b/packages/openfilm/studio/server/examples.test.mjsindex 32a3d6b..72f561c 100644--- a/packages/openfilm/studio/server/examples.test.mjs+++ b/packages/openfilm/studio/server/examples.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { mkdtempSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { exampleSeconds, listExamples, readExamples } from './examples.mjs';@@ -8,7 +8,8 @@ import { exampleSeconds, listExamples, readExamples } from './examples.mjs';test('an index\'s examples: each with the address that fetches its folder, its poster from the repository', () => {const examples = readExamples({examples: [- { folder: 'one-prompt', title: 'One Prompt', description: 'Every frame is code.', poster: 'one-prompt/look.png', duration: '1:29' },+ { folder: 'one-prompt', title: 'One Prompt', description: 'Every frame is code.', poster: 'one-prompt/look.png', duration: '1:29',+ video: 'one-prompt/preview.mp4', category: 'music', segments: [{ title: 'S1-Open', from: 0, to: '0:12' }, { title: 'bad', from: 5, to: 2 }, { from: 1, to: 2 }] },{ folder: '../escape', title: 'No' },{ folder: 'untitled' },{ folder: 'abs', title: 'Abs', poster: 'https://example.com/p.png', duration: 12 },@@ -18,9 +19,11 @@ test('an index\'s examples: each with the address that fetches its folder, its p{id: 'one-prompt', title: 'One Prompt', description: 'Every frame is code.', duration: 89,poster: 'https://raw.githubusercontent.com/openfilm/examples/main/one-prompt/look.png',+ video: 'https://raw.githubusercontent.com/openfilm/examples/main/one-prompt/preview.mp4',url: 'https://github.com/openfilm/examples/tree/main/one-prompt',+ category: 'music', segments: [{ title: 'S1-Open', from: 0, to: 12 }],},- { id: 'abs', title: 'Abs', description: '', duration: 12, poster: 'https://example.com/p.png', url: 'https://github.com/openfilm/examples/tree/main/abs' },+ { id: 'abs', title: 'Abs', description: '', duration: 12, poster: 'https://example.com/p.png', video: null, url: 'https://github.com/openfilm/examples/tree/main/abs', category: null, segments: [] },]);/* another repository: named by the index, or the one it is read from */assert.equal(readExamples({ repo: 'https://github.com/a/b', branch: 'dev', examples: [{ folder: 'x', title: 'X' }] })[0].url, 'https://github.com/a/b/tree/dev/x');@@ -47,3 +50,50 @@ test('the index from a file on this computer, or from an address; one that cannoconst notFound = /** @type {typeof fetch} */ (async () => new Response('', { status: 404 }));assert.deepEqual(await listExamples({ source: 'https://example.test/b.json', fetchImpl: notFound }), []);});++test('an example\'s folder: beside a local index, or fetched into the cache and kept a day', async () => {+ const { mkdtempSync, mkdirSync, writeFileSync, existsSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const { exampleFolder } = await import('./examples.mjs');+ const root = mkdtempSync(join(tmpdir(), 'of-example-'));+ mkdirSync(join(root, 'intro'));+ writeFileSync(join(root, 'intro', 'film.html'), '<!doctype html>');+ writeFileSync(join(root, 'examples.json'), JSON.stringify({ examples: [{ folder: 'intro', title: 'Intro' }] }));+ const fetchFolder = async () => { throw new Error('not fetched'); };+ assert.equal(await exampleFolder('intro', { home: root, source: join(root, 'examples.json'), fetchFolder }), join(root, 'intro'));+ await assert.rejects(exampleFolder('../intro', { home: root, source: join(root, 'examples.json'), fetchFolder }), /no such example/);+ /* from a repository: fetched once, then the copy kept */+ let fetched = 0;+ const index = 'https://index.test/examples.json';+ const fetchImpl = async () => ({ ok: true, json: async () => ({ repo: 'https://github.com/a/b', examples: [{ folder: 'intro', title: 'Intro' }] }) });+ await listExamples({ source: index, fetchImpl });+ const fromRepo = async (url, into) => { fetched++; assert.equal(url, 'https://github.com/a/b/tree/main/intro'); const d = join(into, 'intro'); mkdirSync(d); writeFileSync(join(d, 'film.html'), 'x'); return d; };+ const home = join(root, 'home');+ const dir = await exampleFolder('intro', { home, source: index, fetchFolder: fromRepo });+ assert.equal(dir, join(home, 'cache', 'examples', 'intro'));+ assert.ok(existsSync(join(dir, 'film.html')));+ await exampleFolder('intro', { home, source: index, fetchFolder: fromRepo });+ assert.equal(fetched, 1, 'kept');+ await exampleFolder('intro', { home, source: index, fetchFolder: fromRepo, now: () => Date.now() + 2 * 24 * 3600 * 1000 });+ assert.equal(fetched, 2, 'a day on: fetched again');+});++test('GitHub\'s index shows at once: the copy OpenFilm came with, then the last one read, while GitHub is asked', async () => {+ const { EXAMPLES_INDEX, listExamples } = await import('./examples.mjs');+ const home = mkdtempSync(join(tmpdir(), 'of-examples-home-'));+ let answer;+ const slow = () => new Promise((done) => { answer = done; });+ /* GitHub does not answer yet: the copy that came with OpenFilm, its posters served from it */+ const first = await listExamples({ source: EXAMPLES_INDEX, fetchImpl: slow, home });+ assert.ok(first.length > 0, 'examples at once');+ assert.ok(first.every((e) => e.poster?.startsWith('/api/examples/file/')), 'posters from the copy');+ /* GitHub answers with a newer index: kept, and in Studio's home for the next start */+ const newer = { repo: 'https://github.com/openfilm/examples', branch: 'main', examples: [{ folder: 'fresh-one', title: 'Fresh one', poster: 'fresh-one/look.jpg' }] };+ answer({ ok: true, json: async () => newer });+ await new Promise((done) => setTimeout(done, 20));+ const second = await listExamples({ source: EXAMPLES_INDEX, fetchImpl: slow, home });+ assert.deepEqual(second.map((e) => e.id), ['fresh-one']);+ assert.equal(second[0].poster, 'https://raw.githubusercontent.com/openfilm/examples/main/fresh-one/look.jpg', 'a poster the copy does not have comes from GitHub');+ assert.ok(existsSync(join(home, 'cache', 'examples-index.json')));+});diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjsindex a3ad28f..bff0f02 100644--- a/packages/openfilm/studio/server/exports.mjs+++ b/packages/openfilm/studio/server/exports.mjs@@ -66,14 +66,10 @@ import { filmSubtitleCuesInRange, filmSubtitleShown, filmSubtitleSrt, filmSubtitimport { zipFiles } from './zip.mjs';import { inProject } from './files.mjs';import { PROJECT_PARTS, TOOL_DIR } from './projects.mjs';+import { exportsRoot } from '../../src/locations.mjs';-/**- * The exports folder: OPENFILM_EXPORTS, else `exports` in OPENFILM_HOME when that is set (a Studio kept apart, for work- * on OpenFilm itself, leaves nothing in the person's own folder), else the Desktop, where a file just made is found.- */-export const exportsRoot = () => process.env.OPENFILM_EXPORTS- || (process.env.OPENFILM_HOME ? join(process.env.OPENFILM_HOME, 'exports') : '')- || join(homedir(), 'Desktop');+/** The exports folder: the one chosen in Settings, else the Desktop, where a file just made is found (src/locations.mjs). */+export { exportsRoot };/*** @typedef {'h264' | 'hevc' | 'vp9' | 'prores422hq' | 'prores4444' | 'hevc_alpha' | 'png'} VideoCodecdiff --git a/packages/openfilm/studio/server/fetch-error.mjs b/packages/openfilm/studio/server/fetch-error.mjsindex 104fe72..fcaada4 100644--- a/packages/openfilm/studio/server/fetch-error.mjs+++ b/packages/openfilm/studio/server/fetch-error.mjs@@ -2,7 +2,7 @@/** Why fetching a film failed (fetch-repo.mjs, fetch-github.mjs). */export class FetchError extends Error {/**- * `code`, for the editor's own words: url, host, ref, access, network, git, no-folder, no-film, too-big, timeout,+ * `code`, for the editor's own words: url, host, ref, access, network, git, no-folder, no-film, no-skill, too-big, timeout,* cancelled, failed; 'use-git' only between the two modules (GitHub's API cannot list it, git is tried).* @param {string} message @param {number} [status] @param {string} [code]*/diff --git a/packages/openfilm/studio/server/fetch-repo.mjs b/packages/openfilm/studio/server/fetch-repo.mjsindex 36767c8..26d04d3 100644--- a/packages/openfilm/studio/server/fetch-repo.mjs+++ b/packages/openfilm/studio/server/fetch-repo.mjs@@ -15,6 +15,7 @@ import { existsSync } from 'node:fs';import { lstat, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { FILM_FILE } from '../../src/film-doc.mjs';+import { SKILL_FILE, holdsSkills } from '../../src/skills.mjs';import { FetchError } from './fetch-error.mjs';import { downloadFiles, listFiles, resolveCommit } from './fetch-github.mjs';@@ -223,12 +224,13 @@ export async function cloneInto({ cloneUrl, ref, folder, dir, signal, onLine })* Fetch a film into `library`: the repository or folder `source` points at, as a folder of its own named after it* ("one-prompt", "one-prompt 2", …), without `.git`. Resolves to that folder. A folder that is missing, or has no* film.html, leaves nothing behind. GitHub's public repositories come over https (fetch-github.mjs); the others, and- * any GitHub's API cannot list, through git.+ * any GitHub's API cannot list, through git. `skill`: what is fetched is a skill, or a folder of skills (a SKILL.md+ * in place of film.html: src/skills.mjs).* @param {RepoSource} source* @param {{ library: string, onProgress?: (p: FetchProgress) => void, signal?: AbortSignal, maxBytes?: number, timeoutMs?: number,- * hosts?: import('./fetch-github.mjs').GitHubHosts }} options+ * hosts?: import('./fetch-github.mjs').GitHubHosts, skill?: boolean }} options*/-export async function fetchFilm(source, { library, onProgress = () => {}, signal, maxBytes = MAX_BYTES, timeoutMs = TIMEOUT_MS, hosts }) {+export async function fetchFilm(source, { library, onProgress = () => {}, signal, maxBytes = MAX_BYTES, timeoutMs = TIMEOUT_MS, hosts, skill = false }) {const where = source.host === 'github' ? 'GitHub' : 'GitLab';/* why it stopped, when it was stopped here (nothing coming, too big) or by the caller *//** @type {FetchError | null} */@@ -248,6 +250,12 @@ export async function fetchFilm(source, { library, onProgress = () => {}, signal};waited();+ /** what was fetched is not what was asked for: no film.html, or no SKILL.md */+ const notThere = (/** @type {string[]} */ folder) => {+ const place = folder.length ? `“${folder.join('/')}”` : 'that repository';+ return skill ? new FetchError(`There is no ${SKILL_FILE} in ${place}: it is not a skill.`, 422, 'no-skill')+ : new FetchError(`There is no film.html in ${place}: it is not an OpenFilm film.`, 422, 'no-film');+ };const tooBig = () => new FetchError(`It is bigger than ${Math.max(1, Math.round(maxBytes / 1024 / 1024))} MB, so it was stopped.`, 413, 'too-big');/** @type {FetchProgress} */const progress = { phase: 'lookup', percent: null, bytes: 0, total: null };@@ -267,9 +275,8 @@ export async function fetchFilm(source, { library, onProgress = () => {}, signalconst overHttp = async (/** @type {{ owner: string, repo: string }} */ at) => {const { commit, folder } = await resolveCommit(at, source.tree, source.blob, { signal: control.signal, hosts });const files = await listFiles(at, commit, folder, { signal: control.signal, hosts });- if (!files.some((file) => file.path === FILM_FILE)) {- throw new FetchError(`There is no film.html in ${folder.length ? `“${folder.join('/')}”` : 'that repository'}: it is not an OpenFilm film.`, 422, 'no-film');- }+ const fits = skill ? files.some((file) => file.path === SKILL_FILE || file.path.endsWith(`/${SKILL_FILE}`)) : files.some((file) => file.path === FILM_FILE);+ if (!fits) throw notThere(folder);const total = files.reduce((sum, file) => sum + file.size, 0);if (total > maxBytes) throw tooBig();Object.assign(progress, { phase: 'download', total, percent: 0 });@@ -317,9 +324,7 @@ export async function fetchFilm(source, { library, onProgress = () => {}, signalconst from = join(clone, ...folder);const kind = await stat(from).catch(() => null);if (!kind?.isDirectory()) throw new FetchError(`There is no folder “${folder.join('/')}” in that repository.`, 404, 'no-folder');- if (!existsSync(join(from, FILM_FILE))) {- throw new FetchError(`There is no film.html in ${folder.length ? `“${folder.join('/')}”` : 'that repository'}: it is not an OpenFilm film.`, 422, 'no-film');- }+ if (skill ? !holdsSkills(from) : !existsSync(join(from, FILM_FILE))) throw notThere(folder);/* the copy is the person's own: no history of where it came from, no remote */await rm(join(from, '.git'), { recursive: true, force: true });return { from, folder };diff --git a/packages/openfilm/studio/server/files.mjs b/packages/openfilm/studio/server/files.mjsindex 86abeb8..0cb5145 100644--- a/packages/openfilm/studio/server/files.mjs+++ b/packages/openfilm/studio/server/files.mjs@@ -25,8 +25,9 @@ import { ffmpeg } from '../../src/shared.mjs';export const ASSETS = 'assets';/** Folders that hold tools and builds, not a film's pages. */-/* folders that hold no pages of the film (a dot folder is a tool's, and never looked in) */-const SKIP = new Set(['node_modules', 'dist', 'build', 'lib', 'vendor', ASSETS]);+/* folders that hold no pages of the film (a dot folder is a tool's, and never looked in; skills/ holds the project's+ skills, src/skills.mjs) */+const SKIP = new Set(['node_modules', 'dist', 'build', 'lib', 'vendor', 'skills', ASSETS]);export class FileError extends Error {/** @param {string} message @param {number} status */@@ -152,7 +153,7 @@ function cleanLast(/** @type {string} */ rel) {}/** What a file is to the media pane: a picture, a video, a sound, a page, or something else. */-function kindOf(/** @type {string} */ name) {+export function kindOf(/** @type {string} */ name) {const kind = clipKind(name);return kind === 'still' ? 'image' : kind === 'sound' ? 'audio' : kind ?? 'other';}@@ -483,12 +484,14 @@ function freeIn(/** @type {string} */ dir, /** @type {string} */ name) {* Bring files or folders from this computer into the project folder `into` (`assets` or under it): `copy` copies each* (a clone where the disk can make one: at once, and no more room taken until either is changed), `link` puts a link* to it there and remembers the place as one the person linked. A link to the same place already there is that one.- * Returns where each landed.+ * Returns where each landed. `anywhere`: into any folder of `root` ('' its top), not only assets/ (the Saved library,+ * saved.mjs, whose folder is all media).* @param {string} root @param {string} into @param {string[]} paths @param {'copy' | 'link'} mode+ * @param {{ anywhere?: boolean }} [o]*/-export async function bringIn(root, into, paths, mode) {- if (into !== ASSETS && !into.startsWith(`${ASSETS}/`)) throw new FileError('media goes in assets/');- const dir = inside(root, into);+export async function bringIn(root, into, paths, mode, { anywhere = false } = {}) {+ if (!anywhere && into !== ASSETS && !into.startsWith(`${ASSETS}/`)) throw new FileError('media goes in assets/');+ const dir = into ? inside(root, into) : root;await mkdir(dir, { recursive: true });/** @type {string[]} */const landed = [];diff --git a/packages/openfilm/studio/server/get.mjs b/packages/openfilm/studio/server/get.mjsindex 3a2328d..f6fbac5 100644--- a/packages/openfilm/studio/server/get.mjs+++ b/packages/openfilm/studio/server/get.mjs@@ -28,7 +28,7 @@ import { randomUUID } from 'node:crypto';import { realpathSync } from 'node:fs';import { lstat, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { basename, dirname, extname, join, resolve, sep } from 'node:path';+import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path';import { FILM_FILE, clipKind } from '../../src/film-doc.mjs';import { spokenLines } from './captions.mjs';import { dropTranscripts, readTranscript, transcriptIsCurrent, transcriptPath, writeTranscript } from './transcripts.mjs';@@ -116,7 +116,7 @@ export const VERBS = /** @type {Record<string, VerbSpec>} */ ({options: { url: { value: 'url', required: true, repeat: true } },},call: {- help: 'A request to one of the person\'s own services (below), with its key added by Studio. Its answer comes back as it is: text or JSON here, a file saved under assets/<service>/. What it means is yours to read.',+ help: 'A request to one of the person\'s own services (below): how to call it is in the person\'s words or the service\'s docs. Studio adds its key as Authorization: Bearer, or where you write {key} (a --header, the --path\'s query), as the docs say; you never see the key. Its answer comes back as it is: text or JSON here, a file saved under assets/<service>/. What it means is yours to read.',timeoutSec: CALL_TIMEOUT_SEC,options: { service: { value: 'id', required: true }, path: { value: '/path', default: '/' },method: { value: 'method', choices: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }, json: { value: 'json' },@@ -130,7 +130,7 @@ export const WEB_VERBS = ['web-search', 'web-fetch'];/** Where the person connects a service and picks its models, said the same way everywhere. */export const WHERE_TO_CONNECT = 'In Studio, the OpenFilm logo at the top left opens Settings: connect a service under Providers, '- + 'with the person\'s own key, then choose the model for each kind of media under Models.';+ + 'with the person\'s own key, then choose the model for each kind of media under Services.';/** The services that make `verb`, by name: "fal.ai, Google or OpenAI". @param {string} verb */const makers = (verb) => {const names = listProviders().filter((p) => /** @type {readonly string[]} */ (p.verbs).includes(verb)).map((p) => p.name).sort((a, b) => a.localeCompare(b));@@ -245,6 +245,10 @@ async function projectFile(root, rel, name, want) {if (want === 'speech' ? kind !== 'sound' && kind !== 'video' : kind !== 'still') {throw usage(`--${name} wants ${want === 'speech' ? 'a sound or video file' : 'a picture'}; ${basename(rel)} is not one`);}+ /* a recording's transcript is written beside it, and files and folders starting with a dot are the tools' (.git) */+ if (want === 'speech' && relative(root, abs).split(sep).some((part) => part.startsWith('.'))) {+ throw usage(`--${name} ${rel} belongs to the tools (a name starting with a dot), and its transcript would go beside it: copy it elsewhere in the project first`);+ }}/* ── running ─────────────────────────────────────────────────────────────── */@@ -464,9 +468,11 @@ async function land(root, verb, args, result) {}if (verb !== 'tts' && verb !== 'asr') return;for (const row of result.index ?? []) {+ /* asr: beside the recording --src names, checked already (in the project, not the tools'); tts: beside the+ provider's file, under assets/ */const src = verb === 'asr' ? String(args.src) : row?.src;const words = wordsOf(row?.words);- if (!landable(src) || !words.length) continue;+ if ((verb === 'tts' && !landable(src)) || !words.length) continue;const text = typeof row.text === 'string' && row.text.trim() ? row.text : words.map((w) => w.token).join(' ');const dur = Number(row.dur);const lines = spokenLines(text, words, Number.isFinite(dur) && dur > 0 ? dur * 1000 : undefined);diff --git a/packages/openfilm/studio/server/get.test.mjs b/packages/openfilm/studio/server/get.test.mjsindex e018d67..0292a66 100644--- a/packages/openfilm/studio/server/get.test.mjs+++ b/packages/openfilm/studio/server/get.test.mjs@@ -250,6 +250,28 @@ test('asr: the speech alone is sent, its transcript lands beside the recording,assert.equal(transcribed(), 2, '--force transcribes again');});+test('asr: a recording outside assets/ gets its transcript beside it too; the tools\' files are refused', async () => {+ const root = project();+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1', join(root, 'talk.wav')]);+ assert.deepEqual(JSON.parse(await runGet(root, 'asr', { src: 'talk.wav' })), { src: 'talk.wav', text: 'One two.', transcript: 'talk.vtt' });+ assert.match(readFileSync(join(root, 'talk.vtt'), 'utf8'), /^WEBVTT\n\n00:00:00\.100 --> .*\nOne <00:00:00\.500>two\./);++ /* a video the film is made like, kept beside the film but not in it */+ mkdirSync(join(root, 'references'));+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'color=c=black:s=64x64:d=1', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1',+ '-c:v', 'mpeg4', '-c:a', 'aac', '-shortest', join(root, 'references/ref.mp4')]);+ assert.deepEqual(JSON.parse(await runGet(root, 'asr', { src: 'references/ref.mp4' })), { src: 'references/ref.mp4', text: 'One two.', transcript: 'references/ref.vtt' });+ assert.match(readFileSync(join(root, 'references/ref.vtt'), 'utf8'), /\nOne <00:00:00\.500>two\./);+ assert.equal(JSON.parse(await runGet(root, 'asr', { src: 'references/ref.mp4' })).skip, true, 'not made twice');++ /* files and folders starting with a dot are the tools': nothing is sent, nothing is written there */+ mkdirSync(join(root, '.git'));+ writeFileSync(join(root, '.git/talk.wav'), 'RIFF');+ await assert.rejects(runGet(root, 'asr', { src: '.git/talk.wav' }), (e) => e.code === 2 && /belongs to the tools/.test(e.message));+ assert.ok(!existsSync(join(root, '.git/talk.vtt')));+ assert.equal(calls.filter((c) => c.path === '/v1/speech-to-text').length, 2);+});+test('what lands stays in assets/, and the receipt leaves out what it cost', async (t) => {const root = project();const fal = listProviders().find((p) => p.id === 'fal');diff --git a/packages/openfilm/studio/server/keys.mjs b/packages/openfilm/studio/server/keys.mjsindex 8eb0a0c..61f1923 100644--- a/packages/openfilm/studio/server/keys.mjs+++ b/packages/openfilm/studio/server/keys.mjs@@ -1,7 +1,7 @@// @ts-check/*** The person's own keys for media services (Settings → Providers), which service makes each kind of media and with- * which model (Settings → Models).+ * which model (Settings → Services).** Kept in ~/.openfilm/providers.json, readable by this user only (0600, in a 0700 folder), written whole and atomically:* { "keys": { "<provider id>": "<key>" }, "use": { "<verb>": "<provider id>" }, "model": { "<verb>": "<model id>" },diff --git a/packages/openfilm/studio/server/prefs.mjs b/packages/openfilm/studio/server/prefs.mjsindex c2f7280..83eda6d 100644--- a/packages/openfilm/studio/server/prefs.mjs+++ b/packages/openfilm/studio/server/prefs.mjs@@ -5,21 +5,24 @@** 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)+ * projectsFolder where new projects go, when the person chose (null: the default; src/locations.mjs, which the+ * `openfilm` command reads too)*/import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';+import { isAbsolute, join, resolve } from 'node:path';import { studioHome } from './projects.mjs';-/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null }} Prefs */+/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null, projectsFolder: string | null }} Prefs *//** Proxies as CapCut has them: on, at 720p. */-export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null });+export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: 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 }, seenVersion?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);+ const p = /** @type {{ proxies?: { on?: unknown, height?: unknown }, seenVersion?: unknown, projectsFolder?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);+ const folder = (/** @type {unknown} */ v) => (typeof v === 'string' && isAbsolute(v) ? resolve(v) : null);const height = Number(p?.proxies?.height);return {proxies: {@@ -27,6 +30,7 @@ export function prefsOf(raw) {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,+ projectsFolder: folder(p?.projectsFolder),};}@@ -44,7 +48,7 @@ export function readPrefs() {*/export function writePrefs(patch) {const now = readPrefs();- const asked = /** @type {{ proxies?: object, seenVersion?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});+ const asked = /** @type {{ proxies?: object, seenVersion?: unknown, projectsFolder?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});const next = prefsOf({ ...now, ...asked, proxies: { ...now.proxies, ...(asked.proxies ?? {}) } });const at = file();let kept = {};diff --git a/packages/openfilm/studio/server/projects.mjs b/packages/openfilm/studio/server/projects.mjsindex 0f35322..6433ff0 100644--- a/packages/openfilm/studio/server/projects.mjs+++ b/packages/openfilm/studio/server/projects.mjs@@ -22,6 +22,7 @@ import { basename, dirname, join, resolve, sep } from 'node:path';import { EMPTY_FILM } from './film.mjs';import { FILM_FILE, filmHtml } from '../../src/film-doc.mjs';import { writeAtomic } from './atomic.mjs';+import { libraryRoot } from '../../src/locations.mjs';export const TOOL_DIR = '.film';@@ -56,9 +57,8 @@ export function studioKey() {return key;}-/** Where new projects go: ~/Movies/OpenFilm/Projects on macOS, ~/Videos/OpenFilm/Projects elsewhere. */-export const libraryRoot = () => process.env.OPENFILM_LIBRARY- || join(homedir(), process.platform === 'darwin' ? 'Movies' : 'Videos', 'OpenFilm', 'Projects');+/** Where new projects go: the folder chosen in Settings, else ~/Movies/OpenFilm/Projects on macOS, ~/Videos/OpenFilm/Projects elsewhere (src/locations.mjs). */+export { libraryRoot };/*** @typedef {{ id: string, path: string, openedAt: number, folderId?: string }} Recentdiff --git a/packages/openfilm/studio/server/projects.test.mjs b/packages/openfilm/studio/server/projects.test.mjsindex 7afee15..d19fdbb 100644--- a/packages/openfilm/studio/server/projects.test.mjs+++ b/packages/openfilm/studio/server/projects.test.mjs@@ -48,6 +48,17 @@ test('new projects go to the library as Untitled, Untitled 2', async () => {assert.ok(one.path.startsWith(join(realpathSync(scratch), 'library')));});+test('new projects go to the folder chosen in Settings; those made before stay where they are', async () => {+ const before = await createProject('Before');+ mkdirSync(process.env.OPENFILM_HOME, { recursive: true });+ writeFileSync(join(process.env.OPENFILM_HOME, 'prefs.json'), JSON.stringify({ projectsFolder: join(scratch, 'D', 'OpenFilm', 'Projects') }));+ const after = await createProject('After');+ assert.ok(after.path.startsWith(join(realpathSync(scratch), 'D', 'OpenFilm', 'Projects')), after.path);+ const listed = await listProjects();+ assert.equal(listed.find((p) => p.id === before.id)?.path, before.path, 'the one made before is listed where it is');+ assert.equal(listed.find((p) => p.id === before.id)?.missing, false);+});+test('one folder is one project, however its path reaches it', { skip: process.platform === 'win32' }, async () => {const first = await openProject(join(scratch, 'same'));symlinkSync(join(scratch, 'same'), join(scratch, 'link-to-same'));diff --git a/packages/openfilm/studio/server/providers/contract.mjs b/packages/openfilm/studio/server/providers/contract.mjsindex e059315..d5f966d 100644--- a/packages/openfilm/studio/server/providers/contract.mjs+++ b/packages/openfilm/studio/server/providers/contract.mjs@@ -82,7 +82,7 @@* run: (verb: Verb, args: Record<string, unknown>, ctx: RunContext) => Promise<RunResult>,* }} Provider* `models`: the models it can make each kind of media with, its default first, each with the name people know it by- * (Settings → Models shows "ElevenLabs · Multilingual v2").+ * (Settings → Services shows "ElevenLabs · Multilingual v2").* `checkKey`: throws a sentence when a pasted key cannot work as it is (Azure's must carry its region), shown where it* is pasted instead of at the first run. Only for what the provider knows without calling anyone: it must not fetch.* `billingUrl`: the provider's own page where the person tops up its balance. A run that fails because the account hasdiff --git a/packages/openfilm/studio/server/providers/groq.mjs b/packages/openfilm/studio/server/providers/groq.mjsindex 0a69f94..02c1aa0 100644--- a/packages/openfilm/studio/server/providers/groq.mjs+++ b/packages/openfilm/studio/server/providers/groq.mjs@@ -46,7 +46,7 @@ export default {const language = text(args.language).toLowerCase();const gender = text(args.gender).toLowerCase().slice(0, 1);const said = [- ...(language && !language.startsWith(LANGUAGE[model]) ? [`these voices speak ${LANGUAGE[model] === 'en' ? 'English' : 'Arabic'} only (another model in Settings → Models)`] : []),+ ...(language && !language.startsWith(LANGUAGE[model]) ? [`these voices speak ${LANGUAGE[model] === 'en' ? 'English' : 'Arabic'} only (another model in Settings → Services)`] : []),...(text(args.prompt) ? ['--prompt does not narrow Groq\'s voices'] : []),];const limit = clamp(Math.round(number(args.limit) ?? 5), 1, 100);diff --git a/packages/openfilm/studio/server/providers/index.mjs b/packages/openfilm/studio/server/providers/index.mjsindex 908f011..5707422 100644--- a/packages/openfilm/studio/server/providers/index.mjs+++ b/packages/openfilm/studio/server/providers/index.mjs@@ -36,7 +36,7 @@ import doubao from './doubao.mjs';/** The providers paid with the person's own key. */const OWN = [elevenlabs, openai, google, fal, pexels, pixabay, brave, tavily, groq, azure, doubao];-/** The kinds of media the person chooses a provider and model for (Settings → Models). */+/** The kinds of media the person chooses a provider and model for (Settings → Services). */const USE_VERBS = /** @type {Verb[]} */ (['tts', 'music', 'sfx', 'asr', 'image', 'image-search', 'video', 'translate', 'web-search']);export const listProviders = () => OWN;@@ -89,7 +89,7 @@ export async function chooseProvider(verb, { via, settings } = {}) {}/**- * What each kind of media is made with, as Settings → Models shows it: the person's choice while its provider has a+ * What each kind of media is made with, as Settings → Services shows it: the person's choice while its provider has a* key, else none. A choice whose key went away (an environment's key not set where Studio runs now) is kept in the* settings, and comes back with the key, but is not shown as if it could make anything.* @param {ProviderSettings} settingsdiff --git a/packages/openfilm/studio/server/saved.mjs b/packages/openfilm/studio/server/saved.mjsnew file mode 100644index 0000000..d44ec71--- /dev/null+++ b/packages/openfilm/studio/server/saved.mjs@@ -0,0 +1,316 @@+// @ts-check+/**+ * Saved: the person's own library, one for every project, kept as a folder (src/locations.mjs savedRoot,+ * ~/Movies/OpenFilm/Saved). Anything can go in it, in folders of the person's: files of any kind, uploaded or added from+ * a project, and what Studio saves from a film, each as a folder of its own holding what it needs (a bundle):+ *+ * <bundle>/saved.json { version, savedAt, kind: 'clip' | 'group' | 'page', clip | clips | path, durationMs?, w?,+ * h?, template? } a clip as the film has it (its place, its look, the changes made in its+ * page; no time, no id), clips saved together (each one's track from the top one they had+ * and `at` seconds from the first), or a page of a project with what it loads+ * <bundle>/files/… the clip's file and what it loads (closure.mjs), at the places they had in its project, so a+ * page's own references still find what they name+ * <bundle>/poster.jpg its picture, when one could be drawn+ *+ * A bundle is named as the person reads it (its folder's name), and moved, renamed and taken away as any folder is.+ * The API names what is in the library from `saved/` (LIBRARY), as a project's media is named from `assets/`, so the+ * media pane shows both the same way. Used in a project, a thing is a copy: a file is imported into its assets/ as one+ * from the computer is (the same bytes there already are that file), a bundle's files go to `saved/<its place>/` there+ * once (taken again, what is there is used). Changing one never changes the other.+ */+import { existsSync, createReadStream } from 'node:fs';+import { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';+import { basename, dirname, join, posix } from 'node:path';+import { FILM_FILE, clipKind, filmHtml } from '../../src/film-doc.mjs';+import { savedRoot } from '../../src/locations.mjs';+import { STUDIO_STATE, filmClosure, folderView } from './closure.mjs';+import { readProjectFilm } from './film.mjs';+import { cleanName, importFile, inside, kindOf } from './files.mjs';++export class SavedError extends Error {+ /** @param {string} message @param {number} status */+ constructor(message, status) {+ super(message);+ this.status = status;+ }+}++const VERSION = 2;+/** What the API calls the library's top folder: its paths are `saved/<place in the library>`. */+export const LIBRARY = 'saved';+/** The file that makes a folder of the library a bundle. */+const BUNDLE = 'saved.json';+/** A page whose own CSS sets custom properties on :root (or html): the inspector offers them as its template's controls. */+const ROOT_VARS = /(?::root|\bhtml)\s*(?:,[^{]*)?\{[^}]*--[\w-]+\s*:/i;++/** The library's folder, made when it is not there yet. */+export async function libraryRoot() {+ const root = savedRoot();+ await mkdir(root, { recursive: true });+ return root;+}++/** A library path (`saved/<rel>`, `saved` for the top) as its place in the library ('' for the top). */+export function libraryRel(/** @type {unknown} */ path) {+ if (path === LIBRARY || path === '') return '';+ if (typeof path !== 'string' || !path.startsWith(`${LIBRARY}/`)) throw new SavedError('a place in Saved, please', 400);+ return path.slice(LIBRARY.length + 1);+}++/** A place in the library as the API names it. */+export const libraryPath = (/** @type {string} */ rel) => (rel ? `${LIBRARY}/${rel}` : LIBRARY);++/**+ * The library as the media pane lists a project's media (files.mjs listFiles): its files and folders, any depth, by+ * their `saved/` paths. A bundle is one entry, of the kind of its (top) file, with what it is in `saved`.+ */+export async function listLibrary() {+ const root = await libraryRoot();+ /** @type {{ path: string, kind: string, size: number, mtime: number, added: number, saved?: object }[]} */+ const files = [];+ /** @type {string[]} */+ const folders = [];+ async function walk(/** @type {string} */ rel, /** @type {number} */ depth) {+ const entries = await readdir(rel ? join(root, rel) : root, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ const at = rel ? `${rel}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ const bundle = await readBundle(join(root, at));+ if (bundle) { files.push(bundleEntry(at, bundle)); continue; }+ folders.push(libraryPath(at));+ if (depth < 8) await walk(at, depth + 1);+ continue;+ }+ if (!entry.isFile()) continue;+ const info = await stat(join(root, at)).catch(() => null);+ if (info) files.push({ path: libraryPath(at), kind: kindOf(entry.name), size: info.size, mtime: Math.round(info.mtimeMs), added: Math.round(info.birthtimeMs || info.mtimeMs) });+ }+ }+ await walk('', 0);+ const sort = (/** @type {{ path: string }} */ a, /** @type {{ path: string }} */ b) => a.path.localeCompare(b.path, undefined, { numeric: true });+ folders.sort();+ return { files: files.sort(sort), folders, made: folders, pages: [], links: {} };+}++/** A bundle's saved.json, or null when the folder is no bundle. @param {string} dir */+async function readBundle(dir) {+ const raw = await readFile(join(dir, BUNDLE), 'utf8').catch(() => null);+ if (!raw) return null;+ let item;+ try { item = JSON.parse(raw); } catch { return null; }+ if (!item || typeof item !== 'object') return null;+ /* a page of a project was 'file' before */+ if (item.kind === 'file') item.kind = 'page';+ if (item.kind === 'clip' && typeof item.clip?.src === 'string') return item;+ if (item.kind === 'group' && Array.isArray(item.clips) && item.clips.length && item.clips.every((/** @type {any} */ c) => typeof c?.clip?.src === 'string')) return item;+ if (item.kind === 'page' && typeof item.path === 'string') return item;+ return null;+}++/** Its main file: the clip's, a group's top one, the page. */+const mainOf = (/** @type {any} */ item) => (item.kind === 'clip' ? item.clip.src : item.kind === 'group' ? item.clips[0].clip.src : item.path);++/** A bundle as the listing shows it. @param {string} rel @param {any} item */+function bundleEntry(rel, item) {+ const kind = kindOf(mainOf(item));+ const num = (/** @type {unknown} */ v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.round(v) : undefined);+ const savedAt = Date.parse(item.savedAt) || 0;+ const saved = {+ kind: item.kind,+ ...(item.kind === 'group' ? { count: item.clips.length } : {}),+ ...(item.template === true ? { template: true } : {}),+ ...(num(item.durationMs) ? { durationMs: num(item.durationMs) } : {}),+ ...(num(item.w) ? { w: num(item.w) } : {}),+ ...(num(item.h) ? { h: num(item.h) } : {}),+ };+ return { path: libraryPath(rel), kind: kind === 'page' ? 'page' : kind, size: 0, mtime: savedAt, added: savedAt, saved };+}++/** A bundle's picture, or null. */+export async function bundlePoster(/** @type {unknown} */ path) {+ const root = await libraryRoot();+ const file = join(inside(root, libraryRel(path)), 'poster.jpg');+ return existsSync(file) ? file : null;+}++/** A name that is free in folder `dir`: `name`, else `name 2`, `name 3`… */+function freeName(/** @type {string} */ dir, /** @type {string} */ name) {+ for (let n = 1; ; n++) {+ const candidate = n === 1 ? name : `${name} ${n}`;+ if (!existsSync(join(dir, candidate))) return candidate;+ }+}++/**+ * The files a clip needs in project `root`: its own and what it loads, read as the film would (closure.mjs) from a film+ * holding that clip alone; a page beside it only when it is named (another clip's page beside it is not its).+ * @param {string} root @param {Record<string, unknown> & { src: string }} clip+ */+async function clipFiles(root, clip) {+ const folder = folderView(root);+ const film = filmHtml({ tracks: [{ clips: [{ ...clip, id: 'saved' }] }] });+ const held = await filmClosure({+ ...folder,+ size: (path) => (path === FILM_FILE ? Promise.resolve(Buffer.byteLength(film)) : folder.size(path)),+ text: (path) => (path === FILM_FILE ? Promise.resolve(film) : folder.text(path)),+ });+ const files = [...held.keys()].filter((path) => path !== FILM_FILE && !STUDIO_STATE.includes(path));+ /* a version of a project keeps every page beside a page, in case one loads it; a saved clip needs only the pages it+ names */+ const texts = new Map();+ for (const path of files) if (/\.(html?|css|m?js|json|svg)$/i.test(path)) texts.set(path, await folder.text(path) ?? '');+ const named = (/** @type {string} */ page) => [...texts].some(([path, text]) => path !== page && text.includes(posix.basename(page)));+ return files.filter((path) => !/\.html?$/i.test(path) || path === clip.src || named(path));+}++/**+ * A new bundle in the library folder `into` ('' its top), named `name` (a number after it when taken): `files` of+ * project `root` copied in, what it is written, its picture drawn. Returns its path.+ * @param {string} root @param {string[]} files @param {Record<string, unknown>} about @param {string} name @param {string} into+ * @param {(() => Promise<Buffer | null>) | null} poster+ */+async function keep(root, files, about, name, into, poster) {+ const lib = await libraryRoot();+ const parent = into ? inside(lib, into) : lib;+ await mkdir(parent, { recursive: true });+ const folder = freeName(parent, cleanName(name) || 'Saved');+ const dir = join(parent, folder);+ await mkdir(join(dir, 'files'), { recursive: true });+ let template = false;+ for (const rel of files) {+ const to = join(dir, 'files', rel);+ await mkdir(dirname(to), { recursive: true });+ await copyFile(join(root, rel), to);+ if (!template && /\.(html?|css)$/i.test(rel)) template = ROOT_VARS.test(await readFile(to, 'utf8').catch(() => ''));+ }+ const picture = poster ? await poster().catch(() => null) : null;+ if (picture) await writeFile(join(dir, 'poster.jpg'), picture);+ await writeFile(join(dir, BUNDLE), `${JSON.stringify({ version: VERSION, ...about, savedAt: new Date().toISOString(), ...(template ? { template: true } : {}) }, null, 2)}\n`);+ return libraryPath(into ? `${into}/${folder}` : folder);+}++/** Sizes as asked, when they are some. */+const sizes = (/** @type {{ durationMs?: number, w?: number, h?: number }} */ o) => Object.fromEntries(+ /** @type {const} */ (['durationMs', 'w', 'h']).flatMap((k) => (typeof o[k] === 'number' && Number.isFinite(o[k]) && /** @type {number} */ (o[k]) > 0 ? [[k, Math.round(/** @type {number} */ (o[k]))]] : [])),+);++/**+ * @typedef {{ name?: string, into?: string, durationMs?: number, w?: number, h?: number,+ * poster?: (clip: Record<string, unknown> & { src: string }) => Promise<Buffer | null> }} SaveOptions+ */++/**+ * Saves the clip `clipId` of the project at `root` into the library (`o.into`, a `saved/` path; its top by default): the+ * clip as the film has it, without its place in time or its id (it gets a new one where it is put), and every file it+ * needs. A link to clips left behind is not kept. Returns its path.+ * @param {string} root @param {string} clipId @param {SaveOptions} [o]+ */+export async function saveClip(root, clipId, o = {}) {+ const { value } = await readProjectFilm(root);+ const found = value?.tracks.flatMap((t) => t.clips).find((c) => c.id === clipId);+ if (!found) throw new SavedError('That clip is not in the film any more.', 404);+ const clip = /** @type {Record<string, unknown> & { src: string, attrs?: Record<string, string> }} */ (structuredClone(found));+ delete clip.at;+ delete clip.id;+ if (clip.attrs) {+ delete clip.attrs['data-link'];+ if (!Object.keys(clip.attrs).length) delete clip.attrs;+ }+ const files = await clipFiles(root, clip);+ if (!files.includes(clip.src)) throw new SavedError('That clip’s file is not in the project.', 409);+ const name = o.name?.trim() || clip.src.split('/').pop()?.replace(/\.[^.]+$/, '') || clipId;+ return keep(root, files, { kind: 'clip', clip, ...sizes(o) }, name, libraryRel(o.into ?? LIBRARY), o.poster ? () => /** @type {NonNullable<typeof o.poster>} */ (o.poster)(clip) : null);+}++/**+ * Saves the clips `clipIds` of the project at `root` together, as they are laid out: each one's track counted from the+ * top one among them, its time from the first of them. Links among them are kept (they are made anew where they go),+ * links to clips left out are not. The picture is the top one's that draws one. Returns its path.+ * @param {string} root @param {string[]} clipIds @param {SaveOptions} [o]+ */+export async function saveGroup(root, clipIds, o = {}) {+ const { value } = await readProjectFilm(root);+ /** @type {{ track: number, clip: Record<string, unknown> & { src: string, at?: number, attrs?: Record<string, string> } }[]} */+ const found = [];+ value?.tracks.forEach((track, t) => track.clips.forEach((clip) => { if (clipIds.includes(clip.id)) found.push({ track: t, clip: structuredClone(clip) }); }));+ if (!found.length || found.length !== new Set(clipIds).size) throw new SavedError('Those clips are not all in the film any more.', 404);+ const tracks = [...new Set(found.map((f) => f.track))].sort((a, b) => a - b);+ const first = Math.min(...found.map((f) => f.clip.at ?? 0));+ const links = new Map();+ for (const { clip } of found) { const l = clip.attrs?.['data-link']; if (l) links.set(l, (links.get(l) ?? 0) + 1); }+ const clips = found+ .map(({ track, clip }) => {+ const at = Math.round(((clip.at ?? 0) - first) * 1000) / 1000;+ delete clip.at;+ delete clip.id;+ if (clip.attrs?.['data-link'] && (links.get(clip.attrs['data-link']) ?? 0) < 2) delete clip.attrs['data-link'];+ if (clip.attrs && !Object.keys(clip.attrs).length) delete clip.attrs;+ return { track: tracks.indexOf(track), at, clip };+ })+ .sort((a, b) => a.track - b.track || a.at - b.at);+ const files = new Set();+ for (const { clip } of clips) {+ const need = await clipFiles(root, clip);+ if (!need.includes(clip.src)) throw new SavedError('A clip’s file is not in the project.', 409);+ for (const f of need) files.add(f);+ }+ const top = clips.find(({ clip }) => clipKind(clip.src) !== 'sound' && clip.sound !== true)?.clip ?? null;+ const name = o.name?.trim() || `${clips.length} clips`;+ return keep(root, [...files], { kind: 'group', clips, ...sizes(o) }, name, libraryRel(o.into ?? LIBRARY), top && o.poster ? () => /** @type {NonNullable<typeof o.poster>} */ (o.poster)(top) : null);+}++/**+ * Saves the file `rel` of the project at `root` into the library: a page as a bundle, with what it loads; any other+ * file as itself (the same bytes there already are that file). Returns its path.+ * @param {string} root @param {string} rel @param {Omit<SaveOptions, 'poster'> & { poster?: () => Promise<Buffer | null> }} [o]+ */+export async function saveFile(root, rel, o = {}) {+ if (typeof rel !== 'string' || !rel || rel.startsWith('/') || rel.split('/').includes('..')) throw new SavedError('a file of the project, please', 400);+ const info = await stat(join(root, rel)).catch(() => null);+ if (!info?.isFile()) throw new SavedError('That file is not in the project any more.', 404);+ const into = libraryRel(o.into ?? LIBRARY);+ if (clipKind(rel) === 'page') {+ const files = await clipFiles(root, { src: rel });+ if (!files.includes(rel)) files.unshift(rel);+ const name = o.name?.trim() || rel.split('/').pop()?.replace(/\.[^.]+$/, '') || rel;+ return keep(root, files, { kind: 'page', path: rel, ...sizes(o) }, name, into, o.poster ?? null);+ }+ const lib = await libraryRoot();+ const { path } = await importFile(lib, into ? `${into}/${basename(rel)}` : basename(rel), createReadStream(join(root, rel)));+ return libraryPath(path);+}++/**+ * What a project needs to use a thing of the library (`path`, a `saved/` path): a file imported into its assets/ (as+ * one from the computer is), or a bundle's files copied to `saved/<its place>/` there (a file there already is kept as+ * it is) and the clip, a group's clips or the page, with their files' places there.+ * @param {string} root @param {unknown} path+ * @returns {Promise<{ clip: Record<string, unknown> & { src: string } } | { clips: { track: number, at: number, clip: Record<string, unknown> & { src: string } }[] } | { path: string }>}+ */+export async function takeSaved(root, path) {+ const lib = await libraryRoot();+ const rel = libraryRel(path);+ if (!rel) throw new SavedError('a thing in Saved, please', 400);+ const at = inside(lib, rel);+ const info = await stat(at).catch(() => null);+ if (!info) throw new SavedError('That is not in Saved any more.', 404);+ if (info.isFile()) return { path: (await importFile(root, `assets/${basename(rel)}`, createReadStream(at))).path };+ const item = await readBundle(at);+ if (!item) throw new SavedError('That is a folder: open it and pick what is in it.', 400);+ /* its place in the project: the library's, made a name a page's address takes as it is */+ const base = `saved/${rel.split('/').map((part) => part.normalize('NFKC').replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^-+|-+$/g, '') || 'saved').join('/')}`;+ const from = join(at, 'files');+ for (const entry of await readdir(from, { recursive: true, withFileTypes: true }).catch(() => [])) {+ if (!entry.isFile()) continue;+ const src = join(entry.parentPath ?? entry.path, entry.name);+ const to = join(root, base, src.slice(from.length + 1));+ /* there already (taken before, maybe changed since in this project): it stays as it is */+ if ((await stat(to).catch(() => null))?.isFile()) continue;+ await mkdir(dirname(to), { recursive: true });+ await copyFile(src, to);+ }+ if (item.kind === 'page') return { path: `${base}/${item.path}` };+ if (item.kind === 'group') return { clips: item.clips.map((/** @type {any} */ c) => ({ track: c.track, at: c.at, clip: { ...c.clip, src: `${base}/${c.clip.src}` } })) };+ return { clip: { ...item.clip, src: `${base}/${item.clip.src}` } };+}diff --git a/packages/openfilm/studio/server/saved.test.mjs b/packages/openfilm/studio/server/saved.test.mjsnew file mode 100644index 0000000..f4ebde7--- /dev/null+++ b/packages/openfilm/studio/server/saved.test.mjs@@ -0,0 +1,138 @@+import { test, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { makeFolder, moveFile } from './files.mjs';+import { libraryRel, listLibrary, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';++let saved;+let before;+beforeEach(() => {+ before = process.env.OPENFILM_SAVED;+ saved = join(mkdtempSync(join(tmpdir(), 'of-saved-')), 'Saved');+ process.env.OPENFILM_SAVED = saved;+});+afterEach(() => {+ if (before === undefined) delete process.env.OPENFILM_SAVED; else process.env.OPENFILM_SAVED = before;+});++/** A project with a title page that loads its own CSS, a picture and a page in a frame, beside another clip's page. */+function project() {+ const root = mkdtempSync(join(tmpdir(), 'of-saved-project-'));+ mkdirSync(join(root, 'pages'), { recursive: true });+ mkdirSync(join(root, 'assets'), { recursive: true });+ writeFileSync(join(root, 'pages', 'title.html'), '<!doctype html><link rel="stylesheet" href="title.css"><img src="../assets/logo.png"><h1 id="t">Hi</h1><iframe src="inset.html"></iframe><script>window.film={duration:2,frame(){}}</script>');+ writeFileSync(join(root, 'pages', 'title.css'), ':root { --accent: #ff5746; --size: 96px }\nh1 { color: var(--accent) }');+ writeFileSync(join(root, 'pages', 'inset.html'), '<!doctype html><p>Inset</p>');+ writeFileSync(join(root, 'pages', 'other.html'), '<!doctype html><p>Another clip</p>');+ writeFileSync(join(root, 'assets', 'logo.png'), 'png');+ writeFileSync(join(root, 'assets', 'unused.png'), 'unused');+ writeFileSync(join(root, 'assets', 'v.mp4'), 'mp4');+ writeFileSync(join(root, 'film.html'), `<meta name="viewport" content="width=1920, height=1080">+<section>+ <iframe id="title" src="pages/title.html" at="5" style="left: 10px; top: 20px; width: 400px; height: 200px" overrides='[{"at":"#t","text":"Hello","style":{"--accent":"#00ff00"}}]' data-link="T"></iframe>+</section>+<section>+ <video id="v" src="assets/v.mp4#t=0,4" at="3" data-link="L"></video>+ <video id="w" src="assets/v.mp4#t=4,6" at="9" data-link="M"></video>+</section>+<section>+ <audio id="a" src="assets/v.mp4#t=0,4" at="3" data-link="L"></audio>+</section>+`);+ return root;+}++test('a saved clip is a folder of the library named as the person reads it, with every file it loads and none it does not', async () => {+ const root = project();+ const path = await saveClip(root, 'title', { name: 'Lower third', durationMs: 2000, w: 400, h: 200 });+ assert.equal(path, 'saved/Lower third');+ const dir = join(saved, 'Lower third');+ for (const rel of ['pages/title.html', 'pages/title.css', 'pages/inset.html', 'assets/logo.png']) assert.ok(existsSync(join(dir, 'files', rel)), rel);+ for (const rel of ['pages/other.html', 'assets/unused.png', 'film.html']) assert.ok(!existsSync(join(dir, 'files', rel)), rel);+ const kept = JSON.parse(readFileSync(join(dir, 'saved.json'), 'utf8'));+ assert.equal(kept.kind, 'clip');+ assert.equal(kept.clip.at, undefined, 'no place in time: it gets one where it is put');+ assert.equal(kept.clip.id, undefined);+ assert.equal(kept.clip.attrs, undefined, 'a link to clips of the film it came from is not kept');+ assert.deepEqual(kept.clip.overrides, [{ at: '#t', text: 'Hello', style: { '--accent': '#00ff00' } }]);+ assert.deepEqual(kept.clip.box, { x: 10, y: 20, w: 400, h: 200 });+ assert.equal(kept.template, true, 'its CSS sets custom properties on :root');+ assert.equal(await saveClip(root, 'title', { name: 'Lower third' }), 'saved/Lower third 2', 'a name taken gets a number');+ await assert.rejects(saveClip(root, 'nope'), /not in the film/);+});++test('the library lists files of any kind and folders as a project\'s media, a bundle as one entry with what it is', async () => {+ const root = project();+ mkdirSync(saved, { recursive: true });+ await makeFolder(saved, 'Logos');+ writeFileSync(join(saved, 'Logos', 'acme.svg'), '<svg/>');+ writeFileSync(join(saved, 'notes.pdf'), 'pdf');+ writeFileSync(join(saved, '.DS_Store'), 'x');+ await saveClip(root, 'title', { name: 'Lower third', durationMs: 2000, w: 400, h: 200, into: 'saved/Logos' });+ const { files, folders, pages } = await listLibrary();+ assert.deepEqual(folders, ['saved/Logos']);+ assert.deepEqual(pages, []);+ assert.deepEqual(files.map((f) => [f.path, f.kind]), [['saved/Logos/acme.svg', 'image'], ['saved/Logos/Lower third', 'page'], ['saved/notes.pdf', 'other']]);+ assert.deepEqual(files[1].saved, { kind: 'clip', template: true, durationMs: 2000, w: 400, h: 200 });+});++test('a bundle moves and is renamed as a folder; taken into a project, its files go under saved/ there once, its page still finding them', async () => {+ const root = project();+ await saveClip(root, 'title', { name: 'Lower third' });+ await makeFolder(saved, 'Titles');+ await moveFile(saved, 'Lower third', 'Titles/Blue lower third');+ const other = mkdtempSync(join(tmpdir(), 'of-saved-other-'));+ const taken = await takeSaved(other, 'saved/Titles/Blue lower third');+ assert.ok('clip' in taken);+ assert.equal(taken.clip.src, 'saved/Titles/Blue-lower-third/pages/title.html');+ assert.deepEqual(taken.clip.overrides, [{ at: '#t', text: 'Hello', style: { '--accent': '#00ff00' } }]);+ for (const rel of ['pages/title.html', 'pages/title.css', 'assets/logo.png']) assert.ok(existsSync(join(other, 'saved/Titles/Blue-lower-third', rel)), rel);+ /* taken again: what is there is used, a file changed there is not written over */+ writeFileSync(join(other, 'saved/Titles/Blue-lower-third/assets/logo.png'), 'mine');+ await takeSaved(other, 'saved/Titles/Blue lower third');+ assert.equal(readFileSync(join(other, 'saved/Titles/Blue-lower-third/assets/logo.png'), 'utf8'), 'mine');+ await assert.rejects(takeSaved(other, 'saved/Titles'), /a folder/);+ await assert.rejects(takeSaved(other, 'saved/gone.png'), /not in Saved/);+});++test('a file of any kind is saved as itself, and taken as an import into assets/; a page with what it loads', async () => {+ const root = project();+ writeFileSync(join(root, 'assets', 'brief.pdf'), 'pdf');+ assert.equal(await saveFile(root, 'assets/logo.png'), 'saved/logo.png');+ assert.equal(await saveFile(root, 'assets/logo.png'), 'saved/logo.png', 'the same bytes there already are that file');+ assert.equal(await saveFile(root, 'assets/brief.pdf', { into: 'saved' }), 'saved/brief.pdf');+ assert.equal(await saveFile(root, 'pages/title.html'), 'saved/title');+ assert.ok(existsSync(join(saved, 'title', 'files', 'assets', 'logo.png')));+ const other = mkdtempSync(join(tmpdir(), 'of-saved-other-'));+ assert.deepEqual(await takeSaved(other, 'saved/logo.png'), { path: 'assets/logo.png' });+ assert.deepEqual(await takeSaved(other, 'saved/title'), { path: 'saved/title/pages/title.html' });+ await assert.rejects(saveFile(root, '../outside.png'), /a file of the project/);+ await assert.rejects(saveFile(root, 'assets/gone.png'), /not in the project/);+});++test('clips saved together keep their tracks and times from the first, and the links among them only', async () => {+ const root = project();+ const path = await saveGroup(root, ['title', 'v', 'a', 'w'], { name: 'Opener' });+ assert.equal(path, 'saved/Opener');+ const other = mkdtempSync(join(tmpdir(), 'of-saved-other-'));+ const taken = await takeSaved(other, path);+ assert.ok('clips' in taken);+ assert.deepEqual(taken.clips.map(({ track, at, clip }) => [track, at, clip.src, clip.attrs?.['data-link'] ?? null]), [+ [0, 2, 'saved/Opener/pages/title.html', null],+ [1, 0, 'saved/Opener/assets/v.mp4', 'L'],+ [1, 6, 'saved/Opener/assets/v.mp4', null],+ [2, 0, 'saved/Opener/assets/v.mp4', 'L'],+ ]);+ const listed = (await listLibrary()).files.find((f) => f.path === path);+ assert.deepEqual([listed?.kind, listed?.saved?.kind, listed?.saved?.count], ['page', 'group', 4]);+ await assert.rejects(saveGroup(root, ['title', 'gone']), /not all in the film/);+});++test('a place in the library is named from saved/', () => {+ assert.equal(libraryRel('saved'), '');+ assert.equal(libraryRel('saved/a/b.png'), 'a/b.png');+ assert.throws(() => libraryRel('assets/a.png'), /a place in Saved/);+ assert.throws(() => libraryRel(7), /a place in Saved/);+});diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjsindex d84d710..68fce6e 100644--- a/packages/openfilm/studio/server/server.mjs+++ b/packages/openfilm/studio/server/server.mjs@@ -13,7 +13,7 @@* whose name is pointed at this machine (DNS rebinding) gets nothing, not even /api/health.*/import { randomBytes, timingSafeEqual } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { createReadStream, existsSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, extname, isAbsolute, join, normalize, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';import { createServer } from 'node:http';@@ -32,9 +32,9 @@ import {ProjectError, createFolder, createProject, deleteFolder, deleteProject, libraryRoot, listFolders, listProjects, locateProject, markOpened,moveProjectToFolder, openProject, projectById, renameFolder, renameProject, studioHome, studioKey, TOOL_DIR,} from './projects.mjs';-import { FetchError, createFetches } from './fetch-repo.mjs';+import { FetchError, createFetches, fetchFilm, parseRepoUrl } from './fetch-repo.mjs';import { BrowseError, browseFolder, browsePlaces } from './browse.mjs';-import { listExamples } from './examples.mjs';+import { exampleFile, exampleFolder, listExamples } from './examples.mjs';import { pickFiles, pickFolder } from './folder-picker.mjs';import { readPrefs, writePrefs } from './prefs.mjs';import { ensureProxies } from './proxies.mjs';@@ -44,13 +44,16 @@ import { createWatchers } from './watch.mjs';import { installedFonts } from './fonts.mjs';import { projectFonts, resolveIn } from './project-fonts.mjs';import { FILM_PAGE, PageFrameError, closePageFrames, filmPoster, pageFacts, pageFrame, warmFilmPoster } from './pageframes.mjs';+import { SavedError, bundlePoster, libraryPath, libraryRel, libraryRoot as savedLibrary, listLibrary, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';import { FILM_FILE, clipKind, isPage } from '../../src/film-doc.mjs';+import { listSkills, skillOrigins } from '../../src/skills.mjs';import { providersRoute } from './providers/index.mjs';import { captionRoutes } from './captions.mjs';import { projectSettingsRoute } from './project-settings.mjs';import { markersRoute } from './markers.mjs';import { transitionPageRoutes } from './transition-pages.mjs';import { createAsks, getRoute, subtitleTranscriber, subtitleTranslator } from './get.mjs';+import { LOCATION_KEYS, locations, usableFolder } from '../../src/locations.mjs';/** @typedef {import('./http.mjs').Req} Req @typedef {import('./http.mjs').Res} Res */@@ -107,6 +110,8 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowselet pageCame = () => {};/** media being made for an agent's `openfilm get` right now (it would be lost, and paid for, if Studio stopped) */let making = 0;+ /** the update run from the top bar: `{ status: 'updating' | 'failed', version, error? }` (see /api/update) */+ let updating = /** @type {{ status: 'updating' | 'failed', version: string, error?: string } | null} */ (null);/** whether an app's agent is working in the project at `path` now */const agentIn = (/** @type {string} */ path) => working().some((folder) => resolve(folder) === resolve(path));/** how many editor pages have connected since Studio started: whether one opened an address `/open` gave out */@@ -158,7 +163,8 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse/* which Studio this is: the CLI replaces an older one, and finds its own home's when run.json is gone. Askedwithout the key, so it says nothing of the machine: its home only as a digest (homeTag), no process id */- if (path === '/api/health') return json(res, 200, { product: 'openfilm-studio', version: VERSION, home: homeTag(), filmOrigin });+ /* `app`: the desktop app's Studio, which updates with the app (`openfilm update` says so instead) */+ if (path === '/api/health') return json(res, 200, { product: 'openfilm-studio', version: VERSION, home: homeTag(), filmOrigin, ...(stays ? { app: true } : {}) });const signIn = [`${COOKIE}=${key}; Path=/; HttpOnly; SameSite=Strict`, `${FRAMED}=${key}; Path=/; HttpOnly; Secure; SameSite=None; Partitioned`];/** A page's address with the key in it (the address bar is what a person copies). */const keyed = (/** @type {string} */ to) => {@@ -232,7 +238,21 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowseif (parts[0] === 'version' && parts.length === 1 && req.method === 'GET') {const now = url.searchParams.get('check') === '1';const { latest, checkedAt } = await npmOpenfilm({ force: now, waitMs: 4000 });- return json(res, 200, { version: VERSION, latest, newer: Boolean(latest && olderThanThis(VERSION, latest)), checkedAt, checking: !process.env.OPENFILM_NO_UPDATE_CHECK && !FROM_SOURCE, source: FROM_SOURCE });+ return json(res, 200, { version: VERSION, latest, newer: Boolean(latest && olderThanThis(VERSION, latest)), checkedAt, checking: !process.env.OPENFILM_NO_UPDATE_CHECK && !FROM_SOURCE, source: FROM_SOURCE,+ ...(updating ? { update: updating } : {}) });+ }+ /* the top bar's Update (Studio run with npm, not the app's nor a checkout): the newest openfilm run in the+ background as `openfilm update` (client.mjs updateOpenfilm), which starts Studio again on it; the pages come back+ on the new version and reload. Not while an export runs or media is made. `/api/version` says how it goes */+ if (parts[0] === 'update' && parts.length === 1 && req.method === 'POST') {+ if (stays || FROM_SOURCE) return json(res, 409, { error: 'this Studio does not update itself', code: stays ? 'app' : 'source' });+ if (exports.busy()) return json(res, 409, { error: 'an export is running', code: 'exporting' });+ if (making) return json(res, 409, { error: 'media is being made', code: 'making' });+ if (updating?.status === 'updating') return json(res, 202, { update: updating });+ const { latest } = await npmOpenfilm({ waitMs: 4000 });+ if (!latest || !olderThanThis(VERSION, latest)) return json(res, 409, { error: 'this is the newest openfilm', code: 'newest' });+ updating = runUpdate(latest, (next) => { updating = next; });+ return json(res, 202, { update: updating });}/* the fonts installed here (what a web page can draw with, in the preview and the export alike) */if (parts[0] === 'fonts' && parts.length === 1 && req.method === 'GET') return json(res, 200, { fonts: await installedFonts() });@@ -264,10 +284,76 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowsethrow new HttpError(501, /** @type {Error} */ (e).message);}}+ /* Saved, the person's own library for every project (saved.mjs): its files and folders as a project's media are+ (files.mjs), by their `saved/` paths; a file's bytes, a bundle's picture, and what Studio works out from a file */+ if (parts[0] === 'saved') {+ const sub = parts.slice(1).join('/');+ const lib = await savedLibrary();+ const rel = (/** @type {unknown} */ path) => { try { return libraryRel(path); } catch (e) { throw new HttpError(400, /** @type {Error} */ (e).message); } };+ const at = url.searchParams.get('path') ?? '';+ if (sub === 'files') {+ if (req.method === 'GET') return json(res, 200, await listLibrary());+ if (req.method === 'PUT') return json(res, 200, { path: libraryPath((await importFile(lib, rel(at), req)).path) });+ if (req.method === 'PATCH') {+ const { from, to } = /** @type {{ from?: unknown, to?: unknown }} */ (await readJson(req) ?? {});+ return json(res, 200, { path: libraryPath((await moveFile(lib, rel(from), rel(to))).path) });+ }+ if (req.method === 'DELETE') { await trashFile(lib, rel(at)); return json(res, 200, {}); }+ }+ if (sub === 'folders' && req.method === 'POST') {+ const { path: folder } = /** @type {{ path?: unknown }} */ (await readJson(req) ?? {});+ return json(res, 200, { path: libraryPath(await makeFolder(lib, rel(folder))) });+ }+ /* files or folders of this computer copied in: the paths given, else the person's pick. { landed } */+ if (sub === 'files/bring' && req.method === 'POST') {+ const { into, paths, folder, title } = /** @type {{ into?: unknown, paths?: unknown, folder?: unknown, title?: unknown }} */ (await readJson(req) ?? {});+ const ask = { title: typeof title === 'string' && title.trim() ? title.trim().slice(0, 120) : 'Choose', at: null };+ const picked = Array.isArray(paths) ? paths.map(String)+ : await (folder === true ? pickFolder(ask).then((p) => (p ? [p] : [])) : pickFiles(ask)).catch((e) => { throw new HttpError(501, String(e?.message ?? e)); });+ return json(res, 200, { landed: (await bringIn(lib, rel(into ?? 'saved'), picked, 'copy', { anywhere: true })).map(libraryPath) });+ }+ if (sub === 'reveal' && req.method === 'POST') {+ const { path: shown } = /** @type {{ path?: unknown }} */ (await readJson(req) ?? {});+ const where = rel(shown ?? 'saved');+ if (where) reveal(inside(lib, where)); else openFile(lib);+ return json(res, 200, {});+ }+ if (sub === 'file' && req.method === 'GET') return sendMedia(req, res, inside(lib, rel(at)));+ if (sub === 'poster' && req.method === 'GET') return sendMedia(req, res, await savedCall(() => bundlePoster(at)));+ if (sub === 'media' && req.method === 'GET') {+ const what = url.searchParams.get('what');+ const file = rel(at);+ if (what === 'probe') return json(res, 200, isPage(file) ? {} : await probe(lib, file));+ if (what === 'wave') return json(res, 200, await waveform(lib, file));+ const jpeg = what === 'poster' && !isPage(file) ? await poster(lib, file)+ : what === 'frame' && !isPage(file) ? await frame(lib, file, Number(url.searchParams.get('ms')), Number(url.searchParams.get('w')))+ : null;+ if (!jpeg) throw new HttpError(400, 'what: probe, poster, frame or wave, of a media file');+ res.writeHead(200, { 'content-type': 'image/jpeg', 'cache-control': 'private, max-age=86400', 'content-length': jpeg.length });+ return res.end(jpeg);+ }+ }/* Studio's own preferences, the same for every project (prefs.mjs) */if (parts[0] === 'prefs' && parts.length === 1) {if (req.method === 'GET') return json(res, 200, readPrefs());- if (req.method === 'PATCH') return json(res, 200, writePrefs(await readJson(req)));+ if (req.method === 'PATCH') {+ /* a folder chosen for new projects is checked, and made, before it is kept */+ const patch = /** @type {Record<string, unknown>} */ (await readJson(req) ?? {});+ for (const key of Object.values(LOCATION_KEYS)) {+ if (patch[key] == null) continue;+ try { patch[key] = usableFolder(patch[key]); } catch (e) { throw new HttpError(400, /** @type {Error} */ (e).message); }+ }+ return json(res, 200, writePrefs(patch));+ }+ }+ /* where new projects go (src/locations.mjs): the folder, its default, and its disk's free space; a POST opens it+ in the system's file manager */+ if (parts[0] === 'locations' && parts.length === 1 && req.method === 'GET') return json(res, 200, locations());+ if (parts[0] === 'locations' && parts[1] === 'projects' && parts.length === 2 && req.method === 'POST') {+ const folder = locations()[parts[1]].path;+ mkdirSync(folder, { recursive: true });+ openFile(folder);+ return json(res, 200, { ok: true });}/* the system's file dialog (folder-picker.mjs pickFiles), several at once: { paths } (none: cancelled); 501 whenthis system has none */@@ -287,6 +373,48 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse}/* the example films (examples.mjs): none when the index cannot be read */if (parts[0] === 'examples' && parts.length === 1 && req.method === 'GET') return json(res, 200, { examples: await listExamples() });+ /* a poster or preview beside an index read from this computer (examples.mjs exampleFile) */+ if (parts[0] === 'examples' && parts[1] === 'file' && parts.length > 2 && req.method === 'GET') {+ return sendMedia(req, res, exampleFile(parts.slice(2).map(decodeURIComponent).join('/')), { keep: true });+ }+ /* an example's folder on this computer, to point an agent at (examples.mjs exampleFolder) */+ if (parts[0] === 'examples' && parts.length === 3 && parts[2] === 'folder' && req.method === 'POST') {+ try {+ const folder = await exampleFolder(decodeURIComponent(parts[1]), {+ home: studioHome(),+ fetchFolder: (address, into) => fetchFilm(parseRepoUrl(address), { library: into }),+ });+ return json(res, 200, { folder });+ } catch (e) {+ throw new HttpError(e instanceof FetchError ? e.status : 404, e instanceof Error ? e.message : String(e));+ }+ }+ /* the skills a project can be made with (../../src/skills.mjs): its own, the person's, the official ones */+ if (parts[0] === 'skills' && parts.length === 1 && req.method === 'GET') {+ const id = url.searchParams.get('project');+ const project = id ? (await listProjects()).find((p) => p.id === id && !p.missing) : null;+ const skills = listSkills({ project: project?.path ?? null });+ const origins = skillOrigins();+ const media = (/** @type {string} */ name, /** @type {'cover' | 'preview'} */ which) => `/api/skills/${encodeURIComponent(name)}/${which}${id ? `?project=${encodeURIComponent(id)}` : ''}`;+ return json(res, 200, {+ skills: skills.map((k) => ({+ name: k.name, description: k.description, source: k.source, scripts: k.scripts.length,+ ...(k.shown ? { shown: k.shown } : {}), ...(k.version ? { version: k.version } : {}), ...(k.kind ? { kind: k.kind } : {}),+ ...(k.order != null ? { order: k.order } : {}), ...(k.icon ? { icon: k.icon } : {}), ...(k.repository ? { repository: k.repository } : {}),+ ...(k.cover ? { cover: media(k.name, 'cover') } : {}), ...(k.preview ? { preview: media(k.name, 'preview') } : {}),+ /* the person's own: where it came from (none kept: made where it is) */+ ...(k.source === 'mine' ? { origin: origins[basename(k.folder)] ?? { from: 'made' } } : {}),+ })),+ });+ }+ /* a skill's cover picture or preview video (its openfilm.json's `cover`, `preview`) */+ if (parts[0] === 'skills' && parts.length === 3 && (parts[2] === 'cover' || parts[2] === 'preview') && req.method === 'GET') {+ const id = url.searchParams.get('project');+ const project = id ? (await listProjects()).find((p) => p.id === id && !p.missing) : null;+ const skill = listSkills({ project: project?.path ?? null }).find((k) => k.name === decodeURIComponent(parts[1]));+ const file = skill?.[parts[2]];+ return sendMedia(req, res, skill && file ? join(skill.folder, file) : null, { keep: true });+ }if (parts[0] !== 'projects') throw new HttpError(404, 'no such API');if (parts.length === 1) {@@ -540,6 +668,35 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowsereturn json(res, 200, {});}}+ /* clips, groups of clips and files of this project put in Saved (saved.mjs), each bundle with its picture; and a+ thing of Saved taken into this project (a file imported, a bundle's files copied in) */+ if (rest === 'saved' && req.method === 'POST') {+ const body = /** @type {{ clips?: unknown, groups?: unknown, files?: unknown, into?: unknown }} */ (await readJson(req) ?? {});+ const asked = (/** @type {unknown} */ list) => (Array.isArray(list) ? list.filter((x) => x && typeof x === 'object').slice(0, 50) : []);+ const into = typeof body.into === 'string' ? body.into : undefined;+ const base = pages.folderUrl(project);+ const paths = await savedCall(async () => {+ const out = [];+ for (const c of /** @type {{ id?: unknown, name?: string, durationMs?: number, w?: number, h?: number }[]} */ (asked(body.clips))) {+ const ms = typeof c.durationMs === 'number' && c.durationMs > 0 ? c.durationMs : 0;+ out.push(await saveClip(project.path, String(c.id ?? ''), { ...c, into, poster: (clip) => clipPoster(project.path, base, clip, ms) }));+ }+ for (const g of /** @type {{ ids?: unknown, name?: string, durationMs?: number, w?: number, h?: number }[]} */ (asked(body.groups))) {+ const ids = Array.isArray(g.ids) ? g.ids.filter((id) => typeof id === 'string').slice(0, 200) : [];+ out.push(await saveGroup(project.path, ids, { ...g, into, poster: (clip) => clipPoster(project.path, base, clip, 0) }));+ }+ for (const f of /** @type {{ path?: unknown, name?: string, durationMs?: number, w?: number, h?: number }[]} */ (asked(body.files))) {+ const file = String(f.path ?? '');+ out.push(await saveFile(project.path, file, { ...f, into, poster: () => clipPoster(project.path, base, { src: file }, typeof f.durationMs === 'number' ? f.durationMs : 0) }));+ }+ return out;+ });+ return json(res, 200, { paths });+ }+ if (rest === 'saved/take' && req.method === 'POST') {+ const { path: from } = /** @type {{ path?: unknown }} */ (await readJson(req) ?? {});+ return json(res, 200, await savedCall(() => takeSaved(project.path, from)));+ }/* what Studio works out from a media file: its length and size, a poster, a frame, a waveform (see derived.mjs) */if (rest === 'media' && req.method === 'GET') {const at = url.searchParams.get('path') ?? '';@@ -689,6 +846,8 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse})().catch(() => refuse('500 Internal Server Error'));});await new Promise((done, fail) => { editor.once('error', fail); editor.listen(port, '127.0.0.1', () => done(undefined)); });+ /* the examples index is asked for as Studio starts, so the Examples tab has GitHub's newest when it opens */+ void listExamples().catch(() => {});const address = /** @type {import('node:net').AddressInfo} */ (editor.address());origin = `http://127.0.0.1:${address.port}`;COOKIE = cookieName(address.port);@@ -734,6 +893,35 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse/** Run from a checkout of the repository (the editor's source is beside its build), not from an installed package. */const FROM_SOURCE = existsSync(new URL('../ui/src', import.meta.url));+/**+ * `npx -y openfilm@<version> update` in the background (its words in logs/update.log), as the person would run it: the+ * newest stops this Studio and starts itself in its place. `then` hears it failed later, with its last words, if this+ * Studio is still here to hear it; one that cannot start is said at once.+ * @param {string} version @param {(state: { status: 'failed', version: string, error: string }) => void} then+ * @returns {{ status: 'updating' | 'failed', version: string, error?: string }}+ */+function runUpdate(version, then) {+ const logs = join(studioHome(), 'logs');+ mkdirSync(logs, { recursive: true });+ const file = join(logs, 'update.log');+ writeFileSync(file, '');+ const failed = (/** @type {string} */ error) => then({ status: 'failed', version, error });+ try {+ const out = openSync(file, 'a');+ const child = spawn('npx', ['-y', `openfilm@${version}`, 'update'], {+ detached: true, stdio: ['ignore', out, out], windowsHide: true, shell: process.platform === 'win32', env: { ...process.env, OPENFILM_NO_BROWSER: '1' },+ });+ child.once('error', (e) => failed(`npx did not start (it comes with Node.js): ${e.message}`));+ child.once('exit', (code) => {+ if (code === 0) return;+ const said = readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).pop() ?? '';+ failed(said || `npx stopped (${code})`);+ });+ child.unref();+ } catch (e) { return { status: 'failed', version, error: e instanceof Error ? e.message : String(e) }; }+ return { status: 'updating', version };+}+/** This package's version: the CLI replaces a Studio older than itself. */export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;@@ -795,6 +983,34 @@ export function opener(target, platform = process.platform) {return platform === 'darwin' ? ['open', target] : ['xdg-open', target];}+/**+ * What saved.mjs answers, its refusals as the HTTP errors they are.+ * @template T @param {() => Promise<T>} fn @returns {Promise<T>}+ */+async function savedCall(fn) {+ try { return await fn(); } catch (e) {+ if (e instanceof SavedError) throw new HttpError(/** @type {number} */ (e.status), e.message);+ throw e;+ }+}++/**+ * A saved clip's picture, from the middle of what it shows: a page drawn with the changes made in it, a video's frame,+ * a still's own; a sound has none.+ * @param {string} root @param {string} base the project's folder as the pages are served (pageframes.mjs)+ * @param {{ src: string, time?: unknown, overrides?: unknown }} clip @param {number} durationMs+ * @returns {Promise<Buffer | null>}+ */+async function clipPoster(root, base, clip, durationMs) {+ const kind = clipKind(clip.src);+ const from = Array.isArray(clip.time) && typeof clip.time[0] === 'number' ? clip.time[0] * 1000 : 0;+ const ms = durationMs > 0 ? from + durationMs / 2 : -1;+ if (kind === 'page') return pageFrame(root, base, clip.src, ms, 480, Array.isArray(clip.overrides) ? clip.overrides : null);+ if (kind === 'video') return frame(root, clip.src, Math.max(0, ms), 480);+ if (kind === 'still') return poster(root, clip.src);+ return null;+}+/** A file in the app the system opens it with. */function openFile(/** @type {string} */ file) {const [cmd, ...args] = opener(file);@@ -807,3 +1023,27 @@ function systemBrowser(/** @type {string} */ url) {try { spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true }).on('error', () => {}).unref(); } catch { /* no browser to open */ }}++/**+ * A picture or a video from this computer, a range answered as one (a preview is seeked in); none: 404.+ * @param {import('node:http').IncomingMessage} req @param {import('node:http').ServerResponse} res @param {string | null | undefined} file+ */+function sendMedia(req, res, file, { keep = false } = {}) {+ if (!file || !existsSync(file) || !statSync(file).isFile()) throw new HttpError(404, 'no such file');+ const { size, mtimeMs } = statSync(file);+ /* `keep`: a picture that changes only with its file (a skill's cover, an example's poster) is kept by the browser+ an hour, and then only asked whether it changed */+ const tag = `"${size.toString(36)}-${Math.round(mtimeMs).toString(36)}"`;+ const kept = keep ? { etag: tag, 'cache-control': 'private, max-age=3600' } : {};+ if (keep && req.headers['if-none-match'] === tag) { res.writeHead(304, kept); res.end(); return undefined; }+ const type = {+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif', '.svg': 'image/svg+xml',+ '.mp4': 'video/mp4', '.m4v': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime',+ '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.flac': 'audio/flac',+ }[extname(file).toLowerCase()] ?? 'application/octet-stream';+ const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range ?? ''));+ const [from, to] = range ? [range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2])), range[2] && range[1] ? Math.min(size - 1, Number(range[2])) : size - 1] : [0, size - 1];+ res.writeHead(range ? 206 : 200, { 'content-type': type, 'content-length': to - from + 1, 'accept-ranges': 'bytes', ...kept, ...(range ? { 'content-range': `bytes ${from}-${to}/${size}` } : {}) });+ createReadStream(file, { start: from, end: to }).pipe(res);+ return undefined;+}diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjsindex 8801532..2964d32 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 }, seenVersion: null });+ assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: 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 }, seenVersion: null });+ assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 }, seenVersion: null, projectsFolder: 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 } } });@@ -499,11 +499,23 @@ test('an app\'s Studio (`stays`) is not stopped by `openfilm open`, and says whyassert.equal(res.status, 423);assert.match((await res.json()).error, /app/);assert.equal((await fetch(`${kept.origin}/api/health`)).status, 200, 'still there');+ /* it says it is the app's, so `openfilm update` says the app updates it */+ assert.equal((await (await fetch(`${kept.origin}/api/health`)).json()).app, true);+ const update = await fetch(`${kept.origin}/api/update`, { method: 'POST', headers: { 'x-studio-key': kept.key, 'content-type': 'application/json' }, body: '{}' });+ assert.deepEqual([update.status, (await update.json()).code], [409, 'app'], 'it does not update itself');} finally {await kept.close();}});+test('Update is not run from a source checkout (git pull updates it), nor without the key', async () => {+ assert.equal((await api('/api/update', { method: 'POST', body: {}, key: null })).status, 401);+ const res = await api('/api/update', { method: 'POST', body: {} });+ assert.deepEqual([res.status, (await res.json()).code], [409, 'source']);+ assert.equal((await (await api('/api/health')).json()).app, undefined, 'not an app\'s');+ assert.equal((await (await api('/api/version')).json()).update, undefined, 'no update running');+});+test('`openfilm open` without a folder opens the project opened last, and makes none', async () => {const before = (await (await api('/api/projects')).json()).projects;const last = before.find((p) => !p.missing && existsSync(join(p.path, 'film.html')));diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.jsindex 2fff0ee..25d8f54 100644--- a/packages/openfilm/studio/server/stage.js+++ b/packages/openfilm/studio/server/stage.js@@ -9,6 +9,7 @@** editor → { source: 'openfilm-studio', type: 'stage', seq, op, ...args } (ops below, at `ops`)* film → { source: 'openfilm-film', type: 'stage', seq, result } the answer (null when nothing)+ * { type: 'stage-event', event: 'typing', handle, value } the words of an in-place edit as they are typed* { type: 'stage-event', event: 'text', handle, commit, value?, before? } an in-place edit ended* { type: 'stage-event', event: 'key', key, code, repeat, metaKey, ctrlKey, shiftKey, altKey }* a key pressed in the picture (not while typing in it)@@ -101,6 +102,8 @@const INLINE = new Set(['BR', 'WBR', 'EM', 'STRONG', 'B', 'I', 'U', 'S', 'SPAN', 'SMALL', 'SUP', 'SUB', 'A', 'MARK', 'CODE', 'ABBR', 'Q', 'TIME']);const EDITOR_ATTR = 'data-openfilm-text-editor';const LIMIT = 1500;+ /** At most this many custom properties, and as many words, as a page's template controls. */+ const CONTROLS = 40;const view = (el) => el.ownerDocument.defaultView;const css = (el) => view(el).getComputedStyle(el);@@ -583,6 +586,30 @@*/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 that fills its whole page, whatever it is (a vignette's box, a grain's canvas, a letterbox's picture). */+ const fillsPage = (c, hit) => !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;+ /**+ * The page a point of the picture is about. The top page under it, unless all it has there fills the page (a+ * letterbox, a vignette, grain laid over the film) while a page under it has a layer of its own there: then that+ * one, so a click on a title under a full-frame overlay takes the title. A layer in hand keeps its own page.+ */+ const pageAt = (x, y, includeLocked, held) => {+ const inside = (c) => { const p = matrixOf(c).inverse().transformPoint(new DOMPoint(x, y)); return p.x >= 0 && p.y >= 0 && p.x <= c.w && p.y <= c.h ? p : null; };+ if (held) {+ const own = shown().find((c) => c.kind === 'page' && c.win && c.win.document === held.ownerDocument && inside(c));+ if (own) return own;+ }+ const top = clipAt(x, y);+ if (!top || top.kind !== 'page' || !top.win) return top;+ for (const c of shown()) {+ const p = inside(c);+ if (!p) continue;+ if (c.kind !== 'page' || !c.win) break;+ if (layersAt(c, p.x, p.y, includeLocked).some((h) => !fillsPage(c, h))) return c;+ }+ return top;+ };/** 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 = [];@@ -901,7 +928,12 @@else el.style.setProperty(prop, extra[k], 'important');}};- const onInput = () => { if (search && editing) editing.hold = search(holdInline); };+ /* the editor shows the words as they are typed (the inspector's box with them); they are kept at Enter or blur */+ const onInput = () => {+ if (!editing) return;+ if (search) editing.hold = search(holdInline);+ post({ type: 'stage-event', event: 'typing', handle, value: overlay ? collapse(host.innerText ?? host.textContent ?? '') : stageText(host) });+ };const host = overlay ? openOverlay(el) : el;/* the line hidden under its overlay, the blocks in it still shown (they are not what is typed) */const blocks = overlay ? blocksIn(el).map((b) => [b, b.getAttribute('style')]) : [];@@ -1227,7 +1259,7 @@const ops = {/** The layer under a point: the smallest (Alt: the next one under `cycleFrom`); groups stand for their layers. */hit({ x, y, cycleFrom, includeLocked, from, enter, detail }) {- const c = clipAt(x, y);+ const c = pageAt(x, y, Boolean(includeLocked), nodeOf(cycleFrom) ?? nodeOf(from));if (!c || c.kind !== 'page' || !c.win) return null;const p = matrixOf(c).inverse().transformPoint(new DOMPoint(x, y));const all = layersAt(c, p.x, p.y, Boolean(includeLocked));@@ -1507,6 +1539,53 @@},textStart: startText,textFinish({ commit }) { finishText(Boolean(commit)); return true; },+ /**+ * A page clip's template controls, what the inspector offers to change in it without opening the page: the CSS+ * custom properties its stylesheets set on `:root` (or `html`), each with its value now; its words, each layer of+ * text with its selector and its words now; and its pictures, each <img> and each box painted with one image, with+ * the address drawn now. Null when the clip is not a page on the picture now.+ */+ controls({ clip }) {+ const c = clipById(clip);+ const doc = c?.kind === 'page' ? c.win?.document : null;+ if (!doc?.documentElement || !doc.body) return null;+ const names = new Set();+ const root = /^(?::root|html)$/i;+ const read = (rules) => {+ for (const rule of rules ?? []) {+ if (names.size >= CONTROLS) return;+ if (rule.cssRules && !rule.selectorText) { read(rule.cssRules); continue; }+ if (!rule.selectorText || !rule.selectorText.split(',').some((sel) => root.test(sel.trim()))) continue;+ for (const prop of rule.style) if (prop.startsWith('--')) names.add(prop);+ }+ };+ for (const sheet of doc.styleSheets) {+ try { read(sheet.cssRules); } catch { /* a stylesheet from elsewhere: not readable */ }+ }+ const now = c.win.getComputedStyle(doc.documentElement);+ const vars = [...names].slice(0, CONTROLS).map((name) => ({ name, value: now.getPropertyValue(name).trim() }));+ const texts = [];+ for (const el of layersOf(doc)) {+ if (texts.length >= CONTROLS) break;+ if (kindOf(el) !== 'text' || isSvgText(el) || el.closest('svg')) continue;+ const value = textOf(el);+ if (!value) continue;+ const { at, n } = locOf(el);+ texts.push({ at, ...(n ? { n } : {}), label: el.id ? nameOf(el) : '', value });+ }+ const images = [];+ for (const el of layersOf(doc)) {+ if (images.length >= CONTROLS) break;+ if (el.closest('svg')) continue;+ const img = el.localName.toLowerCase() === 'img';+ const painted = img ? null : /^url\("?([^"]*)"?\)$/.exec(css(el).backgroundImage);+ const src = img ? el.currentSrc || el.src : painted?.[1] ?? '';+ if (!src) continue;+ const { at, n } = locOf(el);+ images.push({ at, ...(n ? { n } : {}), label: el.id ? nameOf(el) : (img && el.alt) || '', kind: img ? 'img' : 'bg', src });+ }+ return { vars, texts, images, page: c.win.location.href };+ },};window.addEventListener('message', async (e) => {diff --git a/packages/openfilm/studio/server/stage.test.mjs b/packages/openfilm/studio/server/stage.test.mjsindex 0eecd63..be4c1f1 100644--- a/packages/openfilm/studio/server/stage.test.mjs+++ b/packages/openfilm/studio/server/stage.test.mjs@@ -77,6 +77,29 @@ test('a click on a page\'s backdrop (a box filling the page) takes the clip, not}});+test('a click on a title under a full-frame overlay (letterbox, vignette) takes the title; on nothing but the overlay, the clip', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-overlay-'));+ writeFileSync(join(dir, 'title.html'), `<!doctype html><body style="margin:0">+<h1 id="title" style="position:absolute;left:20px;top:60px;margin:0;font:700 24px sans-serif">On the road</h1>+<script>window.film={duration:2,frame(){}}</script></body>`);+ writeFileSync(join(dir, 'lens.html'), `<!doctype html><body style="margin:0">+<div id="vignette" style="position:absolute;inset:0;background:radial-gradient(ellipse at 50% 50%,transparent 55%,rgba(0,0,0,.45))"></div>+<div id="top" style="position:absolute;left:0;right:0;top:0;height:20px;background:#000"></div>+<script>window.film={duration:2,frame(){}}</script></body>`);+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'lens', src: 'lens.html' }] }, { clips: [{ id: 'title', src: 'title.html' }] }] }));+ const stage = await stageOf(dir);+ try {+ const title = await stage.ask('hit', { x: 50, y: 72, detail: true });+ assert.equal(title?.text?.value, 'On the road', 'through the overlay, the words under it');+ assert.equal(title?.clip, 'title');+ assert.equal((await stage.ask('hit', { x: 50, y: 72, from: title.handle, detail: true }))?.handle, title.handle, 'in hand, a click on it keeps it');+ assert.equal((await stage.ask('hit', { x: 150, y: 10, detail: true }))?.clip, 'lens', 'the overlay\'s own bar is its layer');+ assert.equal(await stage.ask('hit', { x: 250, y: 150, detail: true }), null, 'nothing but the overlay there: the clip is taken');+ } finally {+ await stage.close();+ }+});+test('a line typed in place starts with all of its words selected; a click on them moves the caret, though something unseen lies over them', { timeout: 60_000 }, async () => {const dir = mkdtempSync(join(tmpdir(), 'of-stage-select-'));writeFileSync(join(dir, 'title.html'), `<!doctype html><body style="margin:0">@@ -105,6 +128,32 @@ test('a line typed in place starts with all of its words selected; a click on th}});+test('a line typed in place tells the editor its words as they are typed, and kept at Enter', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-typing-'));+ writeFileSync(join(dir, 'title.html'), `<!doctype html><body style="margin:0">+<h1 id="title" style="position:absolute;left:20px;top:20px;margin:0;font:700 24px monospace">Every parcel</h1>+<script>window.film={duration:2,frame(){}}</script></body>`);+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'title', src: 'title.html' }] }] }));+ const stage = await stageOf(dir);+ try {+ await stage.page.evaluate(() => {+ window.heard = [];+ window.addEventListener('message', (e) => { if (e.data?.source === 'openfilm-film' && e.data.type === 'stage-event') window.heard.push(e.data); });+ });+ const title = await stage.ask('hit', { x: 40, y: 30, detail: true });+ assert.equal(await stage.ask('textStart', { handle: title.handle }), true);+ /* all of its words selected: the first key replaces them */+ for (const ch of 'Box') await stage.page.keyboard.type(ch);+ await stage.page.keyboard.press('Enter');+ await stage.page.waitForFunction(() => window.heard.some((e) => e.event === 'text'));+ const heard = await stage.page.evaluate(() => window.heard.map(({ event, handle, value, commit }) => ({ event, handle, value, commit })));+ assert.deepEqual(heard.filter((e) => e.event === 'typing').map((e) => [e.handle, e.value]), [[title.handle, 'B'], [title.handle, 'Bo'], [title.handle, 'Box']]);+ assert.deepEqual(heard.at(-1), { event: 'text', handle: title.handle, value: 'Box', commit: true });+ } finally {+ await stage.close();+ }+});+test('a click on words takes them, though a line drawn behind runs across its own box there', { timeout: 60_000 }, async () => {const dir = mkdtempSync(join(tmpdir(), 'of-stage-line-'));writeFileSync(join(dir, 'net.html'), `<!doctype html><body style="margin:0">diff --git a/packages/openfilm/studio/ui/src/App.tsx b/packages/openfilm/studio/ui/src/App.tsxindex f067787..0a1c8ab 100644--- a/packages/openfilm/studio/ui/src/App.tsx+++ b/packages/openfilm/studio/ui/src/App.tsx@@ -3,6 +3,10 @@* opened last, or (none left, or only ones whose folder is gone) shows the Projects window on its own, with "New* project" in it: no folder is made that the person did not ask for. The address is the state, so the agent's* `openfilm open` (which sends the page to a project) and the browser's back button both work.+ *+ * In an app with tabs (lib/host.ts `tabs`) this page is one project's tab: a project picked opens in its own tab (the+ * app's to open), `/` is the projects (the window with no tab open), and `openfilm open` is the app's to settle (every+ * tab hears it).*/import { useEffect, useState, useSyncExternalStore } from 'react';import { api, listen, studioConnection } from './api';@@ -10,8 +14,10 @@ import { useT } from './i18n';import { ProjectView } from './components/ProjectView';import { BrandLoadingScreen } from './components/BrandLoadingScreen';import { ProjectsPopover } from './components/ProjectsLibrary';+import { Launcher } from './components/Launcher';import { studioHost } from './lib/host';import { WhatsNew } from './components/WhatsNew';+import { sourcesApi } from './lib/project-sources';/*** `to` with this page's key in its address (the server puts it there): the address bar is what a person copies, and@@ -26,6 +32,8 @@ const keepKey = (to: string) => {};const projectIn = (path: string) => /^\/projects\/([\w-]+)/.exec(path)?.[1] ?? null;+/** the app's tabs, when Studio is a tab of an app's window */+const tabs = studioHost?.tabs ?? null;export function App() {const [path, setPath] = useState(location.pathname);@@ -34,19 +42,31 @@ export function App() {setPath(to);};+ /* the examples and skills, read as Studio opens: a gallery opened later shows them at once */+ useEffect(() => { sourcesApi.preload(); }, []);+useEffect(() => {const onPop = () => setPath(location.pathname);window.addEventListener('popstate', onPop);- /* `openfilm open` while this page is open: show the project it opened */- const stop = listen('events', (event) => { if (event.type === 'open') go(event.to); }, { watch: true });+ /* `openfilm open` while this page is open: show the project it opened (with tabs, the app says which tab does) */+ const stop = listen('events', (event) => {+ if (event.type !== 'open') return;+ if (tabs) tabs.openRequest(event.to); else go(event.to);+ }, { watch: true });return () => { window.removeEventListener('popstate', onPop); stop(); };}, []);+ /** Show a project: here, or (with tabs) in its own tab. */+ const open = (projectId: string) => { if (tabs) tabs.open(projectId); else go(`/projects/${projectId}`); };+ /** The project shown was deleted: its tab closes (with tabs), or back to the last project. */+ const leave = () => { if (tabs) tabs.report({ gone: true }); else go('/', true); };+const id = projectIn(path);- /* no project in the address: the one opened last that is still there, else the Projects window (`none`) */+ /* no project in the address: the one opened last that is still there, else the Projects window (`none`); with+ tabs, the projects (no tab is open) */const [none, setNone] = useState(false);useEffect(() => {- if (id) return;+ if (id || tabs) return;let alive = true;void api.projects().then((projects) => {if (!alive) return;@@ -57,7 +77,8 @@ export function App() {return () => { alive = false; setNone(false); };}, [id]);- const page = id ? <ProjectView key={id} projectId={id} onProject={(next) => go(`/projects/${next}`)} onLeave={() => go('/', true)} />+ const page = id ? <ProjectView key={id} projectId={id} onProject={open} onLeave={leave} />+ : tabs ? <Launcher onOpen={open} />: !none ? <BrandLoadingScreen labelKey="projects.opening" />: (<div className="workspace-shell bg-[var(--dock-shell)]">diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.tsindex 478b19c..0df6c24 100644--- a/packages/openfilm/studio/ui/src/api.ts+++ b/packages/openfilm/studio/ui/src/api.ts@@ -7,7 +7,9 @@ import { watchStudioVersion } from '@/lib/studio-version';/** `working`: an agent of the app's chat is working in it right now (it cannot be deleted meanwhile). *//** GET /api/version: this Studio's, and npm's latest (null when never learnt; `checking` false: never asked). */-export interface StudioVersion { version: string; latest: string | null; newer: boolean; checkedAt: number | null; checking: boolean; source: boolean }+export interface StudioVersion { version: string; latest: string | null; newer: boolean; checkedAt: number | null; checking: boolean; source: boolean;+ /** the update Studio runs from the top bar (lib/web-update), or one that failed */+ update?: { status: 'updating' | 'failed'; version: string; error?: string } }export type Project = { id: string; path: string; name: string; openedAt: number; missing: boolean; working?: boolean };export type Clip = { src: string; id: string; at?: number; time?: [number] | [number, number];@@ -75,16 +77,25 @@ 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 }; seenVersion: string | null }+export interface StudioPrefs { proxies: { on: boolean; height: 540 | 720 | 1080 }; seenVersion: string | null; projectsFolder: string | null }+/** Where new projects and exports go (src/locations.mjs): the folder, its default, whether the person chose it, the free space on its disk. */+export interface StudioLocation { path: string; default: string; chosen: boolean; free: number | null }+export interface StudioLocations { projects: StudioLocation }/** Said on the window when they change, for what plays by them (the preview's proxies). */export const PREFS_EVENT = 'openfilm:prefs';export const api = {/** this Studio's version and the latest openfilm on npm; `check`: ask npm now */version: (check = false) => call<StudioVersion>(`version${check ? '?check=1' : ''}`),+ /** the newest openfilm, run in the background (`openfilm update`): Studio starts again on it; refused (ApiError, `body.code`) while busy */+ update: () => call<{ update: NonNullable<StudioVersion['update']> }>('update', { method: 'POST', json: {} }),projects: () => call<{ projects: Project[] }>('projects').then((r) => r.projects),prefs: () => call<StudioPrefs>('prefs'),- setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {+ /** where new projects and exports go, and the free space there */+ locations: () => call<StudioLocations>('locations'),+ /** one of them in the system's file manager */+ openLocation: (which: keyof StudioLocations) => call<{ ok: true }>(`locations/${which}`, { method: 'POST', json: {} }),+ setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string; projectsFolder?: string | null }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {window.dispatchEvent(new Event(PREFS_EVENT));return prefs;}),@@ -119,8 +130,24 @@ export const api = {answerAsk: (askId: string, allow: boolean) => call<{ answered: boolean }>(`get/asks/${encodeURIComponent(askId)}`, { method: 'POST', json: { allow } }),/** the provider's own page for its balance, opened in the person's browser */openBilling: (providerId: string) => call<Record<string, never>>(`providers/${encodeURIComponent(providerId)}/billing`, { method: 'POST' }),+ /** clips (by id), clips together (a group) and files (by path) of a project put in Saved (studio/server/saved.mjs):+ each one's place there */+ save: (id: string, what: { clips?: SavedAsk[]; groups?: Array<SavedAsk & { ids: string[] }>; files?: Array<SavedAsk & { path: string }>; into?: string }) => (+ call<{ paths: string[] }>(`${p(id)}/saved`, { method: 'POST', json: what }).then((r) => r.paths)+ ),+ /** a thing of Saved (its `saved/` path) used in the project: a file imported (its place), or a bundle's files brought in+ and the clip, a group's clips or the page to put on the timeline */+ takeSaved: (id: string, path: string) => call<{ clip: Record<string, unknown> & { src: string } } | { clips: SavedGroupClip[] } | { path: string }>(+ `${p(id)}/saved/take`, { method: 'POST', json: { path } },+ ),};+/** A clip of a saved group: its track counted from the group's top one, its time in seconds from the group's start. */+export type SavedGroupClip = { track: number; at: number; clip: Record<string, unknown> & { src: string } };++/** What is said of a thing put in Saved: a clip's id (a file's path beside it), a name, and how long and big it is. */+export type SavedAsk = { id?: string; name?: string; durationMs?: number; w?: number; h?: number };+/** What an agent's `openfilm get` asks the person before it spends (studio/server/get.mjs). */export type SpendAsk = {id: string; kind: 'video'; provider: string; model?: string; seconds?: number; prompt?: string;diff --git a/packages/openfilm/studio/ui/src/components/AudioMeters.tsx b/packages/openfilm/studio/ui/src/components/AudioMeters.tsxindex 82a4f65..8381b13 100644--- a/packages/openfilm/studio/ui/src/components/AudioMeters.tsx+++ b/packages/openfilm/studio/ui/src/components/AudioMeters.tsx@@ -13,6 +13,7 @@ import {channelLevel, fallTo, formatDb, holdPeak, meterPosition, METER_FLOOR_DB, METER_MARKS, type HeldPeak,} from '@/lib/audio-levels';import type { MixSamples } from '@/editor/player';+import { useThemeChanges } from '@/lib/theme-changes';/** How wide the meters are, px: two bars and their scale. */export const METERS_W = 44;@@ -108,7 +109,10 @@ export function AudioMeters({ levels, playing }: {});}, [size]);- React.useEffect(() => { draw(); }, [draw]);+ /* its colors are the theme's, read as it draws: when the theme changes it draws again, or it would keep the old+ theme's bars until the film plays */+ const theme = useThemeChanges();+ React.useEffect(() => { draw(); }, [draw, theme]);/* while playing (and while the bars fall back after), once a frame; nothing otherwise */React.useEffect(() => {diff --git a/packages/openfilm/studio/ui/src/components/BlockThumbs.tsx b/packages/openfilm/studio/ui/src/components/BlockThumbs.tsxindex ace3534..481bcdd 100644--- a/packages/openfilm/studio/ui/src/components/BlockThumbs.tsx+++ b/packages/openfilm/studio/ui/src/components/BlockThumbs.tsx@@ -1,6 +1,7 @@import * as React from 'react';import { THUMB_CELL_PX } from '@/lib/thumb-cache';+import { thumbCellStyle } from '@/lib/thumb-cell';import { pickShot } from '@/lib/thumb-pick';import { retryImage } from '@/lib/retry-image';@@ -71,7 +72,7 @@ export function BlockThumbs({alt=""draggable={false}className="absolute top-0 object-cover"- style={{ left: cell.left, width: thumbWidthPx, height, opacity: 0.9 }}+ style={thumbCellStyle(cell.left, thumbWidthPx, height)}/* a picture that fails is hidden (the clip color shows), better than a broken-image icon, and asked foragain a little later; it comes back when it loads */onError={(e) => { e.currentTarget.style.visibility = 'hidden'; retryImage(e.currentTarget); }}diff --git a/packages/openfilm/studio/ui/src/components/BlockWaveform.tsx b/packages/openfilm/studio/ui/src/components/BlockWaveform.tsxindex 1f9c390..dbe1515 100644--- a/packages/openfilm/studio/ui/src/components/BlockWaveform.tsx+++ b/packages/openfilm/studio/ui/src/components/BlockWaveform.tsx@@ -12,6 +12,7 @@import * as React from 'react';import { normalizeWavePeaks, waveformColumns } from '@/lib/waveform-columns';import { mediaFetch } from '@/lib/media-queue';+import { useThemeChanges } from '@/lib/theme-changes';/** A sound's envelope: the whole file's peaks and its length (to turn peak indexes into ms). */interface Wave {@@ -103,6 +104,8 @@ export function BlockWaveform({return () => { alive = false; };}, [url]);+ /* its color is read as it draws: a theme changed, it draws again */+ const theme = useThemeChanges();const from = Math.max(0, Math.min(width, Math.floor(visiblePx?.from ?? 0)));const to = Math.max(from, Math.min(width, Math.ceil(visiblePx?.to ?? width)));const sliceW = to - from;@@ -139,7 +142,7 @@ export function BlockWaveform({ctx.fill();});return () => cancelAnimationFrame(frame);- }, [wave, width, height, color, inMs, durMs, from, sliceW]);+ }, [wave, width, height, color, inMs, durMs, from, sliceW, theme]);if (!wave?.peaks.length || sliceW <= 0) return null;return (diff --git a/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsx b/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsxnew file mode 100644index 0000000..e486e94--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsx@@ -0,0 +1,586 @@+/**+ * The examples (films made with OpenFilm) and the skills, to start from or to learn from. One view, two places:+ *+ * · start the projects window's "Examples": the examples only; one is started from (copied into a new project)+ * · reference the Community, over a film, from the app's chat (lib/host.ts `onCommand` `show-examples`): two views+ * switched in its title row, Skills first (one is named in the message being written; one of the+ * person's own added), then Examples (one, or a part of it, a segment or a stretch dragged on its strip,+ * is pointed at in the message; starting from one is still there)+ *+ * Examples: the first wide, the others in a grid. Skills: the person's own first, then this project's, then OpenFilm's+ * by kind (ways of working, then looks, each in its openfilm.json `order`), narrowed by a row of filters that stays at+ * the top, beside adding one. Example cards are posters that play their preview under the pointer; skills show their+ * own title and summary (openfilm.json, in the language shown) rather than the words written for the agent. One opened+ * is a page of two columns: its picture or preview on the left, what it is and what to do with it on the right. The+ * title row is the projects window's own, so switching views moves nothing. Esc goes back from a page, else closes.+ */+import React from 'react';+import { createPortal } from 'react-dom';+import {+ ArrowLeft, Check, Clapperboard, Copy, ExternalLink, Film, Folder, GitBranch, Info, Layers, MonitorPlay, Music, PenLine,+ PictureInPicture2, Play, Plus, Presentation, Scissors, Search, Shapes, Sparkles, Wand2, X, Github, type LucideIcon,+} from 'lucide-react';+import { useLanguage, useT } from '@/i18n';+import { studioHost, type CommunityItem } from '@/lib/host';+import { seenExamples, seenSkills, sourcesApi, type Example, type SkillEntry } from '@/lib/project-sources';+import { GitHubDialog } from './ProjectSources';++export type ExamplesMode = 'start' | 'reference';+/** A part of an example picked to point at: none for the whole film. */+export type ExamplePart = { from: number; to: number; segment?: string } | null;++type Opened = { kind: 'example'; example: Example } | { kind: 'skill'; skill: SkillEntry };++/** The skills' filters: all of them, or one group. */+type SkillGroup = 'mine' | 'project' | 'workflow' | 'style';+type SkillFilter = 'all' | SkillGroup;++const byOrder = (a: SkillEntry, b: SkillEntry) => (a.order ?? 999) - (b.order ?? 999) || a.name.localeCompare(b.name);++const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;+/** words in the language shown, else its family's, else English, else any */+const inLanguage = (words: Record<string, string> | undefined, lang: string) =>+ (words ? words[lang] ?? words[lang.split('-')[0]!] ?? words.en ?? Object.values(words)[0] : undefined);++/** A skill as people see it: its title and summary in the language shown, else its name and the agent's description. */+function useSkillWords() {+ const lang = useLanguage();+ return (skill: SkillEntry) => ({+ title: inLanguage(skill.shown?.title, lang) ?? skill.name,+ summary: inLanguage(skill.shown?.summary, lang) ?? skill.description,+ });+}++/** Two titles in the title row, the one shown bright (the projects window's switch is the same). */+export function TitleSwitch<T extends string>({ items, value, onChange }: { items: Array<{ id: T; label: string }>; value: T; onChange: (id: T) => void }) {+ return (+ <div role="tablist" className="mr-auto flex items-baseline gap-5">+ {items.map((item) => (+ <button key={item.id} type="button" role="tab" aria-selected={value === item.id} onClick={() => onChange(item.id)}+ className={`text-[17px] font-semibold tracking-[-0.01em] transition ${value === item.id ? 'text-[var(--text)]' : 'text-[var(--text-faint)] hover:text-[var(--text-muted)]'}`}>+ {item.label}+ </button>+ ))}+ </div>+ );+}++export function ExamplesGallery({ mode, projectId = null, heading, initial, onClose, onStart, onReference, onUseSkill }: {+ mode: ExamplesMode;+ /** open on this skill's or example's page (a pill of one clicked in the chat) */+ initial?: CommunityItem;+ /** the project shown, for its own skills */+ projectId?: string | null;+ /** the title row's left (the projects window's switch); none: the Community's own (Skill, Examples) */+ heading?: React.ReactNode;+ onClose?: () => void;+ onStart: (example: Example) => void;+ onReference?: (example: Example, part: ExamplePart) => void;+ onUseSkill?: (skill: SkillEntry) => void;+}) {+ const t = useT();+ /* the Community (over a film) opens on its skills; the projects window shows the examples only */+ const community = mode === 'reference';+ const [view, setView] = React.useState<'skills' | 'examples'>(community ? 'skills' : 'examples');+ /* what was read before shows at once; what is read now replaces it */+ const [examples, setExamples] = React.useState<Example[] | null>(() => seenExamples());+ const [skills, setSkills] = React.useState<SkillEntry[]>(() => seenSkills(projectId) ?? []);+ const [opened, setOpened] = React.useState<Opened | null>(null);+ /* opening on one item: once what it is in has been read */+ const pending = React.useRef(initial);+ React.useEffect(() => {+ const want = pending.current;+ if (!want) return;+ if (want.kind === 'skill') {+ const skill = skills.find((k) => k.name === want.name);+ if (skill) { pending.current = undefined; setView('skills'); setOpened({ kind: 'skill', skill }); }+ } else if (examples) {+ pending.current = undefined;+ const example = examples.find((e) => e.id === want.id);+ setView('examples');+ if (example) setOpened({ kind: 'example', example });+ }+ }, [skills, examples]);+ const [filter, setFilter] = React.useState<SkillFilter>('all');++ React.useEffect(() => {+ let alive = true;+ void sourcesApi.examples().then((list) => { if (alive) setExamples(list); });+ if (community) void sourcesApi.skills(projectId).then((list) => { if (alive) setSkills(list); });+ return () => { alive = false; };+ }, [projectId, community]);++ React.useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== 'Escape' || e.defaultPrevented) return;+ if (opened) { e.preventDefault(); e.stopPropagation(); setOpened(null); } else if (onClose) { e.preventDefault(); onClose(); }+ };+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ }, [opened, onClose]);++ const kindLabel = (c: string) => { const key = `gallery.cat.${c}`; const label = t(key); return label === key ? c : label; };+ const show = (next: 'skills' | 'examples') => { setView(next); setOpened(null); };++ let body: React.ReactNode;+ if (opened?.kind === 'example') {+ body = <ExampleDetail example={opened.example} mode={mode} onStart={onStart} onReference={onReference} categoryLabel={kindLabel} />;+ } else if (opened?.kind === 'skill') {+ body = <SkillDetail skill={opened.skill} mode={mode} onUse={onUseSkill} />;+ } else if (view === 'skills') {+ const official = skills.filter((k) => k.source === 'official').sort(byOrder);+ const groups: Array<{ id: SkillGroup; items: SkillEntry[] }> = [+ { id: 'workflow', items: official.filter((k) => k.kind !== 'style') },+ { id: 'style', items: official.filter((k) => k.kind === 'style') },+ { id: 'project', items: skills.filter((k) => k.source === 'project').sort(byOrder) },+ { id: 'mine', items: skills.filter((k) => k.source === 'mine').sort(byOrder) },+ ].filter((g) => g.id !== 'project' || g.items.length) as Array<{ id: SkillGroup; items: SkillEntry[] }>;+ body = <SkillsView groups={groups} filter={filter === 'all' || groups.some((g) => g.id === filter) ? filter : 'all'} onFilter={setFilter} onOpen={(k) => setOpened({ kind: 'skill', skill: k })} />;+ } else if (examples == null) {+ body = <Empty text={t('gallery.loading')} />;+ } else if (!examples.length) {+ body = <Empty text={t('gallery.empty')} />;+ } else {+ /* the first wide, the others in a grid */+ const [hero, ...rest] = examples;+ body = (+ <Body note={community ? t('gallery.referenceNote') : t('gallery.discoverNote')}>+ <Hero example={hero!} mode={mode} onOpen={() => setOpened({ kind: 'example', example: hero! })} onStart={() => onStart(hero!)} />+ {rest.length ? (+ <div className="mt-8">+ <Grid>{rest.map((e) => <ExampleCard key={e.id} example={e} label={e.category ? kindLabel(e.category) : null} onOpen={() => setOpened({ kind: 'example', example: e })} />)}</Grid>+ </div>+ ) : null}+ </Body>+ );+ }++ return (+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ {/* the same row as the projects' (ProjectsView): switching between them moves nothing */}+ <header className="flex shrink-0 flex-col px-6 pb-4 pt-5">+ <div className="flex min-h-8 items-center gap-1">+ {/* an opened one has its way back here, where the switch was */}+ {opened ? (+ <button type="button" onClick={() => setOpened(null)} className="mr-auto flex h-8 items-center gap-1.5 rounded-lg pl-1 pr-2.5 text-[13.5px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">+ <ArrowLeft size={16} strokeWidth={1.75} />{t('gallery.back')}+ </button>+ ) : heading ?? <TitleSwitch items={[{ id: 'skills' as const, label: t('gallery.skills') }, { id: 'examples' as const, label: t('gallery.title') }]} value={view} onChange={show} />}+ {onClose ? (+ <button type="button" onClick={onClose} aria-label={t('project.close')}+ className="ml-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">+ <X size={16} strokeWidth={1.75} />+ </button>+ ) : null}+ </div>+ </header>+ <div className="min-h-0 min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">{body}</div>+ </div>+ );+}++/** A view's content: a line saying what it is, then its sections. */+function Body({ note, children }: { note?: string; children: React.ReactNode }) {+ return (+ <div className="px-6 pb-10">+ {note ? <p className="mb-5 text-[12.5px] text-[var(--text-muted)]">{note}</p> : null}+ {children}+ </div>+ );+}++const GROUP_LABEL: Record<SkillGroup, string> = { mine: 'gallery.mine', project: 'gallery.project', workflow: 'gallery.workflow', style: 'gallery.style' };++/**+ * The skills: filters on the left (all of OpenFilm's, its workflows, its looks; this project's; the person's own),+ * adding one and a search on the right, all in a row that stays at the top; then the cards. "All" shows OpenFilm's+ * under their kinds; the person's own are their own filter. What skills are for is a note behind the (i).+ */+function SkillsView({ groups, filter, onFilter, onOpen }: {+ groups: Array<{ id: SkillGroup; items: SkillEntry[] }>; filter: SkillFilter; onFilter: (f: SkillFilter) => void; onOpen: (k: SkillEntry) => void;+}) {+ const t = useT();+ const words = useSkillWords();+ const [query, setQuery] = React.useState('');+ const q = query.trim().toLowerCase();+ const matches = (k: SkillEntry) => !q || [words(k).title, words(k).summary, k.name].some((w) => w?.toLowerCase().includes(q));+ const shown = (filter === 'all' ? groups.filter((g) => g.id === 'workflow' || g.id === 'style') : groups.filter((g) => g.id === filter))+ .map((g) => ({ ...g, items: g.items.filter(matches) }));+ const chip = (id: SkillFilter, label: string, count?: number) => (+ <button key={id} type="button" role="tab" aria-selected={filter === id} onClick={() => onFilter(id)}+ className={`flex h-8 shrink-0 items-center gap-1.5 rounded-[8px] px-3 text-[13px] transition ${filter === id ? 'bg-[var(--bg-hover)] font-medium text-[var(--text)]' : 'text-[var(--text-muted)] hover:text-[var(--text)]'}`}>+ {label}{count ? <span className="text-[var(--text-faint)]">{count}</span> : null}+ </button>+ );+ const own = groups.filter((g) => g.id === 'project' || g.id === 'mine');+ return (+ <div className="pb-10">+ <div className="sticky top-0 z-[1] flex items-center gap-1 bg-[var(--app-content-bg)] px-6 pb-4">+ <div role="tablist" className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">+ {chip('all', t('gallery.all'))}+ {chip('workflow', t('gallery.workflow'))}+ {chip('style', t('gallery.style'))}+ <span className="mx-2 h-4 w-px shrink-0 bg-[var(--border-strong)]" />+ {own.map((g) => chip(g.id, t(GROUP_LABEL[g.id]), g.items.length))}+ <AboutSkills />+ </div>+ {studioHost?.skills ? (+ <button type="button" onClick={() => studioHost?.skills?.add()}+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-[9px] border border-[var(--border)] px-3 text-[13px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]"><Plus size={14} />{t('gallery.addSkill')}</button>+ ) : null}+ <label className="ml-2 flex h-9 w-[260px] shrink-0 items-center gap-2 rounded-[9px] bg-[var(--surface-2)] px-3 text-[var(--text-faint)] ring-1 ring-[var(--border)] focus-within:ring-[var(--border-strong)]">+ <Search size={14} strokeWidth={1.75} />+ <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('gallery.search')}+ className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]" />+ {query ? <button type="button" aria-label={t('project.close')} onClick={() => setQuery('')} className="hover:text-[var(--text)]"><X size={13} /></button> : null}+ </label>+ </div>+ <div className="px-6">+ {shown.map((g, i) => (+ <section key={g.id} className={i ? 'mt-10' : ''}>+ {filter === 'all' && g.items.length ? <h3 className="mb-4 text-[15px] font-semibold text-[var(--text)]">{t(GROUP_LABEL[g.id])}</h3> : null}+ {g.items.length ? <Grid>{g.items.map((k) => <SkillCard key={`${k.source}:${k.name}`} skill={k} onOpen={() => onOpen(k)} />)}</Grid>+ : q ? <Empty text={t('gallery.noMatch')} /> : g.id === 'mine' ? <NoSkills /> : null}+ </section>+ ))}+ </div>+ </div>+ );+}++/** What skills are for, behind an (i) at the end of the filters: shown while the pointer or focus is on it. */+function AboutSkills() {+ const t = useT();+ const [open, setOpen] = React.useState(false);+ return (+ <span className="relative ml-1 flex shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>+ <button type="button" aria-label={t('gallery.aboutSkills')} aria-expanded={open} onFocus={() => setOpen(true)} onBlur={() => setOpen(false)}+ className="flex h-8 w-8 items-center justify-center rounded-[8px] text-[var(--text-faint)] transition hover:text-[var(--text)]">+ <Info size={15} strokeWidth={1.75} />+ </button>+ {open ? (+ <span role="tooltip" className="fixed z-[10060] mt-9 w-[400px] whitespace-pre-line rounded-[10px] border border-[var(--border-strong)] bg-[var(--dock-pane)] px-4 py-3.5 text-[12.5px] leading-[20px] text-[var(--text-muted)] shadow-[0_12px_32px_rgba(0,0,0,0.35)]">+ {t('gallery.skillKinds')}+ </span>+ ) : null}+ </span>+ );+}++/** None of the person's skills yet: what theirs are for, and how to get one. */+function NoSkills() {+ const t = useT();+ return (+ <div className="flex flex-col items-center rounded-[12px] border border-dashed border-[var(--border-strong)] px-6 py-12 text-center">+ <Sparkles size={22} strokeWidth={1.5} className="text-[var(--text-faint)]" />+ <p className="mt-3 max-w-[520px] text-[13px] leading-[20px] text-[var(--text-muted)]">{t('gallery.noSkills')}</p>+ {studioHost?.skills ? (+ <button type="button" onClick={() => studioHost?.skills?.add()}+ className="mt-4 flex h-9 items-center gap-1.5 rounded-[9px] border border-[var(--border)] px-3.5 text-[13px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]"><Plus size={14} />{t('gallery.addSkill')}</button>+ ) : null}+ </div>+ );+}++/** Where one of the person's skills came from, as a short line: GitHub · owner/repo, a folder's name, or made here. */+function Origin({ skill }: { skill: SkillEntry }) {+ const t = useT();+ const o = skill.origin;+ if (!o) return null;+ let icon = <Wand2 size={12} />, text = t('gallery.made');+ if (o.from === 'link') {+ icon = <GitBranch size={12} />;+ try { const u = new URL(o.address); text = `${u.hostname.replace(/^www\./, '').replace(/\.com$/, '').replace(/^github$/, 'GitHub').replace(/^gitlab$/, 'GitLab')} · ${u.pathname.split('/').filter(Boolean).slice(0, 2).join('/')}`; } catch { text = o.address; }+ } else if (o.from === 'folder') {+ icon = <Folder size={12} />;+ text = `${t('gallery.fromFolder')} · ${o.address.split(/[\\/]/).filter(Boolean).pop() ?? o.address}`;+ }+ return <div title={o.from === 'made' ? undefined : o.address} className="mt-2 flex min-w-0 items-center gap-1.5 text-[11.5px] text-[var(--text-faint)]">{icon}<span className="truncate">{text}</span></div>;+}++function Empty({ text }: { text: string }) {+ return <p className="py-14 text-center text-[13px] text-[var(--text-muted)]">{text}</p>;+}++function Grid({ children }: { children: React.ReactNode }) {+ return <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-x-6 gap-y-8">{children}</div>;+}++/** A poster that plays the preview while the pointer is on it; a clapperboard when there is neither. */+function Picture({ example, playing, fit = 'cover' }: { example: Example; playing: boolean; fit?: 'cover' | 'contain' }) {+ const [failed, setFailed] = React.useState(false);+ const fitClass = fit === 'contain' ? 'object-contain' : 'object-cover';+ return (+ <>+ {example.poster && !failed ? <img src={example.poster} alt="" loading="lazy" draggable={false} onError={() => setFailed(true)} className={`absolute inset-0 h-full w-full ${fitClass}`} />+ : <span className="absolute inset-0 flex items-center justify-center bg-[linear-gradient(135deg,var(--surface-2),var(--surface-3))] text-[var(--text-faint)]"><Clapperboard size={24} strokeWidth={1.5} /></span>}+ {playing && example.video ? <video src={example.video} autoPlay muted loop playsInline className={`absolute inset-0 h-full w-full ${fitClass}`} /> : null}+ </>+ );+}++/** The first example, wide: its preview under the pointer, its title over it, and how to start from it. */+function Hero({ example, mode, onOpen, onStart }: { example: Example; mode: ExamplesMode; onOpen: () => void; onStart: () => void }) {+ const t = useT();+ const [hover, setHover] = React.useState(false);+ return (+ <div role="button" tabIndex={0} onClick={onOpen} onKeyDown={(e) => { if (e.key === 'Enter') onOpen(); }}+ onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}+ className="relative block aspect-[2.2/1] w-full cursor-pointer overflow-hidden rounded-[14px] bg-black outline-none ring-1 ring-[var(--border)] transition hover:ring-[var(--border-strong)] focus-visible:ring-2 focus-visible:ring-[var(--text-muted)]">+ <Picture example={example} playing={hover} />+ <div className="absolute inset-0 bg-[linear-gradient(to_top,rgba(0,0,0,0.8)_0%,rgba(0,0,0,0.3)_45%,rgba(0,0,0,0)_75%)]" />+ <div className="absolute inset-x-0 bottom-0 flex items-end gap-6 p-6">+ <div className="min-w-0 flex-1">+ <div className="text-[22px] font-semibold leading-tight tracking-[-0.015em] text-white">{example.title}</div>+ {example.description ? <div className="mt-1.5 line-clamp-2 max-w-[520px] text-[13px] leading-[19px] text-white/80">{example.description}</div> : null}+ {example.duration ? <div className="mt-1.5 text-[12px] text-white/55">{clock(example.duration)}</div> : null}+ </div>+ <button type="button" onClick={(e) => { e.stopPropagation(); if (mode === 'reference') onOpen(); else onStart(); }}+ className="shrink-0 rounded-[10px] bg-white px-4 py-2.5 text-[13px] font-medium text-black transition hover:bg-white/90">+ {mode === 'reference' ? t('gallery.reference') : t('gallery.start')}+ </button>+ </div>+ </div>+ );+}++function ExampleCard({ example, label, onOpen }: { example: Example; label: string | null; onOpen: () => void }) {+ const [hover, setHover] = React.useState(false);+ return (+ <button type="button" onClick={onOpen} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} className="group flex min-w-0 flex-col text-left outline-none">+ <div className="relative aspect-video w-full overflow-hidden rounded-[10px] bg-[var(--surface-2)] ring-1 ring-[var(--border)] transition group-hover:ring-[var(--border-strong)] group-focus-visible:ring-2 group-focus-visible:ring-[var(--text-muted)]">+ <Picture example={example} playing={hover} />+ {example.duration ? <span className="absolute bottom-2 right-2 rounded bg-black/60 px-1.5 py-[1px] font-mono text-[10.5px] text-white">{clock(example.duration)}</span> : null}+ </div>+ <div className="mt-2.5 flex items-baseline gap-2">+ <span className="min-w-0 flex-1 truncate text-[13.5px] font-medium text-[var(--text)]">{example.title}</span>+ {label ? <span className="shrink-0 text-[11.5px] text-[var(--text-faint)]">{label}</span> : null}+ </div>+ {example.description ? <div className="mt-0.5 line-clamp-2 text-[12px] leading-[17px] text-[var(--text-muted)]">{example.description}</div> : null}+ </button>+ );+}++const ICONS: Record<string, LucideIcon> = {+ copy: Copy, scissors: Scissors, monitor: MonitorPlay, shapes: Shapes, pip: PictureInPicture2, pen: PenLine, film: Film,+ music: Music, presentation: Presentation, layers: Layers,+};+/** each mark its own color, so the covers tell apart at a glance */+const HUES: Record<string, number> = { copy: 212, scissors: 18, monitor: 188, shapes: 262, pip: 328, pen: 42, film: 28, music: 286, presentation: 228, layers: 6 };++/** A skill's picture: its cover, else its preview's first frame, else a tile of its mark and title in its own color. */+function SkillCover({ skill, title, big = false, playing = false }: { skill: SkillEntry; title: string; big?: boolean; playing?: boolean }) {+ const [failed, setFailed] = React.useState(false);+ if (skill.cover && !failed) {+ return (+ <>+ <img src={skill.cover} alt="" loading="lazy" draggable={false} onError={() => setFailed(true)} className="absolute inset-0 h-full w-full object-cover" />+ {playing && skill.preview ? <video src={skill.preview} autoPlay muted loop playsInline className="absolute inset-0 h-full w-full object-cover" /> : null}+ </>+ );+ }+ const Mark = ICONS[skill.icon ?? ''] ?? Sparkles;+ const hue = HUES[skill.icon ?? ''] ?? 220;+ return (+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 px-6 text-center"+ style={{ background: `radial-gradient(110% 90% at 25% 0%, hsl(${hue} 70% 55% / 0.22), transparent 62%), radial-gradient(90% 80% at 100% 100%, hsl(${hue} 70% 50% / 0.12), transparent 60%), var(--surface-2)` }}>+ <span className={`flex items-center justify-center rounded-[14px] ${big ? 'h-16 w-16' : 'h-14 w-14'}`}+ style={{ background: `hsl(${hue} 70% 55% / 0.16)`, color: `hsl(${hue} 80% 72%)`, boxShadow: `0 0 0 1px hsl(${hue} 70% 60% / 0.28)` }}>+ <Mark size={big ? 28 : 24} strokeWidth={1.6} />+ </span>+ {/* a card has its title under it; the page's big picture carries it */}+ {big ? <span className="line-clamp-2 text-[22px] font-semibold tracking-[-0.01em] text-[var(--text)]">{title}</span> : null}+ </div>+ );+}++function SkillCard({ skill, onOpen }: { skill: SkillEntry; onOpen: () => void }) {+ const words = useSkillWords()(skill);+ const [hover, setHover] = React.useState(false);+ return (+ <button type="button" onClick={onOpen} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} className="group flex min-w-0 flex-col text-left outline-none">+ <div className="relative aspect-video w-full overflow-hidden rounded-[12px] ring-1 ring-[var(--border)] transition group-hover:ring-[var(--border-strong)] group-focus-visible:ring-2 group-focus-visible:ring-[var(--text-muted)]">+ <SkillCover skill={skill} title={words.title} playing={hover} />+ </div>+ <div className="mt-3 truncate text-[14.5px] font-semibold tracking-[-0.005em] text-[var(--text)]">{words.title}</div>+ {words.summary ? <div className="mt-1 line-clamp-2 text-[12.5px] leading-[18px] text-[var(--text-muted)]">{words.summary}</div> : null}+ <Origin skill={skill} />+ </button>+ );+}++/**+ * A skill on its own: its preview (or picture) large on the left; on the right its title, kind and version, who it is+ * for and what it does, what the agent reads, and using it, at the bottom.+ */+function SkillDetail({ skill, mode, onUse }: { skill: SkillEntry; mode: ExamplesMode; onUse?: (skill: SkillEntry) => void }) {+ const t = useT();+ const lang = useLanguage();+ const words = useSkillWords()(skill);+ const details = inLanguage(skill.shown?.details, lang);+ const group: SkillGroup = skill.source === 'official' ? (skill.kind === 'style' ? 'style' : 'workflow') : skill.source;+ const source = skill.repository ?? (skill.origin?.from === 'link' ? skill.origin.address : undefined);+ return (+ <div className="grid h-full min-h-0 grid-cols-[minmax(0,1.65fr)_minmax(320px,1fr)] border-t border-[var(--border)]">+ <div className="flex min-h-0 items-center justify-center bg-[color-mix(in_srgb,var(--bg)_55%,transparent)] p-8">+ <div className="relative aspect-video w-full overflow-hidden rounded-[12px] bg-black ring-1 ring-[var(--border)]">+ {skill.preview ? <video src={skill.preview} poster={skill.cover} autoPlay muted loop controls playsInline className="absolute inset-0 h-full w-full object-contain" />+ : <SkillCover skill={skill} title={words.title} big />}+ </div>+ </div>+ <div className="flex min-h-0 flex-col border-l border-[var(--border)]">+ <div className="min-h-0 flex-1 overflow-y-auto px-7 pt-7">+ <h2 className="text-[22px] font-semibold leading-tight tracking-[-0.015em] text-[var(--text)]">{words.title}</h2>+ <div className="mt-2.5 flex items-center gap-2 text-[12px] text-[var(--text-muted)]">+ <span>{t(GROUP_LABEL[group])}</span>+ {skill.version ? <span className="rounded-[5px] border border-[var(--border)] px-1.5 py-[1px] font-mono text-[10.5px] text-[var(--text-dim)]">v{skill.version}</span> : null}+ {/* its source: OpenFilm's repository, or the address one of the person's came from */}+ {source ? (+ <a href={source} target="_blank" rel="noreferrer" title={source} aria-label={t('gallery.viewSource')}+ className="flex h-6 w-6 items-center justify-center rounded-[6px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"><Github size={14} strokeWidth={1.75} /></a>+ ) : null}+ </div>+ <Origin skill={skill} />+ {words.summary ? <p className="mt-5 text-[14px] leading-[22px] text-[var(--text)]">{words.summary}</p> : null}+ {details ? details.split('\n').map((line) => <p key={line} className="mt-3 text-[13.5px] leading-[22px] text-[var(--text-muted)]">{line}</p>) : null}+ </div>+ <div className="shrink-0 px-7 pb-7 pt-4">+ {mode === 'reference' && onUse ? (+ <button type="button" onClick={() => onUse(skill)}+ className="flex h-11 w-full items-center justify-center gap-1.5 rounded-[10px] bg-[var(--text)] text-[14px] font-medium text-[var(--bg)] transition hover:opacity-90"><Check size={15} />{t('gallery.useSkill')}</button>+ ) : null}+ </div>+ </div>+ </div>+ );+}++/**+ * An example on its own: its preview with sound, its parts on a strip (one picked by a click, a stretch by dragging+ * across them; none: the whole film), and what to do with it.+ */+function ExampleDetail({ example, mode, onStart, onReference, categoryLabel }: {+ example: Example; mode: ExamplesMode; onStart: (example: Example) => void;+ onReference?: (example: Example, part: ExamplePart) => void; categoryLabel: (c: string) => string;+}) {+ const t = useT();+ const video = React.useRef<HTMLVideoElement>(null);+ const [part, setPart] = React.useState<ExamplePart>(null);+ const duration = example.duration ?? example.segments.at(-1)?.to ?? 0;+ const [drag, setDrag] = React.useState<number | null>(null);+ const strip = React.useRef<HTMLDivElement>(null);+ const timeAt = (clientX: number) => {+ const box = strip.current?.getBoundingClientRect();+ return box && duration ? Math.max(0, Math.min(duration, ((clientX - box.left) / box.width) * duration)) : 0;+ };+ const seek = (s: number) => { if (video.current) { video.current.currentTime = s; void video.current.play().catch(() => {}); } };+ const pick = (next: ExamplePart) => { setPart(next); if (next) seek(next.from); };+ const primary = mode === 'reference' && onReference+ ? { label: part ? t('gallery.referencePart') : t('gallery.reference'), run: () => onReference(example, part) }+ : { label: t('gallery.start'), run: () => onStart(example) };+ const secondary = mode === 'reference' ? { label: t('gallery.startNew'), run: () => onStart(example) } : null;++ return (+ <div className="px-6 pb-10">+ <div className="grid grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)] gap-7">+ <div>+ <div className="relative aspect-video overflow-hidden rounded-[12px] bg-black ring-1 ring-[var(--border)]">+ {example.video ? <video ref={video} src={example.video} poster={example.poster ?? undefined} controls playsInline className="absolute inset-0 h-full w-full object-contain" />+ : <Picture example={example} playing={false} fit="contain" />}+ </div>+ {duration ? (+ <div className="mt-3">+ <div className="mb-1.5 flex items-center justify-between text-[11.5px] text-[var(--text-faint)]">+ <span>{t('gallery.parts')}</span>+ <span>{part ? `${clock(part.from)}–${clock(part.to)}` : t('gallery.whole')}</span>+ </div>+ <div ref={strip}+ onMouseDown={(e) => { if (e.button === 0) { setDrag(timeAt(e.clientX)); setPart(null); } }}+ onMouseMove={(e) => { if (drag != null) { const at = timeAt(e.clientX); if (Math.abs(at - drag) > duration / 200) setPart({ from: Math.min(drag, at), to: Math.max(drag, at) }); } }}+ onMouseUp={() => { if (drag != null && part) seek(part.from); setDrag(null); }}+ onMouseLeave={() => setDrag(null)}+ className="relative flex h-9 cursor-crosshair select-none overflow-hidden rounded-[8px] bg-[var(--surface-2)] ring-1 ring-[var(--border)]">+ {(example.segments.length ? example.segments : [{ title: example.title, from: 0, to: duration }]).map((g) => (+ <button key={`${g.from}-${g.title}`} type="button" title={g.title}+ onMouseDown={(e) => e.stopPropagation()}+ onClick={() => pick(example.segments.length ? { from: g.from, to: g.to, segment: g.title } : null)}+ style={{ left: `${(g.from / duration) * 100}%`, width: `${((g.to - g.from) / duration) * 100}%` }}+ className={`absolute inset-y-1 truncate rounded-[5px] border-l-2 border-[var(--bg)] px-1.5 text-left text-[11px] transition ${part?.segment === g.title ? 'bg-[var(--text)] text-[var(--bg)]' : 'text-[var(--text-muted)] hover:bg-[var(--bg-hover)]'}`}>+ {g.title}+ </button>+ ))}+ {part && !part.segment ? (+ <div className="pointer-events-none absolute inset-y-0 rounded-[4px] ring-2 ring-inset ring-[var(--text)]"+ style={{ left: `${(part.from / duration) * 100}%`, width: `${((part.to - part.from) / duration) * 100}%`, background: 'color-mix(in srgb, var(--text) 18%, transparent)' }} />+ ) : null}+ </div>+ <p className="mt-1.5 text-[11.5px] text-[var(--text-faint)]">{t('gallery.partsHint')}</p>+ </div>+ ) : null}+ </div>+ <div className="flex min-w-0 flex-col">+ {example.category ? <div className="mb-1 text-[11.5px] font-medium text-[var(--text-muted)]">{categoryLabel(example.category)}</div> : null}+ <h2 className="text-[20px] font-semibold leading-tight tracking-[-0.01em] text-[var(--text)]">{example.title}</h2>+ {example.description ? <p className="mt-2 text-[13.5px] leading-[20px] text-[var(--text-muted)]">{example.description}</p> : null}+ {example.duration ? <p className="mt-2 text-[12px] text-[var(--text-faint)]">{clock(example.duration)}</p> : null}+ <div className="mt-5 flex flex-col gap-2">+ <button type="button" onClick={primary.run}+ className="flex h-10 items-center justify-center gap-1.5 rounded-[10px] bg-[var(--text)] text-[13.5px] font-medium text-[var(--bg)] transition hover:opacity-90">+ {mode === 'reference' ? null : <Play size={13} />}{primary.label}+ </button>+ {secondary ? (+ <button type="button" onClick={secondary.run}+ className="h-10 rounded-[10px] border border-[var(--border)] text-[13.5px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]">{secondary.label}</button>+ ) : null}+ </div>+ <p className="mt-3 text-[12px] leading-[17px] text-[var(--text-faint)]">{mode === 'reference' ? t('gallery.referenceHow') : t('gallery.startHow')}</p>+ <a href={example.url} target="_blank" rel="noreferrer" className="mt-auto flex items-center gap-1.5 pt-6 text-[12px] text-[var(--text-dim)] hover:text-[var(--text)]"><ExternalLink size={13} />{t('gallery.viewSource')}</a>+ </div>+ </div>+ </div>+ );+}++/**+ * The examples over a film, opened from the app's chat (`show-examples`): an example or a part of it becomes a+ * reference in the message being written at once (its folder, for the agent to read, fetched meanwhile and by the app+ * when the message is sent), a skill is named in it (lib/host.ts `useSkill`), and an example can still be started+ * from, as a new project (`onStarted`).+ */+export function ExamplesDialog({ projectId, open, onClose, onStarted }: { projectId: string; open?: CommunityItem; onClose: () => void; onStarted: (projectId: string) => void }) {+ const t = useT();+ const [starting, setStarting] = React.useState<Example | null>(null);+ const reference = (example: Example, part: ExamplePart) => {+ /* fetched meanwhile, so the message goes as soon as it is sent */+ void sourcesApi.exampleFolder(example.id).catch(() => {});+ studioHost?.refer?.({+ kind: 'example', id: example.id, title: example.title, url: example.url, ...(example.description ? { description: example.description } : {}),+ ...(part ? { start: part.from, end: part.to, ...(part.segment ? { segment: part.segment } : {}) } : {}),+ });+ onClose();+ };+ return createPortal(+ <>+ <div className="fixed inset-0 z-[10040] bg-black/60" onMouseDown={onClose} />+ <div role="dialog" aria-modal="true" aria-label={t('gallery.community')}+ className="fixed left-1/2 top-1/2 z-[10050] flex -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-2xl border border-[var(--border-strong)] bg-[var(--app-content-bg)] shadow-[0_24px_64px_rgba(0,0,0,0.35)]"+ style={{ width: 'min(1200px, calc(100vw - 64px))', height: 'min(800px, calc(100vh - 80px))' }}>+ <ExamplesGallery+ mode="reference"+ projectId={projectId}+ {...(open ? { initial: open } : {})}+ onClose={onClose}+ onStart={setStarting}+ onReference={reference}+ onUseSkill={(skill) => { studioHost?.useSkill?.({ name: skill.name, description: skill.description }); onClose(); }}+ />+ </div>+ {starting ? (+ <GitHubDialog url={starting.url} start title={starting.title}+ onDone={(id) => { setStarting(null); onStarted(id); onClose(); }}+ onClose={() => setStarting(null)} />+ ) : null}+ </>,+ document.body,+ );+}diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsxindex 55ed6e7..0e853b0 100644--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx@@ -60,6 +60,7 @@ import type { MaskSession } from '@/lib/stage-mask';import type { MaskShape } from '@/lib/clip-mask';import type { FadeMs } from '@/lib/clip-fade';import type { FoundKind } from '@/lib/transitions';+import { TemplateSection, type TemplateHost } from './TemplateSection';/** A change of a layer's words (kept as its `text` override). `expect` is what it said before: painted back on refusal. */export type StageTextEdit = {@@ -174,6 +175,7 @@ export const FilmInspector = React.memo(function FilmInspector({rate,fades,transition,+ templateOf,}: {element: StageElement | null;/** The clips selected on the timeline. A layer picked on the picture wins: one selection at a time. */@@ -251,6 +253,8 @@ export const FilmInspector = React.memo(function FilmInspector({fades?: ReadonlyMap<string, FadeMs>;/** The transition picked on the timeline (no clip selected): its kind and length, made longer or taken away here. */transition?: TransitionPick | null;+ /** A page clip's template controls (TemplateSection): read from its page, written as its overrides. */+ templateOf?: (block: TimelineBlock) => TemplateHost | null;}) {const t = useT();useCommitBeforeLeaving();@@ -322,6 +326,7 @@ export const FilmInspector = React.memo(function FilmInspector({badges={film?.badges}stage={stageSize}{...(fades ? { fades } : {})}+ {...(templateOf ? { templateOf } : {})}/>) : many ? (<MultiClipPanel@@ -1371,8 +1376,10 @@ function clipsLook(*/function ClipPanel({block, onMain, geometry, stage, badges, onEdit, onPreviewClip, pageChangesOf, replaceEntries, clipLookOf, onPreviewLook, onStartCrop, onEditMask, maskAsk, onMaskAsked, fades,+ templateOf,}: {fades?: ReadonlyMap<string, FadeMs>;+ templateOf?: (block: TimelineBlock) => TemplateHost | null;replaceEntries?: (block: TimelineBlock) => ContextMenuEntry[];block: TimelineBlock;/** On the main track, where the magnet acts. */@@ -1417,6 +1424,12 @@ function ClipPanel({const look = target ? clipsLook([target], commit, onPreviewLook) : null;const at = parseFilmDocLoc(loc ?? '');const badge = at ? badges?.[at.track] : undefined;+ /* the same host while the same clip is in hand: the section reads the page again when its overrides change */+ const template = React.useMemo(+ () => (block.kind === 'mg' && docLoc && templateOf ? templateOf(block) : null),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [templateOf, block.clipId, block.kind, docLoc],+ );return (<>@@ -1437,6 +1450,10 @@ function ClipPanel({</p>) : (<>+ {/* a page's own controls first: what a template is used for */}+ {template ? (+ <TemplateSection host={template} commit={(next) => commit([{ loc: loc!, prop: 'overrides', value: next as unknown as Record<string, unknown> | null }])} />+ ) : null}{picture && own && geo ? (<ClipPositionSectiont={t}diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsxindex 6845692..8ae443c 100644--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx@@ -1028,6 +1028,17 @@ function FilmStageSelectImpl({};const finishTextEditRef = React.useRef(finishTextEdit);finishTextEditRef.current = finishTextEdit;+ /* the words as they are typed in the picture: the inspector shows them (its box and the layer's name) as they come */+ const onTyping = (e: Extract<StageEvent, { event: 'typing' }>) => {+ const edit = textEdit.current;+ const element = edit?.element;+ if (!edit || edit.layer.handle !== e.handle || !element?.text) return;+ /* a layer named by its words is named by the new ones */+ const label = element.label === element.text.value && e.value ? e.value : element.label;+ const next = { ...element, label, text: { ...element.text, value: e.value } };+ setPicked((cur) => (cur?.element?.loc === element.loc ? { ...cur, element: next } : cur));+ onSelectElement?.(next);+ };const onTextDone = (e: Extract<StageEvent, { event: 'text' }>) => {const edit = textEdit.current;if (!edit || edit.layer.handle !== e.handle) return;@@ -1035,7 +1046,12 @@ function FilmStageSelectImpl({setEditingText(null);syncGeomSoon();const { element, layer } = edit;- if (!e.commit || !e.value || !onEditTextInline) return;+ if (!e.commit || !e.value || !onEditTextInline) {+ /* given up (or nothing new): the inspector goes back to the words it had */+ setPicked((cur) => (cur?.element?.loc === element.loc ? { ...cur, element } : cur));+ if (pickedRef.current?.element?.loc === element.loc) onSelectElement?.(element);+ return;+ }const value = e.value;const nextElement = { ...element, ...(element.text ? { text: { ...element.text, value } } : {}) };setPicked((cur) => (cur?.element?.loc === element.loc ? { ...cur, element: nextElement } : cur));@@ -1234,6 +1250,7 @@ function FilmStageSelectImpl({if (!preview?.onStage) return undefined;return preview.onStage((e) => {if (e.event === 'text') onTextDoneRef.current(e);+ else if (e.event === 'typing') onTypingRef.current(e);else if (e.event === 'key') {const k = e.key;if (isSelectAll(k)) { if (!textEdit.current && !cropRef.current) void selectAllRef.current(); }@@ -1250,6 +1267,8 @@ function FilmStageSelectImpl({}, [previewRef, syncGeomSoon]);const onTextDoneRef = React.useRef(onTextDone);onTextDoneRef.current = onTextDone;+ const onTypingRef = React.useRef(onTyping);+ onTypingRef.current = onTyping;/* ── the clips selected on the timeline ── */const [linkedMarks, setLinkedMarks] = React.useState<readonly LinkedMark[]>(NO_MARKS);diff --git a/packages/openfilm/studio/ui/src/components/Launcher.tsx b/packages/openfilm/studio/ui/src/components/Launcher.tsxnew file mode 100644index 0000000..abc344e--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/Launcher.tsx@@ -0,0 +1,31 @@+/**+ * The window of an app with tabs (lib/host.ts `tabs`) when no tab is open: an empty window (its top bar still drags+ * it) and the projects window over it, as `+` opens it, only with nothing behind to close it to. The project picked+ * opens in its tab.+ */+import React from 'react';+import { BrandLogo } from './BrandLogo';+import { ProjectsPopover } from './ProjectsLibrary';+import { SettingsModal, type SettingsSection } from './settings/SettingsModal';+import { Tooltip } from './Tooltip';+import { useT } from '@/i18n';++export function Launcher({ onOpen }: { onOpen: (projectId: string) => void }) {+ const t = useT();+ const [settings, setSettings] = React.useState<SettingsSection | null>(null);+ return (+ <div className="workspace-shell flex flex-col bg-[var(--dock-shell)]">+ <div data-titlebar className="relative flex h-8 min-w-0 shrink-0 items-center gap-1 px-[6px]">+ <div aria-hidden className="shrink-0 self-stretch" style={{ width: 'var(--titlebar-logo-x)' }} />+ <Tooltip label={t('project.appMenu')} side="bottom">+ <button type="button" aria-label={t('project.appMenu')} aria-haspopup="dialog" onClick={() => setSettings('general')}+ className="flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-md text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)]">+ <BrandLogo size={15} />+ </button>+ </Tooltip>+ </div>+ <ProjectsPopover open currentProjectId="" onOpen={onOpen} onCurrentRemoved={() => {}} />+ <SettingsModal open={settings !== null} section={settings ?? undefined} onClose={() => setSettings(null)} />+ </div>+ );+}diff --git a/packages/openfilm/studio/ui/src/components/MediaPool.tsx b/packages/openfilm/studio/ui/src/components/MediaPool.tsxindex 91ae086..1bd9107 100644--- a/packages/openfilm/studio/ui/src/components/MediaPool.tsx+++ b/packages/openfilm/studio/ui/src/components/MediaPool.tsx@@ -17,6 +17,10 @@import React from 'react';import {ArrowUpDown,+ Bookmark,+ BookmarkPlus,+ Layers,+ LayoutTemplate,ChevronRight,Clapperboard,Copy,@@ -69,6 +73,7 @@ import { Tooltip } from './Tooltip';import { retryImage } from '@/lib/retry-image';import { boxBetween, boxHits, boxPick, moveTargets, pickItem, type Box } from '@/lib/media-selection';import { barLayout, type BarWords } from '@/lib/media-bar';+import { byName, folderFaces } from '@/lib/media-folders';type Filter = 'all' | 'video' | 'image' | 'audio' | 'page' | 'other';type SortKey = 'name' | 'time' | 'duration' | 'type';@@ -159,8 +164,17 @@ export interface MediaPoolProps {/** A link pointed at where its media is now (the person picks it), or copied into the project in its place. */onRelink?: (path: string, folder: boolean) => Promise<MediaResult>;onCollect?: (path: string) => Promise<MediaResult>;- /** Where the pool is a drawer the person opened (a host app's panel, see lib/host.ts): its close button, last in the bar. */- onClose?: () => void;+ /** Files kept to use again in any project (lib/saved): the file menu's "Add to Saved". */+ onSave?: (files: WorkspaceResource[]) => void;+ /**+ * Which library the pane shows, the project's media or Saved (the person's own, for every project), and the button+ * beside Upload that switches between them. Both are the same pane: upload, folders, views, filters, sort, rename,+ * move, delete, drag onto the timeline.+ */+ scope?: 'project' | 'saved';+ onScope?: (next: 'project' | 'saved') => void;+ /** Upload may also link media kept elsewhere (a project's); without it, files are copied in only (Saved). */+ links?: boolean;/*** The app around Studio has a chat (lib/host.ts `refer`): a file as a reference in it. With it the file menu has* "Reference in chat", and a dragged file carries the reference too (STUDIO_REF_TYPE), for the chat to take.@@ -197,7 +211,10 @@ export function MediaPool({onBring,onRelink,onCollect,- onClose,+ onSave,+ scope = 'project',+ onScope,+ links = true,fileRef,onRefer,reveal,@@ -223,6 +240,10 @@ export function MediaPool({const [dropTarget, setDropTarget] = React.useState<string | null>(null);const [osDrag, setOsDrag] = React.useState(false);const inputRef = React.useRef<HTMLInputElement>(null);+ const inSaved = scope === 'saved';+ React.useEffect(() => { setQuery(''); }, [scope]);+ /* the top folder: All of the project's media, or Saved */+ const topName = inSaved ? t('saved.title') : t('media.filter_all');React.useEffect(() => { setView(loadView(projectId)); setAtState(OPEN_FOLDER.get(projectId) ?? ''); setPicked([]); }, [projectId]);/* the file the viewer shows is the host's: the one clicked last, when it is a file. One shown from elsewhere (a click@@ -264,10 +285,10 @@ export function MediaPool({const q = query.trim();const order = (a: WorkspaceResource, b: WorkspaceResource) => {/* as added: the oldest first, what comes in goes last */- if (view.sort === 'time') return (a.addedMs ?? a.mtimeMs) - (b.addedMs ?? b.mtimeMs) || a.name.localeCompare(b.name, undefined, { numeric: true });+ if (view.sort === 'time') return (a.addedMs ?? a.mtimeMs) - (b.addedMs ?? b.mtimeMs) || byName(a.name, b.name);if (view.sort === 'duration') return (b.durationMs ?? -1) - (a.durationMs ?? -1);if (view.sort === 'type') return filterOf(a).localeCompare(filterOf(b)) || a.name.localeCompare(b.name);- return a.name.localeCompare(b.name, undefined, { numeric: true });+ return byName(a.name, b.name);};/* searching or showing one kind looks through every folder at once */if (q || view.filter !== 'all') {@@ -277,18 +298,8 @@ export function MediaPool({}/* the project's pages are at the top; a page put in a folder is in its folder */const here = allFiles.filter((f) => (inMedia(f.path) ? relDir(assetRel(f.path)) === at : at === '')).sort(order);- const sub = folders- .filter((dir) => relDir(dir) === at)- .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))- .map((rel) => ({- type: 'folder' as const, rel, name: rel.split('/').pop()!,- count: allFiles.filter((f) => inMedia(f.path) && assetRel(f.path).startsWith(`${rel}/`)).length,- /* what the folder holds, on its cover: pictures first (they say the most), sounds after */- covers: allFiles- .filter((f) => inMedia(f.path) && assetRel(f.path).startsWith(`${rel}/`))- .sort((a, b) => Number(a.kind === 'audio') - Number(b.kind === 'audio') || a.name.localeCompare(b.name, undefined, { numeric: true }))- .slice(0, 4),- }));+ /* the folders here, what each holds and its cover (lib/media-folders) */+ const sub = folderFaces(allFiles, folders, at, (path) => (inMedia(path) ? assetRel(path) : null)).map((face) => ({ type: 'folder' as const, ...face }));return [...sub, ...here.map((file) => ({ type: 'file' as const, file }))];}, [allFiles, folders, at, query, view, assetRel, inMedia]);@@ -434,7 +445,7 @@ export function MediaPool({else if (result === 'taken') taken ??= nameOf(path);else failed = true;}- if (taken) setNotice(t('media.moveTaken').replace('{name}', taken).replace('{folder}', intoRel ? intoRel.split('/').pop()! : t('media.filter_all')));+ if (taken) setNotice(t('media.moveTaken').replace('{name}', taken).replace('{folder}', intoRel ? intoRel.split('/').pop()! : topName));else if (failed) setNotice(t('media.moveFailed'));if (selectedRef.current && moved.includes(selectedRef.current)) showFile(null);setPicked((cur) => cur.filter((key) => !moved.includes(key)));@@ -538,7 +549,7 @@ export function MediaPool({submenu: moveTargets(folders, moving).map((rel) => {const here = heres.size === 1 && heres.has(rel);return {- id: `move:${rel}`, label: rel ? rel.split('/').join(' / ') : t('media.filter_all'), checked: here, disabled: here,+ id: `move:${rel}`, label: rel ? rel.split('/').join(' / ') : topName, checked: here, disabled: here,...(here ? { hint: t('media.moveHere') } : {}),onSelect: () => { void moveAll(keys, rel); },};@@ -551,6 +562,7 @@ export function MediaPool({{ id: 'refer-sep', separator: true } as const,] : []),...commonEntries(file.path),+ ...(onSave ? [{ id: 'save', label: t('saved.add'), icon: <BookmarkPlus size={14} />, onSelect: () => onSave([file]) }] : []),{ id: 'sep', separator: true } as const,...linkEntries(file.path, false),/* web pages are the film's code, written by the person's agent (and named in each other's code): not renamed@@ -559,7 +571,8 @@ export function MediaPool({id: 'extract-audio', label: t('assets.extractAudio'), icon: <AudioLines size={14} />,onSelect: () => { void onExtractAudio(file.path).then((r) => { if (r !== 'ok') setNotice(t('assets.extractAudioFailed')); }); },}] : []),- ...(file.kind === 'mg' ? [] : [{ id: 'rename', label: t('assets.rename'), icon: <Pencil size={14} />, onSelect: () => setRenaming(file.path) }]),+ /* a page of the project is named in other pages' code (not renamed here); one of Saved is its own folder */+ ...(file.kind === 'mg' && !file.bundle ? [] : [{ id: 'rename', label: t('assets.rename'), icon: <Pencil size={14} />, onSelect: () => setRenaming(file.path) }]),moveEntry([file.path]),{ id: 'delete', label: t('assets.delete'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setConfirm({ targets: [{ path: file.path, folder: false }], name: file.name }) },];@@ -577,11 +590,16 @@ export function MediaPool({id: 'collect', label: t('media.collect'), note: t('media.collectNote'), icon: <HardDriveDownload size={14} />,onSelect: () => { void collectAll(keys.filter((key) => linkOf(key) && !linkOf(key)!.missing)); },}] : []),+ ...(onSave && keys.some((key) => itemByKey.get(key)?.type === 'file') ? [{+ id: 'save', label: t('saved.add'), icon: <BookmarkPlus size={14} />,+ onSelect: () => onSave(keys.flatMap((key) => { const item = itemByKey.get(key); return item?.type === 'file' ? [item.file] : []; })),+ }] : []),moveEntry(keys),{ id: 'sep', separator: true },{ id: 'delete', label: t('media.deleteMany').replace('{n}', String(keys.length)), icon: <Trash2 size={14} />, danger: true, onSelect: () => askDelete(keys) },];- /* what Upload offers: a copy in the project, or a link to where the media is kept (a NAS, another disk) */+ /* what Upload offers: a copy in the project, or a link to where the media is kept (a NAS, another disk); where+ nothing is linked (Saved), Upload picks the files to copy in at once */const importMenu: ContextMenuEntry[] = [{ id: 'import', label: t('media.importFiles'), note: t('media.importFilesNote'), icon: <Upload size={14} />, onSelect: () => { void bringFrom('copy', false); } },{ id: 'link', label: t('media.linkFiles'), note: t('media.linkFilesNote'), icon: <Link2 size={14} />, onSelect: () => { void bringFrom('link', false); } },@@ -590,7 +608,7 @@ export function MediaPool({const blankMenu: ContextMenuEntry[] = [{ id: 'new-folder', label: t('assets.newFolder'), icon: <FolderPlus size={14} />, onSelect: () => setCreating(true) },{ id: 'import', label: t('media.import'), icon: <Plus size={14} />, onSelect: () => (onPick && onBring ? void bringFrom('copy', false) : inputRef.current?.click()) },- ...(onPick && onBring ? [+ ...(onPick && onBring && links ? [{ id: 'link', label: t('media.linkFiles'), icon: <Link2 size={14} />, onSelect: () => { void bringFrom('link', false); } },{ id: 'link-folder', label: t('media.linkFolder'), icon: <FolderSymlink size={14} />, onSelect: () => { void bringFrom('link', true); } },] : []),@@ -717,7 +735,7 @@ export function MediaPool({}, [hint, uploadWord, fontsTick, rootEl]);/* the fullest bar that fits (lib/media-bar); before the pane is measured, the full one */const bar = paneWidth > 0 && words- ? barLayout(paneWidth, words, 4 + (onClose ? 1 : 0), Boolean(query))+ ? barLayout(paneWidth, words, 5, Boolean(query)): { field: true, uploadWord: true, tight: false, cramped: false };const tight = bar.tight;const [searchOpen, setSearchOpen] = React.useState(false);@@ -842,12 +860,18 @@ export function MediaPool({{/* bringing media in is what this pane is for: the one labeled button, right after the search */}<Tooltip label={t('media.import')} side="bottom"><button type="button" aria-label={t('media.import')} aria-haspopup={onPick && onBring ? 'menu' : undefined}- onClick={(e) => (onPick && onBring ? barMenu(e, importMenu) : inputRef.current?.click())}+ onClick={(e) => (onPick && onBring ? (links ? barMenu(e, importMenu) : void bringFrom('copy', false)) : inputRef.current?.click())}className={`flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-md bg-[var(--bg-active)] text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--border-strong)] ${bar.uploadWord ? 'px-2.5' : 'w-7'}`}><Upload size={13} strokeWidth={2.2} />{bar.uploadWord ? uploadWord : null}</button></Tooltip>+ {/* Saved, the person's own library for every project: the pane shows it in place of the project's media, and back */}+ {onScope ? (+ <BarButton label={t(inSaved ? 'saved.back' : 'saved.title')} on={inSaved} onClick={() => onScope(inSaved ? 'project' : 'saved')}>+ <Bookmark size={14} {...(inSaved ? { fill: 'currentColor' } : {})} />+ </BarButton>+ ) : null}<BarButton label={t(rows ? 'media.viewGrid' : 'media.viewList')} onClick={() => setView((v) => ({ ...v, layout: rows ? 'grid' : 'list' }))}>{rows ? <LayoutGrid size={14} /> : <List size={14} />}</BarButton>@@ -858,7 +882,6 @@ export function MediaPool({id: key, label: t(`media.sort_${key}`), checked: view.sort === key, onSelect: () => setView((v) => ({ ...v, sort: key })),})))}><ArrowUpDown size={14} /></BarButton><BarButton label={t('assets.newFolder')} onClick={() => { setQuery(''); setView((v) => ({ ...v, filter: 'all' })); setCreating(true); }}><FolderPlus size={14} /></BarButton>- {onClose ? <BarButton label={t('media.close')} onClick={onClose}><X size={14} /></BarButton> : null}{/* any kind of file: what Studio cannot play is still the project's material */}<input ref={inputRef} type="file" multiple className="hidden"onChange={(e) => { const list = [...(e.target.files ?? [])]; e.target.value = ''; void importFiles(list); }} />@@ -874,7 +897,7 @@ export function MediaPool({<><button type="button" onClick={() => setAt('')} {...dropProps('')}className={`shrink-0 rounded px-1 ${at ? 'text-[var(--text-muted)] hover:text-[var(--text)]' : 'font-medium text-[var(--text)]'} ${dropTarget === '' ? 'bg-[var(--bg-hover)] ring-1 ring-[var(--accent)]' : ''}`}>- {t('media.filter_all')}+ {topName}</button>{crumbs.map((name, i) => {const rel = crumbs.slice(0, i + 1).join('/');@@ -920,8 +943,8 @@ export function MediaPool({flat ? <p className="px-1 pt-6 text-center text-[12px] text-[var(--text-muted)]">{t('media.noMatch')}</p> : (<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center"><Clapperboard size={22} className="text-[var(--text-faint)]" />- <div className="text-[13px] font-medium text-[var(--text)]">{t(at ? 'media.emptyFolder' : 'media.emptyTitle')}</div>- {at ? null : <p className="max-w-[30ch] text-[12px] leading-relaxed text-[var(--text-muted)]">{t('media.emptyBody')}</p>}+ <div className="text-[13px] font-medium text-[var(--text)]">{t(at ? 'media.emptyFolder' : inSaved ? 'saved.emptyTitle' : 'media.emptyTitle')}</div>+ {at ? null : <p className="max-w-[30ch] text-[12px] leading-relaxed text-[var(--text-muted)]">{t(inSaved ? 'saved.emptyBody' : 'media.emptyBody')}</p>}<button type="button" onClick={() => (onPick && onBring ? void bringFrom('copy', false) : inputRef.current?.click())}className="mt-1 inline-flex h-7 items-center gap-1.5 rounded-md border border-[var(--border)] px-2.5 text-[12.5px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)]"><Plus size={13} />{t('media.import')}@@ -981,7 +1004,9 @@ export function MediaPool({{...(fileRef ? { studioRef: () => fileRef(item.file) } : {})}moving={() => dragKeys(item.file.path)}onPress={(e) => press(item, e)}- typeText={item.file.kind === 'mg' ? t('assets.kindPage') : extOf(item.file.name).toUpperCase()}+ typeText={item.file.bundle ? t(`saved.kind_${item.file.bundle.kind}`) : item.file.kind === 'mg' ? t('assets.kindPage') : extOf(item.file.name).toUpperCase()}+ library={inSaved}+ {...(item.file.bundle?.template ? { templateMark: t('saved.template') } : {})}onMenu={(e) => menuFor(item, e)}onRename={(name) => void rename(item.file.path, name, false)}onCancelRename={() => setRenaming(null)}@@ -1034,7 +1059,8 @@ function BarButton({ label, on, onClick, children }: { label: string; on?: boolereturn (<Tooltip label={label} side="bottom"><button type="button" aria-label={label} onClick={onClick}- className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] ${on ? 'text-[var(--accent)]' : 'text-[var(--text-dim)]'}`}>+ /* two states, on and off: hovered, only the ground lights; an on button keeps its color */+ className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition hover:bg-[var(--bg-hover)] ${on ? 'text-[var(--accent)]' : 'text-[var(--text-dim)] hover:text-[var(--text)]'}`}>{children}</button></Tooltip>@@ -1217,7 +1243,12 @@ function FileTile(p: {typeText: string;/** A row of the list view, not a tile. */row?: boolean;+ /** In Saved: a drag of it says its place there (its files are brought into the project as it lands). */+ library?: boolean;+ /** A bundle of Saved whose page has custom properties: the word that marks it a template. */+ templateMark?: string;}) {+ const bundle = p.file.bundle;return (<divclassName={p.row@@ -1231,7 +1262,7 @@ function FileTile(p: {/* a drag picks nothing: picking opens the inspector, and the pane laid out again under the pointer (or hidden forroom) would lose the drag */onDragStart={(e) => {- setResourceDragData(e.dataTransfer, p.file);+ setResourceDragData(e.dataTransfer, p.library ? { ...p.file, saved: p.file.path } : p.file);if (p.studioRef) e.dataTransfer.setData(STUDIO_REF_TYPE, JSON.stringify([p.studioRef()]));/* any file can go into a folder of this pane: a page's links are written again as it moves (Studio) */e.dataTransfer.setData(FOLDER_DRAG, p.moving().join('\n'));@@ -1283,6 +1314,13 @@ function FileTile(p: {) : p.file.proxy && p.file.proxy.state !== 'failed' ? (<span className="absolute inset-x-0 bottom-0 z-10 h-1" title={p.proxyLabel}><UploadBar ratio={p.file.proxy.state === 'making' ? p.file.proxy.ratio ?? 0 : -1} /></span>) : null}+ {/* a bundle of Saved: a template, and how many clips a group holds */}+ {p.templateMark ? (+ <span className="absolute left-1 top-1 z-10 flex items-center gap-0.5 rounded bg-black/65 px-1 text-[9.5px] font-semibold leading-[15px] text-white/90"><LayoutTemplate size={9} />{p.templateMark}</span>+ ) : null}+ {bundle?.kind === 'group' && bundle.count ? (+ <span className="absolute bottom-1 left-1 z-10 flex items-center gap-0.5 rounded bg-black/65 px-1 text-[10.5px] tabular-nums leading-[16px] text-white"><Layers size={10} />{bundle.count}</span>+ ) : null}{p.duration ? <span className="absolute bottom-1 right-1 z-10 rounded bg-black/65 px-1 text-[10.5px] tabular-nums leading-[16px] text-white">{p.duration}</span> : null}</div></div>diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsxindex 79dfe27..ba4ec7c 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 { ClipboardCopy, ClipboardPaste, GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, TriangleAlert } from 'lucide-react';+import { BookmarkPlus, 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';@@ -18,7 +18,7 @@ import { filmShape, type MediaFacts } from '@/lib/film-shape';import { changesPicture } from '@/lib/picture-files';import type { ReplaceFamily } from '@/lib/clip-replace';import { layoutTracks, type TimelineBlock, type TimelineTrack } from '@/lib/timeline-layout';-import { filmClipKind, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc } from '@/lib/film';+import { filmClipKind, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc, type FilmOverride } from '@/lib/film';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';@@ -51,7 +51,7 @@ import { BrandLogo } from './BrandLogo';import { SettingsModal, type SettingsSection } from './settings/SettingsModal';import { DesktopDialog } from './DesktopDialog';import type { ContextMenuEntry } from './ContextMenu';-import { studioHost, useHostPanel, type HostPanel, type StageBox, type StudioCommand, type StudioRef } from '../lib/host';+import { studioHost, useHostPanel, type CommunityItem, type HostPanel, type StageBox, type StudioCommand, type StudioRef } from '../lib/host';import { clipRef, fileRef, layerRef, markRange, momentRef, rangeRef, regionRef, stillUrl, subtitleRef, trackRef, type ClipFrameSource, type FilmRange } from '@/lib/studio-refs';import { boxNow, chatPointOf, draftBoxesAt, draftMarksOf, sameClip, NO_DRAFT, type DraftMarks, type PictureMarks } from '@/lib/chat-marks';import { shortcutHint } from '@/lib/shortcut-hint';@@ -64,7 +64,9 @@ import { cueAt, filmSubtitleStyleFor, sameFilmSubtitleLanguage } from '@/lib/subimport { DEFAULT_INSPECTOR, DOCK_GAP, DockPaneDivider, MIN_DOCK_H, MIN_INSPECTOR, MIN_STAGE_H, MIN_VIEWER, PaneDivider, usePaneSize } from './PaneDivider';import { PANE_BAR, PANE_BTN_ON, PANE_TOGGLE, PANE_TOGGLE_ICON } from './dock-pane-bar';import { Tooltip } from './Tooltip';-import { UpdateButton } from './UpdateButton';+import { TabStrip } from './TabStrip';+import { ExamplesDialog } from './ExamplesGallery';+import { UpdateButton, WebUpdateButton } from './UpdateButton';import { MediaPool, type ImportProgress } from './MediaPool';import type { SubtitleRowSpec } from './SubtitleRow';import { LayersPanel } from './LayersPanel';@@ -96,6 +98,11 @@ import { FontScopeContext, type FontScope } from '@/lib/use-fonts';import { stageMenu, stageRecoveryMenu, type StageArrangeResult, type StageMenuContext } from './stage-menu';import type { StageEditFailure, StageTextEdit } from './FilmInspector';import { layerTarget, pageClipOf, recoverLayer } from '@/lib/stage-layers';+import type { TemplateControls } from '@/lib/template-controls';+import type { TemplateHost } from './TemplateSection';+import { SAVED, refreshSaved, savedActions, savedSources, useSavedListing } from '@/lib/saved';+import { batchMap } from '@/lib/batch-map';+import { groupInsertAt, groupInsertOps } from '@/lib/saved-insert';import { pageClips, pageMayHave, similarEdits } from '@/lib/similar-layers';import type { MaskSession } from '@/lib/stage-mask';import type { MaskShape } from '@/lib/clip-mask';@@ -106,6 +113,8 @@ import { isTypingTarget } from './typing-target';const PANE = 'relative flex min-h-0 min-w-0 flex-col overflow-hidden rounded-[7px]';/* ⌘ is the modifier on a Mac, Ctrl elsewhere (the editor's keys, lib/timeline-keys) */const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);+/** Which the media pane shows, the project's media or Saved: kept while Studio is open, across projects. */+const MEDIA_SCOPE: { current: 'project' | 'saved' } = { current: 'project' };/** where the app's panel starts: under Studio's top bar (its h-8) */const HOST_PANEL_TOP = 32;@@ -259,6 +268,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {page without a duration has no end, and is dropped on the timeline with a length of its own; a picture's sizegives its clip a box in its own shape */const probed = React.useRef(new Set<string>());+ /* the answers handed on a few times a second, not one by one (lib/batch-map) */+ const factsIn = React.useMemo(() => batchMap<string, ReturnType<typeof factsOfProbe> & { audio?: boolean }>((batch) => {+ setFacts((m) => { const next = new Map(m); for (const [path, f] of batch) next.set(path, f); return next; });+ }, 250), []);+ React.useEffect(() => () => factsIn.cancel(), [factsIn]);React.useEffect(() => {if (!rawListing) return;const wanted = [@@ -279,10 +293,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {...(page && !(probe.duration > 0) ? { endless: true } : {}),...(page && probe.reflows ? { reflows: true } : {}),};- setFacts((m) => new Map(m).set(f.path, facts));+ factsIn.set(f.path, facts);}, () => {});}- }, [rawListing, projectId]);+ }, [rawListing, projectId, factsIn]);const folder = loaded?.folder ?? '';const mediaSources = React.useMemo<MediaSources>(() => {@@ -650,6 +664,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {stageElementRef.current = stageElement;/* the inspector shows a media file, or what is selected */const [pickedMedia, setPickedMedia] = React.useState<WorkspaceResource | null>(null);+ /* the file picked is one of Saved (lib/saved): shown from there, and brought into the project when it is used */+ const [pickedSaved, setPickedSaved] = React.useState(false);const [inspectorContent, setInspectorContent] = React.useState<'selection' | 'subtitles' | WorkspaceResource>('selection');const subs = useFilmSubtitles(projectId);/* fullscreen's CC button (and c): only what is shown, not the film's own setting */@@ -668,6 +684,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {}, []);const pickMedia = React.useCallback((file: WorkspaceResource | null) => {setPickedMedia(file);+ /* one of the project's, unless the Saved pane says otherwise right after (pickSaved) */+ setPickedSaved(false);if (file) { setInspectorContent(file); setInspectorOpen(true); }else setInspectorContent((c) => (typeof c === 'object' ? 'selection' : c));}, []);@@ -956,6 +974,24 @@ export function ProjectView({ projectId, onProject, onLeave }: {const dropAsset = React.useCallback(async (file: ResourceDragItem, target: AssetDropTarget, atMs: number): Promise<string | null> => {const plan = assetDropInsert(file, timelineTracks, target, atMs, stageRef.current);if ('error' in plan) return plan.error === 'locked' ? t('timeline.trackLocked') : t('timeline.dropNotClip');+ /* a thing of Saved (lib/saved): brought into the project first (a file imported, a bundle's files copied in), then+ put where it was dropped: a file as a file of the project goes, a clip as it was saved */+ if (file.saved) {+ let taken: Awaited<ReturnType<typeof api.takeSaved>>;+ try { taken = await api.takeSaved(projectId, file.saved); } catch (e) { return e instanceof Error ? e.message : String(e); }+ /* a group: its tracks new ones, where it was dropped */+ if ('clips' in taken) return edit(groupInsertOps(taken.clips, plan.at, groupInsertAt(plan.track), editModel()), 'history.stepDrop');+ if ('path' in taken) {+ const { saved: _from, ...rest } = file;+ return dropAssetRef.current({ ...rest, path: taken.path }, target, atMs);+ }+ const clip = taken.clip;+ const durMs = file.durationMs ?? assetRunMs([file]);+ return edit([+ { op: 'insert', clip: clip as never, at: plan.at, ...(plan.track != null ? { track: plan.track } : {}) },+ ...roomFor([{ track: plan.track, atSec: plan.at, durMs }], target.edit),+ ], 'history.stepDrop');+ }const pending = pendingDropOf(file, target, atMs);if (pending) setPendingDrops((all) => [...all, pending]);try {@@ -966,7 +1002,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {} finally {if (pending) setPendingDrops((all) => all.filter((d) => d.id !== pending.id));}- }, [timelineTracks, edit, roomFor, t]);+ }, [timelineTracks, edit, roomFor, t, projectId, editModel]);+ const dropAssetRef = React.useRef(dropAsset);+ dropAssetRef.current = dropAsset;/*** A media file put on the timeline without a drag (lib/media-place): the media pane's "+" and Enter (in the* timeline's mode, at the playhead on the targeted track, else at the end of the main track), the source viewer's@@ -987,9 +1025,86 @@ export function ProjectView({ projectId, onProject, onLeave }: {else seekWhenLonger.current = end;}}, [editModel, edit, pause, seek, t, toast]);+ /*+ * A thing of Saved put on the timeline without a drag (its "+", Enter, the source viewer's `,` and `.`): brought into+ * the project first, then as a file of the project goes (`how`), or a clip as it was saved, at the playhead on the+ * targeted track; a group on new tracks at the top, from the playhead.+ */+ const placeSaved = React.useCallback(async (file: WorkspaceResource, how: { mode?: EditMode; range?: SourceRange | null; atPlayhead?: boolean } = {}) => {+ let taken: Awaited<ReturnType<typeof api.takeSaved>>;+ try { taken = await api.takeSaved(projectId, file.path); } catch (e) { toast.show(e instanceof Error ? e.message : String(e)); return; }+ if ('path' in taken) {+ const { bundle: _bundle, ...rest } = file;+ await addMedia({ ...rest, path: taken.path }, how);+ return;+ }+ /* a group: on new tracks at the top, from the playhead */+ if ('clips' in taken) {+ const failed = await edit(groupInsertOps(taken.clips, snapToFrame(timeRef.current) / 1000, 0, editModel()), 'history.stepDrop');+ if (failed) toast.show(failed);+ return;+ }+ const prefs = readTimelinePrefs();+ const target = timelineCommands.current?.target() ?? null;+ const plan = placeMedia(editModel(), { file, range: null, target, at: snapToFrame(timeRef.current), magnet: prefs.magnet, ...followOf(prefs), stage: stageRef.current });+ if ('error' in plan) { toast.show(plan.error === 'locked' ? t('timeline.trackLocked') : t('timeline.dropNotClip')); return; }+ const clip = taken.clip;+ const failed = await edit(plan.ops.map((op) => (op.op === 'insert' ? { ...op, clip: clip as never } : op)), 'history.stepDrop');+ if (failed) toast.show(failed);+ }, [projectId, editModel, edit, addMedia, t, toast]);const placeFromSource = React.useCallback((mode: EditMode, range: SourceRange | null) => {- if (pickedMedia) void addMedia(pickedMedia, { mode, range, atPlayhead: true });- }, [addMedia, pickedMedia]);+ if (pickedMedia && pickedSaved) void placeSaved(pickedMedia, { mode, range, atPlayhead: true });+ else if (pickedMedia) void addMedia(pickedMedia, { mode, range, atPlayhead: true });+ }, [addMedia, placeSaved, pickedMedia, pickedSaved]);+ /* clips (and files) kept to use again in any project (lib/saved, studio/server/saved.mjs): the timeline's, the+ picture's and the media pane's "Add to Saved" */+ const saveThings = React.useCallback(async (what: Parameters<typeof api.save>[1], n: number) => {+ if (!n) return;+ try {+ await api.save(projectId, what);+ refreshSaved();+ toast.show(n === 1 ? t('saved.added') : t('saved.addedMany').replace('{n}', String(n)));+ } catch (e) {+ toast.showError(t('saved.failed').replace('{error}', e instanceof Error ? e.message : String(e)));+ }+ }, [projectId, t, toast]);+ const saveBlocks = React.useCallback((blocks: readonly TimelineBlock[], together = false) => {+ const kept = blocks.filter((b) => b.clipId);+ /* several as one: laid out as they are, from the first one's start to the last one's end */+ if (together && kept.length > 1) {+ const startMs = Math.min(...kept.map((b) => b.startMs));+ const endMs = Math.max(...kept.map((b) => b.endMs));+ /* named and pictured by the top one that draws a picture */+ const trackOf = (b: TimelineBlock) => parseFilmDocLoc(b.loc ?? '')?.track ?? 0;+ const byTrack = [...kept].sort((a, b) => trackOf(a) - trackOf(b) || a.startMs - b.startMs);+ const top = byTrack.find((b) => b.kind === 'mg' || b.kind === 'video') ?? byTrack[0]!;+ const w = top.box?.w ?? top.size?.w;+ const h = top.box?.h ?? top.size?.h;+ const name = `${top.title}${kept.length > 1 ? ` +${kept.length - 1}` : ''}`;+ void saveThings({ groups: [{ ids: kept.map((b) => b.clipId!), name, durationMs: endMs - startMs, ...(w ? { w } : {}), ...(h ? { h } : {}) }] }, 1);+ return;+ }+ const clips = kept.map((b) => {+ const w = b.box?.w ?? b.size?.w;+ const h = b.box?.h ?? b.size?.h;+ return { id: b.clipId!, name: b.title, durationMs: Math.max(0, b.endMs - b.startMs), ...(w ? { w } : {}), ...(h ? { h } : {}) };+ });+ void saveThings({ clips }, clips.length);+ }, [saveThings]);+ const saveFiles = React.useCallback((files: WorkspaceResource[]) => {+ const list = files.map((f) => ({ path: f.path, name: f.name, ...(f.durationMs ? { durationMs: f.durationMs } : {}), ...(f.w ? { w: f.w } : {}), ...(f.h ? { h: f.h } : {}) }));+ void saveThings({ files: list }, list.length);+ }, [saveThings]);+ /* one clip, or several as one (each one alone, too) */+ const saveEntry = (blocks: readonly TimelineBlock[]): ContextMenuEntry[] => {+ const n = blocks.filter((b) => b.clipId).length;+ if (!n) return [];+ if (n === 1) return [{ id: 'save', label: t('saved.add'), icon: <BookmarkPlus size={14} />, onSelect: () => saveBlocks(blocks) }];+ return [+ { id: 'save', label: t('saved.addTogether').replace('{n}', String(n)), icon: <BookmarkPlus size={14} />, onSelect: () => saveBlocks(blocks, true) },+ { id: 'save-each', label: t('saved.addEach'), icon: <BookmarkPlus size={14} />, onSelect: () => saveBlocks(blocks) },+ ];+ };/* the subtitle row (components/SubtitleRow): its edits go into the transcripts, each a step of the undo here */const subtitleEdits = useSubtitleEdits(projectId, { film: film.film, refresh: subs.refresh, record: film.record });const subtitleRow = React.useMemo<SubtitleRowSpec>(() => ({@@ -1072,13 +1187,44 @@ export function ProjectView({ projectId, onProject, onLeave }: {const layersShownWidth = rowWidth ? Math.min(layersWidth, layersRoom) : layersWidth;const layersFit = !rowWidth || layersShownWidth >= 180;const layersShown = layersPaneOpen && layersFit;- const mediaPool = (onClose?: () => void) => (+ /* the media pane shows the project's media, or Saved (lib/saved): the same pane, the button beside Upload switches */+ const [mediaScope, setMediaScope] = React.useState<'project' | 'saved'>(() => MEDIA_SCOPE.current);+ const switchMedia = React.useCallback((next: 'project' | 'saved') => { MEDIA_SCOPE.current = next; setMediaScope(next); }, []);+ const savedListing = useSavedListing(mediaScope === 'saved');+ const savedImport = React.useCallback((files: File[], into: string, onProgress: ImportProgress) => {+ /* in the app a dropped file's path is known: copied on this computer, not sent through the page */+ const paths = files.map((file) => studioHost?.folders?.pathOf(file) ?? '');+ if (paths.length && paths.every(Boolean)) return savedActions.bring(paths, into);+ return savedActions.upload(files, into, onProgress, t('assets.uploadFailed'));+ }, [t]);+ const mediaPool = () => (mediaScope === 'saved' ? (<MediaPool+ key="saved"+ projectId={SAVED}+ listing={savedListing}+ sources={savedSources}+ selectedPath={pickedSaved ? pickedMedia?.path ?? null : null}+ onSelectFile={(file) => { pickMedia(file); setPickedSaved(Boolean(file)); }}+ onImport={savedImport}+ onMove={savedActions.move}+ onDelete={savedActions.remove}+ onNewFolder={savedActions.newFolder}+ onReveal={savedActions.reveal}+ onPick={onPick}+ onBring={(paths, into) => savedActions.bring(paths, into)}+ links={false}+ scope="saved"+ onScope={switchMedia}+ onAdd={(file) => void placeSaved(file)}+ />+ ) : (+ <MediaPool+ key="project"projectId={projectId}listing={listing}sources={mediaSources}usedSrcs={usedSrcs}- selectedPath={pickedMedia?.path ?? null}+ selectedPath={pickedSaved ? null : pickedMedia?.path ?? null}onSelectFile={pickMedia}onImport={onImport}onMove={onMove}@@ -1092,13 +1238,15 @@ export function ProjectView({ projectId, onProject, onLeave }: {onBring={onBring}onRelink={onRelink}onCollect={onCollect}- onClose={onClose}+ onSave={saveFiles}+ scope="project"+ onScope={switchMedia}{...(studioHost?.refer ? { fileRef: refOfFile, onRefer: studioHost.refer } : {})}reveal={revealMedia}litPath={chatPoint?.file ?? null}onAdd={(file) => void addMedia(file)}/>- );+ ));/* the range marked on the timeline (⇧-drag on the ruler, I and O): Studio's, told to the app with the selection */const [markedRange, setMarkedRange] = React.useState<FilmRange | null>(null);rangeNowRef.current = markedRange;@@ -1201,6 +1349,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {if (command.type === 'highlight') { setChatRef(command.ref ?? null); return; }if (command.type === 'draft-refs') { setDraftMarks(draftMarksOf(Array.isArray(command.refs) ? command.refs : [])); return; }if (command.type === 'settings') { setSettingsOpen(command.section ?? 'agents'); return; }+ if (command.type === 'show-examples') { setExamplesOpen(command.open ?? true); return; }if (command.type === 'seek' && Number.isFinite(command.time)) { pause(); seek(command.time * 1000); return; }if ((command.type === 'show-range' || command.type === 'show-subtitle') && Number.isFinite(command.start) && Number.isFinite(command.end)) {/* a subtitle's span marked, and the subtitle panel open: the playhead at its start lights the line there */@@ -1445,6 +1594,28 @@ export function ProjectView({ projectId, onProject, onLeave }: {const startStageCrop = React.useCallback(() => { stageControl.current?.startCrop(); }, []);const editStageMask = React.useCallback((session: MaskSession | null) => { stageControl.current?.editMask(session); }, []);const pageChangesOf = usePageChanges(preview, filmRef);+ /* a page clip's template controls (components/TemplateSection): read from its page on the picture, previewed there,+ written as its overrides by the inspector */+ /* the project's files as listed now, for the Template section's pictures (its host outlives a render) */+ const listingRef = React.useRef(listing);+ listingRef.current = listing;+ const templateOf = React.useCallback((block: TimelineBlock): TemplateHost | null => {+ const clip = block.clipId;+ if (!clip) return null;+ return {+ read: () => askStage<TemplateControls>('controls', { clip }),+ overrides: () => {+ const at = parseFilmDocLoc(blocksRef.current.find((b) => b.clipId === clip)?.loc ?? '');+ return (at ? filmRef.current?.tracks[at.track]?.clips[at.clip]?.overrides : undefined) as readonly FilmOverride[] | undefined;+ },+ preview: (target, patch) => {+ void (patch ? askStage('tweak', { clip, at: target.at, ...(target.n ? { n: target.n } : {}), patch }) : askStage('release', { clip }));+ },+ page: block.src ?? '',+ pictures: () => (listingRef.current?.files ?? []).filter((f) => /\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i.test(f.path)).map((f) => ({ path: f.path, name: f.path.split('/').pop() ?? f.path })),+ pickPicture: () => pickReplacement('picture'),+ };+ }, [askStage, pickReplacement]);/* a clip's own CSS as film.html has it, and the look the player measured (the Inspector's Look section) */const clipLookOf = React.useCallback((clipLoc: string) => {const at = parseFilmDocLoc(clipLoc);@@ -1518,10 +1689,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {const entries = stageMenuFor(el, ctx);const block = el.clipLoc ? blocksRef.current.find((b) => b.loc === el.clipLoc) : null;const whole = el.kind === 'clip' || el.isMgOuter;- const extra = whole && !block ? [] : referEntry(() => [whole ? refOfBlock(block!) : refOfLayer(el)]);+ const extra = whole && !block ? [] : [...referEntry(() => [whole ? refOfBlock(block!) : refOfLayer(el)]), ...(whole && block ? saveEntry([block]) : [])];return extra.length ? [...extra, ...(entries.length ? [{ id: 'refer-sep', separator: true } as const] : []), ...entries] : entries;// eslint-disable-next-line react-hooks/exhaustive-deps- }, [stageMenuFor, t]);+ }, [stageMenuFor, t, saveBlocks]);/** 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]);/* copy and paste attributes, as CapCut's clip menu has them */@@ -1529,7 +1700,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {{ 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-deps+ const timelineMenuExtra = React.useCallback((blocks: readonly TimelineBlock[]) => (blocks.length ? menuGroups(menuGroups([...referEntry(() => blocks.map(refOfBlock)), ...saveEntry(blocks)], tools.menuExtra(blocks)), attrsEntries(blocks)) : []), [t, tools.menuExtra, copiedAttrs, copyAttrs, askPasteAttrs, saveBlocks]); // 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);@@ -2248,6 +2419,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {return { title, durationMs: totalMs, tracks: tracks.length, clips: tracks.reduce((n, tr) => n + tr.clips.length, 0), empty, badges: filmTrackBadges(tracks) };}, [title, totalMs, film.film?.tracks, empty]);const startRename = () => { setTitleEditWidth(titleBoxRef.current?.offsetWidth ?? null); setTitleDraft(title); setRenaming(true); };+ /* in an app with tabs: the tab says this project's title; the tabs are where the projects button and the title are */+ const inTabs = Boolean(studioHost?.tabs);+ /* the app's "New Tab" (its menu): the projects, to pick what the new tab shows */+ React.useEffect(() => studioHost?.tabs?.onPick(() => setProjectsOpen(true)), []);+ React.useEffect(() => { if (title) studioHost?.tabs?.report({ title }); }, [title]);const commitTitle = async () => {setRenaming(false);const next = titleDraft.trim();@@ -2260,6 +2436,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {}};const [projectsOpen, setProjectsOpen] = React.useState(false);+ /* the examples over the film, opened from the app's chat */+ /* the Community over the film: closed, open on its list (true), or on one skill's or example's page */+ const [examplesOpen, setExamplesOpen] = React.useState<boolean | CommunityItem>(false);const [settingsOpen, setSettingsOpen] = React.useState<SettingsSection | null>(null);/* making subtitles: what went wrong, shown on the CC button; with no service to transcribe, it opens Providers */const [subtitleProblem, setSubtitleProblem] = React.useState<{ text: string; connect: boolean } | null>(null);@@ -2338,7 +2517,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {<div className="relative z-10 grid min-h-0 min-w-0 flex-1" style={{ gridTemplateColumns: 'minmax(0, 1fr)', gridTemplateRows: 'auto minmax(0, 1fr)', gridTemplateAreas: '"bar" "main"' }}>{/* ── top bar: the title centered, whatever is on either side ── */}<div data-titlebar className="relative flex h-8 min-w-0 items-center gap-1" style={{ gridArea: 'bar' }}>- <div className="pointer-events-none absolute inset-0 flex min-w-0 items-center justify-center">+ {inTabs ? null : <div className="pointer-events-none absolute inset-0 flex min-w-0 items-center justify-center"><div className="pointer-events-auto flex min-w-0 max-w-full items-center">{renaming ? (<input@@ -2364,7 +2543,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {</Tooltip>)}</div>- </div>+ </div>}<div aria-hidden className="shrink-0 self-stretch" style={{ width: 'var(--titlebar-logo-x)' }} /><div className="pointer-events-auto relative flex min-w-0 items-center gap-1"><Tooltip label={t('project.appMenu')} side="bottom">@@ -2374,13 +2553,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {<BrandLogo size={15} /></button></Tooltip>- <Tooltip label={t('nav.projects')} side="bottom">+ {inTabs ? null : <Tooltip label={t('nav.projects')} side="bottom"><button type="button" aria-label={t('nav.projects')} onClick={() => setProjectsOpen((v) => !v)}className={`${TOP_BTN} ${projectsOpen ? 'bg-[var(--bg-hover)] text-[var(--text)]' : ''}`}><GalleryVerticalEnd size={15} /></button>- </Tooltip>+ </Tooltip>}<UpdateButton />+ <WebUpdateButton />{!studioHost && <Tooltip label={t('desktop.title')} side="bottom"><button type="button" aria-haspopup="dialog" onClick={() => setDesktopOpen(true)}className={`flex h-[26px] shrink-0 items-center gap-1.5 rounded-md px-2 text-[12px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] ${desktopOpen ? 'bg-[var(--bg-hover)] text-[var(--text)]' : ''}`}>@@ -2389,7 +2569,28 @@ export function ProjectView({ projectId, onProject, onLeave }: {</button></Tooltip>}</div>- <div className="min-w-0 flex-1" />+ {inTabs ? (+ <TabStrip onRename={startRename} onNew={() => setProjectsOpen(true)} editor={renaming ? (+ <input+ autoFocus+ value={titleDraft}+ onChange={(e) => setTitleDraft(e.target.value)}+ onBlur={() => void commitTitle()}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void commitTitle();+ if (e.key === 'Escape') { setTitleDraft(title); setRenaming(false); }+ }}+ onClick={(e) => e.stopPropagation()}+ /* opened by a double-click: all its words selected, to type over or to pick from */+ onFocus={(e) => e.currentTarget.select()}+ onMouseDown={(e) => e.stopPropagation()}+ onDoubleClick={(e) => e.stopPropagation()}+ placeholder={t('project.untitled')}+ maxLength={TITLE_MAX_CHARS}+ className="min-w-0 flex-1 bg-transparent text-[12.5px] font-medium text-[var(--text)] outline-none"+ />+ ) : undefined} />+ ) : <div className="min-w-0 flex-1" />}<div ref={headerOpsRef} className="pointer-events-auto flex min-w-0 items-center justify-end gap-1"><ProjectLayoutMenu className={TOP_BTN}/* an app that keeps the media in its own panel opens it there, from its own button: not a pane of Studio's */@@ -2500,7 +2701,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {}} />{pickedMedia ? (<div className="absolute inset-x-0 bottom-0 top-8 z-20">- <SourcePreview file={pickedMedia} sources={mediaSources} onClose={() => pickMedia(null)} onPlace={placeFromSource} />+ <SourcePreview file={pickedSaved && pickedMedia.bundle ? { ...pickedMedia, kind: 'image' } : pickedMedia} sources={pickedSaved ? savedSources : mediaSources} onClose={() => pickMedia(null)} onPlace={placeFromSource} /></div>) : null}{dropped?.length || undone.length ? (@@ -2646,7 +2847,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {<><PaneDivider width={inspectorShownWidth} onResize={commitInspectorWidth} containerRef={viewerRowRef} label={t('inspector.resize')} min={MIN_INSPECTOR} minRest={MIN_VIEWER} side="end" />{typeof inspectorContent === 'object' ? (- <ResourceInspector file={inspectorContent} url={mediaSources.file(inspectorContent)} width={inspectorShownWidth} onClose={closeInspector} />+ <ResourceInspector file={inspectorContent} url={(pickedSaved && inspectorContent === pickedMedia ? savedSources : mediaSources).file(inspectorContent)} width={inspectorShownWidth} onClose={closeInspector} />) : inspectorContent === 'subtitles' ? (<SubtitleInspectorsubtitles={{ style: subs.style, onStyle: subs.patchStyle, translate: subs.translate, sourceLanguage: subs.sourceLanguage, lines: subs.captions?.cues ?? [], onEditLine: (cue, text, language) => void subs.setLine(cue, text, language), timeMs, onSeek: seek, untranscribed: subs.captions?.untranscribed.length ?? 0, onMake: makeSubtitles, making: subs.transcribing, ...(subtitleRefer ? { refer: subtitleRefer } : {}) }}@@ -2676,6 +2877,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {onSelectClip={selectStageClip}onPreviewClip={previewClip}pageChangesOf={pageChangesOf}+ templateOf={templateOf}replaceEntries={tools.replaceEntries}clipLookOf={clipLookOf}onPreviewLook={previewLook}@@ -2779,6 +2981,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {<ProjectHistoryControls projectId={projectId} history={history} open={historyOpen} anchor={historyAnchor} onClose={() => setHistoryOpen(false)} /><ProjectsPopover open={projectsOpen} currentProjectId={projectId} onOpen={(id) => { setProjectsOpen(false); onProject(id); }} onCurrentRemoved={onLeave} onClose={() => setProjectsOpen(false)} />+ {examplesOpen ? (+ <ExamplesDialog projectId={projectId} open={examplesOpen === true ? undefined : examplesOpen} onClose={() => setExamplesOpen(false)}+ /* a film started from an example: in a tab of its own where there are tabs, else here */+ onStarted={(id) => { if (studioHost?.tabs) studioHost.tabs.open(id); else onProject(id); }} />+ ) : null}<SettingsModal open={settingsOpen !== null} section={settingsOpen ?? undefined} onClose={() => setSettingsOpen(null)} />{/* the host app's media drawer (panel.assets): over its panel, under Studio's top bar, down to the `bottom` px thepanel keeps for itself (the panel goes on below it, so the two read as one) */}@@ -2786,7 +2993,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {{hostAssets?.open && hostPanel ? (<div className="fixed z-30 flex min-h-0 min-w-0 flex-col overflow-hidden rounded-t-[7px] bg-[var(--dock-pane)]"style={{ top: HOST_PANEL_TOP, right: DOCK_GAP, bottom: hostAssets.bottom, width: Math.max(0, hostPanel.width - 2 * DOCK_GAP) }}>- {mediaPool(() => hostAssets.setOpen(false))}+ {mediaPool()}</div>) : null}<DesktopDialog open={desktopOpen} onClose={() => setDesktopOpen(false)} />diff --git a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsxindex d40f5c7..70a8bea 100644--- a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx@@ -1,7 +1,8 @@/**- * The Projects popover (the top bar's Projects button): a large centered dialog to switch project, start one, open a- * folder, get a film from GitHub or the examples, rename, delete, or file projects in folders of the list. Its- * contents are ProjectsView; this file holds the data and actions.+ * The Projects popover (the top bar's Projects button; with the app's tabs, their `+`, and the window with no tab open):+ * a large centered dialog to switch project, start one, open a folder, get a film from GitHub, rename, delete, or+ * file projects in folders of the list; or, switched to "Examples", to start from an example (ExamplesGallery). Its+ * projects are ProjectsView; this file holds the data and actions.** Studio's projects are folders on disk: deleting one moves its folder to the system's Trash. One whose folder is gone* (moved, renamed or deleted outside Studio: `missing`) cannot be opened; it can be located (the folder it is in now)@@ -21,13 +22,12 @@ import { api, ApiError } from '@/api';import { useT } from '@/i18n';import { folderApi, folderCounts, folderTrail, type ProjectFolder } from '@/lib/project-folders';import { studioHost } from '@/lib/host';-import { SourceError, examplesCollapsed, setExamplesCollapsed, sourcesApi, type Example } from '@/lib/project-sources';+import { SourceError, sourcesApi } from '@/lib/project-sources';import { ConfirmDialog } from './ConfirmDialog';import { ProjectsView, type LibraryProject } from './ProjectsView';import { FolderBrowserDialog, GitHubDialog } from './ProjectSources';+import { ExamplesGallery, TitleSwitch } from './ExamplesGallery';-/** This browser's storage, when the page may use it. */-const storage = () => { try { return localStorage; } catch { return null; } };/* each card's picture: the film's middle frame, drawn by Studio (cached until film.html changes); none for a projectwhose folder is gone (its card shows its color) */@@ -160,6 +160,16 @@ function useProjectLibrary(open: boolean) {return { projects, folders, loaded, error, flash, reload: reloadFolders, agentRunning, workingIn, deleteProjects, renameProject, createFolder, renameFolder, moveProject, deleteFolder };}+/** The launcher's two views: the person's projects, and the examples to start from (ExamplesGallery). */+export type LauncherView = 'projects' | 'examples';++/** The switch between them, in the title row (the Community's is the same). */+export function LauncherSwitch({ view, onView }: { view: LauncherView; onView: (view: LauncherView) => void }) {+ const t = useT();+ return <TitleSwitch items={[{ id: 'projects' as const, label: t('launcher.projects') }, { id: 'examples' as const, label: t('launcher.examples') }]} value={view} onChange={onView} />;+}++export function ProjectsPopover({open,currentProjectId,@@ -182,6 +192,10 @@ export function ProjectsPopover({}) {const t = useT();const lib = useProjectLibrary(open);+ /* each time it opens: the projects (the examples are a switch away) */+ const [view, setView] = React.useState<LauncherView>('projects');+ React.useEffect(() => { if (open) setView('projects'); }, [open]);+ const showView = setView;const [pendingDelete, setPendingDelete] = React.useState<string[] | null>(null);const [pendingFolder, setPendingFolder] = React.useState<ProjectFolder | null>(null);const [busy, setBusy] = React.useState<'creating' | 'opening' | null>(null);@@ -189,8 +203,6 @@ export function ProjectsPopover({const [browser, setBrowser] = React.useState<{ mode: 'open' } | { mode: 'locate'; project: LibraryProject } | null>(null);const [github, setGithub] = React.useState<{ url?: string; start?: boolean; title?: string } | null>(null);const [askStart, setAskStart] = React.useState<string | null>(null);- const [examples, setExamples] = React.useState<Example[]>([]);- const [examplesFolded, setExamplesFolded] = React.useState(() => examplesCollapsed(storage()));const close = React.useCallback(() => onClose?.(), [onClose]);React.useEffect(() => {@@ -200,14 +212,6 @@ export function ProjectsPopover({return () => window.removeEventListener('keydown', onKey);}, [open, close, pendingDelete, pendingFolder, askStart]);- /* the examples, read on each open (none when the index cannot be read: the section stays hidden) */- React.useEffect(() => {- if (!open) return undefined;- let alive = true;- void sourcesApi.examples().then((list) => { if (alive) setExamples(list); });- return () => { alive = false; };- }, [open]);-const go = (projectId: string, kind: 'creating' | 'opening') => {/* the project already open: nowhere to go, and an "Opening" that would never end */if (projectId === currentProjectId) { close(); return; }@@ -325,7 +329,7 @@ export function ProjectsPopover({/* what deleting it takes: its projects and those of the folders inside it */const folderHeld = pendingFolder ? (folderCounts(lib.projects, lib.folders)[pendingFolder.id] ?? 0) : 0;- return createPortal(+ const content = (<><div className="fixed inset-0 z-[10040] bg-black/60" onMouseDown={close} /><div@@ -341,18 +345,22 @@ export function ProjectsPopover({onDrop={onDrop}><div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">- {lib.loaded ? (+ {view === 'examples' ? (+ <ExamplesGallery+ mode="start"+ heading={<LauncherSwitch view={view} onView={showView} />}+ onClose={onClose}+ onStart={(example) => setGithub({ url: example.url, start: true, title: example.title })}+ />+ ) : lib.loaded ? (<ProjectsView+ heading={<LauncherSwitch view={view} onView={showView} />}projects={lib.projects}creating={busy !== null}onNewProject={() => void newProject()}onOpenFolder={() => void openFolder()}onGetFromGitHub={() => setGithub({})}onLocate={(project) => void locate(project)}- examples={examples}- examplesCollapsed={examplesFolded}- onToggleExamples={() => setExamplesFolded((folded) => { setExamplesCollapsed(storage(), !folded); return !folded; })}- onOpenExample={(example) => setGithub({ url: example.url, start: true, title: example.title })}/* its folder is gone: there is nothing to open, and the editor would only say so */onOpen={(project) => (project.missing ? lib.flash(t('projects.missingOpen')) : go(project.id, 'opening'))}onRename={(projectId, name) => void lib.renameProject(projectId, name)}@@ -458,7 +466,7 @@ export function ProjectsPopover({});}}/>- </>,- document.body,+ </>);+ return createPortal(content, document.body);}diff --git a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx b/packages/openfilm/studio/ui/src/components/ProjectsView.tsxindex ea6e466..ed3b98d 100644--- a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx@@ -65,6 +65,7 @@ export function ProjectsView({onDeleteFolder,onMoveToFolder,onClose,+ heading,}: {projects: LibraryProject[];/** A project is being created or opened; "New project" does not take a second click meanwhile. */@@ -99,6 +100,8 @@ export function ProjectsView({onMoveToFolder: (projectId: string, folderId: string | null) => void;/** Missing: no close button (Studio has no project to go back to). */onClose?: () => void;+ /** The title row's left, in place of "Projects" (the launcher's switch between the projects and the examples). */+ heading?: React.ReactNode;}) {const t = useT();/* recently opened first: someone coming back to the list most likely wants the one they just had */@@ -246,7 +249,7 @@ export function ProjectsView({<div className="flex min-h-0 min-w-0 flex-1 flex-col">{/* the header stays out of the scroll area: inside it, the list view's scrollbar would narrow the header */}<header className="flex shrink-0 flex-col gap-3 px-6 pb-4 pt-5">- <div className="flex items-center gap-2">+ <div className="flex min-h-8 items-center gap-2">{/* inside a folder the title is the way back: "Projects / test", on the same line, so what is in the folderstarts where the projects do */}{currentFolder ? (@@ -259,7 +262,7 @@ export function ProjectsView({onDelete={() => onDeleteFolder(currentFolder)}/>) : (- <h2 className="mr-auto text-[17px] font-semibold tracking-[-0.01em] text-[var(--text)]">{t('nav.projects')}</h2>+ heading ?? <h2 className="mr-auto text-[17px] font-semibold tracking-[-0.01em] text-[var(--text)]">{t('nav.projects')}</h2>)}{projects.length > 0 ? (<>diff --git a/packages/openfilm/studio/ui/src/components/SpendAsks.tsx b/packages/openfilm/studio/ui/src/components/SpendAsks.tsxindex cf12d8d..4ec5971 100644--- a/packages/openfilm/studio/ui/src/components/SpendAsks.tsx+++ b/packages/openfilm/studio/ui/src/components/SpendAsks.tsx@@ -81,7 +81,7 @@ function worded(ask: SpendAsk | StudioNotice, t: (path: string) => string): HostdenyLabel: t('asks.close'),};}- /* "a slow push…" · fal.ai · Seedance 2.0 · 5s, as Settings → Models names a model */+ /* "a slow push…" · fal.ai · Seedance 2.0 · 5s, as Settings → Services names a model */const by = ask.model ? `${ask.provider} · ${ask.model}` : ask.provider;const facts = [ask.prompt ? `“${ask.prompt}”` : null, by, ask.seconds ? `${ask.seconds}s` : null].filter(Boolean).join(' · ');return { id: ask.id, title: t('asks.videoTitle'), body: `${facts}. ${t('asks.videoNote')}`, allowLabel: t('asks.make'), denyLabel: t('asks.skip') };diff --git a/packages/openfilm/studio/ui/src/components/TabStrip.tsx b/packages/openfilm/studio/ui/src/components/TabStrip.tsxnew file mode 100644index 0000000..d9e1a45--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/TabStrip.tsx@@ -0,0 +1,103 @@+/**+ * The app window's tabs, drawn in Studio's top bar (lib/host.ts `tabs`): one per open project, and `+` (`onNew`), which+ * opens the projects window to pick the project a new tab shows. Tabs are the bar's full height, square, side by side+ * between hairlines; the one in front takes the panes' color. A tab says what is happening in it: an agent at work (a+ * spinner), a question waiting for the person (a dot), an export (its percent). A tab is shown by a click, closed by+ * its × or a middle click, moved by dragging; this page's own tab, double-clicked, renames its project (`onRename`),+ * and shows `editor` instead of its title while that happens.+ */+import React from 'react';+import { Loader2, Plus, X } from 'lucide-react';+import { api } from '@/api';+import { useT } from '@/i18n';+import { studioHost, type HostTab } from '@/lib/host';+import { Tooltip } from './Tooltip';++const TAB_TYPE = 'application/x-openfilm-tab';++/** The tabs as the app has them, live, and which is this page's. */+export function useHostTabs() {+ const [tabs, setTabs] = React.useState<HostTab[]>([]);+ const [self, setSelf] = React.useState<string | null>(null);+ React.useEffect(() => {+ const host = studioHost?.tabs;+ if (!host) return undefined;+ let alive = true;+ void host.list().then((r) => { if (alive) { setTabs(r.tabs); setSelf(r.self); } });+ const stop = host.onChange((next) => setTabs(next));+ return () => { alive = false; stop(); };+ }, []);+ return { tabs, self };+}++export function TabStrip({ editor, onRename, onNew }: { editor?: React.ReactNode; onRename?: () => void; onNew?: () => void }) {+ const t = useT();+ const host = studioHost?.tabs;+ const { tabs, self } = useHostTabs();+ /* a tab whose page has not said its title yet (one restored, or not shown since): its project's name */+ const [names, setNames] = React.useState<Record<string, string>>({});+ const unnamed = tabs.some((tab) => !tab.title && !names[tab.projectId]);+ React.useEffect(() => {+ if (!unnamed) return;+ void api.projects().then((list) => setNames(Object.fromEntries(list.map((p) => [p.id, p.name]))), () => {});+ }, [unnamed]);+ const [dragging, setDragging] = React.useState<string | null>(null);+ const [over, setOver] = React.useState<number | null>(null);+ if (!host) return null;++ const titleOf = (tab: HostTab) => tab.title || names[tab.projectId] || t('project.untitled');++ return (+ <div role="tablist" aria-label={t('tabs.label')} className="flex h-full min-w-0 flex-1 items-stretch">+ <div className="flex h-full min-w-0 items-stretch overflow-hidden border-l border-[var(--border)]">+ {tabs.map((tab, i) => {+ const mine = tab.id === self;+ /* being renamed: its words are selected and edited like any text, and the tab does not move */+ const editing = mine && Boolean(editor);+ return (+ <React.Fragment key={tab.id}>+ <div+ role="tab"+ aria-selected={tab.active}+ tabIndex={-1}+ draggable={!editing}+ title={titleOf(tab)}+ onClick={() => { if (!tab.active) host.show(tab.id); }}+ onDoubleClick={() => { if (mine && !editing) onRename?.(); }}+ onMouseDown={(e) => { if (e.button === 1) { e.preventDefault(); host.close(tab.id); } }}+ onDragStart={(e) => { e.dataTransfer.setData(TAB_TYPE, tab.id); e.dataTransfer.effectAllowed = 'move'; setDragging(tab.id); }}+ onDragEnd={() => { setDragging(null); setOver(null); }}+ onDragOver={(e) => { if (e.dataTransfer.types.includes(TAB_TYPE)) { e.preventDefault(); setOver(i); } }}+ onDrop={(e) => { const id = e.dataTransfer.getData(TAB_TYPE); if (id) host.move(id, i); setDragging(null); setOver(null); }}+ className={`group relative flex h-full w-[184px] min-w-[84px] shrink cursor-default items-center gap-1.5 border-r border-[var(--border)] pl-3 pr-1.5 text-[12.5px] transition-colors+ ${tab.active ? 'bg-[var(--dock-pane)] text-[var(--text)]' : 'text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)]'}+ ${dragging === tab.id ? 'opacity-50' : ''} ${over === i && dragging && dragging !== tab.id ? 'shadow-[inset_2px_0_0_var(--text-muted)]' : ''}`}+ >+ {tab.working ? <Loader2 size={11} className="shrink-0 animate-spin text-[var(--text-dim)]" /> : null}+ {tab.asking ? <span className="h-[6px] w-[6px] shrink-0 rounded-full bg-[#ff9f43]" /> : null}+ {editing ? editor : <span className="min-w-0 flex-1 truncate font-medium">{titleOf(tab)}</span>}+ {tab.exporting != null ? <span className="shrink-0 font-mono text-[10.5px] text-[var(--text-faint)]">{Math.round(tab.exporting * 100)}%</span> : null}+ <button+ type="button"+ aria-label={t('tabs.close')}+ onClick={(e) => { e.stopPropagation(); host.close(tab.id); }}+ className={`flex h-[18px] w-[18px] shrink-0 items-center justify-center rounded-[5px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] ${tab.active ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}+ >+ <X size={12} />+ </button>+ </div>+ </React.Fragment>+ );+ })}+ </div>+ {onNew ? (+ <Tooltip label={t('tabs.new')} side="bottom">+ <button type="button" aria-label={t('tabs.new')} onClick={onNew}+ className="ml-1 flex h-[26px] w-[26px] shrink-0 items-center justify-center self-center rounded-md text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">+ <Plus size={15} />+ </button>+ </Tooltip>+ ) : null}+ </div>+ );+}diff --git a/packages/openfilm/studio/ui/src/components/TemplateSection.tsx b/packages/openfilm/studio/ui/src/components/TemplateSection.tsxnew file mode 100644index 0000000..9fa0730--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/TemplateSection.tsx@@ -0,0 +1,329 @@+/**+ * The inspector's Template section for a page clip: the page's custom properties, its words and its pictures, changed+ * here without opening the page, as a motion graphics template is filled in (lib/template-controls). Each field paints+ * first and writes when let go, as every inspector field does; each change is an override of the clip, and a field+ * changed from the page's own value can go back to it. A custom property that names a font gets the font picker; a+ * picture is replaced by a picture of the project (picked from a menu, or dropped from the media pane) or one from this+ * computer.+ */+import * as React from 'react';+import { HardDriveUpload, ImageIcon, RotateCcw } from 'lucide-react';++import { useT } from '@/i18n';+import type { FilmOverride } from '@/lib/film';+import {+ ROOT, changedImage, changedText, changedVar, fieldOf, isFontVar, labelOf, relativeTo, valueOf, withImage, withText, withVar,+ type TemplateControls, type TemplateImage, type VarField,+} from '@/lib/template-controls';+import { joinFontFamily, splitFontFamily } from '@/lib/font-styles';+import { readResourceDragData, RESOURCE_DRAG_TYPE } from '@/lib/resource-drag';+import { ColorField, FIELD, INPUT, NumField, Section, SectionAction } from './inspector-fields';+import { FontFamilyPicker } from './FontFamilyPicker';+import { ContextMenu, type ContextMenuEntry } from './ContextMenu';++type T = ReturnType<typeof useT>;++/** What the section needs of the clip: its controls as the page has them, its overrides, and the picture. */+export interface TemplateHost {+ /** Null when the clip is not on the picture now (the page is read where it is drawn). */+ read: () => Promise<TemplateControls | null>;+ overrides: () => readonly FilmOverride[] | undefined;+ /** Paints a change without writing it; null takes it back. */+ preview: (target: { at: string; n?: number }, patch: { style?: Record<string, string>; text?: string } | null) => void;+ /** The page's file, by its place in the project: a picture put in is named from its folder. */+ page: string;+ /** The project's pictures, by their place in the project. */+ pictures: () => Array<{ path: string; name: string }>;+ /** One from this computer, brought into the project: its place there (null: none picked). */+ pickPicture?: () => Promise<string | null>;+}++const PICTURE = /\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i;++/* a page clip off the picture is read again now and then: the playhead may come to it */+const OFF_PICTURE_EVERY_MS = 1500;++const isNamedColor = (v: string) => typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && CSS.supports('color', v);++export function TemplateSection({ host, commit }: {+ host: TemplateHost;+ /** Writes the clip's next overrides (null: none left). */+ commit: (next: FilmOverride[] | null) => void;+}) {+ const t = useT();+ const [controls, setControls] = React.useState<TemplateControls | null | undefined>(undefined);+ const overrides = host.overrides();+ const kept = JSON.stringify(overrides ?? []);+ React.useEffect(() => {+ let live = true;+ let timer = 0;+ const read = () => {+ void host.read().catch(() => null).then((next) => {+ if (!live) return;+ setControls((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));+ if (!next) timer = window.setTimeout(read, OFF_PICTURE_EVERY_MS);+ });+ };+ /* the picture shows a written change a moment after it is kept */+ timer = window.setTimeout(read, 120);+ return () => { live = false; window.clearTimeout(timer); };+ }, [host, kept]);++ if (controls === undefined) return null;+ if (controls && !controls.vars.length && !controls.texts.length && !controls.images?.length) return null;+ const setVar = (name: string, value: string | null) => commit(withVar(overrides, name, value));+ const setText = (at: string, n: number | undefined, value: string | null) => commit(withText(overrides, at, n, value));+ const setImage = (image: TemplateImage, path: string | null) => commit(withImage(overrides, image, path == null ? null : relativeTo(host.page, path)));++ return (+ <Section id="template" title={t('inspector.template')}>+ {!controls ? (+ <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.templateOffPicture')}</p>+ ) : (+ <>+ {controls.vars.map(({ name, value }) => (+ <Line key={name} label={labelOf(name)} title={name} changed={changedVar(overrides, name) != null} onReset={() => setVar(name, null)} t={t}>+ {isFontVar(name, value) ? (+ <FontInput+ label={labelOf(name)}+ value={value}+ onCommit={(next) => setVar(name, next)}+ onPreview={(next) => host.preview({ at: ROOT }, next == null ? null : { style: { [name]: next } })}+ />+ ) : (+ <VarInput+ name={name}+ field={fieldOf(value, isNamedColor)}+ onCommit={(next) => setVar(name, next)}+ onPreview={(next) => host.preview({ at: ROOT }, next == null ? null : { style: { [name]: next } })}+ />+ )}+ </Line>+ ))}+ {controls.texts.map(({ at, n, label, value }, i) => (+ <Line+ key={`${at}#${n ?? 0}`}+ label={label || `${t('inspector.templateText')} ${i + 1}`}+ title={n ? `${at} (${n})` : at}+ changed={changedText(overrides, at, n) != null}+ onReset={() => setText(at, n, null)}+ t={t}+ wide+ >+ <WordsInput+ value={value}+ label={label || `${t('inspector.templateText')} ${i + 1}`}+ onCommit={(next) => setText(at, n, next)}+ onPreview={(next) => host.preview({ at, ...(n ? { n } : {}) }, next == null ? null : { text: next })}+ />+ </Line>+ ))}+ {(controls.images ?? []).map((image, i) => {+ const label = image.label || `${t('inspector.templatePicture')} ${i + 1}`;+ const put = changedImage(overrides, image);+ /* what it draws now: the picture put in, read from the page's folder, else the page's own */+ const src = put != null && controls.page ? new URL(put, controls.page).href : image.src;+ return (+ <Line key={`${image.at}#${image.n ?? 0}`} label={label} title={image.n ? `${image.at} (${image.n})` : image.at} changed={put != null} onReset={() => setImage(image, null)} t={t}>+ <PictureInput src={src} host={host} label={label} onPick={(path) => setImage(image, path)} t={t} />+ </Line>+ );+ })}+ </>+ )}+ </Section>+ );+}++/** A picture: its thumbnail and name; clicked, the project's pictures and one from this computer; a picture dropped. */+function PictureInput({ src, host, label, onPick, t }: {+ src: string; host: TemplateHost; label: string; onPick: (path: string) => void; t: T;+}) {+ const [menu, setMenu] = React.useState<{ x: number; y: number } | null>(null);+ const [over, setOver] = React.useState(false);+ const name = decodeURIComponent(src.split(/[?#]/)[0]!.split('/').pop() ?? '');+ const entries = (): ContextMenuEntry[] => {+ const list = host.pictures().slice(0, 40);+ const pick = host.pickPicture;+ return [+ ...list.map((f) => ({ id: `pic:${f.path}`, label: f.name, onSelect: () => onPick(f.path) })),+ ...(pick ? [+ ...(list.length ? [{ id: 'pic-sep', separator: true as const }] : []),+ { id: 'pic-computer', label: t('inspector.templatePictureComputer'), icon: <HardDriveUpload size={14} />, onSelect: () => { void pick().then((path) => { if (path && PICTURE.test(path)) onPick(path); }); } },+ ] : []),+ ];+ };+ return (+ <>+ <button+ type="button"+ aria-label={`${label}: ${t('inspector.templatePictureReplace')}`}+ title={t('inspector.templatePictureReplace')}+ onClick={(e) => { const r = e.currentTarget.getBoundingClientRect(); setMenu({ x: r.left, y: r.bottom + 4 }); }}+ onDragOver={(e) => { if (e.dataTransfer.types.includes(RESOURCE_DRAG_TYPE)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; setOver(true); } }}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ setOver(false);+ const file = readResourceDragData(e.dataTransfer);+ if (!file || file.saved || !PICTURE.test(file.path)) return;+ e.preventDefault();+ onPick(file.path);+ }}+ className={`${FIELD} gap-1.5 px-1 text-left ${over ? 'ring-[1.5px] ring-[var(--accent)]' : ''}`}+ >+ <span className="flex h-[18px] w-[28px] shrink-0 items-center justify-center overflow-hidden rounded-[3px] bg-[var(--bg-hover)]">+ {src ? <img src={src} alt="" className="h-full w-full object-cover" draggable={false} /> : <ImageIcon size={12} />}+ </span>+ <span className="min-w-0 flex-1 truncate text-[11px] text-[var(--text)]">{name}</span>+ </button>+ {menu ? <ContextMenu x={menu.x} y={menu.y} items={entries()} onClose={() => setMenu(null)} /> : null}+ </>+ );+}++/** A custom property that names a font: the font picker over its first family, the fallbacks after it kept. */+function FontInput({ label, value, onCommit, onPreview }: {+ label: string; value: string; onCommit: (value: string) => void; onPreview: (value: string | null) => void;+}) {+ const [family, rest] = splitFontFamily(value);+ return (+ <FontFamilyPicker+ label={label}+ value={family}+ sample=""+ onPreview={(next) => onPreview(joinFontFamily(next, rest))}+ onRevert={() => onPreview(null)}+ onCommit={(next) => onCommit(joinFontFamily(next, rest))}+ className={FIELD}+ />+ );+}++/** A control: its name on the left (words above their box), its field, and going back to the page's own value. */+function Line({ label, title, changed, onReset, wide = false, t, children }: {+ label: string; title: string; changed: boolean; onReset: () => void; wide?: boolean; t: T; children: React.ReactNode;+}) {+ const reset = changed ? (+ <SectionAction label={t('inspector.templateReset')} onClick={onReset}><RotateCcw size={11} /></SectionAction>+ ) : <span className="w-5" />;+ const name = (+ <span className="min-w-0 truncate text-[11px] text-[var(--text-muted)]" title={title}>+ {changed ? <span aria-hidden className="mr-1 inline-block h-1.5 w-1.5 rounded-full bg-[var(--accent)] align-middle" /> : null}+ {label}+ </span>+ );+ if (wide) {+ return (+ <div className="flex flex-col gap-1">+ <div className="flex h-5 items-center justify-between gap-2">{name}{reset}</div>+ {children}+ </div>+ );+ }+ return (+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_20px] items-center gap-1.5">+ {name}+ <div className="min-w-0">{children}</div>+ {reset}+ </div>+ );+}++/** A custom property's field by its kind: a color, a number with its unit, or words. */+function VarInput({ name, field, onCommit, onPreview }: {+ name: string;+ field: VarField;+ onCommit: (value: string) => void;+ onPreview: (value: string | null) => void;+}) {+ const label = labelOf(name);+ if (field.kind === 'color') {+ return <ColorField label={label} value={field.value} onCommit={onCommit} onPreview={onPreview} />;+ }+ if (field.kind === 'number') {+ const step = Number.isInteger(field.value) && Math.abs(field.value) >= 2 ? 1 : 0.1;+ return (+ <NumField+ label={label}+ bare+ value={field.value}+ step={step}+ {...(field.unit ? { unit: field.unit } : {})}+ onCommit={(n) => onCommit(valueOf({ ...field, value: n }))}+ onPreview={(n) => onPreview(valueOf({ ...field, value: n }))}+ onRevert={() => onPreview(null)}+ />+ );+ }+ return (+ <TypedInput+ label={label}+ value={field.value}+ onCommit={(v) => onCommit(valueOf({ ...field, value: v }))}+ />+ );+}++/** One line typed and kept when left or on Enter; Esc gives up. */+function TypedInput({ label, value, onCommit }: { label: string; value: string; onCommit: (value: string) => void }) {+ const [raw, setRaw] = React.useState(value);+ React.useEffect(() => setRaw(value), [value]);+ const cancelled = React.useRef(false);+ return (+ <div className={FIELD}>+ <input+ aria-label={label}+ value={raw}+ spellCheck={false}+ onChange={(e) => setRaw(e.target.value)}+ onBlur={() => {+ if (cancelled.current) { cancelled.current = false; return; }+ if (raw.trim() && raw !== value) onCommit(raw);+ else setRaw(value);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.nativeEvent.isComposing) (e.target as HTMLInputElement).blur();+ if (e.key === 'Escape') { cancelled.current = true; setRaw(value); (e.target as HTMLInputElement).blur(); }+ }}+ className={`${INPUT} pl-2`}+ />+ </div>+ );+}++/** A layer's words: the picture follows as they are typed, kept when left or on Enter (Shift+Enter: a new line). */+function WordsInput({ label, value, onCommit, onPreview }: {+ label: string;+ value: string;+ onCommit: (value: string) => void;+ onPreview: (value: string | null) => void;+}) {+ const [raw, setRaw] = React.useState(value);+ const typing = React.useRef(false);+ React.useEffect(() => { if (!typing.current) setRaw(value); }, [value]);+ const cancelled = React.useRef(false);+ return (+ <textarea+ aria-label={label}+ value={raw}+ rows={Math.min(4, Math.max(1, raw.split('\n').length))}+ onChange={(e) => { typing.current = true; setRaw(e.target.value); onPreview(e.target.value); }}+ onBlur={() => {+ typing.current = false;+ if (cancelled.current) { cancelled.current = false; return; }+ if (raw !== value) onCommit(raw);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); (e.target as HTMLTextAreaElement).blur(); }+ if (e.key === 'Escape') {+ cancelled.current = true;+ typing.current = false;+ setRaw(value);+ onPreview(null);+ (e.target as HTMLTextAreaElement).blur();+ }+ }}+ className="w-full resize-none rounded-[5px] bg-[var(--fill-tsp)] px-2 py-1 text-[11.5px] leading-[1.5] text-[var(--text)] outline-none ring-1 ring-inset ring-transparent transition hover:ring-[var(--border)] focus:bg-[var(--bg)] focus:ring-[1.5px] focus:ring-[var(--accent)]"+ />+ );+}diff --git a/packages/openfilm/studio/ui/src/components/UpdateButton.tsx b/packages/openfilm/studio/ui/src/components/UpdateButton.tsxindex d894772..cd68e3f 100644--- a/packages/openfilm/studio/ui/src/components/UpdateButton.tsx+++ b/packages/openfilm/studio/ui/src/components/UpdateButton.tsx@@ -1,12 +1,16 @@/**- * The app's update in Studio's top bar, beside the projects button (an app with updates: lib/host.ts `update`): once a- * new version is downloaded, Restart to install it. Refused while an agent works or Studio exports, it says why beside- * it and stays, ready; quitting installs it too.+ * The update in Studio's top bar, beside the projects button. The app's (lib/host.ts `update`): once a new version is+ * downloaded, Restart to install it; refused while an agent works or Studio exports, it says why beside it and stays,+ * ready; quitting installs it too. Studio run with npm (WebUpdateButton): a newer openfilm on npm is offered, and Update+ * runs it in the background; Studio starts again on it and the page reloads.*/+import { useCallback, useEffect, useState } from 'react';import { CircleArrowDown, Loader2 } from 'lucide-react';import { useT } from '@/i18n';-import { useHostUpdate } from '../lib/host';+import { ApiError, api } from '../api';+import { studioHost, useHostUpdate } from '../lib/host';+import { refusedUpdate, webUpdateOf, type WebUpdate } from '../lib/web-update';import { Tooltip } from './Tooltip';const WAITING = { 'agent-busy': 'update.agentBusy', exporting: 'update.exporting', 'install-failed': 'update.installFailed' } as const;@@ -39,3 +43,62 @@ export function UpdateButton() {</>);}++/* looked at as the page opens and every few hours (Studio asks npm at most daily); while updating, every two seconds */+const LOOK_MS = 6 * 3_600_000;+const UPDATING_MS = 2000;++/**+ * The newest openfilm for a Studio run with npm (none in the app, which updates itself, nor in a source checkout), and+ * `start` to update to it. Shared by the top bar and Settings → About.+ */+export function useWebUpdate(): { update: WebUpdate | null; start: () => void } {+ const [update, setUpdate] = useState<WebUpdate | null>(null);+ const look = useCallback(() => { void api.version().then((v) => setUpdate(webUpdateOf(v))).catch(() => {}); }, []);+ const updating = update?.status === 'updating';+ useEffect(() => {+ if (studioHost) return undefined;+ if (!updating) look();+ const timer = setInterval(look, updating ? UPDATING_MS : LOOK_MS);+ return () => clearInterval(timer);+ }, [look, updating]);+ const start = useCallback(() => {+ if (!update || update.status === 'updating') return;+ const { version } = update;+ setUpdate({ status: 'updating', version });+ void api.update().catch((e: unknown) => setUpdate(e instanceof ApiError+ ? refusedUpdate(version, e.body.code, e.message)+ : { status: 'failed', version, error: e instanceof Error ? e.message : String(e) }));+ }, [update]);+ return { update, start };+}++/** Studio run with npm: Update when npm has a newer openfilm, its progress, or why it waits or failed. */+export function WebUpdateButton() {+ const t = useT();+ const { update, start } = useWebUpdate();+ if (!update) return null;+ const words = (key: string) => t(key).replace('{version}', update.version);+ if (update.status === 'updating') {+ return (+ <span role="status" className="flex h-[26px] shrink-0 items-center gap-1.5 rounded-md px-2 text-[12px] text-[var(--text-dim)]">+ <Loader2 size={13} className="animate-spin" />+ {t('update.webUpdating')}+ </span>+ );+ }+ const said = update.status === 'waiting' ? t(update.reason === 'exporting' ? 'update.webExporting' : 'update.webMaking')+ : update.status === 'failed' ? t('update.webFailed').replace('{error}', update.error) : null;+ return (+ <>+ <Tooltip label={said ?? words('update.webAvailable')} side="bottom">+ <button type="button" onClick={start}+ className="flex h-[26px] shrink-0 items-center gap-1.5 rounded-md bg-[var(--accent-soft)] px-2 text-[12px] font-medium text-[var(--accent)] transition hover:brightness-110">+ <CircleArrowDown size={14} />+ {t('update.webUpdate')}+ </button>+ </Tooltip>+ {said ? <span role="status" className="min-w-0 truncate text-[12px] text-[var(--text-dim)]">{said}</span> : null}+ </>+ );+}diff --git a/packages/openfilm/studio/ui/src/components/export/ExportTray.tsx b/packages/openfilm/studio/ui/src/components/export/ExportTray.tsxindex 9d82191..0555a6b 100644--- a/packages/openfilm/studio/ui/src/components/export/ExportTray.tsx+++ b/packages/openfilm/studio/ui/src/components/export/ExportTray.tsx@@ -10,6 +10,7 @@ import React from 'react';import { projectEvents, studioConnection } from '@/api';import { useT } from '@/i18n';+import { studioHost } from '@/lib/host';import {basenameOf,cancelExport,@@ -56,6 +57,11 @@ export const ExportTray = React.forwardRef<ExportTrayHandle, { projectId: stringvoid cancelExport(projectId, job.id).catch(() => setCancelAsked((s) => { const next = new Set(s); next.delete(job.id); return next; }));};+ /* in an app with tabs: this project's tab shows how far its exports have got (none running: nothing) */+ const running = jobs.filter(jobIsActive);+ const share = running.length ? Math.floor((running.reduce((sum, j) => sum + (j.progress ?? 0), 0) / running.length) * 100) / 100 : null;+ React.useEffect(() => { studioHost?.tabs?.report({ exporting: share }); }, [share]);+const merge = React.useCallback((incoming: readonly ExportJob[]) => {setJobs((prev) => {/* an export can end before the answer that queued it arrives (a subtitle file takes milliseconds): an endeddiff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsxindex 7d4c20d..e847d3d 100644--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx@@ -9,13 +9,17 @@* 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.+ * One not found, or one disconnected, 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). A connected one keeps the program it found. "Why isn't+ * it found?" says what was searched, with a report to copy.+ *+ * Under a connected agent: the skills and the MCP servers the person added to it themselves, each off in the app until+ * let in (its maker's own are always on).*/import React from 'react';-import { Check, Copy, Download, KeyRound, Loader2, X } from 'lucide-react';+import { Check, Copy, Download, KeyRound, Loader2, Plus, X } from 'lucide-react';import { useLanguage, useT } from '@/i18n';-import { BYOK_EFFORTS, studioHost, type HostAgent, type HostAgentDiagnosis, type HostAgentId, type HostAgentUsage, type HostByokEffort, type HostByokEffortLevel, type HostByokFormat } from '@/lib/host';+import { BYOK_EFFORTS, studioHost, type HostAgent, type HostAgentDiagnosis, type HostAgentId, type HostAgentUsage, type HostByokEffort, type HostByokEffortLevel, type HostByokFormat, type HostOwnModel } 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'];@@ -180,21 +184,11 @@ export function AgentsSection() {const action = (agent: HostAgent, chosen = true) => {const working = busy === agent.id;if (agent.status === 'ready' && chosen) {- /* the program can be pointed at even when one was found: a particular version, another install; byok has none */- const canLocate = host.locate && agent.id !== 'byok';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}- <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>- </>+ <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') {@@ -215,17 +209,29 @@ export function AgentsSection() {if (agent.status === 'key') return <SettingsButton onClick={() => setKeyOpen(true)}>{t('settings.agents.setUpKey')}</SettingsButton>;if (agent.status === 'unavailable') return null;if (agent.status === 'checking') return <Loader2 size={16} className="animate-spin text-[var(--text-muted)]" aria-hidden />;+ /* disconnected: the program it runs can be pointed at before connecting again (a particular version, another+ install); a connected one keeps the program it found. The own key has none */+ const canLocate = agent.status === 'off' && host.locate && agent.id !== 'byok';return (- <SettingsButton disabled={working || agent.status === 'waiting'} onClick={() => act(agent.id, () => host.connect(agent.id))}>- {working ? <Loader2 size={16} className="animate-spin" aria-hidden /> : null}- {agent.status === 'sign-in' ? t('settings.agents.signIn') : t('settings.agents.connect')}- </SettingsButton>+ <>+ {canLocate ? (+ <SettingsButton variant="quiet" disabled={working} onClick={() => locate(agent)}>+ {t('settings.agents.locate')}+ </SettingsButton>+ ) : null}+ <SettingsButton disabled={working || agent.status === 'waiting'} onClick={() => act(agent.id, () => host.connect(agent.id))}>+ {working ? <Loader2 size={16} className="animate-spin" aria-hidden /> : null}+ {agent.status === 'sign-in' ? t('settings.agents.signIn') : t('settings.agents.connect')}+ </SettingsButton>+ </>);};const row = (agent: HostAgent, chosen = true) => {const ownKey = agent.id === 'byok' && agent.byok;- const said = error?.id === agent.id ? error.text : agent.error;+ /* found, but it cannot read its own settings, so no session starts: what it says, to fix in its config file */+ const problem = agent.status === 'ready' && agent.problem ? agent.problem : null;+ const said = error?.id === agent.id ? error.text : agent.error ?? (problem ? `${t('settings.agents.unreadable')} ${problem}` : undefined);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);@@ -248,7 +254,7 @@ export function AgentsSection() {{t('settings.agents.recommended')}</span>) : null}- {agent.status === 'ready' && chosen ? <SettingsStatus>{ownKey ? `${byokModels(agent).join(', ')} · •••• ${agent.byok!.last4}` : t('settings.agents.ready')}</SettingsStatus> : null}+ {agent.status === 'ready' && chosen && !problem ? <SettingsStatus>{ownKey ? agent.byok!.models.map((m) => m.name).join(', ') : t('settings.agents.ready')}</SettingsStatus> : null}</>)}description={agent.status === 'ready' ? accountLine(agent) : statusLine(agent)}@@ -261,7 +267,7 @@ export function AgentsSection() {</>)}>- {agent.status === 'waiting' || open || said || agent.chosen || lost || meter ? (+ {agent.status === 'waiting' || open || said || agent.chosen || lost || meter || (chosen && agent.status === 'ready' && (host.mcp || host.skills)) ? (<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')}>@@ -270,6 +276,8 @@ export function AgentsSection() {) : plan?.windows.map((w) => <UsageBar key={w.kind + (w.minutes ?? '')} window={w} />)}</div>) : null}+ {chosen && agent.status === 'ready' && host.skills ? <AgentOwn agent={agent} kind="skills" /> : null}+ {chosen && agent.status === 'ready' && host.mcp ? <AgentOwn agent={agent} kind="mcp" /> : null}{agent.chosen ? (<p className="break-all text-[13.5px] leading-relaxed text-[var(--text-muted)]">{t('settings.agents.chosenAt').replace('{path}', agent.chosen)}{' '}@@ -305,7 +313,7 @@ export function AgentsSection() {<button type="button" onClick={() => act(agent.id, () => host.connect(agent.id))} className="underline underline-offset-2 hover:text-[var(--text)]">{t('settings.agents.startAgain')}</button></p>) : null}- {open ? <ByokForm agent={agent} onDone={() => setKeyOpen(false)} /> : null}+ {open ? <OwnModels agent={agent} onDone={() => setKeyOpen(false)} /> : null}{said ? <p className={settingsError}>{said}</p> : null}</div>) : null}@@ -329,6 +337,62 @@ export function AgentsSection() {);}+/**+ * What the person added to an agent themselves, its skills or its MCP servers: how many are used in the app, and on+ * asking, a switch for each (its maker's own are always on). An agent that cannot be told says it uses them all.+ * None: nothing shown.+ */+function AgentOwn({ agent, kind }: { agent: HostAgent; kind: 'skills' | 'mcp' }) {+ const t = useT();+ const host = studioHost?.agents;+ type Item = { name: string; detail: string; allowed: boolean };+ const [listing, setListing] = React.useState<{ filtered: boolean; items: Item[] } | null>(null);+ const [open, setOpen] = React.useState(false);+ const load = React.useCallback(() => {+ const read = kind === 'skills'+ ? host?.skills?.(agent.id).then((r) => ({ filtered: r.filtered, items: r.skills.map((s) => ({ name: s.name, detail: s.description, allowed: s.allowed })) }))+ : host?.mcp?.(agent.id).then((r) => ({ filtered: r.filtered, items: r.servers }));+ void read?.then(setListing).catch(() => {});+ }, [host, agent.id, kind]);+ React.useEffect(load, [load]);+ const allowIt = kind === 'skills' ? host?.allowSkill : host?.allowMcp;+ if (!allowIt || !listing?.items.length) return null;+ const name = agent.id === 'byok' ? t('settings.agents.byokName') : agent.name;+ const key = (k: string) => t(`settings.agents.${kind}${k}`);+ if (!listing.filtered) {+ return <p className="text-[13.5px] leading-relaxed text-[var(--text-muted)]">{key('Unfiltered').replace('{agent}', name).replace('{n}', String(listing.items.length))}</p>;+ }+ const on = listing.items.filter((i) => i.allowed).length;+ const allow = (item: string, allowed: boolean) => {+ setListing((l) => (l ? { ...l, items: l.items.map((i) => (i.name === item ? { ...i, allowed } : i)) } : l));+ void allowIt(agent.id, item, allowed).finally(load);+ };+ return (+ <div className="flex flex-col gap-2">+ <p className="text-[13.5px] leading-relaxed text-[var(--text-muted)]">+ {key('Summary').replace('{n}', String(listing.items.length)).replace('{on}', String(on))}{' '}+ <button type="button" onClick={() => setOpen((o) => !o)} className="underline underline-offset-2 hover:text-[var(--text)]">+ {open ? t('settings.agents.mcpDone') : t('settings.agents.mcpManage')}+ </button>+ </p>+ {open ? (+ <SettingsInset>+ <p className="text-[13px] leading-relaxed text-[var(--text-faint)]">{key('Note').replaceAll('{agent}', name)}</p>+ {listing.items.map((item) => (+ <div key={item.name} className="flex items-center gap-3">+ <div className="min-w-0 flex-1">+ <div className="truncate text-[14px] text-[var(--text)]">{item.name}</div>+ {item.detail ? <div className="line-clamp-2 text-[12.5px] leading-snug text-[var(--text-faint)]">{item.detail}</div> : null}+ </div>+ <SettingsSwitch checked={item.allowed} label={key('Allow').replace('{name}', item.name)} onChange={(v) => allow(item.name, v)} />+ </div>+ ))}+ </SettingsInset>+ ) : null}+ </div>+ );+}+/** Each API format and the address it starts with. */const FORMATS: ReadonlyArray<{ value: HostByokFormat; label: string; address: string }> = [{ value: 'responses', label: 'OpenAI Responses', address: 'https://api.openai.com/v1' },@@ -336,143 +400,167 @@ const FORMATS: ReadonlyArray<{ value: HostByokFormat; label: string; address: st{ value: 'anthropic', label: 'Anthropic Messages', address: 'https://api.anthropic.com' },];-/** The own key's models, the first one the chat begins with. */-const byokModels = (agent: HostAgent) => (agent.byok?.models?.length ? agent.byok.models : [agent.byok?.model ?? ''].filter(Boolean));--/** Model names typed in one field, separated by commas or new lines: trimmed, each once. */-const modelNames = (text: string) => [...new Set(text.split(/[,\n]/).map((m) => m.trim()).filter(Boolean))];+/** Where a service is, for a model's line: its host, or the address as typed when it is not one. */+const hostOf = (address: string) => { try { return new URL(address).host; } catch { return address; } };-/** A model of the own key, with the efforts it offers and the one it starts on; a new one offers Auto alone. */-interface ByokModelRow extends HostByokEffort { name: string }-const byokRows = (agent: HostAgent): ByokModelRow[] =>- byokModels(agent).map((name) => ({ name, ...(agent.byok?.efforts?.[name] ?? { levels: ['auto'], effort: 'auto' }) }));+/** An address as kept: trimmed, no trailing slash (the roster keeps it so). */+const addressKey = (address: string) => address.trim().replace(/\/+$/, '');/**- * One model of the own key: its name, the efforts it takes (each a toggle, at least one on) and, when it takes more than- * one, the one a conversation starts on.+ * The own key's models, each set up on its own: a line each (its name; the model at its service, where, its key) to+ * change or remove, and one to add. The form takes a line's place while it is changed. With none yet, the form opens.*/-function ByokModel({ row, onChange, onRemove }: { row: ByokModelRow; onChange: (row: ByokModelRow) => void; onRemove: () => void }) {+function OwnModels({ agent, onDone }: { agent: HostAgent; onDone: () => void }) {const t = useT();- const name = (level: HostByokEffortLevel) => t(`settings.agents.effortLevels.${level}`);- const toggle = (level: HostByokEffortLevel) => {- const on = row.levels.includes(level);- if (on && row.levels.length === 1) return;- const levels = BYOK_EFFORTS.filter((l) => (l === level ? !on : row.levels.includes(l)));- onChange({ ...row, levels, effort: levels.includes(row.effort) ? row.effort : levels[0]! });- };+ const host = studioHost?.agents;+ const models = agent.byok?.models ?? [];+ /* the model being changed, 'new' for one being added, null for none */+ const [editing, setEditing] = React.useState<string | null>(models.length ? null : 'new');+ const level = (l: HostByokEffortLevel) => t(`settings.agents.effortLevels.${l}`);return (- <div className="flex flex-col gap-2 rounded-[8px] border border-[var(--border)] px-3 py-2.5">- <div className="flex min-h-8 items-center gap-2">- <span className="min-w-0 flex-1 truncate font-mono text-[13.5px] text-[var(--text)]" title={row.name}>{row.name}</span>- {row.levels.length > 1 ? (- <>- <span className="shrink-0 text-[13px] text-[var(--text-muted)]">{t('settings.agents.effortStart')}</span>- <SettingsSelect<HostByokEffortLevel> label={t('settings.agents.effortStart')} value={row.effort} width={128}- onChange={(effort) => onChange({ ...row, effort })} options={row.levels.map((l) => ({ value: l, label: name(l) }))} />- </>- ) : null}- <button type="button" onClick={onRemove} aria-label={t('settings.agents.removeModel').replace('{name}', row.name)} title={t('settings.agents.removeModel').replace('{name}', row.name)}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-[6px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">- <X size={14} aria-hidden />- </button>- </div>- <div role="group" aria-label={`${t('settings.agents.efforts')} · ${row.name}`} className="flex flex-wrap items-center gap-1">- {BYOK_EFFORTS.map((level) => {- const on = row.levels.includes(level);- return (- <button key={level} type="button" aria-pressed={on} onClick={() => toggle(level)}- className={`inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-[12.5px] transition ${- on ? 'border-[var(--text-muted)] bg-[var(--fill-tsp)] text-[var(--text)]' : 'border-[var(--border)] text-[var(--text-muted)] hover:border-[var(--border-strong)] hover:text-[var(--text)]'- }`}>- {on ? <Check size={12} aria-hidden /> : null}- {name(level)}+ <SettingsInset>+ {models.map((m) => (editing === m.id+ ? <OwnModelForm key={m.id} model={m} models={models} onDone={() => setEditing(null)} />+ : (+ <div key={m.id} className="flex min-h-12 items-center gap-2 rounded-[8px] border border-[var(--border)] px-3 py-2">+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-[14px] text-[var(--text)]" title={m.name}>{m.name}</span>+ <span className="truncate text-[12.5px] text-[var(--text-muted)]">+ <span className="font-mono">{m.model}</span>{` · ${hostOf(m.baseUrl)} · •••• ${m.last4}`}+ {m.levels.length > 1 ? ` · ${m.levels.map(level).join(' / ')}` : ''}+ </span>+ </div>+ <SettingsButton variant="quiet" disabled={editing !== null} onClick={() => setEditing(m.id)}>{t('settings.agents.edit')}</SettingsButton>+ <button type="button" disabled={editing !== null} onClick={() => void host?.removeOwnModel(m.id)}+ aria-label={t('settings.agents.removeModel').replace('{name}', m.name)} title={t('settings.agents.removeModel').replace('{name}', m.name)}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-[6px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40">+ <X size={14} aria-hidden /></button>- );- })}- </div>- </div>+ </div>+ )))}+ {editing === 'new' ? <OwnModelForm models={models} onDone={() => (models.length ? setEditing(null) : onDone())} /> : null}+ {editing === null ? (+ <div className="flex items-center justify-between gap-2">+ <SettingsButton onClick={() => setEditing('new')}><Plus size={15} aria-hidden />{t('settings.agents.addModel')}</SettingsButton>+ <SettingsButton variant="quiet" onClick={onDone}>{t('settings.agents.done')}</SettingsButton>+ </div>+ ) : null}+ <p className="text-[13px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.byokNote')}</p>+ </SettingsInset>);}/**- * The person's own key: the API format, its address (the official one, or any service that speaks it), the models (the- * chat's menu switches between them) and the key. Checked before it is kept.+ * One own model, set up or changed: its name (the model, when empty), the API format, the service's address, the+ * model asked for there, the key (left empty: its own, or another model's on the same address), and the efforts it+ * takes (each a toggle, at least one on) with the one a conversation starts on. Checked before it is kept.*/-function ByokForm({ agent, onDone }: { agent: HostAgent; onDone: () => void }) {+function OwnModelForm({ model, models, onDone }: { model?: HostOwnModel; models: HostOwnModel[]; onDone: () => void }) {const t = useT();const host = studioHost?.agents;- const [format, setFormat] = React.useState<HostByokFormat>(agent.byok?.format ?? 'responses');+ const [name, setName] = React.useState(model?.name ?? '');+ const [format, setFormat] = React.useState<HostByokFormat>(model?.format ?? 'responses');const official = FORMATS.find((f) => f.value === format)!;- const [baseUrl, setBaseUrl] = React.useState(agent.byok?.baseUrl ?? official.address);- const [rows, setRows] = React.useState<ByokModelRow[]>(() => byokRows(agent));- const [draft, setDraft] = React.useState('');- /* names typed (several at once, separated by commas, as before), each added once, offering Auto alone */- const addModels = () => {- const names = modelNames(draft).filter((name) => !rows.some((r) => r.name === name));- if (names.length) setRows((list) => [...list, ...names.map((name): ByokModelRow => ({ name, levels: ['auto'], effort: 'auto' }))]);- setDraft('');- };- /* what is kept: a name still in the field counts as added */- const named = () => [...rows, ...modelNames(draft).filter((name) => !rows.some((r) => r.name === name)).map((name): ByokModelRow => ({ name, levels: ['auto'], effort: 'auto' }))];+ const [baseUrl, setBaseUrl] = React.useState(model?.baseUrl ?? official.address);+ const [modelId, setModelId] = React.useState(model?.model ?? '');const [key, setKey] = React.useState('');+ const [effort, setEffort] = React.useState<HostByokEffort>({ levels: model?.levels ?? ['auto'], effort: model?.effort ?? 'auto' });const [state, setState] = React.useState<{ busy: boolean; error: string | null }>({ busy: false, error: null });+ /* another model on this address, whose key an empty field takes */+ const sameService = models.find((m) => m.id !== model?.id && addressKey(m.baseUrl) === addressKey(baseUrl));/* another format: its official address, unless the person typed one of their own */const pickFormat = (next: HostByokFormat) => {if (FORMATS.some((f) => f.address === baseUrl.trim()) || !baseUrl.trim()) setBaseUrl(FORMATS.find((f) => f.value === next)!.address);setFormat(next);};+ const ready = modelId.trim() && baseUrl.trim() && (key.trim() || model || sameService);const save = () => {- if (!host) return;+ if (!host || !ready) return;setState({ busy: true, error: null });- const kept = named();- void host.configureByok({ format, baseUrl, models: kept.map((r) => r.name), efforts: Object.fromEntries(kept.map((r) => [r.name, { levels: r.levels, effort: r.effort }])), ...(key ? { key } : {}) })- .then((r) => { if (r.ok) { setKey(''); setDraft(''); setState({ busy: false, error: null }); onDone(); } else setState({ busy: false, error: r.error ?? t('settings.agents.failed') }); })+ void host.saveOwnModel({ ...(model ? { id: model.id } : {}), name, format, baseUrl, model: modelId, ...(key.trim() ? { key } : {}), levels: effort.levels, effort: effort.effort })+ .then((r) => { if (r.ok) onDone(); else setState({ busy: false, error: r.error || t('settings.agents.failed') }); }).catch((e: unknown) => setState({ busy: false, error: e instanceof Error ? e.message : String(e) }));};- const ready = named().length > 0 && baseUrl.trim() && (key.trim() || agent.byok);+ const keyHint = model ? t('settings.agents.keyKept').replace('{last4}', model.last4)+ : sameService ? t('settings.agents.keySame').replace('{name}', sameService.name) : t('settings.agents.keyPlaceholder');const label = (text: string) => <span className="w-[92px] shrink-0 text-[13px] text-[var(--text-muted)]">{text}</span>;return (- <SettingsInset>- <form className="contents" onSubmit={(e) => { e.preventDefault(); if (ready && !state.busy) save(); }}>- <div className="flex items-center gap-2">- {label(t('settings.agents.format'))}- <SettingsSelect<HostByokFormat> label={t('settings.agents.format')} value={format} onChange={pickFormat} width={220}- options={FORMATS.map((f) => ({ value: f.value, label: f.label }))} />- </div>- <div className="flex items-center gap-2">- {label(t('settings.agents.address'))}- <SettingsField value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={official.address} aria-label={t('settings.agents.address')} spellCheck={false} />- </div>- <div className="flex items-start gap-2">- <span className="flex h-10 items-center">{label(t('settings.agents.model'))}</span>- <div className="flex min-w-0 flex-1 flex-col gap-2">- {rows.map((row) => (- <ByokModel key={row.name} row={row} onChange={(next) => setRows((list) => list.map((r) => (r.name === row.name ? next : r)))}- onRemove={() => setRows((list) => list.filter((r) => r.name !== row.name))} />- ))}- <div className="flex items-center gap-2">- <SettingsField value={draft} onChange={(e) => setDraft(e.target.value)} placeholder={t('settings.agents.modelPlaceholder')} aria-label={t('settings.agents.model')} spellCheck={false}- onKeyDown={(e) => { if (e.key === 'Enter' && draft.trim()) { e.preventDefault(); addModels(); } }} />- <SettingsButton onClick={addModels} disabled={!draft.trim()}>{t('settings.agents.addModel')}</SettingsButton>- </div>- {rows.length ? <p className="text-[12.5px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.effortHint')}</p> : null}- </div>+ <form className="flex flex-col gap-2.5 rounded-[8px] border border-[var(--border-strong)] p-3" onSubmit={(e) => { e.preventDefault(); if (!state.busy) save(); }}>+ <div className="flex items-center gap-2">+ {label(t('settings.agents.name'))}+ <SettingsField value={name} onChange={(e) => setName(e.target.value)} placeholder={t('settings.agents.namePlaceholder')} aria-label={t('settings.agents.name')} />+ </div>+ <div className="flex items-center gap-2">+ {label(t('settings.agents.format'))}+ <SettingsSelect<HostByokFormat> label={t('settings.agents.format')} value={format} onChange={pickFormat} width={220}+ options={FORMATS.map((f) => ({ value: f.value, label: f.label }))} />+ </div>+ <div className="flex items-center gap-2">+ {label(t('settings.agents.address'))}+ <SettingsField value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={official.address} aria-label={t('settings.agents.address')} spellCheck={false} />+ </div>+ <div className="flex items-center gap-2">+ {label(t('settings.agents.model'))}+ <SettingsField value={modelId} onChange={(e) => setModelId(e.target.value)} placeholder={t('settings.agents.modelPlaceholder')} aria-label={t('settings.agents.model')}+ className="font-mono placeholder:font-sans" spellCheck={false} />+ </div>+ <div className="flex items-center gap-2">+ {label(t('settings.agents.key'))}+ <SettingsField type="password" value={key} onChange={(e) => setKey(e.target.value)} autoComplete="off" className="font-mono placeholder:font-sans"+ placeholder={keyHint} aria-label={t('settings.agents.key')} />+ </div>+ <div className="flex items-start gap-2">+ <span className="flex h-8 items-center">{label(t('settings.agents.efforts'))}</span>+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <EffortPicker value={effort} onChange={setEffort} />+ <p className="text-[12.5px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.effortHint')}</p></div>+ </div>+ {state.error ? <p className={settingsError}>{state.error}</p> : null}+ <div className="flex justify-end gap-1.5">+ <SettingsButton variant="quiet" onClick={onDone}>{t('settings.agents.cancel')}</SettingsButton>+ <SettingsButton type="submit" variant="primary" disabled={state.busy || !ready}>+ {state.busy ? <Loader2 size={15} className="animate-spin" aria-hidden /> : null}+ {state.busy ? t('settings.agents.checkingKey') : t('settings.agents.save')}+ </SettingsButton>+ </div>+ </form>+ );+}++/** The efforts a model takes (each a toggle, at least one on) and, when it takes more than one, the one it starts on. */+function EffortPicker({ value, onChange }: { value: HostByokEffort; onChange: (value: HostByokEffort) => void }) {+ const t = useT();+ const name = (level: HostByokEffortLevel) => t(`settings.agents.effortLevels.${level}`);+ const toggle = (level: HostByokEffortLevel) => {+ const on = value.levels.includes(level);+ if (on && value.levels.length === 1) return;+ const levels = BYOK_EFFORTS.filter((l) => (l === level ? !on : value.levels.includes(l)));+ onChange({ levels, effort: levels.includes(value.effort) ? value.effort : levels[0]! });+ };+ return (+ <>+ <div role="group" aria-label={t('settings.agents.efforts')} className="flex flex-wrap items-center gap-1">+ {BYOK_EFFORTS.map((level) => {+ const on = value.levels.includes(level);+ return (+ <button key={level} type="button" aria-pressed={on} onClick={() => toggle(level)}+ className={`inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-[12.5px] transition ${+ on ? 'border-[var(--text-muted)] bg-[var(--fill-tsp)] text-[var(--text)]' : 'border-[var(--border)] text-[var(--text-muted)] hover:border-[var(--border-strong)] hover:text-[var(--text)]'+ }`}>+ {on ? <Check size={12} aria-hidden /> : null}+ {name(level)}+ </button>+ );+ })}+ </div>+ {value.levels.length > 1 ? (<div className="flex items-center gap-2">- {label(t('settings.agents.key'))}- <SettingsField type="password" value={key} onChange={(e) => setKey(e.target.value)} autoComplete="off" className="font-mono placeholder:font-sans"- placeholder={agent.byok ? t('settings.agents.keyKept').replace('{last4}', agent.byok.last4) : t('settings.agents.keyPlaceholder')} aria-label={t('settings.agents.key')} />+ <span className="shrink-0 text-[13px] text-[var(--text-muted)]">{t('settings.agents.effortStart')}</span>+ <SettingsSelect<HostByokEffortLevel> label={t('settings.agents.effortStart')} value={value.effort} width={128}+ onChange={(effort) => onChange({ ...value, effort })} options={value.levels.map((l) => ({ value: l, label: name(l) }))} /></div>- <p className="text-[13px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.byokNote')}</p>- {state.error ? <p className={settingsError}>{state.error}</p> : null}- <div className="flex justify-end gap-1.5">- <SettingsButton variant="quiet" onClick={onDone}>{t('settings.agents.cancel')}</SettingsButton>- <SettingsButton type="submit" variant="primary" disabled={state.busy || !ready}>- {state.busy ? <Loader2 size={15} className="animate-spin" aria-hidden /> : null}- {state.busy ? t('settings.agents.checkingKey') : t('settings.agents.save')}- </SettingsButton>- </div>- </form>- </SettingsInset>+ ) : null}+ </>);}diff --git a/packages/openfilm/studio/ui/src/components/settings/CustomServices.tsx b/packages/openfilm/studio/ui/src/components/settings/CustomServices.tsxnew file mode 100644index 0000000..6eb6cfa--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/settings/CustomServices.tsx@@ -0,0 +1,104 @@+/**+ * Settings → Services, under which service makes each kind of media: the person's custom services. Any service at an+ * address (one they run on this computer, their own voice, an API not listed), with its key and their words on what it+ * does and how it is called (or where its docs are). OpenFilm does not call one itself: their agent reads those words+ * in `openfilm get` and calls it with `openfilm get call` (studio/server/custom-services.mjs).+ */+import React from 'react';+import { Plus, Server } from 'lucide-react';+import { useT } from '@/i18n';+import type { OwnService, OwnServiceFields, ProvidersHook } from '@/lib/providers';+import { SettingsButton, SettingsField, SettingsGroup, SettingsInset, SettingsItem, SettingsStatus, settingsError, settingsLink } from './ui';++/** Whether the last change that failed was to one of the person's own services (it is said under its form). */+export const customProblem = (hook: ProvidersHook) => hook.problemFor === 'custom' || Boolean(hook.state?.custom.some((s) => s.id === hook.problemFor));++/** The person's own services: each with what it does and how it is called, and a form to add one. */+export function CustomServices({ hook }: { hook: ProvidersHook }) {+ const t = useT();+ const services = hook.state?.custom ?? [];+ const [open, setOpen] = React.useState<string | null>(null);+ if (!hook.state) return null;+ return (+ <SettingsGroup title={t('settings.providers.own.title')} footnote={t('settings.providers.own.note')}>+ {services.map((service) => (+ <SettingsItem+ key={service.id}+ mark={<Server size={16} />}+ title={service.name}+ badge={service.last4 ? <SettingsStatus tone="muted"><span className="font-mono tabular-nums">•••• {service.last4}</span></SettingsStatus> : null}+ description={(+ <>+ <span className="font-mono text-[13px] text-[var(--text-faint)]">{service.url}</span>+ {service.note ? <span className="mt-0.5 block whitespace-pre-line">{service.note}</span> : null}+ </>+ )}+ control={open === service.id ? null : (+ <>+ <SettingsButton variant="quiet" disabled={hook.busy === service.id} onClick={() => void hook.removeService(service.id)}>{t('settings.providers.own.remove')}</SettingsButton>+ <SettingsButton onClick={() => setOpen(service.id)}>{t('settings.providers.own.edit')}</SettingsButton>+ </>+ )}+ >+ {open === service.id ? <ServiceForm hook={hook} service={service} onDone={() => setOpen(null)} /> : null}+ </SettingsItem>+ ))}+ {open === '' ? (+ <div className="py-4"><ServiceForm hook={hook} service={null} onDone={() => setOpen(null)} /></div>+ ) : (+ <div className="py-4">+ <SettingsButton onClick={() => setOpen('')}><Plus size={15} strokeWidth={2} />{t('settings.providers.own.add')}</SettingsButton>+ </div>+ )}+ </SettingsGroup>+ );+}++/**+ * A service's name, address, key and what it does (how it is called, or its docs): added (`service` null) or changed.+ * Where the key goes is not asked: the agent writes {key} where the service's docs want it, else it goes as+ * `Authorization: Bearer` (a service set up when this was asked keeps its answer).+ */+function ServiceForm({ hook, service, onDone }: { hook: ProvidersHook; service: OwnService | null; onDone: () => void }) {+ const t = useT();+ const [fields, setFields] = React.useState<OwnServiceFields>({ name: service?.name ?? '', url: service?.url ?? '', note: service?.note ?? '' });+ const [key, setKey] = React.useState('');+ const [dropKey, setDropKey] = React.useState(false);+ const busy = hook.busy === (service?.id ?? 'custom');+ const set = (name: keyof OwnServiceFields) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setFields((f) => ({ ...f, [name]: e.target.value }));+ const save = async () => {+ if (busy || !fields.name.trim() || !fields.url.trim()) return;+ /* changed without a key typed: the one it has stays (unless taken away) */+ const sent: OwnServiceFields = { ...fields, ...(key.trim() ? { key: key.trim() } : dropKey || !service ? { key: '' } : {}) };+ if (await hook.saveService(service?.id ?? null, sent)) onDone();+ };+ const label = (text: string, field: React.ReactNode) => (+ <label className="flex flex-col gap-1.5 text-[13.5px] text-[var(--text-muted)]">{text}{field}</label>+ );+ return (+ /* under its row, it lines up with the row's words; a new one stands on its own */+ <form className={service ? 'pl-[52px]' : ''} onSubmit={(e) => { e.preventDefault(); void save(); }} onKeyDown={(e) => { if (e.key === 'Escape') { e.preventDefault(); onDone(); } }}>+ <SettingsInset>+ {label(t('settings.providers.own.name'), <SettingsField autoFocus value={fields.name} onChange={set('name')} placeholder={t('settings.providers.own.namePlaceholder')} />)}+ {label(t('settings.providers.own.url'), <SettingsField value={fields.url} onChange={set('url')} placeholder="http://localhost:8000" spellCheck={false} className="font-mono placeholder:font-sans" />)}+ {label(t('settings.providers.own.key'), (+ <SettingsField type="password" autoComplete="off" spellCheck={false} value={key} onChange={(e) => { setKey(e.target.value); setDropKey(false); }}+ placeholder={service?.last4 && !dropKey ? t('settings.providers.own.keyKeep').replaceAll('{last4}', service.last4) : t('settings.providers.own.keyOptional')}+ className="font-mono placeholder:font-sans" />+ ))}+ {service?.last4 && !key && !dropKey ? (+ <button type="button" className={`${settingsLink} self-start text-[13.5px]`} onClick={() => setDropKey(true)}>{t('settings.providers.own.removeKey')}</button>+ ) : null}+ {label(t('settings.providers.own.what'), (+ <textarea value={fields.note} onChange={set('note')} rows={4} maxLength={2000} placeholder={t('settings.providers.own.whatPlaceholder')}+ className="w-full min-w-0 resize-y rounded-[8px] border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] leading-[1.5] text-[var(--text)] outline-none transition placeholder:text-[var(--text-faint)] hover:border-[var(--border-strong)] focus:border-[var(--text-muted)]" />+ ))}+ {hook.problem && hook.problemFor === (service?.id ?? 'custom') ? <p className={settingsError} role="alert">{hook.problem}</p> : null}+ <div className="flex justify-end gap-2">+ <SettingsButton variant="quiet" onClick={onDone}>{t('settings.providers.cancel')}</SettingsButton>+ <SettingsButton type="submit" variant="primary" disabled={busy || !fields.name.trim() || !fields.url.trim()}>{t('settings.providers.save')}</SettingsButton>+ </div>+ </SettingsInset>+ </form>+ );+}diff --git a/packages/openfilm/studio/ui/src/components/settings/ModelsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/ModelsSection.tsxindex 3a0a366..2b211e2 100644--- a/packages/openfilm/studio/ui/src/components/settings/ModelsSection.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/ModelsSection.tsx@@ -1,7 +1,8 @@/**- * Settings → Models: which connected provider, and which of its models, makes each kind of media. One of the models of- * a provider the person has a key for ("ElevenLabs · Eleven v3"), or none, listed by the providers' names, none put- * first. Connecting a provider fills the kinds that have none, with its first model; the person changes any here. Any other service is the agent's to use, told about it in the chat.+ * Settings → Services: which connected provider, and which of its models, makes each kind of media. One of the models+ * of a provider the person has a key for ("ElevenLabs · Eleven v3"), or none, listed by the providers' names, none put+ * first. Connecting a provider fills the kinds that have none, with its first model; the person changes any here.+ * Under them, the person's custom services, which their agent calls itself (CustomServices).*/import React from 'react';import { Check, ChevronDown, ChevronRight } from 'lucide-react';@@ -10,6 +11,7 @@ import { USE_VERBS, couldMake, offered, useProviders, type ProviderVerb, type Primport { Popover } from '@/components/Popover';import { ProviderMark } from './ProviderMark';import { SettingsButton, SettingsGroup, SettingsItem, SettingsPage, settingsError } from './ui';+import { CustomServices, customProblem } from './CustomServices';/** One thing a kind of media can be made with: a provider and its model. */interface Choice {@@ -35,11 +37,13 @@ export function ModelsSection({ onConnect }: { onConnect: () => void }) {</SettingsGroup>) : null}{providers ? (- <SettingsGroup footnote={t('settings.models.otherBody')}>+ <SettingsGroup>{USE_VERBS.filter((verb) => offered(providers, verb)).map((verb) => <ModelRow key={verb} verb={verb} hook={hook} onConnect={onConnect} />)}</SettingsGroup>) : null}- {hook.problem ? <p className={settingsError}>{hook.problem}</p> : null}+ <CustomServices hook={hook} />+ {/* a custom service's problem is said under its form */}+ {hook.problem && !customProblem(hook) ? <p className={settingsError}>{hook.problem}</p> : null}</SettingsPage>);}diff --git a/packages/openfilm/studio/ui/src/components/settings/ProvidersSection.tsx b/packages/openfilm/studio/ui/src/components/settings/ProvidersSection.tsxindex a0d03e1..c4e3183 100644--- a/packages/openfilm/studio/ui/src/components/settings/ProvidersSection.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/ProvidersSection.tsx@@ -4,16 +4,14 @@** ElevenLabs, OpenAI, Google Gemini, fal.ai, Groq, Pexels, Pixabay, Brave Search and Tavily connect with the person's* own key, which pays that service directly when it charges (a key in the environment shows as such and stays there).- * Which of them makes each kind of media, and with which model, is Settings → Models.- *- * Under them, the person's own services: any service at an address (one they run on this computer, their own voice,- * an API not listed), with its key and a few words about what it does. Their agent reaches each with `openfilm get- * call`; OpenFilm knows nothing of what it answers (studio/server/custom-services.mjs).+ * Which of them makes each kind of media, and with which model, is Settings → Services, with the person's own custom+ * services (CustomServices).*/import React from 'react';-import { ExternalLink, Plus, Server } from 'lucide-react';+import { ExternalLink, Plus } from 'lucide-react';import { useT } from '@/i18n';-import { useProviders, type OwnProvider, type OwnService, type OwnServiceFields, type ProviderVerb, type ProvidersHook } from '@/lib/providers';+import { useProviders, type OwnProvider, type ProviderVerb, type ProvidersHook } from '@/lib/providers';+import { customProblem } from './CustomServices';import { ProviderMark } from './ProviderMark';import { SettingsButton, SettingsField, SettingsGroup, SettingsInset, SettingsItem, SettingsPage, SettingsStatus, settingsError, settingsLink } from './ui';@@ -31,108 +29,13 @@ export function ProvidersSection() {<SettingsGroup footnote={t('settings.providers.keyNote')}>{rows.map((provider) => <KeyRow key={provider.id} provider={provider} hook={providers} />)}</SettingsGroup>- <OwnServices hook={providers} />- {/* a key that was refused says why under its own field (KeyRow), not down here past the list */}- {providers.problem && !rows.some((p) => p.id === providers.problemFor) && !ownProblem(providers) ? <p className={settingsError}>{providers.problem}</p> : null}+ {/* a key that was refused says why under its own field (KeyRow), not down here past the list; a custom service's+ under its form (Settings → Services) */}+ {providers.problem && !rows.some((p) => p.id === providers.problemFor) && !customProblem(providers) ? <p className={settingsError}>{providers.problem}</p> : null}</SettingsPage>);}-/** Whether the last change that failed was to one of the person's own services (it is said under its form). */-const ownProblem = (hook: ProvidersHook) => hook.problemFor === 'custom' || Boolean(hook.state?.custom.some((s) => s.id === hook.problemFor));--/** The person's own services: each with what it does, and a form to add one. */-function OwnServices({ hook }: { hook: ProvidersHook }) {- const t = useT();- const services = hook.state?.custom ?? [];- const [open, setOpen] = React.useState<string | null>(null);- if (!hook.state) return null;- return (- <SettingsGroup title={t('settings.providers.own.title')} footnote={t('settings.providers.own.note')}>- {services.map((service) => (- <SettingsItem- key={service.id}- mark={<Server size={16} />}- title={service.name}- badge={service.last4 ? <SettingsStatus tone="muted"><span className="font-mono tabular-nums">•••• {service.last4}</span></SettingsStatus> : null}- description={(- <>- <span className="font-mono text-[13px] text-[var(--text-faint)]">{service.url}</span>- {service.note ? <span className="mt-0.5 block whitespace-pre-line">{service.note}</span> : null}- </>- )}- control={open === service.id ? null : (- <>- <SettingsButton variant="quiet" disabled={hook.busy === service.id} onClick={() => void hook.removeService(service.id)}>{t('settings.providers.own.remove')}</SettingsButton>- <SettingsButton onClick={() => setOpen(service.id)}>{t('settings.providers.own.edit')}</SettingsButton>- </>- )}- >- {open === service.id ? <ServiceForm hook={hook} service={service} onDone={() => setOpen(null)} /> : null}- </SettingsItem>- ))}- {open === '' ? (- <div className="py-4"><ServiceForm hook={hook} service={null} onDone={() => setOpen(null)} /></div>- ) : (- <div className="py-4">- <SettingsButton onClick={() => setOpen('')}><Plus size={15} strokeWidth={2} />{t('settings.providers.own.add')}</SettingsButton>- </div>- )}- </SettingsGroup>- );-}--/** A service's name, address, key, where the key goes and what it does: added (`service` null) or changed. */-function ServiceForm({ hook, service, onDone }: { hook: ProvidersHook; service: OwnService | null; onDone: () => void }) {- const t = useT();- const [fields, setFields] = React.useState<OwnServiceFields>({- name: service?.name ?? '', url: service?.url ?? '', auth: service?.auth ?? DEFAULT_AUTH, note: service?.note ?? '',- });- const [key, setKey] = React.useState('');- const [dropKey, setDropKey] = React.useState(false);- const busy = hook.busy === (service?.id ?? 'custom');- const set = (name: keyof OwnServiceFields) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setFields((f) => ({ ...f, [name]: e.target.value }));- const save = async () => {- if (busy || !fields.name.trim() || !fields.url.trim()) return;- /* changed without a key typed: the one it has stays (unless taken away) */- const sent: OwnServiceFields = { ...fields, ...(key.trim() ? { key: key.trim() } : dropKey || !service ? { key: '' } : {}) };- if (await hook.saveService(service?.id ?? null, sent)) onDone();- };- const label = (text: string, field: React.ReactNode) => (- <label className="flex flex-col gap-1.5 text-[13.5px] text-[var(--text-muted)]">{text}{field}</label>- );- return (- /* under its row, it lines up with the row's words; a new one stands on its own */- <form className={service ? 'pl-[52px]' : ''} onSubmit={(e) => { e.preventDefault(); void save(); }} onKeyDown={(e) => { if (e.key === 'Escape') { e.preventDefault(); onDone(); } }}>- <SettingsInset>- {label(t('settings.providers.own.name'), <SettingsField autoFocus value={fields.name} onChange={set('name')} placeholder={t('settings.providers.own.namePlaceholder')} />)}- {label(t('settings.providers.own.url'), <SettingsField value={fields.url} onChange={set('url')} placeholder="http://localhost:8000" spellCheck={false} className="font-mono placeholder:font-sans" />)}- {label(t('settings.providers.own.key'), (- <SettingsField type="password" autoComplete="off" spellCheck={false} value={key} onChange={(e) => { setKey(e.target.value); setDropKey(false); }}- placeholder={service?.last4 && !dropKey ? t('settings.providers.own.keyKeep').replaceAll('{last4}', service.last4) : t('settings.providers.own.keyOptional')}- className="font-mono placeholder:font-sans" />- ))}- {service?.last4 && !key && !dropKey ? (- <button type="button" className={`${settingsLink} self-start text-[13.5px]`} onClick={() => setDropKey(true)}>{t('settings.providers.own.removeKey')}</button>- ) : null}- {label(t('settings.providers.own.auth'), <SettingsField value={fields.auth} onChange={set('auth')} spellCheck={false} className="font-mono" />)}- {label(t('settings.providers.own.what'), (- <textarea value={fields.note} onChange={set('note')} rows={3} maxLength={600} placeholder={t('settings.providers.own.whatPlaceholder')}- className="w-full min-w-0 resize-y rounded-[8px] border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] leading-[1.5] text-[var(--text)] outline-none transition placeholder:text-[var(--text-faint)] hover:border-[var(--border-strong)] focus:border-[var(--text-muted)]" />- ))}- {hook.problem && hook.problemFor === (service?.id ?? 'custom') ? <p className={settingsError} role="alert">{hook.problem}</p> : null}- <div className="flex justify-end gap-2">- <SettingsButton variant="quiet" onClick={onDone}>{t('settings.providers.cancel')}</SettingsButton>- <SettingsButton type="submit" variant="primary" disabled={busy || !fields.name.trim() || !fields.url.trim()}>{t('settings.providers.save')}</SettingsButton>- </div>- </SettingsInset>- </form>- );-}--/** Where a key goes unless the person says otherwise (the server's DEFAULT_AUTH). */-const DEFAULT_AUTH = 'Authorization: Bearer {key}';-/** A provider in the list: its mark, its name (and what is next to it), a line about it, and what can be done. */function Row({ id, name, badge, children, action, below }: {id: string;diff --git a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsxindex 6fd677d..b6a8efb 100644--- a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx@@ -14,6 +14,7 @@ import { SHORTCUTS, type ShortcutKey } from '@/lib/timeline-keys';import { studioHost, type HostDeveloper, type HostUpdateState } from '@/lib/host';import { showWhatsNew } from '@/lib/whats-new';import { hasNotes, newestVersion } from '../WhatsNew';+import { useWebUpdate } from '../UpdateButton';import { api, type StudioPrefs, type StudioVersion } from '@/api';import { AgentsSection } from './AgentsSection';import { ModelsSection } from './ModelsSection';@@ -21,6 +22,7 @@ import { ProvidersSection } from './ProvidersSection';import { SettingsSelect } from './SettingsSelect';import { SettingsButton, SettingsGroup, SettingsItem, SettingsPage, SettingsSegmented, SettingsSwitch } from './ui';import { useThemeMode, type ThemeMode } from './theme';+import { StorageGroup } from './StorageGroup';export type SettingsSection = 'general' | 'agents' | 'providers' | 'models' | 'developer' | 'shortcuts';@@ -49,7 +51,7 @@ const SECTION_ICON: Record<SettingsSection, React.ReactNode> = {/** what a search through each section reads: its name and every phrase it shows */const SECTION_WORDS: Record<SettingsSection, string | string[]> = {- general: ['settings.appearance', 'settings.playback'],+ general: ['settings.appearance', 'settings.storage', 'settings.playback'],agents: 'settings.agents',providers: 'settings.providers',models: 'settings.models',@@ -237,6 +239,7 @@ function GeneralSection() {)}/></SettingsGroup>+ <StorageGroup /><PlaybackGroup />{studioHost?.update?.onState ? <AppAboutGroup /> : <AboutGroup />}</SettingsPage>@@ -291,6 +294,8 @@ function AboutGroup() {const [state, setState] = React.useState<'idle' | 'checking' | 'failed'>('idle');React.useEffect(() => { void api.version().then(setInfo).catch(() => {}); }, []);const inApp = Boolean(studioHost);+ /* Update here as in the top bar: Studio runs the newest and starts again on it */+ const web = useWebUpdate();const check = () => {setState('checking');const before = info?.checkedAt ?? null;@@ -320,8 +325,19 @@ function AboutGroup() {{!inApp && !info?.source && info?.newer ? (<SettingsItemtitle={t('settings.about.howTitle')}- description={t('settings.about.how')}- control={<code className="select-all rounded-md bg-[var(--surface-2)] px-2 py-1 font-mono text-[12px] text-[var(--text)]">npx -y openfilm@latest open</code>}+ description={web.update?.status === 'updating' ? t('update.webUpdating')+ : web.update?.status === 'waiting' ? t(web.update.reason === 'exporting' ? 'update.webExporting' : 'update.webMaking')+ : web.update?.status === 'failed' ? t('update.webFailed').replace('{error}', web.update.error)+ : t('settings.about.how')}+ control={(+ <>+ <code className="select-all rounded-md bg-[var(--surface-2)] px-2 py-1 font-mono text-[12px] text-[var(--text)]">npx -y openfilm@latest update</code>+ <SettingsButton variant="primary" disabled={!web.update || web.update.status === 'updating'} onClick={web.start}>+ {web.update?.status === 'updating' ? <Loader2 size={14} className="animate-spin" aria-hidden /> : null}+ {t('update.webUpdate')}+ </SettingsButton>+ </>+ )}/>) : null}</SettingsGroup>diff --git a/packages/openfilm/studio/ui/src/components/settings/StorageGroup.tsx b/packages/openfilm/studio/ui/src/components/settings/StorageGroup.tsxnew file mode 100644index 0000000..b160b58--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/settings/StorageGroup.tsx@@ -0,0 +1,93 @@+/**+ * Settings → General → Storage: where new projects go (studio/server's locations, src/locations.mjs). It shows its+ * folder and the free space on its disk, and can be changed (the system's folder dialog), opened in the file manager,+ * or set back to its default. Projects made before stay where they are. Exports have no setting: the export dialog+ * picks the folder and keeps the last one.+ */+import React from 'react';+import { useT } from '@/i18n';+import { api, type StudioLocation, type StudioLocations } from '@/api';+import { studioHost } from '@/lib/host';+import { SettingsButton, SettingsField, SettingsGroup, SettingsItem, settingsError } from './ui';++type Which = keyof StudioLocations;++/** Bytes as the person reads a disk's free space: GB, or MB below one. */+function size(bytes: number): string {+ return bytes >= 1e9 ? `${(bytes / 1e9).toFixed(bytes >= 1e11 ? 0 : 1)} GB` : `${Math.max(1, Math.round(bytes / 1e6))} MB`;+}++export function StorageGroup() {+ const t = useT();+ const [where, setWhere] = React.useState<StudioLocations | null>(null);+ const [busy, setBusy] = React.useState<Which | null>(null);+ const [error, setError] = React.useState<{ which: Which; text: string } | null>(null);+ /* where no folder dialog can open (a browser on another system), the path is typed */+ const [typing, setTyping] = React.useState<{ which: Which; text: string } | null>(null);+ const load = React.useCallback(() => { void api.locations().then(setWhere).catch(() => {}); }, []);+ React.useEffect(load, [load]);+ if (!where) return null;++ const keep = async (which: Which, folder: string | null) => {+ setBusy(which);+ setError(null);+ try {+ await api.setPrefs({ projectsFolder: folder });+ setTyping(null);+ load();+ } catch (e) {+ setError({ which, text: e instanceof Error ? e.message : String(e) });+ } finally {+ setBusy(null);+ }+ };+ const change = async (which: Which) => {+ const ask = { title: t(`settings.storage.${which}Pick`), button: t('settings.storage.pickButton'), at: where[which].path };+ try {+ const pick = studioHost?.folders?.pick;+ const picked = pick ? await pick(ask) : await api.pickFolder(ask.title, ask.at);+ if (picked) await keep(which, picked);+ } catch {+ setTyping({ which, text: where[which].path });+ }+ };++ const row = (which: Which, place: StudioLocation) => (+ <SettingsItem+ key={which}+ title={t(`settings.storage.${which}`)}+ description={(+ <>+ <span className="block">{t(`settings.storage.${which}Hint`)}</span>+ {typing?.which === which ? (+ <form className="mt-2 flex items-center gap-2" onSubmit={(e) => { e.preventDefault(); if (typing.text.trim()) void keep(which, typing.text.trim()); }}>+ <SettingsField autoFocus value={typing.text} onChange={(e) => setTyping({ which, text: e.target.value })} spellCheck={false}+ aria-label={t(`settings.storage.${which}`)} className="font-mono text-[13px]"+ onKeyDown={(e) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setTyping(null); } }} />+ <SettingsButton type="submit" variant="primary" disabled={busy === which || !typing.text.trim()}>{t('settings.storage.save')}</SettingsButton>+ </form>+ ) : (+ <span className="mt-1 block break-all font-mono text-[13px] text-[var(--text)]" title={place.path}>{place.path}</span>+ )}+ {place.free != null ? <span className="mt-0.5 block text-[13px]">{t('settings.storage.free').replace('{size}', size(place.free))}</span> : null}+ {error?.which === which ? <span className={`mt-1 block ${settingsError}`} role="alert">{error.text}</span> : null}+ </>+ )}+ control={(+ <>+ {place.chosen ? (+ <SettingsButton variant="quiet" disabled={busy === which} onClick={() => void keep(which, null)} title={place.default}>{t('settings.storage.reset')}</SettingsButton>+ ) : null}+ <SettingsButton variant="quiet" onClick={() => void api.openLocation(which).catch(() => {})}>{t('settings.storage.show')}</SettingsButton>+ <SettingsButton disabled={busy === which} onClick={() => void change(which)}>{t('settings.storage.change')}</SettingsButton>+ </>+ )}+ />+ );++ return (+ <SettingsGroup title={t('settings.storage.group')}>+ {row('projects', where.projects)}+ </SettingsGroup>+ );+}diff --git a/packages/openfilm/studio/ui/src/components/settings/theme.ts b/packages/openfilm/studio/ui/src/components/settings/theme.tsindex d6a66fc..1ef7de6 100644--- a/packages/openfilm/studio/ui/src/components/settings/theme.ts+++ b/packages/openfilm/studio/ui/src/components/settings/theme.ts@@ -1,6 +1,7 @@/*** The theme: light, dark or the system's, dark until the person chooses. The choice is kept in localStorage `openfilm.theme` and shown as- * `<html data-theme>`; index.html applies it before the first paint, this keeps it current afterwards.+ * `<html data-theme>`; index.html applies it before the first paint, this keeps it current afterwards, in every page+ * of Studio that is open.*/import React from 'react';@@ -24,6 +25,14 @@ const listeners = new Set<() => void>();/* "System" follows the system while Studio is open, not only when it starts */if (typeof window !== 'undefined') dark().addEventListener('change', () => { if (saved() === 'system') apply('system'); });+/* a theme chosen in another of Studio's pages (another tab of the app, another window) is this one's too */+if (typeof window !== 'undefined') {+ window.addEventListener('storage', (event) => {+ if (event.key !== KEY) return;+ apply(saved());+ for (const listener of listeners) listener();+ });+}export function setThemeMode(mode: ThemeMode) {try { localStorage.setItem(KEY, mode); } catch { /* not kept past this page */ }diff --git a/packages/openfilm/studio/ui/src/editor/Preview.tsx b/packages/openfilm/studio/ui/src/editor/Preview.tsxindex c7da8ee..a08c52a 100644--- a/packages/openfilm/studio/ui/src/editor/Preview.tsx+++ b/packages/openfilm/studio/ui/src/editor/Preview.tsx@@ -16,6 +16,7 @@ import { useT } from '@/i18n';import type { ClipSpan } from '@/lib/film-shape';import type { Sound } from './player';import { reloaded, shownAfter, updateKeys, type Frame } from './preview-frames';+import { chromiumBased } from '@/lib/browser';/** How far the film's frame reaches past the picture's box on each side, in px (see the `stage-frames` clip). */const BLEED = 1;@@ -48,10 +49,12 @@ export type PreviewHandle = {};/**- * What the film's stage tells on its own: an in-place text edit ended (`commit` with the new words), a key pressed- * while the picture had focus (not while typing in it), or another load of the film is shown (its handles are new).+ * What the film's stage tells on its own: the words of an in-place text edit as they are typed, the edit ended+ * (`commit` with the new words), a key pressed while the picture had focus (not while typing in it), or another load+ * of the film is shown (its handles are new).*/export type StageEvent =+ | { event: 'typing'; handle: number; value: string }/* `hold`: what kept the other layers in place as the words were typed (style for the same override, null takes a key away) */| { event: 'text'; handle: number; commit: boolean; value?: string; before?: string; hold?: Record<string, string | null> }| { event: 'key'; key: KeyboardEvent }@@ -229,6 +232,8 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde});tell({ event: 'key', key });onKeyRef.current?.(key);+ } else if (m.event === 'typing') {+ tell({ event: 'typing', handle: Number(m.handle), value: String(m.value ?? '') });} else if (m.event === 'text') {tell({event: 'text', handle: Number(m.handle), commit: Boolean(m.commit),@@ -293,6 +298,8 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde<div className="cover" role="alert"><div className="max-w-[420px] text-[13px] leading-relaxed text-white/70"><p>{t('project.previewFailed')}</p>+ {/* in Safari or Firefox the likely reason is the browser: films are drawn and exported in Chromium */}+ {!chromiumBased() ? <p className="mt-1.5">{t('project.previewBrowser')}</p> : null}<p className="mt-1.5 text-[11.5px] text-white/45">{error}</p></div></div>diff --git a/packages/openfilm/studio/ui/src/globals.css b/packages/openfilm/studio/ui/src/globals.cssindex e7eb4e5..49faca8 100644--- a/packages/openfilm/studio/ui/src/globals.css+++ b/packages/openfilm/studio/ui/src/globals.css@@ -539,7 +539,7 @@ body.tl-scrubbing * {/* in a host window with no title bar (lib/host.ts): the top bars drag the window, their controls do not */[data-host-titlebar] [data-titlebar] { -webkit-app-region: drag; app-region: drag; }/* menus and dialogs drawn over a top bar (often from a portal, so not inside it) take their clicks too */-[data-host-titlebar] [data-titlebar] :is(button, a, input, select, textarea, [role='button']),+[data-host-titlebar] [data-titlebar] :is(button, a, input, select, textarea, [role='button'], [role='tab']),[data-host-titlebar] :is([role='menu'], [role='dialog'], [role='listbox'], [role='tooltip']) {-webkit-app-region: no-drag;app-region: no-drag;diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex b2ed513..8e2e978 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -10,6 +10,44 @@ export const en = {projects: 'Projects',desktop: 'Desktop',},+ /* the app window's tabs (TabStrip), a new tab's launcher, and the examples (ExamplesGallery) */+ tabs: { label: 'Tabs', new: 'Open a project', close: 'Close tab' },+ launcher: { projects: 'Projects', examples: 'Examples' },+ gallery: {+ title: 'Examples',+ community: 'Community',+ discoverNote: 'Films made with OpenFilm, to start from or to learn from.',+ noSkills: 'None of yours yet. Save your brand, a series\' style or your usual opening as a skill, and every film can follow it. Add one from a link or a folder, or ask the agent to save a film you like as a skill.',+ all: 'All',+ workflow: 'Workflows',+ style: 'Styles',+ skillKinds: 'There are two kinds of skills:\n· Yours hold what only you know: your brand, your series\' look, your usual opening and ending. No AI can guess them, so save them once and every film can use them.\n· OpenFilm\'s are ready-made ways to make a kind of film, to get you going fast. As AI gets better, you\'ll need them less.',+ search: 'Search skills',+ noMatch: 'No skill matches.',+ aboutSkills: 'About skills',+ fromFolder: 'Folder',+ made: 'Made by you',+ skills: 'Skills',+ loading: 'Reading the examples…',+ empty: 'No examples to show. They are read from GitHub: check the connection.',+ start: 'Start from this',+ startNew: 'Start a new film from this',+ startHow: 'A copy of it becomes a new project of yours, its source ready to change.',+ reference: 'Reference in this film',+ referencePart: 'Reference this part',+ referenceHow: 'It goes into your message. The agent reads how it is made (its pages and timing) and follows it in your film.',+ referenceNote: 'Pick an example, or a part of one, for the agent to follow',+ parts: 'Parts',+ whole: 'The whole film',+ partsHint: 'Click a part, or drag across the strip for a stretch.',+ viewSource: 'View on GitHub',+ back: 'Back',+ useSkill: 'Use this skill',+ mine: 'Yours',+ project: 'This project',+ addSkill: 'Add a skill',+ cat: { launch: 'Product launches', explainer: 'Explainers', slides: 'Slides to video', captions: 'Captions and titles', ads: 'Ads', commerce: 'Selling points', music: 'Music' },+ },/* the app's update, ready to install (Studio's top bar, in an app that has updates: lib/host.ts `update`) */update: {restart: 'Restart to update',@@ -18,6 +56,12 @@ export const en = {exporting: 'An export is running. Restart when it has finished.',installFailed: 'OpenFilm {version} could not install. Quit OpenFilm and open it again to install it.',installing: 'Restarting…',+ webUpdate: 'Update',+ webAvailable: 'OpenFilm {version} is out. Studio restarts on it, and the pages open on it come back.',+ webUpdating: 'Updating…',+ webExporting: 'An export is running. Update when it has finished.',+ webMaking: 'Media is being made. Update when it is done.',+ webFailed: 'Could not update: {error}',},whatsNew: {eyebrow: 'Updated',@@ -467,6 +511,7 @@ export const en = {editsRestore: 'Restore them',editsLeaveOut: 'Leave them out',previewFailed: 'The preview couldn\'t be drawn.',+ previewBrowser: 'This page uses something your browser doesn\'t have. Films are drawn and exported with Chromium: open Studio in Chrome or Edge.',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:',@@ -703,10 +748,25 @@ export const en = {unreadable: '“{name}” was imported, but it can’t be read as a picture, video or sound ({why}). Check the file, or import another copy.',imported: 'Imported {n} file(s) into Media',},+ saved: {+ title: 'Saved',+ back: 'Back to the project’s media',+ add: 'Add to Saved',+ addTogether: 'Add {n} clips to Saved as one',+ addEach: 'Add each to Saved',+ added: 'Added to Saved',+ addedMany: '{n} added to Saved',+ failed: 'Could not add to Saved: {error}',+ emptyTitle: 'Nothing in Saved yet',+ emptyBody: 'Saved is yours in every project. Upload files of any kind or drop them here, or right-click a clip on the timeline and choose Add to Saved.',+ template: 'Template',+ kind_clip: 'Clip',+ kind_group: 'Clips',+ kind_page: 'Page',+ },media: {insertSource: "Insert at the playhead",overwriteSource: "Overwrite at the playhead",- close: 'Close',results: 'Results',moveFailed: 'Could not move it there.',moveAskTitle: 'Some paths in it can’t be updated',@@ -889,6 +949,13 @@ export const en = {sound: 'Sound',gainDb: 'Volume',pageChanges: 'Changes inside the page',+ template: 'Template',+ templateOffPicture: 'Move the playhead onto this clip to see what its page lets you change.',+ templateText: 'Text',+ templateReset: 'Back to the page’s own',+ templatePicture: 'Picture',+ templatePictureReplace: 'Replace picture',+ templatePictureComputer: 'From this computer…',pageChangeLost: 'No longer in the page',pageChangeRemove: 'Undo this change',pageChangeText: 'text',@@ -1371,7 +1438,7 @@ export const en = {sections: {agents: 'Agents',providers: 'Providers',- models: 'Models',+ models: 'Services',developer: 'Developer',general: 'General',shortcuts: 'Keyboard shortcuts',@@ -1387,6 +1454,18 @@ export const en = {themeHint: 'Light, dark, or the same as your system.',languageHint: 'The language OpenFilm shows itself in.',},+ storage: {+ group: 'Storage',+ projects: 'New projects',+ projectsHint: 'Where new projects go, with their media and cache. Projects made before stay where they are.',+ projectsPick: 'Choose where new projects go',+ pickButton: 'Choose',+ change: 'Change…',+ show: 'Show',+ reset: 'Use default',+ save: 'Save',+ free: '{size} free on this disk',+ },playback: {group: "Playback",proxies: "Proxies for heavy footage",@@ -1406,7 +1485,7 @@ export const en = {never: 'Not checked yet.',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.',+ how: 'Click Update, run this, or ask your agent to update OpenFilm: 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}…',@@ -1418,7 +1497,7 @@ export const en = {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, 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.',+ 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 models you set up yourself, each on its own service.',byokName: 'Your own key',groupYours: 'Your agents',groupMore: 'More agents you can use',@@ -1427,7 +1506,7 @@ export const en = {ready: 'Connected',off: 'Not connected',signedOut: 'Not signed in',- waiting: 'Waiting for the sign-in in Terminal…',+ waiting: 'Waiting for you to sign in…',waitingHint: 'Finish signing in in the window that opened, then come back.',startAgain: 'Start again',missing: 'Not installed on this computer',@@ -1439,6 +1518,7 @@ export const en = {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:',+ unreadable: 'It can’t read its own settings, so it can’t start. Fix what it names in its config file, or update it:',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.',@@ -1475,21 +1555,36 @@ export const en = {failed: 'That did not work. Try again.',format: 'API format',address: 'Address',- model: 'Models',- modelPlaceholder: 'A model\'s name, as the service names it',- addModel: 'Add',+ model: 'Model',+ modelPlaceholder: 'The model\'s name, as the service names it',+ addModel: 'Add a model',+ name: 'Name',+ namePlaceholder: 'Shown in the chat (the model, when empty)',+ edit: 'Edit',+ done: 'Done',+ keySame: 'Leave empty to use {name}\'s key',removeModel: 'Remove {name}',efforts: 'Reasoning effort',effortStart: 'Starts on',- effortHint: 'Tick the efforts each model takes: the chat offers those. Auto sends none, so the service decides.',+ effortHint: 'Tick the efforts this model takes: the chat offers those. Auto sends none, so the service decides.',effortLevels: { auto: 'Auto', off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' },key: 'API key',keyPlaceholder: 'Paste your API key',keyKept: 'Key ending in {last4} (leave empty to keep it)',- byokNote: 'Each model has to read pictures: the agent looks at its own frames. Your key stays on this computer and goes only to that service.',+ byokNote: 'Each model has to read pictures: the agent looks at its own frames. Your keys stay on this computer, and each goes only to its service.',save: 'Check and save',checkingKey: 'Checking…',cancel: 'Cancel',+ mcpSummary: 'Your MCP servers: {on} of {n} used in OpenFilm',+ mcpManage: 'Choose',+ mcpDone: 'Done',+ mcpNote: 'MCP servers you added to {agent} yourself are off in OpenFilm until you turn one on. Its own are always on.',+ mcpAllow: 'Use {name} in OpenFilm',+ skillsSummary: 'Your skills: {on} of {n} used in OpenFilm',+ skillsNote: 'Skills you installed in {agent} yourself are off in OpenFilm until you turn one on, so films come out the same each time. Its own are always on.',+ skillsAllow: 'Use {name} in OpenFilm',+ skillsUnfiltered: '{agent} uses all {n} of your own skills in OpenFilm, as in its own app.',+ mcpUnfiltered: '{agent} uses all {n} of your own MCP servers in OpenFilm, as in its own app.',},developer: {intro: 'For finding out exactly what an agent did, and why: nothing here changes what the agents do.',@@ -1569,7 +1664,7 @@ export const en = {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.',+ 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. Which one makes each kind of media is chosen under Services.',connect: 'Connect',disconnect: 'Disconnect',connected: 'Connected',@@ -1582,9 +1677,9 @@ export const en = {keyEnding: 'Key ending in {last4}',useEnv: 'Use the key in ${env}',own: {- title: "Your own services",- note: "Any service you run or use, on this computer or online (your own voice, a transcription server, an API not listed here). Your agent reaches it at its address, and its key stays on this computer. Say what it does, so your agent knows when to use it.",- add: "Add a service",+ title: "Custom services",+ note: "Services not listed above, as many as you like: one you run on this computer or one online (your own voice, a transcription server, an API not listed), with any interface. OpenFilm doesn't call them itself: your agent reads your description and calls them, and their keys stay on this computer, out of the agent's sight. You can also tell your agent about a service in the chat instead; set it up here when it takes a key, so the key stays out of the conversation.",+ add: "Add a custom service",edit: "Edit",remove: "Remove",name: "Name",@@ -1594,9 +1689,8 @@ export const en = {keyOptional: "Optional",keyKeep: "Leave empty to keep the key ending in {last4}",removeKey: "Remove the key",- auth: "Where the key goes",- what: "What it does",- whatPlaceholder: "e.g. Speaks a script in my voice: POST /tts with {\"text\": \"…\"} answers a WAV. Docs: https://…",+ what: "Description",+ whatPlaceholder: "e.g. Speaks a script in my voice: POST /tts with {\"text\": \"…\"} answers a WAV. Or just its API docs: https://…",},verbs: {tts: 'Voice-over',@@ -1612,12 +1706,11 @@ export const en = {},},models: {- desc: 'Which provider and model makes each kind of media. Connecting a provider fills the kinds that have none; change any of them here.',+ desc: 'Which service makes each kind of media: a model of a connected provider. Connecting a provider fills the kinds that have none; change any of them here.',nothing: 'Nothing is connected yet. Connect a provider to choose its models.',goConnect: 'Connect a provider',none: 'None',connectNamed: 'Connect {names}',- otherBody: "Want a service or model that isn’t listed? Add it under Providers → Your own services, with its address and key: your agent can then use it. What it makes lands in Assets like everything else.",about: {tts: 'Speaks a script, and finds voices to speak it',music: 'Makes a soundtrack from a description',diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex f529944..999a236 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -9,6 +9,44 @@ export const es: Words = {projects: 'Proyectos',desktop: 'Escritorio',},+ /* the app window's tabs (TabStrip), a new tab's launcher, and the examples (ExamplesGallery) */+ tabs: { label: 'Pestañas', new: 'Abrir un proyecto', close: 'Cerrar pestaña' },+ launcher: { projects: 'Proyectos', examples: 'Ejemplos' },+ gallery: {+ title: 'Ejemplos',+ community: 'Comunidad',+ discoverNote: 'Películas hechas con OpenFilm, para empezar con ellas o aprender de cómo están hechas.',+ noSkills: 'Aún no tienes skills propias. Guarda tu marca, el estilo de una serie o tu apertura de siempre como skill, y cada película podrá seguirla. Añade una desde un enlace o una carpeta, o pide al agente que guarde como skill una película que te guste.',+ all: 'Todo',+ workflow: 'Flujos de trabajo',+ style: 'Estilos',+ skillKinds: 'Hay dos tipos de skills:\n· Las tuyas guardan lo que solo tú sabes: tu marca, el estilo de tu serie, tu apertura y cierre de siempre. Ninguna IA puede adivinarlos; guárdalos una vez y cada película podrá usarlos.\n· Las de OpenFilm son formas ya hechas de crear un tipo de película, para empezar rápido. Cuanto mejor sea la IA, menos las necesitarás.',+ search: 'Buscar skills',+ noMatch: 'Ninguna skill coincide.',+ aboutSkills: 'Sobre las skills',+ fromFolder: 'Carpeta',+ made: 'Hecha por ti',+ skills: 'Skills',+ loading: 'Leyendo los ejemplos…',+ empty: 'No hay ejemplos que mostrar. Se leen de GitHub: revisa la conexión.',+ start: 'Empezar con este',+ startNew: 'Empezar una película nueva con este',+ startHow: 'Una copia se convierte en un proyecto tuyo nuevo, con el código listo para cambiar.',+ reference: 'Usar como referencia en esta película',+ referencePart: 'Usar esta parte como referencia',+ referenceHow: 'Va en tu mensaje. El agente lee cómo está hecho (sus páginas y tiempos) y lo sigue en tu película.',+ referenceNote: 'Elige un ejemplo, o una parte, para que el agente lo siga',+ parts: 'Partes',+ whole: 'La película entera',+ partsHint: 'Haz clic en una parte o arrastra sobre la barra para un tramo.',+ viewSource: 'Ver en GitHub',+ back: 'Atrás',+ useSkill: 'Usar esta skill',+ mine: 'Tuya',+ project: 'Este proyecto',+ addSkill: 'Añadir una skill',+ cat: { launch: 'Lanzamientos', explainer: 'Explicaciones', slides: 'Diapositivas a vídeo', captions: 'Subtítulos y títulos', ads: 'Anuncios', commerce: 'Puntos de venta', music: 'Música' },+ },/* the app's update, ready to install (Studio's top bar, in an app that has updates: lib/host.ts `update`) */update: {restart: 'Reiniciar para actualizar',@@ -17,6 +55,12 @@ export const es: Words = {exporting: 'Hay una exportación en curso. Reinicia cuando termine.',installFailed: 'No se pudo instalar OpenFilm {version}. Sal de OpenFilm y vuelve a abrirlo para instalarlo.',installing: 'Reiniciando…',+ webUpdate: 'Actualizar',+ webAvailable: 'Ya está OpenFilm {version}. Studio se reinicia con ella y las páginas abiertas vuelven solas.',+ webUpdating: 'Actualizando…',+ webExporting: 'Hay una exportación en curso. Actualiza cuando termine.',+ webMaking: 'Se está generando contenido. Actualiza cuando termine.',+ webFailed: 'No se pudo actualizar: {error}',},whatsNew: {eyebrow: 'Actualizado',@@ -466,6 +510,7 @@ export const es: Words = {editsRestore: 'Restaurarlas',editsLeaveOut: 'Descartarlas',previewFailed: 'No se pudo dibujar la vista previa.',+ previewBrowser: 'Esta página usa algo que tu navegador no tiene. Las películas se dibujan y exportan con Chromium: abre Studio en Chrome o Edge.',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:',@@ -702,10 +747,25 @@ export const es: Words = {unreadable: '“{name}” se importó, pero no se puede leer como imagen, video o sonido ({why}). Revisa el archivo o importa otra copia.',imported: 'Se importaron {n} archivo(s) a Medios',},+ saved: {+ title: 'Guardados',+ back: 'Volver a los medios del proyecto',+ add: 'Añadir a Guardados',+ addTogether: 'Añadir {n} clips a Guardados como uno',+ addEach: 'Añadir cada uno a Guardados',+ added: 'Añadido a Guardados',+ addedMany: '{n} añadidos a Guardados',+ failed: 'No se pudo añadir a Guardados: {error}',+ emptyTitle: 'Aún no hay nada en Guardados',+ emptyBody: 'Guardados es tuyo en todos los proyectos. Sube o suelta aquí archivos de cualquier tipo, o haz clic derecho en un clip de la línea de tiempo y elige Añadir a Guardados.',+ template: 'Plantilla',+ kind_clip: 'Clip',+ kind_group: 'Clips',+ kind_page: 'Página',+ },media: {insertSource: "Insertar en el cabezal",overwriteSource: "Sobrescribir en el cabezal",- close: 'Cerrar',results: 'Resultados',moveFailed: 'No se pudo mover ahí.',moveAskTitle: 'Algunas rutas no se pueden actualizar',@@ -888,6 +948,13 @@ export const es: Words = {sound: 'Sonido',gainDb: 'Volumen',pageChanges: 'Cambios dentro de la página',+ template: 'Plantilla',+ templateOffPicture: 'Lleva el cabezal a este clip para ver qué permite cambiar su página.',+ templateText: 'Texto',+ templateReset: 'Volver al valor de la página',+ templatePicture: 'Imagen',+ templatePictureReplace: 'Reemplazar imagen',+ templatePictureComputer: 'Desde este ordenador…',pageChangeLost: 'Ya no está en la página',pageChangeRemove: 'Deshacer este cambio',pageChangeText: 'texto',@@ -1370,7 +1437,7 @@ export const es: Words = {sections: {agents: 'Agentes',providers: 'Proveedores',- models: 'Modelos',+ models: 'Servicios',developer: 'Desarrollador',general: 'General',shortcuts: 'Atajos de teclado',@@ -1386,6 +1453,18 @@ export const es: Words = {themeHint: 'Claro, oscuro o igual que el sistema.',languageHint: 'El idioma en que se muestra OpenFilm.',},+ storage: {+ group: 'Almacenamiento',+ projects: 'Proyectos nuevos',+ projectsHint: 'Dónde van los proyectos nuevos, con sus medios y su caché. Los proyectos anteriores se quedan donde están.',+ projectsPick: 'Elige dónde van los proyectos nuevos',+ pickButton: 'Elegir',+ change: 'Cambiar…',+ show: 'Abrir',+ reset: 'Usar la predeterminada',+ save: 'Guardar',+ free: '{size} libres en este disco',+ },playback: {group: "Reproducción",proxies: "Proxies para el metraje pesado",@@ -1405,7 +1484,7 @@ export const es: Words = {never: 'Aún no se ha comprobado.',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.',+ how: 'Pulsa Actualizar, ejecuta esto o pídele a tu agente que actualice OpenFilm: 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}…',@@ -1417,7 +1496,7 @@ export const es: Words = {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 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.',+ intro: 'Los agentes que puede usar el chat. Codex, Claude Code y los demás de Tus agentes son tuyos, con la cuenta iniciada en este equipo: para usar otra cuenta, cámbiala en el propio agente y luego desconéctalo y vuelve a conectarlo aquí. Tu propia clave usa modelos que configuras tú, cada uno con su propio servicio.',byokName: 'Tu propia clave',groupYours: 'Tus agentes',groupMore: 'Otros agentes que puedes usar',@@ -1426,7 +1505,7 @@ export const es: Words = {ready: 'Conectado',off: 'No conectado',signedOut: 'Sin sesión iniciada',- waiting: 'Esperando el inicio de sesión en Terminal…',+ waiting: 'Esperando a que inicies sesión…',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',@@ -1438,6 +1517,7 @@ export const es: Words = {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í:',+ unreadable: 'No puede leer su propia configuración, así que no puede iniciarse. Corrige lo que indica en su archivo de configuración o actualízalo:',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.',@@ -1474,21 +1554,36 @@ export const es: Words = {failed: 'No ha funcionado. Inténtalo de nuevo.',format: 'Formato de API',address: 'Dirección',- model: 'Modelos',- modelPlaceholder: 'El nombre de un modelo, como lo llama el servicio',- addModel: 'Añadir',+ model: 'Modelo',+ modelPlaceholder: 'El nombre del modelo, como lo llama el servicio',+ addModel: 'Añadir un modelo',+ name: 'Nombre',+ namePlaceholder: 'El que se muestra en el chat (el del modelo, si se deja vacío)',+ edit: 'Editar',+ done: 'Listo',+ keySame: 'Déjalo vacío para usar la clave de {name}',removeModel: 'Quitar {name}',efforts: 'Esfuerzo de razonamiento',effortStart: 'Empieza en',- effortHint: 'Marca los esfuerzos que admite cada modelo: el chat ofrece esos. Automático no envía ninguno, así decide el servicio.',+ effortHint: 'Marca los esfuerzos que admite este modelo: el chat ofrece esos. Automático no envía ninguno, así decide el servicio.',effortLevels: { auto: 'Automático', off: 'Sin razonar', minimal: 'Mínimo', low: 'Bajo', medium: 'Medio', high: 'Alto', xhigh: 'Muy alto', max: 'Máximo' },key: 'Clave de API',keyPlaceholder: 'Pega tu clave de API',keyKept: 'Clave terminada en {last4} (déjalo vacío para conservarla)',- byokNote: 'Cada modelo tiene que poder leer imágenes: el agente mira sus propios fotogramas. Tu clave se queda en este equipo y solo se envía a ese servicio.',+ byokNote: 'Cada modelo tiene que poder leer imágenes: el agente mira sus propios fotogramas. Tus claves se quedan en este equipo y cada una solo se envía a su servicio.',save: 'Comprobar y guardar',checkingKey: 'Comprobando…',cancel: 'Cancelar',+ mcpSummary: 'Tus servidores MCP: {on} de {n} en uso en OpenFilm',+ mcpManage: 'Elegir',+ mcpDone: 'Listo',+ mcpNote: 'Los servidores MCP que añadiste tú a {agent} están desactivados en OpenFilm hasta que actives uno. Los suyos propios siempre están activos.',+ mcpAllow: 'Usar {name} en OpenFilm',+ skillsSummary: 'Tus skills: {on} de {n} en uso en OpenFilm',+ skillsNote: 'Las skills que instalaste tú en {agent} están desactivadas en OpenFilm hasta que actives una, para que las películas salgan igual cada vez. Las suyas propias siempre están activas.',+ skillsAllow: 'Usar {name} en OpenFilm',+ skillsUnfiltered: '{agent} usa tus {n} skills en OpenFilm, como en su propia app.',+ mcpUnfiltered: '{agent} usa tus {n} servidores MCP en OpenFilm, como en su propia app.',},developer: {intro: 'Para saber exactamente qué hizo un agente y por qué: nada de esto cambia lo que hacen los agentes.',@@ -1568,7 +1663,7 @@ export const es: Words = {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.',+ 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. Cuál crea cada tipo de medio se elige en Servicios.',connect: 'Conectar',disconnect: 'Desconectar',connected: 'Conectado',@@ -1581,9 +1676,9 @@ export const es: Words = {keyEnding: 'Clave terminada en {last4}',useEnv: 'Usar la clave de ${env}',own: {- title: "Tus propios servicios",- note: "Cualquier servicio que ejecutes o uses, en este ordenador o en línea (tu propia voz, un servidor de transcripción, una API que no está en la lista). Tu agente lo usa en su dirección y su clave se queda en este ordenador. Di qué hace, para que tu agente sepa cuándo usarlo.",- add: "Añadir un servicio",+ title: "Servicios personalizados",+ note: "Servicios que no están arriba, tantos como quieras: uno que ejecutes en este ordenador o uno en línea (tu propia voz, un servidor de transcripción, una API que no está en la lista), con cualquier interfaz. OpenFilm no los llama por sí mismo: tu agente lee tu descripción y los llama, y sus claves se quedan en este ordenador, fuera de la vista del agente. También puedes hablarle de un servicio en el chat; si necesita clave, añádelo aquí para que la clave no aparezca en la conversación.",+ add: "Añadir un servicio personalizado",edit: "Editar",remove: "Quitar",name: "Nombre",@@ -1593,9 +1688,8 @@ export const es: Words = {keyOptional: "Opcional",keyKeep: "Déjala vacía para conservar la clave que termina en {last4}",removeKey: "Quitar la clave",- auth: "Dónde va la clave",- what: "Qué hace",- whatPlaceholder: "p. ej. Lee un guion con mi voz: POST /tts con {\"text\": \"…\"} devuelve un WAV. Documentación: https://…",+ what: "Descripción",+ whatPlaceholder: "p. ej. Lee un guion con mi voz: POST /tts con {\"text\": \"…\"} devuelve un WAV. O solo su documentación de API: https://…",},verbs: {tts: 'Locución',@@ -1611,12 +1705,11 @@ export const es: Words = {},},models: {- desc: 'Qué proveedor y modelo crea cada tipo de medio. Al conectar un proveedor se rellenan los tipos que no tienen ninguno; puedes cambiar cualquiera aquí.',+ desc: 'Qué servicio crea cada tipo de medio: un modelo de un proveedor conectado. Al conectar un proveedor se rellenan los tipos que no tienen ninguno; puedes cambiar cualquiera aquí.',nothing: 'Aún no hay nada conectado. Conecta un proveedor para elegir sus modelos.',goConnect: 'Conectar un proveedor',none: 'Ninguno',connectNamed: 'Conectar {names}',- otherBody: "¿Quieres un servicio o modelo que no aparece en la lista? Añádelo en Proveedores → Tus propios servicios, con su dirección y su clave: tu agente podrá usarlo. Lo que cree llega a Recursos como todo lo demás.",about: {tts: 'Lee un guion en voz alta y encuentra voces para leerlo',music: 'Crea una banda sonora a partir de una descripción',diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex 5df29c0..4d28f2f 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -9,6 +9,44 @@ export const ja: Words = {projects: 'プロジェクト',desktop: 'デスクトップ版',},+ /* the app window's tabs (TabStrip), a new tab's launcher, and the examples (ExamplesGallery) */+ tabs: { label: 'タブ', new: 'プロジェクトを開く', close: 'タブを閉じる' },+ launcher: { projects: 'プロジェクト', examples: 'サンプル' },+ gallery: {+ title: 'サンプル',+ community: 'コミュニティ',+ discoverNote: 'OpenFilm で作った映像。ここから始めることも、作り方を参考にすることもできます。',+ noSkills: 'まだ自分のスキルはありません。ブランド、シリーズの雰囲気、いつものオープニングをスキルにしておけば、どの作品もそれに沿って作れます。リンクやフォルダから追加するか、気に入った作品をエージェントにスキルとして保存してもらいましょう。',+ all: 'すべて',+ workflow: 'ワークフロー',+ style: 'スタイル',+ skillKinds: 'スキルには二種類あります。\n· 自分のスキル:ブランド、シリーズの雰囲気、いつものオープニングやエンディングなど、あなたしか知らないことを保存します。AI がどんなに賢くても推測できないので、一度保存すればどの作品でも使えます。\n· OpenFilm のスキル:ある種の映像をすぐ作るための、出来合いの作り方です。AI が賢くなるほど、必要なくなっていきます。',+ search: 'スキルを検索',+ noMatch: '一致するスキルはありません。',+ aboutSkills: 'スキルについて',+ fromFolder: 'フォルダ',+ made: '自分で作成',+ skills: 'スキル',+ loading: 'サンプルを読み込み中…',+ empty: '表示できるサンプルがありません。サンプルは GitHub から読み込みます。接続を確認してください。',+ start: 'これから始める',+ startNew: 'これで新しい映像を始める',+ startHow: 'コピーが新しいプロジェクトになり、ソースをそのまま変更できます。',+ reference: 'この映像で参考にする',+ referencePart: 'この部分を参考にする',+ referenceHow: 'メッセージに入ります。エージェントが作り方(ページとタイミング)を読み、あなたの映像に活かします。',+ referenceNote: 'サンプルやその一部を選んで、エージェントに参考にさせます',+ parts: 'パート',+ whole: '全体',+ partsHint: 'パートをクリックするか、バーの上をドラッグして範囲を選びます。',+ viewSource: 'GitHub で見る',+ back: '戻る',+ useSkill: 'このスキルを使う',+ mine: '自分の',+ project: 'このプロジェクト',+ addSkill: 'スキルを追加',+ cat: { launch: '製品発表', explainer: '解説', slides: 'スライドを動画に', captions: '字幕とテロップ', ads: '広告', commerce: 'セールスポイント', music: '音楽' },+ },/* the app's update, ready to install (Studio's top bar, in an app that has updates: lib/host.ts `update`) */update: {restart: '再起動してアップデート',@@ -17,6 +55,12 @@ export const ja: Words = {exporting: '書き出し中です。終わってから再起動してください。',installFailed: 'OpenFilm {version} をインストールできませんでした。OpenFilm を終了してもう一度開くとインストールされます。',installing: '再起動しています…',+ webUpdate: 'アップデート',+ webAvailable: 'OpenFilm {version} が公開されました。Studio は新しいバージョンで再起動し、開いているページは自動的に戻ります。',+ webUpdating: 'アップデートしています…',+ webExporting: 'エクスポート中です。終わってからアップデートしてください。',+ webMaking: '素材を作成中です。終わってからアップデートしてください。',+ webFailed: 'アップデートできませんでした:{error}',},whatsNew: {eyebrow: 'アップデート済み',@@ -466,6 +510,7 @@ export const ja: Words = {editsRestore: '元に戻す',editsLeaveOut: '戻さない',previewFailed: 'プレビューを描画できませんでした。',+ previewBrowser: 'このページは、お使いのブラウザにない機能を使っています。映像は Chromium で描画・書き出しされるため、Studio は Chrome か Edge で開いてください。',previewMissing: 'メディアなし:{file} · クリップを右クリックで再リンク',filmEmptyHint: 'メディアをタイムラインにドラッグして映像を作り始めるか、エージェントに作成を頼んでください。',filmBroken: '現在 film.html を読み込めないため、Studio は最後の状態の映像を表示しています。修正されるまで、ここでの編集は保存できません:',@@ -702,10 +747,25 @@ export const ja: Words = {unreadable: '「{name}」は読み込まれましたが、画像・ビデオ・サウンドとして読み取れません({why})。ファイルを確認するか、別のコピーを読み込んでください。',imported: '{n} 個のファイルをメディアに読み込みました',},+ saved: {+ title: 'コレクション',+ back: 'プロジェクトの素材に戻る',+ add: 'コレクションに追加',+ addTogether: '{n} 個のクリップをまとめてコレクションに追加',+ addEach: '1 つずつコレクションに追加',+ added: 'コレクションに追加しました',+ addedMany: '{n} 件をコレクションに追加しました',+ failed: 'コレクションに追加できませんでした:{error}',+ emptyTitle: 'コレクションはまだ空です',+ emptyBody: 'コレクションはどのプロジェクトでも使えます。どんなファイルでもアップロードやドロップで追加でき、タイムラインのクリップを右クリックして「コレクションに追加」も選べます。',+ template: 'テンプレート',+ kind_clip: 'クリップ',+ kind_group: 'クリップ群',+ kind_page: 'ページ',+ },media: {insertSource: "再生ヘッドに挿入",overwriteSource: "再生ヘッドに上書き",- close: '閉じる',results: '結果',moveFailed: 'そこへ移動できませんでした。',moveAskTitle: '一部のパスは自動で更新できません',@@ -888,6 +948,13 @@ export const ja: Words = {sound: 'サウンド',gainDb: '音量',pageChanges: 'ページ内の変更',+ template: 'テンプレート',+ templateOffPicture: '再生ヘッドをこのクリップに合わせると、ページで変えられる項目が表示されます。',+ templateText: 'テキスト',+ templateReset: 'ページの元の値に戻す',+ templatePicture: '画像',+ templatePictureReplace: '画像を置き換え',+ templatePictureComputer: 'このコンピュータから…',pageChangeLost: 'ページ内にもうありません',pageChangeRemove: 'この変更を取り消す',pageChangeText: 'テキスト',@@ -1370,7 +1437,7 @@ export const ja: Words = {sections: {agents: 'エージェント',providers: 'プロバイダー',- models: 'モデル',+ models: 'サービス',developer: '開発者',general: '一般',shortcuts: 'キーボードショートカット',@@ -1386,6 +1453,18 @@ export const ja: Words = {themeHint: 'ライト、ダーク、またはシステムに合わせる。',languageHint: 'OpenFilm の表示言語。',},+ storage: {+ group: '保存場所',+ projects: '新しいプロジェクト',+ projectsHint: '新しいプロジェクトの保存先です。素材やキャッシュもプロジェクト内に置かれます。以前のプロジェクトはそのままの場所で開けます。',+ projectsPick: '新しいプロジェクトの保存先を選択',+ pickButton: '選択',+ change: '変更…',+ show: '開く',+ reset: 'デフォルトに戻す',+ save: '保存',+ free: 'このディスクの空き容量 {size}',+ },playback: {group: "再生",proxies: "重い素材にプロキシを使う",@@ -1405,7 +1484,7 @@ export const ja: Words = {never: 'まだ確認していません。',inApp: 'Studio はデスクトップアプリと一緒に更新されます:OpenFilm → Check for Updates…',howTitle: 'アップデート',- how: 'このコマンドを実行するか、エージェントに実行を頼んでください。Studio が新しいバージョンで再起動します。',+ how: '「アップデート」をクリックするか、このコマンドを実行するか、エージェントに OpenFilm のアップデートを頼んでください。Studio が新しいバージョンで再起動します。',appOff: 'ソースから実行している開発版のため自動では更新されません。インストール版は自動で更新されます。',appChecked: '前回の確認:{time}。',appDownloading: 'OpenFilm {version} をダウンロード中…',@@ -1417,7 +1496,7 @@ export const ja: Words = {appFailed: 'アップデートを完了できませんでした。しばらくしてからお試しください。',},agents: {- intro: 'チャットで使えるエージェントです。Codex や Claude Code など「あなたのエージェント」はあなた自身のもので、このコンピューターでサインイン中のアカウントを使います。別のアカウントを使うには、エージェント側でアカウントを切り替え、ここで接続を解除してもう一度接続してください。自分のキーはあなたのサービスで動きます。',+ intro: '会話で使えるエージェントです。Codex、Claude Code など「あなたのエージェント」はあなた自身のもので、このコンピュータでサインインしているアカウントを使います。アカウントを変えるには、エージェント側で切り替えてから、ここで接続を解除して再接続してください。自分のキーは自分で設定したモデルで動き、モデルごとに別のサービスを使えます。',byokName: '自分のキー',groupYours: 'あなたのエージェント',groupMore: 'ほかに使えるエージェント',@@ -1426,7 +1505,7 @@ export const ja: Words = {ready: '接続済み',off: '未接続',signedOut: 'サインインしていません',- waiting: 'ターミナルでのサインインを待っています…',+ waiting: 'サインインを待っています…',waitingHint: '開いたウィンドウでサインインを完了してから、戻ってきてください。',startAgain: 'やり直す',missing: 'このコンピューターにインストールされていません',@@ -1438,6 +1517,7 @@ export const ja: Words = {automatic: '自動検出に戻す',notAProgram: 'このコンピュータで起動できるプログラムではありません。エージェントのプログラム自体を選んでください(Windows では .exe または .cmd ファイル)。',didNotStart: 'ここからは起動できませんでした:',+ unreadable: '自分の設定を読み込めないため起動できません。設定ファイルの該当箇所を直すか、更新してください:',whyMissing: '見つからない理由は?',searching: '検索中…',hintChosenMissing: '選択したプログラムが見つかりません。もう一度選ぶか、自動検出に戻してください。',@@ -1476,19 +1556,34 @@ export const ja: Words = {address: 'アドレス',model: 'モデル',modelPlaceholder: 'サービスでのモデル名',- addModel: '追加',+ addModel: 'モデルを追加',+ name: '名前',+ namePlaceholder: 'チャットに表示される名前(空欄ならモデル名)',+ edit: '編集',+ done: '完了',+ keySame: '空欄なら「{name}」のキーを使います',removeModel: '{name} を削除',efforts: '推論の強さ',effortStart: '最初の強さ',- effortHint: '各モデルが対応する推論の強さにチェックを入れてください。チャットではそれだけが選べます。「自動」は何も送らず、サービスに任せます。',+ effortHint: 'このモデルが対応する推論の強さにチェックを入れてください。チャットではそれだけが選べます。「自動」は何も送らず、サービスに任せます。',effortLevels: { auto: '自動', off: 'オフ', minimal: '最小', low: '低', medium: '中', high: '高', xhigh: '特高', max: '最大' },key: 'API キー',keyPlaceholder: 'API キーを貼り付け',keyKept: '末尾が {last4} のキー(空欄のままにすると現在のキーを使います)',- byokNote: 'どのモデルも画像を読める必要があります。エージェントは自分で作ったフレームを確認するためです。キーはこのコンピューターに保存され、そのサービス以外には送信されません。',+ byokNote: 'どのモデルも画像を読める必要があります。エージェントは自分で作ったフレームを確認するためです。キーはこのコンピューターに保存され、それぞれのサービス以外には送信されません。',save: '確認して保存',checkingKey: '確認中…',cancel: 'キャンセル',+ mcpSummary: 'あなたの MCP サーバー:{n} 個のうち {on} 個を OpenFilm で使用',+ mcpManage: '選ぶ',+ mcpDone: '完了',+ mcpNote: '{agent} に自分で追加した MCP サーバーは、オンにするまで OpenFilm では使いません。{agent} 自身のものは常に使えます。',+ mcpAllow: 'OpenFilm で {name} を使う',+ skillsSummary: 'あなたのスキル:{n} 個のうち {on} 個を OpenFilm で使用',+ skillsNote: '{agent} に自分で入れたスキルは、毎回同じように仕上がるよう、オンにするまで OpenFilm では使いません。{agent} 自身のものは常に使えます。',+ skillsAllow: 'OpenFilm で {name} を使う',+ skillsUnfiltered: '{agent} は本来のアプリと同じく、OpenFilm でも自分のスキル {n} 個をすべて使います。',+ mcpUnfiltered: '{agent} は本来のアプリと同じく、OpenFilm でも自分の MCP サーバー {n} 個をすべて使います。',},developer: {intro: 'エージェントが何をなぜ行ったかを正確に確かめるためのものです。エージェントの動作は変わりません。',@@ -1568,7 +1663,7 @@ export const ja: Words = {copyDrag: '押しながらクリップをドラッグ:離した位置にコピー、元のクリップはそのまま',},providers: {- desc: '音声、音楽、効果音、書き起こし、画像、ビデオの提供元です。OpenFilm はこれらがなくても映像の作成・編集ができます。エージェントがメディアを必要とするときに接続してください。',+ desc: '音声、音楽、効果音、書き起こし、画像、ビデオの提供元です。OpenFilm はこれらがなくても映像の作成・編集ができます。エージェントがメディアを必要とするときに接続してください。各種メディアにどれを使うかは「サービス」で選びます。',connect: '接続',disconnect: '接続を解除',connected: '接続済み',@@ -1581,9 +1676,9 @@ export const ja: Words = {keyEnding: '末尾が {last4} のキー',useEnv: '環境変数 ${env} のキーを使う',own: {- title: "自分のサービス",- note: "自分で動かしている、または使っている任意のサービス(このコンピュータ上でもオンラインでも可:自分の声、文字起こしサーバー、ここにない API など)。エージェントはそのアドレスで利用し、キーはこのコンピュータに残ります。何ができるかを書いておくと、エージェントがいつ使うか判断できます。",- add: "サービスを追加",+ title: "カスタムサービス",+ note: "上に一覧にないサービスをいくつでも追加できます。このコンピュータで動かしているものでもオンラインのものでも構いません(自分の声、文字起こしサーバー、一覧にない API など)。インターフェースは自由です。OpenFilm 自体は呼び出しません。エージェントが説明を読んで呼び出し、キーはこのコンピュータに残り、エージェントからは見えません。ここに追加せず、チャットでエージェントに伝えることもできます。キーが必要なサービスはここに追加すると、キーが会話に出ません。",+ add: "カスタムサービスを追加",edit: "編集",remove: "削除",name: "名前",@@ -1593,9 +1688,8 @@ export const ja: Words = {keyOptional: "省略可",keyKeep: "空欄のままにすると末尾 {last4} のキーを保持します",removeKey: "キーを削除",- auth: "キーの送り先",- what: "できること",- whatPlaceholder: "例:原稿を自分の声で読み上げる:POST /tts に {\"text\": \"…\"} を送ると WAV を返す。ドキュメント:https://…",+ what: "説明",+ whatPlaceholder: "例:原稿を自分の声で読み上げる:POST /tts に {\"text\": \"…\"} を送ると WAV を返す。API ドキュメントの URL だけでも可:https://…",},verbs: {tts: 'ナレーション',@@ -1611,12 +1705,11 @@ export const ja: Words = {},},models: {- desc: '各種メディアをどのプロバイダーとモデルで作成するかを設定します。プロバイダーを接続すると、未設定の種類に自動で割り当てられます。ここでいつでも変更できます。',+ desc: '各種メディアをどのサービスで作成するか:接続したプロバイダーのモデルから選びます。プロバイダーを接続すると、未設定の種類に自動で割り当てられます。ここでいつでも変更できます。',nothing: 'まだ何も接続されていません。プロバイダーを接続するとモデルを選べます。',goConnect: 'プロバイダーを接続',none: 'なし',connectNamed: '{names} を接続',- otherBody: "一覧にないサービスやモデルを使いたい場合は、「プロバイダ → 自分のサービス」にアドレスとキーを追加すると、エージェントが使えるようになります。作成されたものは、他と同じく素材に入ります。",about: {tts: '台本を読み上げ、読み上げる声を探します',music: '説明からサウンドトラックを作成します',diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex ae4d513..e2e8311 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -9,6 +9,44 @@ export const ko: Words = {projects: '프로젝트',desktop: '데스크톱',},+ /* the app window's tabs (TabStrip), a new tab's launcher, and the examples (ExamplesGallery) */+ tabs: { label: '탭', new: '프로젝트 열기', close: '탭 닫기' },+ launcher: { projects: '내 프로젝트', examples: '예시' },+ gallery: {+ title: '예시',+ community: '커뮤니티',+ discoverNote: 'OpenFilm으로 만든 영상. 여기서 시작하거나 만든 방식을 참고하세요.',+ noSkills: '아직 내 스킬이 없습니다. 브랜드, 시리즈의 분위기, 늘 쓰는 오프닝을 스킬로 저장하면 모든 영상이 그것을 따를 수 있습니다. 링크나 폴더로 추가하거나, 마음에 드는 영상을 에이전트에게 스킬로 저장해 달라고 하세요.',+ all: '전체',+ workflow: '작업',+ style: '스타일',+ skillKinds: '스킬은 두 가지입니다.\n· 내 스킬: 브랜드, 시리즈의 분위기, 늘 쓰는 오프닝과 엔딩처럼 당신만 아는 것을 저장합니다. AI가 아무리 똑똑해도 추측할 수 없으니, 한 번 저장해 두면 모든 영상에 쓸 수 있습니다.\n· OpenFilm의 스킬: 어떤 종류의 영상을 빠르게 만드는 기성 방법입니다. AI가 똑똑해질수록 점점 덜 필요해집니다.',+ search: '스킬 검색',+ noMatch: '일치하는 스킬이 없습니다.',+ aboutSkills: '스킬에 대해',+ fromFolder: '폴더',+ made: '직접 만든 스킬',+ skills: '스킬',+ loading: '예시를 읽는 중…',+ empty: '표시할 예시가 없습니다. 예시는 GitHub에서 읽어 옵니다. 연결을 확인하세요.',+ start: '이것으로 시작',+ startNew: '이것으로 새 영상 시작',+ startHow: '복사본이 새 프로젝트가 되고, 소스를 바로 바꿀 수 있습니다.',+ reference: '이 영상에서 참고',+ referencePart: '이 부분 참고',+ referenceHow: '메시지에 들어갑니다. 에이전트가 만든 방식(페이지와 타이밍)을 읽고 당신의 영상에 적용합니다.',+ referenceNote: '예시나 그 일부를 골라 에이전트가 참고하게 하세요',+ parts: '구간',+ whole: '전체',+ partsHint: '구간을 클릭하거나 막대 위를 드래그해 범위를 고르세요.',+ viewSource: 'GitHub에서 보기',+ back: '뒤로',+ useSkill: '이 스킬 사용',+ mine: '내 스킬',+ project: '이 프로젝트',+ addSkill: '스킬 추가',+ cat: { launch: '제품 출시', explainer: '해설', slides: '슬라이드를 영상으로', captions: '자막과 타이틀', ads: '광고', commerce: '판매 포인트', music: '음악' },+ },/* the app's update, ready to install (Studio's top bar, in an app that has updates: lib/host.ts `update`) */update: {restart: '재시작하여 업데이트',@@ -17,6 +55,12 @@ export const ko: Words = {exporting: '내보내는 중입니다. 끝난 뒤 재시작하세요.',installFailed: 'OpenFilm {version}을(를) 설치하지 못했습니다. OpenFilm을 종료했다가 다시 열면 설치됩니다.',installing: '재시작하는 중…',+ webUpdate: '업데이트',+ webAvailable: 'OpenFilm {version}이(가) 나왔습니다. Studio가 새 버전으로 다시 시작되고, 열려 있던 페이지는 자동으로 돌아옵니다.',+ webUpdating: '업데이트 중…',+ webExporting: '내보내는 중입니다. 끝난 뒤에 업데이트하세요.',+ webMaking: '미디어를 만드는 중입니다. 끝난 뒤에 업데이트하세요.',+ webFailed: '업데이트하지 못했습니다: {error}',},whatsNew: {eyebrow: '업데이트됨',@@ -466,6 +510,7 @@ export const ko: Words = {editsRestore: '복원',editsLeaveOut: '제외',previewFailed: '미리보기를 그릴 수 없습니다.',+ previewBrowser: '이 페이지는 현재 브라우저가 지원하지 않는 기능을 사용합니다. 영상은 Chromium으로 그리고 내보내므로 Studio를 Chrome이나 Edge에서 여세요.',previewMissing: '미디어 없음: {file} · 클립 오른쪽 클릭으로 다시 연결',filmEmptyHint: '미디어를 타임라인으로 끌어와 영상을 시작하거나, 에이전트에게 만들어 달라고 요청하세요.',filmBroken: '지금은 film.html을 읽을 수 없어 Studio가 마지막 상태의 영상을 보여 줍니다. 문제가 해결될 때까지 여기서 한 편집은 저장할 수 없습니다:',@@ -702,10 +747,25 @@ export const ko: Words = {unreadable: '“{name}”을(를) 가져왔지만 이미지, 비디오 또는 사운드로 읽을 수 없습니다({why}). 파일을 확인하거나 다른 사본을 가져오세요.',imported: '파일 {n}개를 미디어로 가져왔습니다',},+ saved: {+ title: '보관함',+ back: '프로젝트 미디어로 돌아가기',+ add: '보관함에 추가',+ addTogether: '클립 {n}개를 하나로 보관함에 추가',+ addEach: '하나씩 보관함에 추가',+ added: '보관함에 추가했습니다',+ addedMany: '{n}개를 보관함에 추가했습니다',+ failed: '보관함에 추가하지 못했습니다: {error}',+ emptyTitle: '보관함이 아직 비어 있습니다',+ emptyBody: '보관함은 모든 프로젝트에서 쓸 수 있습니다. 어떤 파일이든 업로드하거나 끌어다 놓고, 타임라인의 클립을 오른쪽 클릭해 보관함에 추가할 수도 있습니다.',+ template: '템플릿',+ kind_clip: '클립',+ kind_group: '클립 묶음',+ kind_page: '페이지',+ },media: {insertSource: "재생 헤드에 삽입",overwriteSource: "재생 헤드에 덮어쓰기",- close: '닫기',results: '결과',moveFailed: '그곳으로 옮길 수 없습니다.',moveAskTitle: '일부 경로는 자동으로 바꿀 수 없습니다',@@ -888,6 +948,13 @@ export const ko: Words = {sound: '사운드',gainDb: '볼륨',pageChanges: '페이지 안의 변경 사항',+ template: '템플릿',+ templateOffPicture: '재생 헤드를 이 클립 위로 옮기면 페이지에서 바꿀 수 있는 항목이 보입니다.',+ templateText: '텍스트',+ templateReset: '페이지 원래 값으로',+ templatePicture: '이미지',+ templatePictureReplace: '이미지 바꾸기',+ templatePictureComputer: '이 컴퓨터에서…',pageChangeLost: '더 이상 페이지에 없음',pageChangeRemove: '이 변경 취소',pageChangeText: '텍스트',@@ -1369,7 +1436,7 @@ export const ko: Words = {sections: {agents: '에이전트',providers: '제공업체',- models: '모델',+ models: '서비스',developer: '개발자',general: '일반',shortcuts: '키보드 단축키',@@ -1385,6 +1452,18 @@ export const ko: Words = {themeHint: '라이트, 다크 또는 시스템 설정을 따릅니다.',languageHint: 'OpenFilm 화면에 표시되는 언어.',},+ storage: {+ group: '저장 위치',+ projects: '새 프로젝트',+ projectsHint: '새 프로젝트가 저장되는 곳입니다. 소재와 캐시도 프로젝트 안에 있습니다. 이전 프로젝트는 원래 위치에서 그대로 열 수 있습니다.',+ projectsPick: '새 프로젝트 위치 선택',+ pickButton: '선택',+ change: '변경…',+ show: '열기',+ reset: '기본값으로',+ save: '저장',+ free: '이 디스크 남은 공간 {size}',+ },playback: {group: "재생",proxies: "무거운 영상에 프록시 사용",@@ -1404,7 +1483,7 @@ export const ko: Words = {never: '아직 확인하지 않았습니다.',inApp: 'Studio는 데스크톱 앱과 함께 업데이트됩니다: OpenFilm → Check for Updates…',howTitle: '업데이트',- how: '이 명령을 실행하거나 에이전트에게 실행을 맡기세요. Studio가 새 버전으로 다시 시작됩니다.',+ how: '"업데이트"를 누르거나, 이 명령을 실행하거나, 에이전트에게 OpenFilm 업데이트를 맡기세요. Studio가 새 버전으로 다시 시작됩니다.',appOff: '소스에서 실행 중인 개발 빌드라 자동으로 업데이트되지 않습니다. 설치된 앱은 자동으로 업데이트됩니다.',appChecked: '마지막 확인: {time}.',appDownloading: 'OpenFilm {version} 다운로드 중…',@@ -1416,7 +1495,7 @@ export const ko: Words = {appFailed: '업데이트를 완료하지 못했습니다. 나중에 다시 시도하세요.',},agents: {- intro: '채팅에서 쓸 수 있는 에이전트입니다. Codex, Claude Code 등 「내 에이전트」는 나의 것이며 이 컴퓨터에 로그인된 계정을 사용합니다. 다른 계정을 쓰려면 에이전트에서 계정을 바꾼 뒤 여기서 연결을 해제했다가 다시 연결하세요. 내 키는 내 서비스에서 실행됩니다.',+ intro: '채팅에서 쓸 수 있는 에이전트입니다. Codex, Claude Code 등 「내 에이전트」는 나의 것이며 이 컴퓨터에 로그인된 계정을 사용합니다. 다른 계정을 쓰려면 에이전트에서 계정을 바꾼 뒤 여기서 연결을 끊고 다시 연결하세요. 내 키는 직접 설정한 모델로 실행되며, 모델마다 다른 서비스를 쓸 수 있습니다.',byokName: '내 키',groupYours: '내 에이전트',groupMore: '그 밖에 쓸 수 있는 에이전트',@@ -1425,7 +1504,7 @@ export const ko: Words = {ready: '연결됨',off: '연결 안 됨',signedOut: '로그인하지 않음',- waiting: '터미널에서 로그인을 기다리는 중…',+ waiting: '로그인을 기다리는 중…',waitingHint: '열린 창에서 로그인을 완료한 뒤 돌아오세요.',startAgain: '다시 시작',missing: '이 컴퓨터에 설치되어 있지 않음',@@ -1437,6 +1516,7 @@ export const ko: Words = {automatic: '자동 감지로 되돌리기',notAProgram: '이 컴퓨터에서 실행할 수 있는 프로그램이 아닙니다. 에이전트 프로그램 자체를 선택하세요(Windows에서는 .exe 또는 .cmd 파일).',didNotStart: '여기서 실행하지 못했습니다:',+ unreadable: '자체 설정을 읽지 못해 시작할 수 없습니다. 설정 파일에서 지적된 부분을 고치거나 업데이트하세요:',whyMissing: '왜 찾지 못하나요?',searching: '찾는 중…',hintChosenMissing: '선택한 프로그램이 더 이상 없습니다. 다시 선택하거나 자동 감지로 되돌리세요.',@@ -1475,19 +1555,34 @@ export const ko: Words = {address: '주소',model: '모델',modelPlaceholder: '서비스에서 쓰는 모델 이름',- addModel: '추가',+ addModel: '모델 추가',+ name: '이름',+ namePlaceholder: '채팅에 표시되는 이름(비워 두면 모델 이름)',+ edit: '편집',+ done: '완료',+ keySame: '비워 두면 "{name}"의 키를 사용합니다',removeModel: '{name} 삭제',efforts: '추론 강도',effortStart: '시작 강도',- effortHint: '모델마다 지원하는 추론 강도를 체크하세요. 채팅에는 체크한 것만 나옵니다. "자동"은 아무것도 보내지 않고 서비스에 맡깁니다.',+ effortHint: '이 모델이 지원하는 추론 강도를 체크하세요. 채팅에는 체크한 것만 나옵니다. "자동"은 아무것도 보내지 않고 서비스에 맡깁니다.',effortLevels: { auto: '자동', off: '끔', minimal: '최소', low: '낮음', medium: '중간', high: '높음', xhigh: '매우 높음', max: '최대' },key: 'API 키',keyPlaceholder: 'API 키 붙여넣기',keyKept: '{last4}(으)로 끝나는 키(유지하려면 비워 두세요)',- byokNote: '모든 모델이 이미지를 읽을 수 있어야 합니다. 에이전트가 직접 만든 프레임을 확인하기 때문입니다. 키는 이 컴퓨터에만 저장되며 해당 서비스로만 전송됩니다.',+ byokNote: '모든 모델이 이미지를 읽을 수 있어야 합니다. 에이전트가 직접 만든 프레임을 확인하기 때문입니다. 키는 이 컴퓨터에만 저장되며 각자의 서비스로만 전송됩니다.',save: '확인 후 저장',checkingKey: '확인 중…',cancel: '취소',+ mcpSummary: '내 MCP 서버: {n}개 중 {on}개를 OpenFilm에서 사용',+ mcpManage: '선택',+ mcpDone: '완료',+ mcpNote: '{agent}에 직접 추가한 MCP 서버는 켜기 전에는 OpenFilm에서 사용하지 않습니다. {agent} 자체 서버는 항상 사용됩니다.',+ mcpAllow: 'OpenFilm에서 {name} 사용',+ skillsSummary: '내 스킬: {n}개 중 {on}개를 OpenFilm에서 사용',+ skillsNote: '{agent}에 직접 설치한 스킬은 매번 같은 결과가 나오도록 켜기 전에는 OpenFilm에서 사용하지 않습니다. {agent} 자체 스킬은 항상 사용됩니다.',+ skillsAllow: 'OpenFilm에서 {name} 사용',+ skillsUnfiltered: '{agent}는 자체 앱에서처럼 OpenFilm에서도 내 스킬 {n}개를 모두 사용합니다.',+ mcpUnfiltered: '{agent}는 자체 앱에서처럼 OpenFilm에서도 내 MCP 서버 {n}개를 모두 사용합니다.',},developer: {intro: '에이전트가 무엇을 왜 했는지 정확히 확인하기 위한 기능입니다. 에이전트의 동작은 바뀌지 않습니다.',@@ -1567,7 +1662,7 @@ export const ko: Words = {copyDrag: '누른 채 클립 드래그: 놓은 자리에 복사본, 원래 클립은 그대로',},providers: {- desc: '음성, 음악, 효과음, 대본, 이미지, 비디오를 가져오는 곳입니다. OpenFilm은 이 서비스 없이도 영상을 만들고 편집합니다. 에이전트에게 미디어가 필요할 때 연결하세요.',+ desc: '음성, 음악, 효과음, 대본, 이미지, 비디오를 가져오는 곳입니다. OpenFilm은 이 서비스 없이도 영상을 만들고 편집합니다. 에이전트에게 미디어가 필요할 때 연결하세요. 각 미디어에 무엇을 쓸지는 「서비스」에서 고릅니다.',connect: '연결',disconnect: '연결 해제',connected: '연결됨',@@ -1580,9 +1675,9 @@ export const ko: Words = {keyEnding: '{last4}(으)로 끝나는 키',useEnv: '환경 변수 ${env}의 키 사용',own: {- title: "내 서비스",- note: "직접 실행하거나 사용하는 모든 서비스(이 컴퓨터에서든 온라인이든: 내 목소리, 음성 인식 서버, 여기에 없는 API 등). 에이전트는 주소로 접근하며, 키는 이 컴퓨터에만 남습니다. 무엇을 하는지 적어 두면 에이전트가 언제 쓸지 압니다.",- add: "서비스 추가",+ title: "사용자 지정 서비스",+ note: "위 목록에 없는 서비스를 개수 제한 없이 추가할 수 있습니다. 이 컴퓨터에서 실행하는 것이든 온라인이든 괜찮습니다(내 목소리, 음성 인식 서버, 목록에 없는 API 등). 인터페이스는 자유입니다. OpenFilm이 직접 호출하지는 않습니다. 에이전트가 설명을 읽고 호출하며, 키는 이 컴퓨터에 남고 에이전트에게는 보이지 않습니다. 여기에 추가하지 않고 채팅에서 에이전트에게 알려 줄 수도 있습니다. 키가 필요한 서비스는 여기에 추가하면 키가 대화에 나오지 않습니다.",+ add: "사용자 지정 서비스 추가",edit: "편집",remove: "삭제",name: "이름",@@ -1592,9 +1687,8 @@ export const ko: Words = {keyOptional: "선택 사항",keyKeep: "비워 두면 끝자리가 {last4}인 키를 유지합니다",removeKey: "키 삭제",- auth: "키를 넣을 곳",- what: "하는 일",- whatPlaceholder: "예: 대본을 내 목소리로 읽음: POST /tts에 {\"text\": \"…\"}를 보내면 WAV를 반환. 문서: https://…",+ what: "설명",+ whatPlaceholder: "예: 대본을 내 목소리로 읽음: POST /tts에 {\"text\": \"…\"}를 보내면 WAV를 반환. API 문서 주소만 적어도 됩니다: https://…",},verbs: {tts: '보이스오버',@@ -1610,12 +1704,11 @@ export const ko: Words = {},},models: {- desc: '각 종류의 미디어를 만드는 제공업체와 모델입니다. 제공업체를 연결하면 아직 지정되지 않은 종류가 채워지며, 여기서 언제든 바꿀 수 있습니다.',+ desc: '각 종류의 미디어를 어떤 서비스로 만들지 정합니다: 연결한 제공업체의 모델 중에서 고릅니다. 제공업체를 연결하면 아직 지정되지 않은 종류가 채워지며, 여기서 언제든 바꿀 수 있습니다.',nothing: '아직 연결된 것이 없습니다. 제공업체를 연결하고 모델을 선택하세요.',goConnect: '제공업체 연결',none: '없음',connectNamed: '{names} 연결',- otherBody: "목록에 없는 서비스나 모델을 원하세요? ‘제공업체 → 내 서비스’에 주소와 키를 추가하면 에이전트가 사용할 수 있습니다. 만든 결과물은 다른 것과 마찬가지로 에셋에 들어갑니다.",about: {tts: '대본을 읽고, 읽을 음성을 찾습니다',music: '설명으로 사운드트랙을 만듭니다',diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 7c515ce..1584353 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -10,6 +10,44 @@ export const zhCN: Words = {projects: '项目',desktop: '桌面版',},+ /* the app window's tabs (TabStrip), a new tab's launcher, and the examples (ExamplesGallery) */+ tabs: { label: '标签页', new: '打开项目', close: '关闭标签页' },+ launcher: { projects: '我的项目', examples: '示例' },+ gallery: {+ title: '示例',+ community: '社区',+ discoverNote: '用 OpenFilm 做的片子,可以从它开始,也可以参考它的做法。',+ noSkills: '还没有你的 skill。把品牌、系列风格、固定片头片尾存成 skill,以后每部片子都能保持一致。可以从链接或文件夹添加,也可以在做完一部满意的片子后,让 agent 把它存成 skill。',+ all: '全部',+ workflow: '场景',+ style: '风格',+ skillKinds: 'Skill 有两种:\n· 你自己的:存着只有你知道的东西,比如你的品牌、系列风格、固定的片头片尾。AI 再聪明也猜不到,存一次,以后每部片子都能用上。\n· OpenFilm 提供的:做某一类片子的现成做法,帮你快速上手。AI 越来越强,这类会越来越用不上。',+ search: '搜索 skill',+ noMatch: '没有匹配的 skill。',+ aboutSkills: '关于 skill',+ fromFolder: '文件夹',+ made: '你做的',+ skills: 'Skill',+ loading: '正在读取示例…',+ empty: '没有可显示的示例。示例从 GitHub 读取,请检查网络。',+ start: '用它开始',+ startNew: '用它开始一部新片',+ startHow: '会复制一份成为你的新项目,源码可以直接改。',+ reference: '在这部片子里参考',+ referencePart: '参考这一段',+ referenceHow: '会放进你的消息里。agent 会读它是怎么做的(页面和时间),照着用在你的片子里。',+ referenceNote: '选一个示例,或者其中一段,让 agent 参考着做',+ parts: '分段',+ whole: '整部',+ partsHint: '点一段,或者在条上拖出一段。',+ viewSource: '在 GitHub 上查看',+ back: '返回',+ useSkill: '使用这个 skill',+ mine: '我的',+ project: '本项目',+ addSkill: '添加 skill',+ cat: { launch: '产品发布', explainer: '科普讲解', slides: '幻灯片转视频', captions: '字幕与花字', ads: '广告', commerce: '电商卖点', music: '音乐' },+ },/* the app's update, ready to install (Studio's top bar, in an app that has updates: lib/host.ts `update`) */update: {restart: '重启以更新',@@ -18,6 +56,12 @@ export const zhCN: Words = {exporting: '正在导出,导出完成后再重启。',installFailed: 'OpenFilm {version} 暂时无法安装。退出 OpenFilm 后重新打开即可安装。',installing: '正在重启…',+ webUpdate: '更新',+ webAvailable: 'OpenFilm {version} 已发布。更新后 Studio 会在新版本上重启,已打开的页面会自动回来。',+ webUpdating: '正在更新…',+ webExporting: '正在导出,导出完成后再更新。',+ webMaking: '正在生成素材,完成后再更新。',+ webFailed: '更新失败:{error}',},whatsNew: {eyebrow: '已更新',@@ -467,6 +511,7 @@ export const zhCN: Words = {editsRestore: '恢复它们',editsLeaveOut: '不恢复',previewFailed: '无法绘制预览。',+ previewBrowser: '这个页面用到了当前浏览器不支持的功能。影片是用 Chromium 绘制和导出的,请在 Chrome 或 Edge 里打开 Studio。',previewMissing: '媒体丢失:{file} · 右键片段重新链接',filmEmptyHint: '把媒体拖到时间轴上开始制作影片,或让智能体帮你做一部。',filmBroken: '目前无法读取 film.html,因此 Studio 显示的是影片上一次的样子;修复之前,这里的编辑无法保存:',@@ -703,10 +748,25 @@ export const zhCN: Words = {unreadable: '“{name}”已导入,但无法作为图片、视频或声音读取({why})。请检查该文件,或导入另一份副本。',imported: '已将 {n} 个文件导入到媒体',},+ saved: {+ title: '收藏',+ back: '回到项目素材',+ add: '收藏',+ addTogether: '把 {n} 个片段收藏为一组',+ addEach: '逐个收藏',+ added: '已收藏',+ addedMany: '已收藏 {n} 项',+ failed: '收藏失败:{error}',+ emptyTitle: '收藏里还没有东西',+ emptyBody: '收藏在所有项目里都能用。可以上传或拖入任何文件,也可以在时间轴的片段上右键选「收藏」。',+ template: '模板',+ kind_clip: '片段',+ kind_group: '片段组',+ kind_page: '页面',+ },media: {insertSource: "在播放头处插入",overwriteSource: "在播放头处覆盖",- close: '关闭',results: '结果',moveFailed: '无法移动到那里。',moveAskTitle: '有些路径无法自动更新',@@ -889,6 +949,13 @@ export const zhCN: Words = {sound: '声音',gainDb: '音量',pageChanges: '页面内的修改',+ template: '模板参数',+ templateOffPicture: '把播放头移到这个片段上,就能看到它的页面可以改哪些参数。',+ templateText: '文字',+ templateReset: '恢复页面原值',+ templatePicture: '图片',+ templatePictureReplace: '替换图片',+ templatePictureComputer: '从这台电脑选择…',pageChangeLost: '已不在页面中',pageChangeRemove: '撤销此修改',pageChangeText: '文字',@@ -1371,7 +1438,7 @@ export const zhCN: Words = {sections: {agents: '智能体',providers: '服务商',- models: '模型',+ models: '服务',developer: '开发者',general: '通用',shortcuts: '键盘快捷键',@@ -1387,6 +1454,18 @@ export const zhCN: Words = {themeHint: '浅色、深色,或跟随系统。',languageHint: 'OpenFilm 界面使用的语言。',},+ storage: {+ group: '存储位置',+ projects: '新项目位置',+ projectsHint: '新建的项目放在这里,素材和缓存也在项目里。之前的项目留在原处,照常可以打开。',+ projectsPick: '选择新项目的位置',+ pickButton: '选择',+ change: '更改…',+ show: '打开',+ reset: '恢复默认',+ save: '保存',+ free: '所在磁盘剩余 {size}',+ },playback: {group: "播放",proxies: "为大体积素材生成代理",@@ -1406,7 +1485,7 @@ export const zhCN: Words = {never: '还没有检查过。',inApp: 'Studio 随桌面端一起更新:OpenFilm → Check for Updates…',howTitle: '更新',- how: '运行这条命令,或让你的智能体运行:Studio 会以新版本重新启动。',+ how: '点「更新」,或运行这条命令,或让你的智能体更新 OpenFilm:Studio 会以新版本重新启动。',appOff: '这是从源码运行的开发版,不会自动更新;安装的正式版会自己更新。',appChecked: '上次检查:{time}。',appDownloading: '正在下载 OpenFilm {version}…',@@ -1418,7 +1497,7 @@ export const zhCN: Words = {appFailed: '更新没能完成,请稍后再试。',},agents: {- intro: '对话可以使用的智能体。Codex、Claude Code 等「你的智能体」是你自己的,使用这台电脑上已登录的账号:想换账号,就在智能体自己那里切换,再回到这里断开、重新连接。自有密钥运行在你自己的服务上。',+ intro: '对话可以使用的智能体。Codex、Claude Code 等「你的智能体」是你自己的,使用这台电脑上已登录的账号:想换账号,就在智能体里切换,再回到这里断开后重新连接。自有密钥使用你自己配置的模型,每个模型可以接不同的服务。',byokName: '自有密钥',groupYours: '你的智能体',groupMore: '还可以接入的智能体',@@ -1427,7 +1506,7 @@ export const zhCN: Words = {ready: '已连接',off: '未连接',signedOut: '未登录',- waiting: '正在等待终端中的登录…',+ waiting: '正在等待你完成登录…',waitingHint: '请在刚打开的窗口中完成登录,然后回到这里。',startAgain: '重新开始',missing: '这台电脑上尚未安装',@@ -1437,8 +1516,9 @@ export const zhCN: Words = {locateButton: '使用这个',chosenAt: '正在使用你选择的程序:{path}',automatic: '改回自动检测',- notAProgram: '这不是这台电脑能启动的程序。请选择 agent 程序本身(Windows 上是 .exe 或 .cmd 文件)。',+ notAProgram: '这不是这台电脑能启动的程序。请选择智能体程序本身(Windows 上是 .exe 或 .cmd 文件)。',didNotStart: '从这里启动失败:',+ unreadable: '它读不了自己的设置,所以无法启动。请修改它的配置文件里提到的那一项,或更新它:',whyMissing: '为什么检测不到?',searching: '正在查找…',hintChosenMissing: '你选择的程序已经不在了。重新选择,或改回自动检测。',@@ -1477,27 +1557,42 @@ export const zhCN: Words = {address: '地址',model: '模型',modelPlaceholder: '模型名,与服务中的写法一致',- addModel: '添加',+ addModel: '添加模型',+ name: '名称',+ namePlaceholder: '聊天里显示的名字(留空则用模型名)',+ edit: '编辑',+ done: '完成',+ keySame: '留空则使用「{name}」的密钥',removeModel: '移除 {name}',efforts: '推理档位',effortStart: '起始档位',- effortHint: '勾选每个模型支持的推理档位,聊天里只会出现这些档位。「自动」不发送推理参数,由服务决定。',+ effortHint: '勾选这个模型支持的推理档位,聊天里只会出现这些档位。「自动」不发送推理参数,由服务决定。',effortLevels: { auto: '自动', off: '不思考', minimal: '极低', low: '低', medium: '中', high: '高', xhigh: '超高', max: '最高' },key: 'API 密钥',keyPlaceholder: '粘贴你的 API 密钥',keyKept: '尾号为 {last4} 的密钥(留空则保留)',- byokNote: '每个模型都需要能看图:智能体会查看自己生成的画面。你的密钥只保存在这台电脑上,且只会发送给该服务。',+ byokNote: '每个模型都需要能看图:智能体会查看自己生成的画面。密钥只保存在这台电脑上,且只会发送给各自的服务。',save: '检查并保存',checkingKey: '正在检查…',cancel: '取消',+ mcpSummary: '你的 MCP 服务:{n} 个,其中 {on} 个在 OpenFilm 里使用',+ mcpManage: '选择',+ mcpDone: '完成',+ mcpNote: '你自己给 {agent} 添加的 MCP 服务,在 OpenFilm 里默认不使用,打开开关后才会使用。它自带的服务始终保留。',+ mcpAllow: '在 OpenFilm 里使用 {name}',+ skillsSummary: '你的 skill:{n} 个,其中 {on} 个在 OpenFilm 里使用',+ skillsNote: '你自己给 {agent} 装的 skill,在 OpenFilm 里默认不使用,这样每次做出的片子更稳定;打开开关后才会使用。它自带的 skill 始终保留。',+ skillsAllow: '在 OpenFilm 里使用 {name}',+ skillsUnfiltered: '{agent} 在 OpenFilm 里会使用你自己的全部 {n} 个 skill,和它自己的应用里一样。',+ mcpUnfiltered: '{agent} 在 OpenFilm 里会使用你自己的全部 {n} 个 MCP 服务,和它自己的应用里一样。',},developer: {- intro: '用来弄清楚 agent 到底做了什么、为什么这么做;这里的设置不会改变 agent 的行为。',+ intro: '用来弄清楚智能体到底做了什么、为什么这么做;这里的设置不会改变智能体的行为。',group: '每一轮',changes: '显示每一轮的改动',changesHint: '每条回复下面列出这一轮新增、删除或修改的文件,以及增减的行数。点开一个文件可以看到改动的行。',logs: '显示每一轮的日志',- logsHint: '打开后,对话里每一轮都有“日志”按钮:提示词和所在会话、每次工具调用的输入和输出、每个提问和回答、这一轮怎么结束的,都按 agent 发来的原样显示。',+ logsHint: '打开后,对话里每一轮都有“日志”按钮:提示词和所在会话、每次工具调用的输入和输出、每个提问和回答、这一轮怎么结束的,都按智能体发来的原样显示。',where: '不论是否打开,每一轮都会记录在项目的 .film/logs 文件夹里,只保存在这台电脑上。',releaseGroup: '发版',previewWhatsNew: '更新内容弹窗',@@ -1569,7 +1664,7 @@ export const zhCN: Words = {copyDrag: '按住它拖动片段:在松手处复制一份,原片段不动',},providers: {- desc: '配音、音乐、音效、文字稿、图片和视频从哪里来。即使不连接任何服务,OpenFilm 也能制作和编辑影片:等智能体需要素材时再连接即可。',+ desc: '配音、音乐、音效、文字稿、图片和视频从哪里来。即使不连接任何服务,OpenFilm 也能制作和编辑影片:等智能体需要素材时再连接即可。每种媒体具体用哪一个,在「服务」里选择。',connect: '连接',disconnect: '断开连接',connected: '已连接',@@ -1580,11 +1675,11 @@ export const zhCN: Words = {save: '保存',cancel: '取消',keyEnding: '尾号为 {last4} 的密钥',- useEnv: '使用环境变量 ${env} 里的 key',+ useEnv: '使用环境变量 ${env} 里的密钥',own: {- title: "自己的服务",- note: "你自己运行或使用的任何服务,在这台电脑上或在线上都可以(你自己的声音、语音转写服务、这里没列出的 API)。智能体按地址访问它,密钥只留在这台电脑上。写清它能做什么,智能体才知道什么时候用它。",- add: "添加服务",+ title: "自定义服务",+ note: "上面没列出的服务都可以加在这里,数量不限:本机运行的或线上的都行(你自己的声音、语音转写服务、没列出的 API),接口可以完全自定义。OpenFilm 不会自动调用它们:智能体读你写的说明来调用,密钥只留在这台电脑上,智能体看不到。也可以不加在这里,直接在对话里把服务告诉智能体;需要密钥的服务建议加在这里,密钥就不会出现在对话中。",+ add: "添加自定义服务",edit: "编辑",remove: "移除",name: "名称",@@ -1592,11 +1687,10 @@ export const zhCN: Words = {url: "地址",key: "密钥",keyOptional: "可选",- keyKeep: "留空则保留末尾为 {last4} 的密钥",+ keyKeep: "留空则保留尾号为 {last4} 的密钥",removeKey: "移除密钥",- auth: "密钥放在哪里",- what: "它能做什么",- whatPlaceholder: "例如:用我的声音朗读文案:POST /tts,内容 {\"text\": \"…\"},返回 WAV。文档:https://…",+ what: "说明",+ whatPlaceholder: "例如:用我的声音朗读文案:POST /tts,内容 {\"text\": \"…\"},返回 WAV。也可以只写 API 文档地址:https://…",},verbs: {tts: '配音',@@ -1612,12 +1706,11 @@ export const zhCN: Words = {},},models: {- desc: '每种媒体由哪个服务商和模型生成。连接服务商后,会自动填补尚未设置的类型;你也可以在这里修改任意一项。',- nothing: '尚未连接任何服务。连接一个服务商即可选择它的模型。',+ desc: '每种媒体用哪个服务来生成:从已连接服务商的模型中选择。连接服务商后,会自动填补尚未设置的类型;你也可以在这里修改任意一项。',+ nothing: '尚未连接任何服务商。连接一个服务商即可选择它的模型。',goConnect: '连接服务商',none: '无',connectNamed: '连接 {names}',- otherBody: "想用列表里没有的服务或模型?在“服务商 → 自己的服务”里添加它的地址和密钥,智能体就能使用。生成的内容会和其他内容一样出现在素材中。",about: {tts: '朗读脚本,并寻找合适的音色',music: '根据描述生成配乐',diff --git a/packages/openfilm/studio/ui/src/lib/asset-timeline.test.ts b/packages/openfilm/studio/ui/src/lib/asset-timeline.test.tsindex bebccfe..7dc6000 100644--- a/packages/openfilm/studio/ui/src/lib/asset-timeline.test.ts+++ b/packages/openfilm/studio/ui/src/lib/asset-timeline.test.ts@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { assetClipElement, assetDropInsert, assetDropSpot, assetDropTargetOf, assetFitBox, assetPageFit, assetRunInsert, soundLaneHit } from './asset-timeline.ts';+import { assetClipElement, assetClipKindOf, assetDropInsert, assetDropSpot, assetDropTargetOf, assetFitBox, assetPageFit, assetRunInsert, soundLaneHit } from './asset-timeline.ts';import type { TimelineTrack } from './timeline-layout.ts';/* A file from the media pane lands on the row under the pointer — a track has no kind (SPEC) — or, where its time@@ -136,3 +136,8 @@ test('a page without a size of its own keeps the size it is shown at alone, scalassert.deepEqual(assetClipElement(page, { w: 1920, h: 1080 }), { src: 'scenes/cards.html' });assert.equal(assetPageFit({ w: 480, h: 320 }, { w: 2520, h: 1080 }), null);});++test('a page the pane names one without its ending (a bundle of Saved) is an mg clip', () => {+ assert.equal(assetClipKindOf({ path: 'saved/Lower third', kind: 'mg' }), 'mg');+ assert.equal(assetClipKindOf({ path: 'saved/notes', kind: 'other' }), null);+});diff --git a/packages/openfilm/studio/ui/src/lib/asset-timeline.ts b/packages/openfilm/studio/ui/src/lib/asset-timeline.tsindex 7fbf7c7..402ec42 100644--- a/packages/openfilm/studio/ui/src/lib/asset-timeline.ts+++ b/packages/openfilm/studio/ui/src/lib/asset-timeline.ts@@ -27,8 +27,9 @@ import { renumberTracks, type TimelineBlockKind, type TimelineTrack } from './tiexport type AssetClipKind = 'mg' | 'video' | 'audio';export function assetClipKindOf(file: { path: string; kind: string }): AssetClipKind | null {- /* a web page (`scenes/intro.html`) is an mg clip, its src the page's path */- if (filmSrcIsPage(file.path)) return 'mg';+ /* a web page (`scenes/intro.html`) is an mg clip, its src the page's path; so is a page the pane names one without+ its ending (a bundle of Saved, a folder holding its page) */+ if (filmSrcIsPage(file.path) || file.kind === 'mg') return 'mg';if (file.kind === 'video' || file.kind === 'image') return 'video';if (file.kind === 'audio') return 'audio';return null;diff --git a/packages/openfilm/studio/ui/src/lib/batch-map.test.ts b/packages/openfilm/studio/ui/src/lib/batch-map.test.tsnew file mode 100644index 0000000..7460d96--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/batch-map.test.ts@@ -0,0 +1,30 @@+import { test, mock } from 'node:test';+import assert from 'node:assert/strict';+import { batchMap } from './batch-map.ts';++test('entries set within the wait go on together, in one batch', () => {+ mock.timers.enable({ apis: ['setTimeout'] });+ try {+ const batches: [string, number][][] = [];+ const b = batchMap<string, number>((m) => batches.push([...m]), 250);+ b.set('a', 1); b.set('b', 2); b.set('a', 3);+ assert.equal(batches.length, 0, 'nothing before the wait is over');+ mock.timers.tick(250);+ assert.deepEqual(batches, [[['a', 3], ['b', 2]]]);+ b.set('c', 4);+ mock.timers.tick(250);+ assert.deepEqual(batches.at(-1), [['c', 4]]);+ } finally { mock.timers.reset(); }+});++test('what is waiting is dropped when cancelled', () => {+ mock.timers.enable({ apis: ['setTimeout'] });+ try {+ const batches: unknown[] = [];+ const b = batchMap<string, number>((m) => batches.push(m), 100);+ b.set('a', 1);+ b.cancel();+ mock.timers.tick(500);+ assert.equal(batches.length, 0);+ } finally { mock.timers.reset(); }+});diff --git a/packages/openfilm/studio/ui/src/lib/batch-map.ts b/packages/openfilm/studio/ui/src/lib/batch-map.tsnew file mode 100644index 0000000..8e432a3--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/batch-map.ts@@ -0,0 +1,28 @@+/**+ * Entries set one by one, handed on together: the first one waits `ms`, and everything set in that time goes in the+ * same batch. For the media facts probed as a project opens (ProjectView): thousands of files answer one after another,+ * and each answer set on its own laid out the media pane and the timeline's sources again, the picture stalling for+ * tens of ms each time while a person watched it play.+ */+export function batchMap<K, V>(flush: (batch: Map<K, V>) => void, ms: number) {+ let batch = new Map<K, V>();+ let timer: ReturnType<typeof setTimeout> | null = null;+ return {+ set(key: K, value: V) {+ batch.set(key, value);+ if (timer != null) return;+ timer = setTimeout(() => {+ timer = null;+ const done = batch;+ batch = new Map();+ flush(done);+ }, ms);+ },+ /** What is waiting dropped (the project closed). */+ cancel() {+ if (timer != null) clearTimeout(timer);+ timer = null;+ batch = new Map();+ },+ };+}diff --git a/packages/openfilm/studio/ui/src/lib/browser.test.ts b/packages/openfilm/studio/ui/src/lib/browser.test.tsnew file mode 100644index 0000000..07da33c--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/browser.test.ts@@ -0,0 +1,17 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { chromiumBased } from './browser.ts';++test('Chromium browsers are told from the others by their brands, else their user agent', () => {+ const ua = {+ chrome: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',+ edge: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0',+ safari: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Safari/605.1.15',+ firefox: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0',+ };+ assert.equal(chromiumBased(ua.chrome), true);+ assert.equal(chromiumBased(ua.edge), true);+ assert.equal(chromiumBased(ua.safari), false);+ assert.equal(chromiumBased(ua.firefox), false);+ assert.equal(chromiumBased('', [{ brand: 'Not A;Brand' }, { brand: 'Chromium' }]), true);+});diff --git a/packages/openfilm/studio/ui/src/lib/browser.ts b/packages/openfilm/studio/ui/src/lib/browser.tsnew file mode 100644index 0000000..57ca2fa--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/browser.ts@@ -0,0 +1,10 @@+/**+ * Whether the page is in a browser built on Chromium (Chrome, Edge, Arc, the desktop app), the engine films are+ * rendered and checked in. Another one (Safari, Firefox) may lack something a film's page draws with, such as canvas+ * filters: its preview can fail where the export does not.+ */+export function chromiumBased(ua: string = typeof navigator === 'undefined' ? '' : navigator.userAgent,+ brands: readonly { brand: string }[] | undefined = typeof navigator === 'undefined' ? undefined : (navigator as { userAgentData?: { brands?: { brand: string }[] } }).userAgentData?.brands): boolean {+ if (brands?.some((b) => /Chromium/i.test(b.brand))) return true;+ return /\b(Chrome|Chromium|CriOS|Edg)\//.test(ua) && !/\bFirefox\//.test(ua);+}diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.tsindex 74c79cd..6a69866 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.*/+/** A tab of the app's window (`tabs` below): a project's, its title as Studio shows it. */+export interface HostTab { id: string; projectId: string; title: string; active: boolean; working: boolean; asking: boolean; exporting: number | null }+/** Settings → Developer, as the app keeps it (`developer` below). */export interface HostDeveloper { logs: boolean; changes: boolean }@@ -59,6 +62,14 @@ export interface StudioHost {setWidth?: (width: number, done?: boolean) => void;onChange: (listener: (state: { open: boolean; width: number; assets?: { open: boolean; bottom: number } }) => void) => void;};+ /**+ * The app's chat names a skill in the message being written: the examples (opened from the chat, `show-examples`)+ * call this for a skill picked in them.+ */+ useSkill?: (skill: { name: string; description: string }) => void;+ /** The person's own skills, where the app keeps them: one added, the app's own way (from a link, a folder, or made+ with the agent). The Community's skills offer it. */+ skills?: { add: () => void };/** Let the app ask Studio to show something: Studio calls this once with its listener. */onCommand?: (listener: (command: StudioCommand) => void) => void;/**@@ -79,7 +90,21 @@ export interface StudioHost {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[]; efforts?: Record<string, HostByokEffort>; key?: string }) => Promise<{ ok: boolean; error?: string; code?: string }>;+ /**+ * One of the person's own models set up (no `id`) or changed: checked before it is kept. A key left empty keeps its+ * own, or takes the one of another model on the same address.+ */+ saveOwnModel: (config: HostOwnModelConfig) => Promise<{ ok: true; id: string } | { ok: false; error: string; code?: string }>;+ removeOwnModel: (id: string) => Promise<unknown>;+ /**+ * The MCP servers the person added to an agent themselves (its maker's not among them), each let into the app or+ * not: hidden there until let in. `filtered` false: the agent cannot be told, and has them all.+ */+ mcp?: (id: HostAgentId) => Promise<{ filtered: boolean; servers: Array<{ name: string; detail: string; allowed: boolean }> }>;+ allowMcp?: (id: HostAgentId, name: string, allowed: boolean) => Promise<unknown>;+ /** The same for the skills the person installed in an agent themselves (OpenFilm's own skill for terminal agents is never among them). */+ skills?: (id: HostAgentId) => Promise<{ filtered: boolean; skills: Array<{ name: string; description: string; allowed: boolean }> }>;+ allowSkill?: (id: HostAgentId, name: string, allowed: boolean) => Promise<unknown>;onChange: (listener: (agents: HostAgent[]) => void) => () => void;};/**@@ -112,6 +137,28 @@ export interface StudioHost {set: (next: Partial<HostDeveloper>) => Promise<unknown>;onChange: (listener: (prefs: HostDeveloper) => void) => () => void;};+ /**+ * The app shows each project in a tab of its own window and draws no tab strip of its own: Studio draws the tabs in+ * its top bar (where the projects button and the title are otherwise), with a `+` that opens the projects window to+ * pick the project a new tab shows (`open`; one open already is shown). With no tab open the page is at `/`, and+ * Studio shows the projects there. `list` gives the tabs and which is this page's (`self`); `onChange` every change.+ * A page `report`s what it shows (its title, an export's progress, its project gone: its tab closes). Studio's+ * "open this project" (heard by every page) goes to `openRequest`, which the app settles once; `onPick` is the app+ * asking for the projects window (a new tab from its menu).+ */+ tabs?: {+ list: () => Promise<{ self: string | null; tabs: HostTab[] }>;+ onChange: (listener: (tabs: HostTab[]) => void) => () => void;+ show: (id: string) => void;+ close: (id?: string) => void;+ /** a project's tab: shown, opened when it is not */+ open: (projectId: string) => void;+ move: (id: string, index: number) => void;+ report: (state: { title?: string; exporting?: number | null; gone?: boolean }) => void;+ openRequest: (to: string) => void;+ onPick: (listener: () => void) => () => void;+ };+/*** The app picks folders, and knows where a dropped one is: the Projects list gets "Open…", which asks the app for a* folder to open as a project (`pick`: null when the person cancelled), and opens a folder dropped on it (`pathOf`:@@ -175,10 +222,22 @@ export interface HostAgent {path?: string | null;chosen?: string | null;error?: string;+ /** Found, but it cannot read its own settings (Codex's config file), as it says: no session starts until fixed. */+ problem?: string;account?: HostAgentAccount;- byok?: { format: HostByokFormat; baseUrl: string; model: string; models?: string[]; efforts?: Record<string, HostByokEffort>; last4: string };+ /** The own key's models, each set up on its own; the first is the one a conversation starts on. */+ byok?: { models: HostOwnModel[] };}+/**+ * One of the person's own models: its `id` (the app's), the `name` the chat's menu shows, its service (API `format`+ * and `baseUrl`), the `model` asked for there, its efforts, and the last four characters of its key.+ */+export interface HostOwnModel extends HostByokEffort { id: string; name: string; format: HostByokFormat; baseUrl: string; model: string; last4: string }++/** What setting up one of the person's own models sends: `id` to change one, no `key` to keep its key. */+export interface HostOwnModelConfig { id?: string; name?: string; format: HostByokFormat; baseUrl: string; model: string; key?: string; levels: HostByokEffortLevel[]; effort: HostByokEffortLevel }+/*** The reasoning efforts a model of the person's own key offers, in this order (`auto`: none is sent, the service decides),* and the one a conversation starts on. A model given none offers `auto` alone.@@ -228,6 +287,9 @@ export interface StudioRefImage { src?: string; viewer?: boolean; crop?: StageBo* · range a stretch of the film (marked on the timeline's ruler, or with I and O): the clips playing in it* · track a whole track* · file a file of the project (the media pane): its path, kind, and length / size when known+ * · example an example film (ExamplesGallery), or a part of it (`start`–`end`, a `segment` it names): where it comes+ * from (`url`), and its folder on this computer to read how it is made (`folder`: fetched by the app+ * when the message is sent, if not yet)* · subtitle a line of the film's subtitles (the subtitle panel), or words picked inside one: their span on the film,* the words, the language they are in when a translation is shown (`lang`), the line's number in the panel* (`index`, from 1), and each word's own span when the transcript has word times (`words`)@@ -244,6 +306,7 @@ export type StudioRef = (| { kind: 'track'; track: number; label: string; clipIds: string[] }| { kind: 'file'; path: string; fileKind: string; duration?: number; w?: number; h?: number }| { kind: 'subtitle'; start: number; end: number; text: string; lang?: string | null; index?: number; words?: Array<{ text: string; start: number; end: number }> }+ | { kind: 'example'; id: string; title: string; url: string; folder?: string; start?: number; end?: number; segment?: string; description?: string }) & { image?: StudioRefImage };/**@@ -286,7 +349,13 @@ export type StudioCommand =| { type: 'highlight'; ref: StudioRef | null }| { type: 'draft-refs'; refs: StudioRef[] }/* the app's chat sends the person to Settings (an agent to set up) */- | { type: 'settings'; section?: 'agents' | 'providers' };+ | { type: 'settings'; section?: 'agents' | 'providers' }+ /* the app's chat opens the examples over the film, to point at one or a part of one, or name a skill; `open`: on+ that skill's or example's page (a pill of one clicked) */+ | { type: 'show-examples'; open?: CommunityItem };++/** A skill or an example in the Community, to open on its page. */+export type CommunityItem = { kind: 'skill'; name: string } | { kind: 'example'; id: string };export const studioHost: StudioHost | null = (globalThis as { openfilmHost?: StudioHost }).openfilmHost ?? null;diff --git a/packages/openfilm/studio/ui/src/lib/media-folders.test.ts b/packages/openfilm/studio/ui/src/lib/media-folders.test.tsnew file mode 100644index 0000000..5cf5e94--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-folders.test.ts@@ -0,0 +1,33 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { byName, folderFaces } from './media-folders.ts';++const file = (path: string, kind = 'image') => ({ path, name: path.split('/').pop()!, kind });+const relOf = (path: string) => (path.startsWith('assets/') ? path.slice('assets/'.length) : null);++test('names go in their natural order', () => {+ assert.deepEqual(['shot 10', 'shot 2', 'shot 1'].sort(byName), ['shot 1', 'shot 2', 'shot 10']);+});++test('the folders in the one shown, each with all the files under it and its cover', () => {+ const files = [+ file('assets/video/b.mp4', 'video'), file('assets/video/a 10.jpg'), file('assets/video/a 2.jpg'), file('assets/video/song.mp3', 'audio'),+ file('assets/video/old/c.jpg'), file('assets/audio/vo.mp3', 'audio'), file('assets/top.jpg'), file('intro.html', 'page'),+ ];+ const faces = folderFaces(files, ['video', 'video/old', 'audio', 'empty'], '', relOf);+ assert.deepEqual(faces.map((f) => [f.rel, f.count]), [['audio', 1], ['empty', 0], ['video', 5]]);+ const video = faces.find((f) => f.rel === 'video')!;+ /* pictures first by their natural order, sounds after; at most four */+ assert.deepEqual(video.covers.map((f) => f.name), ['a 2.jpg', 'a 10.jpg', 'b.mp4', 'c.jpg']);+});++test('inside a folder: its own folders only, the files under each counted', () => {+ const files = [file('assets/video/old/c.jpg'), file('assets/video/old/deep/d.jpg'), file('assets/video/x.jpg'), file('assets/audio/vo.mp3', 'audio')];+ const faces = folderFaces(files, ['video', 'video/old', 'video/old/deep', 'audio'], 'video', relOf);+ assert.deepEqual(faces.map((f) => [f.rel, f.name, f.count]), [['video/old', 'old', 2]]);+});++test('a folder\'s cover takes sounds only when it has nothing else', () => {+ const files = [file('assets/a/z.mp3', 'audio'), file('assets/a/y.mp3', 'audio'), file('assets/a/p.jpg')];+ assert.deepEqual(folderFaces(files, ['a'], '', relOf)[0]!.covers.map((f) => f.name), ['p.jpg', 'y.mp3', 'z.mp3']);+});diff --git a/packages/openfilm/studio/ui/src/lib/media-folders.ts b/packages/openfilm/studio/ui/src/lib/media-folders.tsnew file mode 100644index 0000000..d261247--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-folders.ts@@ -0,0 +1,45 @@+/**+ * The media pane's folders (MediaPool): those directly in the folder shown, each with how many files it holds (at any+ * depth) and the four on its cover (pictures first, they say the most; sounds after; by name). Worked out in one pass+ * over the files, with one collator: a project holds thousands of files, the pane is laid out again whenever its+ * listing changes, and a filter and a sort per folder (a collator made for each comparison) took tens of ms each time.+ */++/** Names in their natural order (shot 2 before shot 10). */+export const byName = new Intl.Collator(undefined, { numeric: true }).compare;++type File = { path: string; name: string; kind: string };+export type FolderFace<F extends File> = { rel: string; name: string; count: number; covers: F[] };++/** Pictures before sounds, then by name: the order of a folder's cover. */+const coverOrder = (a: File, b: File) => Number(a.kind === 'audio') - Number(b.kind === 'audio') || byName(a.name, b.name);+const COVERS = 4;++/**+ * The folders of `dirs` (paths under the media folder) directly in `at` ('' its top), in name order. `relOf` gives a+ * file's path under the media folder, or null for one outside it (a project's own page).+ */+export function folderFaces<F extends File>(files: readonly F[], dirs: readonly string[], at: string, relOf: (path: string) => string | null): FolderFace<F>[] {+ const parentOf = (rel: string) => (rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '');+ const faces = new Map<string, FolderFace<F>>();+ for (const rel of [...dirs].filter((d) => parentOf(d) === at).sort(byName)) faces.set(rel, { rel, name: rel.split('/').pop()!, count: 0, covers: [] });+ if (!faces.size) return [];+ const prefix = at ? `${at}/` : '';+ for (const f of files) {+ const rel = relOf(f.path);+ if (rel == null || !rel.startsWith(prefix)) continue;+ const slash = rel.indexOf('/', prefix.length);+ if (slash < 0) continue; // a file of `at` itself+ const face = faces.get(rel.slice(0, slash));+ if (!face) continue;+ face.count++;+ /* the cover's four, kept in order as they come (no sort of the whole folder) */+ const covers = face.covers;+ if (covers.length === COVERS && coverOrder(f, covers[COVERS - 1]!) >= 0) continue;+ let i = covers.length;+ while (i > 0 && coverOrder(f, covers[i - 1]!) < 0) i--;+ covers.splice(i, 0, f);+ if (covers.length > COVERS) covers.pop();+ }+ return [...faces.values()];+}diff --git a/packages/openfilm/studio/ui/src/lib/project-sources.ts b/packages/openfilm/studio/ui/src/lib/project-sources.tsindex 383ab67..df61143 100644--- a/packages/openfilm/studio/ui/src/lib/project-sources.ts+++ b/packages/openfilm/studio/ui/src/lib/project-sources.ts@@ -7,6 +7,7 @@* POST /api/projects { path, create: false } → { project }, or 409 code 'no-film' (ask before starting one there)* POST /api/projects/fetch { url } → { job }; GET / DELETE /api/projects/fetch/:id* GET /api/examples → { examples } (none when the index cannot be read)+ * GET /api/skills?project=<id> → { skills } (the project's, the person's own, the official ones)* POST /api/projects/:id/locate { path } → { project }*/@@ -37,7 +38,28 @@ export type FetchJob = {code?: string;project?: { id: string };};-export type Example = { id: string; title: string; description: string; poster: string | null; duration: number | null; url: string };+/** a skill a project can be made with (openfilm/src/skills.mjs): the project's own, the person's, or official */+export type SkillEntry = {+ name: string; description: string; source: 'project' | 'mine' | 'official'; scripts: number;+ /** how people see it (its openfilm.json): a title and a one-line summary, by language */+ shown?: { title: Record<string, string>; summary: Record<string, string>; details?: Record<string, string> };+ /** its openfilm.json's (else its front matter's) */+ version?: string;+ /** a way of working (a kind of job) or a look; its place among its kind; its mark */+ kind?: 'workflow' | 'style'; order?: number; icon?: string;+ /** addresses of its cover picture and preview video, when it has them */+ cover?: string; preview?: string;+ /** where its source can be read (a repository's address) */+ repository?: string;+ /** the person's own: where it came from (a link, a folder), or made where it is */+ origin?: { from: 'link' | 'folder'; address: string } | { from: 'made' };+};+/** an example film's part, as its index names it (`S2-Hook`), from and to in seconds */+export type ExampleSegment = { title: string; from: number; to: number };+export type Example = {+ id: string; title: string; description: string; poster: string | null; video: string | null; duration: number | null; url: string;+ category: string | null; segments: ExampleSegment[];+};export class SourceError extends Error {readonly status: number;@@ -59,6 +81,13 @@ async function call<T>(path: string, method = 'GET', json?: unknown): Promise<T>return body as T;}+/* what the galleries read last: shown at once when one opens, and asked for again behind it */+const seen: { examples: Example[] | null; skills: Map<string, SkillEntry[]> } = { examples: null, skills: new Map() };+/** The examples read last, or null. */+export const seenExamples = (): Example[] | null => seen.examples;+/** The skills read last for a project (else for no project: the official ones and the person's own), or null. */+export const seenSkills = (projectId?: string | null): SkillEntry[] | null => seen.skills.get(projectId ?? '') ?? seen.skills.get('') ?? null;+export const sourcesApi = {browse: (path?: string | null) => call<BrowseListing>(`browse${path ? `?path=${encodeURIComponent(path)}` : ''}`),/** opens the folder only when it holds a film: else a SourceError with code 'no-film' (or 'not-found') */@@ -66,7 +95,13 @@ export const sourcesApi = {startFetch: (url: string) => call<{ job: FetchJob }>('projects/fetch', 'POST', { url }).then((r) => r.job),fetchJob: (id: string) => call<{ job: FetchJob }>(`projects/fetch/${encodeURIComponent(id)}`).then((r) => r.job),cancelFetch: (id: string) => call<object>(`projects/fetch/${encodeURIComponent(id)}`, 'DELETE'),- examples: () => call<{ examples: Example[] }>('examples').then((r) => r.examples, () => [] as Example[]),+ examples: () => call<{ examples: Example[] }>('examples').then((r) => (seen.examples = r.examples), () => seen.examples ?? []),+ /** an example's folder on this computer, fetched when needed (for an agent to read how it is made) */+ exampleFolder: (id: string) => call<{ folder: string }>(`examples/${encodeURIComponent(id)}/folder`, 'POST').then((r) => r.folder),+ skills: (projectId?: string | null) => call<{ skills: SkillEntry[] }>(`skills${projectId ? `?project=${encodeURIComponent(projectId)}` : ''}`)+ .then((r) => { seen.skills.set(projectId ?? '', r.skills); return r.skills; }, () => seenSkills(projectId) ?? []),+ /** asked as Studio opens, so a gallery opened later shows its examples and skills at once */+ preload: () => { void sourcesApi.examples(); void sourcesApi.skills(null); },locate: (id: string, path: string) => call<{ project: { id: string } }>(`projects/${encodeURIComponent(id)}/locate`, 'POST', { path }).then((r) => r.project),};diff --git a/packages/openfilm/studio/ui/src/lib/providers.ts b/packages/openfilm/studio/ui/src/lib/providers.tsindex 9462c91..23dfa25 100644--- a/packages/openfilm/studio/ui/src/lib/providers.ts+++ b/packages/openfilm/studio/ui/src/lib/providers.ts@@ -27,8 +27,8 @@ export interface OwnProvider {}/**- * One of the person's own services (studio/server/custom-services.mjs): any service at an address, reached by their- * agent with `openfilm get call`. `auth`: the header its key goes in, `{key}` standing for it.+ * One of the person's custom services (studio/server/custom-services.mjs): any service at an address, reached by their+ * agent with `openfilm get call`. `auth`: the header its key goes in when the agent does not place it ({key}).*/export interface OwnService {id: string;@@ -39,8 +39,8 @@ export interface OwnService {last4: string | null;}-/** What Settings sends for a service: no `key` keeps the one it has, '' takes it away. */-export type OwnServiceFields = { name: string; url: string; auth: string; note: string; key?: string };+/** What Settings sends for a service: no `key` keeps the one it has, '' takes it away; no `auth` keeps where it goes. */+export type OwnServiceFields = { name: string; url: string; auth?: string; note: string; key?: string };export interface ProvidersState {providers: OwnProvider[];diff --git a/packages/openfilm/studio/ui/src/lib/resource-drag.ts b/packages/openfilm/studio/ui/src/lib/resource-drag.tsindex d37f6eb..c07ac84 100644--- a/packages/openfilm/studio/ui/src/lib/resource-drag.ts+++ b/packages/openfilm/studio/ui/src/lib/resource-drag.ts@@ -34,6 +34,8 @@ export interface ResourceDragItem {w?: number;h?: number;fps?: number;+ /** A saved thing (lib/saved), not a file of the project: its files are brought in as it lands. */+ saved?: string;}const KINDS: readonly ResourceKind[] = ['video', 'image', 'audio', 'mg', 'other'];@@ -101,6 +103,7 @@ function normalizeResourceDragItem(value: unknown): ResourceDragItem | null {...(w === undefined ? {} : { w }),...(h === undefined ? {} : { h }),...(fps === undefined ? {} : { fps }),+ ...(typeof item.saved === 'string' && item.saved ? { saved: item.saved } : {}),};}diff --git a/packages/openfilm/studio/ui/src/lib/saved-insert.test.ts b/packages/openfilm/studio/ui/src/lib/saved-insert.test.tsnew file mode 100644index 0000000..d273284--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/saved-insert.test.ts@@ -0,0 +1,31 @@+import { test as it } from 'node:test';+import assert from 'node:assert/strict';+import type { SavedGroupClip } from '../api.ts';+import type { EditModel } from './timeline-edit.ts';+import { groupInsertAt, groupInsertOps } from './saved-insert.ts';++const clip = (src: string, link?: string) => ({ src, ...(link ? { attrs: { 'data-link': link } } : {}) });++it('a group goes in on new tracks, in its order, each clip at its time from where it lands, its links made anew', () => {+ const group: SavedGroupClip[] = [+ { track: 1, at: 6, clip: clip('s/v.mp4') },+ { track: 0, at: 2, clip: clip('s/title.html') },+ { track: 1, at: 0, clip: clip('s/v.mp4', 'L') },+ { track: 2, at: 0, clip: clip('s/v.mp4', 'L') },+ ];+ /* the film has a link of that name already: another one is made */+ const model = [{ clips: [{ id: 'x', link: 'saved-L' }] }] as unknown as EditModel;+ const ops = groupInsertOps(group, 1.5, 3, model);+ assert.deepEqual(ops.map((op) => (op.op === 'insert' ? [op.clip?.src, op.at, op.track, op.link ?? null] : null)), [+ ['s/title.html', 3.5, { insert: 3 }, null],+ ['s/v.mp4', 1.5, { insert: 4 }, 'saved-L-2'],+ ['s/v.mp4', 7.5, 4, null],+ ['s/v.mp4', 1.5, { insert: 5 }, 'saved-L-2'],+ ]);+});++it('a group dropped on a track goes in above it; on a new track, there; anywhere else, on top', () => {+ assert.equal(groupInsertAt(2), 2);+ assert.equal(groupInsertAt({ insert: 4 }), 4);+ assert.equal(groupInsertAt(undefined), 0);+});diff --git a/packages/openfilm/studio/ui/src/lib/saved-insert.ts b/packages/openfilm/studio/ui/src/lib/saved-insert.tsnew file mode 100644index 0000000..5a3fd64--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/saved-insert.ts@@ -0,0 +1,40 @@+/**+ * A saved group of clips put on the timeline (lib/saved, studio/server/saved.mjs): each of its tracks a new track,+ * the top one at `insertAt` and the others under it in their order, each clip at `atSec` plus its time in the group.+ * Clips linked in the group are linked anew there (a link of their own, not one a clip of the film has).+ *+ * Pure: no React, so `node --test` runs it (lib/saved-insert.test.ts).+ */+import type { Op, SavedGroupClip } from '../api.ts';+import { freshLink, type EditModel } from './timeline-edit.ts';++export function groupInsertOps(clips: readonly SavedGroupClip[], atSec: number, insertAt: number, model: EditModel): Op[] {+ const links = new Map<string, string>();+ const taken = new Set<string>();+ const linkOf = (clip: SavedGroupClip['clip']): string | null => {+ const was = (clip.attrs as Record<string, string> | undefined)?.['data-link'];+ if (!was) return null;+ if (!links.has(was)) { const made = freshLink(model, `saved-${was}`, taken); taken.add(made); links.set(was, made); }+ return links.get(was)!;+ };+ const opened = new Set<number>();+ return [...clips]+ .sort((a, b) => a.track - b.track || a.at - b.at)+ .map(({ track, at, clip }) => {+ const link = linkOf(clip);+ const first = !opened.has(track);+ opened.add(track);+ return {+ op: 'insert' as const,+ clip: clip as never,+ at: Math.round((Math.max(0, atSec) + at) * 1000) / 1000,+ track: first ? { insert: insertAt + track } : insertAt + track,+ ...(link ? { link } : {}),+ };+ });+}++/** Where a group's top track goes for a drop: a new track asked for, above the track dropped on, else on top. */+export function groupInsertAt(track: number | { insert: number } | undefined): number {+ return typeof track === 'object' ? track.insert : typeof track === 'number' ? track : 0;+}diff --git a/packages/openfilm/studio/ui/src/lib/saved.ts b/packages/openfilm/studio/ui/src/lib/saved.tsnew file mode 100644index 0000000..956fd6a--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/saved.ts@@ -0,0 +1,114 @@+/**+ * Saved, the person's own library for every project (studio/server/saved.mjs), as the media pane shows it: its files+ * and folders listed as a project's media are (`saved/` in place of `assets/`), with where their pictures, sounds and+ * bytes come from, and the pane's changes made there. Read again whenever something is put in it from anywhere in+ * Studio, and when the window comes back (a file may have been put in its folder from the file manager).+ */+import React from 'react';+import type { ImportProgress } from '@/components/MediaPool';+import { mediaFetch } from './media-queue';+import {+ factsOfProbe, mediaListingOf, type FilesListing, type MediaFacts, type MediaListing, type MediaResult, type MediaSources,+} from './workspace-resources';++/** The library's top folder as its paths name it. */+export const SAVED = 'saved';++let version = 0;+const listeners = new Set<() => void>();++/** Read the library again (something was put in it, or may have been). */+export function refreshSaved(): void {+ version += 1;+ for (const fn of listeners) fn();+}++const enc = (path: string) => encodeURIComponent(path);+const media = (what: string, path: string, v: number) => `/api/saved/media?what=${what}&path=${enc(path)}&v=${v}`;++/** Where the library's pictures, sounds and bytes come from. A bundle is pictured by its poster. */+export const savedSources: MediaSources = {+ file: (f) => (f.bundle ? `/api/saved/poster?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}` : `/api/saved/file?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}`),+ poster: (f) => (f.bundle ? `/api/saved/poster?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}` : f.kind === 'video' ? media('poster', f.path, Math.round(f.mtimeMs)) : undefined),+ wave: (f) => media('wave', f.path, Math.round(f.mtimeMs)),+ pagePoster: (f) => (f.bundle ? `/api/saved/poster?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}` : undefined),+};++/** The library as the media pane lists it, once read (null before, or while `on` is false). */+export function useSavedListing(on: boolean): MediaListing | null {+ const seen = React.useSyncExternalStore(+ (fn) => { listeners.add(fn); return () => { listeners.delete(fn); }; },+ () => version,+ () => version,+ );+ const [raw, setRaw] = React.useState<(FilesListing & { made?: string[] }) | null>(null);+ const [facts, setFacts] = React.useState<ReadonlyMap<string, MediaFacts>>(new Map());+ React.useEffect(() => {+ if (!on) return undefined;+ let live = true;+ void fetch('/api/saved/files', { cache: 'no-store' }).then((r) => (r.ok ? r.json() : null), () => null).then((body) => { if (live && body) setRaw(body); });+ return () => { live = false; };+ }, [on, seen]);+ /* the window back: its folder may have been changed from the file manager */+ React.useEffect(() => {+ if (!on) return undefined;+ const back = () => refreshSaved();+ window.addEventListener('focus', back);+ return () => window.removeEventListener('focus', back);+ }, [on]);+ /* each media file's length and size, as a project's are probed */+ React.useEffect(() => {+ for (const f of raw?.files ?? []) {+ const key = `${f.path}@${f.mtime}`;+ if (f.saved || !['video', 'audio', 'image'].includes(f.kind) || facts.has(key)) continue;+ void mediaFetch(media('probe', f.path, f.mtime)).then((r) => (r.ok ? r.json() : null)).then((probe) => {+ if (probe) setFacts((m) => new Map(m).set(key, factsOfProbe(probe)));+ }, () => {});+ }+ }, [raw]); // eslint-disable-line react-hooks/exhaustive-deps+ return React.useMemo(() => (raw ? mediaListingOf(+ raw,+ (path) => facts.get(`${path}@${raw.files.find((f) => f.path === path)?.mtime}`),+ raw.made,+ SAVED,+ ) : null), [raw, facts]);+}++const result = async (res: Response): Promise<MediaResult> => (res.ok ? 'ok' : res.status === 409 ? 'taken' : 'failed');+const send = (method: string, url: string, body: unknown) => fetch(url, { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });++/** The media pane's changes, made in the library; each reads it again. */+export const savedActions = {+ move: async (from: string, to: string) => { const r = await result(await send('PATCH', '/api/saved/files', { from, to })); refreshSaved(); return r; },+ remove: async (path: string) => { const r = await result(await fetch(`/api/saved/files?path=${enc(path)}`, { method: 'DELETE' })); refreshSaved(); return r; },+ newFolder: async (path: string) => { const r = await result(await send('POST', '/api/saved/folders', { path })); refreshSaved(); return r; },+ reveal: (path: string) => { void send('POST', '/api/saved/reveal', { path }); },+ /** Files of this computer (their paths) copied in. Resolves with where each landed. */+ bring: async (paths: string[], into: string): Promise<string[]> => {+ const r = await send('POST', '/api/saved/files/bring', { paths, into });+ const body = await r.json().catch(() => ({})) as { landed?: string[]; error?: string };+ refreshSaved();+ if (!r.ok) throw new Error(body.error ?? 'failed');+ return body.landed ?? [];+ },+ /** Files sent from the page, one at a time, each one's bytes sent reported as it goes. */+ upload: async (files: File[], into: string, onProgress: ImportProgress, failed: string): Promise<string[]> => {+ const landed: string[] = [];+ for (const [i, file] of files.entries()) {+ // eslint-disable-next-line no-await-in-loop+ const { ok, body } = await new Promise<{ ok: boolean; body: { path?: string; error?: string } }>((done) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', `/api/saved/files?path=${enc(`${into}/${file.name}`)}`);+ xhr.upload.onprogress = (e) => { if (e.lengthComputable && e.total > 0) onProgress(i, Math.min(0.99, e.loaded / e.total)); };+ xhr.onload = () => { let body = {}; try { body = JSON.parse(xhr.responseText); } catch { /* none */ } done({ ok: xhr.status >= 200 && xhr.status < 300, body }); };+ xhr.onerror = () => done({ ok: false, body: {} });+ xhr.send(file);+ });+ if (!ok) { refreshSaved(); throw new Error(String(body.error ?? failed)); }+ if (body.path) landed.push(body.path);+ onProgress(i, 1, body.path);+ }+ refreshSaved();+ return landed;+ },+};diff --git a/packages/openfilm/studio/ui/src/lib/template-controls.test.ts b/packages/openfilm/studio/ui/src/lib/template-controls.test.tsnew file mode 100644index 0000000..745c5ce--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/template-controls.test.ts@@ -0,0 +1,94 @@+import { test as it } from 'node:test';+import assert from 'node:assert/strict';+import type { FilmOverride } from './film.ts';+import { changedImage, changedText, changedVar, cssUrl, fieldOf, isFontVar, labelOf, relativeTo, urlOf, valueOf, withImage, withText, withVar } from './template-controls.ts';++it('a custom property is changed as a color, a number with its unit, words, or as typed', () => {+ assert.deepEqual(fieldOf('#ff5746'), { kind: 'color', value: '#ff5746' });+ assert.deepEqual(fieldOf(' rgb(10 20 30 / 50%) '), { kind: 'color', value: 'rgb(10 20 30 / 50%)' });+ assert.deepEqual(fieldOf('oklch(70% 0.1 30)'), { kind: 'color', value: 'oklch(70% 0.1 30)' });+ assert.deepEqual(fieldOf('red'), { kind: 'raw', value: 'red' }, 'a named color takes a browser to know');+ assert.deepEqual(fieldOf('red', (v) => v === 'red'), { kind: 'color', value: 'red' });+ assert.deepEqual(fieldOf('96px'), { kind: 'number', value: 96, unit: 'px' });+ assert.deepEqual(fieldOf('.5'), { kind: 'number', value: 0.5, unit: '' });+ assert.deepEqual(fieldOf('-12.5deg'), { kind: 'number', value: -12.5, unit: 'deg' });+ assert.deepEqual(fieldOf('1.2S'), { kind: 'number', value: 1.2, unit: 's' });+ assert.deepEqual(fieldOf('"Aura Pods"'), { kind: 'text', value: 'Aura Pods' });+ assert.deepEqual(fieldOf(`'It\\'s here'`), { kind: 'text', value: "It's here" });+ assert.deepEqual(fieldOf('calc(10px + 2vw)'), { kind: 'raw', value: 'calc(10px + 2vw)' });+ assert.deepEqual(fieldOf('Helvetica, sans-serif'), { kind: 'raw', value: 'Helvetica, sans-serif' });+});++it('a field writes back what CSS reads', () => {+ assert.equal(valueOf({ kind: 'number', value: 1.23456, unit: 's' }), '1.235s');+ assert.equal(valueOf({ kind: 'text', value: 'Say "hi"' }), '"Say \\"hi\\""');+ assert.equal(valueOf({ kind: 'text', value: 'two\nlines' }), '"two\\A lines"');+ assert.equal(valueOf({ kind: 'color', value: '#00ff00' }), '#00ff00');+ for (const raw of ['"Aura Pods"', '96px', '#ff5746', 'calc(1px + 2px)']) assert.equal(valueOf(fieldOf(raw)), raw, raw);+});++it('a custom property is named as a person reads it', () => {+ assert.equal(labelOf('--accent-color'), 'Accent color');+ assert.equal(labelOf('--titleSize'), 'Title size');+ assert.equal(labelOf('--bg_2'), 'Bg 2');+ assert.equal(labelOf('--'), '--');+});++it('a custom property is kept in the :root entry, beside what else the person changed', () => {+ const title: FilmOverride = { at: '#title', text: 'Hello' };+ const fade = { fade: [0.5, 0] } as unknown as FilmOverride;+ let all = withVar([fade, title], '--accent', '#00ff00');+ assert.deepEqual(all, [fade, title, { at: ':root', style: { '--accent': '#00ff00' } }]);+ all = withVar(all ?? undefined, '--size', '120px');+ assert.equal(changedVar(all ?? undefined, '--accent'), '#00ff00');+ assert.equal(changedVar(all ?? undefined, '--size'), '120px');+ assert.equal(changedVar(all ?? undefined, '--other'), null);+ all = withVar(all ?? undefined, '--accent', null);+ assert.deepEqual(all?.at(-1), { at: ':root', style: { '--size': '120px' } });+ /* the last one back to the page's: no :root entry left */+ assert.deepEqual(withVar(all ?? undefined, '--size', null), [fade, title]);+ assert.equal(withVar(undefined, '--size', null), null, 'nothing to take back');+});++it('a layer\'s words are its text override, by its selector and which match', () => {+ let all = withText(undefined, 'p.line', 2, 'Second');+ assert.deepEqual(all, [{ at: 'p.line', n: 2, text: 'Second' }]);+ assert.equal(changedText(all ?? undefined, 'p.line', 2), 'Second');+ assert.equal(changedText(all ?? undefined, 'p.line'), null, 'every match is another layer');+ all = withText(all ?? undefined, 'p.line', 2, null);+ assert.equal(all, null);+});++it('a picture put in a page is named from the page\'s folder, as CSS writes a url', () => {+ assert.equal(relativeTo('pages/lower.html', 'assets/logo.png'), '../assets/logo.png');+ assert.equal(relativeTo('lower.html', 'assets/logo.png'), 'assets/logo.png');+ assert.equal(relativeTo('saved/x/pages/a.html', 'saved/x/pages/img/b.png'), 'img/b.png');+ assert.equal(relativeTo('a/b/c.html', 'a/d.png'), '../d.png');+ assert.equal(cssUrl('../my "logo".png'), 'url("../my \\"logo\\".png")');+ for (const path of ['../assets/logo.png', 'a b.png', 'my "logo".png']) assert.equal(urlOf(cssUrl(path)), path);+ assert.equal(urlOf("url('x.png')"), 'x.png');+ assert.equal(urlOf('url(x.png)'), 'x.png');+ assert.equal(urlOf('none'), null);+});++it('a picture is replaced with the CSS that draws another file in its place: content for an <img>, a background for a box', () => {+ const logo = { at: 'img.logo', kind: 'img' as const };+ const card = { at: '.card', n: 2, kind: 'bg' as const };+ let all = withImage(undefined, logo, '../assets/new.png');+ all = withImage(all ?? undefined, card, 'bg.jpg');+ assert.deepEqual(all, [+ { at: 'img.logo', style: { content: 'url("../assets/new.png")' } },+ { at: '.card', n: 2, style: { backgroundImage: 'url("bg.jpg")' } },+ ]);+ assert.equal(changedImage(all ?? undefined, logo), '../assets/new.png');+ assert.equal(changedImage(all ?? undefined, { at: '.card', kind: 'bg' }), null, 'another match is another layer');+ assert.deepEqual(withImage(all ?? undefined, logo, null), [{ at: '.card', n: 2, style: { backgroundImage: 'url("bg.jpg")' } }]);+});++it('a custom property that names a font gets the font picker', () => {+ assert.equal(isFontVar('--title-font', '"Inter", sans-serif'), true);+ assert.equal(isFontVar('--fontFamily', 'Geist'), true);+ assert.equal(isFontVar('--font-size', '48px'), false);+ assert.equal(isFontVar('--font-color', '#fff'), false);+ assert.equal(isFontVar('--accent', 'Inter'), false);+});diff --git a/packages/openfilm/studio/ui/src/lib/template-controls.ts b/packages/openfilm/studio/ui/src/lib/template-controls.tsnew file mode 100644index 0000000..3db606b--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/template-controls.ts@@ -0,0 +1,127 @@+/**+ * A page clip's template controls: what the inspector offers to change in a page without opening it, as a motion+ * graphics template has. Read from the page as it is on the picture (studio/server/stage.js `controls`): the CSS custom+ * properties its stylesheets set on `:root`, its words, and its pictures. Each change is an override of the clip, as any+ * change made on the picture is: a custom property in the style of the `:root` entry (the host sets it with priority,+ * so it wins over the page's own), words as a `text` entry, a picture as the CSS that draws another file in its place+ * (`content: url()` for an <img>, `background-image` for a box painted with one). Nothing for an agent to learn: a page+ * that keeps its colors and sizes in custom properties is a template already.+ *+ * Pure: no React, no DOM, so `node --test` runs it (src/template-controls.test.mjs).+ */++import type { FilmOverride } from './film.ts';+import { nextOverrides, overrideOf } from './film-overrides.ts';++/** What the page said: its custom properties and its words, each as it is now. */+export interface TemplateControls {+ vars: Array<{ name: string; value: string }>;+ texts: Array<{ at: string; n?: number; label: string; value: string }>;+ /** Its pictures: an <img>, or a box painted with one image (`bg`); `src` is the address it draws now. */+ images?: TemplateImage[];+ /** The page's own address, that a picture's place is read from. */+ page?: string;+}++export interface TemplateImage { at: string; n?: number; label: string; kind: 'img' | 'bg'; src: string }++/** The style key that draws another file in a picture's place. */+export const imageKey = (kind: TemplateImage['kind']) => (kind === 'img' ? 'content' : 'backgroundImage');++/** How a custom property is changed: a color, a number with its unit, words, or the value as typed. */+export type VarField =+ | { kind: 'color'; value: string }+ | { kind: 'number'; value: number; unit: string }+ | { kind: 'text'; value: string }+ | { kind: 'raw'; value: string };++/** The selector of the entry that holds a clip's custom properties. */+export const ROOT = ':root';++const COLOR = /^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(.*\))$/i;+const NUMBER = /^(-?(?:\d+\.?\d*|\.\d+))([a-z%]*)$/i;+const QUOTED = /^(["'])((?:\\.|(?!\1).)*)\1$/;++/** The field for a value. `isColor` also takes a named color (`red`), which only a browser knows. */+export function fieldOf(value: string, isColor: (v: string) => boolean = () => false): VarField {+ const v = value.trim();+ if (COLOR.test(v) || (/^[a-z]+$/i.test(v) && isColor(v))) return { kind: 'color', value: v };+ const num = NUMBER.exec(v);+ if (num) return { kind: 'number', value: Number(num[1]), unit: num[2]!.toLowerCase() };+ const quoted = QUOTED.exec(v);+ if (quoted) return { kind: 'text', value: quoted[2]!.replace(/\\(.)/g, '$1') };+ return { kind: 'raw', value: v };+}++/** A custom property that names a font (`--title-font: "Inter", sans-serif`): changed with the font picker. */+export function isFontVar(name: string, value: string): boolean {+ return /font|family|typeface/i.test(name) && !NUMBER.test(value.trim()) && !COLOR.test(value.trim());+}++/** What a field writes back: a number with its unit, words quoted as CSS writes a string. */+export function valueOf(field: VarField): string {+ if (field.kind === 'number') return `${Math.round(field.value * 1000) / 1000}${field.unit}`;+ if (field.kind === 'text') return `"${field.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\A ')}"`;+ return field.value.trim();+}++/** A custom property's name as a person reads it: `--accent-color` → "Accent color", `--titleSize` → "Title size". */+export function labelOf(name: string): string {+ const words = name.replace(/^-+/, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[-_\s]+/).filter(Boolean).join(' ').toLowerCase();+ return words ? words[0]!.toUpperCase() + words.slice(1) : name;+}++/** The clip's own value of a custom property (an override), or null when it has the page's. */+export function changedVar(overrides: readonly FilmOverride[] | undefined, name: string): string | null {+ const v = overrideOf(overrides, { at: ROOT })?.style?.[name];+ return v == null ? null : String(v);+}++/** The clip's own words for a layer (an override), or null when it has the page's. */+export function changedText(overrides: readonly FilmOverride[] | undefined, at: string, n?: number): string | null {+ const text = overrideOf(overrides, { at, ...(n != null ? { n } : {}) })?.text;+ return typeof text === 'string' ? text : null;+}++/** The next overrides with a custom property set (null: back to the page's). Null when none is left. */+export function withVar(overrides: readonly FilmOverride[] | undefined, name: string, value: string | null): FilmOverride[] | null {+ const prev = overrideOf(overrides, { at: ROOT });+ const style = { [name]: value };+ /* the entry goes when its last property does (nextOverrides drops an entry that is back to nothing) */+ return nextOverrides(overrides, { at: ROOT }, prev || value != null ? { style } : null);+}++/** The next overrides with a layer's words (null: back to the page's). Null when none is left. */+export function withText(overrides: readonly FilmOverride[] | undefined, at: string, n: number | undefined, value: string | null): FilmOverride[] | null {+ return nextOverrides(overrides, { at, ...(n != null ? { n } : {}) }, { text: value });+}++/** A file's place from a page's folder: `assets/logo.png` from `pages/title.html` is `../assets/logo.png`. */+export function relativeTo(page: string, path: string): string {+ const from = page.split('/').slice(0, -1);+ const to = path.split('/');+ let same = 0;+ while (same < from.length && same < to.length - 1 && from[same] === to[same]) same += 1;+ return [...from.slice(same).map(() => '..'), ...to.slice(same)].join('/');+}++/** A file's place as CSS writes it. */+export const cssUrl = (path: string) => `url("${path.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}")`;++/** The place a CSS `url()` names, or null. */+export function urlOf(css: string | null | undefined): string | null {+ const m = /^\s*url\(\s*(?:"((?:\\.|[^"])*)"|'((?:\\.|[^'])*)'|([^)\s]*))\s*\)\s*$/.exec(css ?? '');+ if (!m) return null;+ return (m[1] ?? m[2] ?? m[3] ?? '').replace(/\\(.)/g, '$1');+}++/** The picture the clip draws in a layer's place (its place from the page's folder), or null when it has the page's. */+export function changedImage(overrides: readonly FilmOverride[] | undefined, image: Pick<TemplateImage, 'at' | 'n' | 'kind'>): string | null {+ const v = overrideOf(overrides, { at: image.at, ...(image.n != null ? { n: image.n } : {}) })?.style?.[imageKey(image.kind)];+ return v == null ? null : urlOf(String(v));+}++/** The next overrides with another file drawn in a picture's place (`path` from the page's folder; null: the page's own). */+export function withImage(overrides: readonly FilmOverride[] | undefined, image: Pick<TemplateImage, 'at' | 'n' | 'kind'>, path: string | null): FilmOverride[] | null {+ return nextOverrides(overrides, { at: image.at, ...(image.n != null ? { n: image.n } : {}) }, { style: { [imageKey(image.kind)]: path == null ? null : cssUrl(path) } });+}diff --git a/packages/openfilm/studio/ui/src/lib/theme-changes.ts b/packages/openfilm/studio/ui/src/lib/theme-changes.tsnew file mode 100644index 0000000..34448b5--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/theme-changes.ts@@ -0,0 +1,31 @@+/**+ * How many times the theme (`<html data-theme>`) has changed since the page loaded, for what draws the theme's colors+ * on a canvas (the audio meters, the waveforms): a canvas keeps the colors it was drawn with, so it draws again when+ * this changes. One observer for the whole page, made when the first one asks.+ */+import React from 'react';++let changes = 0;+const listeners = new Set<() => void>();+let watching = false;++function watch(): void {+ if (watching || typeof MutationObserver === 'undefined' || typeof document === 'undefined') return;+ watching = true;+ let theme = document.documentElement.dataset.theme;+ new MutationObserver(() => {+ if (document.documentElement.dataset.theme === theme) return;+ theme = document.documentElement.dataset.theme;+ changes += 1;+ for (const fn of listeners) fn();+ }).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });+}++/** A number that changes when the theme does: put it among an effect's dependencies to draw again. */+export function useThemeChanges(): number {+ return React.useSyncExternalStore(+ (fn) => { watch(); listeners.add(fn); return () => { listeners.delete(fn); }; },+ () => changes,+ () => 0,+ );+}diff --git a/packages/openfilm/studio/ui/src/lib/thumb-cell.test.ts b/packages/openfilm/studio/ui/src/lib/thumb-cell.test.tsnew file mode 100644index 0000000..63ec654--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/thumb-cell.test.ts@@ -0,0 +1,11 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { thumbCellStyle } from './thumb-cell.ts';++test('a thumbnail cell keeps its own width in a clip narrower than it, so the row has no gaps', () => {+ const style = thumbCellStyle(-50.9, 80, 38);+ assert.equal(style.width, 80);+ assert.equal(style.maxWidth, 'none', 'the page\'s img max-width would squeeze it to the clip');+ assert.equal(style.left, -50.9);+ assert.equal(style.height, 38);+});diff --git a/packages/openfilm/studio/ui/src/lib/thumb-cell.ts b/packages/openfilm/studio/ui/src/lib/thumb-cell.tsnew file mode 100644index 0000000..85c1491--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/thumb-cell.ts@@ -0,0 +1,8 @@+/**+ * How a cell of a clip's thumbnail row is drawn (BlockThumbs): at its own width. An <img> takes the page's+ * `max-width: 100%`, so in a clip narrower than a cell every picture was squeezed to the clip's width while the+ * cells kept their steps, and the clip color showed between them, as if the pictures were broken.+ */+export function thumbCellStyle(left: number, width: number, height: number) {+ return { left, width, maxWidth: 'none', height, opacity: 0.9 } as const;+}diff --git a/packages/openfilm/studio/ui/src/lib/web-update.test.ts b/packages/openfilm/studio/ui/src/lib/web-update.test.tsnew file mode 100644index 0000000..3ce6bbc--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/web-update.test.ts@@ -0,0 +1,26 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { refusedUpdate, webUpdateOf, type VersionSaid } from './web-update.ts';++const said = (over: Partial<VersionSaid> = {}): VersionSaid => ({ version: '0.1.8', latest: '0.1.9', newer: true, checking: true, source: false, ...over });++test("a newer openfilm is offered; none to a Studio that runs the newest, or that does not update itself", () => {+ assert.deepEqual(webUpdateOf(said()), { status: 'available', version: '0.1.9' });+ assert.equal(webUpdateOf(said({ newer: false, latest: '0.1.8' })), null);+ assert.equal(webUpdateOf(said({ source: true })), null, 'a source checkout: git pull');+ assert.equal(webUpdateOf(said({ checking: false })), null, 'checks turned off');+ assert.equal(webUpdateOf(null), null);+});++test('an update Studio is running, or one that failed, is shown as Studio says it', () => {+ assert.deepEqual(webUpdateOf(said({ update: { status: 'updating', version: '0.1.9' } })), { status: 'updating', version: '0.1.9' });+ assert.deepEqual(webUpdateOf(said({ update: { status: 'failed', version: '0.1.9', error: 'npx did not start' } })),+ { status: 'failed', version: '0.1.9', error: 'npx did not start' });+});++test('an export or media being made is a wait; the newest already, nothing; anything else failed', () => {+ assert.deepEqual(refusedUpdate('0.1.9', 'exporting', 'an export is running'), { status: 'waiting', version: '0.1.9', reason: 'exporting' });+ assert.deepEqual(refusedUpdate('0.1.9', 'making', 'media is being made'), { status: 'waiting', version: '0.1.9', reason: 'making' });+ assert.equal(refusedUpdate('0.1.9', 'newest', 'this is the newest openfilm'), null);+ assert.deepEqual(refusedUpdate('0.1.9', undefined, 'Studio answered 500'), { status: 'failed', version: '0.1.9', error: 'Studio answered 500' });+});diff --git a/packages/openfilm/studio/ui/src/lib/web-update.ts b/packages/openfilm/studio/ui/src/lib/web-update.tsnew file mode 100644index 0000000..939cc5c--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/web-update.ts@@ -0,0 +1,41 @@+/**+ * The newest openfilm for a Studio run with npm (not the desktop app's, which updates with the app, nor a source+ * checkout): what Studio's /api/version says of it, and the top bar's Update, which Studio runs in the background as+ * `openfilm update`. Studio then starts again on the new version and the page reloads on it by itself (api.ts listen).+ */++/** What Studio says of its version and the newest (api.ts StudioVersion). */+export interface VersionSaid {+ version: string;+ latest: string | null;+ newer: boolean;+ /** it looks for updates (not a checkout, not turned off) */+ checking: boolean;+ source: boolean;+ /** an update it is running, or one that failed */+ update?: { status: 'updating' | 'failed'; version: string; error?: string };+}++/** The update the top bar shows: one to take, one under way, one waiting for Studio to be idle, or one that failed. */+export type WebUpdate =+ | { status: 'available' | 'updating'; version: string }+ | { status: 'waiting'; version: string; reason: 'exporting' | 'making' }+ | { status: 'failed'; version: string; error: string };++/** The update to show from what Studio says: none for a Studio that does not update itself, or runs the newest. */+export function webUpdateOf(said: VersionSaid | null): WebUpdate | null {+ if (!said || said.source || !said.checking) return null;+ if (said.update?.status === 'updating') return { status: 'updating', version: said.update.version };+ if (said.update?.status === 'failed') return { status: 'failed', version: said.update.version, error: said.update.error ?? '' };+ return said.newer && said.latest ? { status: 'available', version: said.latest } : null;+}++/**+ * Studio would not start the update: why, by its answer's `code`. An export running or media being made is a wait (the+ * update is offered again); the newest already, nothing to show; anything else failed, in its own words.+ */+export function refusedUpdate(version: string, code: unknown, error: string): WebUpdate | null {+ if (code === 'exporting' || code === 'making') return { status: 'waiting', version, reason: code };+ if (code === 'newest') return null;+ return { status: 'failed', version, error };+}diff --git a/packages/openfilm/studio/ui/src/lib/whats-new.test.ts b/packages/openfilm/studio/ui/src/lib/whats-new.test.tsindex dc62297..15f332e 100644--- a/packages/openfilm/studio/ui/src/lib/whats-new.test.ts+++ b/packages/openfilm/studio/ui/src/lib/whats-new.test.ts@@ -1,5 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';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: [] } });@@ -33,3 +34,9 @@ test('each release says what is new in every language, a few lines each', () =>const versions = RELEASES.map((r) => r.version);assert.deepEqual(versions, [...versions].sort((a, b) => compareVersions(b, a)), 'the newest first');});++test('this version has its notes: a release without them shows nothing after the update (as 0.1.7 did)', () => {+ const { version } = JSON.parse(readFileSync(new URL('../../../../package.json', import.meta.url), 'utf8'));+ assert.ok(releaseNotes(version), `write ${version}'s notes in lib/whats-new.ts (the newest first), in every language`);+ assert.equal(RELEASES[0].version, version, 'the newest notes are this version\'s');+});diff --git a/packages/openfilm/studio/ui/src/lib/whats-new.ts b/packages/openfilm/studio/ui/src/lib/whats-new.tsindex 8d2536d..563b542 100644--- a/packages/openfilm/studio/ui/src/lib/whats-new.ts+++ b/packages/openfilm/studio/ui/src/lib/whats-new.ts@@ -3,7 +3,8 @@* 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.+ * for the changelog; these say what a person would notice, in their words, at most six lines. A version without them+ * fails the tests (whats-new.test.ts), so that pull request cannot be merged until they are written.** 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.@@ -15,6 +16,52 @@ 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.7',+ date: '2026-10-14',+ notes: {+ en: [+ { kind: 'new', text: 'Settings › Providers takes services of your own (your voice, a transcription server on this computer, an API that isn’t listed), and your agent can use them.' },+ { kind: 'new', text: 'A title can be restyled together with every title like it (“All like it”), and several layers picked together scale and turn by their box.' },+ { kind: 'new', text: 'Your own key: each model gets the reasoning efforts it takes, and the chat’s model menu offers them.' },+ { kind: 'improved', text: 'Markers have a row of their own under the ruler, and the timeline shows the main track by its look.' },+ { kind: 'improved', text: 'Claude Code runs on your Claude subscription and signs in its own way; its model menu shows its four current models.' },+ { kind: 'fixed', text: 'On Windows, command windows no longer flash up while the app checks or talks to your agents.' },+ ],+ 'zh-CN': [+ { kind: 'new', text: '设置 › 服务商 可以添加你自己的服务(自己的声音、本机的转写服务、未列出的 API),智能体可以直接使用。' },+ { kind: 'new', text: '标题可以和同类标题一起改样式(「所有同类」);多选的图层可以按整体框一起缩放、旋转。' },+ { kind: 'new', text: '自有密钥:每个模型可以设置它支持的推理档位,对话里的模型菜单会提供这些档位。' },+ { kind: 'improved', text: '标记在标尺下方有了单独的一行;时间线用外观区分主轨道。' },+ { kind: 'improved', text: 'Claude Code 只使用你的 Claude 订阅,并按官方方式授权登录;模型菜单显示它当前的四个模型。' },+ { kind: 'fixed', text: 'Windows 上检查或使用智能体时,不再不停弹出命令行窗口。' },+ ],+ ja: [+ { kind: 'new', text: '設定 › プロバイダーに自分のサービス(自分の声、このコンピューターの文字起こしサーバー、一覧にない API)を追加でき、エージェントが使えます。' },+ { kind: 'new', text: 'タイトルを同じ種類のタイトルとまとめてスタイル変更でき(「同じ種類すべて」)、複数選んだレイヤーは枠ごと拡大縮小・回転できます。' },+ { kind: 'new', text: '自分のキー:モデルごとに対応する推論の強さを設定でき、チャットのモデルメニューで選べます。' },+ { kind: 'improved', text: 'マーカーはルーラーの下に専用の行ができ、タイムラインはメイントラックを見た目で示します。' },+ { kind: 'improved', text: 'Claude Code は Claude のサブスクリプションだけで動き、公式の方法でサインインします。モデルメニューには現在の 4 つのモデルが表示されます。' },+ { kind: 'fixed', text: 'Windows で、エージェントの確認や利用のたびにコマンドウィンドウが開かなくなりました。' },+ ],+ ko: [+ { kind: 'new', text: '설정 › 제공업체에 내 서비스(내 목소리, 이 컴퓨터의 전사 서버, 목록에 없는 API)를 추가할 수 있고, 에이전트가 사용할 수 있습니다.' },+ { kind: 'new', text: '제목을 같은 종류의 제목과 함께 스타일 변경할 수 있고("같은 종류 모두"), 여러 레이어를 선택하면 상자째로 크기를 바꾸고 회전할 수 있습니다.' },+ { kind: 'new', text: '내 키: 모델마다 지원하는 추론 강도를 정할 수 있고, 채팅의 모델 메뉴에서 고를 수 있습니다.' },+ { kind: 'improved', text: '마커는 눈금자 아래 전용 줄에 놓이고, 타임라인은 메인 트랙을 모양으로 보여 줍니다.' },+ { kind: 'improved', text: 'Claude Code는 Claude 구독으로만 실행되고 공식 방식으로 로그인합니다. 모델 메뉴에는 현재의 네 모델이 나옵니다.' },+ { kind: 'fixed', text: 'Windows에서 에이전트를 확인하거나 사용할 때 명령 창이 더 이상 뜨지 않습니다.' },+ ],+ es: [+ { kind: 'new', text: 'Ajustes › Proveedores admite servicios tuyos (tu voz, un servidor de transcripción en este equipo, una API que no está en la lista), y tu agente puede usarlos.' },+ { kind: 'new', text: 'Un título puede cambiar de estilo junto con todos los títulos como él («Todos los iguales»), y varias capas seleccionadas se escalan y giran con su caja.' },+ { kind: 'new', text: 'Tu propia clave: cada modelo tiene los esfuerzos de razonamiento que admite, y el menú de modelos del chat los ofrece.' },+ { kind: 'improved', text: 'Los marcadores tienen su propia fila bajo la regla, y la línea de tiempo muestra la pista principal por su aspecto.' },+ { kind: 'improved', text: 'Claude Code funciona solo con tu suscripción de Claude e inicia sesión a su manera; su menú de modelos muestra sus cuatro modelos actuales.' },+ { kind: 'fixed', text: 'En Windows ya no se abren ventanas de comandos mientras la app revisa o usa tus agentes.' },+ ],+ },+ },{version: '0.1.6',date: '2026-10-13',diff --git a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts b/packages/openfilm/studio/ui/src/lib/workspace-resources.tsindex c4f1812..775e9d4 100644--- a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts+++ b/packages/openfilm/studio/ui/src/lib/workspace-resources.ts@@ -41,8 +41,13 @@ export interface WorkspaceResource {link?: MediaLink;/** Heavy footage's proxy for the preview (studio/server/proxies.mjs): waiting, being made (`ratio`), ready, failed. */proxy?: MediaProxy;+ /** In Saved, what Studio saved from a film (studio/server/saved.mjs): a clip, clips together, or a page with its files. */+ bundle?: SavedBundle;}+/** What a bundle of Saved is: a clip, a group of `count` clips, or a page; `template`: its page has custom properties. */+export interface SavedBundle { kind: 'clip' | 'group' | 'page'; count?: number; template?: boolean }+export interface MediaProxy { state: 'waiting' | 'making' | 'ready' | 'failed'; ratio?: number }/** Where a linked file or folder is kept (`to`, a full path); `missing`: it cannot be reached (a NAS that is off). */@@ -99,7 +104,7 @@ export interface MediaFacts {/** Studio's `GET files` answer. */export interface FilesListing {- files: readonly { path: string; kind: string; size: number; mtime: number; added?: number }[];+ files: readonly { path: string; kind: string; size: number; mtime: number; added?: number; saved?: SavedBundle & { durationMs?: number; w?: number; h?: number } }[];folders: readonly string[];pages: readonly { path: string; size: number; mtime: number }[];/** Links to media kept elsewhere, by project path (files and folders). */@@ -147,12 +152,19 @@ export function mediaListingOf(/* a page put in a folder here is a page still: its poster, its preview, an mg clip */files: raw.files.map((f) => ({path: f.path,- name: f.kind === 'page' ? pageName(f.path) : f.path.slice(f.path.lastIndexOf('/') + 1),+ name: f.kind === 'page' && !f.saved ? pageName(f.path) : f.path.slice(f.path.lastIndexOf('/') + 1),dir: dirOf(f.path),size: f.size,kind: (f.kind === 'page' ? 'mg' : MEDIA_KINDS.includes(f.kind) ? f.kind : 'other') as WorkspaceResourceKind,mtimeMs: f.mtime,addedMs: f.added ?? f.mtime,+ /* a bundle of Saved says its own length and size (it is no file to probe) */+ ...(f.saved ? {+ bundle: { kind: f.saved.kind, ...(f.saved.count ? { count: f.saved.count } : {}), ...(f.saved.template ? { template: true } : {}) },+ ...(f.saved.durationMs ? { durationMs: f.saved.durationMs } : {}),+ ...(f.saved.w ? { w: f.saved.w } : {}),+ ...(f.saved.h ? { h: f.saved.h } : {}),+ } : {}),...facts?.(f.path),...(raw.links?.[f.path] ? { link: raw.links[f.path]! } : {}),})),diff --git a/scripts/audit-public.mjs b/scripts/audit-public.mjsindex 84d3880..707dc77 100644--- a/scripts/audit-public.mjs+++ b/scripts/audit-public.mjs@@ -4,7 +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, the release notes (whats-new.ts) and translated docs+ * cjk Chinese, Japanese or Korean prose outside the i18n dictionaries, the release notes (whats-new.ts), translated docs+ * and a skill's openfilm.json (its title and summary in each language)* (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@@ -38,7 +39,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)\/|\/whats-new\.ts$|\.(zh-CN|ja|ko|es)\.md$/;+const LOCALE = /(^|\/)(i18n|locales)\/|\/whats-new\.ts$|\.(zh-CN|ja|ko|es)\.md$|(^|\/)skills\/[^/]+\/openfilm\.json$/;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. */diff --git a/scripts/sync-examples.mjs b/scripts/sync-examples.mjsnew file mode 100644index 0000000..522d66d--- /dev/null+++ b/scripts/sync-examples.mjs@@ -0,0 +1,54 @@+#!/usr/bin/env node+/**+ * `pnpm examples:sync`: the examples index and the posters it names, copied from a checkout of openfilm/examples into+ * packages/openfilm/examples-index, which the npm package and the desktop app take with them. Studio shows these at+ * once, before the index on GitHub is read (studio/server/examples.mjs): the films themselves are fetched when one is+ * opened. This folder is replaced whole, and its SOURCE file says which commit it came from.+ *+ * pnpm examples:sync from the checkout beside this repository+ * pnpm examples:sync <folder> from another checkout+ * pnpm examples:sync --check exit 1 when the copy here is not that checkout's commit, as SOURCE says+ */+import { execFileSync } from 'node:child_process';+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));+const TO = join(ROOT, 'packages', 'openfilm', 'examples-index');+const REPO = 'https://github.com/openfilm/examples';++const args = process.argv.slice(2);+const check = args.includes('--check');+const from = resolve(args.find((a) => !a.startsWith('--')) ?? join(ROOT, '..', 'examples'));+const fail = (/** @type {string} */ why) => { console.error(`examples:sync: ${why}`); process.exit(1); };++if (!existsSync(join(from, 'examples.json'))) fail(`${from} is not a checkout of ${REPO}: clone it beside this repository, or name one`);+const git = (/** @type {string[]} */ a) => execFileSync('git', ['-C', from, ...a], { encoding: 'utf8' }).trim();+const commit = git(['rev-parse', 'HEAD']);+if (git(['status', '--porcelain', '--', 'examples.json'])) fail(`${from}/examples.json has changes not committed: commit them first`);++const index = JSON.parse(readFileSync(join(from, 'examples.json'), 'utf8'));+/* the posters it names, as paths in the repository (an address stays an address) */+const posters = (Array.isArray(index.examples) ? index.examples : [])+ .map((e) => e?.poster).filter((p) => typeof p === 'string' && !/^https?:\/\//.test(p) && !p.split('/').includes('..'));+const wanted = ['examples.json', ...posters];+const source = `${REPO}/commit/${commit}\nCopied by \`pnpm examples:sync\`. Change the examples in ${REPO}, not here.\n`;++if (check) {+ const said = existsSync(join(TO, 'SOURCE')) ? readFileSync(join(TO, 'SOURCE'), 'utf8') : '';+ if (said !== source) fail(`SOURCE does not name ${commit.slice(0, 7)}, the commit of ${from}: run pnpm examples:sync`);+ const differ = wanted.filter((f) => !existsSync(join(TO, f)) || !readFileSync(join(from, f)).equals(readFileSync(join(TO, f))));+ if (differ.length) fail(`the copy differs from ${commit.slice(0, 7)} in ${differ.join(', ')}: run pnpm examples:sync`);+ console.log(`examples:sync: packages/openfilm/examples-index is ${REPO} at ${commit.slice(0, 7)}`);+ process.exit(0);+}++for (const f of posters) if (!existsSync(join(from, f))) fail(`${f}, a poster examples.json names, is not in ${from}`);+rmSync(TO, { recursive: true, force: true });+for (const f of wanted) {+ mkdirSync(dirname(join(TO, f)), { recursive: true });+ copyFileSync(join(from, f), join(TO, f));+}+writeFileSync(join(TO, 'SOURCE'), source);+console.log(`examples:sync: the index and ${posters.length} posters from ${REPO} at ${commit.slice(0, 7)} → ${relative(ROOT, TO)}`);diff --git a/scripts/sync-skills.mjs b/scripts/sync-skills.mjsnew file mode 100644index 0000000..657d11e--- /dev/null+++ b/scripts/sync-skills.mjs@@ -0,0 +1,60 @@+#!/usr/bin/env node+/**+ * `pnpm skills:sync`: the official skills, copied from a checkout of openfilm/skills into packages/openfilm/skills,+ * where the npm package and the desktop app take them from. The skills are changed there, never here: this folder is+ * replaced whole, and its SOURCE file says which commit it came from.+ *+ * pnpm skills:sync from the checkout beside this repository (the folder holding it also holds skills/)+ * pnpm skills:sync <folder> from another checkout+ * pnpm skills:sync --check exit 1 when the copy here is not that checkout's commit, as SOURCE says+ *+ * The checkout's own check runs first, and a checkout with changes not committed is refused: a copy is always of a+ * commit. While changing skills, `pnpm dev` reads them from the checkout itself (OPENFILM_OFFICIAL_SKILLS).+ */+import { execFileSync } from 'node:child_process';+import { cpSync, existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));+const TO = join(ROOT, 'packages', 'openfilm', 'skills');+const SOURCE = join(TO, 'SOURCE');+const REPO = 'https://github.com/openfilm/skills';++const args = process.argv.slice(2);+const check = args.includes('--check');+const from = resolve(args.find((a) => !a.startsWith('--')) ?? join(ROOT, '..', 'skills'));+const fail = (/** @type {string} */ why) => { console.error(`skills:sync: ${why}`); process.exit(1); };++if (!existsSync(join(from, 'skills')) || !existsSync(join(from, 'scripts', 'check.mjs'))) {+ fail(`${from} is not a checkout of ${REPO}: clone it beside this repository, or name one`);+}+const git = (/** @type {string[]} */ a) => execFileSync('git', ['-C', from, ...a], { encoding: 'utf8' }).trim();+const commit = git(['rev-parse', 'HEAD']);+if (git(['status', '--porcelain'])) fail(`${from} has changes not committed: commit them first, so the copy is of a commit`);++/** Every file under a folder, by its path in it, dot files and SOURCE left out. @param {string} dir */+const files = (dir, base = '') => readdirSync(join(dir, base), { withFileTypes: true })+ .filter((e) => !e.name.startsWith('.') && !(base === '' && e.name === 'SOURCE'))+ .flatMap((e) => (e.isDirectory() ? files(dir, join(base, e.name)) : [join(base, e.name)]))+ .sort();++const source = `${REPO}/commit/${commit}\nCopied by \`pnpm skills:sync\`. Change the skills in ${REPO}, not here.\n`;+if (check) {+ const theirs = files(join(from, 'skills'));+ const ours = existsSync(TO) ? files(TO) : [];+ const differ = [...new Set([...theirs, ...ours])].filter((file) => !theirs.includes(file) || !ours.includes(file)+ || !readFileSync(join(from, 'skills', file)).equals(readFileSync(join(TO, file))));+ const said = existsSync(SOURCE) ? readFileSync(SOURCE, 'utf8') : '';+ if (said !== source) fail(`SOURCE does not name ${commit.slice(0, 7)}, the commit of ${from}: run pnpm skills:sync`);+ if (differ.length) fail(`the copy differs from ${commit.slice(0, 7)} in ${differ.join(', ')}: run pnpm skills:sync`);+ console.log(`skills:sync: packages/openfilm/skills is ${REPO} at ${commit.slice(0, 7)}`);+ process.exit(0);+}++execFileSync(process.execPath, [join(from, 'scripts', 'check.mjs')], { stdio: 'inherit' });+rmSync(TO, { recursive: true, force: true });+cpSync(join(from, 'skills'), TO, { recursive: true, filter: (src) => !src.split(/[\\/]/).pop()?.startsWith('.') });+writeFileSync(SOURCE, source);+const names = readdirSync(TO).filter((n) => statSync(join(TO, n)).isDirectory());+console.log(`skills:sync: ${names.length} skills from ${REPO} at ${commit.slice(0, 7)} → ${relative(ROOT, TO)}`);