Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Keep local projects usable when Windows file access fails

shinshin8631e0da8ee016
diff --git a/README.ja.md b/README.ja.md
index 4b380fb..aa64ef0 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -17,6 +17,12 @@ npm run dev
ターミナルに表示された URL(例: `http://127.0.0.1:5173/`)をブラウザで開くと、同梱のサンプル(チャイナドレスのミコ)が表示されます。左の一覧からパーツを選び、画像の上の点をドラッグすると、右のプレビューに結果が反映されます。サンプルは読み取り専用なので、編集すると「コピーして編集を続ける」ボタンが出ます。押すと自分用のコピーで作業を続けられます。
+### Windows で使うとき
+
+リポジトリの取得には、できれば `git clone` を使ってください。ZIP を使う場合は、展開する前にエクスプローラーで ZIP のプロパティを開き、ブロック解除の項目があれば解除してください。
+
+エージェントに作業を頼む前に、自分の Windows アカウントで `projects/` フォルダを作っておいてください。別のアカウントやサンドボックス内で動くエージェントが作ったフォルダは、アクセス権限の違いでエディタから読めないことがあります。読めない場合は、フォルダの「プロパティ → セキュリティ」で、自分のアカウントにプロジェクト全体へのアクセス権限を付け直してください。中のファイルやサブフォルダにも権限が引き継がれるように設定します。
+
## 使い方の流れ
自分のイラストからアバターを作る手順は4つです。1と4はこのリポジトリで動かすコーディングエージェント(Claude Code または Codex)が行い、2と3はエディタで行います。
diff --git a/README.md b/README.md
index 1c0fd3f..1bec742 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,17 @@ the bundled sample, Miko in a qipao. Pick a part on the left, drag its dots on t
watch the preview on the right. The sample is read-only; when you change it, choose
**Copy and keep editing** to continue in your own copy.
+### Using Windows
+
+Use `git clone` to download the repository when possible. If you use a ZIP, open its
+Properties in File Explorer and select **Unblock**, if shown, before extracting it.
+
+Create `projects/` yourself under your Windows account before asking an agent to work in it.
+Folders created by another account or an agent running in a sandbox can have permissions
+that prevent the editor from reading them. If a project cannot be read, use the folder's
+**Properties → Security** settings to grant your account access to the whole project,
+including its files and subfolders through permission inheritance.
+
## How it works
Making an avatar from your own illustration takes four steps. Steps 1 and 4 are done by a
diff --git a/e2e/project-errors.spec.ts b/e2e/project-errors.spec.ts
new file mode 100644
index 0000000..9c524cd
--- /dev/null
+++ b/e2e/project-errors.spec.ts
@@ -0,0 +1,79 @@
+import { expect, test } from '@playwright/test';
+
+const messages = {
+ en: { unreadable: 'Cannot read this project.', missing: 'Required files are missing.', read: 'A file or folder could not be read.' },
+ ja: { unreadable: 'このプロジェクトは読み取れません。', missing: '必要なファイルが足りません。', read: 'ファイルまたはフォルダを読み取れませんでした。' },
+ zh: { unreadable: '无法读取此项目。', missing: '缺少必需文件。', read: '无法读取文件或文件夹。' },
+};
+
+for (const language of ['en', 'ja', 'zh'] as const) {
+ test(`unreadable projects remain visible and disabled in the list and history (${language})`, async ({ page }, testInfo) => {
+ await page.addInitScript(language => {
+ localStorage.setItem('mesh-avatar-language', language);
+ localStorage.setItem('mesh-avatar-guide-seen', '1');
+ localStorage.setItem('mesh-avatar-recent-projects', JSON.stringify([{ id: 'server:locked-project', name: 'locked-project', serverName: 'locked-project', relativePath: 'projects/locked-project', kind: 'server', lastOpened: '2026-01-01T00:00:00Z' }]));
+ }, language);
+ const opened: string[] = [];
+ page.on('request', request => { if (request.url().includes('/__studio/projects/locked-project/')) opened.push(request.url()); });
+ await page.route('**/__studio/projects', async route => {
+ const response = await route.fetch();
+ const sample = (await response.json()).filter((entry: { name: string }) => entry.name === 'sample-miko-qipao');
+ await route.fulfill({ json: [...sample, { name: 'locked-project', relativePath: 'projects/locked-project', readOnly: false, error: { code: 'EACCES', path: 'projects/locked-project/rig.json' } }] });
+ });
+ await page.goto('/');
+ await page.locator('.open-menu > summary').click();
+ const blocked = page.getByTestId('project-locked-project');
+ await expect(blocked).toBeDisabled();
+ await expect(blocked).toContainText(messages[language].unreadable);
+ await expect(blocked).toContainText('EACCES');
+ await expect(blocked).toContainText('projects/locked-project/rig.json');
+ await expect(blocked).not.toContainText('Invalid Date');
+ await expect(page.getByTestId('recent-server:locked-project')).toBeDisabled();
+ expect(opened).toEqual([]);
+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem('mesh-avatar-recent-projects')!).length)).toBe(1);
+ await testInfo.attach('project-menu', { body: await page.locator('.project-menu').screenshot(), contentType: 'image/png' });
+ const sample = page.getByTestId('project-sample-miko-qipao');
+ if (await sample.count()) {
+ await expect(sample).toBeEnabled();
+ await sample.click();
+ await expect(page.getByTestId('project-location')).toBeVisible();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ }
+ });
+
+ test(`folder picker distinguishes missing files from unreadable files (${language})`, async ({ page }, testInfo) => {
+ await page.addInitScript(language => {
+ localStorage.setItem('mesh-avatar-language', language);
+ localStorage.setItem('mesh-avatar-guide-seen', '1');
+ let attempt = 0;
+ Object.defineProperty(window, 'showDirectoryPicker', { value: async () => {
+ const current = attempt++;
+ return { name: 'locked-project', async *values() {
+ if (current === 0) return;
+ yield { kind: 'file', name: 'source.png', getFile: async () => new File(['image'], 'source.png') };
+ yield { kind: 'directory', name: 'built', async *values() {
+ yield { kind: 'file', name: 'layers.json', getFile: async () => {
+ if (current === 1) throw new DOMException('File locked', 'NotReadableError');
+ const file = new File(['{"layers":{}}'], 'layers.json');
+ Object.defineProperty(file, 'arrayBuffer', { value: async () => { throw new DOMException('File locked', 'NotReadableError'); } });
+ return file;
+ } };
+ } };
+ } };
+ } });
+ }, language);
+ await page.goto('/');
+ const alert = page.locator('p.error[role="alert"]');
+ for (let attempt = 0; attempt < 3; attempt++) {
+ await page.locator('.open-menu > summary').click();
+ await page.locator('.project-menu > button').first().click();
+ await expect(alert).toContainText(attempt === 0 ? messages[language].missing : messages[language].read);
+ if (attempt > 0) {
+ await expect(alert).not.toContainText(messages[language].missing);
+ await expect(alert).toContainText('built/layers.json');
+ }
+ await expect(page.getByTestId('project-location')).toHaveCount(0);
+ }
+ await testInfo.attach('folder-read-error', { body: await alert.screenshot(), contentType: 'image/png' });
+ });
+}
diff --git a/src/editor/App.tsx b/src/editor/App.tsx
index 577ea03..13eca10 100644
--- a/src/editor/App.tsx
+++ b/src/editor/App.tsx
@@ -6,7 +6,8 @@ import type { Rig } from '../rig/types';
import { parseRig, validateRig } from '../rig/validate';
import { Preview } from './Preview';
import { RigHistory, downloadRig } from './history';
-import { openProjectFolder, openLocalProject, copySample, localProjects, projectAction, sampleImagesAvailable, repositoryContext, runProjectJob, ProjectJobError, type ProjectJob, type LocalProject } from './project';
+import { openProjectFolder, openLocalProject, copySample, localProjects, projectAction, sampleImagesAvailable, repositoryContext, runProjectJob, ProjectJobError, type ProjectJob, type LocalProject, type LocalProjectEntry } from './project';
+import { folderOpenError } from './folder-errors';
import { layerSignature } from './stale';
import { RigFields } from './RigFields';
import { GROUPS } from './parts';
@@ -23,7 +24,7 @@ import { readRecent, addRecent, saveRecent, REOPEN_KEY, pickDirectory, hasDirect
keepDirectory, restoreDirectory, forgetDirectory, clearDirectories, type RecentProject, type ProjectDirectory } from './recent-projects';
import './style.css';
-type EditorError = { kind: 'invalidRig' | 'invalidFolder' | 'invalidValue' | 'saveError' | 'revealError' | 'copyError' | 'continueError'; paths: string[] };
+type EditorError = { kind: 'invalidRig' | 'invalidFolder' | 'missingFolderFiles' | 'unreadableFolder' | 'unreadableProject' | 'invalidValue' | 'saveError' | 'revealError' | 'copyError' | 'continueError'; paths: string[] };
function errorPaths(value: string) { return [...new Set(value.match(/rig(?:\.[\w]+|\[\d+\])+/g) ?? [])]; }
export function App() { return <I18nProvider><Workspace /></I18nProvider>; }
@@ -41,7 +42,7 @@ function Workspace() {
const objectUrls = useRef<string[]>([]);
const [sourceUrl, setSourceUrl] = useState('');
const [assets, setAssets] = useState<Record<string, string> | undefined>(undefined);
- const [projects, setProjects] = useState<LocalProject[] | null>(null);
+ const [projects, setProjects] = useState<LocalProjectEntry[] | null>(null);
const [localProject, setLocalProject] = useState<LocalProject | null>(null);
const [pickedName, setPickedName] = useState('');
const [notice, setNotice] = useState<{ key: 'savedTo' | 'missingRecent' | 'variantsReloaded' | 'reloadFailed'; path?: string } | null>(null);
@@ -80,7 +81,7 @@ function Workspace() {
const latest = available[0];
if (latest.kind === 'server') {
const project = list?.find(item => item.name === latest.serverName);
- if (project) { projectOpened.current = true; await openLocal(project, true); }
+ if (project && !project.error) { projectOpened.current = true; await openLocal(project, true); }
} else if (latest.hasHandle) {
const handle = await restoreDirectory(latest.id);
if (!active || !handle) return;
@@ -160,10 +161,11 @@ function Workspace() {
remember({ id, name, kind: 'folder', relativePath: name, lastOpened: new Date().toISOString(), hasHandle });
if (openMenu.current) openMenu.current.open = false;
return true;
- } catch { setError({ kind: 'invalidFolder', paths: [] }); return false; }
+ } catch (error) { setError(folderOpenError(error)); return false; }
};
- const openLocal = async (entry: LocalProject, automatic = false) => {
+ const openLocal = async (entry: LocalProjectEntry, automatic = false) => {
if (jobRef.current) return;
+ if (entry.error) { setError({ kind: 'unreadableProject', paths: [entry.error.code, entry.error.path] }); return; }
setOpening(true);
try {
const project = await openLocalProject(entry);
@@ -226,7 +228,7 @@ function Workspace() {
if (openMenu.current) openMenu.current.open = false;
if (folder && hasDirectoryPicker()) {
try { const handle = await pickDirectory(); await openFolder(await directoryFiles(handle), handle); }
- catch (error) { if (!(error instanceof DOMException && error.name === 'AbortError')) setError({ kind: 'invalidFolder', paths: [] }); }
+ catch (error) { if (!(error instanceof DOMException && error.name === 'AbortError')) setError(folderOpenError(error)); }
} else (folder ? folderInput : fileInput).current!.click();
};
const openRecent = async (entry: RecentProject) => {
@@ -246,6 +248,7 @@ function Workspace() {
await openFolder(await directoryFiles(handle), handle); return;
} catch (error) {
if (error instanceof DOMException && error.name === 'NotFoundError') { removeRecent(entry.id); setNotice({ key: 'missingRecent', path: entry.name }); return; }
+ setError(folderOpenError(error)); return;
}
}
}
@@ -257,7 +260,7 @@ function Workspace() {
onReopen={value => { setReopen(value); savePreference(REOPEN_KEY, value ? '1' : '0'); }} />;
const reloadInPlace = async (entry: LocalProject) => {
const list = await localProjects(), fresh = list?.find(item => item.name === entry.name);
- if (!fresh) throw new ProjectJobError('toolFailed', t.reloadFailed);
+ if (!fresh || fresh.error) throw new ProjectJobError('toolFailed', t.reloadFailed);
const loaded = await openLocalProject(fresh);
// Keep the canvas mounted, its view, selection and the existing undo/redo stack.
history.replacePresent(loaded.rig!); setRig(history.present); setDragStale(null);
@@ -276,7 +279,7 @@ function Workspace() {
if (!active || generation !== revision || jobRef.current) return;
try {
const list = await localProjects(), fresh = list?.find(item => item.name === entry.name);
- if (!fresh) throw new Error('Project unavailable');
+ if (!fresh || fresh.error) throw new Error('Project unavailable');
const loaded = await openLocalProject(fresh);
if (!active || generation !== revision || jobRef.current) return;
// Sprite changes must not discard unsaved outlines, selection, view or undo history.
@@ -306,14 +309,14 @@ function Workspace() {
} finally { jobRef.current = null; setJob(null); }
};
const sampleEditing = !!localProject?.readOnly || (!localProject && !pickedName);
- const listedProject = !localProject && pickedName ? projects?.find(project => !project.readOnly && project.name === pickedName && project.relativePath.startsWith('projects/')) : undefined;
+ const listedProject = !localProject && pickedName ? projects?.find(project => !project.error && !project.readOnly && project.name === pickedName && project.relativePath.startsWith('projects/')) : undefined;
const continueEditing = async () => {
if (jobRef.current || saving || opening) return;
const edited = structuredClone(history.present), previousSignature = builtSignature;
jobRef.current = 'transfer'; setOpening(true); setError(null);
try {
const entry = sampleEditing ? await copySample(edited) : listedProject;
- if (!entry) throw new Error('Project unavailable');
+ if (!entry || entry.error) throw new Error('Project unavailable');
const loaded = await openLocalProject(entry);
// The copied layers still reflect the sample's original outlines, not the edited rig.
setBuiltSignature(sampleEditing ? previousSignature : layerSignature(loaded.rig!));
@@ -340,10 +343,10 @@ function Workspace() {
<div className="project-menu">{recentControl}<p className="project-help">{t.projectHelp}</p>
{projects && <div className="project-list" aria-label={t.localProjects}>
{projects.length === 0 && <p>{t.noProjects}</p>}
- {projects.map(project => <button key={project.name} disabled={opening} data-testid={`project-${project.name}`} onClick={() => { void openLocal(project); }}>
+ {projects.map(project => <button key={project.name} className={project.error ? 'unreadable-project' : undefined} disabled={opening || !!project.error} data-testid={`project-${project.name}`} onClick={() => { void openLocal(project); }}>
<strong>{project.readOnly ? t.sampleProject : project.name}</strong><small>{project.relativePath}</small>
- <small>{t.updated}: {new Date(project.updatedAt).toLocaleString(locale)}
- {project.hasSprites && <span className="badge">{t.drawnVariants}</span>}{project.readOnly && <span className="badge">{t.readOnly}</span>}</small>
+ <small>{project.error ? <>{t.unreadableProject} ({project.error.code}) · {project.error.path}</> : <>{t.updated}: {new Date(project.updatedAt).toLocaleString(locale)}
+ {project.hasSprites && <span className="badge">{t.drawnVariants}</span>}{project.readOnly && <span className="badge">{t.readOnly}</span>}</>}</small>
</button>)}
</div>}
<button onClick={() => { void chooseFile(true); }}>{t.openFolder}</button><button onClick={() => { void chooseFile(false); }}>{t.openRig}</button>
diff --git a/src/editor/RecentProjects.tsx b/src/editor/RecentProjects.tsx
index 0a96ba4..7909055 100644
--- a/src/editor/RecentProjects.tsx
+++ b/src/editor/RecentProjects.tsx
@@ -1,9 +1,9 @@
import { useI18n } from './i18n';
-import type { LocalProject } from './project';
+import type { LocalProjectEntry } from './project';
import type { RecentProject } from './recent-projects';
export function RecentProjects({ recent, projects, reopen, onOpen, onRemove, onClear, onReopen }: {
- recent: RecentProject[]; projects: LocalProject[] | null; reopen: boolean;
+ recent: RecentProject[]; projects: LocalProjectEntry[] | null; reopen: boolean;
onOpen(entry: RecentProject): void; onRemove(id: string): void; onClear(): void; onReopen(value: boolean): void;
}) {
const { t, locale } = useI18n();
@@ -12,10 +12,12 @@ export function RecentProjects({ recent, projects, reopen, onOpen, onRemove, onC
{recent.length === 0 && <p className="recent-empty">{t.noRecent}</p>}
<div className="recent-list">{recent.map(entry => {
const browse = entry.kind === 'folder' ? !entry.hasHandle : !projects?.some(item => item.name === entry.serverName);
+ const failure = entry.kind === 'server' ? projects?.find(item => item.name === entry.serverName)?.error : undefined;
return <div key={entry.id} className="recent-row">
- <button data-testid={`recent-${entry.id}`} onClick={() => onOpen(entry)}>
+ <button data-testid={`recent-${entry.id}`} className={failure ? 'unreadable-project' : undefined} disabled={!!failure} onClick={() => onOpen(entry)}>
<strong>{entry.serverName === 'sample-miko-qipao' ? t.sampleProject : entry.name}</strong>
<small>{entry.relativePath} · {new Date(entry.lastOpened).toLocaleString(locale)}</small>
+ {failure && <small>{t.unreadableProject} ({failure.code}) · {failure.path}</small>}
{browse && <small>{t.browseAgain}</small>}
</button><button className="remove-recent" aria-label={`${t.removeRecent} ${entry.name}`} onClick={() => onRemove(entry.id)}>×</button>
</div>;
diff --git a/src/editor/folder-errors.ts b/src/editor/folder-errors.ts
new file mode 100644
index 0000000..44bd345
--- /dev/null
+++ b/src/editor/folder-errors.ts
@@ -0,0 +1,12 @@
+export class FolderOpenError extends Error {
+ constructor(public kind: 'missingFolderFiles' | 'unreadableFolder', public paths: string[] = []) { super(kind); }
+}
+
+export function folderOpenError(error: unknown): { kind: 'missingFolderFiles' | 'unreadableFolder' | 'invalidFolder'; paths: string[] } {
+ if (error instanceof FolderOpenError) return error;
+ if (error instanceof DOMException) {
+ if (['NotReadableError', 'NotAllowedError', 'SecurityError'].includes(error.name)) return { kind: 'unreadableFolder', paths: [] };
+ if (error.name === 'NotFoundError') return { kind: 'missingFolderFiles', paths: [] };
+ }
+ return { kind: 'invalidFolder', paths: [] };
+}
diff --git a/src/editor/i18n-zh.ts b/src/editor/i18n-zh.ts
index 70f734e..ae61f80 100644
--- a/src/editor/i18n-zh.ts
+++ b/src/editor/i18n-zh.ts
@@ -36,7 +36,10 @@ export const uiZh = {
emptyHelp: '从“打开项目”的列表中选择项目,或选择项目文件夹。',
newProjectHelp: '想从新的插画开始?让编程助手按照制作指南准备一个项目。',
invalidRig: '无法打开绑定配置。请检查 JSON 格式及以下字段:',
- invalidFolder: '无法打开此文件夹。请确保包含 source.png、rig.json、layers.json 和所有拆分图层图片。',
+ invalidFolder: '无法打开此文件夹。请检查 rig.json 和 layers.json 的内容是否有效。',
+ missingFolderFiles: '缺少必需文件。请确保包含 source.png、layers.json 和所有拆分图层图片。',
+ unreadableFolder: '无法读取文件或文件夹。请检查访问权限,或是否正被其他应用占用,然后重试。',
+ unreadableProject: '无法读取此项目。请检查访问权限,或文件是否正被占用。',
invalidValue: '请检查以下字段的数值:', point: '控制点', node: '节点', strand: '发束', eye: '眼睛',
accessory: '饰品', x: '横向 X', y: '纵向 Y', px: '像素',
};
diff --git a/src/editor/i18n.tsx b/src/editor/i18n.tsx
index 9b5068c..9e5f06b 100644
--- a/src/editor/i18n.tsx
+++ b/src/editor/i18n.tsx
@@ -44,7 +44,10 @@ const en = {
emptyHelp: 'Choose a project from Open project, or browse for its folder.',
newProjectHelp: 'Starting from a new illustration? Ask your agent to prepare a project using the agent guide.',
invalidRig: 'Could not open the rig file. Check the JSON and these field paths:',
- invalidFolder: 'Could not open this folder. Include source.png, rig.json, layers.json and every cut-out image.',
+ invalidFolder: 'Could not open this folder. Check rig.json and layers.json for invalid data.',
+ missingFolderFiles: 'Required files are missing. Include source.png, layers.json and every cut-out image.',
+ unreadableFolder: 'A file or folder could not be read. Check access permissions and whether another app is using it, then try again.',
+ unreadableProject: 'Cannot read this project. Check permissions or whether the file is in use.',
invalidValue: 'Check the values at these field paths:', point: 'point', node: 'node', strand: 'Strand', eye: 'Eye',
accessory: 'Accessory', x: 'X', y: 'Y', px: 'px',
};
@@ -84,7 +87,10 @@ const ja: typeof en = {
emptyHelp: '「プロジェクトを開く」の一覧から選ぶか、フォルダを指定してください。',
newProjectHelp: '新しいイラストでは、エージェントに手順書に沿ってプロジェクトを作るよう依頼してください。',
invalidRig: '設定ファイルを開けませんでした。JSONの形式と次の項目を確認してください:',
- invalidFolder: 'フォルダーを開けませんでした。source.png、rig.json、layers.json とすべての切り抜き画像を用意してください。',
+ invalidFolder: 'フォルダを開けませんでした。rig.json と layers.json の内容を確認してください。',
+ missingFolderFiles: '必要なファイルが足りません。source.png、layers.json とすべての切り抜き画像を用意してください。',
+ unreadableFolder: 'ファイルまたはフォルダを読み取れませんでした。アクセス権限や、別のアプリで使用中でないかを確認して、もう一度お試しください。',
+ unreadableProject: 'このプロジェクトは読み取れません。アクセス権限や、ファイルが使用中でないかを確認してください。',
invalidValue: '次の項目の数値を確認してください:', point: '点', node: '節点', strand: '髪の束', eye: '目',
accessory: '飾り', x: '横', y: '縦', px: '画素',
};
diff --git a/src/editor/project.ts b/src/editor/project.ts
index 73bf2ea..2a437b9 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -1,5 +1,8 @@
import { parseRig } from '../rig/validate';
import type { Rig } from '../rig/types';
+import type { LocalProject, LocalProjectEntry } from '../project-types';
+import { FolderOpenError } from './folder-errors';
+export type { LocalProject, LocalProjectEntry } from '../project-types';
export interface ProjectAssets {
sourceUrl: string;
@@ -11,39 +14,40 @@ export async function openProjectFolder(files: File[]): Promise<ProjectAssets> {
const entries = files.map(file => ({ file, path: file.webkitRelativePath.replace(/^[^/]+\//, '') || file.name }));
const source = entries.find(entry => /(^|\/)source\.png$/i.test(entry.path));
const layers = entries.find(entry => /(^|\/)layers\.json$/i.test(entry.path));
- if (!source || !layers) throw new Error('Choose a project folder containing source.png, layers.json and the cut-out images.');
+ if (!source || !layers) throw new FolderOpenError('missingFolderFiles', [!source ? 'source.png' : '', !layers ? 'layers.json' : ''].filter(Boolean));
+ const read = async (entry: typeof entries[number]) => {
+ try { return await entry.file.arrayBuffer(); }
+ catch { throw new FolderOpenError('unreadableFolder', [entry.path]); }
+ };
const prefix = layers.path.slice(0, -'layers.json'.length);
const rigFile = entries.find(entry => /(^|\/)rig\.json$/i.test(entry.path));
- const rig = rigFile ? parseRig(JSON.parse(await rigFile.file.text())) : undefined;
- const metadata = JSON.parse(await layers.file.text()) as { layers?: Record<string, unknown> };
+ const rig = rigFile ? parseRig(JSON.parse(new TextDecoder().decode(await read(rigFile)))) : undefined;
+ const layerBytes = await read(layers);
+ const metadata = JSON.parse(new TextDecoder().decode(layerBytes)) as { layers?: Record<string, unknown> };
if (!metadata.layers || typeof metadata.layers !== 'object') throw new Error('layers.json must contain layer rectangles.');
const available = new Set(entries.filter(entry => entry.path.startsWith(prefix)).map(entry => entry.path.slice(prefix.length)));
const required = ['base.png', 'hairmask.png', ...Object.keys(metadata.layers).map(name => `${name}.png`)];
const missing = required.filter(name => !available.has(name));
- if (missing.length) throw new Error(`Missing image files: ${missing.join(', ')}`);
+ if (missing.length) throw new FolderOpenError('missingFolderFiles', missing.map(name => `${prefix}${name}`));
+ // Reading the bytes catches locked files before replacing the current project.
+ // Object URLs alone do not read a File and defer failures to the preview.
+ const sourceBytes = await read(source);
+ const built = [];
+ for (const entry of entries.filter(entry => entry.path.startsWith(prefix))) {
+ built.push({ entry, bytes: entry === layers ? layerBytes : await read(entry) });
+ }
const urls: string[] = [];
- const sourceUrl = URL.createObjectURL(source.file);
+ const sourceUrl = URL.createObjectURL(new Blob([sourceBytes], { type: source.file.type }));
urls.push(sourceUrl);
- const assets = Object.fromEntries(entries.filter(entry => entry.path.startsWith(prefix)).map(entry => {
- const url = URL.createObjectURL(entry.file);
+ const assets = Object.fromEntries(built.map(({ entry, bytes }) => {
+ const url = URL.createObjectURL(new Blob([bytes], { type: entry.file.type }));
urls.push(url);
return [entry.path.slice(prefix.length), url];
}));
return { sourceUrl, assets, rig, urls };
}
-export interface LocalProject {
- name: string;
- relativePath: string;
- absolutePath: string;
- displayPath?: string;
- updatedAt: string;
- hasSprites: boolean;
- hasVariants: boolean;
- readOnly: boolean;
- rigFile?: 'rig.json' | 'rig.draft.json';
-}
-export async function localProjects(): Promise<LocalProject[] | null> {
+export async function localProjects(): Promise<LocalProjectEntry[] | null> {
if (!import.meta.env.DEV) return null;
try {
const response = await fetch('/__studio/projects');
diff --git a/src/editor/recent-projects.ts b/src/editor/recent-projects.ts
index 6a2bd2f..eb2b972 100644
--- a/src/editor/recent-projects.ts
+++ b/src/editor/recent-projects.ts
@@ -1,4 +1,5 @@
import { readPreference, savePreference } from './preferences';
+import { FolderOpenError } from './folder-errors';
export const RECENT_KEY = 'mesh-avatar-recent-projects';
export const REOPEN_KEY = 'mesh-avatar-reopen-project';
@@ -36,22 +37,31 @@ export function pickDirectory(): Promise<ProjectDirectory> {
}
export async function directoryFiles(handle: ProjectDirectory): Promise<File[]> {
const files: File[] = [];
+ const read = async (entry: FileSystemFileHandle, path: string) => {
+ try {
+ const file = await entry.getFile();
+ Object.defineProperty(file, 'webkitRelativePath', { value: path }); files.push(file);
+ } catch (error) {
+ throw new FolderOpenError(error instanceof DOMException && error.name === 'NotFoundError' ? 'missingFolderFiles' : 'unreadableFolder', [path]);
+ }
+ };
async function walk(directory: ProjectDirectory, prefix: string) {
- for await (const entry of directory.values()) {
- const path = `${prefix}/${entry.name}`;
- if (entry.kind === 'directory') await walk(entry as ProjectDirectory, path);
- else {
- const file = await (entry as FileSystemFileHandle).getFile();
- Object.defineProperty(file, 'webkitRelativePath', { value: path }); files.push(file);
+ try {
+ for await (const entry of directory.values()) {
+ const path = `${prefix}/${entry.name}`;
+ if (entry.kind === 'directory') await walk(entry as ProjectDirectory, path);
+ else await read(entry as FileSystemFileHandle, path);
}
+ } catch (error) {
+ if (error instanceof FolderOpenError) throw error;
+ throw new FolderOpenError('unreadableFolder', [prefix]);
}
}
// Read only the files the editor uses, not scratch images or unrelated project documents.
for await (const entry of handle.values()) {
if (entry.kind === 'directory' && entry.name === 'built') await walk(entry as ProjectDirectory, `${handle.name}/built`);
else if (entry.kind === 'file' && ['rig.json', 'source.png'].includes(entry.name)) {
- const file = await (entry as FileSystemFileHandle).getFile();
- Object.defineProperty(file, 'webkitRelativePath', { value: `${handle.name}/${entry.name}` }); files.push(file);
+ await read(entry as FileSystemFileHandle, `${handle.name}/${entry.name}`);
}
}
return files;
diff --git a/src/editor/style.css b/src/editor/style.css
index 6adae5a..d64e7ea 100644
--- a/src/editor/style.css
+++ b/src/editor/style.css
@@ -39,6 +39,7 @@ summary::-webkit-details-marker { display: none; }
.project-list { max-height: 320px; overflow: auto; border-bottom: 1px solid var(--line); margin-bottom: 6px; }
.project-list button { margin: 4px 0; background: #f5f7fb; }
.project-list small { display: block; color: var(--muted); font-size: 11px; margin-top: 4px; overflow-wrap: anywhere; }
+.project-menu button.unreadable-project:disabled { opacity: 1; color: var(--muted); cursor: not-allowed; }
.badge { display: inline-block; font-size: 10px; color: #395476; background: #edf3ff; border-radius: 4px; padding: 2px 4px; margin-left: 6px; }
.recent-projects { padding: 8px; border-bottom: 1px solid var(--line); text-align: left; }
.recent-heading { display: flex; align-items: center; justify-content: space-between; }
diff --git a/src/project-types.ts b/src/project-types.ts
new file mode 100644
index 0000000..2e1a4d6
--- /dev/null
+++ b/src/project-types.ts
@@ -0,0 +1,20 @@
+export interface ProjectFileError { code: string; path: string }
+
+interface ProjectIdentity {
+ name: string;
+ relativePath: string;
+ readOnly: boolean;
+}
+
+export interface LocalProject extends ProjectIdentity {
+ error?: undefined;
+ absolutePath: string;
+ displayPath?: string;
+ updatedAt: string;
+ hasSprites: boolean;
+ hasVariants: boolean;
+ rigFile?: 'rig.json' | 'rig.draft.json';
+}
+
+export interface UnreadableProject extends ProjectIdentity { error: ProjectFileError }
+export type LocalProjectEntry = LocalProject | UnreadableProject;
diff --git a/src/server/local-projects.ts b/src/server/local-projects.ts
index 820324a..22159c4 100644
--- a/src/server/local-projects.ts
+++ b/src/server/local-projects.ts
@@ -2,17 +2,28 @@ import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
import { readFile, readdir, realpath, stat, writeFile, rename, unlink, mkdir, cp, lstat, rm } from 'node:fs/promises';
-import { resolve, relative, extname, sep } from 'node:path';
+import { resolve, relative, extname, sep, isAbsolute } from 'node:path';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Plugin } from 'vite';
import { validateRig } from '../rig/validate';
+import type { LocalProject, LocalProjectEntry } from '../project-types';
import { decodeVariants, JobError, projectJob, runTool, variantState, VARIANTS, type Runner } from './project-jobs';
const SAMPLE = 'sample-miko-qipao';
const displayPath = (path: string) => path === homedir() ? '~' : path.startsWith(`${homedir()}${sep}`) ? `~${path.slice(homedir().length)}` : path;
const safeName = /^[A-Za-z0-9._-]+$/;
class HttpError extends Error { constructor(public status: number, message: string) { super(message); } }
-const inside = (base: string, path: string) => { const rel = relative(base, path); return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !rel.startsWith(sep)); };
+const inside = (base: string, path: string) => { const rel = relative(base, path); return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel)); };
+function fileSystemError(root: string, error: unknown, fallback = 'projects') {
+ const failure = error as NodeJS.ErrnoException | null;
+ if (!failure?.code || !/^E[A-Z0-9]+$/.test(failure.code)) return;
+ const code = failure.code;
+ const path = typeof failure.path === 'string' && isAbsolute(failure.path) && inside(root, failure.path)
+ ? relative(root, failure.path).split(sep).join('/') || '.' : fallback;
+ const status = ['EPERM', 'EACCES', 'EROFS'].includes(code) ? 403 : code === 'EBUSY' ? 409 : ['ENOENT', 'ENOTDIR'].includes(code) ? 404 : 500;
+ const reason = status === 403 ? 'Permission denied' : status === 409 ? 'File or folder is in use' : status === 404 ? 'Project or file not found' : 'Local project operation failed';
+ return { status, body: { error: `${reason} (${code}): ${path}`, code, path } };
+}
async function exists(path: string) { try { await stat(path); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error; } }
async function checked(base: string, path: string) {
if (!inside(base, resolve(path)) || !inside(base, await realpath(path))) throw new HttpError(400, 'Path must stay inside the project.');
@@ -66,7 +77,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
if (!(await stat(path)).isDirectory()) throw new HttpError(404, 'Project not found.');
return path;
}
- async function info(name: string) {
+ async function info(name: string): Promise<LocalProject | null> {
const path = await folder(name), rigPath = resolve(path, 'rig.json');
const draft = resolve(path, 'rig.draft.json');
if (!await exists(rigPath) && !(await exists(draft) && await exists(resolve(path, 'built')))) return null;
@@ -79,6 +90,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
return async (req: IncomingMessage, res: ServerResponse, next: () => void) => {
if (!req.url?.startsWith('/__studio/')) { next(); return; }
const json = (status: number, value: unknown) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); res.end(JSON.stringify(value)); };
+ let errorPath = 'projects';
try {
// Reject cross-origin browser requests, including writes triggered by another website.
if (req.headers.origin && req.headers.origin !== `http://${req.headers.host}`) throw new HttpError(403, 'Use the local studio origin.');
@@ -120,17 +132,30 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
if (parts.length === 1 && req.method === 'GET') {
if (await exists(base) && await realpath(base) !== base) throw new HttpError(400, 'Project root cannot redirect elsewhere.');
const entries = await exists(base) ? await readdir(base, { withFileTypes: true }) : [];
- const list = [];
+ const list: LocalProjectEntry[] = [];
+ const add = async (name: string, isSample = false) => {
+ try {
+ if (isSample && (!await exists(resolve(sample, 'source.png')) || !await exists(resolve(sample, 'built/base.png')))) return;
+ const value = await info(name); if (value) list.push(value);
+ } catch (error) {
+ if (error instanceof HttpError) return;
+ const relativePath = isSample ? 'samples/miko-qipao' : `projects/${name}`;
+ const failure = fileSystemError(root, error, relativePath);
+ if (!failure) throw error;
+ // A folder removed during the scan is no longer a project.
+ if (failure.body.code === 'ENOENT') return;
+ list.push({ name, relativePath, readOnly: isSample, error: { code: failure.body.code, path: failure.body.path } });
+ }
+ };
for (const entry of entries) if (entry.isDirectory() && !entry.name.startsWith('.') && safeName.test(entry.name) && entry.name !== SAMPLE) {
- try { const value = await info(entry.name); if (value) list.push(value); } catch (error) { if (!(error instanceof HttpError)) throw error; }
- }
- if (await exists(resolve(sample, 'source.png')) && await exists(resolve(sample, 'built/base.png'))) {
- const value = await info(SAMPLE); if (value) list.push(value);
+ await add(entry.name);
}
- list.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ await add(SAMPLE, true);
+ list.sort((a, b) => (b.error ? '' : b.updatedAt).localeCompare(a.error ? '' : a.updatedAt));
json(200, list); return;
}
if (parts.length < 3) throw new HttpError(404, 'Not found.');
+ errorPath = parts[1] === SAMPLE ? 'samples/miko-qipao' : `projects/${parts[1]}`;
const name = parts[1], path = await folder(name), tail = parts.slice(2);
if (req.method === 'POST' && tail.length === 1 && tail[0] === 'reveal') {
await reveal(path); json(200, { path }); return;
@@ -168,6 +193,8 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
res.end(bytes);
} catch (error) {
if (error instanceof JobError) { json(422, { error: error.code, code: error.code, log: error.log }); return; }
+ const failure = fileSystemError(root, error, errorPath);
+ if (failure) { json(failure.status, failure.body); return; }
const status = error instanceof HttpError ? error.status : (error as NodeJS.ErrnoException).code === 'ENOENT' ? 404 : 500;
json(status, { error: error instanceof HttpError ? error.message : status === 404 ? 'Project or file not found.' : 'Local project operation failed.' });
}
@@ -180,7 +207,11 @@ export function localProjectsPlugin(root: string): Plugin {
if (!safeName.test(parts[0]) || parts[0].startsWith('.') || parts[0] === SAMPLE) return;
if (parts[1] === 'variants' || (parts[1] === 'built' && parts[2] === 'sprites')) return parts[0];
};
- return { name: 'local-studio-projects', apply: 'serve', configureServer(server) {
+ return { name: 'local-studio-projects', apply: 'serve', config(config) {
+ if (config.server?.watch === null) return;
+ // Configure this before Vite starts watching the root, not only after add().
+ return { server: { watch: { ignored: [(file: string) => inside(base, file) && relative(base, file).split(sep).some(part => part.startsWith('.'))] } } };
+ }, configureServer(server) {
server.middlewares.use(localProjectMiddleware(root));
const timers = new Map<string, ReturnType<typeof setTimeout>>();
const changed = (file: string) => {
@@ -192,6 +223,10 @@ export function localProjectsPlugin(root: string): Plugin {
server.ws.send({ type: 'custom', event: 'studio:variants-changed', data: { name } });
}, 800));
};
+ server.watcher.on('error', error => {
+ const failure = fileSystemError(root, error);
+ server.config.logger.warn(`[local-studio-projects] Watch error: ${failure?.body.error ?? 'File watcher failed.'}`);
+ });
server.watcher.add(base);
server.watcher.on('all', (_event, file) => changed(file));
server.httpServer?.once('close', () => { for (const timer of timers.values()) clearTimeout(timer); });
diff --git a/tests/local-projects.test.ts b/tests/local-projects.test.ts
index 3d54a52..9aba614 100644
--- a/tests/local-projects.test.ts
+++ b/tests/local-projects.test.ts
@@ -3,10 +3,24 @@ import { mkdtemp, mkdir, writeFile, readFile, rm, symlink } from 'node:fs/promis
import { homedir } from 'node:os';
import { resolve, join } from 'node:path';
import { Readable } from 'node:stream';
+import { EventEmitter } from 'node:events';
+import { createServer, resolveConfig, type ViteDevServer } from 'vite';
import type { IncomingMessage, ServerResponse } from 'node:http';
import fixture from '../samples/miko-qipao/rig.json';
import { localProjectMiddleware, localProjectsPlugin } from '../src/server/local-projects';
+const failure = vi.hoisted(() => ({ operation: '', path: '', code: '' }));
+vi.mock('node:fs/promises', async importOriginal => {
+ const actual = await importOriginal<typeof import('node:fs/promises')>();
+ const methods = ['realpath', 'stat', 'readdir', 'readFile'] as const;
+ return { ...actual, ...Object.fromEntries(methods.map(method => [method, async (...args: unknown[]) => {
+ if (failure.operation === method && String(args[0]) === failure.path) {
+ throw Object.assign(new Error(`Private filesystem details: ${failure.path}`), { code: failure.code, path: failure.path });
+ }
+ return Reflect.apply(actual[method], actual, args);
+ }])) };
+});
+
let root: string;
beforeEach(async () => {
const scratch = resolve('projects'); await mkdir(scratch, { recursive: true });
@@ -19,7 +33,7 @@ beforeEach(async () => {
}
await writeFile(resolve(root, 'projects/nova/built/sprites/sprites.json'), '{}');
});
-afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+afterEach(async () => { failure.operation = ''; vi.useRealTimers(); await rm(root, { recursive: true, force: true }); });
async function call(path: string, method = 'GET', body?: unknown, headers: Record<string, string> = {}, reveal = vi.fn(async (_path: string) => { void _path; })) {
const request = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]) as IncomingMessage;
@@ -95,6 +109,104 @@ test('plugin is development-only and has no production or preview middleware hoo
expect(plugin.apply).toBe('serve'); expect(plugin.configurePreviewServer).toBeUndefined();
});
+for (const operation of ['realpath', 'stat']) for (const code of ['EPERM', 'EACCES', 'EBUSY']) {
+ test(`lists other projects and an unreadable entry when ${operation} fails with ${code}`, async () => {
+ Object.assign(failure, { operation, code, path: resolve(root, 'projects/nova') });
+ const response = await call('/__studio/projects');
+ expect(response.status).toBe(200);
+ const list = JSON.parse(response.body);
+ expect(list.find((entry: { name: string }) => entry.name === 'sample-miko-qipao')).toMatchObject({ readOnly: true, hasSprites: false });
+ const blocked = list.find((entry: { name: string }) => entry.name === 'nova');
+ expect(blocked).toEqual({ name: 'nova', relativePath: 'projects/nova', readOnly: false, error: { code, path: 'projects/nova' } });
+ expect(JSON.stringify(blocked)).not.toContain(root);
+ });
+}
+
+test('a nested file error or unreadable sample does not discard healthy projects', async () => {
+ Object.assign(failure, { operation: 'stat', code: 'EACCES', path: resolve(root, 'projects/nova/built/sprites/sprites.json') });
+ let list = JSON.parse((await call('/__studio/projects')).body);
+ expect(list.find((entry: { name: string }) => entry.name === 'nova').error.path).toBe('projects/nova/built/sprites/sprites.json');
+ failure.path = resolve(root, 'samples/miko-qipao/source.png');
+ list = JSON.parse((await call('/__studio/projects')).body);
+ expect(list.find((entry: { name: string }) => entry.name === 'nova').error).toBeUndefined();
+ expect(list.find((entry: { name: string }) => entry.name === 'sample-miko-qipao').error).toEqual({ code: 'EACCES', path: 'samples/miko-qipao/source.png' });
+});
+
+for (const [code, status] of [['EPERM', 403], ['EACCES', 403], ['EBUSY', 409], ['ENOENT', 404]] as const) {
+ test(`API maps ${code} to ${status} without disclosing absolute paths`, async () => {
+ Object.assign(failure, { operation: 'readFile', code, path: resolve(root, 'projects/nova/rig.json') });
+ const response = await call('/__studio/projects/nova/rig.json');
+ expect(response.status).toBe(status);
+ expect(JSON.parse(response.body)).toMatchObject({ code, path: 'projects/nova/rig.json' });
+ expect(response.body).not.toContain(root);
+ expect(response.body).not.toContain('Private filesystem details');
+ });
+}
+
+test('a denied projects directory returns a specific error instead of an empty list', async () => {
+ Object.assign(failure, { operation: 'readdir', code: 'EACCES', path: resolve(root, 'projects') });
+ const response = await call('/__studio/projects');
+ expect(response.status).toBe(403);
+ expect(JSON.parse(response.body)).toMatchObject({ code: 'EACCES', path: 'projects' });
+});
+
+test('errors outside the repository or without a path use a safe project-relative fallback', async () => {
+ for (const path of [undefined, resolve(root, '../outside-private-file'), 'C:\\Users\\private-account\\secret', '\\\\host\\private\\secret']) {
+ const reveal = vi.fn(async () => { throw Object.assign(new Error('private details'), { code: 'EACCES', path }); });
+ const response = await call('/__studio/projects/nova/reveal', 'POST', {}, {}, reveal);
+ expect(response.status).toBe(403);
+ expect(JSON.parse(response.body)).toEqual({ error: 'Permission denied (EACCES): projects/nova', code: 'EACCES', path: 'projects/nova' });
+ }
+});
+
+test('watch ignores hidden project paths while preserving existing exclusions and variant reloads after EBUSY', async () => {
+ const plugin = localProjectsPlugin(root);
+ const config = await resolveConfig({ configFile: false, root, plugins: [plugin], server: { watch: { ignored: ['**/existing-ignore/**'] } } }, 'serve');
+ const ignored = config.server.watch?.ignored as (string | ((path: string) => boolean))[];
+ expect(ignored).toContain('**/existing-ignore/**');
+ const excludes = ignored.find(value => typeof value === 'function') as (path: string) => boolean;
+ for (const path of ['projects/.studio-job-123', 'projects/.readme-tmp-123/built/base.png', 'projects/nova/variants/.scratch/image.png']) {
+ expect(excludes(resolve(root, path)), path).toBe(true);
+ }
+ for (const path of ['projects', 'projects/nova/variants/mouth_a.png', 'projects/nova/built/sprites/sprites.json', 'src/editor/App.tsx']) {
+ expect(excludes(resolve(root, path)), path).toBe(false);
+ }
+ vi.useFakeTimers();
+ const watcher = Object.assign(new EventEmitter(), { add: vi.fn() });
+ const send = vi.fn(), warn = vi.fn(), httpServer = new EventEmitter();
+ const configure = plugin.configureServer as (server: ViteDevServer) => void;
+ configure({ watcher, ws: { send }, config: { logger: { warn } }, middlewares: { use: vi.fn() }, httpServer } as unknown as ViteDevServer);
+ expect(() => watcher.emit('error', Object.assign(new Error('private detail'), { code: 'EBUSY', path: resolve(root, 'projects/.studio-job-123') }))).not.toThrow();
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('EBUSY'));
+ expect(warn.mock.calls[0][0]).not.toContain(root);
+ watcher.emit('all', 'change', resolve(root, 'projects/.studio-job-123/variants/mouth_a.png'));
+ watcher.emit('all', 'change', resolve(root, 'projects/nova/variants/mouth_a.png'));
+ watcher.emit('all', 'change', resolve(root, 'projects/nova/built/sprites/sprites.json'));
+ await vi.advanceTimersByTimeAsync(800);
+ expect(send).toHaveBeenCalledExactlyOnceWith({ type: 'custom', event: 'studio:variants-changed', data: { name: 'nova' } });
+ const response = await call('/__studio/projects'); expect(response.status).toBe(200);
+ watcher.emit('all', 'change', resolve(root, 'projects/nova/variants/mouth_a.png'));
+ httpServer.emit('close'); await vi.advanceTimersByTimeAsync(800);
+ expect(send).toHaveBeenCalledTimes(1);
+});
+
+test('the live watcher skips temporary directories and still detects new variants and sprite updates', async () => {
+ const stage = resolve(root, 'projects/.studio-job-123');
+ await mkdir(resolve(stage, 'built'), { recursive: true });
+ await writeFile(resolve(stage, 'built/base.png'), 'scratch');
+ const server = await createServer({ configFile: false, root, cacheDir: resolve(root, '.vite'), plugins: [localProjectsPlugin(root)], server: { middlewareMode: true, hmr: false } });
+ try {
+ await vi.waitFor(() => expect(server.watcher.getWatched()[resolve(root, 'projects/nova/variants')]).toBeDefined());
+ expect(Object.keys(server.watcher.getWatched()).some(path => path.includes('.studio-job-123'))).toBe(false);
+ const send = vi.spyOn(server.ws, 'send');
+ await writeFile(resolve(root, 'projects/nova/variants/mouth_a.png'), 'new variant');
+ await vi.waitFor(() => expect(send).toHaveBeenCalledWith({ type: 'custom', event: 'studio:variants-changed', data: { name: 'nova' } }), { timeout: 5000 });
+ send.mockClear();
+ await writeFile(resolve(root, 'projects/nova/built/sprites/sprites.json'), '{"layers":{}}');
+ await vi.waitFor(() => expect(send).toHaveBeenCalledWith({ type: 'custom', event: 'studio:variants-changed', data: { name: 'nova' } }), { timeout: 5000 });
+ } finally { await server.close(); }
+}, 15_000);
+
test('sample copies reserve unused names, carry edits and built assets, and reject invalid or redirected sources', async () => {
const edited = structuredClone(fixture); edited.head.cx += 10;
diff --git a/tests/project-folder.test.ts b/tests/project-folder.test.ts
new file mode 100644
index 0000000..1cce6ab
--- /dev/null
+++ b/tests/project-folder.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, expect, test, vi } from 'vitest';
+import { openProjectFolder } from '../src/editor/project';
+import { directoryFiles, type ProjectDirectory } from '../src/editor/recent-projects';
+import { FolderOpenError, folderOpenError } from '../src/editor/folder-errors';
+
+afterEach(() => vi.restoreAllMocks());
+function files() {
+ return ['source.png', 'built/layers.json', 'built/base.png', 'built/hairmask.png', 'built/head.png'].map(path => {
+ const file = new File([path.endsWith('.json') ? '{"layers":{"head":{}}}' : 'synthetic bytes'], path.split('/').at(-1)!);
+ Object.defineProperty(file, 'webkitRelativePath', { value: `nova/${path}` });
+ return file;
+ });
+}
+
+test('missing files identify what is absent', async () => {
+ await expect(openProjectFolder([])).rejects.toMatchObject({ kind: 'missingFolderFiles', paths: ['source.png', 'layers.json'] });
+ await expect(openProjectFolder(files().filter(file => file.name !== 'head.png'))).rejects.toMatchObject({ kind: 'missingFolderFiles', paths: ['built/head.png'] });
+});
+
+for (const name of ['layers.json', 'source.png', 'head.png']) test(`an existing unreadable ${name} is reported before creating object URLs`, async () => {
+ const entries = files(), file = entries.find(file => file.name === name)!;
+ vi.spyOn(file, 'arrayBuffer').mockRejectedValue(new DOMException('Locked', 'NotReadableError'));
+ const create = vi.spyOn(URL, 'createObjectURL');
+ await expect(openProjectFolder(entries)).rejects.toMatchObject({ kind: 'unreadableFolder', paths: [file.webkitRelativePath.slice('nova/'.length)] });
+ expect(create).not.toHaveBeenCalled();
+});
+
+test('readable files still produce usable source and asset URLs', async () => {
+ const result = await openProjectFolder(files());
+ try {
+ expect(Object.keys(result.assets)).toEqual(['layers.json', 'base.png', 'hairmask.png', 'head.png']);
+ expect(await (await fetch(result.sourceUrl)).text()).toBe('synthetic bytes');
+ expect(await (await fetch(result.assets['layers.json'])).json()).toEqual({ layers: { head: {} } });
+ } finally { result.urls.forEach(url => URL.revokeObjectURL(url)); }
+});
+
+test('malformed metadata remains a format error and permissions are separate from missing files', async () => {
+ const entries = files();
+ vi.spyOn(entries[1], 'arrayBuffer').mockResolvedValue(new TextEncoder().encode('{bad json').buffer);
+ try { await openProjectFolder(entries); throw new Error('Expected invalid JSON'); }
+ catch (error) { expect(error).toBeInstanceOf(SyntaxError); expect(folderOpenError(error).kind).toBe('invalidFolder'); }
+ for (const name of ['NotReadableError', 'NotAllowedError', 'SecurityError']) expect(folderOpenError(new DOMException('', name)).kind).toBe('unreadableFolder');
+ expect(folderOpenError(new DOMException('', 'NotFoundError')).kind).toBe('missingFolderFiles');
+ expect(folderOpenError(new FolderOpenError('unreadableFolder', ['built/head.png'])).paths).toEqual(['built/head.png']);
+});
+
+test('directory handles preserve the unreadable file or subdirectory path', async () => {
+ const handle = { name: 'nova', async *values() {
+ yield { kind: 'file', name: 'source.png', getFile: async () => { throw new DOMException('Denied', 'NotReadableError'); } };
+ } } as unknown as ProjectDirectory;
+ await expect(directoryFiles(handle)).rejects.toMatchObject({ kind: 'unreadableFolder', paths: ['nova/source.png'] });
+ const nested = { name: 'nova', async *values() {
+ yield { kind: 'directory', name: 'built', values() { throw new DOMException('Denied', 'NotAllowedError'); } };
+ } } as unknown as ProjectDirectory;
+ await expect(directoryFiles(nested)).rejects.toMatchObject({ kind: 'unreadableFolder', paths: ['nova/built'] });
+});