Open History to see the last commit
1// `rive-video-preview wait-feedback [project-dir | file.riv]`
2//
3// Blocks until the user presses "Send to agent" (or returns at once if unread feedback is
4// already waiting), prints the feedback, marks it read and exits 0. Coding agents run it as a
5// background command: when it exits, its output wakes the agent with the feedback, and the
6// agent's session stays free while it waits. It reads bundles from disk, so the player does
7// not have to be running.
8import { existsSync, readFileSync, statSync, watch } from 'node:fs';
9import { readFile } from 'node:fs/promises';
10import path from 'node:path';
11import { FeedbackStore, bundleMarkdown } from './feedback.mjs';
12import { claimBundles, registerListener } from './listeners.mjs';
13
14export const EXIT_TIMEOUT = 124; // like timeout(1)
15const EXIT_INTERRUPTED = 130;
16const POLL_MS = 2000; // fallback when file events are missed or unsupported
17const SETTLE_MS = 300; // let bundles sent together all land before printing
18
19const HELP = `usage: rive-video-preview wait-feedback [project-dir | file.riv] [options]
20
21Wait until the user presses "Send to agent" in the player, print the feedback
22(notes, timecodes, artboard/animation, image paths, audio mix), mark it read
23and exit 0. Returns at once if unread feedback is already waiting. The player
24does not need to be running.
25
26Coding agents: start it as a background command after showing the player
27(Claude Code: Bash with run_in_background). It exits when the user sends
28feedback, which wakes you with it. Start it again after handling the feedback.
29
30options:
31 --timeout <time> give up after this long: 90, 90s, 10m, 2h (default: never)
32 --no-mark-read leave the bundles unread
33 -h, --help show this help
34
35exit codes:
36 0 feedback printed
37 1 error (bad arguments, not a Rive project, …)
38 ${EXIT_TIMEOUT} timed out with no feedback
39 130 interrupted (Ctrl-C)
40`;
41
42function fail(msg) {
43 console.error(`rive-video-preview wait-feedback: ${msg}\nrun with --help for usage`);
44 process.exit(1);
45}
46
47function parseDuration(s) {
48 const m = String(s).trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/i);
49 if (!m) return null;
50 const mult = { ms: 0.001, s: 1, m: 60, h: 3600 }[(m[2] || 's').toLowerCase()];
51 const sec = Number(m[1]) * mult;
52 return sec > 0 ? sec : null;
53}
54
55function parseArgs(argv) {
56 const opts = { markRead: true, timeout: null };
57 const positional = [];
58 for (let i = 0; i < argv.length; i++) {
59 const a = argv[i];
60 const [flag, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
61 switch (flag) {
62 case '-h':
63 case '--help':
64 opts.help = true;
65 break;
66 case '--timeout': {
67 const v = inline ?? argv[++i];
68 if (v === undefined) fail('--timeout needs a value');
69 opts.timeout = parseDuration(v);
70 if (opts.timeout == null) fail(`bad --timeout ${v} (use e.g. 90, 90s, 10m, 2h)`);
71 break;
72 }
73 case '--no-mark-read':
74 opts.markRead = false;
75 break;
76 default:
77 if (a.startsWith('-')) fail(`unknown option ${a}`);
78 positional.push(a);
79 }
80 }
81 if (positional.length > 1) fail('expected at most one project dir or .riv file');
82 opts.target = path.resolve(positional[0] ?? '.');
83 return opts;
84}
85
86function projectName(dir) {
87 try {
88 const m = readFileSync(path.join(dir, 'rive.yaml'), 'utf8').match(/^name:\s*["']?([^"'\n#]+?)["']?\s*$/m);
89 if (m) return m[1];
90 } catch {}
91 return path.basename(dir);
92}
93
94/**
95 * Resolve with the unread bundles once there are any. Watches the feedback folder and also
96 * polls, since file events can be missed (or unsupported, e.g. on some network drives).
97 * A bundle counts once its feedback.json exists: the store writes that file last, atomically.
98 * With `claim`, bundles are claimed exclusively (see claimBundles), so concurrent waiters never
99 * deliver the same one. Resolves with { bundles, claims } (release the claims when done), or
100 * null on timeout/abort.
101 */
102export function waitForBundles(store, { timeoutMs = null, signal, claim = true } = {}) {
103 return new Promise((resolve, reject) => {
104 let timer = null;
105 let poll = null;
106 let deadline = null;
107 let watcher = null;
108 let checking = false;
109 let again = false;
110 let settled = false;
111
112 const finish = (fn, value) => {
113 if (settled) return;
114 settled = true;
115 clearTimeout(timer);
116 clearInterval(poll);
117 clearTimeout(deadline);
118 watcher?.close();
119 signal?.removeEventListener('abort', onAbort);
120 fn(value);
121 };
122 const onAbort = () => finish(resolve, null);
123
124 const check = async () => {
125 if (checking) return void (again = true);
126 checking = true;
127 try {
128 let pending = await store.listBundles({ pendingOnly: true });
129 if (pending.length) {
130 // Another bundle may be landing right now (two quick sends): give it a moment.
131 await new Promise((r) => setTimeout(r, SETTLE_MS));
132 pending = await store.listBundles({ pendingOnly: true });
133 if (!claim) {
134 if (pending.length) return finish(resolve, { bundles: pending, claims: null });
135 } else {
136 // Another consumer may be delivering some of these; take only the rest.
137 const { claimed, claims } = claimBundles(store, pending);
138 if (claimed.length) {
139 if (settled) claims.release(); // timed out or aborted meanwhile
140 else return finish(resolve, { bundles: claimed, claims });
141 }
142 }
143 }
144 } catch (err) {
145 return finish(reject, err);
146 } finally {
147 checking = false;
148 }
149 if (again && !settled) {
150 again = false;
151 check();
152 }
153 };
154 const soon = () => {
155 clearTimeout(timer);
156 timer = setTimeout(check, 50);
157 };
158
159 if (signal?.aborted) return finish(resolve, null);
160 signal?.addEventListener('abort', onAbort);
161 for (const recursive of [true, false]) {
162 try {
163 // Recursive, to see feedback.json land inside a new bundle folder.
164 watcher = watch(store.sentDir, { recursive }, soon);
165 watcher.on('error', () => {});
166 break;
167 } catch {}
168 }
169 poll = setInterval(check, POLL_MS);
170 if (timeoutMs != null) deadline = setTimeout(() => finish(resolve, null), timeoutMs);
171 check();
172 });
173}
174
175const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
176
177async function formatBundles(bundles, { target, project, marked }) {
178 const out = [
179 `Rive preview feedback for ${project}: ${plural(bundles.length, 'bundle')} from the user${marked ? ' (now marked read)' : ''}.`,
180 `Project: ${target}`,
181 '',
182 ];
183 for (const b of bundles) {
184 let md;
185 try {
186 md = await readFile(b.markdown, 'utf8');
187 } catch {
188 md = bundleMarkdown(b);
189 }
190 out.push(`======== Bundle ${b.id} ========`, `Folder: ${b.dir}`, `feedback.md: ${b.markdown}`, '', md.trimEnd(), '');
191 out.push('Screenshots (open each image to see the frame):');
192 for (const s of b.shots) {
193 const where = [s.artboard, s.animation].filter(Boolean).join(' / ');
194 const r = s.region;
195 const box = r ? ` [region ${r.x}, ${r.y}, ${r.width} × ${r.height} in artboard units]` : '';
196 out.push(` ${s.index}. ${s.timecode}${where ? ` — ${where}` : ''}${box}: ${s.image}`);
197 }
198 out.push('');
199 }
200 out.push(
201 'Each timecode is seconds into the animation and the frame at its fps; fix that animation at that frame unless the note says otherwise.',
202 `When you have handled this, start \`rive-video-preview wait-feedback ${target}\` in the background again to hear the next round.`,
203 );
204 return out.join('\n') + '\n';
205}
206
207export async function runWaitFeedback(argv) {
208 const opts = parseArgs(argv);
209 if (opts.help) return void process.stdout.write(HELP);
210 const { target } = opts;
211 if (!existsSync(target)) fail(`${target} does not exist`);
212 let project;
213 if (statSync(target).isDirectory()) {
214 if (!existsSync(path.join(target, 'rive.yaml'))) fail(`${target} has no rive.yaml — not a Rive CLI project`);
215 project = projectName(target);
216 } else if (target.endsWith('.riv')) {
217 project = path.basename(target, '.riv');
218 } else {
219 fail('expected a Rive project directory or a .riv file');
220 }
221
222 const store = new FeedbackStore(target, { project });
223 await store.ensure();
224 const unregister = registerListener(target, 'cli');
225 const abort = new AbortController();
226 let interrupted = false;
227 for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
228 process.on(sig, () => {
229 interrupted = true;
230 abort.abort();
231 });
232 }
233
234 const limit = opts.timeout != null ? ` (timeout ${opts.timeout}s)` : '';
235 console.error(`Waiting for the user to press "Send to agent" for ${project} (${store.sentDir})${limit}…`);
236 let got;
237 try {
238 // --no-mark-read only peeks, so it doesn't claim the bundles away from another consumer.
239 got = await waitForBundles(store, { timeoutMs: opts.timeout != null ? opts.timeout * 1000 : null, signal: abort.signal, claim: opts.markRead });
240 } finally {
241 unregister();
242 }
243
244 if (!got) {
245 if (interrupted) {
246 console.error('Stopped waiting for feedback (interrupted).');
247 process.exitCode = EXIT_INTERRUPTED;
248 } else {
249 console.log(`No feedback arrived for ${project} within ${opts.timeout}s. Nothing was sent from the player; start the command again to keep listening.`);
250 process.exitCode = EXIT_TIMEOUT;
251 }
252 return;
253 }
254
255 const { bundles, claims } = got;
256 try {
257 const text = await formatBundles(bundles, { target, project, marked: opts.markRead });
258 await new Promise((resolve, reject) => process.stdout.write(text, (err) => (err ? reject(err) : resolve())));
259 if (opts.markRead) {
260 try {
261 for (const b of bundles) await store.markConsumed(b.id, 'agent');
262 } catch (err) {
263 // The feedback was printed; it just may be delivered again.
264 console.error(`Warning: could not mark the feedback read (${err.message}); it may be delivered again.`);
265 }
266 }
267 } finally {
268 claims?.release(); // read ones no longer need it; on failure the next consumer gets them
269 }
270 process.exitCode = 0;
271}