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

feedback.mjs

347 lines14.2 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, lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
18import path from 'node:path';
19import { mixMarkdown, sanitizeMix } from './mix.mjs';
20​
21const ID_RE = /^[a-z0-9-]+$/;
22// A bundle folder name as _share() makes it: bundleStamp(), plus a suffix on a same-second clash.
23const STAMP_RE = /^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(-[0-9a-f]{4})?$/;
24// Where _prune() moves a bundle just before deleting it: `.pruning-<bundle stamp>-<8 hex>`.
25const PRUNING_RE = /^\.pruning-\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(-[0-9a-f]{4})?-[0-9a-f]{8}$/;
26export const DEFAULT_FEEDBACK_DAYS = 14;
27​
28const isDirectory = (p) => existsSync(p) && statSync(p).isDirectory();
29​
30/** The shared `.rive-preview` folder: in the project dir, or beside a bare .riv. */
31export function feedbackTop(target) {
32 return path.join(isDirectory(target) ? target : path.dirname(target), '.rive-preview');
34​
35/** Where this target's drafts and bundles live (the player and the MCP server must agree). */
36export function feedbackRoot(target) {
37 return isDirectory(target) ? feedbackTop(target) : path.join(feedbackTop(target), path.basename(target));
39​
40const pad = (n, w = 2) => String(n).padStart(w, '0');
41​
42// Shot metadata comes from the browser: keep only values of the expected shape.
43const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
44const count = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
45const text = (v, max = 200) => (typeof v === 'string' ? v.slice(0, max) : null);
46​
47const round1 = (v) => Math.round(v * 10) / 10;
48​
49/**
50 * A highlighted region, in artboard units from the artboard's top-left, plus the artboard size:
51 * { x, y, width, height, artboardWidth, artboardHeight }. Anything else (or a box with no area
52 * inside the artboard) becomes null. The box is clamped to the artboard.
53 */
54export function sanitizeRegion(r) {
55 if (!r || typeof r !== 'object') return null;
56 const [x, y, w, h, aw, ah] = [r.x, r.y, r.width, r.height, r.artboardWidth, r.artboardHeight].map(num);
57 if ([x, y, w, h, aw, ah].some((v) => v == null) || aw <= 0 || ah <= 0 || w <= 0 || h <= 0) return null;
58 const x0 = Math.min(Math.max(x, 0), aw);
59 const y0 = Math.min(Math.max(y, 0), ah);
60 const x1 = Math.min(Math.max(x + w, 0), aw);
61 const y1 = Math.min(Math.max(y + h, 0), ah);
62 if (x1 <= x0 || y1 <= y0) return null;
63 return { x: round1(x0), y: round1(y0), width: round1(x1 - x0), height: round1(y1 - y0), artboardWidth: round1(aw), artboardHeight: round1(ah) };
65​
66/** "Region: 120, 80, 200 × 150 in artboard units (artboard 1920 × 1080)" */
67export function regionLine(r) {
68 if (!r) return null;
69 return `Region: ${r.x}, ${r.y}, ${r.width} × ${r.height} in artboard units (x, y, width × height from the artboard's top-left; artboard ${r.artboardWidth} × ${r.artboardHeight})`;
71​
72/** Resolve `name` inside `dir`, refusing anything that would land outside it. */
73function inside(dir, name) {
74 const full = path.resolve(dir, name);
75 if (path.dirname(full) !== path.resolve(dir)) throw new Error(`unsafe file name: ${name}`);
76 return full;
78​
79function bundleStamp(d = new Date()) {
80 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}-${pad(d.getSeconds())}`;
82​
83async function writeJsonAtomic(file, data) {
84 // Unique per write, so overlapping writes of one file never share (and steal) a temp file.
85 const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
86 await writeFile(tmp, JSON.stringify(data, null, 2) + '\n');
87 await rename(tmp, file);
89​
90function shotHeading(s) {
91 const where = [s.artboard, s.animation].filter(Boolean).join(' / ');
92 return `${s.timecode}${where ? ` — ${where}` : ''}`;
94​
95export function bundleMarkdown(b) {
96 const lines = [
97 `# Rive preview feedback — ${b.project}`,
98 '',
99 `Sent ${new Date(b.createdAt).toLocaleString()} · ${b.shots.length} screenshot${b.shots.length === 1 ? '' : 's'} · project: \`${b.target}\``,
100 '',
101 'Timecodes are seconds into the animation and the frame at its fps. Each image is the artboard',
102 'exactly as the preview player drew it at that frame. A shot with a "Region" line has that box',
103 'outlined (and the rest dimmed) on the image: the note is about what is inside it.',
104 '',
105 ];
106 if (b.message) lines.push('## Overall', '', b.message.trim(), '');
107 b.shots.forEach((s, i) => {
108 lines.push(`## ${i + 1}. ${shotHeading(s)}`, '', `![shot ${i + 1}](${s.file})`, '', `Image: \`${s.image}\``, '');
109 if (s.region) lines.push(regionLine(s.region), '');
110 lines.push(s.note?.trim() || '_(no note)_', '');
111 });
112 lines.push(...mixMarkdown(b.mix));
113 return lines.join('\n');
115​
116export class FeedbackStore {
117 constructor(target, { project } = {}) {
118 this.target = target;
119 this.project = project ?? path.basename(target);
120 this.top = feedbackTop(target);
121 this.root = feedbackRoot(target);
122 this.draftsDir = path.join(this.root, 'drafts');
123 this.sentDir = path.join(this.root, 'feedback');
124 this.queue = Promise.resolve();
125 }
126​
127 /** Run store mutations one at a time, so a share never interleaves with a note update or delete. */
128 serial(fn) {
129 const run = this.queue.then(fn, fn);
130 this.queue = run.catch(() => {});
131 return run;
132 }
133​
134 async ensure() {
135 await mkdir(this.draftsDir, { recursive: true });
136 await mkdir(this.sentDir, { recursive: true });
137 const gi = path.join(this.top, '.gitignore');
138 if (!existsSync(gi)) await writeFile(gi, '*\n');
139 }
140​
141 // ------------------------------------------------------------ drafts
142 draftPng(id) {
143 if (!ID_RE.test(id)) throw new Error('bad id');
144 return path.join(this.draftsDir, `${id}.png`);
145 }
146​
147 async listDrafts() {
148 let names = [];
149 try {
150 names = (await readdir(this.draftsDir)).filter((n) => n.endsWith('.json'));
151 } catch {
152 return [];
153 }
154 const shots = [];
155 for (const n of names) {
156 try {
157 shots.push(JSON.parse(await readFile(path.join(this.draftsDir, n), 'utf8')));
158 } catch {}
159 }
160 return shots.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
161 }
162​
163 async addDraft({ png, ...meta }) {
164 await this.ensure();
165 const id = Date.now().toString(36) + '-' + randomBytes(3).toString('hex');
166 const shot = {
167 id,
168 createdAt: new Date().toISOString(),
169 note: '',
170 time: num(meta.time),
171 frame: count(meta.frame),
172 fps: num(meta.fps),
173 timecode: text(meta.timecode, 80) ?? '',
174 artboard: text(meta.artboard),
175 animation: text(meta.animation),
176 width: count(meta.width),
177 height: count(meta.height),
178 region: sanitizeRegion(meta.region),
179 };
180 await writeFile(this.draftPng(id), png);
181 await writeJsonAtomic(path.join(this.draftsDir, `${id}.json`), shot);
182 return shot;
183 }
184​
185 updateDraft(id, { note }) {
186 return this.serial(() => this._updateDraft(id, { note }));
187 }
188​
189 async _updateDraft(id, { note }) {
190 const file = path.join(this.draftsDir, `${id}.json`);
191 if (!ID_RE.test(id) || !existsSync(file)) return null;
192 const shot = JSON.parse(await readFile(file, 'utf8'));
193 if (typeof note === 'string') shot.note = note.slice(0, 20000);
194 await writeJsonAtomic(file, shot);
195 return shot;
196 }
197​
198 deleteDraft(id) {
199 return this.serial(() => this._deleteDraft(id));
200 }
201​
202 async _deleteDraft(id) {
203 if (!ID_RE.test(id)) return false;
204 await rm(path.join(this.draftsDir, `${id}.json`), { force: true });
205 await rm(path.join(this.draftsDir, `${id}.png`), { force: true });
206 return true;
207 }
208​
209 // ------------------------------------------------------------ bundles
210 /** Move every draft into a new feedback bundle. */
211 share({ message = '' } = {}) {
212 return this.serial(() => this._share({ message: String(message ?? '').slice(0, 20000) }));
213 }
214​
215 async _share({ message }) {
216 const drafts = await this.listDrafts();
217 if (!drafts.length) throw new Error('no screenshots to send');
218 await this.ensure();
219 let id = bundleStamp();
220 if (existsSync(path.join(this.sentDir, id))) id += '-' + randomBytes(2).toString('hex');
221 const dir = path.join(this.sentDir, id);
222 await mkdir(dir, { recursive: true });
223​
224 const shots = [];
225 for (const [i, d] of drafts.entries()) {
226 const frame = count(d.frame);
227 const file = `${pad(i + 1)}${frame != null ? `-f${frame}` : ''}.png`;
228 await copyFile(this.draftPng(d.id), inside(dir, file));
229 const { id: _id, ...rest } = d;
230 shots.push({ index: i + 1, ...rest, frame, region: sanitizeRegion(d.region), file, image: path.join(dir, file) });
231 }
232 let mix = null;
233 try {
234 mix = sanitizeMix(JSON.parse(await readFile(path.join(this.root, 'mix.json'), 'utf8')));
235 } catch {}
236 const bundle = {
237 id,
238 createdAt: new Date().toISOString(),
239 project: this.project,
240 target: this.target,
241 message: message.trim(),
242 dir,
243 markdown: path.join(dir, 'feedback.md'),
244 shots,
245 mix,
246 };
247 await writeFile(bundle.markdown, bundleMarkdown(bundle));
248 // feedback.json last: its presence is what marks the bundle complete.
249 await writeJsonAtomic(path.join(dir, 'feedback.json'), bundle);
250 for (const d of drafts) await this._deleteDraft(d.id);
251 return bundle;
252 }
253​
254 async listBundles({ pendingOnly = false } = {}) {
255 let names = [];
256 try {
257 names = await readdir(this.sentDir);
258 } catch {
259 return [];
260 }
261 const out = [];
262 for (const n of names.sort()) {
263 const dir = path.join(this.sentDir, n);
264 try {
265 const b = JSON.parse(await readFile(path.join(dir, 'feedback.json'), 'utf8'));
266 let consumed = null;
267 try {
268 consumed = JSON.parse(await readFile(path.join(dir, 'consumed.json'), 'utf8'));
269 } catch {}
270 if (pendingOnly && consumed) continue;
271 out.push({ ...b, consumed });
272 } catch {}
273 }
274 return out;
275 }
276​
277 /**
278 * Delete bundles an agent read more than `olderThanDays` days ago (by consumed.json `at`).
279 * Only touches direct children of the feedback dir that look like a complete bundle; unread
280 * bundles, drafts, mix.json and anything unexpected are left alone. Returns the ids removed
281 * (or, with dryRun, the ones that would be).
282 */
283 prune({ olderThanDays = DEFAULT_FEEDBACK_DAYS, dryRun = false } = {}) {
284 return this.serial(() => this._prune({ olderThanDays, dryRun }));
285 }
286​
287 async _prune({ olderThanDays, dryRun }) {
288 if (!Number.isFinite(olderThanDays) || olderThanDays < 0) throw new Error(`bad olderThanDays: ${olderThanDays}`);
289 const cutoff = Date.now() - olderThanDays * 86400000;
290 const sentDir = path.resolve(this.sentDir);
291 let names = [];
292 let realParent;
293 try {
294 if (!(await lstat(sentDir)).isDirectory()) return [];
295 // No symlinks between the project (or the .riv's folder) and the feedback dir either,
296 // so a linked .rive-preview can't send deletes somewhere else.
297 const base = isDirectory(this.target) ? this.target : path.dirname(this.target);
298 realParent = path.join(await realpath(base), path.relative(path.resolve(base), path.dirname(sentDir)));
299 if ((await realpath(sentDir)) !== path.join(realParent, path.basename(sentDir))) return [];
300 names = await readdir(sentDir);
301 // Leftovers of a prune that stopped partway (see below).
302 if (!dryRun) {
303 for (const n of await readdir(path.dirname(sentDir))) {
304 if (!PRUNING_RE.test(n)) continue;
305 const leftover = inside(path.dirname(sentDir), n);
306 if ((await lstat(leftover).catch(() => null))?.isDirectory()) await rm(leftover, { recursive: true, force: true }).catch(() => {});
307 }
308 }
309 } catch {
310 return [];
311 }
312 const removed = [];
313 for (const n of names.sort()) {
314 if (!STAMP_RE.test(n)) continue;
315 try {
316 const dir = inside(sentDir, n);
317 if (!(await lstat(dir)).isDirectory()) continue; // not a symlink, not a file
318 const fbJson = inside(dir, 'feedback.json');
319 if (!(await lstat(fbJson)).isFile()) continue;
320 const consumed = JSON.parse(await readFile(inside(dir, 'consumed.json'), 'utf8'));
321 const at = typeof consumed?.at === 'string' ? Date.parse(consumed.at) : NaN;
322 if (!Number.isFinite(at) || at >= cutoff) continue;
323 if (!dryRun) {
324 // Move it out of the feedback dir in one step, then delete it there. rename() and rm()
325 // act on a symlink itself, never through it, so a folder swapped for a link after the
326 // checks above only loses the link. listBundles() stops seeing the bundle at once.
327 const doomed = inside(path.dirname(sentDir), `.pruning-${n}-${randomBytes(4).toString('hex')}`);
328 await rename(dir, doomed);
329 // If a folder above was swapped for a link meanwhile, the move went elsewhere: undo it.
330 if ((await realpath(doomed)) !== path.join(realParent, path.basename(doomed))) {
331 await rename(doomed, dir).catch(() => {});
332 continue;
333 }
334 await rm(doomed, { recursive: true, force: true });
335 }
336 removed.push(n);
337 } catch {} // unreadable, malformed or vanished: leave it
338 }
339 return removed;
340 }
341​
342 async markConsumed(id, by = 'agent') {
343 if (!/^[\w-]+$/.test(id)) return;
344 const dir = path.join(this.sentDir, id);
345 if (existsSync(dir)) await writeJsonAtomic(path.join(dir, 'consumed.json'), { at: new Date().toISOString(), by });
346 }