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

listeners.mjs

218 lines7.1 KB

1// Who is waiting for feedback right now. An agent that is listening (the `wait-feedback`
2// command, or the MCP tool wait_for_feedback) registers a small heartbeat file, so the player
3// can tell the user whether "Send to agent" will wake the agent or needs a paste:
4//
5// .rive-preview/[<name>.riv/]listeners/<pid>-<rand>.json { pid, kind, startedAt, beat }
6//
7// A listener counts while its process is alive and its heartbeat is fresh. The files of a
8// listener killed without cleanup are removed by the next reader.
9import { randomBytes } from 'node:crypto';
10import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
11import path from 'node:path';
12import { feedbackRoot, feedbackTop } from './feedback.mjs';
13​
14const BEAT_MS = 5000;
15const STALE_MS = 20000;
16​
17const listenersDir = (target) => path.join(feedbackRoot(target), 'listeners');
18​
19function alive(pid) {
20 try {
21 process.kill(pid, 0);
22 return true;
23 } catch (err) {
24 return err.code === 'EPERM'; // exists, owned by someone else
25 }
27​
28/**
29 * Register this process as listening for `target`'s feedback until the returned function is
30 * called (also on exit). `kind` is 'cli' or 'mcp'.
31 */
32export function registerListener(target, kind) {
33 const dir = listenersDir(target);
34 const file = path.join(dir, `${process.pid}-${randomBytes(3).toString('hex')}.json`);
35 const startedAt = new Date().toISOString();
36 const write = () => {
37 try {
38 mkdirSync(dir, { recursive: true });
39 const gi = path.join(feedbackTop(target), '.gitignore');
40 if (!existsSync(gi)) writeFileSync(gi, '*\n');
41 const tmp = `${file}.tmp`;
42 writeFileSync(tmp, JSON.stringify({ pid: process.pid, kind, startedAt, beat: Date.now() }));
43 renameSync(tmp, file);
44 } catch {}
45 };
46 write();
47 const timer = setInterval(write, BEAT_MS);
48 timer.unref();
49 let done = false;
50 const unregister = () => {
51 if (done) return;
52 done = true;
53 clearInterval(timer);
54 process.off('exit', unregister);
55 rmSync(file, { force: true });
56 };
57 process.on('exit', unregister);
58 return unregister;
60​
61/** The live listeners for `target`: [{ pid, kind, startedAt }]. */
62export function listListeners(target) {
63 const dir = listenersDir(target);
64 let names = [];
65 try {
66 names = readdirSync(dir).filter((n) => n.endsWith('.json'));
67 } catch {
68 return [];
69 }
70 const out = [];
71 for (const n of names) {
72 const file = path.join(dir, n);
73 try {
74 const l = JSON.parse(readFileSync(file, 'utf8'));
75 if (Number.isSafeInteger(l.pid) && alive(l.pid) && Date.now() - l.beat < STALE_MS) {
76 out.push({ pid: l.pid, kind: l.kind, startedAt: l.startedAt });
77 continue;
78 }
79 } catch {}
80 rmSync(file, { force: true });
81 }
82 return out;
84​
85// ------------------------------------------------------------ claims
86// Two consumers (two `wait-feedback`s, or one plus the MCP server) can see the same unread
87// bundle at once. Each takes an exclusive claim on a bundle before delivering it, so only one
88// of them hands it to the agent:
89//
90// feedback/<bundle-id>/claimed.json { pid, token, at } created with O_EXCL
91// feedback/<bundle-id>/claimed.json.lock held briefly while taking over a stale claim
92//
93// The holder renews `at` while it delivers and removes the claim when done (only if it is still
94// its own, by token). A claim whose process died, or that went CLAIM_STALE_MS without renewal
95// (a hung process, or a reused pid), is stale and can be taken over. Takeover happens under the
96// lock and re-checks the claim there, so two consumers can't both replace it.
97const CLAIM_STALE_MS = 60000;
98const CLAIM_RENEW_MS = 10000;
99const LOCK_STALE_MS = 10000; // a takeover takes milliseconds; an older lock was left by a crash
100​
101function claimIsStale(file) {
102 try {
103 const c = JSON.parse(readFileSync(file, 'utf8'));
104 return !Number.isSafeInteger(c.pid) || !alive(c.pid) || !(Date.now() - c.at < CLAIM_STALE_MS);
105 } catch (err) {
106 if (err.code === 'ENOENT') return false; // gone: the caller may simply create it
107 // Unreadable: it may be being written this instant, so go by its age.
108 try {
109 return Date.now() - statSync(file).mtimeMs >= CLAIM_STALE_MS;
110 } catch {
111 return false;
112 }
113 }
115​
116function withLock(lock, fn) {
117 const take = () => writeFileSync(lock, JSON.stringify({ pid: process.pid, at: Date.now() }), { flag: 'wx' });
118 try {
119 take();
120 } catch (err) {
121 if (err.code !== 'EEXIST') return false;
122 try {
123 if (Date.now() - statSync(lock).mtimeMs < LOCK_STALE_MS) return false;
124 rmSync(lock, { force: true });
125 take();
126 } catch {
127 return false;
128 }
129 }
130 try {
131 return fn();
132 } finally {
133 rmSync(lock, { force: true });
134 }
136​
137function readToken(file) {
138 try {
139 return JSON.parse(readFileSync(file, 'utf8')).token;
140 } catch {
141 return undefined;
142 }
144​
145/**
146 * A set of claims held by this process. `take(bundle)` claims one (false if another consumer
147 * holds it); `release()` drops every claim still ours. Release in a `finally`: once a bundle is
148 * marked read its claim no longer matters, and if delivery failed the next consumer gets it.
149 */
150export class Claims {
151 constructor(store) {
152 this.store = store;
153 this.held = new Map(); // claim file -> token
154 this.timer = null;
155 }
156​
157 get size() {
158 return this.held.size;
159 }
160​
161 take(bundle) {
162 if (!/^[\w-]+$/.test(bundle.id)) return false;
163 const file = path.join(this.store.sentDir, bundle.id, 'claimed.json');
164 if (this.held.has(file)) return true;
165 const token = randomBytes(8).toString('hex');
166 const create = () => {
167 try {
168 writeFileSync(file, JSON.stringify({ pid: process.pid, token, at: Date.now() }), { flag: 'wx' });
169 return true;
170 } catch {
171 return false;
172 }
173 };
174 const ok =
175 create() ||
176 (claimIsStale(file) &&
177 withLock(`${file}.lock`, () => {
178 if (existsSync(file) && !claimIsStale(file)) return false; // someone got there first
179 rmSync(file, { force: true });
180 return create();
181 }));
182 if (!ok) return false;
183 this.held.set(file, token);
184 if (!this.timer) {
185 this.timer = setInterval(() => this.renew(), CLAIM_RENEW_MS);
186 this.timer.unref();
187 }
188 return true;
189 }
190​
191 renew() {
192 for (const [file, token] of this.held) {
193 if (readToken(file) !== token) {
194 this.held.delete(file); // lost it (taken over after we stalled): not ours to touch
195 continue;
196 }
197 try {
198 const tmp = `${file}.${token}.tmp`;
199 writeFileSync(tmp, JSON.stringify({ pid: process.pid, token, at: Date.now() }));
200 renameSync(tmp, file);
201 } catch {}
202 }
203 }
204​
205 release() {
206 clearInterval(this.timer);
207 this.timer = null;
208 for (const [file, token] of this.held) if (readToken(file) === token) rmSync(file, { force: true });
209 this.held.clear();
210 }
212​
213/** Claim every bundle in `bundles` that no other consumer holds: { claimed, claims }. */
214export function claimBundles(store, bundles) {
215 const claims = new Claims(store);
216 const claimed = bundles.filter((b) => claims.take(b));
217 return { claimed, claims };