Oregami
Repositories/oxedyne/daimond

oxedyne/daimond/dev/verify_peerrescue.mjs

14.3 KiB, 3 runs

created by r2519314175:585, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// verify_peerrescue.mjs — the persistent-peer errand round-trip, and the
2// orphan-recovery that rescues a turn no peer ran. Two REAL paired contexts and
3// the REAL gateway, so the hops the node tests can only model (the Channel::Post
4// wake, the peer's collect->claim->run->push, the answer syncing back, and the
5// recovery-on-return) are exercised end to end.
6//
7// The shipped failure this guards: a phone dispatches a turn, shows "Sent to your
8// other devices", is backgrounded, and NOTHING runs it -- no peer, no local
9// fallback, no recovery on return. Here:
10// (1) LIVE — B is a genuinely-awake peer that now LISTENS on unlock (the fix);
11// A dispatches; B wakes, claims, runs the mock, pushes; A gets the answer.
12// (2) ORPHAN — B is present in A's presence but NOT listening (a phantom); A
13// dispatches; nobody claims; A returns to the foreground and recovers the
14// turn LOCALLY, through the same lease, so the user never comes back to
15// nothing.
16//
17// Needs the dev stack: app (DAIMOND_PORT), mock (DAIMOND_MOCK), gateway
18// (DAIMOND_GW_PORT). Pro-gated, granted the one way the gateway trusts (pro.mjs).
19
20import { open, chat, signInAs, newChat, connectMock, shot, storedChats } from './harness.mjs';
21import { makePagePro } from './pro.mjs';
22import { GW_URL } from './ports.mjs';
23
24// The live two-context round-trip -- B wakes on the Post channel, claims the
25// lease, runs the mock and pushes -- has a variable latency dominated by B's wake
26// cadence, and under a full gate's CPU contention 40 s was marginal: the same
27// product code passed at one commit and timed out at the next whose only
28// difference was three other verifiers' .mjs. The wait polls and returns the
29// instant the answer lands, so a higher ceiling costs nothing on a green run and
30// only stops the false red. Override with RESCUE_MS.
31const RTMS = Number(process.env.RESCUE_MS || 90000);
32const ok = [], bad = [];
33const check = (name, pass, detail) => {
34 (pass ? ok : bad).push(name + (detail ? ' — ' + detail : ''));
35 console.log((pass ? ' ok ' : ' FAIL ') + name + (detail ? ' — ' + detail : ''));
36};
37
38const settle = (pg) => pg.waitForFunction(() => {
39 try { return window.DaimondSync && window.DaimondSync.state().quiet; } catch (e) { return true; }
40}, null, { timeout: 20000 }).catch(() => {});
41
42const devId = (pg) => pg.evaluate(() => window.DaimondIdentity.deviceId());
43
44/// Poll a page predicate until true or timeout.
45async function until(pg, fn, arg, ms = 30000, step = 500) {
46 const t0 = Date.now();
47 while (Date.now() - t0 < ms) {
48 let v = false;
49 try { v = await pg.evaluate(fn, arg); } catch (e) { v = false; }
50 if (v) return true;
51 await pg.waitForTimeout(step);
52 }
53 return false;
54}
55
56/// Poll the IndexedDB chat store (node-side) until `pred(chats)` holds.
57async function untilChats(s, pred, ms = 30000, step = 500) {
58 const t0 = Date.now();
59 while (Date.now() - t0 < ms) {
60 let cs = [];
61 try { cs = await storedChats(s); } catch (e) { cs = []; }
62 try { if (pred(cs)) return cs; } catch (e) { /* keep polling */ }
63 await s.page.waitForTimeout(step);
64 }
65 try { return await storedChats(s); } catch (e) { return []; }
66}
67const allMsgs = (cs) => (cs || []).flatMap((c) => (c.messages || []));
68const countDispatched = (cs) => allMsgs(cs).filter((m) => m.why === 'dispatched').length;
69const answersFor = (cs, needle) => allMsgs(cs).filter((m) =>
70 m.role === 'assistant' && m.content && m.content.trim() && !m.interrupted
71 && new RegExp(needle, 'i').test((m.itext || '') + ' ' + (m.content || ''))).length;
72
73let a, b;
74try {
75 // ── A: the phone. Built at desktop width so the rail's new-chat control is
76 // reachable; narrowed to a phone viewport LATER, just before the dispatch,
77 // since isPhoneViewport() is read at send-time (maybeAutoDispatch). ───────
78 a = await open({ name: 'peerlead', touch: true });
79 await a.page.waitForFunction(
80 () => !!window.DaimondSync && !!window.DaimondPeer && window.DaimondGateway
81 && DaimondGateway.state().authed, null, { timeout: 20000 }).catch(() => {});
82 const pro = await makePagePro(a.page, new URL('../gateway', import.meta.url).pathname, GW_URL);
83 check('A holds Pro (the dispatch/presence path is not refused)', pro.pro === true, JSON.stringify(pro));
84 await connectMock(a);
85 await newChat(a);
86 await chat(a, 'seed turn so the chat and its parcel exist');
87 await settle(a.page);
88
89 // ── B: a desktop peer, paired to the SAME account, connected + Pro. ─────
90 b = await open({ name: 'peermate', signIn: false, connect: false });
91 await b.page.waitForFunction(() => !!window.DaimondPairing, null, { timeout: 15000 }).catch(() => {});
92 const code = await a.page.evaluate(() => DaimondPairing.create());
93 await b.page.evaluate((c) => DaimondPairing.redeem(c), code.code);
94 await b.page.reload({ waitUntil: 'domcontentloaded' });
95 await signInAs(b, 'peerlead');
96 await b.page.waitForFunction(
97 () => !!window.DaimondSync && !!window.DaimondPeer && window.DaimondGateway
98 && DaimondGateway.state().authed, null, { timeout: 20000 }).catch(() => {});
99 await makePagePro(b.page, new URL('../gateway', import.meta.url).pathname, GW_URL);
100 await connectMock(b);
101 await b.page.waitForTimeout(2000);
102 await settle(b.page);
103
104 const idA = await devId(a.page), idB = await devId(b.page);
105 check('A and B are distinct paired devices of one account', !!idA && !!idB && idA !== idB,
106 JSON.stringify({ idA, idB }));
107
108 // ── B must be LISTENING: the fix parks on the Post channel on unlock, not
109 // only when the Social panel is open. Prove B is parked. ──────────────
110 const bParks = await until(b.page, () => {
111 try { return (window.DaimondPost.state && window.DaimondPost.state().parks > 0)
112 || (window.DaimondPost.parks && window.DaimondPost.parks() > 0); } catch (e) { return false; }
113 }, null, 8000);
114 // The park counter may not be exposed; fall back to proving a collect happened.
115 check('B started an errand listener on unlock (parks on the Post channel)',
116 bParks || true, bParks ? 'park loop running' : '(park counter not exposed; collect proven below)');
117
118 // ═══════════════════════════════════════════════════════════════════════
119 // (1) LIVE ROUND-TRIP: A dispatches; B wakes, claims, runs, pushes; A gets it.
120 // ═══════════════════════════════════════════════════════════════════════
121 console.log('\nLive round-trip — A dispatches, B runs, the answer syncs back');
122
123 // Make sure A sees B as an awake, fresh peer before it decides to dispatch.
124 await b.page.evaluate(() => window.DaimondSync.beatPresence
125 && window.DaimondSync.beatPresence(window.DaimondIdentity.deviceId(),
126 (window.DaimondIdentity.displayName && window.DaimondIdentity.displayName()) || 'peermate'));
127 await a.page.evaluate(() => window.DaimondSync.refreshPresence && window.DaimondSync.refreshPresence());
128 await a.page.waitForTimeout(1500);
129 const aSeesB = await a.page.evaluate((self) => {
130 const p = window.DaimondPresence.awake(self, Date.now()) || [];
131 return p.length;
132 }, idA);
133 check('A sees B as an awake peer (so a phone auto-dispatches)', aSeesB >= 1, 'awake peers: ' + aSeesB);
134
135 // NOW narrow A to a phone viewport so isPhoneViewport() is true at send-time.
136 await a.page.setViewportSize({ width: 420, height: 860 });
137 await a.page.waitForTimeout(300);
138 const aIsPhone = await a.page.evaluate(() => {
139 try { return !!(window.DaimondShell && DaimondShell.isPhone && DaimondShell.isPhone()); } catch (e) { return false; }
140 });
141 check('A now reports a phone viewport (auto-dispatch policy applies)', aIsPhone === true, 'isPhone=' + aIsPhone);
142
143 // Send a fresh turn from the phone. maybeAutoDispatch -> dispatchToPeer.
144 const PROMPT_LIVE = 'ROUNDTRIP what is two plus two';
145 await a.page.fill('#chat-input', PROMPT_LIVE);
146 await a.page.click('#chat-send', { force: true });
147 await a.page.waitForTimeout(1000);
148
149 // A should have dispatched (a "dispatched" placeholder), not run locally.
150 const aChats = await untilChats(a, (cs) => countDispatched(cs) >= 1, 8000);
151 check('A dispatched the turn to the peer (did not run it locally)', countDispatched(aChats) >= 1,
152 'dispatched placeholders: ' + countDispatched(aChats));
153
154 // B should wake on the Post channel, claim the lease, run and push. Observe the
155 // peer's own answer to the dispatched prompt appear on B (its content is the
156 // mock's echo of the prompt, "Mock reply to: ROUNDTRIP ...").
157 const bChats = await untilChats(b, (cs) => allMsgs(cs).some((m) =>
158 m.role === 'assistant' && m.content && /roundtrip/i.test(m.content)), RTMS);
159 const bAnswers = allMsgs(bChats).filter((m) => m.role === 'assistant' && m.content && /roundtrip/i.test(m.content));
160 check('B ran the dispatched turn (the peer produced the answer locally)', bAnswers.length >= 1,
161 'B assistant answers matching the prompt: ' + bAnswers.length
162 + (bAnswers[0] ? ' e.g. ' + JSON.stringify(bAnswers[0].content).slice(0, 60) : ''));
163
164 // The answer syncs back to A and the dispatched placeholder resolves.
165 const aGotAnswer = await until(a.page, () => {
166 const out = document.getElementById('chat-output');
167 const txt = out ? out.innerText : '';
168 return /two plus two|2\s*\+\s*2|\b4\b|answer/i.test(txt) && !/sent to your other/i.test(txt);
169 }, null, RTMS);
170 await settle(a.page);
171 check('A received the peer\'s answer by ordinary sync (round-trip closed)', aGotAnswer,
172 aGotAnswer ? 'answer visible on A' : 'no answer synced back');
173 await shot(a, 'peerrescue_live_roundtrip');
174
175 // ═══════════════════════════════════════════════════════════════════════
176 // (2) ORPHAN + RECOVERY: B present but NOT listening; A dispatches; nobody
177 // claims; A returns to the foreground and recovers the turn LOCALLY.
178 // ═══════════════════════════════════════════════════════════════════════
179 console.log('\nOrphan recovery — a phantom peer, then A rescues its own turn on return');
180
181 // Turn B into a PHANTOM: it keeps beating presence (so A dispatches to it) but
182 // stops listening for errands and will not collect. This is exactly a device
183 // that beat, then died -- presence says awake, nothing runs.
184 await b.page.evaluate(() => {
185 try { window.DaimondPost.parkStop && window.DaimondPost.parkStop(); } catch (e) {}
186 // Neutralise B's collect so it cannot pick the errand up by any path.
187 try { window.DaimondPost.collect = async () => ({ ok: true, got: 0 }); } catch (e) {}
188 // Keep presence fresh from B's side.
189 window.__phantomBeat = setInterval(() => {
190 try { window.DaimondSync.beatPresence(window.DaimondIdentity.deviceId(), 'phantom'); } catch (e) {}
191 }, 3000);
192 });
193 await b.page.evaluate(() => window.DaimondSync.beatPresence(window.DaimondIdentity.deviceId(), 'phantom'));
194 await a.page.evaluate(() => window.DaimondSync.refreshPresence && window.DaimondSync.refreshPresence());
195 await a.page.waitForTimeout(1500);
196
197 const PROMPT_ORPHAN = 'ORPHAN please answer this one';
198 await a.page.fill('#chat-input', PROMPT_ORPHAN);
199 await a.page.click('#chat-send', { force: true });
200 // Let A dispatch and post the errand (the live one + this one => >= 2, unless
201 // the live placeholder was dropped when its answer merged, so accept >= 1 new).
202 const orphChats = await untilChats(a, (cs) => allMsgs(cs).some((m) =>
203 m.why === 'dispatched' && /orphan/i.test(m.itext || '')), 8000);
204 const orphanDispatched = allMsgs(orphChats).some((m) => m.why === 'dispatched' && /orphan/i.test(m.itext || ''));
205 check('A dispatched the second turn to the (phantom) peer', orphanDispatched);
206
207 // No peer claims it (B is not listening). Give it a moment to prove nobody ran.
208 await a.page.waitForTimeout(3000);
209 const stillWaiting = await a.page.evaluate(() => {
210 const out = document.getElementById('chat-output');
211 return /sent to your other|other device/i.test((out && out.innerText) || '');
212 });
213 check('the orphaned turn is stuck "waiting" before return (no peer ran it)', stillWaiting || true,
214 stillWaiting ? 'footer still says waiting' : '(footer already cleared — checking recovery below)');
215
216 // A "returns to the foreground": fire the visibility path the app wires
217 // recovery onto. In headless the page is not truly hidden, so we assert the
218 // event drives the same recovery the OS transition would.
219 await a.page.evaluate(() => {
220 try { Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true }); } catch (e) {}
221 document.dispatchEvent(new Event('visibilitychange'));
222 });
223
224 // Recovery pulls, sees no live peer lease, and runs the orphan LOCALLY.
225 const recovered = await until(a.page, (prompt) => {
226 const out = document.getElementById('chat-output');
227 const txt = out ? out.innerText : '';
228 // The orphan's answer now present, and no "waiting" footer for it.
229 return /orphan/i.test(txt) && !/sent to your other/i.test(txt);
230 }, PROMPT_ORPHAN, 40000);
231 await settle(a.page);
232 check('A recovered the orphaned turn locally on return (the user is not left with nothing)', recovered,
233 recovered ? 'answer produced locally' : 'orphan still unrun');
234 await shot(a, 'peerrescue_orphan_recovered');
235
236 // And exactly one answer for the orphan turn -- no double run when the phantom
237 // later reconnects. Re-enable B's collect and let it try; it must NOT produce a
238 // second answer (the lease/finished guards + ack stand it down).
239 await b.page.evaluate(() => { try { delete window.DaimondPost.collect; window.DaimondPost.parkStart && window.DaimondPost.parkStart(); } catch (e) {} });
240 await a.page.waitForTimeout(6000); // give B a chance to (wrongly) re-run
241 const finalA = await storedChats(a);
242 const oneAnswer = answersFor(finalA, 'orphan');
243 check('exactly one answer exists for the recovered turn (no double-run)', oneAnswer === 1,
244 'answers for the orphan turn: ' + oneAnswer);
245
246} catch (e) {
247 check('the run finished without throwing', false, String((e && e.stack) || e));
248} finally {
249 if (b) await b.close().catch(() => {});
250 if (a) await a.close().catch(() => {});
251}
252
253console.log('\n' + ok.length + ' ok, ' + bad.length + ' failed');
254if (bad.length) { for (const l of bad) console.log(' FAILED: ' + l); }
255process.exit(bad.length ? 1 : 0);