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

wait-feedback.mjs

269 lines9.9 KB

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);
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;
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;
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);
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 });
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 out.push(` ${s.index}. ${s.timecode}${where ? ` — ${where}` : ''}: ${s.image}`);
195 }
196 out.push('');
197 }
198 out.push(
199 'Each timecode is seconds into the animation and the frame at its fps; fix that animation at that frame unless the note says otherwise.',
200 `When you have handled this, start \`rive-video-preview wait-feedback ${target}\` in the background again to hear the next round.`,
201 );
202 return out.join('\n') + '\n';
204​
205export async function runWaitFeedback(argv) {
206 const opts = parseArgs(argv);
207 if (opts.help) return void process.stdout.write(HELP);
208 const { target } = opts;
209 if (!existsSync(target)) fail(`${target} does not exist`);
210 let project;
211 if (statSync(target).isDirectory()) {
212 if (!existsSync(path.join(target, 'rive.yaml'))) fail(`${target} has no rive.yaml — not a Rive CLI project`);
213 project = projectName(target);
214 } else if (target.endsWith('.riv')) {
215 project = path.basename(target, '.riv');
216 } else {
217 fail('expected a Rive project directory or a .riv file');
218 }
219​
220 const store = new FeedbackStore(target, { project });
221 await store.ensure();
222 const unregister = registerListener(target, 'cli');
223 const abort = new AbortController();
224 let interrupted = false;
225 for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
226 process.on(sig, () => {
227 interrupted = true;
228 abort.abort();
229 });
230 }
231​
232 const limit = opts.timeout != null ? ` (timeout ${opts.timeout}s)` : '';
233 console.error(`Waiting for the user to press "Send to agent" for ${project} (${store.sentDir})${limit}…`);
234 let got;
235 try {
236 // --no-mark-read only peeks, so it doesn't claim the bundles away from another consumer.
237 got = await waitForBundles(store, { timeoutMs: opts.timeout != null ? opts.timeout * 1000 : null, signal: abort.signal, claim: opts.markRead });
238 } finally {
239 unregister();
240 }
241​
242 if (!got) {
243 if (interrupted) {
244 console.error('Stopped waiting for feedback (interrupted).');
245 process.exitCode = EXIT_INTERRUPTED;
246 } else {
247 console.log(`No feedback arrived for ${project} within ${opts.timeout}s. Nothing was sent from the player; start the command again to keep listening.`);
248 process.exitCode = EXIT_TIMEOUT;
249 }
250 return;
251 }
252​
253 const { bundles, claims } = got;
254 try {
255 const text = await formatBundles(bundles, { target, project, marked: opts.markRead });
256 await new Promise((resolve, reject) => process.stdout.write(text, (err) => (err ? reject(err) : resolve())));
257 if (opts.markRead) {
258 try {
259 for (const b of bundles) await store.markConsumed(b.id, 'agent');
260 } catch (err) {
261 // The feedback was printed; it just may be delivered again.
262 console.error(`Warning: could not mark the feedback read (${err.message}); it may be delivered again.`);
263 }
264 }
265 } finally {
266 claims?.release(); // read ones no longer need it; on failure the next consumer gets them
267 }
268 process.exitCode = 0;