Files
openmotion/tests/projects.test.ts
Dery Ferdika 6a701566fc fix(workspace): one filename rule for project writes and import (#570)
* fix(workspace): one filename rule for project writes and import

Project archive import rejects Windows device names, trailing dots or spaces and names that collide after NFC and lowercase folding, because a ZIP assembled on Linux can otherwise collapse into one file on Windows or a default macOS volume. Writes had no such rule: projectPath rejected separators, control characters, dot-prefixed segments and the ignored build folders, and nothing else.

Two failures followed from that asymmetry. A write batch containing con.html passed validation and then failed inside the transaction when the filesystem refused the reserved name. A batch containing both A.css and a.css reported two changed files and two hashes in the revision, but on a case-insensitive volume only one file existed, so one edit was silently lost.

Review follow-ups shaped the final version:

- The portable-name rule now lives once, in shared/project-name.ts, and both workspace writes and the ZIP reader use it. It rejects reserved device names and trailing dots or spaces on every platform, so a Linux-authored project can no longer export an archive that import refuses; otherwise the asymmetry simply moved to the export side.
- Only case and NFC folding is a filesystem property, so it stays conditional. Callers pass the fold policy, and the predicate and duplicate helper are exported with an explicit parameter instead of reading the platform inside, which lets the Linux suite cover both branches.
- The entry-file guard keeps exact paths. Duplicate detection folds, but "does this batch create index.html" now compares exact names, so a batch of Index.html no longer passes the guard that a case-insensitive volume would otherwise satisfy.

Validation: tests/projects.test.ts passes 9/9 on Windows, covering reserved names and trailing dots on any platform, the importAsset target guard, the folded duplicate rejection, the differently cased entry file, and a normal write that reads back. tests/project-archive.test.ts gains two cases in a file the distribution lane already runs: the shared predicate and duplicate helper in both fold modes, and a ZIP containing con.html being refused by readProjectZip. The archive suite and tests/phase1.test.ts keep their two pre-existing Windows failures (symlink creation needs a privilege this environment does not grant), and npm run check passes.

* test: exercise project filename guards in the archive CI lane

---------

Co-authored-by: lefarcen <935902669@qq.com>
2026-11-18 17:41:37 +08:00

180 lines
13 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { startServer } from '../server.ts';
import { WorkspaceStore, createBlankProject } from '../workspace.ts';
import { inspectProject, pluginRoot, startStudio } from '../hyperframes.ts';
import { fixture } from './fixtures.ts';
test('default project labels migrate while explicit names survive reopening', () => fixture(async store => {
assert.equal(store.projectCatalog().projects[0].titleKey, 'OpenMotion Sample Video');
for (const title of ['初始工程', 'OpenMotion 示例短片']) {
const otherId = crypto.randomUUID();
await writeFile(path.join(store.directory, 'projects.json'), JSON.stringify({ activeId: 'project', projects: [
{ id: 'project', title }, { id: otherId, title },
] }));
const migrated = store.projectCatalog();
assert.equal(migrated.projects[0].title, 'OpenMotion 示例短片');
assert.equal(migrated.projects[0].titleKey, 'OpenMotion Sample Video');
assert.equal(migrated.projects[1].title, title);
assert.equal(migrated.projects[1].titleKey, undefined);
await store.renameProject('project', title);
const reopened = new WorkspaceStore(store.directory).projectCatalog().projects[0];
assert.equal(reopened.title, title);
assert.equal(reopened.titleKey, null);
}
await writeFile(path.join(store.directory, 'projects.json'), JSON.stringify({ activeId: 'project', projects: [{ id: 'project', title: 'My own film' }] }));
assert.deepEqual(store.projectCatalog().projects[0], { id: 'project', title: 'My own film' });
}, false));
for (const entry of ['sidebar', 'direct preview'] as const) {
test(`missing initial project opens the bundled default through ${entry} without overwriting other projects`, { timeout: 60_000 }, () => fixture(async store => {
const id = crypto.randomUUID(), directory = store.projectDirectoryFor(id);
await createBlankProject(directory, pluginRoot, 'Agent project');
await store.selectProject(id, { id, title: 'Agent project' });
const before = await readFile(path.join(directory, 'index.html'), 'utf8');
assert.equal((await store.forProject('project').get()).project, null);
const running = await startServer(store, 0);
try {
const origin = `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;
const stale = await fetch(origin + '/motion-api/projects/project/open', {
method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' },
body: JSON.stringify({ expectedRevision: '0'.repeat(64), expectedProjectId: id }),
});
assert.equal(stale.status, 409);
assert.equal((await store.forProject('project').get()).project, null, 'stale switches cannot create defaults');
if (entry === 'sidebar') await running.openProject('project');
else await running.ensureStudio('project');
const initial = store.forProject('project');
const file = path.join(initial.projectDirectory, 'index.html');
const withoutStampedIds = (source: string) => source.replace(/ data-hf-id="[^"]*"/g, '');
assert.equal(withoutStampedIds(await readFile(file, 'utf8')), await readFile(path.join(pluginRoot, 'template-library/openmotion-welcome/index.html'), 'utf8'));
assert.ok((await initial.files()).some(file => file.path === 'compositions/intro.html'));
assert.equal(withoutStampedIds(await readFile(path.join(directory, 'index.html'), 'utf8')), before);
if (entry === 'direct preview') assert.equal(store.projectId, id, 'preview warming retains active project ownership');
const edited = (await readFile(file, 'utf8')).replace('OpenMotion Welcome', 'My saved title');
await writeFile(file, edited);
await running.openProject(id);
await running.openProject('project');
assert.equal(await readFile(file, 'utf8'), edited, 'reopening retains existing edits');
} finally { await running.close(); }
}, false));
}
test('default initialization refuses a partial initial project without replacing its files', () => fixture(async store => {
await mkdir(store.projectDirectoryFor('project'), { recursive: true });
const note = path.join(store.projectDirectoryFor('project'), 'note.txt');
await writeFile(note, 'Keep this unfinished project');
await assert.rejects(store.initialize(pluginRoot), /已有文件但缺少 index.html/);
assert.equal(await readFile(note, 'utf8'), 'Keep this unfinished project');
}, false));
test('project sessions create blank editable projects, isolate uploads and restore the selected project after restart', { timeout: 180_000 }, () => fixture(async store => {
let running = await startServer(store, 0);
const baseUrl = () => `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;
async function mutate(route: string, body: unknown, method = 'POST') {
return fetch(baseUrl() + route, { method, headers: { Origin: baseUrl(), 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
}
async function create(title?: string, instruction?: string) {
const state = await store.status();
const response = await mutate('/motion-api/projects', { title, instruction, expectedRevision: state.revision, expectedProjectId: state.projectId });
assert.equal(response.status, 201, await response.clone().text());
return response.json();
}
try {
const initial = await store.get();
const first = await create('素材剪辑 <一>', ' 做一个产品演示\n保留字幕 ');
const conversationUrl = `/motion-api/projects/${first.projectId}/conversation`;
const conversation = await (await fetch(baseUrl() + conversationUrl)).json();
assert.equal(conversation.messages[0].content, '做一个产品演示\n保留字幕');
const beforeMessage = (await store.get()).revision;
const message = { id: crypto.randomUUID(), content: '再缩短到 12 秒' };
for (let retry = 0; retry < 2; retry++) assert.equal((await mutate(conversationUrl, message)).status, 201);
assert.equal((await store.conversation(first.projectId)).messages.length, 2, 'an uncertain network retry must not duplicate the request');
assert.equal((await store.get()).revision, beforeMessage, 'conversation metadata is not a video edit');
for (const content of ['', 'a'.repeat(8001), 123]) assert.equal((await mutate(conversationUrl, { id: crypto.randomUUID(), content })).status, 400);
assert.equal((await mutate(conversationUrl, { id: '-'.repeat(36), content: 'Invalid message' })).status, 400);
const firstDirectory = store.projectDirectory;
assert.notEqual(first.projectId, 'project');
assert.match((await store.get()).project!.html!, /素材剪辑 &lt;一&gt;/);
assert.doesNotMatch((await store.get()).project!.html!, /class="clip"|compositions\//);
assert.equal((await inspectProject(pluginRoot, firstDirectory, 'lint')).exitCode, 0);
assert.equal((await store.get()).project!.files.some(file => file.path === 'assets/gsap.min.js'), true);
const upload = new FormData();
upload.append('files', new Blob([Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==', 'base64')], { type: 'image/png' }), 'clip.png');
const uploaded = await fetch(`${baseUrl()}/api/projects/${first.projectId}/upload?dir=assets`, { method: 'POST', headers: { Origin: baseUrl() }, body: upload });
assert.equal(uploaded.status, 201, await uploaded.clone().text());
assert.ok((await readdir(path.join(firstDirectory, 'assets'))).some(name => name.endsWith('.png')));
const firstSource = (await store.get()).project!.html!;
await store.writeFiles((await store.get()).revision, [{ path: 'notes.md', content: 'Only in project one' }]);
const second = await create();
assert.deepEqual((await store.conversation(second.projectId)).messages, []);
assert.equal((await store.conversation(first.projectId)).messages[1].content, message.content);
assert.notEqual(first.projectId, second.projectId);
assert.equal((await store.get()).project!.files.some(file => file.path.endsWith('.png') || file.path === 'notes.md'), false);
const catalog = new WorkspaceStore(store.directory).projectCatalog();
assert.equal(catalog.projects.length, 3);
assert.equal(catalog.activeId, second.projectId);
assert.ok(catalog.projects.every(item => item.id === 'project' || item.openedAt));
// An older page still resolves its own directory; writes still require its file version.
for (const method of ['GET', 'PUT']) {
const stale = await fetch(`${baseUrl()}/api/projects/${first.projectId}/files/index.html`, { method, headers: { Origin: baseUrl(), 'Content-Type': 'text/html' }, ...(method === 'PUT' ? { body: firstSource } : {}) });
assert.equal(stale.status, method === 'GET' ? 200 : 428);
}
assert.equal((await mutate('/motion-api/projects', { expectedRevision: initial.revision })).status, 409);
assert.equal((await mutate('/motion-api/projects', { expectedRevision: (await store.get()).revision, expectedProjectId: first.projectId })).status, 409);
for (const title of ['', ' ', 'a'.repeat(101), 12]) assert.equal((await mutate('/motion-api/projects', { title, expectedRevision: (await store.get()).revision })).status, 400);
assert.equal(store.projectCatalog().projects.length, 3);
assert.equal((await readdir(path.join(store.directory, 'projects'))).length, 2);
assert.equal((await mutate(`/motion-api/projects/${first.projectId}`, { title: ' 已整理素材 ' }, 'PATCH')).status, 200);
assert.equal((await mutate(`/motion-api/projects/${first.projectId}`, { title: '' }, 'PATCH')).status, 400);
assert.equal(store.projectCatalog().activeId, second.projectId);
assert.equal((await mutate(`/motion-api/projects/${first.projectId}/open`, { expectedRevision: (await store.get()).revision })).status, 200);
assert.equal((await store.readFile('notes.md')).content, 'Only in project one');
assert.equal((await store.get()).project!.html, firstSource);
assert.equal((await store.status()).projectTitle, '已整理素材');
await running.close();
running = await startServer(new WorkspaceStore(store.directory), 0);
assert.equal((await (await fetch(baseUrl() + conversationUrl)).json()).messages.length, 2);
assert.equal((await (await fetch(baseUrl() + '/motion-api/project/status')).json()).projectId, first.projectId);
assert.equal((await (await fetch(baseUrl() + '/__hyperframes_config')).json()).projectDir, firstDirectory);
assert.equal(await readFile(path.join(store.directory, 'project/index.html'), 'utf8'), initial.project!.html);
} finally { await running.close(); }
}));
test('native project service avoids Fetch-restricted ports after repeated switches', { timeout: 30_000 }, () => fixture(async store => {
const studio = await startStudio(pluginRoot, store.projectDirectory, path.join(store.directory, 'studio.log'), 4190);
try {
assert.ok(Number(new URL(studio.url).port) >= 20_000);
const response = await fetch(new URL('/__hyperframes_config', studio.url));
assert.equal(response.status, 200);
assert.equal((await response.json()).projectDir, store.projectDirectory);
} finally { await studio.close(); }
}));
test('project writes reject portable-name violations on every platform', () => fixture(async store => {
const initial = await store.get();
await assert.rejects(store.writeFiles(initial.revision, [{ path: 'con.html', content: 'reserved' }]), /路径无效/);
await assert.rejects(store.writeFiles(initial.revision, [{ path: 'notes. ', content: 'trailing' }]), /路径无效/);
const source = path.join(store.directory, 'source.png');
await writeFile(source, 'png-bytes');
await assert.rejects(store.importAsset(initial.revision, source, 'assets/nul.png'), /路径无效/);
const written = await store.writeFiles(initial.revision, [{ path: 'notes.md', content: 'kept' }]);
assert.equal((await store.readFile('notes.md')).content, 'kept');
assert.ok(written.revision);
}));
test('case-folded duplicates and entry names are judged separately', () => fixture(async store => {
const initial = await store.get();
if (['win32', 'darwin'].includes(process.platform)) {
await assert.rejects(store.writeFiles(initial.revision, [{ path: 'A.css', content: 'a' }, { path: 'a.css', content: 'b' }]), /重复文件/);
} else {
const written = await store.writeFiles(initial.revision, [{ path: 'A.css', content: 'a' }, { path: 'a.css', content: 'b' }]);
assert.ok(written.revision);
}
}));
test('a differently cased entry file does not satisfy the create guard', { skip: !['win32', 'darwin'].includes(process.platform) && 'case-insensitive file systems only' }, () => fixture(async store => {
const initial = await store.get();
await assert.rejects(store.writeFiles(initial.revision, [{ path: 'Index.html', content: '<html></html>' }]), /index\.html/);
}, false));