Skip to content

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

Explain when layers cannot be rebuilt and offer a way forward

shinshin86f36f91efe1c9
diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts
index d2d60a8..4b4f946 100644
--- a/e2e/editor.spec.ts
+++ b/e2e/editor.spec.ts
@@ -122,7 +122,7 @@ test('a newly opened project establishes its own cut-out baseline', async ({ pag
await expect(point).toHaveValue('447');
await expect(page.locator('.stale')).toHaveCount(0);
await point.fill('448');
- await expect(page.locator('.stale')).toContainText('run build-layers');
+ await expect(page.locator('.stale')).toContainText('This project is available in the project list.');
await folder.setInputFiles(directory);
await expect(page.locator('.stale')).toHaveCount(0);
} finally {
diff --git a/e2e/rebuild-guidance.spec.ts b/e2e/rebuild-guidance.spec.ts
new file mode 100644
index 0000000..6e09fb0
--- /dev/null
+++ b/e2e/rebuild-guidance.spec.ts
@@ -0,0 +1,89 @@
+import { test, expect, type Page } from '@playwright/test';
+import { cp, mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';
+
+async function editHead(page: Page) {
+ await page.getByTestId('part-head').click();
+ const field = page.getByRole('spinbutton', { name: 'head.cx', exact: true });
+ await field.fill('635');
+ await expect(page.getByTestId('stale-banner')).toBeVisible();
+ return field;
+}
+
+test('sample copy preserves edits and undo, protects the original and enables a real rebuild', async ({ page }) => {
+ test.skip(!samplePresent, sampleSkipReason); test.setTimeout(90000);
+ const sourceFiles = ['rig.json', 'source.png', 'built/base.png', 'built/layers.json'];
+ const originals = await Promise.all(sourceFiles.map(file => readFile(resolve('samples/miko-qipao', file))));
+ let copiedName = '';
+ try {
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.goto('/'); await dismissGuide(page);
+ const field = await editHead(page), banner = page.getByTestId('stale-banner');
+ await expect(banner).toContainText('The sample is read-only');
+ await expect(banner.getByRole('button', { name: 'Save and rebuild layers', exact: true })).toHaveCount(0);
+ await page.getByRole('button', { name: '日本語', exact: true }).click();
+ await expect(banner).toContainText('読み取り専用のため');
+ await page.screenshot({ path: 'docs/screenshots/ui7-sample-guidance-ja-1440x900.png' });
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ await page.route('**/__studio/copy-sample', async route => { await gate; await route.fulfill({ status: 500, contentType: 'application/json', body: '{}' }); });
+ await banner.getByRole('button', { name: 'コピーして編集を続ける', exact: true }).click();
+ try {
+ await expect(page.getByRole('button', { name: '元に戻す', exact: true })).toBeDisabled();
+ await expect(page.getByRole('button', { name: '設定を保存', exact: true })).toBeDisabled();
+ } finally { release(); }
+ await expect(banner.getByRole('alert')).toContainText('今の編集内容は残っています'); await expect(field).toHaveValue('635');
+ await page.unroute('**/__studio/copy-sample');
+ const response = page.waitForResponse(response => response.url().endsWith('/__studio/copy-sample'));
+ await banner.getByRole('button', { name: 'コピーして編集を続ける', exact: true }).click();
+ const entry = await (await response).json(); copiedName = entry.name;
+ await expect(page.getByTestId('project-location').locator('strong')).toHaveText(copiedName);
+ await expect(field).toHaveValue('635'); await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ expect(JSON.parse(await readFile(resolve('projects', copiedName, 'rig.json'), 'utf8')).head.cx).toBe(635);
+ for (const file of ['source.png', 'built/base.png', 'built/layers.json']) expect(await readFile(resolve('projects', copiedName, file))).toEqual(originals[sourceFiles.indexOf(file)]);
+ await page.getByRole('button', { name: '元に戻す', exact: true }).click(); await expect(field).toHaveValue('615');
+ await page.getByRole('button', { name: 'やり直す', exact: true }).click(); await expect(field).toHaveValue('635');
+ await banner.getByRole('button', { name: '保存してレイヤーを作り直す', exact: true }).click();
+ await expect(banner).toHaveCount(0, { timeout: 60000 });
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready'); await expect(field).toHaveValue('635');
+ for (let index = 0; index < sourceFiles.length; index++) expect(await readFile(resolve('samples/miko-qipao', sourceFiles[index]))).toEqual(originals[index]);
+ } finally { if (copiedName) await rm(resolve('projects', copiedName), { recursive: true, force: true }); }
+});
+
+test('a picked folder can reopen a matching listed project without discarding edits', async ({ page }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ await mkdir(resolve('projects'), { recursive: true });
+ const directory = await mkdtemp(join(resolve('projects'), 'reopen-check-'));
+ try {
+ await cp(resolve('samples/miko-qipao'), directory, { recursive: true });
+ const original = await readFile(join(directory, 'rig.json'));
+ await page.setViewportSize({ width: 1440, height: 900 }); await page.goto('/'); await dismissGuide(page);
+ await page.getByLabel('Open project folder files', { exact: true }).setInputFiles(directory);
+ const field = await editHead(page), banner = page.getByTestId('stale-banner');
+ await expect(banner).toContainText('This project is available in the project list.');
+ await expect(banner).toContainText('browser cannot identify this folder');
+ await page.getByRole('button', { name: '日本語', exact: true }).click();
+ await expect(banner).toContainText('このプロジェクトは一覧から開けます');
+ await page.screenshot({ path: 'docs/screenshots/ui7-picked-guidance-ja-1440x900.png' });
+ await banner.getByRole('button', { name: '一覧から開き直す', exact: true }).click();
+ await expect(banner.getByRole('button', { name: '保存してレイヤーを作り直す', exact: true })).toBeEnabled();
+ await expect(field).toHaveValue('635'); await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ expect(await readFile(join(directory, 'rig.json'))).toEqual(original);
+ await page.getByRole('button', { name: '設定を保存', exact: true }).click();
+ await expect.poll(async () => JSON.parse(await readFile(join(directory, 'rig.json'), 'utf8')).head.cx).toBe(635);
+ await page.getByRole('button', { name: '元に戻す', exact: true }).click(); await expect(field).toHaveValue('615');
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
+
+test('unmatched picked folders retain a short manual instruction and explain why rebuild is unavailable', async ({ page }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ await page.route('**/__studio/projects', route => route.fulfill({ contentType: 'application/json', body: '[]' }));
+ await page.goto('/'); await dismissGuide(page);
+ await page.getByLabel('Open project folder files', { exact: true }).setInputFiles(resolve('samples/miko-qipao'));
+ await editHead(page); const banner = page.getByTestId('stale-banner');
+ await expect(banner).toContainText('browser cannot identify this folder'); await expect(banner).toContainText('run build-layers');
+ await expect(banner.getByRole('button')).toHaveCount(0);
+ await page.getByRole('button', { name: '日本語', exact: true }).click();
+ await expect(banner).toContainText('場所を取得できないため'); await expect(banner).toContainText('そのフォルダで build-layers');
+});
diff --git a/src/editor/App.tsx b/src/editor/App.tsx
index 8d285a7..9f175d7 100644
--- a/src/editor/App.tsx
+++ b/src/editor/App.tsx
@@ -6,7 +6,7 @@ import type { Rig } from '../rig/types';
import { parseRig, validateRig } from '../rig/validate';
import { Preview } from './Preview';
import { RigHistory, downloadRig } from './history';
-import { openProjectFolder, openLocalProject, 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 } from './project';
import { layerSignature } from './stale';
import { RigFields } from './RigFields';
import { GROUPS } from './parts';
@@ -23,7 +23,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'; paths: string[] };
+type EditorError = { kind: 'invalidRig' | 'invalidFolder' | '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>; }
@@ -51,7 +51,7 @@ function Workspace() {
const [focusRequest, setFocusRequest] = useState<{ group: string; id: number }>();
const [mouthSprites, setMouthSprites] = useState(true), [mouthRequest, setMouthRequest] = useState(0);
const [job, setJob] = useState<ProjectJob | null>(null);
- const jobRef = useRef<ProjectJob | null>(null);
+ const jobRef = useRef<ProjectJob | 'transfer' | null>(null);
const [rebuildError, setRebuildError] = useState<ProjectJobError | null>(null);
useEffect(() => { void repositoryContext().then(context => { setRootPath(context?.rootPath); }); }, []);
const [recent, setRecent] = useState(readRecent);
@@ -305,6 +305,27 @@ function Workspace() {
return result;
} 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 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');
+ 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!));
+ history.replacePresent(edited); setRig(history.present); setDragStale(null);
+ objectUrls.current.forEach(url => URL.revokeObjectURL(url)); objectUrls.current = [];
+ projectOpened.current = true; setSourceUrl(loaded.sourceUrl); setAssets(loaded.assets);
+ setLocalProject(entry); setPickedName(''); setChecking(false); setRebuildError(null);
+ setProjects(await localProjects());
+ remember({ id: `server:${entry.name}`, kind: 'server', name: entry.name, serverName: entry.name, relativePath: entry.relativePath, lastOpened: new Date().toISOString() });
+ } catch { setError({ kind: 'continueError', paths: [] }); }
+ finally { jobRef.current = null; setOpening(false); }
+ };
return <main onDragOver={event => event.preventDefault()} onDrop={event => { event.preventDefault(); void openFile(event.dataTransfer.files[0]); }}>
<header className="toolbar">
<div className="brand"><h1>{t.product}</h1><p>{t.subtitle}</p></div>
@@ -313,7 +334,7 @@ function Workspace() {
onChange={event => { void openFile(event.target.files?.[0]); event.target.value = ''; }} />
<input ref={folderInput} type="file" multiple hidden aria-label={t.folderFiles} {...{ webkitdirectory: '' }}
onChange={event => { void openFolder(Array.from(event.target.files ?? [])); event.target.value = ''; }} />
- <details ref={openMenu} className="open-menu" inert={job !== null} onToggle={event => {
+ <details ref={openMenu} className="open-menu" inert={job !== null || opening} onToggle={event => {
if (event.currentTarget.open) void localProjects().then(setProjects);
}}><summary>{t.openProject}<Icon name="chevron" /></summary>
<div className="project-menu">{recentControl}<p className="project-help">{t.projectHelp}</p>
@@ -328,10 +349,10 @@ function Workspace() {
<button onClick={() => { void chooseFile(true); }}>{t.openFolder}</button><button onClick={() => { void chooseFile(false); }}>{t.openRig}</button>
</div>
</details>
- <button className="icon-button" aria-label={t.save} disabled={saving || job !== null} title={`${t.save} · ⌘S`} onClick={() => { void save(); }}><Icon name="save" /></button>
+ <button className="icon-button" aria-label={t.save} disabled={saving || job !== null || opening} title={`${t.save} · ⌘S`} onClick={() => { void save(); }}><Icon name="save" /></button>
<span className="toolbar-divider" />
- <button className="icon-button" aria-label={t.undo} title={`${t.undo} · ⌘Z`} disabled={!history.canUndo || job !== null} onClick={() => setRig(history.undo())}><Icon name="undo" /></button>
- <button className="icon-button" aria-label={t.redo} title={`${t.redo} · ⇧⌘Z`} disabled={!history.canRedo || job !== null} onClick={() => setRig(history.redo())}><Icon name="redo" /></button>
+ <button className="icon-button" aria-label={t.undo} title={`${t.undo} · ⌘Z`} disabled={!history.canUndo || job !== null || opening} onClick={() => setRig(history.undo())}><Icon name="undo" /></button>
+ <button className="icon-button" aria-label={t.redo} title={`${t.redo} · ⇧⌘Z`} disabled={!history.canRedo || job !== null || opening} onClick={() => setRig(history.redo())}><Icon name="redo" /></button>
<span className="toolbar-divider" />
<button className="icon-button" aria-label={t.help} title={t.help} aria-expanded={help} onClick={() => setHelp(current => !current)}><Icon name="help" /></button>
<div className="language-toggle" role="group" aria-label={t.language}>
@@ -348,14 +369,15 @@ function Workspace() {
</div>}
{notice && <div role="status" className="save-notice">{t[notice.key]}{notice.path && ` ${notice.path}`}</div>}
{help && <Help onClose={() => setHelp(false)} onGuide={() => { setGuide(true); setHelp(false); }} />}
- {(dragStale ?? changed.length > 0) && <div className="stale" data-testid="stale-banner"><p role="status">{localProject && !localProject.readOnly ? t.staleLocal : t.stale}</p><small>{t.changedParts}: {changed.map(key => parts[key as PartGroup]?.[0] ?? title(key)).join(' · ')}</small>
- {localProject && !localProject.readOnly ? <button className="primary" disabled={job !== null || saving} onClick={() => { setRebuildError(null); void runJob('rebuild').catch(error => setRebuildError(error instanceof ProjectJobError ? error : new ProjectJobError('toolFailed'))); }}>{job === 'rebuild' ? t.rebuilding : t.rebuild}</button> : <p>{t.rebuildUnavailable}</p>}
+ {(dragStale ?? changed.length > 0) && <div className="stale" data-testid="stale-banner"><p role="status">{localProject && !localProject.readOnly ? t.staleLocal : sampleEditing ? t.staleSample : listedProject ? t.staleListed : t.stale}</p><small>{t.changedParts}: {changed.map(key => parts[key as PartGroup]?.[0] ?? title(key)).join(' · ')}</small>
+ {localProject && !localProject.readOnly ? <button className="primary" disabled={job !== null || saving} onClick={() => { setRebuildError(null); void runJob('rebuild').catch(error => setRebuildError(error instanceof ProjectJobError ? error : new ProjectJobError('toolFailed'))); }}>{job === 'rebuild' ? t.rebuilding : t.rebuild}</button> : <><small>{sampleEditing ? t.sampleRebuildReason : t.folderRebuildReason}</small>{sampleEditing || listedProject ? <button className="primary" disabled={opening || saving || job !== null || (sampleEditing && !rootPath)} onClick={() => { void continueEditing(); }}>{opening ? t.operationBusy : sampleEditing ? t.copyContinue : t.reopenListed}</button> : <p>{t.rebuildUnavailable}</p>}</>}
{rebuildError && <JobFeedback error={rebuildError} />}
+ {error?.kind === 'continueError' && errorNotice}
</div>}
{!sourceUrl && <section className="panel empty-project"><h2>{checking ? t.checking : t.emptyTitle}</h2><p>{t.projectHelp}</p><p>{t.emptyHelp}</p>{recentControl}<AskAgent newProject rootPath={rootPath} />{errorNotice}</section>}
{sourceUrl && <div className="workspace">
- <div className="parts-container" inert={job !== null}><PartList rig={rig} visible={visible} selected={selected} onSelect={selectPart} onFocus={group => { selectPart(group); setFocusRequest(current => ({ group, id: (current?.id ?? 0) + 1 })); }} onVisible={setVisible} /></div>
- <section className="panel editor-panel" inert={job !== null}>
+ <div className="parts-container" inert={job !== null || opening}><PartList rig={rig} visible={visible} selected={selected} onSelect={selectPart} onFocus={group => { selectPart(group); setFocusRequest(current => ({ group, id: (current?.id ?? 0) + 1 })); }} onVisible={setVisible} /></div>
+ <section className="panel editor-panel" inert={job !== null || opening}>
<div className="panel-title"><h2>{t.source}</h2><span>{rig.image.width} × {rig.image.height} {t.px}</span></div>
<div className="canvas-stage">
<EditorCanvas sourceUrl={sourceUrl} rig={rig} visible={visible} selected={selected} onSelect={setSelected} onChange={update} focusRequest={focusRequest}
@@ -368,7 +390,7 @@ function Workspace() {
<Preview rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={() => setMouthRequest(value => value + 1)} />
<VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} busy={job !== null || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />
{!localProject && !pickedName && <details className="panel new-illustration"><summary>{t.newIllustration}</summary><AskAgent newProject rootPath={rootPath} /></details>}
- <aside className="panel inspector" inert={job !== null}>
+ <aside className="panel inspector" inert={job !== null || opening}>
<div className="selection-heading"><h2>{selectedPart?.[0] ?? t.selection}</h2></div>
{errorNotice}
{selectedPart ? <><p className="part-description">{selectedPart[1]}</p><p className="part-tip"><strong>{t.tip}</strong> {selectedPart[2]}</p>
diff --git a/src/editor/i18n.tsx b/src/editor/i18n.tsx
index 2b72ba4..bd792ed 100644
--- a/src/editor/i18n.tsx
+++ b/src/editor/i18n.tsx
@@ -38,7 +38,7 @@ const en = {
guide3: 'Watch the preview on the right', gotIt: 'Got it', shortcuts: 'Keyboard & mouse', guideAgain: 'Show the guide again',
shortcutUndo: 'Undo / redo', shortcutSave: 'Save rig', shortcutPan: 'Pan the image', shortcutZoom: 'Zoom the image',
shortcutVertex: 'Add / remove a dot', spaceDrag: 'Space + drag', wheel: 'Scroll', vertexKeys: 'Double-click a line / Alt-click a dot',
- stale: 'Outlines changed. Save the rig, run build-layers, then reopen the project. Preview still uses the old images.',
+ stale: 'Outlines changed. The preview still uses the previous layers.',
changedParts: 'Changed parts', checking: 'Checking for sample images…', emptyTitle: 'Open a project',
emptyHelp: 'Choose a project from Open project, or browse for its folder. Sample images are installed separately.',
newProjectHelp: 'Starting from a new illustration? Ask your agent to prepare a project using the agent guide.',
@@ -78,7 +78,7 @@ const ja: typeof en = {
guide3: '右のプレビューで動きを見る', gotIt: 'わかりました', shortcuts: 'キーボード・マウス操作', guideAgain: '使い方をもう一度表示',
shortcutUndo: '元に戻す/やり直す', shortcutSave: '設定を保存', shortcutPan: '画像を移動', shortcutZoom: '画像を拡大・縮小',
shortcutVertex: '点を追加/削除', spaceDrag: 'スペース+ドラッグ', wheel: 'スクロール', vertexKeys: '線をダブルクリック/⌥+点をクリック',
- stale: '輪郭が変更されました。設定を保存し、build-layersを実行してからプロジェクトを開き直してください。プレビューには変更前の画像を使っています。',
+ stale: '輪郭が変更されました。プレビューには変更前の画像を使っています。',
changedParts: '変更されたパーツ', checking: 'サンプル画像を確認中…', emptyTitle: 'プロジェクトを開く',
emptyHelp: '「プロジェクトを開く」の一覧から選ぶか、フォルダを指定してください。サンプル画像は別途用意が必要です。',
newProjectHelp: '新しいイラストでは、エージェントに手順書に沿ってプロジェクトを作るよう依頼してください。',
diff --git a/src/editor/project.ts b/src/editor/project.ts
index 059a227..2b7afb9 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -57,6 +57,11 @@ export async function repositoryContext(): Promise<{ rootPath: string; displayRo
if (!import.meta.env.DEV) return null;
try { const response = await fetch('/__studio/context'); return response.ok && response.headers.get('content-type')?.includes('application/json') ? await response.json() : null; } catch { return null; }
}
+export async function copySample(rig: Rig): Promise<LocalProject> {
+ const response = await fetch('/__studio/copy-sample', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(rig) });
+ if (!response.ok) throw new Error('Could not copy the sample.');
+ return response.json();
+}
export async function revealRepository() {
const response = await fetch('/__studio/reveal', { method: 'POST' });
if (!response.ok) throw new Error('Could not open repository.');
diff --git a/src/editor/workflow-i18n.ts b/src/editor/workflow-i18n.ts
index 043344a..a81ea2a 100644
--- a/src/editor/workflow-i18n.ts
+++ b/src/editor/workflow-i18n.ts
@@ -13,7 +13,11 @@ export const workflowEn = {
agentUnknownPath: 'The browser cannot read this folder’s full path. Open it from the development server’s project list to prepare an exact request.',
agentEyes: 'eye', agentMouth: 'mouth', agentBoth: 'eye and mouth',
rebuild: 'Save and rebuild layers', rebuilding: 'Saving and rebuilding layers…', staleLocal: 'Outlines changed. Rebuild layers to update the preview.',
- rebuildUnavailable: 'Automatic rebuild needs a writable project from the local list. Browser-picked folders have no server path; save the rig, run build-layers from the repository root, then reopen the folder.',
+ staleSample: 'The sample is read-only. To continue editing, copy it into a project.', copyContinue: 'Copy and continue editing',
+ staleListed: 'This project is available in the project list.', reopenListed: 'Reopen from the list',
+ sampleRebuildReason: 'Rebuild is unavailable because the sample is read-only.', folderRebuildReason: 'Rebuild is unavailable because the browser cannot identify this folder’s location.',
+ continueError: 'Could not open an editable project. Your edits are still here; try again.',
+ rebuildUnavailable: 'Save rig.json, run build-layers in the project folder, then reopen it.',
jobFailed: 'The local tool could not finish. Previous layers were kept.', dependenciesHelp: 'Install uv and Python 3.10 or later, then try again. With Homebrew: brew install uv python. Setup: docs/agent-guide.md.',
unsafeFilesHelp: 'The project contains redirected files. Use regular files inside this project and try again.', showLog: 'Show log', operationBusy: 'Working locally…', reloadFailed: 'Could not reload the project. The current view is still open.',
variantsTitle: 'Drawn variants', variantMissing: 'Missing', variantsHelp: 'Drawn expressions make closed eyes and speaking look more natural.',
@@ -43,7 +47,11 @@ export const workflowJa: typeof workflowEn = {
agentUnknownPath: 'ブラウザで選んだフォルダの実際の場所は取得できません。正しい場所を含む依頼文を作るには、開発サーバーのプロジェクト一覧から開いてください。',
agentEyes: '目', agentMouth: '口', agentBoth: '目と口',
rebuild: '保存してレイヤーを作り直す', rebuilding: '保存してレイヤーを作り直しています…', staleLocal: '輪郭が変更されました。レイヤーを作り直すとプレビューに反映されます。',
- rebuildUnavailable: '自動で作り直すには、ローカル一覧から編集できるプロジェクトを開いてください。ブラウザで選んだフォルダはサーバー上の場所を取得できません。設定を保存し、リポジトリのルートで build-layers を実行してから開き直してください。',
+ staleSample: 'サンプルは読み取り専用です。編集を続けるには、コピーしてプロジェクトにしてください。', copyContinue: 'コピーして編集を続ける',
+ staleListed: 'このプロジェクトは一覧から開けます', reopenListed: '一覧から開き直す',
+ sampleRebuildReason: '読み取り専用のため、このままでは作り直せません。', folderRebuildReason: 'ブラウザで選んだフォルダの場所を取得できないため、このままでは作り直せません。',
+ continueError: '編集できるプロジェクトを開けませんでした。今の編集内容は残っています。もう一度お試しください。',
+ rebuildUnavailable: '設定を保存し、そのフォルダで build-layers を実行してから開き直してください。',
jobFailed: '作業を完了できませんでした。以前のレイヤーは残しています。', dependenciesHelp: 'uv と Python 3.10 以降を用意してから、もう一度お試しください。Homebrew の場合: brew install uv python。準備手順: docs/agent-guide.md。',
unsafeFilesHelp: 'プロジェクトに別の場所へ転送するファイルがあります。このプロジェクト内の通常のファイルにしてからお試しください。', showLog: 'ログを表示', operationBusy: 'この端末で処理中…', reloadFailed: 'プロジェクトを読み込み直せませんでした。現在の画面は残っています。',
variantsTitle: '描き分け画像', variantMissing: 'なし', variantsHelp: '目を閉じたときや話すときの絵を描き分けると、動きが自然になります。',
diff --git a/src/server/local-projects.ts b/src/server/local-projects.ts
index 3810251..820324a 100644
--- a/src/server/local-projects.ts
+++ b/src/server/local-projects.ts
@@ -1,7 +1,7 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
-import { readFile, readdir, realpath, stat, writeFile, rename, unlink } from 'node:fs/promises';
+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 type { IncomingMessage, ServerResponse } from 'node:http';
import type { Plugin } from 'vite';
@@ -92,6 +92,30 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
});
if (parts.length === 1 && parts[0] === 'context' && req.method === 'GET') { json(200, { rootPath: root, displayRootPath: displayPath(root) }); return; }
if (parts.length === 1 && parts[0] === 'reveal' && req.method === 'POST') { await reveal(root); json(200, { path: root }); return; }
+ if (parts.length === 1 && parts[0] === 'copy-sample' && req.method === 'POST') {
+ const rig = await readBody(req), errors = validateRig(rig);
+ if (errors.length) throw new HttpError(400, `Invalid rig: ${errors.join(', ')}`);
+ await folder(SAMPLE);
+ await mkdir(base, { recursive: true });
+ if (await realpath(base) !== base) throw new HttpError(400, 'Project root cannot redirect elsewhere.');
+ let name = 'miko-qipao-copy', path = resolve(base, name);
+ for (let index = 1; ; index++) {
+ try { await mkdir(path); break; }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ name = `miko-qipao-copy-${index}`; path = resolve(base, name);
+ }
+ }
+ try {
+ await cp(sample, path, { recursive: true, force: false, errorOnExist: true, filter: async source => {
+ if ((await lstat(source)).isSymbolicLink()) throw new HttpError(400, 'Sample contains redirected files.');
+ return true;
+ } });
+ await saveRig(path, rig);
+ json(200, await info(name));
+ } catch (error) { await rm(path, { recursive: true, force: true }); throw error; }
+ return;
+ }
if (parts[0] !== 'projects') throw new HttpError(404, 'Not found.');
if (parts.length === 1 && req.method === 'GET') {
if (await exists(base) && await realpath(base) !== base) throw new HttpError(400, 'Project root cannot redirect elsewhere.');
diff --git a/tests/local-projects.test.ts b/tests/local-projects.test.ts
index 2f70c48..3d54a52 100644
--- a/tests/local-projects.test.ts
+++ b/tests/local-projects.test.ts
@@ -94,3 +94,27 @@ test('plugin is development-only and has no production or preview middleware hoo
const plugin = localProjectsPlugin(root);
expect(plugin.apply).toBe('serve'); expect(plugin.configurePreviewServer).toBeUndefined();
});
+
+
+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;
+ const original = await readFile(resolve(root, 'samples/miko-qipao/rig.json'));
+ expect((await call('/__studio/copy-sample', 'POST', { version: 1 })).status).toBe(400);
+ expect((await call('/__studio/copy-sample', 'POST', edited, { origin: 'https://example.invalid' })).status).toBe(403);
+ await mkdir(resolve(root, 'projects/miko-qipao-copy'));
+ await writeFile(resolve(root, 'projects/miko-qipao-copy/keep.txt'), 'keep');
+ const results = await Promise.all([call('/__studio/copy-sample', 'POST', edited), call('/__studio/copy-sample', 'POST', edited)]);
+ expect(results.map(result => result.status)).toEqual([200, 200]);
+ const names = results.map(result => JSON.parse(result.body).name).sort();
+ expect(names).toEqual(['miko-qipao-copy-1', 'miko-qipao-copy-2']);
+ for (const name of names) {
+ expect(JSON.parse(await readFile(resolve(root, 'projects', name, 'rig.json'), 'utf8'))).toEqual(edited);
+ expect(await readFile(resolve(root, 'projects', name, 'source.png'), 'utf8')).toBe('synthetic image bytes');
+ expect(await readFile(resolve(root, 'projects', name, 'built/base.png'), 'utf8')).toBe('synthetic base bytes');
+ }
+ expect(await readFile(resolve(root, 'samples/miko-qipao/rig.json'))).toEqual(original);
+ expect(await readFile(resolve(root, 'projects/miko-qipao-copy/keep.txt'), 'utf8')).toBe('keep');
+ await symlink(resolve(root, 'projects/nova'), resolve(root, 'samples/miko-qipao/redirect'));
+ expect((await call('/__studio/copy-sample', 'POST', edited)).status).toBe(400);
+ expect((await call('/__studio/projects/miko-qipao-copy-3/rig.json')).status).toBe(404);
+});