@mindexec/cli 0.2.476 → 0.2.478

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +323 -323
  2. package/codex-model-catalog.js +202 -202
  3. package/codex-runtime.js +1608 -1608
  4. package/desktop-workspace-state.cjs +120 -120
  5. package/electron/main.cjs +517 -517
  6. package/electron/preload.cjs +17 -17
  7. package/electron/recurring-update-owner-smoke.mjs +55 -55
  8. package/electron/recurring-update-owner.cjs +97 -97
  9. package/electron/source-smoke.mjs +108 -108
  10. package/electron/update-feed-resolver.cjs +79 -79
  11. package/electron/update-feed.json +10 -10
  12. package/electron/update-manager-smoke.mjs +146 -146
  13. package/electron/update-manager.cjs +297 -297
  14. package/electron/windows-package-smoke.mjs +156 -156
  15. package/launch-bridge.cjs +236 -236
  16. package/lzo1x.js +110 -110
  17. package/mode4-atlas-worker.js +440 -440
  18. package/mode4-atlas.js +130 -130
  19. package/package.json +1 -1
  20. package/port-guard.cjs +285 -285
  21. package/remote-fast/osx-arm64/MacScreenCaptureKitH264.swift +339 -339
  22. package/remote-fast/osx-arm64/MacSystemAudioCapture.swift +214 -214
  23. package/remote-fast/osx-arm64/UnixRawCaptureHelper.mjs +80 -80
  24. package/remote-fast/osx-arm64/livedesk-raw-capture-resampler.mjs +73 -73
  25. package/remote-fast/osx-arm64/mindexec-remote-fast.dll +0 -0
  26. package/remote-fast/osx-x64/MacScreenCaptureKitH264.swift +339 -339
  27. package/remote-fast/osx-x64/MacSystemAudioCapture.swift +214 -214
  28. package/remote-fast/osx-x64/UnixRawCaptureHelper.mjs +80 -80
  29. package/remote-fast/osx-x64/livedesk-raw-capture-resampler.mjs +73 -73
  30. package/remote-fast/osx-x64/mindexec-remote-fast.dll +0 -0
  31. package/remote-fast/win-x64/mindexec-remote-fast.dll +0 -0
  32. package/remote-hub.js +3698 -3698
  33. package/scripts/auth-session-smoke.mjs +262 -262
  34. package/scripts/board-render-ownership-smoke.mjs +85 -85
  35. package/scripts/codex-model-catalog-smoke.mjs +150 -150
  36. package/scripts/codex-runtime-home-smoke.mjs +58 -58
  37. package/scripts/codex-sdk-image-live-smoke.mjs +43 -43
  38. package/scripts/codex-sdk-image-runtime-smoke.mjs +122 -122
  39. package/scripts/codex-sdk-runtime-smoke.mjs +89 -89
  40. package/scripts/desktop-update-publisher-smoke.mjs +89 -89
  41. package/scripts/desktop-update-worker-smoke.mjs +72 -72
  42. package/scripts/desktop-workspace-state-smoke.mjs +81 -81
  43. package/scripts/drive-installed-update-smoke.mjs +67 -67
  44. package/scripts/npm-fresh-install-smoke.mjs +216 -216
  45. package/scripts/publish-mindexec-desktop-updates.mjs +224 -224
  46. package/scripts/remote-agent-managed-smoke.mjs +318 -318
  47. package/scripts/remote-agent-package-smoke.mjs +64 -64
  48. package/scripts/remote-agent-ws-smoke.mjs +269 -269
  49. package/scripts/remote-fast-live-rate-smoke.mjs +343 -343
  50. package/scripts/remote-fast-mdm-browser-smoke.mjs +453 -453
  51. package/scripts/remote-fleet-render-smoke.mjs +1350 -1350
  52. package/scripts/remote-frame-ws-smoke.mjs +234 -234
  53. package/scripts/remote-http-smoke.mjs +592 -592
  54. package/scripts/remote-hub-identity-smoke.mjs +146 -146
  55. package/scripts/remote-hub-scale-smoke.mjs +124 -124
  56. package/scripts/remote-hub-smoke.mjs +699 -699
  57. package/scripts/remote-input-ws-smoke.mjs +263 -263
  58. package/scripts/remote-registry-follower-smoke.mjs +815 -815
  59. package/scripts/setup-tree-sitter-grammars.mjs +59 -59
  60. package/server.js +7690 -7690
  61. package/start-bridge.bat +32 -32
  62. package/start-bridge.sh +81 -81
  63. package/wwwroot/_content/MindExecution.Plugins.Admin/css/admin-dashboard.css +546 -546
  64. package/wwwroot/_content/MindExecution.Plugins.YouTube/css/youtube-search.css +251 -251
  65. package/wwwroot/_content/MindExecution.Shared/css/app.css +1 -1
  66. package/wwwroot/_content/MindExecution.Shared/css/mind-map-overrides.css +3789 -3789
  67. package/wwwroot/_content/MindExecution.Shared/js/agent-visualization.js +27 -27
  68. package/wwwroot/_content/MindExecution.Shared/js/background-themes.js +1449 -1449
  69. package/wwwroot/_content/MindExecution.Shared/js/code-master.js +8316 -8316
  70. package/wwwroot/_content/MindExecution.Shared/js/file-system-helper.js +338 -338
  71. package/wwwroot/_content/MindExecution.Shared/js/marked.min.js +69 -69
  72. package/wwwroot/_content/MindExecution.Shared/js/mind-map-animated-image-preview.js +270 -270
  73. package/wwwroot/_content/MindExecution.Shared/js/mind-map-automation-edge-motion.js +170 -170
  74. package/wwwroot/_content/MindExecution.Shared/js/mind-map-board-render-ownership.js +81 -81
  75. package/wwwroot/_content/MindExecution.Shared/js/mind-map-core.js +10506 -10517
  76. package/wwwroot/_content/MindExecution.Shared/js/mind-map-css3d-hotpath.js +902 -902
  77. package/wwwroot/_content/MindExecution.Shared/js/mind-map-css3d-manager.js +24637 -24637
  78. package/wwwroot/_content/MindExecution.Shared/js/mind-map-dev-guards.js +325 -325
  79. package/wwwroot/_content/MindExecution.Shared/js/mind-map-dnd.js +1491 -1491
  80. package/wwwroot/_content/MindExecution.Shared/js/mind-map-glow-shader.js +70 -70
  81. package/wwwroot/_content/MindExecution.Shared/js/mind-map-image-policy.js +218 -218
  82. package/wwwroot/_content/MindExecution.Shared/js/mind-map-interactions.js +7065 -7065
  83. package/wwwroot/_content/MindExecution.Shared/js/mind-map-lod-plan-worker.js +160 -160
  84. package/wwwroot/_content/MindExecution.Shared/js/mind-map-lod-renderer.js +9956 -9956
  85. package/wwwroot/_content/MindExecution.Shared/js/mind-map-lod-video-placeholder.js +107 -107
  86. package/wwwroot/_content/MindExecution.Shared/js/mind-map-logic-workers.js +1004 -1004
  87. package/wwwroot/_content/MindExecution.Shared/js/mind-map-menu-manager.js +1351 -1351
  88. package/wwwroot/_content/MindExecution.Shared/js/mind-map-multi-select.js +865 -865
  89. package/wwwroot/_content/MindExecution.Shared/js/mind-map-node-search-worker.js +554 -554
  90. package/wwwroot/_content/MindExecution.Shared/js/mind-map-nodes.js +4744 -4744
  91. package/wwwroot/_content/MindExecution.Shared/js/mind-map-normal-boundary-optimizer.js +624 -624
  92. package/wwwroot/_content/MindExecution.Shared/js/mind-map-object-manager.js +241 -241
  93. package/wwwroot/_content/MindExecution.Shared/js/mind-map-pipeline.js +2290 -2290
  94. package/wwwroot/_content/MindExecution.Shared/js/mind-map-remote-codecs.js +202 -202
  95. package/wwwroot/_content/MindExecution.Shared/js/mind-map-render-plan.js +1971 -1971
  96. package/wwwroot/_content/MindExecution.Shared/js/mind-map-text-lod-system.js +93 -93
  97. package/wwwroot/_content/MindExecution.Shared/js/mind-map-texture-factory.js +2391 -2391
  98. package/wwwroot/_content/MindExecution.Shared/js/mind-map-video-playback-controls.js +95 -95
  99. package/wwwroot/_content/MindExecution.Shared/js/mind-map-visibility-worker.js +895 -895
  100. package/wwwroot/_content/MindExecution.Shared/js/mindmap-toolbar.js +636 -636
  101. package/wwwroot/_content/MindExecution.Shared/js/native-drop-handler.js +45 -45
  102. package/wwwroot/_content/MindExecution.Shared/js/plan-master.js +117 -117
  103. package/wwwroot/_content/MindExecution.Shared/js/renderers/CSS3DRenderer.js +114 -114
  104. package/wwwroot/_content/MindExecution.Shared/js/texture-worker-manager.js +10 -10
  105. package/wwwroot/_content/MindExecution.Shared/js/three.min.js +6 -6
  106. package/wwwroot/_content/MindExecution.Shared/js/token-manager.js +7 -7
  107. package/wwwroot/_content/MindExecution.Shared/js/troika-bundle.js +6 -6
  108. package/wwwroot/_content/MindExecution.Shared/js/troika-bundle.js.map +2 -2
  109. package/wwwroot/_content/MindExecution.Shared/lib/font-awesome/css/all.min.css +8 -8
  110. package/wwwroot/_content/MindExecution.Shared/models/vocab.txt +30522 -30522
  111. package/wwwroot/_framework/{Google.Protobuf.9h59ukbel7.dll → Google.Protobuf.33g2gb5is0.dll} +0 -0
  112. package/wwwroot/_framework/{MindExecution.Core.cx2pre7qz2.dll → MindExecution.Core.z100xo4mg0.dll} +0 -0
  113. package/wwwroot/_framework/{MindExecution.Kernel.engfih12kr.dll → MindExecution.Kernel.i9cldrx8yc.dll} +0 -0
  114. package/wwwroot/_framework/{MindExecution.Plugins.Admin.xfunemn9zi.dll → MindExecution.Plugins.Admin.48lzqddb0a.dll} +0 -0
  115. package/wwwroot/_framework/{MindExecution.Plugins.Business.ja94a5ze3i.dll → MindExecution.Plugins.Business.7m8u1q142p.dll} +0 -0
  116. package/wwwroot/_framework/{MindExecution.Plugins.Concept.3q05vzviqb.dll → MindExecution.Plugins.Concept.cl5wmr53od.dll} +0 -0
  117. package/wwwroot/_framework/{MindExecution.Plugins.Directory.re4jjs91d1.dll → MindExecution.Plugins.Directory.slipi39041.dll} +0 -0
  118. package/wwwroot/_framework/{MindExecution.Plugins.PlanMaster.89etwfquz1.dll → MindExecution.Plugins.PlanMaster.qfge05l671.dll} +0 -0
  119. package/wwwroot/_framework/{MindExecution.Plugins.YouTube.aqf4vztjji.dll → MindExecution.Plugins.YouTube.tn7v29ut77.dll} +0 -0
  120. package/wwwroot/_framework/{MindExecution.Shared.9b1rucdxvv.dll → MindExecution.Shared.rjqlf0umjn.dll} +0 -0
  121. package/wwwroot/_framework/{MindExecution.Web.ssp0n0xf1e.dll → MindExecution.Web.rwawrxxk38.dll} +0 -0
  122. package/wwwroot/_framework/blazor.boot.json +23 -23
  123. package/wwwroot/_headers +40 -40
  124. package/wwwroot/_redirects +1 -1
  125. package/wwwroot/index.html +772 -772
  126. package/wwwroot/js/marketing-tool.js +180 -180
  127. package/wwwroot/manifest.webmanifest +23 -23
  128. package/wwwroot/service-worker-assets.js +78 -106
  129. package/wwwroot/service-worker.js +33 -33
  130. package/tree-sitter-grammars/README.md +0 -18
  131. package/tree-sitter-grammars/tree-sitter-c_sharp.wasm +0 -0
  132. package/tree-sitter-grammars/tree-sitter-go.wasm +0 -0
  133. package/tree-sitter-grammars/tree-sitter-java.wasm +0 -0
  134. package/tree-sitter-grammars/tree-sitter-javascript.wasm +0 -0
  135. package/tree-sitter-grammars/tree-sitter-python.wasm +0 -0
  136. package/tree-sitter-grammars/tree-sitter-rust.wasm +0 -0
  137. package/tree-sitter-grammars/tree-sitter-tsx.wasm +0 -0
  138. package/tree-sitter-grammars/tree-sitter-typescript.wasm +0 -0
  139. package/wwwroot/_content/MindExecution.Plugins.Directory/background.png +0 -0
  140. package/wwwroot/_content/MindExecution.Shared/fonts/NotoSansKR-Bold.ttf +0 -0
  141. package/wwwroot/_content/MindExecution.Shared/fonts/NotoSansKR-Regular.ttf +0 -0
  142. package/wwwroot/_content/MindExecution.Shared/js/mind-map-core.js.backup +0 -1059
  143. package/wwwroot/_content/MindExecution.Shared/js/mind-map-dnd.js.bak +0 -434
  144. package/wwwroot/_content/MindExecution.Shared/js/mind-map-object-manager.js.backup +0 -372
  145. package/wwwroot/_content/MindExecution.Shared/js/mind-map-texture-factory.js.backup +0 -1258
@@ -1,815 +1,815 @@
1
- #!/usr/bin/env node
2
-
3
- import assert from 'node:assert/strict';
4
- import { spawn } from 'node:child_process';
5
- import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
6
- import { createServer } from 'node:http';
7
- import net from 'node:net';
8
- import os from 'node:os';
9
- import path from 'node:path';
10
- import { fileURLToPath } from 'node:url';
11
- import { WebSocketServer } from 'ws';
12
-
13
- const BRIDGE_TOKEN = 'remote-registry-follower-smoke-token';
14
- const PAIR_TOKEN = 'remote-registry-follower-pair-token';
15
- const USER_ID = '11111111-2222-4333-8444-555555555555';
16
- const SUPABASE_KEY = 'remote-registry-follower-key';
17
- const ACCESS_TOKEN = 'remote-registry-follower-access-token';
18
- const EXPIRED_ACCESS_TOKEN = 'remote-registry-follower-expired-access-token';
19
- const REFRESHED_ACCESS_TOKEN = 'remote-registry-follower-refreshed-access-token';
20
- const REFRESH_TOKEN = 'remote-registry-follower-refresh-token';
21
- const LOCAL_BRIDGE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
22
-
23
- function wait(ms) {
24
- return new Promise(resolve => setTimeout(resolve, ms));
25
- }
26
-
27
- async function findFreePort() {
28
- return await new Promise((resolve, reject) => {
29
- const server = net.createServer();
30
- server.unref();
31
- server.once('error', reject);
32
- server.listen(0, '127.0.0.1', () => {
33
- const address = server.address();
34
- const port = typeof address === 'object' && address ? address.port : 0;
35
- server.close(() => resolve(port));
36
- });
37
- });
38
- }
39
-
40
- async function fetchJson(url, options = {}) {
41
- const response = await fetch(url, {
42
- ...options,
43
- headers: {
44
- ...(options.body ? { 'Content-Type': 'application/json' } : {}),
45
- 'X-Bridge-Token': options.token || BRIDGE_TOKEN,
46
- ...(options.headers || {})
47
- }
48
- });
49
- let payload = null;
50
- try {
51
- payload = await response.json();
52
- } catch {
53
- // Empty responses are allowed in failure diagnostics.
54
- }
55
- return { ok: response.ok, status: response.status, payload };
56
- }
57
-
58
- async function waitFor(predicate, timeoutMs, label) {
59
- const startedAt = Date.now();
60
- let lastError = null;
61
- while (Date.now() - startedAt < timeoutMs) {
62
- try {
63
- const value = await predicate();
64
- if (value) {
65
- return value;
66
- }
67
- } catch (error) {
68
- lastError = error;
69
- }
70
- await wait(100);
71
- }
72
- throw new Error(`Timed out waiting for ${label}${lastError ? `: ${lastError.message}` : ''}.`);
73
- }
74
-
75
- function createRegistryTarget({ endpoint, endpointCandidates, leaseId, active = true, pairToken = PAIR_TOKEN }) {
76
- return {
77
- user_id: USER_ID,
78
- active,
79
- endpoint,
80
- endpoint_candidates: endpointCandidates,
81
- pair_token: pairToken,
82
- lease_id: leaseId,
83
- node_id: 'remote-registry-follower-node',
84
- host_instance_id: `host-${leaseId}`,
85
- expires_at: new Date(Date.now() + 60_000).toISOString()
86
- };
87
- }
88
-
89
- function startFakeSupabase(getTarget, setTarget = null) {
90
- const requests = [];
91
- const realtimeClients = new Set();
92
- const validAccessTokens = new Set([ACCESS_TOKEN]);
93
- const assertRegistryAuth = req => {
94
- assert.equal(String(req.headers.apikey || ''), SUPABASE_KEY);
95
- const authorization = String(req.headers.authorization || '');
96
- assert.ok(
97
- validAccessTokens.has(authorization.replace(/^Bearer\s+/i, '')),
98
- `unexpected registry authorization: ${authorization}`);
99
- };
100
- const server = createServer(async (req, res) => {
101
- const readBody = () => new Promise(resolve => {
102
- let body = '';
103
- req.on('data', chunk => {
104
- body += chunk.toString();
105
- });
106
- req.on('end', () => resolve(body));
107
- });
108
- const parsed = new URL(req.url || '/', 'http://127.0.0.1');
109
- const requestRecord = {
110
- method: req.method,
111
- pathname: parsed.pathname,
112
- authorization: req.headers.authorization || '',
113
- apikey: req.headers.apikey || ''
114
- };
115
- requests.push(requestRecord);
116
-
117
- if (req.method === 'GET' && parsed.pathname === '/rest/v1/remote_host_targets') {
118
- assertRegistryAuth(req);
119
- res.writeHead(200, {
120
- 'Content-Type': 'application/json',
121
- 'Cache-Control': 'no-store'
122
- });
123
- const target = getTarget();
124
- res.end(JSON.stringify(target ? [target] : []));
125
- return;
126
- }
127
-
128
- if (req.method === 'POST' && parsed.pathname === '/rest/v1/rpc/set_remote_host_target') {
129
- assertRegistryAuth(req);
130
- const body = JSON.parse(await readBody() || '{}');
131
- requestRecord.body = body;
132
- const now = Date.now();
133
- const existing = getTarget();
134
- const sameLease = existing
135
- && String(existing.lease_id || '') === String(body.p_lease_id || '')
136
- && String(existing.host_instance_id || '') === String(body.p_host_instance_id || '');
137
- const expired = !existing?.expires_at || Date.parse(existing.expires_at) <= now;
138
- if (existing?.active === true && !sameLease && !expired && body.p_takeover !== true) {
139
- res.writeHead(200, { 'Content-Type': 'application/json' });
140
- res.end(JSON.stringify([{ ok: false, reason: 'host-target-taken' }]));
141
- return;
142
- }
143
-
144
- setTarget?.({
145
- user_id: USER_ID,
146
- active: true,
147
- endpoint: String(body.p_endpoint || ''),
148
- endpoint_candidates: Array.isArray(body.p_endpoint_candidates)
149
- ? body.p_endpoint_candidates
150
- : [String(body.p_endpoint || '')].filter(Boolean),
151
- pair_token: String(body.p_pair_token || ''),
152
- lease_id: String(body.p_lease_id || ''),
153
- node_id: String(body.p_node_id || ''),
154
- host_instance_id: String(body.p_host_instance_id || ''),
155
- expires_at: String(body.p_expires_at || new Date(Date.now() + 60_000).toISOString())
156
- });
157
- res.writeHead(200, { 'Content-Type': 'application/json' });
158
- res.end(JSON.stringify([{ ok: true, reason: 'ok' }]));
159
- return;
160
- }
161
-
162
- if (req.method === 'POST' && parsed.pathname === '/auth/v1/token') {
163
- assert.equal(parsed.searchParams.get('grant_type'), 'refresh_token');
164
- assert.equal(String(req.headers.apikey || ''), SUPABASE_KEY);
165
- assert.equal(String(req.headers.authorization || ''), `Bearer ${SUPABASE_KEY}`);
166
- const body = JSON.parse(await readBody() || '{}');
167
- assert.equal(body.refresh_token, REFRESH_TOKEN);
168
- validAccessTokens.add(REFRESHED_ACCESS_TOKEN);
169
- res.writeHead(200, {
170
- 'Content-Type': 'application/json',
171
- 'Cache-Control': 'no-store'
172
- });
173
- res.end(JSON.stringify({
174
- access_token: REFRESHED_ACCESS_TOKEN,
175
- refresh_token: REFRESH_TOKEN,
176
- token_type: 'bearer',
177
- expires_in: 3600,
178
- expires_at: Math.floor(Date.now() / 1000) + 3600,
179
- user: {
180
- id: USER_ID,
181
- email: 'remote-registry-follower@example.test'
182
- }
183
- }));
184
- return;
185
- }
186
-
187
- res.writeHead(404, { 'Content-Type': 'application/json' });
188
- res.end(JSON.stringify({ error: 'not-found' }));
189
- });
190
- const realtime = new WebSocketServer({ noServer: true });
191
-
192
- realtime.on('connection', (ws, req) => {
193
- realtimeClients.add(ws);
194
- ws.on('message', data => {
195
- const text = data.toString();
196
- let message = null;
197
- try {
198
- message = JSON.parse(text);
199
- } catch {
200
- return;
201
- }
202
-
203
- if (message.event === 'phx_join') {
204
- assert.equal(String(req.headers.apikey || ''), SUPABASE_KEY);
205
- assert.ok(validAccessTokens.has(String(req.headers.authorization || '').replace(/^Bearer\s+/i, '')));
206
- assert.ok(validAccessTokens.has(String(message.payload?.access_token || '')));
207
- assert.deepEqual(
208
- message.payload?.config?.postgres_changes?.[0],
209
- {
210
- event: '*',
211
- schema: 'public',
212
- table: 'remote_host_targets',
213
- filter: `user_id=eq.${USER_ID}`
214
- });
215
- ws.remoteRegistryTopic = message.topic;
216
- ws.send(JSON.stringify({
217
- topic: message.topic,
218
- event: 'phx_reply',
219
- payload: {
220
- status: 'ok',
221
- response: {
222
- postgres_changes: [
223
- {
224
- id: 1,
225
- event: '*',
226
- schema: 'public',
227
- table: 'remote_host_targets'
228
- }
229
- ]
230
- }
231
- },
232
- ref: message.ref,
233
- join_ref: message.join_ref
234
- }));
235
- return;
236
- }
237
-
238
- if (message.event === 'heartbeat') {
239
- ws.send(JSON.stringify({
240
- topic: message.topic,
241
- event: 'phx_reply',
242
- payload: { status: 'ok', response: {} },
243
- ref: message.ref
244
- }));
245
- }
246
- });
247
- ws.on('close', () => realtimeClients.delete(ws));
248
- });
249
-
250
- server.on('upgrade', (req, socket, head) => {
251
- const parsed = new URL(req.url || '/', 'http://127.0.0.1');
252
- if (parsed.pathname !== '/realtime/v1/websocket') {
253
- socket.destroy();
254
- return;
255
- }
256
-
257
- realtime.handleUpgrade(req, socket, head, ws => {
258
- realtime.emit('connection', ws, req);
259
- });
260
- });
261
-
262
- return new Promise((resolve, reject) => {
263
- server.once('error', reject);
264
- server.listen(0, '127.0.0.1', () => {
265
- const address = server.address();
266
- const port = typeof address === 'object' && address ? address.port : 0;
267
- resolve({
268
- url: `http://127.0.0.1:${port}`,
269
- requests,
270
- realtimeClients,
271
- broadcastChange: (type = 'UPDATE') => {
272
- for (const client of realtimeClients) {
273
- if (client.readyState !== 1 || !client.remoteRegistryTopic) {
274
- continue;
275
- }
276
-
277
- client.send(JSON.stringify({
278
- topic: client.remoteRegistryTopic,
279
- event: 'postgres_changes',
280
- payload: {
281
- ids: [1],
282
- data: {
283
- schema: 'public',
284
- table: 'remote_host_targets',
285
- commit_timestamp: new Date().toISOString(),
286
- type,
287
- record: getTarget(),
288
- old_record: null
289
- }
290
- },
291
- ref: null
292
- }));
293
- }
294
- },
295
- stop: () => new Promise(done => {
296
- for (const client of realtimeClients) {
297
- try {
298
- client.close();
299
- } catch {
300
- // best effort only
301
- }
302
- }
303
- realtime.close(() => server.close(done));
304
- })
305
- });
306
- });
307
- });
308
- }
309
-
310
- function spawnBridge({ bridgePort, remoteHubPort, workspacePath, authRoot, label, supabaseUrl = '', follower = false, publicHost = '' }) {
311
- const child = spawn(process.execPath, ['server.js'], {
312
- cwd: LOCAL_BRIDGE_DIR,
313
- stdio: ['ignore', 'pipe', 'pipe'],
314
- windowsHide: true,
315
- env: {
316
- ...process.env,
317
- BRIDGE_PORT: String(bridgePort),
318
- BRIDGE_TOKEN,
319
- BRIDGE_REQUIRE_TOKEN: '1',
320
- MINDEXEC_REMOTE_HUB: '1',
321
- REMOTE_HUB_HOST: '127.0.0.1',
322
- REMOTE_HUB_PORT: String(remoteHubPort),
323
- REMOTE_HUB_PUBLIC_HOST: publicHost,
324
- REMOTE_HUB_PAIR_TOKEN: PAIR_TOKEN,
325
- WORKSPACE_PATH: workspacePath,
326
- MINDEXEC_AUTH_DATA_ROOT: authRoot,
327
- MINDEXEC_REMOTE_REGISTRY_FOLLOWER: follower ? '1' : '0',
328
- MINDEXEC_REMOTE_REGISTRY_POLL_MS: '10000',
329
- MINDEXEC_REMOTE_REGISTRY_FAST_RETRY_MS: '250',
330
- MINDEXEC_REMOTE_REGISTRY_INACTIVE_STOP_COUNT: '2',
331
- MINDEXEC_REMOTE_REGISTRY_INACTIVE_GRACE_MS: '500',
332
- MINDEXEC_REMOTE_REGISTRY_REALTIME_RECONNECT_MS: '250',
333
- MINDEXEC_REMOTE_REGISTRY_REALTIME_DEBOUNCE_MS: '100',
334
- MINDEXEC_REMOTE_HOST_TARGET_RENEW_MS: '5000',
335
- SUPABASE_URL: supabaseUrl,
336
- SUPABASE_KEY,
337
- NO_COLOR: '1'
338
- }
339
- });
340
-
341
- let stdout = '';
342
- let stderr = '';
343
- child.stdout.on('data', chunk => {
344
- stdout += chunk.toString();
345
- });
346
- child.stderr.on('data', chunk => {
347
- stderr += chunk.toString();
348
- });
349
-
350
- const exitPromise = new Promise(resolve => child.once('exit', resolve));
351
- const details = () => `${label} stdout=${stdout}\n${label} stderr=${stderr}`;
352
- const stop = async () => {
353
- if (child.exitCode === null && !child.killed) {
354
- child.kill('SIGTERM');
355
- await Promise.race([exitPromise, wait(5000)]);
356
- if (child.exitCode === null && !child.killed) {
357
- child.kill('SIGKILL');
358
- }
359
- }
360
- };
361
-
362
- return {
363
- baseUrl: `http://127.0.0.1:${bridgePort}`,
364
- child,
365
- details,
366
- stop
367
- };
368
- }
369
-
370
- async function waitForBridge(bridge) {
371
- return await waitFor(async () => {
372
- const result = await fetchJson(`${bridge.baseUrl}/api/status`);
373
- return result.ok && result.payload?.status === 'ok' ? result.payload : null;
374
- }, 30000, `bridge startup\n${bridge.details()}`);
375
- }
376
-
377
- function createSessionPayload(options = {}) {
378
- const accessToken = options.accessToken || ACCESS_TOKEN;
379
- const refreshToken = options.refreshToken || REFRESH_TOKEN;
380
- const expiresAt = options.expiresAt ?? Math.floor(Date.now() / 1000) + 3600;
381
- return JSON.stringify({
382
- access_token: accessToken,
383
- refresh_token: refreshToken,
384
- expires_at: expiresAt,
385
- user: {
386
- id: USER_ID,
387
- email: 'remote-registry-follower@example.test'
388
- }
389
- });
390
- }
391
-
392
- async function writeSession(authRoot, options = {}) {
393
- await mkdir(authRoot, { recursive: true });
394
- await writeFile(path.join(authRoot, 'supabase-session.json'), createSessionPayload(options), 'utf8');
395
- }
396
-
397
- async function waitForManagedAgent(bridge, managerEndpoint, label, timeoutMs = 20000) {
398
- return await waitFor(async () => {
399
- const result = await fetchJson(`${bridge.baseUrl}/api/remote/agent/status`);
400
- const agent = result.payload;
401
- return agent?.running === true
402
- && agent?.ready === true
403
- && String(agent.manager || '') === managerEndpoint
404
- ? agent
405
- : null;
406
- }, timeoutMs, `${label} managed agent\n${bridge.details()}`);
407
- }
408
-
409
- async function waitForManagedAgentRestart(bridge, managerEndpoint, previousPid, label, timeoutMs = 20000) {
410
- return await waitFor(async () => {
411
- const result = await fetchJson(`${bridge.baseUrl}/api/remote/agent/status`);
412
- const agent = result.payload;
413
- return agent?.running === true
414
- && agent?.ready === true
415
- && String(agent.manager || '') === managerEndpoint
416
- && Number(agent.pid || 0) > 0
417
- && Number(agent.pid || 0) !== Number(previousPid || 0)
418
- ? agent
419
- : null;
420
- }, timeoutMs, `${label} managed agent restart\n${bridge.details()}`);
421
- }
422
-
423
- async function waitForConnectedDevice(bridge, label) {
424
- return await waitFor(async () => {
425
- const result = await fetchJson(`${bridge.baseUrl}/api/remote/devices`);
426
- return result.payload?.devices?.find(device => device.connected === true) || null;
427
- }, 12000, `${label} connected device\n${bridge.details()}`);
428
- }
429
-
430
- function killProcess(pid) {
431
- const value = Number(pid || 0);
432
- assert.ok(value > 0, `expected positive pid, got ${pid}`);
433
- try {
434
- process.kill(value, 'SIGTERM');
435
- } catch (error) {
436
- if (error?.code !== 'ESRCH') {
437
- throw error;
438
- }
439
- }
440
- }
441
-
442
- async function main() {
443
- const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'mindexec-remote-registry-smoke-'));
444
- let fakeSupabase = null;
445
- let renewHost = null;
446
- let hostA = null;
447
- let hostB = null;
448
- let client = null;
449
-
450
- const renewHostBridgePort = await findFreePort();
451
- const renewHostRemotePort = await findFreePort();
452
- const hostABridgePort = await findFreePort();
453
- const hostARemotePort = await findFreePort();
454
- const hostBBridgePort = await findFreePort();
455
- const hostBRemotePort = await findFreePort();
456
- const clientBridgePort = await findFreePort();
457
- const clientRemotePort = await findFreePort();
458
- const stalePort = await findFreePort();
459
- const renewPublicHost = '192.0.2.10';
460
- const renewPublicEndpoint = `${renewPublicHost}:${renewHostRemotePort}`;
461
- const hostAEndpoint = `127.0.0.1:${hostARemotePort}`;
462
- const hostBEndpoint = `127.0.0.1:${hostBRemotePort}`;
463
- const staleEndpoint = `127.0.0.1:${stalePort}`;
464
- let currentTarget = null;
465
-
466
- try {
467
- fakeSupabase = await startFakeSupabase(
468
- () => currentTarget,
469
- target => {
470
- currentTarget = target;
471
- });
472
-
473
- const renewHostAuth = path.join(tempRoot, 'auth-renew-host');
474
- const hostAAuth = path.join(tempRoot, 'auth-host-a');
475
- const hostBAuth = path.join(tempRoot, 'auth-host-b');
476
- const clientAuth = path.join(tempRoot, 'auth-client');
477
- await writeSession(renewHostAuth);
478
- await writeSession(clientAuth, {
479
- accessToken: EXPIRED_ACCESS_TOKEN,
480
- expiresAt: Math.floor(Date.now() / 1000) - 30
481
- });
482
-
483
- renewHost = spawnBridge({
484
- bridgePort: renewHostBridgePort,
485
- remoteHubPort: renewHostRemotePort,
486
- workspacePath: path.join(tempRoot, 'renew-host'),
487
- authRoot: renewHostAuth,
488
- label: 'renew-host',
489
- supabaseUrl: fakeSupabase.url,
490
- follower: true,
491
- publicHost: renewPublicHost
492
- });
493
- await waitForBridge(renewHost);
494
-
495
- const renewSetHost = await fetchJson(`${renewHost.baseUrl}/api/remote/host-target`, {
496
- method: 'POST',
497
- token: BRIDGE_TOKEN,
498
- body: JSON.stringify({
499
- nodeId: 'remote-registry-renew-node',
500
- enabled: true,
501
- leaseMs: 60000
502
- })
503
- });
504
- assert.equal(renewSetHost.ok, true, JSON.stringify(renewSetHost.payload));
505
- assert.equal(renewSetHost.payload?.ok, true, JSON.stringify(renewSetHost.payload));
506
- assert.equal(renewSetHost.payload?.active, true, JSON.stringify(renewSetHost.payload));
507
- assert.equal(renewSetHost.payload?.hostTargetRenew?.status, 'active', JSON.stringify(renewSetHost.payload?.hostTargetRenew));
508
- assert.equal(currentTarget?.endpoint, renewPublicEndpoint, JSON.stringify(currentTarget));
509
- assert.equal(currentTarget?.node_id, 'remote-registry-renew-node', JSON.stringify(currentTarget));
510
- const explicitSetHostPublish = fakeSupabase.requests.find(request =>
511
- request.method === 'POST'
512
- && request.pathname === '/rest/v1/rpc/set_remote_host_target'
513
- && request.body?.p_node_id === 'remote-registry-renew-node');
514
- assert.equal(explicitSetHostPublish?.body?.p_takeover, true, JSON.stringify(explicitSetHostPublish?.body));
515
- const beforeQuietRenewPublishCount = fakeSupabase.requests.filter(request =>
516
- request.method === 'POST'
517
- && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
518
- const quietRenewSetHost = await fetchJson(`${renewHost.baseUrl}/api/remote/host-target`, {
519
- method: 'POST',
520
- token: BRIDGE_TOKEN,
521
- body: JSON.stringify({
522
- nodeId: 'remote-registry-renew-node',
523
- enabled: true,
524
- leaseMs: 60000,
525
- renew: true
526
- })
527
- });
528
- assert.equal(quietRenewSetHost.ok, true, JSON.stringify(quietRenewSetHost.payload));
529
- assert.equal(quietRenewSetHost.payload?.ok, true, JSON.stringify(quietRenewSetHost.payload));
530
- assert.equal(quietRenewSetHost.payload?.active, true, JSON.stringify(quietRenewSetHost.payload));
531
- assert.equal(quietRenewSetHost.payload?.hostTargetTakeover, false, JSON.stringify(quietRenewSetHost.payload));
532
- const quietRenewPublish = fakeSupabase.requests
533
- .filter(request =>
534
- request.method === 'POST'
535
- && request.pathname === '/rest/v1/rpc/set_remote_host_target')
536
- .slice(beforeQuietRenewPublishCount)
537
- .find(request => request.body?.p_node_id === 'remote-registry-renew-node');
538
- assert.equal(quietRenewPublish?.body?.p_takeover, false, JSON.stringify(quietRenewPublish?.body));
539
- await waitFor(() => {
540
- const publishCount = fakeSupabase.requests.filter(request =>
541
- request.method === 'POST'
542
- && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
543
- return publishCount >= 2 ? publishCount : null;
544
- }, 8000, `host-target auto renew publish\n${renewHost.details()}`);
545
- const beforeResumePublishCount = fakeSupabase.requests.filter(request =>
546
- request.method === 'POST'
547
- && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
548
- const renewResume = await fetchJson(`${renewHost.baseUrl}/api/remote/system/resume`, {
549
- method: 'POST',
550
- token: BRIDGE_TOKEN,
551
- body: JSON.stringify({
552
- driftMs: 65000
553
- })
554
- });
555
- assert.equal(renewResume.ok, true, JSON.stringify(renewResume.payload));
556
- assert.equal(renewResume.payload?.ok, true, JSON.stringify(renewResume.payload));
557
- assert.equal(renewResume.payload?.remoteSystemResume?.localHost, true, JSON.stringify(renewResume.payload?.remoteSystemResume));
558
- await waitFor(() => {
559
- const publishCount = fakeSupabase.requests.filter(request =>
560
- request.method === 'POST'
561
- && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
562
- return publishCount > beforeResumePublishCount ? publishCount : null;
563
- }, 8000, `host-target resume republish\n${renewHost.details()}`);
564
- const renewStatus = await fetchJson(`${renewHost.baseUrl}/api/status`);
565
- assert.equal(renewStatus.payload?.remoteHostTargetRenew?.status, 'active', JSON.stringify(renewStatus.payload?.remoteHostTargetRenew));
566
- assert.equal(renewStatus.payload?.remoteHostTargetRenew?.endpoint, renewPublicEndpoint, JSON.stringify(renewStatus.payload?.remoteHostTargetRenew));
567
- const currentLeaseId = currentTarget?.lease_id;
568
- const currentHostInstanceId = currentTarget?.host_instance_id;
569
- currentTarget = {
570
- ...currentTarget,
571
- pair_token: 'stale-local-pair-token',
572
- lease_id: 'stale-local-lease',
573
- host_instance_id: 'stale-local-host-instance',
574
- expires_at: new Date(Date.now() + 60_000).toISOString()
575
- };
576
- const staleLocalResume = await fetchJson(`${renewHost.baseUrl}/api/remote/system/resume`, {
577
- method: 'POST',
578
- token: BRIDGE_TOKEN,
579
- body: JSON.stringify({
580
- driftMs: 65000
581
- })
582
- });
583
- assert.equal(staleLocalResume.ok, true, JSON.stringify(staleLocalResume.payload));
584
- assert.equal(staleLocalResume.payload?.ok, true, JSON.stringify(staleLocalResume.payload));
585
- await waitFor(() => {
586
- return currentTarget?.pair_token === PAIR_TOKEN
587
- && currentTarget?.lease_id === currentLeaseId
588
- && currentTarget?.host_instance_id === currentHostInstanceId
589
- ? currentTarget
590
- : null;
591
- }, 8000, `stale local host target republish\n${renewHost.details()}`);
592
- const republishedStatus = await fetchJson(`${renewHost.baseUrl}/api/status`);
593
- assert.equal(republishedStatus.payload?.remoteHub?.hostTargetActive, true, JSON.stringify(republishedStatus.payload?.remoteHub));
594
- assert.equal(republishedStatus.payload?.remoteHostTargetRenew?.status, 'active', JSON.stringify(republishedStatus.payload?.remoteHostTargetRenew));
595
- assert.equal(republishedStatus.payload?.remoteHostTargetRenew?.reason, 'local-monitor-host-republished', JSON.stringify(republishedStatus.payload?.remoteHostTargetRenew));
596
- const renewAgent = await fetchJson(`${renewHost.baseUrl}/api/remote/agent/status`);
597
- assert.equal(renewAgent.payload?.running, false, JSON.stringify(renewAgent.payload));
598
-
599
- const renewClear = await fetchJson(`${renewHost.baseUrl}/api/remote/host-target`, {
600
- method: 'DELETE',
601
- token: BRIDGE_TOKEN,
602
- body: JSON.stringify({
603
- nodeId: 'remote-registry-renew-node'
604
- })
605
- });
606
- assert.equal(renewClear.ok, true, JSON.stringify(renewClear.payload));
607
- assert.equal(renewClear.payload?.ok, true, JSON.stringify(renewClear.payload));
608
- await renewHost.stop();
609
- renewHost = null;
610
-
611
- currentTarget = createRegistryTarget({
612
- endpoint: hostAEndpoint,
613
- endpointCandidates: [staleEndpoint, hostAEndpoint],
614
- leaseId: 'lease-a'
615
- });
616
-
617
- hostA = spawnBridge({
618
- bridgePort: hostABridgePort,
619
- remoteHubPort: hostARemotePort,
620
- workspacePath: path.join(tempRoot, 'host-a'),
621
- authRoot: hostAAuth,
622
- label: 'host-a'
623
- });
624
- hostB = spawnBridge({
625
- bridgePort: hostBBridgePort,
626
- remoteHubPort: hostBRemotePort,
627
- workspacePath: path.join(tempRoot, 'host-b'),
628
- authRoot: hostBAuth,
629
- label: 'host-b'
630
- });
631
- await waitForBridge(hostA);
632
- await waitForBridge(hostB);
633
-
634
- client = spawnBridge({
635
- bridgePort: clientBridgePort,
636
- remoteHubPort: clientRemotePort,
637
- workspacePath: path.join(tempRoot, 'client'),
638
- authRoot: clientAuth,
639
- label: 'client',
640
- supabaseUrl: fakeSupabase.url,
641
- follower: true
642
- });
643
- await waitForBridge(client);
644
-
645
- const firstAgent = await waitForManagedAgent(client, hostAEndpoint, 'host-a');
646
- assert.equal(firstAgent.usingNpx, false, JSON.stringify(firstAgent));
647
- assert.match(String(firstAgent.launcher || ''), /mindexec-remote-fast/i);
648
- assert.equal(firstAgent.manager, hostAEndpoint);
649
- assert.equal(firstAgent.managerCandidates?.[0], hostAEndpoint, JSON.stringify(firstAgent.managerCandidates));
650
- assert.equal(firstAgent.managerCandidates?.length, 1, JSON.stringify(firstAgent.managerCandidates));
651
- assert.ok(
652
- fakeSupabase.requests.some(request =>
653
- request.method === 'POST'
654
- && request.pathname === '/auth/v1/token'),
655
- 'expected LocalBridge to refresh expired persisted Supabase session without browser involvement');
656
- assert.ok(
657
- fakeSupabase.requests.some(request =>
658
- request.method === 'GET'
659
- && request.pathname === '/rest/v1/remote_host_targets'
660
- && request.authorization === `Bearer ${REFRESHED_ACCESS_TOKEN}`),
661
- 'expected registry read to use refreshed access token');
662
- await waitForConnectedDevice(hostA, 'host-a');
663
- const firstStatus = await fetchJson(`${client.baseUrl}/api/status`);
664
- assert.equal(firstStatus.payload?.remoteRegistryRealtime?.subscribed, true, JSON.stringify(firstStatus.payload?.remoteRegistryRealtime));
665
- assert.ok(fakeSupabase.realtimeClients.size >= 1, 'expected LocalBridge realtime watcher to connect');
666
- const firstPid = Number(firstAgent.pid || 0);
667
- assert.ok(firstPid > 0, JSON.stringify(firstAgent));
668
-
669
- const clientResume = await fetchJson(`${client.baseUrl}/api/remote/system/resume`, {
670
- method: 'POST',
671
- token: BRIDGE_TOKEN,
672
- body: JSON.stringify({
673
- driftMs: 65000
674
- })
675
- });
676
- assert.equal(clientResume.ok, true, JSON.stringify(clientResume.payload));
677
- assert.equal(clientResume.payload?.ok, true, JSON.stringify(clientResume.payload));
678
- assert.equal(clientResume.payload?.remoteSystemResume?.registryAgentRestarted, true, JSON.stringify(clientResume.payload?.remoteSystemResume));
679
- const resumedAgent = await waitForManagedAgentRestart(client, hostAEndpoint, firstPid, 'host-a after resume', 12000);
680
- assert.equal(resumedAgent.usingNpx, false, JSON.stringify(resumedAgent));
681
- assert.match(String(resumedAgent.launcher || ''), /mindexec-remote-fast/i);
682
- assert.equal(resumedAgent.leaseId, 'lease-a');
683
- await waitForConnectedDevice(hostA, 'host-a after resume');
684
-
685
- currentTarget = createRegistryTarget({
686
- endpoint: hostBEndpoint,
687
- endpointCandidates: [hostBEndpoint],
688
- leaseId: 'lease-b'
689
- });
690
- fakeSupabase.broadcastChange('UPDATE');
691
-
692
- const secondAgent = await waitForManagedAgent(client, hostBEndpoint, 'host-b', 9000);
693
- assert.equal(secondAgent.usingNpx, false, JSON.stringify(secondAgent));
694
- assert.match(String(secondAgent.launcher || ''), /mindexec-remote-fast/i);
695
- assert.equal(secondAgent.manager, hostBEndpoint);
696
- assert.equal(secondAgent.leaseId, 'lease-b');
697
- await waitForConnectedDevice(hostB, 'host-b');
698
-
699
- await wait(250);
700
- currentTarget = null;
701
- fakeSupabase.broadcastChange('DELETE');
702
- await waitFor(async () => {
703
- const status = await fetchJson(`${client.baseUrl}/api/status`);
704
- const agent = await fetchJson(`${client.baseUrl}/api/remote/agent/status`);
705
- return status.payload?.remoteRegistryFollower?.reason === 'no-active-target-agent-kept'
706
- && agent.payload?.running === true
707
- && String(agent.payload?.manager || '') === hostBEndpoint
708
- ? { status: status.payload.remoteRegistryFollower, agent: agent.payload }
709
- : null;
710
- }, 4000, `transient no-active-target keeps managed agent\n${client.details()}`);
711
-
712
- currentTarget = createRegistryTarget({
713
- endpoint: hostBEndpoint,
714
- endpointCandidates: [hostBEndpoint],
715
- leaseId: 'lease-b'
716
- });
717
- fakeSupabase.broadcastChange('INSERT');
718
- const restoredAgent = await waitForManagedAgent(client, hostBEndpoint, 'host-b after transient missing target', 9000);
719
- assert.equal(Number(restoredAgent.pid || 0), Number(secondAgent.pid || 0), JSON.stringify(restoredAgent));
720
-
721
- const missingAuthWake = await fetchJson(`${client.baseUrl}/api/auth/session`, {
722
- method: 'DELETE',
723
- token: BRIDGE_TOKEN
724
- });
725
- assert.equal(missingAuthWake.ok, true, JSON.stringify(missingAuthWake.payload));
726
- await waitFor(async () => {
727
- const status = await fetchJson(`${client.baseUrl}/api/status`);
728
- const agent = await fetchJson(`${client.baseUrl}/api/remote/agent/status`);
729
- return status.payload?.remoteRegistryFollower?.reason === 'registry-not-authenticated-agent-kept'
730
- && status.payload?.remoteRegistryFollower?.agentKept === true
731
- && agent.payload?.running === true
732
- && String(agent.payload?.manager || '') === hostBEndpoint
733
- && Number(agent.payload?.pid || 0) === Number(secondAgent.pid || 0)
734
- ? { status: status.payload.remoteRegistryFollower, agent: agent.payload }
735
- : null;
736
- }, 4000, `transient missing auth keeps managed agent\n${client.details()}`);
737
-
738
- const restoredAuthWake = await fetchJson(`${client.baseUrl}/api/auth/session`, {
739
- method: 'POST',
740
- token: BRIDGE_TOKEN,
741
- body: JSON.stringify({
742
- content: createSessionPayload()
743
- })
744
- });
745
- assert.equal(restoredAuthWake.ok, true, JSON.stringify(restoredAuthWake.payload));
746
- const authRestoredAgent = await waitForManagedAgent(client, hostBEndpoint, 'host-b after transient missing auth', 9000);
747
- assert.equal(Number(authRestoredAgent.pid || 0), Number(secondAgent.pid || 0), JSON.stringify(authRestoredAgent));
748
-
749
- const secondPid = Number(secondAgent.pid || 0);
750
- killProcess(secondPid);
751
- const restartedAgent = await waitForManagedAgentRestart(client, hostBEndpoint, secondPid, 'host-b', 12000);
752
- assert.equal(restartedAgent.usingNpx, false, JSON.stringify(restartedAgent));
753
- assert.match(String(restartedAgent.launcher || ''), /mindexec-remote-fast/i);
754
- assert.equal(restartedAgent.leaseId, 'lease-b');
755
- await waitForConnectedDevice(hostB, 'host-b after restart');
756
-
757
- currentTarget = {
758
- ...currentTarget,
759
- active: false,
760
- expires_at: new Date(Date.now() - 1000).toISOString()
761
- };
762
- fakeSupabase.broadcastChange('UPDATE');
763
- await wait(700);
764
- fakeSupabase.broadcastChange('UPDATE');
765
-
766
- await waitFor(async () => {
767
- const status = await fetchJson(`${client.baseUrl}/api/status`);
768
- const agent = await fetchJson(`${client.baseUrl}/api/remote/agent/status`);
769
- return status.payload?.remoteRegistryFollower?.reason === 'registry-inactive-agent-kept'
770
- && status.payload?.remoteRegistryFollower?.agentKept === true
771
- && status.payload?.remoteRegistryFollower?.dataPlaneReady === true
772
- && agent.payload?.running === true
773
- && agent.payload?.ready === true
774
- && String(agent.payload?.manager || '') === hostBEndpoint
775
- && Number(agent.payload?.pid || 0) === Number(restartedAgent.pid || 0)
776
- ? { status: status.payload.remoteRegistryFollower, agent: agent.payload }
777
- : null;
778
- }, 9000, `registry inactive keeps ready data-plane agent\n${client.details()}`);
779
-
780
- const inactivePid = Number(restartedAgent.pid || 0);
781
- killProcess(inactivePid);
782
- const recoveredInactiveAgent = await waitForManagedAgentRestart(
783
- client,
784
- hostBEndpoint,
785
- inactivePid,
786
- 'host-b after inactive target recovery',
787
- 12000);
788
- assert.equal(recoveredInactiveAgent.usingNpx, false, JSON.stringify(recoveredInactiveAgent));
789
- assert.match(String(recoveredInactiveAgent.launcher || ''), /mindexec-remote-fast/i);
790
- assert.equal(recoveredInactiveAgent.leaseId, 'lease-b');
791
- await waitForConnectedDevice(hostB, 'host-b after inactive target recovery');
792
- await waitFor(async () => {
793
- const status = await fetchJson(`${client.baseUrl}/api/status`);
794
- return status.payload?.remoteRegistryFollower?.reason === 'registry-inactive-agent-recovered'
795
- && String(status.payload?.remoteRegistryFollower?.targetEndpoint || '') === hostBEndpoint
796
- ? status.payload.remoteRegistryFollower
797
- : null;
798
- }, 4000, `inactive target recovered managed agent\n${client.details()}`);
799
- const finalStatus = await fetchJson(`${client.baseUrl}/api/status`);
800
- assert.ok(finalStatus.payload?.remoteRegistryRealtime?.changes >= 2, JSON.stringify(finalStatus.payload?.remoteRegistryRealtime));
801
- assert.ok(finalStatus.payload?.remoteRegistryRealtime?.wakeups >= 2, JSON.stringify(finalStatus.payload?.remoteRegistryRealtime));
802
-
803
- assert.ok(fakeSupabase.requests.length >= 2, JSON.stringify(fakeSupabase.requests));
804
- console.log('Remote registry follower smoke OK');
805
- } finally {
806
- if (client) await client.stop();
807
- if (hostB) await hostB.stop();
808
- if (hostA) await hostA.stop();
809
- if (renewHost) await renewHost.stop();
810
- if (fakeSupabase) await fakeSupabase.stop();
811
- await rm(tempRoot, { recursive: true, force: true });
812
- }
813
- }
814
-
815
- await main();
1
+ #!/usr/bin/env node
2
+
3
+ import assert from 'node:assert/strict';
4
+ import { spawn } from 'node:child_process';
5
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
6
+ import { createServer } from 'node:http';
7
+ import net from 'node:net';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { WebSocketServer } from 'ws';
12
+
13
+ const BRIDGE_TOKEN = 'remote-registry-follower-smoke-token';
14
+ const PAIR_TOKEN = 'remote-registry-follower-pair-token';
15
+ const USER_ID = '11111111-2222-4333-8444-555555555555';
16
+ const SUPABASE_KEY = 'remote-registry-follower-key';
17
+ const ACCESS_TOKEN = 'remote-registry-follower-access-token';
18
+ const EXPIRED_ACCESS_TOKEN = 'remote-registry-follower-expired-access-token';
19
+ const REFRESHED_ACCESS_TOKEN = 'remote-registry-follower-refreshed-access-token';
20
+ const REFRESH_TOKEN = 'remote-registry-follower-refresh-token';
21
+ const LOCAL_BRIDGE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
22
+
23
+ function wait(ms) {
24
+ return new Promise(resolve => setTimeout(resolve, ms));
25
+ }
26
+
27
+ async function findFreePort() {
28
+ return await new Promise((resolve, reject) => {
29
+ const server = net.createServer();
30
+ server.unref();
31
+ server.once('error', reject);
32
+ server.listen(0, '127.0.0.1', () => {
33
+ const address = server.address();
34
+ const port = typeof address === 'object' && address ? address.port : 0;
35
+ server.close(() => resolve(port));
36
+ });
37
+ });
38
+ }
39
+
40
+ async function fetchJson(url, options = {}) {
41
+ const response = await fetch(url, {
42
+ ...options,
43
+ headers: {
44
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
45
+ 'X-Bridge-Token': options.token || BRIDGE_TOKEN,
46
+ ...(options.headers || {})
47
+ }
48
+ });
49
+ let payload = null;
50
+ try {
51
+ payload = await response.json();
52
+ } catch {
53
+ // Empty responses are allowed in failure diagnostics.
54
+ }
55
+ return { ok: response.ok, status: response.status, payload };
56
+ }
57
+
58
+ async function waitFor(predicate, timeoutMs, label) {
59
+ const startedAt = Date.now();
60
+ let lastError = null;
61
+ while (Date.now() - startedAt < timeoutMs) {
62
+ try {
63
+ const value = await predicate();
64
+ if (value) {
65
+ return value;
66
+ }
67
+ } catch (error) {
68
+ lastError = error;
69
+ }
70
+ await wait(100);
71
+ }
72
+ throw new Error(`Timed out waiting for ${label}${lastError ? `: ${lastError.message}` : ''}.`);
73
+ }
74
+
75
+ function createRegistryTarget({ endpoint, endpointCandidates, leaseId, active = true, pairToken = PAIR_TOKEN }) {
76
+ return {
77
+ user_id: USER_ID,
78
+ active,
79
+ endpoint,
80
+ endpoint_candidates: endpointCandidates,
81
+ pair_token: pairToken,
82
+ lease_id: leaseId,
83
+ node_id: 'remote-registry-follower-node',
84
+ host_instance_id: `host-${leaseId}`,
85
+ expires_at: new Date(Date.now() + 60_000).toISOString()
86
+ };
87
+ }
88
+
89
+ function startFakeSupabase(getTarget, setTarget = null) {
90
+ const requests = [];
91
+ const realtimeClients = new Set();
92
+ const validAccessTokens = new Set([ACCESS_TOKEN]);
93
+ const assertRegistryAuth = req => {
94
+ assert.equal(String(req.headers.apikey || ''), SUPABASE_KEY);
95
+ const authorization = String(req.headers.authorization || '');
96
+ assert.ok(
97
+ validAccessTokens.has(authorization.replace(/^Bearer\s+/i, '')),
98
+ `unexpected registry authorization: ${authorization}`);
99
+ };
100
+ const server = createServer(async (req, res) => {
101
+ const readBody = () => new Promise(resolve => {
102
+ let body = '';
103
+ req.on('data', chunk => {
104
+ body += chunk.toString();
105
+ });
106
+ req.on('end', () => resolve(body));
107
+ });
108
+ const parsed = new URL(req.url || '/', 'http://127.0.0.1');
109
+ const requestRecord = {
110
+ method: req.method,
111
+ pathname: parsed.pathname,
112
+ authorization: req.headers.authorization || '',
113
+ apikey: req.headers.apikey || ''
114
+ };
115
+ requests.push(requestRecord);
116
+
117
+ if (req.method === 'GET' && parsed.pathname === '/rest/v1/remote_host_targets') {
118
+ assertRegistryAuth(req);
119
+ res.writeHead(200, {
120
+ 'Content-Type': 'application/json',
121
+ 'Cache-Control': 'no-store'
122
+ });
123
+ const target = getTarget();
124
+ res.end(JSON.stringify(target ? [target] : []));
125
+ return;
126
+ }
127
+
128
+ if (req.method === 'POST' && parsed.pathname === '/rest/v1/rpc/set_remote_host_target') {
129
+ assertRegistryAuth(req);
130
+ const body = JSON.parse(await readBody() || '{}');
131
+ requestRecord.body = body;
132
+ const now = Date.now();
133
+ const existing = getTarget();
134
+ const sameLease = existing
135
+ && String(existing.lease_id || '') === String(body.p_lease_id || '')
136
+ && String(existing.host_instance_id || '') === String(body.p_host_instance_id || '');
137
+ const expired = !existing?.expires_at || Date.parse(existing.expires_at) <= now;
138
+ if (existing?.active === true && !sameLease && !expired && body.p_takeover !== true) {
139
+ res.writeHead(200, { 'Content-Type': 'application/json' });
140
+ res.end(JSON.stringify([{ ok: false, reason: 'host-target-taken' }]));
141
+ return;
142
+ }
143
+
144
+ setTarget?.({
145
+ user_id: USER_ID,
146
+ active: true,
147
+ endpoint: String(body.p_endpoint || ''),
148
+ endpoint_candidates: Array.isArray(body.p_endpoint_candidates)
149
+ ? body.p_endpoint_candidates
150
+ : [String(body.p_endpoint || '')].filter(Boolean),
151
+ pair_token: String(body.p_pair_token || ''),
152
+ lease_id: String(body.p_lease_id || ''),
153
+ node_id: String(body.p_node_id || ''),
154
+ host_instance_id: String(body.p_host_instance_id || ''),
155
+ expires_at: String(body.p_expires_at || new Date(Date.now() + 60_000).toISOString())
156
+ });
157
+ res.writeHead(200, { 'Content-Type': 'application/json' });
158
+ res.end(JSON.stringify([{ ok: true, reason: 'ok' }]));
159
+ return;
160
+ }
161
+
162
+ if (req.method === 'POST' && parsed.pathname === '/auth/v1/token') {
163
+ assert.equal(parsed.searchParams.get('grant_type'), 'refresh_token');
164
+ assert.equal(String(req.headers.apikey || ''), SUPABASE_KEY);
165
+ assert.equal(String(req.headers.authorization || ''), `Bearer ${SUPABASE_KEY}`);
166
+ const body = JSON.parse(await readBody() || '{}');
167
+ assert.equal(body.refresh_token, REFRESH_TOKEN);
168
+ validAccessTokens.add(REFRESHED_ACCESS_TOKEN);
169
+ res.writeHead(200, {
170
+ 'Content-Type': 'application/json',
171
+ 'Cache-Control': 'no-store'
172
+ });
173
+ res.end(JSON.stringify({
174
+ access_token: REFRESHED_ACCESS_TOKEN,
175
+ refresh_token: REFRESH_TOKEN,
176
+ token_type: 'bearer',
177
+ expires_in: 3600,
178
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
179
+ user: {
180
+ id: USER_ID,
181
+ email: 'remote-registry-follower@example.test'
182
+ }
183
+ }));
184
+ return;
185
+ }
186
+
187
+ res.writeHead(404, { 'Content-Type': 'application/json' });
188
+ res.end(JSON.stringify({ error: 'not-found' }));
189
+ });
190
+ const realtime = new WebSocketServer({ noServer: true });
191
+
192
+ realtime.on('connection', (ws, req) => {
193
+ realtimeClients.add(ws);
194
+ ws.on('message', data => {
195
+ const text = data.toString();
196
+ let message = null;
197
+ try {
198
+ message = JSON.parse(text);
199
+ } catch {
200
+ return;
201
+ }
202
+
203
+ if (message.event === 'phx_join') {
204
+ assert.equal(String(req.headers.apikey || ''), SUPABASE_KEY);
205
+ assert.ok(validAccessTokens.has(String(req.headers.authorization || '').replace(/^Bearer\s+/i, '')));
206
+ assert.ok(validAccessTokens.has(String(message.payload?.access_token || '')));
207
+ assert.deepEqual(
208
+ message.payload?.config?.postgres_changes?.[0],
209
+ {
210
+ event: '*',
211
+ schema: 'public',
212
+ table: 'remote_host_targets',
213
+ filter: `user_id=eq.${USER_ID}`
214
+ });
215
+ ws.remoteRegistryTopic = message.topic;
216
+ ws.send(JSON.stringify({
217
+ topic: message.topic,
218
+ event: 'phx_reply',
219
+ payload: {
220
+ status: 'ok',
221
+ response: {
222
+ postgres_changes: [
223
+ {
224
+ id: 1,
225
+ event: '*',
226
+ schema: 'public',
227
+ table: 'remote_host_targets'
228
+ }
229
+ ]
230
+ }
231
+ },
232
+ ref: message.ref,
233
+ join_ref: message.join_ref
234
+ }));
235
+ return;
236
+ }
237
+
238
+ if (message.event === 'heartbeat') {
239
+ ws.send(JSON.stringify({
240
+ topic: message.topic,
241
+ event: 'phx_reply',
242
+ payload: { status: 'ok', response: {} },
243
+ ref: message.ref
244
+ }));
245
+ }
246
+ });
247
+ ws.on('close', () => realtimeClients.delete(ws));
248
+ });
249
+
250
+ server.on('upgrade', (req, socket, head) => {
251
+ const parsed = new URL(req.url || '/', 'http://127.0.0.1');
252
+ if (parsed.pathname !== '/realtime/v1/websocket') {
253
+ socket.destroy();
254
+ return;
255
+ }
256
+
257
+ realtime.handleUpgrade(req, socket, head, ws => {
258
+ realtime.emit('connection', ws, req);
259
+ });
260
+ });
261
+
262
+ return new Promise((resolve, reject) => {
263
+ server.once('error', reject);
264
+ server.listen(0, '127.0.0.1', () => {
265
+ const address = server.address();
266
+ const port = typeof address === 'object' && address ? address.port : 0;
267
+ resolve({
268
+ url: `http://127.0.0.1:${port}`,
269
+ requests,
270
+ realtimeClients,
271
+ broadcastChange: (type = 'UPDATE') => {
272
+ for (const client of realtimeClients) {
273
+ if (client.readyState !== 1 || !client.remoteRegistryTopic) {
274
+ continue;
275
+ }
276
+
277
+ client.send(JSON.stringify({
278
+ topic: client.remoteRegistryTopic,
279
+ event: 'postgres_changes',
280
+ payload: {
281
+ ids: [1],
282
+ data: {
283
+ schema: 'public',
284
+ table: 'remote_host_targets',
285
+ commit_timestamp: new Date().toISOString(),
286
+ type,
287
+ record: getTarget(),
288
+ old_record: null
289
+ }
290
+ },
291
+ ref: null
292
+ }));
293
+ }
294
+ },
295
+ stop: () => new Promise(done => {
296
+ for (const client of realtimeClients) {
297
+ try {
298
+ client.close();
299
+ } catch {
300
+ // best effort only
301
+ }
302
+ }
303
+ realtime.close(() => server.close(done));
304
+ })
305
+ });
306
+ });
307
+ });
308
+ }
309
+
310
+ function spawnBridge({ bridgePort, remoteHubPort, workspacePath, authRoot, label, supabaseUrl = '', follower = false, publicHost = '' }) {
311
+ const child = spawn(process.execPath, ['server.js'], {
312
+ cwd: LOCAL_BRIDGE_DIR,
313
+ stdio: ['ignore', 'pipe', 'pipe'],
314
+ windowsHide: true,
315
+ env: {
316
+ ...process.env,
317
+ BRIDGE_PORT: String(bridgePort),
318
+ BRIDGE_TOKEN,
319
+ BRIDGE_REQUIRE_TOKEN: '1',
320
+ MINDEXEC_REMOTE_HUB: '1',
321
+ REMOTE_HUB_HOST: '127.0.0.1',
322
+ REMOTE_HUB_PORT: String(remoteHubPort),
323
+ REMOTE_HUB_PUBLIC_HOST: publicHost,
324
+ REMOTE_HUB_PAIR_TOKEN: PAIR_TOKEN,
325
+ WORKSPACE_PATH: workspacePath,
326
+ MINDEXEC_AUTH_DATA_ROOT: authRoot,
327
+ MINDEXEC_REMOTE_REGISTRY_FOLLOWER: follower ? '1' : '0',
328
+ MINDEXEC_REMOTE_REGISTRY_POLL_MS: '10000',
329
+ MINDEXEC_REMOTE_REGISTRY_FAST_RETRY_MS: '250',
330
+ MINDEXEC_REMOTE_REGISTRY_INACTIVE_STOP_COUNT: '2',
331
+ MINDEXEC_REMOTE_REGISTRY_INACTIVE_GRACE_MS: '500',
332
+ MINDEXEC_REMOTE_REGISTRY_REALTIME_RECONNECT_MS: '250',
333
+ MINDEXEC_REMOTE_REGISTRY_REALTIME_DEBOUNCE_MS: '100',
334
+ MINDEXEC_REMOTE_HOST_TARGET_RENEW_MS: '5000',
335
+ SUPABASE_URL: supabaseUrl,
336
+ SUPABASE_KEY,
337
+ NO_COLOR: '1'
338
+ }
339
+ });
340
+
341
+ let stdout = '';
342
+ let stderr = '';
343
+ child.stdout.on('data', chunk => {
344
+ stdout += chunk.toString();
345
+ });
346
+ child.stderr.on('data', chunk => {
347
+ stderr += chunk.toString();
348
+ });
349
+
350
+ const exitPromise = new Promise(resolve => child.once('exit', resolve));
351
+ const details = () => `${label} stdout=${stdout}\n${label} stderr=${stderr}`;
352
+ const stop = async () => {
353
+ if (child.exitCode === null && !child.killed) {
354
+ child.kill('SIGTERM');
355
+ await Promise.race([exitPromise, wait(5000)]);
356
+ if (child.exitCode === null && !child.killed) {
357
+ child.kill('SIGKILL');
358
+ }
359
+ }
360
+ };
361
+
362
+ return {
363
+ baseUrl: `http://127.0.0.1:${bridgePort}`,
364
+ child,
365
+ details,
366
+ stop
367
+ };
368
+ }
369
+
370
+ async function waitForBridge(bridge) {
371
+ return await waitFor(async () => {
372
+ const result = await fetchJson(`${bridge.baseUrl}/api/status`);
373
+ return result.ok && result.payload?.status === 'ok' ? result.payload : null;
374
+ }, 30000, `bridge startup\n${bridge.details()}`);
375
+ }
376
+
377
+ function createSessionPayload(options = {}) {
378
+ const accessToken = options.accessToken || ACCESS_TOKEN;
379
+ const refreshToken = options.refreshToken || REFRESH_TOKEN;
380
+ const expiresAt = options.expiresAt ?? Math.floor(Date.now() / 1000) + 3600;
381
+ return JSON.stringify({
382
+ access_token: accessToken,
383
+ refresh_token: refreshToken,
384
+ expires_at: expiresAt,
385
+ user: {
386
+ id: USER_ID,
387
+ email: 'remote-registry-follower@example.test'
388
+ }
389
+ });
390
+ }
391
+
392
+ async function writeSession(authRoot, options = {}) {
393
+ await mkdir(authRoot, { recursive: true });
394
+ await writeFile(path.join(authRoot, 'supabase-session.json'), createSessionPayload(options), 'utf8');
395
+ }
396
+
397
+ async function waitForManagedAgent(bridge, managerEndpoint, label, timeoutMs = 20000) {
398
+ return await waitFor(async () => {
399
+ const result = await fetchJson(`${bridge.baseUrl}/api/remote/agent/status`);
400
+ const agent = result.payload;
401
+ return agent?.running === true
402
+ && agent?.ready === true
403
+ && String(agent.manager || '') === managerEndpoint
404
+ ? agent
405
+ : null;
406
+ }, timeoutMs, `${label} managed agent\n${bridge.details()}`);
407
+ }
408
+
409
+ async function waitForManagedAgentRestart(bridge, managerEndpoint, previousPid, label, timeoutMs = 20000) {
410
+ return await waitFor(async () => {
411
+ const result = await fetchJson(`${bridge.baseUrl}/api/remote/agent/status`);
412
+ const agent = result.payload;
413
+ return agent?.running === true
414
+ && agent?.ready === true
415
+ && String(agent.manager || '') === managerEndpoint
416
+ && Number(agent.pid || 0) > 0
417
+ && Number(agent.pid || 0) !== Number(previousPid || 0)
418
+ ? agent
419
+ : null;
420
+ }, timeoutMs, `${label} managed agent restart\n${bridge.details()}`);
421
+ }
422
+
423
+ async function waitForConnectedDevice(bridge, label) {
424
+ return await waitFor(async () => {
425
+ const result = await fetchJson(`${bridge.baseUrl}/api/remote/devices`);
426
+ return result.payload?.devices?.find(device => device.connected === true) || null;
427
+ }, 12000, `${label} connected device\n${bridge.details()}`);
428
+ }
429
+
430
+ function killProcess(pid) {
431
+ const value = Number(pid || 0);
432
+ assert.ok(value > 0, `expected positive pid, got ${pid}`);
433
+ try {
434
+ process.kill(value, 'SIGTERM');
435
+ } catch (error) {
436
+ if (error?.code !== 'ESRCH') {
437
+ throw error;
438
+ }
439
+ }
440
+ }
441
+
442
+ async function main() {
443
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'mindexec-remote-registry-smoke-'));
444
+ let fakeSupabase = null;
445
+ let renewHost = null;
446
+ let hostA = null;
447
+ let hostB = null;
448
+ let client = null;
449
+
450
+ const renewHostBridgePort = await findFreePort();
451
+ const renewHostRemotePort = await findFreePort();
452
+ const hostABridgePort = await findFreePort();
453
+ const hostARemotePort = await findFreePort();
454
+ const hostBBridgePort = await findFreePort();
455
+ const hostBRemotePort = await findFreePort();
456
+ const clientBridgePort = await findFreePort();
457
+ const clientRemotePort = await findFreePort();
458
+ const stalePort = await findFreePort();
459
+ const renewPublicHost = '192.0.2.10';
460
+ const renewPublicEndpoint = `${renewPublicHost}:${renewHostRemotePort}`;
461
+ const hostAEndpoint = `127.0.0.1:${hostARemotePort}`;
462
+ const hostBEndpoint = `127.0.0.1:${hostBRemotePort}`;
463
+ const staleEndpoint = `127.0.0.1:${stalePort}`;
464
+ let currentTarget = null;
465
+
466
+ try {
467
+ fakeSupabase = await startFakeSupabase(
468
+ () => currentTarget,
469
+ target => {
470
+ currentTarget = target;
471
+ });
472
+
473
+ const renewHostAuth = path.join(tempRoot, 'auth-renew-host');
474
+ const hostAAuth = path.join(tempRoot, 'auth-host-a');
475
+ const hostBAuth = path.join(tempRoot, 'auth-host-b');
476
+ const clientAuth = path.join(tempRoot, 'auth-client');
477
+ await writeSession(renewHostAuth);
478
+ await writeSession(clientAuth, {
479
+ accessToken: EXPIRED_ACCESS_TOKEN,
480
+ expiresAt: Math.floor(Date.now() / 1000) - 30
481
+ });
482
+
483
+ renewHost = spawnBridge({
484
+ bridgePort: renewHostBridgePort,
485
+ remoteHubPort: renewHostRemotePort,
486
+ workspacePath: path.join(tempRoot, 'renew-host'),
487
+ authRoot: renewHostAuth,
488
+ label: 'renew-host',
489
+ supabaseUrl: fakeSupabase.url,
490
+ follower: true,
491
+ publicHost: renewPublicHost
492
+ });
493
+ await waitForBridge(renewHost);
494
+
495
+ const renewSetHost = await fetchJson(`${renewHost.baseUrl}/api/remote/host-target`, {
496
+ method: 'POST',
497
+ token: BRIDGE_TOKEN,
498
+ body: JSON.stringify({
499
+ nodeId: 'remote-registry-renew-node',
500
+ enabled: true,
501
+ leaseMs: 60000
502
+ })
503
+ });
504
+ assert.equal(renewSetHost.ok, true, JSON.stringify(renewSetHost.payload));
505
+ assert.equal(renewSetHost.payload?.ok, true, JSON.stringify(renewSetHost.payload));
506
+ assert.equal(renewSetHost.payload?.active, true, JSON.stringify(renewSetHost.payload));
507
+ assert.equal(renewSetHost.payload?.hostTargetRenew?.status, 'active', JSON.stringify(renewSetHost.payload?.hostTargetRenew));
508
+ assert.equal(currentTarget?.endpoint, renewPublicEndpoint, JSON.stringify(currentTarget));
509
+ assert.equal(currentTarget?.node_id, 'remote-registry-renew-node', JSON.stringify(currentTarget));
510
+ const explicitSetHostPublish = fakeSupabase.requests.find(request =>
511
+ request.method === 'POST'
512
+ && request.pathname === '/rest/v1/rpc/set_remote_host_target'
513
+ && request.body?.p_node_id === 'remote-registry-renew-node');
514
+ assert.equal(explicitSetHostPublish?.body?.p_takeover, true, JSON.stringify(explicitSetHostPublish?.body));
515
+ const beforeQuietRenewPublishCount = fakeSupabase.requests.filter(request =>
516
+ request.method === 'POST'
517
+ && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
518
+ const quietRenewSetHost = await fetchJson(`${renewHost.baseUrl}/api/remote/host-target`, {
519
+ method: 'POST',
520
+ token: BRIDGE_TOKEN,
521
+ body: JSON.stringify({
522
+ nodeId: 'remote-registry-renew-node',
523
+ enabled: true,
524
+ leaseMs: 60000,
525
+ renew: true
526
+ })
527
+ });
528
+ assert.equal(quietRenewSetHost.ok, true, JSON.stringify(quietRenewSetHost.payload));
529
+ assert.equal(quietRenewSetHost.payload?.ok, true, JSON.stringify(quietRenewSetHost.payload));
530
+ assert.equal(quietRenewSetHost.payload?.active, true, JSON.stringify(quietRenewSetHost.payload));
531
+ assert.equal(quietRenewSetHost.payload?.hostTargetTakeover, false, JSON.stringify(quietRenewSetHost.payload));
532
+ const quietRenewPublish = fakeSupabase.requests
533
+ .filter(request =>
534
+ request.method === 'POST'
535
+ && request.pathname === '/rest/v1/rpc/set_remote_host_target')
536
+ .slice(beforeQuietRenewPublishCount)
537
+ .find(request => request.body?.p_node_id === 'remote-registry-renew-node');
538
+ assert.equal(quietRenewPublish?.body?.p_takeover, false, JSON.stringify(quietRenewPublish?.body));
539
+ await waitFor(() => {
540
+ const publishCount = fakeSupabase.requests.filter(request =>
541
+ request.method === 'POST'
542
+ && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
543
+ return publishCount >= 2 ? publishCount : null;
544
+ }, 8000, `host-target auto renew publish\n${renewHost.details()}`);
545
+ const beforeResumePublishCount = fakeSupabase.requests.filter(request =>
546
+ request.method === 'POST'
547
+ && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
548
+ const renewResume = await fetchJson(`${renewHost.baseUrl}/api/remote/system/resume`, {
549
+ method: 'POST',
550
+ token: BRIDGE_TOKEN,
551
+ body: JSON.stringify({
552
+ driftMs: 65000
553
+ })
554
+ });
555
+ assert.equal(renewResume.ok, true, JSON.stringify(renewResume.payload));
556
+ assert.equal(renewResume.payload?.ok, true, JSON.stringify(renewResume.payload));
557
+ assert.equal(renewResume.payload?.remoteSystemResume?.localHost, true, JSON.stringify(renewResume.payload?.remoteSystemResume));
558
+ await waitFor(() => {
559
+ const publishCount = fakeSupabase.requests.filter(request =>
560
+ request.method === 'POST'
561
+ && request.pathname === '/rest/v1/rpc/set_remote_host_target').length;
562
+ return publishCount > beforeResumePublishCount ? publishCount : null;
563
+ }, 8000, `host-target resume republish\n${renewHost.details()}`);
564
+ const renewStatus = await fetchJson(`${renewHost.baseUrl}/api/status`);
565
+ assert.equal(renewStatus.payload?.remoteHostTargetRenew?.status, 'active', JSON.stringify(renewStatus.payload?.remoteHostTargetRenew));
566
+ assert.equal(renewStatus.payload?.remoteHostTargetRenew?.endpoint, renewPublicEndpoint, JSON.stringify(renewStatus.payload?.remoteHostTargetRenew));
567
+ const currentLeaseId = currentTarget?.lease_id;
568
+ const currentHostInstanceId = currentTarget?.host_instance_id;
569
+ currentTarget = {
570
+ ...currentTarget,
571
+ pair_token: 'stale-local-pair-token',
572
+ lease_id: 'stale-local-lease',
573
+ host_instance_id: 'stale-local-host-instance',
574
+ expires_at: new Date(Date.now() + 60_000).toISOString()
575
+ };
576
+ const staleLocalResume = await fetchJson(`${renewHost.baseUrl}/api/remote/system/resume`, {
577
+ method: 'POST',
578
+ token: BRIDGE_TOKEN,
579
+ body: JSON.stringify({
580
+ driftMs: 65000
581
+ })
582
+ });
583
+ assert.equal(staleLocalResume.ok, true, JSON.stringify(staleLocalResume.payload));
584
+ assert.equal(staleLocalResume.payload?.ok, true, JSON.stringify(staleLocalResume.payload));
585
+ await waitFor(() => {
586
+ return currentTarget?.pair_token === PAIR_TOKEN
587
+ && currentTarget?.lease_id === currentLeaseId
588
+ && currentTarget?.host_instance_id === currentHostInstanceId
589
+ ? currentTarget
590
+ : null;
591
+ }, 8000, `stale local host target republish\n${renewHost.details()}`);
592
+ const republishedStatus = await fetchJson(`${renewHost.baseUrl}/api/status`);
593
+ assert.equal(republishedStatus.payload?.remoteHub?.hostTargetActive, true, JSON.stringify(republishedStatus.payload?.remoteHub));
594
+ assert.equal(republishedStatus.payload?.remoteHostTargetRenew?.status, 'active', JSON.stringify(republishedStatus.payload?.remoteHostTargetRenew));
595
+ assert.equal(republishedStatus.payload?.remoteHostTargetRenew?.reason, 'local-monitor-host-republished', JSON.stringify(republishedStatus.payload?.remoteHostTargetRenew));
596
+ const renewAgent = await fetchJson(`${renewHost.baseUrl}/api/remote/agent/status`);
597
+ assert.equal(renewAgent.payload?.running, false, JSON.stringify(renewAgent.payload));
598
+
599
+ const renewClear = await fetchJson(`${renewHost.baseUrl}/api/remote/host-target`, {
600
+ method: 'DELETE',
601
+ token: BRIDGE_TOKEN,
602
+ body: JSON.stringify({
603
+ nodeId: 'remote-registry-renew-node'
604
+ })
605
+ });
606
+ assert.equal(renewClear.ok, true, JSON.stringify(renewClear.payload));
607
+ assert.equal(renewClear.payload?.ok, true, JSON.stringify(renewClear.payload));
608
+ await renewHost.stop();
609
+ renewHost = null;
610
+
611
+ currentTarget = createRegistryTarget({
612
+ endpoint: hostAEndpoint,
613
+ endpointCandidates: [staleEndpoint, hostAEndpoint],
614
+ leaseId: 'lease-a'
615
+ });
616
+
617
+ hostA = spawnBridge({
618
+ bridgePort: hostABridgePort,
619
+ remoteHubPort: hostARemotePort,
620
+ workspacePath: path.join(tempRoot, 'host-a'),
621
+ authRoot: hostAAuth,
622
+ label: 'host-a'
623
+ });
624
+ hostB = spawnBridge({
625
+ bridgePort: hostBBridgePort,
626
+ remoteHubPort: hostBRemotePort,
627
+ workspacePath: path.join(tempRoot, 'host-b'),
628
+ authRoot: hostBAuth,
629
+ label: 'host-b'
630
+ });
631
+ await waitForBridge(hostA);
632
+ await waitForBridge(hostB);
633
+
634
+ client = spawnBridge({
635
+ bridgePort: clientBridgePort,
636
+ remoteHubPort: clientRemotePort,
637
+ workspacePath: path.join(tempRoot, 'client'),
638
+ authRoot: clientAuth,
639
+ label: 'client',
640
+ supabaseUrl: fakeSupabase.url,
641
+ follower: true
642
+ });
643
+ await waitForBridge(client);
644
+
645
+ const firstAgent = await waitForManagedAgent(client, hostAEndpoint, 'host-a');
646
+ assert.equal(firstAgent.usingNpx, false, JSON.stringify(firstAgent));
647
+ assert.match(String(firstAgent.launcher || ''), /mindexec-remote-fast/i);
648
+ assert.equal(firstAgent.manager, hostAEndpoint);
649
+ assert.equal(firstAgent.managerCandidates?.[0], hostAEndpoint, JSON.stringify(firstAgent.managerCandidates));
650
+ assert.equal(firstAgent.managerCandidates?.length, 1, JSON.stringify(firstAgent.managerCandidates));
651
+ assert.ok(
652
+ fakeSupabase.requests.some(request =>
653
+ request.method === 'POST'
654
+ && request.pathname === '/auth/v1/token'),
655
+ 'expected LocalBridge to refresh expired persisted Supabase session without browser involvement');
656
+ assert.ok(
657
+ fakeSupabase.requests.some(request =>
658
+ request.method === 'GET'
659
+ && request.pathname === '/rest/v1/remote_host_targets'
660
+ && request.authorization === `Bearer ${REFRESHED_ACCESS_TOKEN}`),
661
+ 'expected registry read to use refreshed access token');
662
+ await waitForConnectedDevice(hostA, 'host-a');
663
+ const firstStatus = await fetchJson(`${client.baseUrl}/api/status`);
664
+ assert.equal(firstStatus.payload?.remoteRegistryRealtime?.subscribed, true, JSON.stringify(firstStatus.payload?.remoteRegistryRealtime));
665
+ assert.ok(fakeSupabase.realtimeClients.size >= 1, 'expected LocalBridge realtime watcher to connect');
666
+ const firstPid = Number(firstAgent.pid || 0);
667
+ assert.ok(firstPid > 0, JSON.stringify(firstAgent));
668
+
669
+ const clientResume = await fetchJson(`${client.baseUrl}/api/remote/system/resume`, {
670
+ method: 'POST',
671
+ token: BRIDGE_TOKEN,
672
+ body: JSON.stringify({
673
+ driftMs: 65000
674
+ })
675
+ });
676
+ assert.equal(clientResume.ok, true, JSON.stringify(clientResume.payload));
677
+ assert.equal(clientResume.payload?.ok, true, JSON.stringify(clientResume.payload));
678
+ assert.equal(clientResume.payload?.remoteSystemResume?.registryAgentRestarted, true, JSON.stringify(clientResume.payload?.remoteSystemResume));
679
+ const resumedAgent = await waitForManagedAgentRestart(client, hostAEndpoint, firstPid, 'host-a after resume', 12000);
680
+ assert.equal(resumedAgent.usingNpx, false, JSON.stringify(resumedAgent));
681
+ assert.match(String(resumedAgent.launcher || ''), /mindexec-remote-fast/i);
682
+ assert.equal(resumedAgent.leaseId, 'lease-a');
683
+ await waitForConnectedDevice(hostA, 'host-a after resume');
684
+
685
+ currentTarget = createRegistryTarget({
686
+ endpoint: hostBEndpoint,
687
+ endpointCandidates: [hostBEndpoint],
688
+ leaseId: 'lease-b'
689
+ });
690
+ fakeSupabase.broadcastChange('UPDATE');
691
+
692
+ const secondAgent = await waitForManagedAgent(client, hostBEndpoint, 'host-b', 9000);
693
+ assert.equal(secondAgent.usingNpx, false, JSON.stringify(secondAgent));
694
+ assert.match(String(secondAgent.launcher || ''), /mindexec-remote-fast/i);
695
+ assert.equal(secondAgent.manager, hostBEndpoint);
696
+ assert.equal(secondAgent.leaseId, 'lease-b');
697
+ await waitForConnectedDevice(hostB, 'host-b');
698
+
699
+ await wait(250);
700
+ currentTarget = null;
701
+ fakeSupabase.broadcastChange('DELETE');
702
+ await waitFor(async () => {
703
+ const status = await fetchJson(`${client.baseUrl}/api/status`);
704
+ const agent = await fetchJson(`${client.baseUrl}/api/remote/agent/status`);
705
+ return status.payload?.remoteRegistryFollower?.reason === 'no-active-target-agent-kept'
706
+ && agent.payload?.running === true
707
+ && String(agent.payload?.manager || '') === hostBEndpoint
708
+ ? { status: status.payload.remoteRegistryFollower, agent: agent.payload }
709
+ : null;
710
+ }, 4000, `transient no-active-target keeps managed agent\n${client.details()}`);
711
+
712
+ currentTarget = createRegistryTarget({
713
+ endpoint: hostBEndpoint,
714
+ endpointCandidates: [hostBEndpoint],
715
+ leaseId: 'lease-b'
716
+ });
717
+ fakeSupabase.broadcastChange('INSERT');
718
+ const restoredAgent = await waitForManagedAgent(client, hostBEndpoint, 'host-b after transient missing target', 9000);
719
+ assert.equal(Number(restoredAgent.pid || 0), Number(secondAgent.pid || 0), JSON.stringify(restoredAgent));
720
+
721
+ const missingAuthWake = await fetchJson(`${client.baseUrl}/api/auth/session`, {
722
+ method: 'DELETE',
723
+ token: BRIDGE_TOKEN
724
+ });
725
+ assert.equal(missingAuthWake.ok, true, JSON.stringify(missingAuthWake.payload));
726
+ await waitFor(async () => {
727
+ const status = await fetchJson(`${client.baseUrl}/api/status`);
728
+ const agent = await fetchJson(`${client.baseUrl}/api/remote/agent/status`);
729
+ return status.payload?.remoteRegistryFollower?.reason === 'registry-not-authenticated-agent-kept'
730
+ && status.payload?.remoteRegistryFollower?.agentKept === true
731
+ && agent.payload?.running === true
732
+ && String(agent.payload?.manager || '') === hostBEndpoint
733
+ && Number(agent.payload?.pid || 0) === Number(secondAgent.pid || 0)
734
+ ? { status: status.payload.remoteRegistryFollower, agent: agent.payload }
735
+ : null;
736
+ }, 4000, `transient missing auth keeps managed agent\n${client.details()}`);
737
+
738
+ const restoredAuthWake = await fetchJson(`${client.baseUrl}/api/auth/session`, {
739
+ method: 'POST',
740
+ token: BRIDGE_TOKEN,
741
+ body: JSON.stringify({
742
+ content: createSessionPayload()
743
+ })
744
+ });
745
+ assert.equal(restoredAuthWake.ok, true, JSON.stringify(restoredAuthWake.payload));
746
+ const authRestoredAgent = await waitForManagedAgent(client, hostBEndpoint, 'host-b after transient missing auth', 9000);
747
+ assert.equal(Number(authRestoredAgent.pid || 0), Number(secondAgent.pid || 0), JSON.stringify(authRestoredAgent));
748
+
749
+ const secondPid = Number(secondAgent.pid || 0);
750
+ killProcess(secondPid);
751
+ const restartedAgent = await waitForManagedAgentRestart(client, hostBEndpoint, secondPid, 'host-b', 12000);
752
+ assert.equal(restartedAgent.usingNpx, false, JSON.stringify(restartedAgent));
753
+ assert.match(String(restartedAgent.launcher || ''), /mindexec-remote-fast/i);
754
+ assert.equal(restartedAgent.leaseId, 'lease-b');
755
+ await waitForConnectedDevice(hostB, 'host-b after restart');
756
+
757
+ currentTarget = {
758
+ ...currentTarget,
759
+ active: false,
760
+ expires_at: new Date(Date.now() - 1000).toISOString()
761
+ };
762
+ fakeSupabase.broadcastChange('UPDATE');
763
+ await wait(700);
764
+ fakeSupabase.broadcastChange('UPDATE');
765
+
766
+ await waitFor(async () => {
767
+ const status = await fetchJson(`${client.baseUrl}/api/status`);
768
+ const agent = await fetchJson(`${client.baseUrl}/api/remote/agent/status`);
769
+ return status.payload?.remoteRegistryFollower?.reason === 'registry-inactive-agent-kept'
770
+ && status.payload?.remoteRegistryFollower?.agentKept === true
771
+ && status.payload?.remoteRegistryFollower?.dataPlaneReady === true
772
+ && agent.payload?.running === true
773
+ && agent.payload?.ready === true
774
+ && String(agent.payload?.manager || '') === hostBEndpoint
775
+ && Number(agent.payload?.pid || 0) === Number(restartedAgent.pid || 0)
776
+ ? { status: status.payload.remoteRegistryFollower, agent: agent.payload }
777
+ : null;
778
+ }, 9000, `registry inactive keeps ready data-plane agent\n${client.details()}`);
779
+
780
+ const inactivePid = Number(restartedAgent.pid || 0);
781
+ killProcess(inactivePid);
782
+ const recoveredInactiveAgent = await waitForManagedAgentRestart(
783
+ client,
784
+ hostBEndpoint,
785
+ inactivePid,
786
+ 'host-b after inactive target recovery',
787
+ 12000);
788
+ assert.equal(recoveredInactiveAgent.usingNpx, false, JSON.stringify(recoveredInactiveAgent));
789
+ assert.match(String(recoveredInactiveAgent.launcher || ''), /mindexec-remote-fast/i);
790
+ assert.equal(recoveredInactiveAgent.leaseId, 'lease-b');
791
+ await waitForConnectedDevice(hostB, 'host-b after inactive target recovery');
792
+ await waitFor(async () => {
793
+ const status = await fetchJson(`${client.baseUrl}/api/status`);
794
+ return status.payload?.remoteRegistryFollower?.reason === 'registry-inactive-agent-recovered'
795
+ && String(status.payload?.remoteRegistryFollower?.targetEndpoint || '') === hostBEndpoint
796
+ ? status.payload.remoteRegistryFollower
797
+ : null;
798
+ }, 4000, `inactive target recovered managed agent\n${client.details()}`);
799
+ const finalStatus = await fetchJson(`${client.baseUrl}/api/status`);
800
+ assert.ok(finalStatus.payload?.remoteRegistryRealtime?.changes >= 2, JSON.stringify(finalStatus.payload?.remoteRegistryRealtime));
801
+ assert.ok(finalStatus.payload?.remoteRegistryRealtime?.wakeups >= 2, JSON.stringify(finalStatus.payload?.remoteRegistryRealtime));
802
+
803
+ assert.ok(fakeSupabase.requests.length >= 2, JSON.stringify(fakeSupabase.requests));
804
+ console.log('Remote registry follower smoke OK');
805
+ } finally {
806
+ if (client) await client.stop();
807
+ if (hostB) await hostB.stop();
808
+ if (hostA) await hostA.stop();
809
+ if (renewHost) await renewHost.stop();
810
+ if (fakeSupabase) await fakeSupabase.stop();
811
+ await rm(tempRoot, { recursive: true, force: true });
812
+ }
813
+ }
814
+
815
+ await main();