The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Desktop: Codex from the Store found right; chat keys stay in the chat; Studio: Replace, subtitle style (#40)
riverisbuildingbe758b9fe010
diff --git a/.changeset/agent-notices-apart.md b/.changeset/agent-notices-apart.mdnew file mode 100644index 0000000..240c7b9--- /dev/null+++ b/.changeset/agent-notices-apart.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: an agent's own notices show apart from its reply. A Codex warning such as "Falling back from WebSockets to HTTPS transport" is now a quiet line of its own instead of words in the middle of the answer, as are notes like "Context compacted".diff --git a/.changeset/chat-keys-stay-in-chat.md b/.changeset/chat-keys-stay-in-chat.mdnew file mode 100644index 0000000..a9a16a5--- /dev/null+++ b/.changeset/chat-keys-stay-in-chat.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: keys and clicks in the chat stay in the chat. A click anywhere in it, not only in the message box, keeps the keyboard there: Space no longer plays the film, and Delete, ⌘A or ⌘Z no longer act on Studio. Clicking into the chat keeps what is selected in Studio, so the message can point at it. Typing while a media file is previewed no longer plays it or loses the spaces.diff --git a/.changeset/codex-store-window-program.md b/.changeset/codex-store-window-program.mdnew file mode 100644index 0000000..5812f5a--- /dev/null+++ b/.changeset/codex-store-window-program.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++Desktop on Windows: the Codex app from the Microsoft Store is no longer taken for the Codex CLI. Its own `Codex.exe` is the app's window, so Codex showed as ready, the model menu could not start it, and each Retry opened the app. Only a console program found there is used now: with no CLI installed, Codex shows as not installed, with where to get it. When the model menu cannot start an agent, the reason is written to the app's log.diff --git a/.changeset/media-requests-in-turn.md b/.changeset/media-requests-in-turn.mdnew file mode 100644index 0000000..091a5e8--- /dev/null+++ b/.changeset/media-requests-in-turn.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: a clip dropped on the timeline of a film just made is saved at once. The timeline's thumbnails, clip posters, the media pane's covers and waveforms now take turns (web pages one at a time, as the server draws them), so they no longer hold every connection while an edit or an import waits; a film's thumbnails also come sooner.diff --git a/.changeset/replace-order-viewer.md b/.changeset/replace-order-viewer.mdnew file mode 100644index 0000000..010fb33--- /dev/null+++ b/.changeset/replace-order-viewer.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: a clip's inspector has a Replace button: another file of the project in its place, or one picked from your computer (also in the clip's menu, under Replace with…). The media pane lists files in the order they were added, the newest last, and selects what you just imported. In the viewer, a click in the dark around the picture no longer pauses the film: it stops only once a selection box is pulled open there.diff --git a/.changeset/subtitle-pick-shows-look.md b/.changeset/subtitle-pick-shows-look.mdnew file mode 100644index 0000000..4e6e06e--- /dev/null+++ b/.changeset/subtitle-pick-shows-look.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Studio: pressing a subtitle on the picture, or its line on the timeline's subtitle row, opens the subtitle style (font, size, color, outline, box) in the inspector, as pressing a layer opens its own.diff --git a/apps/desktop/chat/src/components/AgentActivityRow.tsx b/apps/desktop/chat/src/components/AgentActivityRow.tsxindex abda7d9..ea650a3 100644--- a/apps/desktop/chat/src/components/AgentActivityRow.tsx+++ b/apps/desktop/chat/src/components/AgentActivityRow.tsx@@ -33,7 +33,7 @@ export interface AgentActivityItem {/*** i18n token.* · act — `act.<name>`, a closed set (see AGENT_ACTS in @openfilm/shared)- * · notice — the note the platform leaves+ * · notice — the note the platform leaves (empty for an agent's own notice: its words are in `text`)* · text — unused; the body is in `text`*/label: string;@@ -143,6 +143,8 @@ const AgentActivityRow = React.memo(function AgentActivityRow({/* A note the platform leaves in the conversation (today only "earlier messages were summarized").Drawn as a labeled divider: it marks that the agent no longer sees the original text above it. */if (item.kind === 'notice') {+ /* A local agent's own notice (a Codex warning): its words, quiet, apart from what it says to the person */+ if (item.text) return <p className="break-words py-1 text-[12px] leading-relaxed text-[var(--chat-hint)]">{item.text}</p>;return (<div className="flex items-center gap-2.5 py-1.5"><span className="h-px flex-1 bg-[var(--border)]" />diff --git a/apps/desktop/chat/src/lib/agent-transcript.ts b/apps/desktop/chat/src/lib/agent-transcript.tsindex d72eca8..48d05f4 100644--- a/apps/desktop/chat/src/lib/agent-transcript.ts+++ b/apps/desktop/chat/src/lib/agent-transcript.ts@@ -54,6 +54,8 @@ export interface TranscriptItem {* These rows are not the agent speaking but a note the platform leaves in the conversation; today* there is one: earlier messages were summarized. It belongs in the conversation, because what it* says is that the agent no longer has the original of the text above it.+ *+ * A local agent's own notice (ACP `notice`, such as a Codex warning) has no key: its words are in `text`.*/noticeKey?: string;text?: string;@@ -260,7 +262,7 @@ export function toTraceLogItems(items: TranscriptItem[]): AgentActivityItem[] {function traceLogItem(item: TranscriptItem): AgentActivityItem {if (item.kind === 'notice') {- return { kind: 'notice' as const, id: item.id, label: item.noticeKey ?? '' };+ return { kind: 'notice' as const, id: item.id, label: item.noticeKey ?? '', ...(item.text ? { text: item.text } : {}) };}if (item.kind === 'thought') {return {diff --git a/apps/desktop/chat/src/lib/local-agent-run.ts b/apps/desktop/chat/src/lib/local-agent-run.tsindex 1c431f6..51b1d07 100644--- a/apps/desktop/chat/src/lib/local-agent-run.ts+++ b/apps/desktop/chat/src/lib/local-agent-run.ts@@ -317,12 +317,13 @@ export class LocalAgentTurn {this.lastEventAt = Date.now();const kind = update.sessionUpdate;const closed = kind !== 'agent_thought_chunk' && this.closeThought();- if (kind === 'tool_call' || kind === 'agent_thought_chunk' || kind === 'plan') {+ if (kind === 'tool_call' || kind === 'agent_thought_chunk' || kind === 'plan' || kind === 'notice') {if (this.lastWasText) this.part += 1;this.lastWasText = false;}if (kind === 'agent_thought_chunk') { this.think(update); return; }if (kind === 'plan') { this.plan(update); return; }+ if (kind === 'notice') { this.agentNotice(update); return; }const callId = (update as { toolCallId?: unknown }).toolCallId;const tool = kind === 'tool_call_update' && callId != null? this.calls.get(String(callId))?.tool@@ -431,6 +432,25 @@ export class LocalAgentTurn {this.emit();}+ /**+ * A note from the agent itself (ACP `notice`: Codex's warnings, its context compaction), in its own words. It+ * is not part of the reply, so it gets its own row.+ */+ private agentNotice(update: AcpUpdate): void {+ const { title, description } = update as { title?: unknown; description?: unknown };+ const text = [title, description]+ .filter((s): s is string => typeof s === 'string' && s.trim() !== '')+ .map((s) => s.trim())+ .join(' — ');+ if (text) {+ this.noticeNo += 1;+ this.items = [...this.items, { id: `notice:${this.turnNo}:agent:${this.noticeNo}`, kind: 'notice', text, turnNo: this.turnNo, pending: false, startedAt: Date.now() }];+ }+ this.emit();+ }++ private noticeNo = 0;+/** Later fields make the row clearer (Codex sends an edit's diff later, and the title may change). */private refineAct(update: AcpUpdate): void {const u = update as { toolCallId?: unknown; title?: unknown; kind?: unknown; rawInput?: unknown; locations?: unknown; content?: unknown };diff --git a/apps/desktop/shell/index.html b/apps/desktop/shell/index.htmlindex 0ef7934..cba8c91 100644--- a/apps/desktop/shell/index.html+++ b/apps/desktop/shell/index.html@@ -17,9 +17,11 @@</head><body><div id="root"></div>-<!-- the chat's column beside Studio (the panel Studio leaves room for), and its layer for what floats -->-<div id="of-chat" class="of-chat" data-studio-host-panel></div>-<div id="of-chat-layer" class="of-chat"></div>+<!-- the chat's column beside Studio (the panel Studio leaves room for), and its layer for what floats. Both are+ Studio's host panel (its keys leave them alone) and take focus: a click anywhere in the chat, not only in its+ fields, keeps the keyboard in the chat (Space, Delete, ⌘A there never reach Studio). -->+<div id="of-chat" class="of-chat" data-studio-host-panel tabindex="-1"></div>+<div id="of-chat-layer" class="of-chat" data-studio-host-panel tabindex="-1"></div><script type="module" src="./main.tsx"></script></body></html>diff --git a/apps/desktop/shell/shell.css b/apps/desktop/shell/shell.cssindex bf2b0ab..6594360 100644--- a/apps/desktop/shell/shell.css+++ b/apps/desktop/shell/shell.css@@ -13,3 +13,5 @@#of-chat[data-assets-open] aside { pointer-events: auto; }/* the chat's layer takes no room: what it holds is fixed in place over the window */#of-chat-layer { height: 0; background: transparent; }+/* focused by a click to keep the keyboard in the chat (index.html), never ringed */+#of-chat:focus, #of-chat-layer:focus { outline: none; }diff --git a/apps/desktop/src/agent-installation.mjs b/apps/desktop/src/agent-installation.mjsindex 168a718..21e07b2 100644--- a/apps/desktop/src/agent-installation.mjs+++ b/apps/desktop/src/agent-installation.mjs@@ -5,7 +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 { accessSync, constants, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs';+import { accessSync, closeSync, constants, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';import { homedir } from 'node:os';import { delimiter, dirname, isAbsolute, join } from 'node:path';@@ -42,6 +42,28 @@ export function executableFile(path) {try { accessSync(path, constants.X_OK); return statSync(path).isFile(); } catch { return false; }}+/**+ * Whether a file is a Windows program for the console, by its header and without starting it: a window program (a+ * desktop app's own, as `app\Codex.exe` in the Codex Store app is) would open its window, and answers nothing.+ */+export function consoleProgram(path) {+ let fd;+ try {+ fd = openSync(path, 'r');+ const head = Buffer.alloc(4096);+ const read = readSync(fd, head, 0, head.length, 0);+ if (read < 64 || head.toString('latin1', 0, 2) !== 'MZ') return false;+ const pe = head.readUInt32LE(0x3c);+ /* the subsystem sits at the same place in 32- and 64-bit headers: 3 is the console, 2 a window */+ if (pe + 0x5e > read || head.toString('latin1', pe, pe + 4) !== 'PE\0\0') return false;+ return head.readUInt16LE(pe + 0x5c) === 3;+ } catch {+ return false;+ } finally {+ if (fd !== undefined) closeSync(fd);+ }+}+/*** Claude Code as the Claude app keeps it: one folder per version under Application Support, newest first, the program* either straight inside (`<version>/claude.app`) or one folder down (`<version>/<build>/claude.app`, newer apps).diff --git a/apps/desktop/src/agent-installation.test.mjs b/apps/desktop/src/agent-installation.test.mjsindex 88f8846..0f49d9b 100644--- a/apps/desktop/src/agent-installation.test.mjs+++ b/apps/desktop/src/agent-installation.test.mjs@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { chosenProgram, claudeAppCli, cmdTarget, detectAgentInstallation, findExecutable, searchReport, windowsBinDirs } from './agent-installation.mjs';+import { chosenProgram, claudeAppCli, cmdTarget, consoleProgram, detectAgentInstallation, findExecutable, searchReport, windowsBinDirs } from './agent-installation.mjs';test("an npm .cmd shim (Windows) runs its package's script: that is what gets started", () => {const npm = mkdtempSync(join(tmpdir(), 'of-npm-'));@@ -142,6 +142,31 @@ test('the program the person chose comes first; it can be a shim, the .cmd besidassert.equal(chosenProgram('relative\\claude.exe', { names: ['claude'], win: true }), null);});+/** A Windows program's header, enough to tell its subsystem: 3 the console, 2 a window. */+function peProgram(subsystem, { wide = true } = {}) {+ const bytes = Buffer.alloc(0x200);+ bytes.write('MZ', 0, 'latin1');+ bytes.writeUInt32LE(0x80, 0x3c);+ bytes.write('PE\0\0', 0x80, 'latin1');+ bytes.writeUInt16LE(wide ? 0x20b : 0x10b, 0x80 + 24);+ bytes.writeUInt16LE(subsystem, 0x80 + 0x5c);+ return bytes;+}++test('a console program is told from a window program by its header, without starting it', () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-pe-'));+ const at = (name, bytes) => { const file = join(dir, name); writeFileSync(file, bytes); return file; };+ assert.equal(consoleProgram(at('codex.exe', peProgram(3))), true);+ assert.equal(consoleProgram(at('codex32.exe', peProgram(3, { wide: false }))), true);+ /* the Codex Store app's own Codex.exe: its window, not the CLI */+ assert.equal(consoleProgram(at('Codex.exe', peProgram(2))), false);+ /* the Linux CLI the same app carries for WSL, a script, a cut-off file, nothing */+ assert.equal(consoleProgram(at('codex', Buffer.concat([Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.alloc(60)]))), false);+ assert.equal(consoleProgram(at('codex.cmd', '@echo off')), false);+ assert.equal(consoleProgram(at('short.exe', peProgram(3).subarray(0, 0x90))), false);+ assert.equal(consoleProgram(join(dir, 'missing.exe')), false);+});+test('a program found some other way (a Store app) is used last', () => {if (process.platform === 'win32') return;const home = mkdtempSync(join(tmpdir(), 'of-home-'));diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjsindex fa88ac6..a4a2b11 100644--- a/apps/desktop/src/agents.mjs+++ b/apps/desktop/src/agents.mjs@@ -32,7 +32,7 @@ import { Readable, Writable } from 'node:stream';import { fileURLToPath } from 'node:url';import * as acp from '@agentclientprotocol/sdk';import { PATH_SEP, childEnvironment, lastPathSource, loginShellEnvironment, loginShellVariables } from './environment.mjs';-import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, detectAgentInstallation, searchReport } from './agent-installation.mjs';+import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, consoleProgram, detectAgentInstallation, searchReport } from './agent-installation.mjs';import { nodeBinary } from './node-runtime.mjs';import { outOfBalance } from './pi-config.mjs';@@ -156,7 +156,7 @@ let slowFound = { npmPrefix: null, storeCodex: null };let slowCache = null;const SLOW_FOR_MS = 10 * 60_000;/* an OpenAI app from the Microsoft Store (ChatGPT, Codex) that carries Codex: where its codex.exe is */-const STORE_CODEX = "Get-AppxPackage -Name 'OpenAI.*' | ForEach-Object { Get-ChildItem -LiteralPath $_.InstallLocation -Recurse -Depth 5 -Filter codex.exe -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName }";+const STORE_CODEX = "Get-AppxPackage -Name 'OpenAI.*' | ForEach-Object { Get-ChildItem -LiteralPath $_.InstallLocation -Recurse -Depth 5 -Filter codex.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName }";/*** Windows only, and only when an agent is not found the quick way: where npm puts global commands (a prefix of the@@ -173,7 +173,9 @@ function windowsSlowSearch({ fresh = false } = {}) {run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', STORE_CODEX], 20_000, { env }),]);const prefix = npm.ok ? npm.stdout.trim().split(/\r?\n/).pop()?.trim() : null;- const exe = store.ok ? store.stdout.split(/\r?\n/).map((l) => l.trim()).find((l) => /codex\.exe$/i.test(l)) : null;+ /* the Codex app's own window program is a codex.exe too (`app\Codex.exe`, the filter ignores case): only a console+ program is the CLI */+ const exe = store.ok ? store.stdout.split(/\r?\n/).map((l) => l.trim()).find((l) => /codex\.exe$/i.test(l) && isAbsolute(l) && consoleProgram(l)) : null;slowFound = { npmPrefix: prefix && isAbsolute(prefix) ? prefix : null, storeCodex: exe && isAbsolute(exe) ? exe : null };return slowFound;})().catch(() => slowFound);@@ -509,6 +511,16 @@ export function formContent(questions, answers) {return content;}+/** What the app tells each agent, as it shakes hands, that the chat can do. */+export const CLIENT_CAPABILITIES = {+ fs: { readTextFile: false, writeTextFile: false }, terminal: false, elicitation: { form: {} },+ /* the agent's own warnings (Codex: "Falling back from WebSockets…") come as notices, not as words in its reply */+ session: { notices: {} },+ /* Claude Code's "recommended value" extension: its model and effort lists come without a "Default" row, the+ current value named for what it is */+ _meta: { jetbrains: { air: { version: 1, capabilities: ['recommendedValue'] } } },+};+/** ACP's auth_required: the agent wants its own sign-in first. */const AUTH_REQUIRED = -32000;@@ -626,12 +638,7 @@ export class AgentSession {const init = await this.conn.agent.request(acp.methods.agent.initialize, {protocolVersion: acp.PROTOCOL_VERSION,- clientCapabilities: {- fs: { readTextFile: false, writeTextFile: false }, terminal: false, elicitation: { form: {} },- /* Claude Code's "recommended value" extension: its model and effort lists come without a "Default" row, the- current value named for what it is */- _meta: { jetbrains: { air: { version: 1, capabilities: ['recommendedValue'] } } },- },+ clientCapabilities: CLIENT_CAPABILITIES,clientInfo: { name: 'openfilm-desktop', title: 'OpenFilm', version: '0.1.0' },});diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjsindex 3eb5936..9e7ef97 100644--- a/apps/desktop/src/agents.test.mjs+++ b/apps/desktop/src/agents.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { allowOption, codexDeveloperInstructions, legacyOptions, readAgentStatus } from './agents.mjs';+import { CLIENT_CAPABILITIES, allowOption, codexDeveloperInstructions, legacyOptions, readAgentStatus } from './agents.mjs';test('an agent that asks: yes for good where it offers that, else yes this once; nothing to say yes with is null', () => {const options = [@@ -46,3 +46,13 @@ test("the person's own developer_instructions in Codex's config, read as TOML wrassert.equal(codexDeveloperInstructions('model = "gpt"\n'), null);assert.equal(codexDeveloperInstructions(''), null);});++test('the chat says it shows notices, so an agent sends its warnings as notices and not as words in its reply', async () => {+ /* the SDK's own parser, which drops a malformed capability without a word */+ const { zClientCapabilities } = await import(new URL('../node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.js', import.meta.url).href);+ const parsed = zClientCapabilities.parse(CLIENT_CAPABILITIES);+ /* the check Codex's adapter makes (codex-acp: clientSupportsNotices) */+ const notices = parsed.session?.notices;+ assert.ok(typeof notices === 'object' && notices !== null && !Array.isArray(notices));+ assert.deepEqual(parsed.elicitation, { form: {} });+});diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjsindex 604d2c1..82ef3c3 100644--- a/apps/desktop/src/local-agents-ipc.mjs+++ b/apps/desktop/src/local-agents-ipc.mjs@@ -146,7 +146,10 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacawait Promise.race([heard, new Promise((done) => setTimeout(done, PROBE_COMMANDS_MS))]);return { ok: true, info: { ...info, ...(commands ? { commands } : {}) } };} catch (e) {- return { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.code ? { code: String(e.code) } : {}) };+ const error = e instanceof Error ? e.message : String(e);+ /* the model menu says only that it could not start: what went wrong is kept here (logs/studio.log) */+ log(`probe ${agent}: ${error.replace(/\s+/g, ' ').slice(0, 500)}\n`);+ return { ok: false, error, ...(e?.code ? { code: String(e.code) } : {}) };} finally {session?.close();}diff --git a/apps/desktop/src/shell-page.test.mjs b/apps/desktop/src/shell-page.test.mjsnew file mode 100644index 0000000..950fde3--- /dev/null+++ b/apps/desktop/src/shell-page.test.mjs@@ -0,0 +1,13 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';++const page = readFileSync(new URL('../shell/index.html', import.meta.url), 'utf8');++test('the chat\'s column and its layer are Studio\'s host panel and take focus, so its keys stay in the chat', () => {+ for (const id of ['of-chat', 'of-chat-layer']) {+ const tag = new RegExp(`<div id="${id}"[^>]*>`).exec(page)?.[0] ?? '';+ assert.match(tag, /\sdata-studio-host-panel[\s>]/, `${id} is the host panel`);+ assert.match(tag, /\stabindex="-1"/, `${id} takes focus when clicked`);+ }+});diff --git a/packages/openfilm/package.json b/packages/openfilm/package.jsonindex 95858c3..f802775 100644--- a/packages/openfilm/package.json+++ b/packages/openfilm/package.json@@ -60,7 +60,7 @@},"scripts": {"dev": "node scripts/dev.mjs",- "test": "node --test --test-concurrency=1 --test-timeout=300000 src/*.test.mjs studio/*.test.mjs studio/server/*.test.mjs studio/server/providers/*.test.mjs studio/ui/src/editor/*.test.ts studio/ui/src/lib/*.test.ts",+ "test": "node --test --test-concurrency=1 --test-timeout=300000 src/*.test.mjs studio/*.test.mjs studio/server/*.test.mjs studio/server/providers/*.test.mjs studio/ui/src/editor/*.test.ts studio/ui/src/lib/*.test.ts studio/ui/src/components/*.test.ts","typecheck": "tsc -p studio/server && tsc -p studio/ui","build:ui": "vite build --config studio/ui/vite.config.ts","prepare": "npm run build:ui",diff --git a/packages/openfilm/studio/server/files.mjs b/packages/openfilm/studio/server/files.mjsindex 26eb45c..86abeb8 100644--- a/packages/openfilm/studio/server/files.mjs+++ b/packages/openfilm/studio/server/files.mjs@@ -11,7 +11,7 @@import { execFile } from 'node:child_process';import { createHash } from 'node:crypto';import { constants, createReadStream, createWriteStream, existsSync, lstatSync, realpathSync, statSync } from 'node:fs';-import { copyFile, cp, lstat, mkdir, readFile, readdir, readlink, rename, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';+import { copyFile, cp, lstat, mkdir, readFile, readdir, readlink, rename, rm, stat, symlink, unlink, utimes, writeFile } from 'node:fs/promises';import { basename, dirname, extname, isAbsolute, join, normalize, relative, sep } from 'node:path';import { Transform } from 'node:stream';import { pipeline } from 'node:stream/promises';@@ -166,7 +166,8 @@ function kindOf(/** @type {string} */ name) {export async function listFiles(root) {/** @type {string[]} */const made = [];- /** @type {{ path: string, kind: string, size: number, mtime: number }[]} */+ /** `added`: when it came into the project (a link: when it was made), for listing the newest last+ * @type {{ path: string, kind: string, size: number, mtime: number, added: number }[]} */const files = [];/** @type {string[]} */const folders = [];@@ -190,8 +191,10 @@ export async function listFiles(root) {const info = readableLink(root, abs) ? await stat(abs).catch(() => null) : null;links[rel] = { to: isAbsolute(to) ? to : join(dir, to), ...(info ? {} : { missing: true }) };if (info?.isDirectory()) { folders.push(rel); if (depth < 8) await walk(abs, depth + 1, true); continue; }- const at = info ?? await lstat(abs).catch(() => null);- if (at) files.push({ path: rel, kind: kindOf(entry.name), size: info ? info.size : 0, mtime: Math.round(at.mtimeMs) });+ const own = await lstat(abs).catch(() => null);+ const at = info ?? own;+ /* `added`: when the link was made, not when what it leads to last changed */+ if (at) files.push({ path: rel, kind: kindOf(entry.name), size: info ? info.size : 0, mtime: Math.round(at.mtimeMs), added: Math.round((own ?? at).mtimeMs) });continue;}if (entry.isDirectory()) {@@ -202,7 +205,7 @@ export async function listFiles(root) {if (!entry.isFile()) continue;const info = await stat(abs).catch(() => null);if (!info) continue;- if (media) files.push({ path: rel, kind: kindOf(entry.name), size: info.size, mtime: Math.round(info.mtimeMs) });+ if (media) files.push({ path: rel, kind: kindOf(entry.name), size: info.size, mtime: Math.round(info.mtimeMs), added: Math.round(info.mtimeMs) });/* the film is not one of its pages */else if (/\.html?$/i.test(entry.name) && rel !== FILM_FILE) pages.push({ path: rel, size: info.size, mtime: Math.round(info.mtimeMs) });}@@ -513,7 +516,12 @@ export async function bringIn(root, into, paths, mode) {const part = join(dir, `.${basename(at)}.${process.pid}.importing`);try {if (info.isDirectory()) await cp(from, part, { recursive: true, mode: constants.COPYFILE_FICLONE, filter: (src) => !basename(src).startsWith('.') });- else await copyFile(from, part, constants.COPYFILE_FICLONE);+ else {+ await copyFile(from, part, constants.COPYFILE_FICLONE);+ /* dated now, as it came in (a copy on Windows keeps the original's date): the pane lists it after the rest */+ const now = new Date();+ await utimes(part, now, now);+ }await rename(part, at);} catch (e) {await rm(part, { recursive: true, force: true });diff --git a/packages/openfilm/studio/server/files.test.mjs b/packages/openfilm/studio/server/files.test.mjsindex 4dc2bb1..7e9efff 100644--- a/packages/openfilm/studio/server/files.test.mjs+++ b/packages/openfilm/studio/server/files.test.mjs@@ -1,6 +1,6 @@import { test, beforeEach } from 'node:test';import assert from 'node:assert/strict';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { Readable } from 'node:stream';@@ -343,3 +343,22 @@ test('files copied in from this computer: a copy each under a free name, the oriawait assert.rejects(bringIn(root, 'scenes', [join(disk, 'a.png')], 'copy'), FileError);await assert.rejects(bringIn(root, 'assets', ['a.png'], 'copy'), FileError);});++test('media is dated when it came into the project: a copy now, a link when it was made', links, async () => {+ const away = mkdtempSync(join(tmpdir(), 'of-away-'));+ for (const name of ['old.mp4', 'linked.mp4']) {+ writeFileSync(join(away, name), name);+ utimesSync(join(away, name), new Date('2020-01-01'), new Date('2020-01-01'));+ }+ put('assets/here.png');+ const before = Date.now() - 2000;+ await bringIn(root, 'assets', [join(away, 'old.mp4')], 'copy');+ await bringIn(root, 'assets', [join(away, 'linked.mp4')], 'link');+ const { files } = await listFiles(root);+ const of = (path) => files.find((f) => f.path === path);+ assert.ok(of('assets/old.mp4').added >= before, 'a copy is dated now, not as the original');+ assert.ok(of('assets/linked.mp4').added >= before, 'a link is dated when it was made');+ /* what a link leads to keeps its own date: its pictures are made again when it changes */+ assert.equal(of('assets/linked.mp4').mtime, new Date('2020-01-01').getTime());+ assert.equal(of('assets/here.png').added, of('assets/here.png').mtime);+});diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.tsindex 4c620b9..478b19c 100644--- a/packages/openfilm/studio/ui/src/api.ts+++ b/packages/openfilm/studio/ui/src/api.ts@@ -22,7 +22,7 @@ export type Track = { clips: Clip[]; locked?: boolean; hidden?: boolean; muted?:export type Film = { stage?: { w: number; h: number }; tracks: Track[] };/** `value`: film.html as read, every clip named (a clip with no id takes its file's name, as the server and preview do). */export type ProjectFilm = { project: Project; folder: string; text: string; rev: string; value: Film | null; doc: Film | null; problems: string[] };-export type MediaFile = { path: string; kind: 'video' | 'image' | 'audio' | 'page' | 'other'; size: number; mtime: number };+export type MediaFile = { path: string; kind: 'video' | 'image' | 'audio' | 'page' | 'other'; size: number; mtime: number; added?: number };/** A project's editor settings (studio/server/project-settings.mjs). */export type ProjectSettings = { fps?: number; trackNames?: { name: string; index: number; clips: string[] }[]; trackHeights?: { height: number; index: number; clips: string[] }[] };export type Listing = { files: MediaFile[]; folders: string[]; pages: { path: string; size: number; mtime: number }[] };diff --git a/packages/openfilm/studio/ui/src/components/BlockWaveform.tsx b/packages/openfilm/studio/ui/src/components/BlockWaveform.tsxindex 7a27c57..1f9c390 100644--- a/packages/openfilm/studio/ui/src/components/BlockWaveform.tsx+++ b/packages/openfilm/studio/ui/src/components/BlockWaveform.tsx@@ -11,6 +11,7 @@*/import * as React from 'react';import { normalizeWavePeaks, waveformColumns } from '@/lib/waveform-columns';+import { mediaFetch } from '@/lib/media-queue';/** A sound's envelope: the whole file's peaks and its length (to turn peak indexes into ms). */interface Wave {@@ -33,7 +34,7 @@ const PENDING = new Map<string, Promise<Wave | null>>();* About half a minute at most; after that the block stays plain until its address changes.*/async function fetchWhenReady(url: string, tries = 30): Promise<Response> {- const res = await fetch(url);+ const res = await mediaFetch(url);if (res.status !== 503 || tries <= 1) return res;const wait = Math.min(Math.max(Number(res.headers.get('retry-after')) || 1, 0.5), 5) * 1000;await new Promise((done) => setTimeout(done, wait));diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsxindex 722b975..45dcc76 100644--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx@@ -19,7 +19,7 @@ import {AlignCenterHorizontal, AlignCenterVertical, AlignEndHorizontal, AlignEndVertical, AlignHorizontalDistributeCenter,AlignStartHorizontal, AlignStartVertical, AlignVerticalDistributeCenter, ArrowRightToLine, AudioLines, Captions,Check, ChevronRight, CircleAlert, Clapperboard, Copy, Film, Gauge, Image as ImageIcon, Link2, Maximize2, MousePointerClick,- Lock, MoveHorizontal, Music, RotateCcw, Scissors, Shapes, Sparkles, Square, Type, Unlink2, Video, Volume2, X,+ Lock, MoveHorizontal, Music, Replace, RotateCcw, Scissors, Shapes, Sparkles, Square, Type, Unlink2, Video, Volume2, X,} from 'lucide-react';import {@@ -46,6 +46,7 @@ import { CANVAS_RATIOS, canvasRatioLabel, shaped } from './FramePicker';import { declared, withDeclarations, type ClipLook } from '@/lib/clip-look';import { PANE_BAR, PANE_BTN, PANE_ICON, PANE_TITLE } from './dock-pane-bar';import { Tooltip } from './Tooltip';+import { ContextMenu, type ContextMenuEntry } from './ContextMenu';import {ICON, MIXED, NumField, Row, RotateGlyph, Section, SectionAction, Segmented, SliderField,useTimeUnit, type FieldApply, type Mixed,@@ -152,6 +153,7 @@ export const FilmInspector = React.memo(function FilmInspector({onSelectClip,onPreviewClip,pageChangesOf,+ replaceEntries,clipLookOf,onPreviewLook,stage,@@ -207,6 +209,8 @@ export const FilmInspector = React.memo(function FilmInspector({onPreviewClip?: (clipLoc: string, patch: Partial<MgTransform> | null) => void;/** A page clip's in-page changes (film.html `overrides`) and which of them its page no longer has. */pageChangesOf?: (clipLoc: string) => PageChanges | null;+ /** What can take a clip's place (the project's files, one from this computer): the clip's Replace button. */+ replaceEntries?: (block: TimelineBlock) => ContextMenuEntry[];/** A clip's own CSS and `class` in film.html and how it looks now (see clip-look): its look sections read them. */clipLookOf?: (clipLoc: string) => { css: string; look: ClipLook | null; cls?: string } | null;/** Shows a clip in CSS not kept yet while a look value is dragged (null: its own again). */@@ -300,6 +304,7 @@ export const FilmInspector = React.memo(function FilmInspector({onEdit={onEditClips}onPreviewClip={onPreviewClip}{...(pageChangesOf ? { pageChangesOf } : {})}+ {...(replaceEntries ? { replaceEntries } : {})}{...(clipLookOf ? { clipLookOf } : {})}{...(onPreviewLook ? { onPreviewLook } : {})}{...(onStartCrop ? { onStartCrop } : {})}@@ -520,7 +525,7 @@ function clipKindLabel(t: T, what: ClipWhat): string {* badge; the rest (kind, time, source file) is one gray line under it.*/function Header({- icon, name, meta, mono, badge,+ icon, name, meta, mono, badge, action,}: {icon: React.ReactNode;name: string;@@ -529,6 +534,8 @@ function Header({mono?: string;/** The track it is on (V1). */badge?: string;+ /** A button at the right (a clip's Replace). */+ action?: React.ReactNode;}) {return (<div className="flex items-center gap-2 px-3 pb-2 pt-2.5">@@ -546,6 +553,7 @@ function Header({{mono ? `${meta} · ${mono}` : meta}</div></div>+ {action}</div>);}@@ -1334,9 +1342,10 @@ function clipsLook(* can only be looked at.*/function ClipPanel({- block, onMain, geometry, stage, badges, onEdit, onPreviewClip, pageChangesOf, clipLookOf, onPreviewLook, onStartCrop, onEditMask, maskAsk, onMaskAsked, fades,+ block, onMain, geometry, stage, badges, onEdit, onPreviewClip, pageChangesOf, replaceEntries, clipLookOf, onPreviewLook, onStartCrop, onEditMask, maskAsk, onMaskAsked, fades,}: {fades?: ReadonlyMap<string, FadeMs>;+ replaceEntries?: (block: TimelineBlock) => ContextMenuEntry[];block: TimelineBlock;/** On the main track, where the magnet acts. */onMain: boolean;@@ -1389,6 +1398,7 @@ function ClipPanel({meta={`${clipKindLabel(t, what)} · ${formatTimecode(block.startMs)} – ${formatTimecode(block.endMs)}`}{...(block.src ? { mono: block.src } : {})}{...(badge ? { badge } : {})}+ {...(editable && block.clipId && replaceEntries ? { action: <ReplaceButton block={block} entries={replaceEntries} t={t} /> } : {})}/>{refusal ? (<RefusalBanner message={refusal} onDismiss={() => setRefusal(null)} t={t} />@@ -1474,6 +1484,32 @@ function ClipPanel({);}+/** A clip's Replace: another file of the project in its place, or one from this computer (use-editor-tools). */+function ReplaceButton({ block, entries, t }: { block: TimelineBlock; entries: (block: TimelineBlock) => ContextMenuEntry[]; t: T }) {+ const ref = React.useRef<HTMLButtonElement>(null);+ const [menu, setMenu] = React.useState<{ x: number; y: number; top: number; items: ContextMenuEntry[] } | null>(null);+ return (+ <>+ <button+ ref={ref}+ type="button"+ aria-haspopup="menu"+ aria-expanded={Boolean(menu)}+ onClick={() => {+ if (menu) { setMenu(null); return; }+ const r = ref.current!.getBoundingClientRect();+ setMenu({ x: r.right, y: r.bottom + 4, top: r.top - 4, items: entries(block) });+ }}+ className="flex h-6 shrink-0 items-center gap-1 rounded-[5px] px-1.5 text-[11px] text-[var(--text-muted)] transition hover:bg-[var(--fill-tsp)] hover:text-[var(--text)]"+ >+ <Replace size={12} />+ {t('editorTools.replaceButton')}+ </button>+ {menu ? <ContextMenu x={menu.x} y={menu.y} flipTo={menu.top} align="end" dense items={menu.items} trigger={ref} onClose={() => setMenu(null)} /> : null}+ </>+ );+}+/*** Start, length, in point and speed, as timecodes (frames at the project's rate, as the player counts them) or seconds;* and the source bar: the whole file, the part the clip plays drawn on it — dragged, the clip plays another part ofdiff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsxindex edb5a50..a4e3c14 100644--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx@@ -46,6 +46,7 @@ import { MgOutline } from '@/components/MgOutline';import { FRAME_BLUE, GestureHint, StageTransformFrame, type FrameGeometry } from '@/components/StageTransformFrame';import { StageMaskOverlay } from '@/components/StageMaskOverlay';import { linkedOutlines } from '@/components/film-stage-hit';+import { inHostPanel } from '@/components/typing-target';import type { StageArrange, StageArrangeResult, StageMenuContext } from '@/components/stage-menu';import type { PreviewHandle, StageEvent } from '@/editor/Preview';import { useT } from '@/i18n';@@ -1053,7 +1054,7 @@ function FilmStageSelectImpl({if (!picked) { keyHandler.current = null; return undefined; }const onKey = (e: KeyboardEvent) => {/* keys pressed in an app's own panel are the app's (typing-target.ts) */- if ((e.target as Element | null)?.closest?.('[data-studio-host-panel]')) return;+ if (inHostPanel(e.target)) return;const typingNow = () => {const focus = document.activeElement as HTMLElement | null;return Boolean(focus && (/^(INPUT|TEXTAREA|SELECT)$/.test(focus.tagName) || focus.isContentEditable));@@ -1152,12 +1153,14 @@ function FilmStageSelectImpl({};keyHandler.current = onKey;/* a press elsewhere lets go: selecting is "I mean this one", and the hand moving away ends it. Not the stage, its- menus, the inspector (and its floating panels), the dividers or list boxes. On the timeline only layers let go:- a whole clip in hand is the timeline's own selection, which it keeps or clears itself. */+ menus, the inspector (and its floating panels), the dividers or list boxes, nor an app's own panel (its chat+ points at what is selected). On the timeline only layers let go: a whole clip in hand is the timeline's own+ selection, which it keeps or clears itself. */const onDown = (e: PointerEvent) => {const el = e.target as HTMLElement | null;if (- el?.closest('[data-film-select]')+ inHostPanel(el)+ || el?.closest('[data-film-select]')|| el?.closest('[data-selection-toolbar]')|| el?.closest('[role="menu"]')|| el?.closest('[data-film-inspector]')@@ -1598,7 +1601,7 @@ function FilmStageSelectImpl({const onKey = (e: KeyboardEvent) => {if (!e.key.startsWith('Arrow') || !arrowsMoveRef.current || e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;const el = e.target as HTMLElement | null;- if (el?.closest('input, textarea, select, [contenteditable="true"], [data-timeline]')) return;+ if (inHostPanel(el) || el?.closest('input, textarea, select, [contenteditable="true"], [data-timeline]')) return;nudgeGroupRef.current(e);};window.addEventListener('keydown', onKey, true);@@ -1964,7 +1967,10 @@ function FilmStageSelectImpl({const d = draftRef.current = { ...draftRef.current, x2: x, y2: y };setDraft(d);const area = { x: Math.min(d.x1, d.x2) / vs, y: Math.min(d.y1, d.y2) / vs, w: Math.abs(d.x2 - d.x1) / vs, h: Math.abs(d.y2 - d.y1) / vs };- marqueeQueue.push(area.w >= MARQUEE_MIN_PX && area.h >= MARQUEE_MIN_PX ? area : null);+ const open = area.w >= MARQUEE_MIN_PX && area.h >= MARQUEE_MIN_PX;+ /* a box pulled open from the dark around the picture: the film stops now (see pressDown) */+ if (open && pauseWhenOpen.current) { pauseWhenOpen.current = false; onPause?.(); }+ marqueeQueue.push(open ? area : null);return;}/* with a clip in hand too: what is in it and around it is still found (its own outline is its frame) */@@ -2206,6 +2212,7 @@ function FilmStageSelectImpl({}const start = draftRef.current;if (!start) return;+ pauseWhenOpen.current = false;e.stopPropagation();const p = local(e);const box = { left: Math.min(start.x1, p.x), top: Math.min(start.y1, p.y), width: Math.abs(p.x - start.x1), height: Math.abs(p.y - start.y1) };@@ -2423,18 +2430,24 @@ function FilmStageSelectImpl({/*** A press: on the picture, or on the dark around it (a marquee starts there too, as on Figma's canvas, so what sits* at an edge can be boxed whole). The moves and the release then come to the overlay, which holds the pointer.+ * `outside`: in the dark, where nothing can be clicked, only a box drawn: the film plays on until the box is pulled+ * open (a click there only lets the selection go).*/- const pressDown = (e: PressEvent) => {+ const pauseWhenOpen = React.useRef(false);+ const pressDown = (e: PressEvent, outside = false) => {if (e.button !== 0) return;e.stopPropagation();/* pause at the press, not the release: a clock still running would move the selection off under the hand */- onPause?.();+ pauseWhenOpen.current = outside;+ if (!outside) onPause?.();const p = local(e);/* the first press of a double-click is kept: the second one lands where the picture has moved to */const prev = lastPressRef.current;if (!prev || e.timeStamp - prev.at > DOUBLE_PRESS_MS) lastPressRef.current = { x: p.x / viewScaleNow(), y: p.y / viewScaleNow(), at: e.timeStamp };/* ⌘ held: a box to point at in the chat, whatever is under the press (nothing is selected or moved) */if (onRegion && regionKeyHeld(e)) {+ /* a box for the chat is meant at once, wherever it starts */+ if (outside) { pauseWhenOpen.current = false; onPause?.(); }host.current?.setPointerCapture(e.pointerId);regionDraftRef.current = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };setRegionDraft(regionDraftRef.current);@@ -2658,7 +2671,7 @@ function FilmStageSelectImpl({/* only the dark around the picture: what lies over the picture (the subtitles) has its own presses */const r = filmRect();if (r && e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) return;- pressDownRef.current(e);+ pressDownRef.current(e, true);};area.addEventListener('pointerdown', onDown);return () => area.removeEventListener('pointerdown', onDown);diff --git a/packages/openfilm/studio/ui/src/components/MediaPool.tsx b/packages/openfilm/studio/ui/src/components/MediaPool.tsxindex d219aa3..91ae086 100644--- a/packages/openfilm/studio/ui/src/components/MediaPool.tsx+++ b/packages/openfilm/studio/ui/src/components/MediaPool.tsx@@ -63,7 +63,8 @@ import {} from '@/lib/workspace-resources';import { ConfirmDialog } from './ConfirmDialog';import { ContextMenu, type ContextMenuEntry } from './ContextMenu';-import { KIND_ICON, MediaPreview } from './MediaPreview';+import { KIND_ICON, MediaPreview, useNearViewport } from './MediaPreview';+import { useMediaImage } from '@/lib/media-queue';import { Tooltip } from './Tooltip';import { retryImage } from '@/lib/retry-image';import { boxBetween, boxHits, boxPick, moveTargets, pickItem, type Box } from '@/lib/media-selection';@@ -88,16 +89,20 @@ const filterOf = (f: WorkspaceResource): Filter => (f.kind === 'mg' ? 'page' : f/** `layout`: tiles in a grid, or rows of a list (name, length, kind). */interface ViewState { sort: SortKey; filter: Filter; layout: 'grid' | 'list' }-const viewKey = (projectId: string) => `openfilm.media.${projectId}`;+/* v2: the order became "as added" by default. A view kept before it (saved whether chosen or not) keeps its filter and+ layout, not its order */+const viewKey = (projectId: string) => `openfilm.media.v2.${projectId}`;+const oldViewKey = (projectId: string) => `openfilm.media.${projectId}`;function loadView(projectId: string): ViewState {try {- const raw = JSON.parse(window.localStorage.getItem(viewKey(projectId)) ?? 'null') as Partial<ViewState> | null;+ const kept = window.localStorage.getItem(viewKey(projectId));+ const raw = JSON.parse(kept ?? window.localStorage.getItem(oldViewKey(projectId)) ?? 'null') as Partial<ViewState> | null;return {- sort: SORTS.includes(raw?.sort as SortKey) ? raw!.sort as SortKey : 'name',+ sort: kept && SORTS.includes(raw?.sort as SortKey) ? raw!.sort as SortKey : 'time',filter: FILTERS.includes(raw?.filter as Filter) ? raw!.filter as Filter : 'all',layout: raw?.layout === 'list' ? 'list' : 'grid',};- } catch { return { sort: 'name', filter: 'all', layout: 'grid' }; }+ } catch { return { sort: 'time', filter: 'all', layout: 'grid' }; }}type Item = { type: 'folder'; rel: string; name: string; count: number; covers: WorkspaceResource[] } | { type: 'file'; file: WorkspaceResource };@@ -258,7 +263,8 @@ export function MediaPool({if (!allFiles) return null;const q = query.trim();const order = (a: WorkspaceResource, b: WorkspaceResource) => {- if (view.sort === 'time') return b.mtimeMs - a.mtimeMs;+ /* 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 === '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 });@@ -372,11 +378,22 @@ export function MediaPool({return all.filter((u) => !gone(u));});}, []);- /* a card gives way to the file once the listing has it (or a while after it landed, if it never shows here) */+ const uploadsRef = React.useRef(uploads);+ uploadsRef.current = uploads;+ /* a card gives way to the file once the listing has it (or a while after it landed, if it never shows here); what+ came in is selected and scrolled to, so it is found among many */React.useEffect(() => {if (!media) return;const have = new Set([...media.files.map((f) => f.path), ...media.dirs.map((d) => `${media.dir}/${d}`)]);+ const arrived = uploadsRef.current.flatMap((u) => (u.landed && have.has(u.landed) ? [u.landed] : []));dropUploads((u) => Boolean(u.landed && have.has(u.landed)));+ if (!arrived.length) return undefined;+ setPicked(arrived);+ anchor.current = arrived[arrived.length - 1]!;+ const frame = requestAnimationFrame(() => {+ gridRef.current?.querySelector(`[data-media-key="${CSS.escape(arrived[arrived.length - 1]!)}"]`)?.scrollIntoView({ block: 'nearest' });+ });+ return () => cancelAnimationFrame(frame);}, [media, dropUploads]);const landedCount = uploads.filter((u) => u.landed).length;React.useEffect(() => {@@ -384,8 +401,6 @@ export function MediaPool({const timer = window.setTimeout(() => dropUploads((u) => Boolean(u.landed)), 5000);return () => window.clearTimeout(timer);}, [landedCount, dropUploads]);- const uploadsRef = React.useRef(uploads);- uploadsRef.current = uploads;React.useEffect(() => () => { for (const u of uploadsRef.current) if (u.preview) URL.revokeObjectURL(u.preview); }, []);/** Files on their way into a folder or one inside it: their progress together, for its cover. */const progressInto = (rel: string) => {@@ -1335,16 +1350,19 @@ function PagePoster({ file, sources }: { file: WorkspaceResource; sources: Mediaconst [loaded, setLoaded] = React.useState<string | null>(null);const [failed, setFailed] = React.useState<string | null>(null);const own = sources.pagePoster?.(file);- const src = own && failed !== own ? own : null;+ /* drawn in the headless browser: asked for in turn with Studio's other media (lib/media-queue), once near the screen */+ const [nearRef, near] = useNearViewport<HTMLSpanElement>();+ const turn = useMediaImage(own && failed !== own ? own : null, near);+ const src = turn && failed !== turn ? turn : null;const shown = src != null && loaded != null;return (- <>+ <span ref={nearRef} className="absolute inset-0">{shown ? null : <span className="absolute inset-0 flex items-center justify-center"><Clapperboard size={20} className="text-[var(--text-muted)]" /></span>}{src ? (- <img src={src} alt="" loading="lazy" onLoad={() => setLoaded(src)}+ <img src={src} alt="" onLoad={() => setLoaded(src)}onError={(e) => { setLoaded(null); retryImage(e.currentTarget, () => setFailed(src)); }}className={`absolute inset-0 h-full w-full object-cover ${shown ? '' : 'invisible'}`} />) : null}- </>+ </span>);}diff --git a/packages/openfilm/studio/ui/src/components/MediaPreview.tsx b/packages/openfilm/studio/ui/src/components/MediaPreview.tsxindex d0d49f9..a334f17 100644--- a/packages/openfilm/studio/ui/src/components/MediaPreview.tsx+++ b/packages/openfilm/studio/ui/src/components/MediaPreview.tsx@@ -13,6 +13,7 @@ import {type WorkspaceResourceKind,} from '@/lib/workspace-resources';import { normalizeWavePeaks } from '@/lib/waveform-columns';+import { useMediaImage } from '@/lib/media-queue';/** A file's icon by kind, where there is no picture of it. */export const KIND_ICON: Record<WorkspaceResourceKind, LucideIcon> = {@@ -30,7 +31,7 @@ const extOf = (name: string) => /\.([^./\s]{1,8})$/.exec(name)?.[1] ?? '';* Has this element come near the viewport yet. A tile asks for its poster only then: a pane of eighty files would* otherwise send eighty requests at once, and the visible row would come in last. Latched: once near, it stays.*/-function useNearViewport<T extends Element>(margin = 200): [React.RefCallback<T>, boolean] {+export function useNearViewport<T extends Element>(margin = 200): [React.RefCallback<T>, boolean] {const [near, setNear] = React.useState(false);const observer = React.useRef<IntersectionObserver | null>(null);@@ -68,27 +69,29 @@ export function MediaPreview({const [failed, setFailed] = React.useState(false);const [boxRef, near] = useNearViewport<HTMLSpanElement>();React.useEffect(() => { setBroken(false); setFailed(false); }, [file.path, file.mtimeMs]);+ const thumbable = !broken && (file.kind === 'image' || file.kind === 'video');+ const poster = thumbable ? sources.poster?.(file) : undefined;+ const picture = file.kind === 'image' ? (poster && !failed ? poster : sources.file(file)) : file.kind === 'video' ? poster : undefined;+ /* asked for in turn with Studio's other media (lib/media-queue), once the tile is near the screen */+ const shown = useMediaImage(thumbable ? picture : null, near);if (file.kind === 'audio') return <AudioPreview file={file} sources={sources} />;const Icon = KIND_ICON[file.kind] ?? FileIcon;- const thumbable = !broken && (file.kind === 'image' || file.kind === 'video');- const poster = thumbable ? sources.poster?.(file) : undefined;const IMG = 'absolute inset-0 h-full w-full min-w-0 object-contain';return (<span ref={boxRef} className="absolute inset-0 flex items-center justify-center">- {thumbable && file.kind === 'image' ? (+ {thumbable && file.kind === 'image' && shown ? (/* the small picture when there is one; the original when not, or when it fails; broken only when both do */<img- src={poster && !failed ? poster : sources.file(file)}+ src={shown}alt=""- loading="lazy"onError={() => (poster && !failed ? setFailed(true) : setBroken(true))}className={IMG}/>- ) : thumbable && near && poster ? (- <img src={poster} alt="" onError={() => setBroken(true)} className={IMG} />+ ) : thumbable && file.kind === 'video' && shown ? (+ <img src={shown} alt="" onError={() => setBroken(true)} className={IMG} />) : file.kind === 'other' ? (/* a file Studio does not play (a document, a model, data): its icon and its ending, which say what it is */<span className="flex flex-col items-center gap-1">diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsxindex 05b1124..cde233d 100644--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx@@ -16,6 +16,7 @@ import { Player } from '@/editor/player';import { Preview, type FilmInfo, type PreviewHandle } from '@/editor/Preview';import { filmShape, type MediaFacts } from '@/lib/film-shape';import { changesPicture } from '@/lib/picture-files';+import 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 { footageFps, setTimecodeFps, snapToFrame, stepFrames } from '@/lib/timecode';@@ -25,7 +26,7 @@ import { cutPoints, namedTrack, nextCut, trackNamesOf } from '@/lib/timeline-navimport { anyLocked, lockedEdits } from '@/lib/track-lock';import { placeMedia, type SourceRange } from '@/lib/media-place';import { apartOnTracks, type ClipEdit } from '@/lib/film-clip-edits';-import { mediaFetch } from '@/lib/media-queue';+import { mediaFetch, useMediaImages } from '@/lib/media-queue';import { clipboardItemsOf, clipboardNow, pasteEdit, type TimelineClipboardItem } from '@/lib/timeline-clipboard';import { editModelOf, freshLink, linkedIds, magnetOn, mainTrackOf, planMove, planRippleTrim, planRoom, planSpeed, soundTrackFor, type EditMode } from '@/lib/timeline-edit';import { followOf, readTimelinePrefs } from '@/lib/timeline-prefs';@@ -656,6 +657,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {setInspectorContent('subtitles');setInspectorOpen(!(inspectorOpen && inspectorContent === 'subtitles'));}, [inspectorOpen, inspectorContent]);+ /* a subtitle picked (on the picture, or its line on the timeline) is what is selected now, as a layer picked is: the+ clips let go, and the inspector shows the subtitles' look */+ const showSubtitleLook = React.useCallback(() => {+ setSelectedKeys([]);+ setStageElement(null);+ setInspectorContent('subtitles');+ setInspectorOpen(true);+ }, []);const pickMedia = React.useCallback((file: WorkspaceResource | null) => {setPickedMedia(file);if (file) { setInspectorContent(file); setInspectorOpen(true); }@@ -985,7 +994,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {const subtitleRow = React.useMemo<SubtitleRowSpec>(() => ({cues: subs.captions?.cues ?? [], edits: subtitleEdits,speakerAt: (ms) => speakerAt(tracksRef.current, subs.captions?.cues ?? [], ms),- }), [subs.captions, subtitleEdits]);+ onPick: showSubtitleLook,+ }), [subs.captions, subtitleEdits, showSubtitleLook]);const relinkInputRef = React.useRef<HTMLInputElement>(null);const relinkTarget = React.useRef<TimelineBlock | null>(null);const relinkBlock = React.useCallback(async (block: TimelineBlock, path: string | null) => {@@ -999,10 +1009,13 @@ export function ProjectView({ projectId, onProject, onLeave }: {const doomed = blocksRef.current.filter((b) => !!b.src && paths.some((p) => srcHitsAsset(b.src!, p)));return doomed.length ? removeBlocks(doomed) : Promise.resolve(null);}, [removeBlocks]);- /* markers, solo, track heights, loudness, freeze frame, replace (use-editor-tools) */+ /* markers, solo, track heights, loudness, freeze frame, replace (use-editor-tools); a replacement from this computer+ is picked and brought in as the media pane's Import does (pickReplacement, below) */+ const pickReplacementRef = React.useRef<(family: ReplaceFamily) => Promise<string | null>>(async () => null);+ const pickReplacement = React.useCallback((family: ReplaceFamily) => pickReplacementRef.current(family), []);const tools = useEditorTools({projectId, tracks: timelineTracks, film: film.film, settings, patchSettings, player, timeRef, seek, edit: editOps, record: film.record,- editModel, selectedClipIds: selectedKeys, listing, toast,+ editModel, selectedClipIds: selectedKeys, listing, toast, pickFile: pickReplacement,});/* how many of the person's edits an outside write undid: edits inside pages it left out, and clip edits it changed */@@ -1622,6 +1635,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {return out;// eslint-disable-next-line react-hooks/exhaustive-deps}, [timelineTracks, projectId, mtimeOf]);+ /* each drawn once it has had its turn among Studio's media requests (lib/media-queue) */+ const shownPosters = useMediaImages(posters);const waveUrl = React.useCallback((src: string) => `/api/projects/${encodeURIComponent(projectId)}/media?what=wave&path=${encodeURIComponent(src)}&v=${mtimeOf.get(src) ?? 0}`, [projectId, mtimeOf]);/* clips whose files are gone, and where the same name may be now */const mediaTrouble = React.useMemo(() => {@@ -1717,6 +1732,26 @@ export function ProjectView({ projectId, onProject, onLeave }: {}return landed;}, [projectApi, t, toast, onBring]);+ pickReplacementRef.current = async (family) => {+ /* the system's dialog where there is one (the app, or Studio on this computer), else the browser's */+ const picked = await onPick(t('editorTools.replacePick'), false);+ if (picked !== 'no-dialog') {+ if (!picked.length) return null;+ const [at] = await onBring([picked[0]!], 'assets', 'copy');+ return at ?? null;+ }+ const file = await new Promise<File | null>((done) => {+ const input = document.createElement('input');+ input.type = 'file';+ input.accept = family === 'sound' ? 'audio/*,video/*' : 'video/*,image/*,.html,.htm';+ input.addEventListener('change', () => done(input.files?.[0] ?? null));+ input.addEventListener('cancel', () => done(null));+ input.click();+ });+ if (!file) return null;+ const [at] = await onImport([file], 'assets', () => {});+ return at ?? null;+ };/* ── files dropped from the computer: imported into assets/ (the media pane's own import), then put on the film ── *//** A file just imported, as the media pane would hand it to a drop: its kind from its name, its length and size probed. */@@ -2496,6 +2531,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {timeMs={liveMs}style={filmSubtitleStyleFor(subs.style, frameBox)}onMove={fullscreen ? undefined : subs.move}+ onPick={fullscreen ? undefined : showSubtitleLook}/>)}</LiveTime></div>@@ -2576,6 +2612,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {onSelectClip={selectStageClip}onPreviewClip={previewClip}pageChangesOf={pageChangesOf}+ replaceEntries={tools.replaceEntries}clipLookOf={clipLookOf}onPreviewLook={previewLook}onStartCrop={startStageCrop}@@ -2628,7 +2665,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {onDuplicate={duplicateBlocks}onPlayRange={playRange}thumbs={shownThumbs}- posters={posters}+ posters={shownPosters}mediaTrouble={mediaTrouble}relinkCandidates={relinkCandidates}onRelink={(block, path) => void relinkBlock(block, path)}diff --git a/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx b/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsxindex c12be18..ea81dfb 100644--- a/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx+++ b/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx@@ -18,6 +18,7 @@ import * as React from 'react';import { createPortal } from 'react-dom';import { Tooltip } from '@/components/Tooltip';+import { inHostPanel } from '@/components/typing-target';import { placeToolbar, type ScreenBox, type ToolbarPlacement } from '@/lib/selection-toolbar';export interface SelectionTool {@@ -67,7 +68,8 @@ export function SelectionToolbar({React.useEffect(() => {if (!shown) return undefined;- const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setDismissed(selection); };+ /* an Esc pressed in an app's own panel is the app's (its chat's: stop the agent) */+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !inHostPanel(e.target)) setDismissed(selection); };const again = () => setTick((n) => n + 1);window.addEventListener('keydown', onKey);window.addEventListener('resize', again);diff --git a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx b/packages/openfilm/studio/ui/src/components/SourcePreview.tsxindex b044324..282155c 100644--- a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx+++ b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx@@ -190,8 +190,7 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewPropReact.useEffect(() => {const onKey = (e: KeyboardEvent) => {- const tag = (e.target as HTMLElement | null)?.tagName;- if (tag === 'INPUT' || tag === 'TEXTAREA') return;+ if (isTypingTarget(e.target)) return;if (e.key === 'Escape') { e.preventDefault(); onClose(); }/* space plays the source while it is up, not the film behind it */if (e.key === ' ' && timed) { e.preventDefault(); e.stopPropagation(); toggle(); }@@ -366,8 +365,7 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {React.useEffect(() => {const onKey = (e: KeyboardEvent) => {- const tag = (e.target as HTMLElement | null)?.tagName;- if (tag === 'INPUT' || tag === 'TEXTAREA') return;+ if (isTypingTarget(e.target)) return;if (e.key === 'Escape') { e.preventDefault(); onClose(); }if (e.key === ' ') { e.preventDefault(); e.stopPropagation(); toggle(); }};diff --git a/packages/openfilm/studio/ui/src/components/SubtitleOverlay.tsx b/packages/openfilm/studio/ui/src/components/SubtitleOverlay.tsxindex 9df3e41..25b3e6e 100644--- a/packages/openfilm/studio/ui/src/components/SubtitleOverlay.tsx+++ b/packages/openfilm/studio/ui/src/components/SubtitleOverlay.tsx@@ -29,7 +29,7 @@ import {} from '@/lib/subtitles';export function SubtitleOverlay({- cues, timeMs, style, onMove,+ cues, timeMs, style, onMove, onPick,}: {/** The lines as shown (see useFilmSubtitles: the picked language already applied). */cues: readonly SubtitleCue[];@@ -38,6 +38,8 @@ export function SubtitleOverlay({style: SubtitleStyle;/** Where it was dragged to (fractions of the frame). Without it the subtitle cannot be dragged (read only). */onMove?: (pos: { x: number; y: number }) => void;+ /** The subtitle pressed: its look is shown (the inspector), as a layer pressed shows its own. */+ onPick?: () => void;}): React.ReactElement | null {const cue = React.useMemo(() => (style.on ? cueAt(cues, timeMs) : null), [cues, timeMs, style.on]);const box = React.useRef<HTMLDivElement | null>(null);@@ -54,6 +56,7 @@ export function SubtitleOverlay({if (!frame) return;e.preventDefault();e.stopPropagation();+ onPick?.();setDragging(true);const rect = frame.getBoundingClientRect();/* how far from the anchor it was grabbed, or it would jump under the pointer. The anchor is `pos` itself (the line@@ -92,7 +95,7 @@ export function SubtitleOverlay({};window.addEventListener('pointermove', move);window.addEventListener('pointerup', up);- }, [onMove, style.pos.x, style.pos.y]);+ }, [onMove, onPick, style.pos.x, style.pos.y]);if (!cue) return null;/* position, size, color, stroke and box all come from the shared function; this layer adds only what editing has:diff --git a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsxindex 7c69e2b..7cee1e4 100644--- a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx+++ b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx@@ -45,6 +45,8 @@ export interface SubtitleRowSpec {edits: SubtitleEdits;/** The clip a cue added at `ms` would be said by, or null: nothing heard there. */speakerAt: (ms: number) => { clipId: string; src: string; endMs: number } | null;+ /** A cue pressed: the subtitles' look is shown (the inspector). */+ onPick?: () => void;}/* ── shown or not: kept on this machine ── */@@ -261,6 +263,7 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {const key = cueKey(cue);setSelected(key);targeted.current = true;+ spec.onPick?.();const fromX = e.clientX;const grabMs = msAt(e.clientX) - cue.startMs;const others = cuesRef.current.flatMap((c, j) => (j === i ? [] : [{ ms: c.startMs, kind: 'edge' as const }, { ms: cueEnd(c), kind: 'edge' as const }]));diff --git a/packages/openfilm/studio/ui/src/components/typing-target.test.ts b/packages/openfilm/studio/ui/src/components/typing-target.test.tsnew file mode 100644index 0000000..d48f9d3--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/typing-target.test.ts@@ -0,0 +1,43 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { inHostPanel, isTypingTarget } from './typing-target.ts';++/** An element as the checks read it: its tag, what `closest` finds above it, whether it is editable. */+function element({ tag = 'DIV', type, above = [], editable = false }: { tag?: string; type?: string; above?: string[]; editable?: boolean } = {}) {+ const el = {+ nodeType: 1,+ tagName: tag,+ type,+ isContentEditable: editable,+ closest(selector: string) {+ const wanted = selector.split(',').map((s) => s.trim());+ const own = [tag.toLowerCase(), ...above];+ return wanted.some((s) => own.includes(s)) ? el : null;+ },+ };+ return el as unknown as EventTarget;+}++test('anything in an app\'s own panel is the app\'s: not a field, not editable, still not Studio\'s keys', () => {+ const panel = ['[data-studio-host-panel]'];+ assert.equal(inHostPanel(element({ above: panel })), true);+ assert.equal(isTypingTarget(element({ above: panel })), true);+ assert.equal(isTypingTarget(element({ tag: 'BUTTON', above: panel })), true);+ /* a text node inside it, as a key pressed with nothing focused but the panel reports */+ assert.equal(inHostPanel({ nodeType: 3, parentElement: element({ above: panel }) } as unknown as EventTarget), true);+});++test('Studio\'s own page is not the panel', () => {+ assert.equal(inHostPanel(element()), false);+ assert.equal(inHostPanel(null), false);+ assert.equal(isTypingTarget(element()), false);+ assert.equal(isTypingTarget(element({ tag: 'BODY' })), false);+});++test('a text field or editable text types; a slider or checkbox does not', () => {+ assert.equal(isTypingTarget(element({ tag: 'INPUT', type: 'text' })), true);+ assert.equal(isTypingTarget(element({ tag: 'TEXTAREA' })), true);+ assert.equal(isTypingTarget(element({ editable: true })), true);+ assert.equal(isTypingTarget(element({ tag: 'INPUT', type: 'range' })), false);+ assert.equal(isTypingTarget(element({ tag: 'INPUT', type: 'checkbox' })), false);+});diff --git a/packages/openfilm/studio/ui/src/components/typing-target.ts b/packages/openfilm/studio/ui/src/components/typing-target.tsindex 538ab9a..2141048 100644--- a/packages/openfilm/studio/ui/src/components/typing-target.ts+++ b/packages/openfilm/studio/ui/src/components/typing-target.ts@@ -12,15 +12,9 @@* constructors, so a cross-document instanceof is always false.*/export function isTypingTarget(target: EventTarget | null): boolean {- if (!target || !('nodeType' in target)) return false;- const node = target as Node;- const el = node.nodeType === 1- ? node as HTMLElement- : node.nodeType === 3- ? node.parentElement- : null;+ const el = elementOf(target);if (!el) return false;- if (typeof el.closest === 'function' && el.closest('[data-studio-host-panel]')) return true;+ if (inHostPanel(el)) return true;const field = typeof el.closest === 'function' ? el.closest('input, textarea, select') : null;if (field) {/* A focused slider, color swatch or checkbox is not typing: after dragging a volume or@@ -33,4 +27,19 @@ export function isTypingTarget(target: EventTarget | null): boolean {return Boolean(el.isContentEditable);}+/**+ * Whether an event happened in an app's own panel inside Studio's page (lib/host.ts `panel`): its keys and presses are+ * the app's, and leave Studio as it was (what is selected stays selected, nothing plays).+ */+export function inHostPanel(target: EventTarget | null): boolean {+ const el = elementOf(target);+ return Boolean(el && typeof el.closest === 'function' && el.closest('[data-studio-host-panel]'));+}++function elementOf(target: EventTarget | null): HTMLElement | null {+ if (!target || !('nodeType' in target)) return null;+ const node = target as Node;+ return node.nodeType === 1 ? node as HTMLElement : node.nodeType === 3 ? node.parentElement : null;+}+const NON_TEXT_INPUTS = new Set(['range', 'color', 'checkbox', 'radio', 'button', 'submit', 'reset', 'file', 'image']);diff --git a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsxindex c5dce26..412cabb 100644--- a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx+++ b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx@@ -5,11 +5,11 @@* here; the edits go through the page's own edit, one write and one undo step each.*/import * as React from 'react';-import { AudioLines, Flag, Replace, Snowflake } from 'lucide-react';+import { AudioLines, Flag, HardDriveUpload, Replace, Snowflake } from 'lucide-react';import { api, type Clip, type Film, type Op, type ProjectSettings } from '@/api';import { useT } from '@/i18n';-import { canReplace, replaceClip, type ReplaceFile } from '@/lib/clip-replace';+import { canReplace, familyOfClip, replaceClip, type ReplaceFamily, type ReplaceFile } from '@/lib/clip-replace';import { freezeSourceMs, planFreeze } from '@/lib/freeze-frame';import { LOUDNESS_TARGETS, measuredSpan, normalizeVolume } from '@/lib/loudness';import {@@ -30,6 +30,10 @@ import { ClipMarkers, MarkersButton, RulerMarkers, type MarkerActions } from './type Toast = { show: (text: string) => void; showError: (text: string) => void };+/** A file brought in to replace a clip: how long its length is waited for, and how long the file itself. */+const REPLACE_PROBE_MS = 8000;+const REPLACE_GIVE_UP_MS = 30_000;+/** The timeline's own heights, by kind of track (Timeline's TRACK_H). */const OWN_H = TRACK_SIZES.medium;@@ -39,7 +43,7 @@ const sounding = (b: TimelineBlock) => Boolean(b.clipId && b.loc && b.src) && () && b.volume !== 0;export function useEditorTools({- projectId, tracks, film, settings, patchSettings, player, timeRef, seek, edit, record, editModel, selectedClipIds, listing, toast,+ projectId, tracks, film, settings, patchSettings, player, timeRef, seek, edit, record, editModel, selectedClipIds, listing, toast, pickFile,}: {projectId: string;tracks: readonly TimelineTrack[];@@ -58,6 +62,11 @@ export function useEditorTools({/** the project's media and pages, with their lengths as probed */listing: MediaListing | null;toast: Toast;+ /**+ * A file from this computer, to replace a clip with: the person picks it, it is brought into the project, and its+ * path there comes back (null: cancelled). Missing: the replace menu has only the project's files.+ */+ pickFile?: (family: ReplaceFamily) => Promise<string | null>;}) {const t = useT();/* what can take a clip's place: the media and the pages */@@ -271,6 +280,54 @@ export function useEditorTools({}, [edit, toast, t]);const onReplaceDrop = React.useCallback((block: TimelineBlock, file: ReplaceFile) => { void replace(block, file); }, [replace]);+ /* a file from this computer: brought in first, then put in the clip's place once the listing has it with its length+ (probed after it lands); a file whose length never comes is used as it is after a while */+ const pendingReplace = React.useRef<{ block: TimelineBlock; path: string; since: number } | null>(null);+ const [replaceWait, setReplaceWait] = React.useState(0);+ const tryPendingReplace = React.useCallback(() => {+ const wait = pendingReplace.current;+ if (!wait) return;+ const file = media.find((f) => f.path === wait.path);+ const late = Date.now() - wait.since > REPLACE_PROBE_MS;+ if (!file) {+ if (Date.now() - wait.since > REPLACE_GIVE_UP_MS) { pendingReplace.current = null; toast.showError(t('assets.uploadFailed')); }+ return;+ }+ const timed = file.kind === 'video' || file.kind === 'audio';+ if (timed && !(file.durationMs && file.durationMs > 0) && !late) return;+ pendingReplace.current = null;+ void replace(wait.block, file);+ }, [media, replace, toast, t]);+ React.useEffect(() => { tryPendingReplace(); }, [tryPendingReplace, replaceWait]);+ React.useEffect(() => {+ if (!replaceWait) return undefined;+ const timer = window.setInterval(() => { if (pendingReplace.current) tryPendingReplace(); else window.clearInterval(timer); }, 500);+ return () => window.clearInterval(timer);+ }, [replaceWait, tryPendingReplace]);+ const replaceFromComputer = React.useCallback(async (block: TimelineBlock) => {+ const clip: Clip | undefined = filmRef.current?.tracks.flatMap((tr) => tr.clips).find((c) => c.id === block.clipId);+ if (!clip || !pickFile) return;+ let path: string | null;+ try { path = await pickFile(familyOfClip(clip)); } catch (e) { toast.showError(e instanceof Error && e.message ? e.message : t('assets.uploadFailed')); return; }+ if (!path) return;+ pendingReplace.current = { block, path, since: Date.now() };+ setReplaceWait((n) => n + 1);+ }, [pickFile, toast, t]);++ /** What can take a clip's place: the project's files that fit, then one from this computer. */+ const replaceEntries = React.useCallback((block: TimelineBlock): ContextMenuEntry[] => {+ const clip = block.clipId ? filmRef.current?.tracks.flatMap((tr) => tr.clips).find((c) => c.id === block.clipId) : undefined;+ if (!clip) return [];+ const fits = media.filter((f) => canReplace(clip, f));+ return [+ ...fits.slice(0, 20).map((f) => ({ id: `replace:${f.path}`, label: f.name, onSelect: () => { void replace(block, f); } })),+ ...(pickFile ? [+ ...(fits.length ? [{ id: 'replace-sep', separator: true as const }] : []),+ { id: 'replace-computer', label: t('editorTools.replaceFromComputer'), icon: <HardDriveUpload size={14} />, onSelect: () => { void replaceFromComputer(block); } },+ ] : []),+ ];+ }, [media, replace, replaceFromComputer, pickFile, t]);+/** What the tools add to a clip's menu. */const menuExtra = React.useCallback((blocks: readonly TimelineBlock[]): ContextMenuEntry[] => {const out: ContextMenuEntry[] = [];@@ -294,21 +351,20 @@ export function useEditorTools({out.push({ id: 'freeze', label: t('editorTools.freeze'), icon: <Snowflake size={14} />, disabled: !inside, hint: t('editorTools.freezeOutside'), onSelect: () => { void freeze(one); } });}if (one?.clipId) {- const clip = filmRef.current?.tracks.flatMap((tr) => tr.clips).find((c) => c.id === one.clipId);- const fits = clip ? media.filter((f) => canReplace(clip, f)) : [];+ const choices = replaceEntries(one);out.push({id: 'replace',label: t('editorTools.replace'),icon: <Replace size={14} />,- disabled: !fits.length,+ disabled: !choices.length,hint: t('editorTools.replaceNone'),- submenu: fits.slice(0, 20).map((f) => ({ id: `replace:${f.path}`, label: f.name, onSelect: () => { void replace(one, f); } })),+ submenu: choices,});const on = atMs >= one.startMs && atMs < one.endMs;out.push({ id: 'clip-marker', label: t('editorTools.markerAddClip'), icon: <Flag size={14} />, shortcut: 'M', disabled: !on, hint: t('editorTools.freezeOutside'), onSelect: () => addMarkerHere(one) });}return out;- }, [measuring, media, normalize, freeze, replace, addMarkerHere, timeRef, t]);+ }, [measuring, media, normalize, freeze, replaceEntries, addMarkerHere, timeRef, t]);/* ── what the timeline draws ── */const clipMarkersByTrack = React.useMemo(() => {@@ -340,6 +396,8 @@ export function useEditorTools({tracks: shownTracks,timeline: { solo: soloProp, rulerOverlay, trackOverlay, toolbarExtra, snapPointsMs, onResizeTrack, onReplaceDrop },menuExtra,+ /** what can replace a clip (the inspector's Replace) */+ replaceEntries,headMenuExtra,onKey,levels,diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex a89a307..e41cacf 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -739,7 +739,7 @@ export const en = {copyPath: 'Copy path',dropHint: 'Drop to import into this project',sort_name: 'Name',- sort_time: 'Date modified',+ sort_time: 'Date added',sort_duration: 'Duration',sort_type: 'Type',moveTo: "Move to",@@ -1279,6 +1279,9 @@ export const en = {replaceNone: "No file in the project can take its place",replaceKind: "A picture is replaced by a picture, a sound by a sound",replaceShort: "The new file is shorter: the clip is {s} s shorter",+ replaceButton: "Replace",+ replaceFromComputer: "From your computer…",+ replacePick: "Choose a file to replace the clip",},/* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */clipAttrs: {diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex 6fac505..811d2d1 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -738,7 +738,7 @@ export const es: Words = {copyPath: 'Copiar ruta',dropHint: 'Suelta para importar a este proyecto',sort_name: 'Nombre',- sort_time: 'Fecha de modificación',+ sort_time: 'Fecha de incorporación',sort_duration: 'Duración',sort_type: 'Tipo',moveTo: "Mover a",@@ -1278,6 +1278,9 @@ export const es: Words = {replaceNone: "Ningún archivo del proyecto puede ocupar su lugar",replaceKind: "Una imagen se reemplaza por una imagen, un sonido por un sonido",replaceShort: "El archivo nuevo es más corto: el clip dura {s} s menos",+ replaceButton: "Reemplazar",+ replaceFromComputer: "Desde tu ordenador…",+ replacePick: "Elige un archivo para reemplazar el clip",},/* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */clipAttrs: {diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex dadc257..0946dd0 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -738,7 +738,7 @@ export const ja: Words = {copyPath: 'パスをコピー',dropHint: 'ドロップしてこのプロジェクトに読み込み',sort_name: '名前',- sort_time: '変更日',+ sort_time: '追加日',sort_duration: 'デュレーション',sort_type: '種類',moveTo: "移動先",@@ -1278,6 +1278,9 @@ export const ja: Words = {replaceNone: "置き換えられるファイルがプロジェクトにありません",replaceKind: "映像は映像で、音は音で置き換えます",replaceShort: "新しいファイルのほうが短いため、クリップが {s} 秒短くなりました",+ replaceButton: "置き換え",+ replaceFromComputer: "このコンピュータから…",+ replacePick: "クリップと置き換えるファイルを選択",},/* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */clipAttrs: {diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex bb3e192..167e8f0 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -738,7 +738,7 @@ export const ko: Words = {copyPath: '경로 복사',dropHint: '놓으면 이 프로젝트로 가져옵니다',sort_name: '이름',- sort_time: '수정한 날짜',+ sort_time: '추가한 날짜',sort_duration: '길이',sort_type: '유형',moveTo: "이동",@@ -1278,6 +1278,9 @@ export const ko: Words = {replaceNone: "프로젝트에 대신할 수 있는 파일이 없습니다",replaceKind: "화면은 화면으로, 소리는 소리로 바꿉니다",replaceShort: "새 파일이 더 짧아 클립이 {s}초 짧아졌습니다",+ replaceButton: "바꾸기",+ replaceFromComputer: "이 컴퓨터에서…",+ replacePick: "클립을 바꿀 파일 선택",},/* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */clipAttrs: {diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex ebb4325..09b2fc0 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -739,7 +739,7 @@ export const zhCN: Words = {copyPath: '复制路径',dropHint: '松开即可导入到此项目',sort_name: '名称',- sort_time: '修改日期',+ sort_time: '添加时间',sort_duration: '时长',sort_type: '类型',moveTo: "移动到",@@ -1279,6 +1279,9 @@ export const zhCN: Words = {replaceNone: "项目里没有可以替换它的文件",replaceKind: "画面只能用画面替换,声音只能用声音替换",replaceShort: "新文件更短:片段短了 {s} 秒",+ replaceButton: "替换",+ replaceFromComputer: "从电脑选择…",+ replacePick: "选择用来替换的文件",},/* a clip's attributes copied onto others (lib/clip-attrs, components/PasteAttrsDialog), as CapCut's */clipAttrs: {diff --git a/packages/openfilm/studio/ui/src/lib/clip-replace.test.ts b/packages/openfilm/studio/ui/src/lib/clip-replace.test.tsindex de604fe..05d72d6 100644--- a/packages/openfilm/studio/ui/src/lib/clip-replace.test.ts+++ b/packages/openfilm/studio/ui/src/lib/clip-replace.test.ts@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { readFilm } from '../../../../src/film-doc.mjs';import { applyOps } from '../../../server/ops.mjs';import type { Clip } from '../api.ts';-import { canReplace, replaceClip } from './clip-replace.ts';+import { canReplace, familyOfClip, replaceClip } from './clip-replace.ts';/* the edits applied by the server's own code, and the film read back strictly, as a host reads film.html */const replaced = (clip: Clip, durMs: number, file: Parameters<typeof replaceClip>[2]) => {@@ -52,3 +52,10 @@ test('a sound takes a sound, or a video\'s own sound; never a picture', () => {assert.equal(canReplace(shot, { path: 'assets/bed.mp3', kind: 'audio' }), false);assert.deepEqual(replaceClip(shot, 2000, { path: 'assets/a.mp4', kind: 'video' }), { error: 'same' });});++test('a clip is replaced from its family: a sound by a sound, a picture by a picture', () => {+ assert.equal(familyOfClip({ src: 'assets/bed.m4a' }), 'sound');+ assert.equal(familyOfClip({ src: 'assets/take.mp4', sound: true }), 'sound');+ assert.equal(familyOfClip({ src: 'assets/take.mp4' }), 'picture');+ assert.equal(familyOfClip({ src: 'scenes/title.html' }), 'picture');+});diff --git a/packages/openfilm/studio/ui/src/lib/clip-replace.ts b/packages/openfilm/studio/ui/src/lib/clip-replace.tsindex 2fc44e4..0f9fc0f 100644--- a/packages/openfilm/studio/ui/src/lib/clip-replace.ts+++ b/packages/openfilm/studio/ui/src/lib/clip-replace.ts@@ -14,10 +14,11 @@ export type ReplacePlan =| { edits: { prop: string; value: PropValue }[]; shortMs: number }| { error: 'kind' | 'same' };-type Family = 'picture' | 'sound';+export type ReplaceFamily = 'picture' | 'sound';const isSoundFile = (f: ReplaceFile) => f.kind === 'audio';-const familyOfClip = (clip: Pick<Clip, 'src' | 'sound'>): Family => (clip.sound || /\.(mp3|m4a|aac|wav|ogg|oga|opus|flac|aif|aiff)$/i.test(clip.src) ? 'sound' : 'picture');+/** What can take a clip's place: a picture (a video, a still, a page) or a sound (a sound file, a video's sound). */+export const familyOfClip = (clip: Pick<Clip, 'src' | 'sound'>): ReplaceFamily => (clip.sound || /\.(mp3|m4a|aac|wav|ogg|oga|opus|flac|aif|aiff)$/i.test(clip.src) ? 'sound' : 'picture');/** Whether `file` can take the place of `clip`. */export function canReplace(clip: Pick<Clip, 'src' | 'sound'>, file: ReplaceFile): boolean {diff --git a/packages/openfilm/studio/ui/src/lib/media-queue.test.ts b/packages/openfilm/studio/ui/src/lib/media-queue.test.tsnew file mode 100644index 0000000..f954bf5--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-queue.test.ts@@ -0,0 +1,87 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';++/* the browser's side, as the queue sees it: requests that answer when told, pictures that load when told */+const asked: string[] = [];+const answers = new Map<string, () => void>();+let out = 0;+let most = 0;+const settle = (url: string) => new Promise<void>((done) => {+ out += 1;+ most = Math.max(most, out);+ answers.set(url, () => { out -= 1; answers.delete(url); done(); });+});+(globalThis as { fetch: unknown }).fetch = async (url: string) => { asked.push(url); await settle(url); return new Response('{}'); };+(globalThis as { Image: unknown }).Image = class {+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ set src(url: string) { asked.push(url); void settle(url).then(() => (url.includes('broken') ? this.onerror : this.onload)?.()); }+};+const { MEDIA_IN_FLIGHT, mediaFetch, mediaImage } = await import('./media-queue.ts');++const tick = () => new Promise((done) => setTimeout(done, 0));+const answer = async (url: string) => { answers.get(url)!(); await tick(); await tick(); };++test('a few at a time; what a file is goes before its pictures; a picture no longer wanted is never asked for', async () => {+ let wanted = true;+ const got = [+ mediaImage('frame-1'), mediaImage('frame-2'), mediaImage('frame-3', () => wanted),+ mediaImage('frame-4'), mediaFetch('probe-1'),+ ];+ /* the same picture asked again while it waits: one request */+ const again = mediaImage('frame-4');+ await tick();+ assert.deepEqual(asked, ['frame-1', 'frame-2']);+ assert.equal(out, MEDIA_IN_FLIGHT);+ wanted = false;+ await answer('frame-1');+ assert.deepEqual(asked, ['frame-1', 'frame-2', 'probe-1'], 'the facts jump the pictures waiting');+ await answer('frame-2');+ assert.deepEqual(asked, ['frame-1', 'frame-2', 'probe-1', 'frame-4'], 'frame-3, no longer wanted, is skipped');+ await answer('probe-1');+ await answer('frame-4');+ assert.deepEqual(await Promise.all(got.map((p) => p.then((r) => (r instanceof Response ? 'response' : r)))), [true, true, null, true, 'response']);+ assert.equal(await again, true);+ assert.equal(most, MEDIA_IN_FLIGHT);+ /* loaded once: shown again without a turn or a request */+ assert.equal(await mediaImage('frame-1'), true);+ assert.equal(asked.filter((u) => u === 'frame-1').length, 1);+});++test('a picture that does not load says so, and is asked for again next time', async () => {+ asked.length = 0;+ const first = mediaImage('broken-1');+ await tick();+ await answer('broken-1');+ assert.equal(await first, false);+ const second = mediaImage('broken-1');+ await tick();+ await answer('broken-1');+ assert.equal(await second, false);+ assert.deepEqual(asked, ['broken-1', 'broken-1']);+});++test('web pages, drawn one at a time by the server, go one at a time; a media file\'s go beside them', async () => {+ asked.length = 0;+ const page = (n: number) => `/media?what=frame&path=scene-${n}.html`;+ const got = [mediaImage(page(1)), mediaImage(page(2)), mediaFetch('/media?what=wave&path=assets/song.mp3')];+ await tick();+ assert.deepEqual(asked, [page(1), '/media?what=wave&path=assets/song.mp3'], 'the sound is not behind the pages');+ await answer(page(1));+ assert.deepEqual(asked, [page(1), '/media?what=wave&path=assets/song.mp3', page(2)]);+ await answer('/media?what=wave&path=assets/song.mp3');+ await answer(page(2));+ await Promise.all(got);+});++test('a page\'s pictures go before its facts', async () => {+ asked.length = 0;+ const p = (what: string, n: number) => `/media?what=${what}&path=scene-${n}.html`;+ const got = [mediaImage(p('poster', 1)), mediaFetch(p('probe', 2)), mediaImage(p('poster', 3))];+ await tick();+ await answer(p('poster', 1));+ assert.deepEqual(asked, [p('poster', 1), p('poster', 3)]);+ await answer(p('poster', 3));+ await answer(p('probe', 2));+ await Promise.all(got);+});diff --git a/packages/openfilm/studio/ui/src/lib/media-queue.ts b/packages/openfilm/studio/ui/src/lib/media-queue.tsindex 43c3e1e..99019ec 100644--- a/packages/openfilm/studio/ui/src/lib/media-queue.ts+++ b/packages/openfilm/studio/ui/src/lib/media-queue.ts@@ -1,24 +1,107 @@/**- * Studio's background requests for media facts (a file's length and size, a waveform): a few at a time.+ * Studio's background requests for media (a file's length and size, a waveform, and the pictures: the timeline's+ * thumbnails, a clip's poster, the media pane's covers): a few at a time.*- * A browser keeps six connections to Studio. Opening a project used to ask for every file's facts at once — a web- * page's are found by drawing it in the headless browser, one after another — and those requests held all six for- * half a minute: an edit made meanwhile waited for a free one, and the person saw it fail. With at most- * MEDIA_IN_FLIGHT of them out, the editor's own requests always find a connection.+ * A browser keeps six connections to Studio. Opening a project used to ask for every file's facts and every picture at+ * once, and those requests held all six for half a minute: an edit made meanwhile (a sound dropped at the film's end)+ * waited for a free one, and the person saw it not land. So they go in two lines: a web page's facts and pictures are+ * found by drawing it in the headless browser, one at a time on the server, so one at a time here (more would only+ * wait there, each holding a connection); a media file's come from ffmpeg, MEDIA_IN_FLIGHT at a time. The editor's own+ * requests always find a connection. A media file's facts go before its pictures (a video's length decides which+ * frames are asked for); a page's pictures go before its facts (they are what the person waits to see, and a page+ * clip's length is in film.html already).*/+import * as React from 'react';+export const MEDIA_IN_FLIGHT = 2;+export const PAGES_IN_FLIGHT = 1;-let running = 0;-const waiting: Array<() => void> = [];+/** `first`: what waits there goes before `then` */+type Line = { running: number; most: number; first: Array<() => void>; then: Array<() => void>; picturesFirst: boolean };+const files: Line = { running: 0, most: MEDIA_IN_FLIGHT, first: [], then: [], picturesFirst: false };+const pages: Line = { running: 0, most: PAGES_IN_FLIGHT, first: [], then: [], picturesFirst: true };-/** `fetch`, waiting its turn among the media requests. */-export async function mediaFetch(url: string, init?: RequestInit): Promise<Response> {- if (running >= MEDIA_IN_FLIGHT) await new Promise<void>((go) => waiting.push(go));- running += 1;+/** A request about a web page (its `path`) is drawn in the headless browser. */+const lineOf = (url: string): Line => (/\.html?$/i.test(new URL(url, 'http://studio').searchParams.get('path') ?? '') ? pages : files);++/** Wait for a turn, run, give the turn on. `still`: asked when the turn comes; false skips it (not wanted any more). */+async function inTurn<T>(run: () => Promise<T>, line: Line, picture: boolean, still?: () => boolean): Promise<T | undefined> {+ if (line.running >= line.most) await new Promise<void>((go) => (picture === line.picturesFirst ? line.first : line.then).push(go));+ line.running += 1;try {- return await fetch(url, init);+ if (still && !still()) return undefined;+ return await run();} finally {- running -= 1;- waiting.shift()?.();+ line.running -= 1;+ (line.first.shift() ?? line.then.shift())?.();}}++/** `fetch`, waiting its turn among the media requests. */+export async function mediaFetch(url: string, init?: RequestInit): Promise<Response> {+ return (await inTurn(() => fetch(url, init), lineOf(url), false))!;+}++/** Pictures loaded once: the browser has them, so they are shown again without waiting a turn. */+const LOADED = new Set<string>();+const LOADED_MAX = 2000;+/** Pictures waiting their turn or loading, each asked for once. */+const WAITING = new Map<string, { done: Promise<boolean | null>; stills: Array<() => boolean> }>();++/**+ * Load a picture into the browser's cache, waiting its turn; true when it loaded, false when it did not. `still` is+ * asked when its turn comes: a picture not wanted any more by then (another zoom, a tile scrolled away) is not asked+ * for at all (null).+ */+export async function mediaImage(url: string, still?: () => boolean): Promise<boolean | null> {+ if (LOADED.has(url)) return true;+ /* asked again while waiting (the timeline asks again on every change): one request, wanted while anyone wants it */+ const queued = WAITING.get(url);+ if (queued) { queued.stills.push(still ?? (() => true)); return queued.done; }+ const stills = [still ?? (() => true)];+ const done = inTurn(() => new Promise<boolean>((loaded) => {+ const img = new Image();+ img.onload = () => loaded(true);+ img.onerror = () => loaded(false);+ img.src = url;+ }), lineOf(url), true, () => stills.some((s) => s())).then((ok) => {+ WAITING.delete(url);+ if (ok) {+ LOADED.add(url);+ if (LOADED.size > LOADED_MAX) LOADED.delete(LOADED.values().next().value!);+ }+ return ok ?? null;+ });+ WAITING.set(url, { done, stills });+ return done;+}++/**+ * A picture's address once it has had its turn (loaded or not: a failure is the `<img>`'s to show and retry), else+ * the last one that had it, so a picture made again never flickers. `wanted` false: not asked for yet (off screen).+ */+export function useMediaImage(url: string | null | undefined, wanted = true): string | null {+ const [ready, setReady] = React.useState<string | null>(() => (url && LOADED.has(url) ? url : null));+ React.useEffect(() => {+ if (!url || !wanted || ready === url) return undefined;+ let live = true;+ void mediaImage(url, () => live).then((had) => { if (live && had !== null) setReady(url); });+ return () => { live = false; };+ }, [url, wanted, ready]);+ return url && LOADED.has(url) ? url : ready;+}++/** The pictures of `urls` (by any key) that have had their turn: what can be drawn now. */+export function useMediaImages(urls: Readonly<Record<string, string>>): Readonly<Record<string, string>> {+ const [ready, setReady] = React.useState<ReadonlySet<string>>(() => new Set());+ const wanted = React.useRef(urls);+ wanted.current = urls;+ React.useEffect(() => {+ for (const url of new Set(Object.values(urls))) {+ if (ready.has(url)) continue;+ void mediaImage(url, () => Object.values(wanted.current).includes(url))+ .then((had) => { if (had !== null) setReady((cur) => (cur.has(url) ? cur : new Set(cur).add(url))); });+ }+ }, [urls]); // eslint-disable-line react-hooks/exhaustive-deps+ return React.useMemo(() => Object.fromEntries(Object.entries(urls).filter(([, url]) => ready.has(url) || LOADED.has(url))), [urls, ready]);+}diff --git a/packages/openfilm/studio/ui/src/lib/use-loaded-thumbs.ts b/packages/openfilm/studio/ui/src/lib/use-loaded-thumbs.tsindex 8914968..5ac42fd 100644--- a/packages/openfilm/studio/ui/src/lib/use-loaded-thumbs.ts+++ b/packages/openfilm/studio/ui/src/lib/use-loaded-thumbs.ts@@ -8,6 +8,8 @@*/import * as React from 'react';+import { mediaImage } from './media-queue';+/** `mtime:clipId` of a key (`mtime:clipId@intoMs#v`, see thumb-frame), and the clip id alone. */function versionOf(key: string): { version: string; clip: string } | null {const at = key.lastIndexOf('@', key.lastIndexOf('#'));@@ -46,33 +48,37 @@ export function useLoadedThumbs(wanted: ReadonlyMap<string, string>): ReadonlyMaconst load = (key: string, url: string) => {if (loadedRef.current.get(key) === url || pending.current.has(url)) return;pending.current.add(url);- const img = new Image();- img.onload = () => {- pending.current.delete(url);- tries.current.delete(url);- arrived.current.set(key, url);- if (flush.current) return;- flush.current = requestAnimationFrame(() => {- flush.current = 0;- const batch = arrived.current; arrived.current = new Map();- setLoaded((prev) => { const next = new Map(prev); for (const [k, u] of batch) next.set(k, u); return next; });- });- };- /* not there (yet): asked again a little later while it is still wanted, and the next time it is wanted. Waiting- for the next zoom instead left a clip on the nearest other picture it had (a trimmed clip on its source's black- first frame) for as long as nobody zoomed */- img.onerror = () => {+ /* in turn with Studio's other media requests (lib/media-queue): a picture no longer wanted when its turn comes+ (another zoom) is not asked for */+ void mediaImage(url, () => wantedRef.current.get(key) === url).then((ok) => {pending.current.delete(url);- const n = (tries.current.get(url) ?? 0) + 1;- tries.current.set(url, n);- if (n > 6) return;- const timer = setTimeout(() => {- retries.current.delete(timer);- if (wantedRef.current.get(key) === url) load(key, url);- }, Math.min(8000, 1000 * 2 ** (n - 1)));- retries.current.add(timer);- };- img.src = url;+ if (ok === null) return;+ if (ok) arrive(key, url);+ else failed(key, url);+ });+ };+ const arrive = (key: string, url: string) => {+ tries.current.delete(url);+ arrived.current.set(key, url);+ if (flush.current) return;+ flush.current = requestAnimationFrame(() => {+ flush.current = 0;+ const batch = arrived.current; arrived.current = new Map();+ setLoaded((prev) => { const next = new Map(prev); for (const [k, u] of batch) next.set(k, u); return next; });+ });+ };+ /* not there (yet): asked again a little later while it is still wanted, and the next time it is wanted. Waiting+ for the next zoom instead left a clip on the nearest other picture it had (a trimmed clip on its source's black+ first frame) for as long as nobody zoomed */+ const failed = (key: string, url: string) => {+ const n = (tries.current.get(url) ?? 0) + 1;+ tries.current.set(url, n);+ if (n > 6) return;+ const timer = setTimeout(() => {+ retries.current.delete(timer);+ if (wantedRef.current.get(key) === url) load(key, url);+ }, Math.min(8000, 1000 * 2 ** (n - 1)));+ retries.current.add(timer);};for (const [key, url] of wanted) load(key, url);}, [wanted]);diff --git a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts b/packages/openfilm/studio/ui/src/lib/workspace-resources.tsindex 30a6102..c4f1812 100644--- a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts+++ b/packages/openfilm/studio/ui/src/lib/workspace-resources.ts@@ -22,6 +22,8 @@ export interface WorkspaceResource {size: number;kind: WorkspaceResourceKind;mtimeMs: number;+ /** When it came into the project (a link: when it was made); its mtime when the server does not say */+ addedMs?: number;/*** The probed length. Dragging a clip onto the timeline needs it (a clip cannot be pulled longer than its source);* missing when it could not be probed, and the timeline then uses a cautious default.@@ -97,7 +99,7 @@ export interface MediaFacts {/** Studio's `GET files` answer. */export interface FilesListing {- files: readonly { path: string; kind: string; size: number; mtime: number }[];+ files: readonly { path: string; kind: string; size: number; mtime: number; added?: number }[];folders: readonly string[];pages: readonly { path: string; size: number; mtime: number }[];/** Links to media kept elsewhere, by project path (files and folders). */@@ -150,6 +152,7 @@ export function mediaListingOf(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,...facts?.(f.path),...(raw.links?.[f.path] ? { link: raw.links[f.path]! } : {}),})),@@ -163,6 +166,7 @@ export function mediaListingOf(size: p.size,kind: 'mg' as const,mtimeMs: p.mtime,+ addedMs: p.mtime,...facts?.(p.path),})),};