Open History to see the last commit
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');
33}
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));
38}
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
47/** Resolve `name` inside `dir`, refusing anything that would land outside it. */
48function inside(dir, name) {
49 const full = path.resolve(dir, name);
50 if (path.dirname(full) !== path.resolve(dir)) throw new Error(`unsafe file name: ${name}`);
51 return full;
52}
53
54function bundleStamp(d = new Date()) {
55 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}-${pad(d.getSeconds())}`;
56}
57
58async function writeJsonAtomic(file, data) {
59 // Unique per write, so overlapping writes of one file never share (and steal) a temp file.
60 const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
61 await writeFile(tmp, JSON.stringify(data, null, 2) + '\n');
62 await rename(tmp, file);
63}
64
65function shotHeading(s) {
66 const where = [s.artboard, s.animation].filter(Boolean).join(' / ');
67 return `${s.timecode}${where ? ` — ${where}` : ''}`;
68}
69
70export function bundleMarkdown(b) {
71 const lines = [
72 `# Rive preview feedback — ${b.project}`,
73 '',
74 `Sent ${new Date(b.createdAt).toLocaleString()} · ${b.shots.length} screenshot${b.shots.length === 1 ? '' : 's'} · project: \`${b.target}\``,
75 '',
76 'Timecodes are seconds into the animation and the frame at its fps. Each image is the artboard',
77 'exactly as the preview player drew it at that frame.',
78 '',
79 ];
80 if (b.message) lines.push('## Overall', '', b.message.trim(), '');
81 b.shots.forEach((s, i) => {
82 lines.push(`## ${i + 1}. ${shotHeading(s)}`, '', ``, '', `Image: \`${s.image}\``, '', s.note?.trim() || '_(no note)_', '');
83 });
84 lines.push(...mixMarkdown(b.mix));
85 return lines.join('\n');
86}
87
88export class FeedbackStore {
89 constructor(target, { project } = {}) {
90 this.target = target;
91 this.project = project ?? path.basename(target);
92 this.top = feedbackTop(target);
93 this.root = feedbackRoot(target);
94 this.draftsDir = path.join(this.root, 'drafts');
95 this.sentDir = path.join(this.root, 'feedback');
96 this.queue = Promise.resolve();
97 }
98
99 /** Run store mutations one at a time, so a share never interleaves with a note update or delete. */
100 serial(fn) {
101 const run = this.queue.then(fn, fn);
102 this.queue = run.catch(() => {});
103 return run;
104 }
105
106 async ensure() {
107 await mkdir(this.draftsDir, { recursive: true });
108 await mkdir(this.sentDir, { recursive: true });
109 const gi = path.join(this.top, '.gitignore');
110 if (!existsSync(gi)) await writeFile(gi, '*\n');
111 }
112
113 // ------------------------------------------------------------ drafts
114 draftPng(id) {
115 if (!ID_RE.test(id)) throw new Error('bad id');
116 return path.join(this.draftsDir, `${id}.png`);
117 }
118
119 async listDrafts() {
120 let names = [];
121 try {
122 names = (await readdir(this.draftsDir)).filter((n) => n.endsWith('.json'));
123 } catch {
124 return [];
125 }
126 const shots = [];
127 for (const n of names) {
128 try {
129 shots.push(JSON.parse(await readFile(path.join(this.draftsDir, n), 'utf8')));
130 } catch {}
131 }
132 return shots.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
133 }
134
135 async addDraft({ png, ...meta }) {
136 await this.ensure();
137 const id = Date.now().toString(36) + '-' + randomBytes(3).toString('hex');
138 const shot = {
139 id,
140 createdAt: new Date().toISOString(),
141 note: '',
142 time: num(meta.time),
143 frame: count(meta.frame),
144 fps: num(meta.fps),
145 timecode: text(meta.timecode, 80) ?? '',
146 artboard: text(meta.artboard),
147 animation: text(meta.animation),
148 width: count(meta.width),
149 height: count(meta.height),
150 };
151 await writeFile(this.draftPng(id), png);
152 await writeJsonAtomic(path.join(this.draftsDir, `${id}.json`), shot);
153 return shot;
154 }
155
156 updateDraft(id, { note }) {
157 return this.serial(() => this._updateDraft(id, { note }));
158 }
159
160 async _updateDraft(id, { note }) {
161 const file = path.join(this.draftsDir, `${id}.json`);
162 if (!ID_RE.test(id) || !existsSync(file)) return null;
163 const shot = JSON.parse(await readFile(file, 'utf8'));
164 if (typeof note === 'string') shot.note = note.slice(0, 20000);
165 await writeJsonAtomic(file, shot);
166 return shot;
167 }
168
169 deleteDraft(id) {
170 return this.serial(() => this._deleteDraft(id));
171 }
172
173 async _deleteDraft(id) {
174 if (!ID_RE.test(id)) return false;
175 await rm(path.join(this.draftsDir, `${id}.json`), { force: true });
176 await rm(path.join(this.draftsDir, `${id}.png`), { force: true });
177 return true;
178 }
179
180 // ------------------------------------------------------------ bundles
181 /** Move every draft into a new feedback bundle. */
182 share({ message = '' } = {}) {
183 return this.serial(() => this._share({ message: String(message ?? '').slice(0, 20000) }));
184 }
185
186 async _share({ message }) {
187 const drafts = await this.listDrafts();
188 if (!drafts.length) throw new Error('no screenshots to send');
189 await this.ensure();
190 let id = bundleStamp();
191 if (existsSync(path.join(this.sentDir, id))) id += '-' + randomBytes(2).toString('hex');
192 const dir = path.join(this.sentDir, id);
193 await mkdir(dir, { recursive: true });
194
195 const shots = [];
196 for (const [i, d] of drafts.entries()) {
197 const frame = count(d.frame);
198 const file = `${pad(i + 1)}${frame != null ? `-f${frame}` : ''}.png`;
199 await copyFile(this.draftPng(d.id), inside(dir, file));
200 const { id: _id, ...rest } = d;
201 shots.push({ index: i + 1, ...rest, frame, file, image: path.join(dir, file) });
202 }
203 let mix = null;
204 try {
205 mix = sanitizeMix(JSON.parse(await readFile(path.join(this.root, 'mix.json'), 'utf8')));
206 } catch {}
207 const bundle = {
208 id,
209 createdAt: new Date().toISOString(),
210 project: this.project,
211 target: this.target,
212 message: message.trim(),
213 dir,
214 markdown: path.join(dir, 'feedback.md'),
215 shots,
216 mix,
217 };
218 await writeFile(bundle.markdown, bundleMarkdown(bundle));
219 // feedback.json last: its presence is what marks the bundle complete.
220 await writeJsonAtomic(path.join(dir, 'feedback.json'), bundle);
221 for (const d of drafts) await this._deleteDraft(d.id);
222 return bundle;
223 }
224
225 async listBundles({ pendingOnly = false } = {}) {
226 let names = [];
227 try {
228 names = await readdir(this.sentDir);
229 } catch {
230 return [];
231 }
232 const out = [];
233 for (const n of names.sort()) {
234 const dir = path.join(this.sentDir, n);
235 try {
236 const b = JSON.parse(await readFile(path.join(dir, 'feedback.json'), 'utf8'));
237 let consumed = null;
238 try {
239 consumed = JSON.parse(await readFile(path.join(dir, 'consumed.json'), 'utf8'));
240 } catch {}
241 if (pendingOnly && consumed) continue;
242 out.push({ ...b, consumed });
243 } catch {}
244 }
245 return out;
246 }
247
248 /**
249 * Delete bundles an agent read more than `olderThanDays` days ago (by consumed.json `at`).
250 * Only touches direct children of the feedback dir that look like a complete bundle; unread
251 * bundles, drafts, mix.json and anything unexpected are left alone. Returns the ids removed
252 * (or, with dryRun, the ones that would be).
253 */
254 prune({ olderThanDays = DEFAULT_FEEDBACK_DAYS, dryRun = false } = {}) {
255 return this.serial(() => this._prune({ olderThanDays, dryRun }));
256 }
257
258 async _prune({ olderThanDays, dryRun }) {
259 if (!Number.isFinite(olderThanDays) || olderThanDays < 0) throw new Error(`bad olderThanDays: ${olderThanDays}`);
260 const cutoff = Date.now() - olderThanDays * 86400000;
261 const sentDir = path.resolve(this.sentDir);
262 let names = [];
263 let realParent;
264 try {
265 if (!(await lstat(sentDir)).isDirectory()) return [];
266 // No symlinks between the project (or the .riv's folder) and the feedback dir either,
267 // so a linked .rive-preview can't send deletes somewhere else.
268 const base = isDirectory(this.target) ? this.target : path.dirname(this.target);
269 realParent = path.join(await realpath(base), path.relative(path.resolve(base), path.dirname(sentDir)));
270 if ((await realpath(sentDir)) !== path.join(realParent, path.basename(sentDir))) return [];
271 names = await readdir(sentDir);
272 // Leftovers of a prune that stopped partway (see below).
273 if (!dryRun) {
274 for (const n of await readdir(path.dirname(sentDir))) {
275 if (!PRUNING_RE.test(n)) continue;
276 const leftover = inside(path.dirname(sentDir), n);
277 if ((await lstat(leftover).catch(() => null))?.isDirectory()) await rm(leftover, { recursive: true, force: true }).catch(() => {});
278 }
279 }
280 } catch {
281 return [];
282 }
283 const removed = [];
284 for (const n of names.sort()) {
285 if (!STAMP_RE.test(n)) continue;
286 try {
287 const dir = inside(sentDir, n);
288 if (!(await lstat(dir)).isDirectory()) continue; // not a symlink, not a file
289 const fbJson = inside(dir, 'feedback.json');
290 if (!(await lstat(fbJson)).isFile()) continue;
291 const consumed = JSON.parse(await readFile(inside(dir, 'consumed.json'), 'utf8'));
292 const at = typeof consumed?.at === 'string' ? Date.parse(consumed.at) : NaN;
293 if (!Number.isFinite(at) || at >= cutoff) continue;
294 if (!dryRun) {
295 // Move it out of the feedback dir in one step, then delete it there. rename() and rm()
296 // act on a symlink itself, never through it, so a folder swapped for a link after the
297 // checks above only loses the link. listBundles() stops seeing the bundle at once.
298 const doomed = inside(path.dirname(sentDir), `.pruning-${n}-${randomBytes(4).toString('hex')}`);
299 await rename(dir, doomed);
300 // If a folder above was swapped for a link meanwhile, the move went elsewhere: undo it.
301 if ((await realpath(doomed)) !== path.join(realParent, path.basename(doomed))) {
302 await rename(doomed, dir).catch(() => {});
303 continue;
304 }
305 await rm(doomed, { recursive: true, force: true });
306 }
307 removed.push(n);
308 } catch {} // unreadable, malformed or vanished: leave it
309 }
310 return removed;
311 }
312
313 async markConsumed(id, by = 'agent') {
314 if (!/^[\w-]+$/.test(id)) return;
315 const dir = path.join(this.sentDir, id);
316 if (existsSync(dir)) await writeJsonAtomic(path.join(dir, 'consumed.json'), { at: new Date().toISOString(), by });
317 }
318}