Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: open projects stay live after a rename (#85)

xyd945d6a3a86ba990
diff --git a/.changeset/open-project-rename.md b/.changeset/open-project-rename.md
new file mode 100644
index 0000000..978509d
--- /dev/null
+++ b/.changeset/open-project-rename.md
@@ -0,0 +1,6 @@
+---
+"openfilm": patch
+"@openfilm/desktop": patch
+---
+
+Keep live film, file, history and export updates connected after a project is renamed, and send the desktop agent to its new folder. Wait for active agent work and running or queued exports to finish before renaming a project.
diff --git a/apps/desktop/shell/bridge.ts b/apps/desktop/shell/bridge.ts
index 330597d..972d748 100644
--- a/apps/desktop/shell/bridge.ts
+++ b/apps/desktop/shell/bridge.ts
@@ -10,12 +10,11 @@
* (src/preload.cjs). Imported before Studio's modules and the chat's: Studio reads its host as it loads.
*/
import { flushSync } from 'react-dom';
-import type { CommunityItem, HostAgent, HostAsk, HostUpdate, HostUpdateState, StudioCommand, StudioHost, StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';
+import type { CommunityItem, HostAgent, HostAsk, HostProject as Project, HostUpdate, HostUpdateState, StudioCommand, StudioHost, StudioRef, StudioSelection } from 'openfilm/studio-ui/lib/host.ts';
type Listener<T> = (value: T) => void;
type Stop = () => void;
type Theme = 'light' | 'dark';
-type Project = { id: string; name: string; path: string };
interface Native {
platform: string;
@@ -135,14 +134,26 @@ language.on((next) => native.setLanguage(next));
/* ── the project Studio shows (its address, /projects/<id>) ── */
const project = signal<Project | null>(null);
let projectReady: Promise<void> = Promise.resolve();
+let projectRequest = 0;
+const projectId = () => /^\/projects\/([\w-]+)/.exec(location.pathname)?.[1] ?? null;
+function projectChanged(next: Project, request?: number) {
+ if (next.id !== projectId()) return;
+ if (request === undefined) projectRequest += 1;
+ else if (request !== projectRequest) return;
+ const current = project.get();
+ if (current?.id === next.id && current.name === next.name && current.path === next.path) return;
+ project.set({ id: next.id, name: next.name, path: next.path });
+}
async function follow() {
- const id = /^\/projects\/([\w-]+)/.exec(location.pathname)?.[1] ?? null;
- if (!id || id === project.get()?.id) return;
+ /* Reads from before a rename or a previous visit cannot restore an old folder. */
+ const request = ++projectRequest;
+ const id = projectId();
+ if (!id) return; // Keep the chat mounted while the project list covers it.
try {
const res = await fetch('/api/projects');
const body = await res.json() as { projects?: Project[] };
const found = body.projects?.find((p) => p.id === id);
- if (found) project.set({ id: found.id, name: found.name, path: found.path });
+ if (found) projectChanged(found, request);
} catch { /* told next time the address changes */ }
}
for (const method of ['pushState', 'replaceState'] as const) {
@@ -258,6 +269,7 @@ const INSET_RIGHT = 138;
const host: StudioHost = {
version: 1,
name: 'OpenFilm',
+ projectChanged,
...(mac ? { titlebar: { inset: INSET, onChange: (listener: Listener<number>) => { fullScreen.on((full) => listener(full ? 6 : INSET)); } } } : {}),
...(windows ? { titlebar: { inset: 6, insetRight: INSET_RIGHT } } : {}),
/* in order, each with its picture: two pointed at quickly must not swap or share a screenshot */
diff --git a/apps/desktop/src/project-bridge.test.mjs b/apps/desktop/src/project-bridge.test.mjs
new file mode 100644
index 0000000..5fbb3fd
--- /dev/null
+++ b/apps/desktop/src/project-bridge.test.mjs
@@ -0,0 +1,199 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import vm from 'node:vm';
+import ts from 'typescript';
+
+const bridgeSource = readFileSync(new URL('../shell/bridge.ts', import.meta.url), 'utf8');
+const apiSource = readFileSync(new URL('../../../packages/openfilm/studio/ui/src/api.ts', import.meta.url), 'utf8');
+
+// Run the real bridge and API together; only their native, DOM and network boundaries are replaced.
+function loadSource(context, source) {
+ const js = ts.transpileModule(source.replace(/^import .*;\n/gm, ''), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText;
+ vm.runInContext(js.replace(/^export /gm, '').replace(/^\{\s*\};?$/gm, ''), context);
+}
+function harness() {
+ const requests = [], sockets = [], timers = [];
+ const events = new Map();
+ const element = () => ({ style: {}, dataset: {}, toggleAttribute() {} });
+ const column = element();
+ const location = { pathname: '/projects/a', protocol: 'http:', host: 'localhost:4787' };
+ const native = {
+ platform: 'linux',
+ hello: async () => ({ chatOpen: true, chatWidth: 420, chatMin: 340, studioMin: 640, fullScreen: false }),
+ agents: {}, localAgents: {}, chat: {}, skills: {},
+ setTheme() {}, setLanguage() {}, onFullScreen() {}, onToggleChat() {},
+ };
+ const context = vm.createContext({
+ window: { openfilmNative: native },
+ location,
+ history: Object.fromEntries(['pushState', 'replaceState'].map((method) => [method, (_state, _title, url) => { location.pathname = url; }])),
+ document: { documentElement: element(), getElementById: () => column, createElement: element, head: { append() {} } },
+ MutationObserver: class { observe() {} },
+ WebSocket: class {
+ constructor(url) { this.url = url; sockets.push(this); }
+ close() { this.closed = true; }
+ emit(event) { this.onmessage({ data: JSON.stringify(event) }); }
+ },
+ setTimeout: (fn) => { timers.push(fn); return timers.length; },
+ clearTimeout: (id) => { timers[id - 1] = null; },
+ innerWidth: 1280,
+ addEventListener: (name, listener) => events.set(name, listener),
+ flushSync: (fn) => fn(),
+ fetch: (url, init) => new Promise((resolve) => {
+ requests.push({ url, init, respond: (body, status = 200) => resolve({ ok: status < 400, status, json: async () => body }) });
+ }),
+ });
+ loadSource(context, bridgeSource);
+ context.studioHost = context.window.openfilmHost;
+ loadSource(context, apiSource);
+ const api = vm.runInContext('api', context);
+ const projectEvents = vm.runInContext('projectEvents', context);
+ const bridge = context.window.openfilmDesktop;
+ const changed = [];
+ bridge.onProject((project) => changed.push({ ...project }));
+ return {
+ api, bridge, native, requests, changed, sockets, column,
+ subscribe: (id = 'a', listener = () => {}) => projectEvents(id, listener),
+ reconnect: () => { sockets.at(-1).onclose(); timers.at(-1)(); sockets.at(-1).onopen(); },
+ navigate: (path) => context.history.pushState(null, '', path),
+ };
+}
+const project = (name = 'Untitled', id = 'a') => ({ id, name, path: `/projects/${name}`, openedAt: 1, missing: false });
+const shown = (p) => ({ id: p.id, name: p.name, path: p.path });
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+async function opened(h) {
+ h.requests[0].respond({ projects: [project()] });
+ await h.bridge.hello();
+}
+
+test('a confirmed rename updates the existing chat immediately, ahead of its pending project lookup', async () => {
+ const h = harness();
+ const chat = h.bridge.chat;
+ const renamed = project('My film');
+ const rename = h.api.rename('a', renamed.name);
+ assert.equal(h.requests[1].url, '/api/projects/a');
+ assert.equal(h.requests[1].init.method, 'PATCH');
+ h.requests[1].respond({ project: renamed });
+ assert.equal((await rename).path, renamed.path);
+ assert.deepEqual(h.changed, [shown(renamed)]);
+ h.requests[0].respond({ projects: [project()] });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(renamed));
+ assert.equal(h.bridge.chat, chat, 'the same chat bridge stays attached');
+});
+
+test('film reads cannot restore an old folder after a confirmed rename', async () => {
+ const h = harness();
+ await opened(h);
+ const oldFilm = h.api.film('a');
+ const rename = h.api.rename('a', 'My film');
+ h.requests[2].respond({ project: project('My film') });
+ await rename;
+ h.requests[1].respond({ project: project(), text: '' });
+ await oldFilm;
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('My film')));
+ assert.deepEqual(h.changed.map((p) => p.name), ['Untitled', 'My film']);
+});
+
+test('the shared project stream updates chat for a rename in another page', async () => {
+ const h = harness();
+ await opened(h);
+ const received = [];
+ h.subscribe('a', (event) => received.push(event.type));
+ h.subscribe('a');
+ assert.equal(h.sockets.length, 1);
+ const renamed = project('Renamed elsewhere');
+ h.sockets[0].emit({ type: 'project', project: renamed });
+ h.sockets[0].emit({ type: 'film', rev: '' });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(renamed));
+ assert.deepEqual(h.changed.map((p) => p.name), ['Untitled', 'Renamed elsewhere']);
+ assert.deepEqual(received, ['project', 'film']);
+ assert.equal(h.requests.length, 1, 'current project metadata needs no extra HTTP lookup');
+});
+
+test('the project snapshot on reconnect repairs a rename missed while disconnected', async () => {
+ const h = harness();
+ await opened(h);
+ const received = [];
+ h.subscribe('a', (event) => received.push(event.type));
+ h.reconnect();
+ assert.equal(h.sockets.length, 2);
+ h.sockets[1].emit({ type: 'project', project: project('Renamed while offline') });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('Renamed while offline')));
+ assert.deepEqual(received, ['film', 'files', 'history', 'project']);
+});
+
+test('an initial project snapshot prevents an older list response from restoring the old folder', async () => {
+ const h = harness();
+ h.subscribe();
+ h.sockets[0].emit({ type: 'project', project: project('Current folder') });
+ h.requests[0].respond({ projects: [project()] });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('Current folder')));
+});
+
+test('an earlier project-list response cannot replace the project reached by navigation', async () => {
+ const h = harness();
+ h.navigate('/projects/b');
+ h.requests[1].respond({ projects: [project('Project B', 'b')] });
+ await h.bridge.hello();
+ h.requests[0].respond({ projects: [project()] });
+ await tick();
+ assert.deepEqual(h.changed, [shown(project('Project B', 'b'))]);
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('Project B', 'b')));
+});
+
+test('a previous project rename does not cancel the newly opened project lookup', async () => {
+ const h = harness();
+ await opened(h);
+ const rename = h.api.rename('a', 'Renamed A');
+ h.subscribe('a');
+ h.navigate('/projects/b');
+ h.requests[1].respond({ project: project('Renamed A') });
+ await rename;
+ h.sockets[0].emit({ type: 'project', project: project('Renamed A again') });
+ h.requests[2].respond({ projects: [project('Project B', 'b')] });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('Project B', 'b')));
+});
+
+test('leaving keeps the chat mounted and returning invalidates reads from the earlier visit', async () => {
+ const h = harness();
+ await opened(h);
+ const chat = h.bridge.chat;
+ h.navigate('/projects/a');
+ h.navigate('/');
+ assert.equal(h.column.hidden, true);
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project()));
+ assert.equal(h.bridge.chat, chat);
+ assert.deepEqual(h.changed, [shown(project())], 'no null/reset project notification on leaving');
+ h.navigate('/projects/a');
+ assert.equal(h.column.hidden, false);
+ h.requests[1].respond({ projects: [project('Earlier visit')] });
+ await tick();
+ assert.deepEqual(h.changed.map((p) => p.name), ['Untitled']);
+ h.requests[2].respond({ projects: [project('Current visit')] });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('Current visit')));
+});
+
+test('late events from an unsubscribed project stream cannot overwrite its next visit', async () => {
+ const h = harness();
+ await opened(h);
+ const stop = h.subscribe();
+ stop();
+ assert.equal(h.sockets[0].closed, true);
+ h.navigate('/');
+ h.navigate('/projects/a');
+ h.subscribe();
+ h.sockets[1].emit({ type: 'project', project: project('Current visit') });
+ h.sockets[0].emit({ type: 'project', project: project('Previous visit') });
+ h.requests[1].respond({ projects: [project()] });
+ assert.deepEqual({ ...(await h.bridge.hello()).project }, shown(project('Current visit')));
+});
+
+test('a refused rename leaves the chat path unchanged and preserves the reason for Studio', async () => {
+ const h = harness();
+ await opened(h);
+ const rename = h.api.rename('a', 'My film');
+ h.requests[1].respond({ error: 'Stop the agent first.', code: 'agent-running' }, 409);
+ await assert.rejects(rename, (error) => error.status === 409 && error.body.code === 'agent-running');
+ assert.deepEqual(h.changed, [shown(project())]);
+});
diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjs
index 5c0e054..7ae604d 100644
--- a/packages/openfilm/studio/server/server.mjs
+++ b/packages/openfilm/studio/server/server.mjs
@@ -97,7 +97,7 @@ export function desktopInstaller(os, arch, base = DESKTOP_FILES) {
* `onQuit`: what `POST /api/quit` does (by default, close); `stays`: it does nothing and says so (an app's Studio,
* which its window needs). `editorDir`: the built editor to serve (by default studio/ui/dist); an app that builds
* Studio's editor into a page of its own (its chat beside it) serves that one. `working`: the folders an app's agent
- * is working in right now (an app with a chat), which cannot be deleted meanwhile. Resolves once both servers listen.
+ * is working in right now (an app with a chat), which cannot be renamed or deleted meanwhile. Resolves once both servers listen.
* @param {{ port?: number, key?: string, openBrowser?: (url: string) => void, advertise?: boolean, onQuit?: () => void, stays?: boolean, editorDir?: string, working?: () => string[] }} [options]
*/
export async function startStudio({ port = 4747, key, openBrowser = systemBrowser, advertise = false, onQuit, stays = false, editorDir = EDITOR_DIR, working = () => [] } = {}) {
@@ -155,9 +155,11 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
pageCame();
return () => { editorPages.delete(send); };
};
- /** @param {{ path: string }} project @param {(event: any) => void} send */
+ /** @param {Awaited<ReturnType<typeof projectById>>} project @param {(event: any) => void} send */
const projectStream = (project, send) => {
const stop = watchers.subscribe(project.path, send);
+ /* A page reconnecting after a rename takes the current path even if it missed the live event. */
+ send({ type: 'project', project });
for (const ask of asks.pending(project.path)) send(ask);
return stop;
};
@@ -514,11 +516,24 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
}
if (req.method === 'PATCH') {
const { name } = /** @type {{ name?: string }} */ (await readJson(req));
+ if (agentIn(project.path)) throw new HttpError(409, 'An agent is running in this project: stop it first, then rename the project.', { code: 'agent-running' });
+ if (exports.list(project.id).some((job) => job.status === 'waiting' || job.status === 'running')) {
+ throw new HttpError(409, 'An export is queued or running in this project: wait for it to finish or stop it first, then rename the project.', { code: 'export-running' });
+ }
const renamed = await renameProject(project.id, String(name ?? ''));
- /* its address stays: the preview open on it keeps loading from the folder by its new name */
- pages.folderUrl(renamed);
- /* the pages showing it (renamed from another tab, or the projects list) take the new name */
- watchers.emit(project.path, { type: 'project', project: renamed });
+ if (renamed.path !== project.path || renamed.name !== project.name) {
+ watchers.move(project.path, renamed.path);
+ exportRoots.set(project.id, renamed.path);
+ /* its address stays: the preview open on it keeps loading from the folder by its new name */
+ pages.folderUrl(renamed);
+ /* the pages showing it (renamed from another tab, or the projects list) take the new name */
+ watchers.emit(renamed.path, { type: 'project', project: renamed });
+ /* Reload changes waiting to settle when the old watcher closed. A blank revision also refreshes
+ an unchanged film, but only for this project after an actual rename. */
+ watchers.emit(renamed.path, { type: 'film', rev: '' });
+ watchers.emit(renamed.path, { type: 'files' });
+ watchers.emit(renamed.path, { type: 'history' });
+ }
return json(res, 200, { project: renamed });
}
/* the project is deleted: its folder goes to the Trash (pages showing it go back to the list) */
diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjs
index 417f4ad..7cdc0da 100644
--- a/packages/openfilm/studio/server/server.test.mjs
+++ b/packages/openfilm/studio/server/server.test.mjs
@@ -1,6 +1,8 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+import fsPromises from 'node:fs/promises';
+import { syncBuiltinESMExports } from 'node:module';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';
@@ -177,6 +179,171 @@ test('a project\'s event stream reports the agent writing film.html', async () =
assert.ok(got.find((e) => e.type === 'film').rev);
});
+test('rename refreshes only its open pages, including writes still waiting to settle', { timeout: 10_000 }, async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { name: 'Refresh draft' } })).json();
+ const before = await (await api(`/api/projects/${project.id}`)).json();
+ const { project: other } = await (await api('/api/projects', { method: 'POST', body: { name: 'Unchanged project' } })).json();
+ const sockets = [project, project, other].map((project) => {
+ const ws = new WebSocket(`${studio.origin.replace(/^http/, 'ws')}/api/projects/${project.id}/events`, { headers: { 'x-studio-key': studio.key } });
+ const page = { ws, events: [] };
+ ws.onmessage = (event) => page.events.push(JSON.parse(String(event.data)));
+ return page;
+ });
+ const pages = sockets.slice(0, 2);
+ const unaffected = sockets[2];
+ try {
+ await Promise.all(sockets.map(({ ws }) => new Promise((done, fail) => { ws.onopen = done; ws.onerror = fail; })));
+ await new Promise((r) => setTimeout(r, 600));
+ /* only the project event: on a Mac the watcher can still report the new project's own files after the wait */
+ assert.deepEqual(unaffected.events.filter((e) => e.type === 'project'), [{ type: 'project', project: other }], 'every connection receives its current project');
+ unaffected.events.length = 0;
+ let current = before;
+ for (const [name, text] of [['Refresh film', null], ['Refresh final', filmHtml({ stage: { w: 800, h: 450 }, tracks: [] })]]) {
+ for (const page of pages) page.events.length = 0;
+ // A write just before rename must not be lost when its old watcher's settle timer is cancelled.
+ if (text) writeFileSync(join(current.project.path, 'film.html'), text);
+ const previous = current.project.path;
+ const renamed = (await (await api(`/api/projects/${project.id}`, { method: 'PATCH', body: { name } })).json()).project;
+ const refreshed = () => pages.every(({ events }) => ['project', 'film', 'files', 'history'].every((type) => events.some((e) => e.type === type)));
+ for (const end = Date.now() + 4000; !refreshed() && Date.now() < end;) await new Promise((r) => setTimeout(r, 25));
+ assert.ok(refreshed(), 'both existing sockets refresh without another write or reconnect');
+ current = await (await api(`/api/projects/${project.id}`)).json();
+ assert.equal(current.project.path, renamed.path);
+ assert.notEqual(current.project.path, previous);
+ if (text) assert.deepEqual(current.doc.stage, { w: 800, h: 450 });
+ else assert.equal(current.rev, before.rev, 'unchanged films still refresh the project path');
+ for (const { events } of pages) {
+ assert.ok(events.some((e) => e.type === 'film' && e.rev === ''), 'a forced refresh bypasses the editor’s unchanged-revision filter');
+ assert.deepEqual(events.find((e) => e.type === 'project').project, renamed);
+ }
+ assert.deepEqual(unaffected.events, [], 'a different open project never refreshes');
+ const reconnected = await collect(`/api/projects/${project.id}/events`, (events) => events.some((e) => e.type === 'project'));
+ assert.deepEqual(reconnected.find((e) => e.type === 'project').project, renamed, 'a page reconnecting after rename receives the current name and path');
+ assert.equal((await fetch(`${before.folder}film.html`)).status, 200, 'the existing preview address resolves to the renamed folder');
+ }
+ } finally {
+ await Promise.all(sockets.map(({ ws }) => new Promise((done) => { ws.onclose = done; ws.close(); })));
+ }
+});
+
+test('saving the same project name does not redraw its open page or replace its watcher', { timeout: 10_000 }, async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { name: 'Same name' } })).json();
+ const ws = new WebSocket(`${studio.origin.replace(/^http/, 'ws')}/api/projects/${project.id}/events`, { headers: { 'x-studio-key': studio.key } });
+ const events = [];
+ ws.onmessage = (event) => events.push(JSON.parse(String(event.data)));
+ try {
+ await new Promise((done, fail) => { ws.onopen = done; ws.onerror = fail; });
+ await new Promise((done) => setTimeout(done, 600));
+ events.length = 0;
+ for (const name of ['Same name', ' Same name ']) {
+ const response = await api(`/api/projects/${project.id}`, { method: 'PATCH', body: { name } });
+ assert.equal(response.status, 200);
+ assert.deepEqual((await response.json()).project, project);
+ }
+ await new Promise((done) => setTimeout(done, 250));
+ assert.deepEqual(events, [], 'unchanged names, including normalized names, send no redraw events');
+ writeFileSync(join(project.path, 'after.html'), '<p>still watched</p>');
+ for (const end = Date.now() + 4000; !events.some((e) => e.type === 'files') && Date.now() < end;) await new Promise((done) => setTimeout(done, 25));
+ assert.ok(events.some((e) => e.type === 'files' && e.paths?.includes('after.html')), 'the original watcher still reports changes');
+ } finally {
+ await new Promise((done) => { ws.onclose = done; ws.close(); });
+ }
+});
+
+test('rename waits for this project’s running or queued exports, but other projects can be renamed', { timeout: 15_000 }, async (t) => {
+ const create = async (name) => (await (await api('/api/projects', { method: 'POST', body: { name } })).json()).project;
+ const running = await create('Exporting draft');
+ const waiting = await create('Queued draft');
+ const other = await create('Idle draft');
+ const film = join(running.path, 'film.html');
+ const originalFilm = readFileSync(film, 'utf8');
+ const copyFile = fsPromises.copyFile;
+ const copying = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ // Hold a real project export at its copy, so the route sees stable running and waiting jobs.
+ t.mock.method(fsPromises, 'copyFile', async (...args) => {
+ if (args[0] === film) { copying.resolve(); await release.promise; }
+ return copyFile(...args);
+ });
+ syncBuiltinESMExports();
+ const start = async (project) => {
+ const response = await api(`/api/projects/${project.id}/exports`, { method: 'POST', body: { kind: 'project', as: 'folder', folder: join(scratch, 'rename-export-output') } });
+ assert.equal(response.status, 200);
+ return (await response.json()).export;
+ };
+ const jobs = async (project) => (await (await api(`/api/projects/${project.id}/exports`)).json()).exports;
+ const rename = (project) => api(`/api/projects/${project.id}`, { method: 'PATCH', body: { name: `${project.name} renamed` } });
+ let active;
+ let queued;
+ try {
+ active = await start(running);
+ await copying.promise;
+ queued = await start(waiting);
+ assert.equal((await jobs(running)).find((job) => job.id === active.id).status, 'running');
+ assert.equal((await jobs(waiting)).find((job) => job.id === queued.id).status, 'waiting');
+ for (const project of [running, waiting]) {
+ const response = await rename(project);
+ assert.equal(response.status, 409);
+ assert.equal((await response.json()).code, 'export-running');
+ assert.ok(existsSync(project.path), 'the export’s captured source folder stays in place');
+ }
+ assert.equal((await rename(other)).status, 200, 'another project is unaffected by the export queue');
+ assert.equal((await api(`/api/projects/${waiting.id}/exports/${queued.id}`, { method: 'DELETE' })).status, 200);
+ assert.equal((await jobs(waiting)).find((job) => job.id === queued.id).status, 'cancelled');
+ assert.equal((await rename(waiting)).status, 200, 'a cancelled queued job no longer prevents rename');
+ release.resolve();
+ let completed;
+ for (const end = Date.now() + 4000; Date.now() < end;) {
+ completed = (await jobs(running)).find((job) => job.id === active.id);
+ if (completed.status !== 'running') break;
+ await new Promise((done) => setTimeout(done, 25));
+ }
+ assert.equal(completed.status, 'done');
+ assert.equal(readFileSync(join(completed.outputs[0], 'film.html'), 'utf8'), originalFilm);
+ assert.equal((await rename(running)).status, 200, 'a finished export no longer prevents rename');
+ } finally {
+ release.resolve();
+ if (queued) await api(`/api/projects/${waiting.id}/exports/${queued.id}`, { method: 'DELETE' });
+ if (active) await api(`/api/projects/${running.id}/exports/${active.id}`, { method: 'DELETE' });
+ t.mock.restoreAll();
+ syncBuiltinESMExports();
+ }
+});
+
+test('an open project keeps film, file, history and export events after rename without reconnecting', { timeout: 15_000 }, async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { name: 'Watched draft' } })).json();
+ const ws = new WebSocket(`${studio.origin.replace(/^http/, 'ws')}/api/projects/${project.id}/events`, { headers: { 'x-studio-key': studio.key } });
+ const events = [];
+ ws.onmessage = (event) => events.push(JSON.parse(String(event.data)));
+ const waitFor = async (predicate, message) => {
+ for (const end = Date.now() + 4000; !events.some(predicate) && Date.now() < end;) await new Promise((r) => setTimeout(r, 25));
+ assert.ok(events.some(predicate), message);
+ };
+ try {
+ await new Promise((done, fail) => { ws.onopen = done; ws.onerror = fail; });
+ const renamed = (await (await api(`/api/projects/${project.id}`, { method: 'PATCH', body: { name: 'Watched film' } })).json()).project;
+ await new Promise((r) => setTimeout(r, 600));
+ events.length = 0;
+ writeFileSync(join(renamed.path, 'film.html'), filmHtml({ stage: { w: 640, h: 360 }, tracks: [] }));
+ writeFileSync(join(renamed.path, 'scene.html'), '<p>after rename</p>');
+ await waitFor((e) => e.type === 'film' && e.rev, 'the existing socket sees the new film revision');
+ await waitFor((e) => e.type === 'files' && e.paths?.includes('scene.html'), 'the existing socket sees new files');
+ const committed = await api(`/api/projects/${project.id}/history/commit`, { method: 'POST', body: { message: 'After rename' } });
+ assert.equal(committed.status, 200);
+ await waitFor((e) => e.type === 'history', 'the existing socket sees history changes');
+ assert.ok(events.some((e) => e.type === 'history-progress' && e.op === 'commit'));
+ const started = await api(`/api/projects/${project.id}/exports`, { method: 'POST', body: { kind: 'project', as: 'folder' } });
+ assert.equal(started.status, 200);
+ const job = (await started.json()).export;
+ await waitFor((e) => e.type === 'export' && e.job.id === job.id && ['done', 'failed'].includes(e.job.status), 'the existing socket sees the finished export');
+ const completed = events.find((e) => e.type === 'export' && e.job.id === job.id && e.job.status === 'done');
+ assert.ok(completed, 'the export finishes successfully');
+ assert.equal(readFileSync(join(completed.job.outputs[0], 'scene.html'), 'utf8'), '<p>after rename</p>');
+ } finally {
+ await new Promise((done) => { ws.onclose = done; ws.close(); });
+ }
+});
+
test('a film whose clips have no ids comes back with each named after its file, as the preview names them', async () => {
const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Unnamed') } })).json();
writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 1920, h: 1080 }, tracks: [{ clips: [{ src: 'title.html' }, { src: 'title.html', at: 2 }] }] }));
@@ -186,11 +353,11 @@ test('a film whose clips have no ids comes back with each named after its file,
test('rename renames the folder and tells the pages showing it; delete moves it to the Trash and off the list', async () => {
const { project } = await (await api('/api/projects', { method: 'POST', body: { name: 'Draft' } })).json();
- const events = collect(`/api/projects/${project.id}/events`, (e) => e.some((x) => x.type === 'project'));
+ const events = collect(`/api/projects/${project.id}/events`, (e) => e.some((x) => x.type === 'project' && x.project.name === 'Final'));
await new Promise((r) => setTimeout(r, 300));
const renamed = await (await api(`/api/projects/${project.id}`, { method: 'PATCH', body: { name: 'Final' } })).json();
assert.equal(renamed.project.name, 'Final');
- assert.equal((await events).find((e) => e.type === 'project').project.name, 'Final');
+ assert.equal((await events).findLast((e) => e.type === 'project').project.name, 'Final');
assert.ok(existsSync(renamed.project.path));
assert.equal((await api(`/api/projects/${project.id}`, { method: 'DELETE' })).status, 200);
assert.equal((await api(`/api/projects/${project.id}`)).status, 404);
@@ -473,7 +640,7 @@ test('an advertised Studio writes run.json, quits when asked by a key holder, an
assert.equal(existsSync(run), false);
});
-test('a project an app\'s agent is working in is marked so, and is not deleted until it stops', async () => {
+test('a project an app\'s agent is working in is marked so, and is neither renamed nor deleted until it stops', async () => {
let working = [];
const app = await startStudio({ port: 0, openBrowser: () => {}, working: () => working });
try {
@@ -486,9 +653,18 @@ test('a project an app\'s agent is working in is marked so, and is not deleted u
assert.equal(refused.status, 409);
assert.equal((await refused.json()).code, 'agent-running');
assert.ok(existsSync(project.path), 'its folder untouched');
+ const rename = await call(`/api/projects/${project.id}`, 'PATCH', { name: 'Busy renamed' });
+ assert.equal(rename.status, 409);
+ assert.equal((await rename.json()).code, 'agent-running');
+ assert.ok(existsSync(project.path), 'rename leaves the working folder untouched');
+ assert.equal((await (await call(`/api/projects/${project.id}`)).json()).project.path, project.path);
working = [];
+ const renamed = await call(`/api/projects/${project.id}`, 'PATCH', { name: 'Busy renamed' });
+ assert.equal(renamed.status, 200, 'rename succeeds once the agent stops');
+ const moved = (await renamed.json()).project;
+ assert.ok(existsSync(moved.path));
assert.equal((await call(`/api/projects/${project.id}`, 'DELETE')).status, 200, 'once the agent stops');
- assert.ok(!existsSync(project.path), 'to the Trash');
+ assert.ok(!existsSync(moved.path), 'to the Trash');
} finally {
await app.close();
}
diff --git a/packages/openfilm/studio/server/watch.mjs b/packages/openfilm/studio/server/watch.mjs
index 0f29034..9c4553d 100644
--- a/packages/openfilm/studio/server/watch.mjs
+++ b/packages/openfilm/studio/server/watch.mjs
@@ -40,6 +40,7 @@ export function watchFolder(root, send) {
let paths = new Set();
let timer = /** @type {NodeJS.Timeout | null} */ (null);
let lastRev = '';
+ let closed = false;
readProjectFilm(root).then((f) => { lastRev = f.rev; }, () => {});
const flush = async () => {
@@ -51,12 +52,14 @@ export function watchFolder(root, send) {
if (kinds.includes('film')) {
const { rev } = await readProjectFilm(root).catch(() => ({ rev: '' }));
/* the same text written again (an editor's save, Studio's own write echoed back) is no change */
+ if (closed) return;
if (rev && rev !== lastRev) { lastRev = rev; send({ type: 'film', rev }); }
}
if (kinds.includes('files')) send(changed ? { type: 'files', paths: [...changed] } : { type: 'files' });
};
const close = watchTree(root, (name) => {
+ if (closed) return;
if (!name) { pending.add('files'); pending.add('film'); paths = null; }
else {
const rel = name;
@@ -66,7 +69,7 @@ export function watchFolder(root, send) {
}
if (!timer) timer = setTimeout(flush, SETTLE_MS);
});
- return () => { if (timer) clearTimeout(timer); close(); };
+ return () => { closed = true; if (timer) clearTimeout(timer); close(); };
}
/**
@@ -117,29 +120,45 @@ export function watchTree(root, onChange, native = process.platform === 'darwin'
* it with its last.
*/
export function createWatchers() {
- /** @type {Map<string, { close: () => void, listeners: Set<(e: FolderEvent) => void> }>} */
+ /** @typedef {{ root: string, listener: (e: FolderEvent) => void }} Subscription */
+ /** @type {Map<string, { close: () => void, listeners: Set<Subscription> }>} */
const byRoot = new Map();
+ /** @param {string} root @param {Set<Subscription>} listeners */
+ const start = (root, listeners) => ({ listeners, close: watchFolder(root, (e) => { for (const { listener } of listeners) listener(e); }) });
return {
/** @param {string} root @param {(e: FolderEvent) => void} listener */
subscribe(root, listener) {
let entry = byRoot.get(root);
if (!entry) {
- const listeners = new Set();
- entry = { listeners, close: watchFolder(root, (e) => { for (const fn of listeners) fn(e); }) };
+ entry = start(root, new Set());
byRoot.set(root, entry);
}
- entry.listeners.add(listener);
+ const subscription = { root, listener };
+ entry.listeners.add(subscription);
return () => {
- const current = byRoot.get(root);
+ const current = byRoot.get(subscription.root);
if (!current) return;
- current.listeners.delete(listener);
- if (!current.listeners.size) { current.close(); byRoot.delete(root); }
+ current.listeners.delete(subscription);
+ if (!current.listeners.size) { current.close(); byRoot.delete(subscription.root); }
};
},
+ /** A renamed folder: keep its pages subscribed, but watch and read the new path. */
+ move(/** @type {string} */ from, /** @type {string} */ to) {
+ if (from === to) return;
+ const entry = byRoot.get(from);
+ if (!entry) return;
+ entry.close();
+ byRoot.delete(from);
+ const target = byRoot.get(to);
+ target?.close();
+ for (const subscription of target?.listeners ?? []) entry.listeners.add(subscription);
+ for (const subscription of entry.listeners) subscription.root = to;
+ byRoot.set(to, start(to, entry.listeners));
+ },
/** The projects someone is watching now. */
roots: () => [...byRoot.keys()],
/** Tell everyone watching `root` something the folder itself does not say (a new version in its history). */
- emit(/** @type {string} */ root, /** @type {FolderEvent} */ event) { for (const fn of byRoot.get(root)?.listeners ?? []) fn(event); },
+ emit(/** @type {string} */ root, /** @type {FolderEvent} */ event) { for (const { listener } of byRoot.get(root)?.listeners ?? []) listener(event); },
closeAll() { for (const entry of byRoot.values()) entry.close(); byRoot.clear(); },
};
}
diff --git a/packages/openfilm/studio/server/watch.test.mjs b/packages/openfilm/studio/server/watch.test.mjs
index 1df72d3..afde3e7 100644
--- a/packages/openfilm/studio/server/watch.test.mjs
+++ b/packages/openfilm/studio/server/watch.test.mjs
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { mkdirSync, mkdtempSync, renameSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { revOf } from './film.mjs';
@@ -71,3 +71,84 @@ test('watching folder by folder (Linux): a file replaced by a rename is seen eve
close();
}
});
+
+
+test('renamed folders keep their listeners and original unsubscribe functions through repeated moves', async () => {
+ const scratch = mkdtempSync(join(tmpdir(), 'of-watch-rename-'));
+ const from = join(scratch, 'Untitled');
+ const to = join(scratch, 'Named film');
+ const again = join(scratch, 'Final film');
+ mkdirSync(from);
+ writeFileSync(join(from, 'film.html'), 'initial');
+ const watchers = createWatchers();
+ const first = [], second = [];
+ const stopFirst = watchers.subscribe(from, (event) => first.push(event));
+ const stopSecond = watchers.subscribe(from, (event) => second.push(event));
+ try {
+ await settle(600);
+ renameSync(from, to);
+ watchers.move(from, to);
+ assert.deepEqual(watchers.roots(), [to]);
+ await settle(600);
+ first.length = second.length = 0;
+ writeFileSync(join(to, 'film.html'), 'renamed');
+ writeFileSync(join(to, 'scene.html'), '<p>new scene</p>');
+ await settle();
+ for (const seen of [first, second]) {
+ assert.deepEqual(seen.filter((e) => e.type === 'film'), [{ type: 'film', rev: revOf('renamed') }]);
+ assert.ok(seen.some((e) => e.type === 'files' && e.paths?.includes('scene.html')));
+ }
+ const history = { type: 'history' };
+ watchers.emit(to, history);
+ assert.equal(first.at(-1), history);
+ assert.equal(second.at(-1), history);
+ stopFirst();
+ stopFirst(); // closing the same page twice must not stop the other one
+ first.length = second.length = 0;
+ renameSync(to, again);
+ watchers.move(to, again);
+ await settle(600);
+ second.length = 0;
+ writeFileSync(join(again, 'film.html'), 'renamed again');
+ await settle();
+ assert.deepEqual(first, [], 'the first page stays unsubscribed after another rename');
+ assert.deepEqual(second.filter((e) => e.type === 'film'), [{ type: 'film', rev: revOf('renamed again') }]);
+ watchers.emit(from, history);
+ watchers.emit(to, history);
+ assert.ok(!second.some((e) => e.type === 'history'), 'old paths no longer route events');
+ stopSecond();
+ assert.deepEqual(watchers.roots(), [], 'the original final unsubscribe closes the moved watcher');
+ } finally {
+ watchers.closeAll();
+ rmSync(scratch, { recursive: true, force: true });
+ }
+});
+
+test('moving into an already watched path preserves both subscriptions', () => {
+ const scratch = mkdtempSync(join(tmpdir(), 'of-watch-merge-'));
+ const from = join(scratch, 'before'), to = join(scratch, 'after');
+ mkdirSync(from);
+ mkdirSync(to);
+ const watchers = createWatchers();
+ const first = [], second = [];
+ const stopFirst = watchers.subscribe(from, (event) => first.push(event));
+ const stopSecond = watchers.subscribe(to, (event) => second.push(event));
+ try {
+ watchers.move(from, to);
+ watchers.move(to, to);
+ watchers.move(join(scratch, 'not watched'), to);
+ assert.deepEqual(watchers.roots(), [to]);
+ watchers.emit(to, { type: 'history' });
+ assert.equal(first.length, 1);
+ assert.equal(second.length, 1);
+ stopFirst();
+ watchers.emit(to, { type: 'history' });
+ assert.equal(first.length, 1);
+ assert.equal(second.length, 2);
+ stopSecond();
+ assert.deepEqual(watchers.roots(), []);
+ } finally {
+ watchers.closeAll();
+ rmSync(scratch, { recursive: true, force: true });
+ }
+});
diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.ts
index 00e7ab6..87245ec 100644
--- a/packages/openfilm/studio/ui/src/api.ts
+++ b/packages/openfilm/studio/ui/src/api.ts
@@ -3,6 +3,7 @@
* cookie `/open` set; writes are refused from any other origin.
*/
import type { ExportJob } from '@/lib/export-jobs';
+import { studioHost } from '@/lib/host';
import { watchStudioVersion } from '@/lib/studio-version';
/** `working`: an agent of the app's chat is working in it right now (it cannot be deleted meanwhile). */
@@ -130,7 +131,10 @@ export const api = {
newProject: (name?: string) => call<{ project: Project }>('projects', { method: 'POST', json: { name } }).then((r) => r.project),
/** open a folder (its full path) as a project: made one when it is not yet */
openFolder: (path: string) => call<{ project: Project }>('projects', { method: 'POST', json: { path } }).then((r) => r.project),
- rename: (id: string, name: string) => call<{ project: Project }>(p(id), { method: 'PATCH', json: { name } }).then((r) => r.project),
+ rename: (id: string, name: string) => call<{ project: Project }>(p(id), { method: 'PATCH', json: { name } }).then((r) => {
+ studioHost?.projectChanged?.(r.project);
+ return r.project;
+ }),
forget: (id: string) => call<object>(p(id), { method: 'DELETE' }),
film: (id: string) => call<ProjectFilm>(p(id)),
/** the person opened it here: the one `openfilm open` alone comes back to */
@@ -284,7 +288,10 @@ export function projectEvents(id: string, on: (event: FolderEvent) => void): ()
let stream = streams.get(id);
if (!stream) {
const listeners = new Set<(event: FolderEvent) => void>();
- const tell = (event: FolderEvent) => { for (const fn of [...listeners]) fn(event); };
+ const tell = (event: FolderEvent) => {
+ if (listeners.size && event.type === 'project') studioHost?.projectChanged?.(event.project);
+ for (const fn of [...listeners]) fn(event);
+ };
/* back after Studio was away: the film, the files and the history may all have changed meanwhile */
const stop = listen(`${p(id)}/events`, tell, { onBack: () => { tell({ type: 'film', rev: '' }); tell({ type: 'files' }); tell({ type: 'history' }); } });
stream = { stop, listeners };
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index 68818cd..f14523d 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -246,7 +246,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const [undone, setUndone] = React.useState<PersonEdit[]>([]);
const personSteps = React.useRef<readonly Step[]>([]);
const settledEdits = React.useRef(new Set<PersonEdit>());
- const initial = React.useMemo(() => (loaded?.doc && loaded.value ? { value: loaded.value, rev: loaded.rev } : null), [loaded]);
+ /* the film as loaded: a new project name (a rename, or the snapshot a reconnecting page is sent) leaves it as it is */
+ const initial = React.useMemo(() => (loaded?.doc && loaded.value ? { value: loaded.value, rev: loaded.rev } : null), [loaded?.doc, loaded?.value, loaded?.rev]);
React.useEffect(() => { if (initial) lastServerDoc.current = initial.value; }, [initial]);
const film = useFilm(projectId, initial, React.useCallback((value: Film, kind: 'edit' | 'server', head?: string) => {
preview.current?.update(value, head);
@@ -2484,7 +2485,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
React.useEffect(() => studioHost?.tabs?.onPick(() => setProjectsOpen(true)), []);
React.useEffect(() => { if (title) studioHost?.tabs?.report({ title }); }, [title]);
const renameError = (e: unknown, name: string) =>
- toast.showError(e instanceof ApiError && e.status === 409 ? t('projects.renameTaken').replace('{name}', name) : t('project.renameFailed'));
+ toast.showError(e instanceof ApiError && e.body.code === 'agent-running' ? t('projects.agentRunningRename')
+ : e instanceof ApiError && e.body.code === 'export-running' ? t('projects.exportRunningRename')
+ : e instanceof ApiError && e.status === 409 ? t('projects.renameTaken').replace('{name}', name) : t('project.renameFailed'));
const commitTitle = async (draft = titleDraft) => {
setRenaming(false);
const next = draft.trim();
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
index 0be5652..c11da29 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
@@ -173,7 +173,9 @@ function useProjectLibrary(open: boolean) {
} catch (e) {
setProjects(before);
/* a name that is taken: retrying can't help, so the message says what to do instead */
- flash(e instanceof ApiError && e.status === 409 ? t('projects.renameTaken').replace('{name}', name.trim()) : t('project.renameFailed'));
+ flash(e instanceof ApiError && e.body.code === 'agent-running' ? t('projects.agentRunningRename')
+ : e instanceof ApiError && e.body.code === 'export-running' ? t('projects.exportRunningRename')
+ : e instanceof ApiError && e.status === 409 ? t('projects.renameTaken').replace('{name}', name.trim()) : t('project.renameFailed'));
}
}
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index 55d5763..a5ad9f8 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -169,6 +169,8 @@ export const en = {
missing: 'Folder not found',
missingOpen: 'This project’s folder is not there any more: it was moved, renamed or deleted. You can remove it from the list.',
agentRunning: 'Agent running',
+ agentRunningRename: 'An agent is running in this project. Stop it first, then rename the project.',
+ exportRunningRename: 'An export is running or queued for this project. Wait for it to finish or cancel it, then rename the project.',
agentRunningDelete: 'An agent is running in this project. Stop it first, then delete the project.',
agentRunningDeleteMany: 'An agent is running in {n} of these projects. Stop it first, then delete them.',
removeFromList: 'Remove from list',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index a59f8c9..d8420ba 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -168,6 +168,8 @@ export const es: Words = {
missing: 'Carpeta no encontrada',
missingOpen: 'La carpeta de este proyecto ya no está: se movió, se renombró o se eliminó. Puedes quitarlo de la lista.',
agentRunning: 'Agente en marcha',
+ agentRunningRename: 'Hay un agente trabajando en este proyecto. Detenlo antes de cambiarle el nombre al proyecto.',
+ exportRunningRename: 'Este proyecto tiene una exportación en curso o en cola. Espera a que termine o cancélala antes de cambiarle el nombre.',
agentRunningDelete: 'Un agente está trabajando en este proyecto. Detenlo primero y luego elimina el proyecto.',
agentRunningDeleteMany: 'Un agente está trabajando en {n} de estos proyectos. Detenlo primero y luego elimínalos.',
removeFromList: 'Quitar de la lista',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index dda10a8..752b669 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -168,6 +168,8 @@ export const ja: Words = {
missing: 'フォルダーが見つかりません',
missingOpen: 'このプロジェクトのフォルダーが見つかりません。移動、名前の変更、または削除されたようです。リストから削除できます。',
agentRunning: 'エージェント実行中',
+ agentRunningRename: 'このプロジェクトでエージェントが実行中です。先に停止してから、プロジェクト名を変更してください。',
+ exportRunningRename: 'このプロジェクトには実行中または待機中の書き出しがあります。完了を待つかキャンセルしてから、プロジェクト名を変更してください。',
agentRunningDelete: 'このプロジェクトでエージェントが実行中です。先に停止してから削除してください。',
agentRunningDeleteMany: '{n} 件のプロジェクトでエージェントが実行中です。先に停止してから削除してください。',
removeFromList: 'リストから削除',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 87bfd1d..30fa962 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -168,6 +168,8 @@ export const ko: Words = {
missing: '폴더를 찾을 수 없음',
missingOpen: '이 프로젝트의 폴더가 더 이상 없습니다. 이동되었거나, 이름이 바뀌었거나, 삭제되었습니다. 목록에서 제거할 수 있습니다.',
agentRunning: '에이전트 실행 중',
+ agentRunningRename: '이 프로젝트에서 에이전트가 실행 중입니다. 먼저 중지한 다음 프로젝트 이름을 변경하세요.',
+ exportRunningRename: '이 프로젝트에 실행 중이거나 대기 중인 내보내기가 있습니다. 완료될 때까지 기다리거나 취소한 다음 프로젝트 이름을 변경하세요.',
agentRunningDelete: '이 프로젝트에서 에이전트가 실행 중입니다. 먼저 중지한 다음 프로젝트를 삭제하세요.',
agentRunningDeleteMany: '{n}개 프로젝트에서 에이전트가 실행 중입니다. 먼저 중지한 다음 삭제하세요.',
removeFromList: '목록에서 제거',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 10b7e61..05f11bf 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -169,6 +169,8 @@ export const zhCN: Words = {
missing: '找不到文件夹',
missingOpen: '此项目的文件夹已不在原处:它被移动、重命名或删除了。你可以将它从列表中移除。',
agentRunning: 'Agent 运行中',
+ agentRunningRename: 'Agent 正在这个项目里运行,请先停止它,再重命名项目。',
+ exportRunningRename: '这个项目有正在进行或排队中的导出。请等待导出完成或取消后,再重命名项目。',
agentRunningDelete: 'Agent 正在这个项目里运行,请先停止它,再删除项目。',
agentRunningDeleteMany: '其中 {n} 个项目里有 Agent 正在运行,请先停止,再删除。',
removeFromList: '从列表中移除',
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index f8bb03f..21d890f 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -12,6 +12,9 @@ export interface HostTab { id: string; projectId: string; title: string; active:
/** Settings → Developer, as the app keeps it (`developer` below). */
export interface HostDeveloper { logs: boolean; changes: boolean }
+/** The project identity and current folder shared with an embedded chat. */
+export interface HostProject { id: string; name: string; path: string }
+
export interface StudioHost {
/** the version of this interface the app speaks */
version: 1;
@@ -19,6 +22,8 @@ export interface StudioHost {
settings?: { onOpen: (listener: () => void) => () => void };
/** the app's name, for the person */
name?: string;
+ /** A successful rename, here or in another page: the chat keeps its identity but uses the new name and folder. */
+ projectChanged?: (project: HostProject) => void;
/**
* The window has no title bar of its own: Studio's top bar is where the window is dragged, and `inset` pixels at its
* left (macOS) and `insetRight` at its right (Windows) are left free for the window's controls. `onChange` tells of a