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