Skip to content
Source
Sign inSign up
fuko/rive-preview-player
Open History to see the last commit

feedback.mjs

241 lines8.7 KB

1// Screenshots + notes taken in the player, and the feedback bundles sent to a
2// coding agent. Everything lives on disk under <project>/.rive-preview/ so the
3// MCP server (a separate process) and plain file-reading agents can see it:
4//
5// .rive-preview/
6// .gitignore "*" — never committed
7// [<name>.riv/] for a bare .riv: its own subfolder, so .riv files that
8// share a folder keep separate drafts and bundles
9// drafts/<id>.png|.json shots not sent yet (notes still editable)
10// feedback/<bundle-id>/ one folder per "Send to agent"
11// feedback.md human/agent-readable summary with image paths
12// feedback.json the same, structured
13// 01-f741.png … the screenshots
14// consumed.json written once an agent has read the bundle
15import { randomBytes } from 'node:crypto';
16import { existsSync, statSync } from 'node:fs';
17import { copyFile, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
18import path from 'node:path';
19​
20const ID_RE = /^[a-z0-9-]+$/;
21​
22const isDirectory = (p) => existsSync(p) && statSync(p).isDirectory();
23​
24/** The shared `.rive-preview` folder: in the project dir, or beside a bare .riv. */
25export function feedbackTop(target) {
26 return path.join(isDirectory(target) ? target : path.dirname(target), '.rive-preview');
28​
29/** Where this target's drafts and bundles live (the player and the MCP server must agree). */
30export function feedbackRoot(target) {
31 return isDirectory(target) ? feedbackTop(target) : path.join(feedbackTop(target), path.basename(target));
33​
34const pad = (n, w = 2) => String(n).padStart(w, '0');
35​
36// Shot metadata comes from the browser: keep only values of the expected shape.
37const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
38const count = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
39const text = (v, max = 200) => (typeof v === 'string' ? v.slice(0, max) : null);
40​
41/** Resolve `name` inside `dir`, refusing anything that would land outside it. */
42function inside(dir, name) {
43 const full = path.resolve(dir, name);
44 if (path.dirname(full) !== path.resolve(dir)) throw new Error(`unsafe file name: ${name}`);
45 return full;
47​
48function bundleStamp(d = new Date()) {
49 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}-${pad(d.getSeconds())}`;
51​
52async function writeJsonAtomic(file, data) {
53 // Unique per write, so overlapping writes of one file never share (and steal) a temp file.
54 const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
55 await writeFile(tmp, JSON.stringify(data, null, 2) + '\n');
56 await rename(tmp, file);
58​
59function shotHeading(s) {
60 const where = [s.artboard, s.animation].filter(Boolean).join(' / ');
61 return `${s.timecode}${where ? ` — ${where}` : ''}`;
63​
64export function bundleMarkdown(b) {
65 const lines = [
66 `# Rive preview feedback — ${b.project}`,
67 '',
68 `Sent ${new Date(b.createdAt).toLocaleString()} · ${b.shots.length} screenshot${b.shots.length === 1 ? '' : 's'} · project: \`${b.target}\``,
69 '',
70 'Timecodes are seconds into the animation and the frame at its fps. Each image is the artboard',
71 'exactly as the preview player drew it at that frame.',
72 '',
73 ];
74 if (b.message) lines.push('## Overall', '', b.message.trim(), '');
75 b.shots.forEach((s, i) => {
76 lines.push(`## ${i + 1}. ${shotHeading(s)}`, '', `![shot ${i + 1}](${s.file})`, '', `Image: \`${s.image}\``, '', s.note?.trim() || '_(no note)_', '');
77 });
78 return lines.join('\n');
80​
81export class FeedbackStore {
82 constructor(target, { project } = {}) {
83 this.target = target;
84 this.project = project ?? path.basename(target);
85 this.top = feedbackTop(target);
86 this.root = feedbackRoot(target);
87 this.draftsDir = path.join(this.root, 'drafts');
88 this.sentDir = path.join(this.root, 'feedback');
89 this.queue = Promise.resolve();
90 }
91​
92 /** Run store mutations one at a time, so a share never interleaves with a note update or delete. */
93 serial(fn) {
94 const run = this.queue.then(fn, fn);
95 this.queue = run.catch(() => {});
96 return run;
97 }
98​
99 async ensure() {
100 await mkdir(this.draftsDir, { recursive: true });
101 await mkdir(this.sentDir, { recursive: true });
102 const gi = path.join(this.top, '.gitignore');
103 if (!existsSync(gi)) await writeFile(gi, '*\n');
104 }
105​
106 // ------------------------------------------------------------ drafts
107 draftPng(id) {
108 if (!ID_RE.test(id)) throw new Error('bad id');
109 return path.join(this.draftsDir, `${id}.png`);
110 }
111​
112 async listDrafts() {
113 let names = [];
114 try {
115 names = (await readdir(this.draftsDir)).filter((n) => n.endsWith('.json'));
116 } catch {
117 return [];
118 }
119 const shots = [];
120 for (const n of names) {
121 try {
122 shots.push(JSON.parse(await readFile(path.join(this.draftsDir, n), 'utf8')));
123 } catch {}
124 }
125 return shots.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
126 }
127​
128 async addDraft({ png, ...meta }) {
129 await this.ensure();
130 const id = Date.now().toString(36) + '-' + randomBytes(3).toString('hex');
131 const shot = {
132 id,
133 createdAt: new Date().toISOString(),
134 note: '',
135 time: num(meta.time),
136 frame: count(meta.frame),
137 fps: num(meta.fps),
138 timecode: text(meta.timecode, 80) ?? '',
139 artboard: text(meta.artboard),
140 animation: text(meta.animation),
141 width: count(meta.width),
142 height: count(meta.height),
143 };
144 await writeFile(this.draftPng(id), png);
145 await writeJsonAtomic(path.join(this.draftsDir, `${id}.json`), shot);
146 return shot;
147 }
148​
149 updateDraft(id, { note }) {
150 return this.serial(() => this._updateDraft(id, { note }));
151 }
152​
153 async _updateDraft(id, { note }) {
154 const file = path.join(this.draftsDir, `${id}.json`);
155 if (!ID_RE.test(id) || !existsSync(file)) return null;
156 const shot = JSON.parse(await readFile(file, 'utf8'));
157 if (typeof note === 'string') shot.note = note.slice(0, 20000);
158 await writeJsonAtomic(file, shot);
159 return shot;
160 }
161​
162 deleteDraft(id) {
163 return this.serial(() => this._deleteDraft(id));
164 }
165​
166 async _deleteDraft(id) {
167 if (!ID_RE.test(id)) return false;
168 await rm(path.join(this.draftsDir, `${id}.json`), { force: true });
169 await rm(path.join(this.draftsDir, `${id}.png`), { force: true });
170 return true;
171 }
172​
173 // ------------------------------------------------------------ bundles
174 /** Move every draft into a new feedback bundle. */
175 share({ message = '' } = {}) {
176 return this.serial(() => this._share({ message: String(message ?? '').slice(0, 20000) }));
177 }
178​
179 async _share({ message }) {
180 const drafts = await this.listDrafts();
181 if (!drafts.length) throw new Error('no screenshots to send');
182 await this.ensure();
183 let id = bundleStamp();
184 if (existsSync(path.join(this.sentDir, id))) id += '-' + randomBytes(2).toString('hex');
185 const dir = path.join(this.sentDir, id);
186 await mkdir(dir, { recursive: true });
187​
188 const shots = [];
189 for (const [i, d] of drafts.entries()) {
190 const frame = count(d.frame);
191 const file = `${pad(i + 1)}${frame != null ? `-f${frame}` : ''}.png`;
192 await copyFile(this.draftPng(d.id), inside(dir, file));
193 const { id: _id, ...rest } = d;
194 shots.push({ index: i + 1, ...rest, frame, file, image: path.join(dir, file) });
195 }
196 const bundle = {
197 id,
198 createdAt: new Date().toISOString(),
199 project: this.project,
200 target: this.target,
201 message: message.trim(),
202 dir,
203 markdown: path.join(dir, 'feedback.md'),
204 shots,
205 };
206 await writeFile(bundle.markdown, bundleMarkdown(bundle));
207 // feedback.json last: its presence is what marks the bundle complete.
208 await writeJsonAtomic(path.join(dir, 'feedback.json'), bundle);
209 for (const d of drafts) await this._deleteDraft(d.id);
210 return bundle;
211 }
212​
213 async listBundles({ pendingOnly = false } = {}) {
214 let names = [];
215 try {
216 names = await readdir(this.sentDir);
217 } catch {
218 return [];
219 }
220 const out = [];
221 for (const n of names.sort()) {
222 const dir = path.join(this.sentDir, n);
223 try {
224 const b = JSON.parse(await readFile(path.join(dir, 'feedback.json'), 'utf8'));
225 let consumed = null;
226 try {
227 consumed = JSON.parse(await readFile(path.join(dir, 'consumed.json'), 'utf8'));
228 } catch {}
229 if (pendingOnly && consumed) continue;
230 out.push({ ...b, consumed });
231 } catch {}
232 }
233 return out;
234 }
235​
236 async markConsumed(id, by = 'agent') {
237 if (!/^[\w-]+$/.test(id)) return;
238 const dir = path.join(this.sentDir, id);
239 if (existsSync(dir)) await writeJsonAtomic(path.join(dir, 'consumed.json'), { at: new Date().toISOString(), by });
240 }