@yuriai/web 0.2.40-beta.5 → 0.2.40-beta.7
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.
- package/dist/assets/{AgentAvatar-B7KbxN8Y.js → AgentAvatar-BTLQDhXH.js} +1 -1
- package/dist/assets/AssistantConversationSurface-B59k-lXE.css +1 -0
- package/dist/assets/AssistantConversationSurface-CMMUXPIG.js +3 -0
- package/dist/assets/AssistantSessionCard-CZWiX3PR.js +2 -0
- package/dist/assets/{AssistantUnreadBadge-vu4ZhTft.js → AssistantUnreadBadge-B5I8avUG.js} +1 -1
- package/dist/assets/{AssistantView-CEfEWUIr.js → AssistantView-COHkH9qm.js} +1 -1
- package/dist/assets/{DiagramView-Dlzr08J_.js → DiagramView-DiwpnazQ.js} +1 -1
- package/dist/assets/{FadeInOnReveal-DMRmNsau.js → FadeInOnReveal-BxelcK76.js} +1 -1
- package/dist/assets/{GuiPluginPage-DVug4z_p.js → GuiPluginPage-CLD3qMom.js} +1 -1
- package/dist/assets/{GuiPluginSurface-L43o6Xv8.js → GuiPluginSurface-Cra2RdI2.js} +1 -1
- package/dist/assets/{GuiPluginWindow-tHXkS18H.js → GuiPluginWindow-CX4PYIEy.js} +1 -1
- package/dist/assets/{Icon-DizeYahT.js → Icon-BN1Zz-it.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-BZC5m_km.js → ImageLoadingPlaceholder-CZFYt1Xf.js} +1 -1
- package/dist/assets/{LoadingImage-Csw4L-Dr.js → LoadingImage-BCMztEsC.js} +1 -1
- package/dist/assets/{MarkdownRenderer-D_0iKhQN.js → MarkdownRenderer-194nc-0S.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-BZ0XgjS0.js → MarkdownRendererImpl-0-mJL1TL.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-DBd6Glg9.js → MarkstreamRendererImpl-DaTyfTOH.js} +1 -1
- package/dist/assets/MobileDetailNavigation-CXAtNLak.js +1 -0
- package/dist/assets/{MobileResizableSheet-CQQ7O-2X.js → MobileResizableSheet-BvwMTE7L.js} +1 -1
- package/dist/assets/{MobileShareBridge-IO45gM2G.js → MobileShareBridge-BpO-ZEFG.js} +1 -1
- package/dist/assets/MobileSurface-DIhzZpb9.js +2 -0
- package/dist/assets/{MultiRunWindow-fJ3XfntS.js → MultiRunWindow-ErbLasVC.js} +1 -1
- package/dist/assets/{OnboardingScreen-MJS5T5rL.js → OnboardingScreen-C_rigW9c.js} +1 -1
- package/dist/assets/{OverlayScrollbar-jtMYTn1y.js → OverlayScrollbar-BopzmDhe.js} +1 -1
- package/dist/assets/RemoteAssistantSessionCard-6ktwRL7R.js +1 -0
- package/dist/assets/{SettingsView-ZWFLpPSI.js → SettingsView--qdcJENp.js} +10 -10
- package/dist/assets/{SettingsWindow-DGRmrIWz.js → SettingsWindow-BbJoqFSB.js} +1 -1
- package/dist/assets/{SetupTourDialog-BYbAubwA.js → SetupTourDialog-CT3NmpEw.js} +1 -1
- package/dist/assets/{TerminalView-CoJ6_9P1.js → TerminalView-Cw-p34fv.js} +1 -1
- package/dist/assets/{ToolOutputDialog-5xBwOJ6a.js → ToolOutputDialog-Bph7Tjg_.js} +1 -1
- package/dist/assets/{VoiceSettings-CN33koSc.js → VoiceSettings-B8jYVsYS.js} +2 -2
- package/dist/assets/{YuriLogo-CvyJy_R9.js → YuriLogo-VXtP1vhh.js} +1 -1
- package/dist/assets/{YuriWordmark-DnFAS-Ko.js → YuriWordmark-B7lmpLRB.js} +1 -1
- package/dist/assets/{capgoAdapter-CCLtBZL1.js → capgoAdapter-BQCbf31K.js} +1 -1
- package/dist/assets/{checkbox-rOV6DjeG.js → checkbox-q45nTdJl.js} +1 -1
- package/dist/assets/{client-uz8O6TPX.js → client-1Fk5IbQR.js} +3 -3
- package/dist/assets/{collapsible-CKswuqAw.js → collapsible-GtMRfwfw.js} +1 -1
- package/dist/assets/{context-menu-B4njwT_M.js → context-menu-efudajQ5.js} +1 -1
- package/dist/assets/{diagram-BppQ_USn.js → diagram-D39tZKkF.js} +1 -1
- package/dist/assets/{dialog-Bg8MJnOV.js → dialog-BtnUw5J1.js} +1 -1
- package/dist/assets/{es-Ba3NUCtE.js → es-DuTK1iYh.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-D-AdTJVr.js → fileMentionTouchSelection-CJ78x95X.js} +1 -1
- package/dist/assets/{fr-CRhp3hyT.js → fr-C_XToFWm.js} +1 -1
- package/dist/assets/{gitApi-DVx_V1x6.js → gitApi-CBnJOeVr.js} +1 -1
- package/dist/assets/gitApiHttp-B0FJaIhU.js +3 -0
- package/dist/assets/{gui-DN2sVP96.js → gui-BMN3-WPc.js} +1 -1
- package/dist/assets/{host-DrGjjO6K.js → host-D9EDWNmx.js} +1 -1
- package/dist/assets/{i18n-RH7UieOS.js → i18n-qHllte6P.js} +1 -1
- package/dist/assets/{input-DRjuZMeA.js → input-KETIwVja.js} +1 -1
- package/dist/assets/{input-store-CjUOfpyA.js → input-store-CsY-uaSj.js} +1 -1
- package/dist/assets/insertionBoundaries-CodoJFbE.js +1 -0
- package/dist/assets/{ja-D-UPjDY2.js → ja-D0pDybpB.js} +1 -1
- package/dist/assets/{ko-x-z9J5z7.js → ko-CAzlaaDJ.js} +1 -1
- package/dist/assets/main-Cgg4eDdr.js +2 -0
- package/dist/assets/{main-D2s9J_jN.js → main-D4t2Tw1D.js} +14 -14
- package/dist/assets/{markdownHeightCache-BL99DlhC.js → markdownHeightCache-BCzMmJds.js} +1 -1
- package/dist/assets/{mcpQueries-HzYMEVWd.js → mcpQueries-BIvH9V8j.js} +1 -1
- package/dist/assets/miniChat-CKw0itTX.js +2 -0
- package/dist/assets/mobile-w1JspRFK.js +2 -0
- package/dist/assets/{mobileBackNavigation--ZdrI-Yj.js → mobileBackNavigation-qI9CYpqm.js} +1 -1
- package/dist/assets/{mobileConnections-C3eGEOPy.js → mobileConnections-Cbt8y7gt.js} +2 -2
- package/dist/assets/{multirun-CDYNyLBH.js → multirun-DOmwPpvA.js} +1 -1
- package/dist/assets/{native-DsqzO52u.js → native-CDqNKjmz.js} +1 -1
- package/dist/assets/{native-config-DOawZfln.js → native-config-BIePc5av.js} +1 -1
- package/dist/assets/{navigation-Ibk_Pw-q.js → navigation-CxKtO3Tu.js} +2 -2
- package/dist/assets/openRemoteProjectSession-DbQYpcai.js +1 -0
- package/dist/assets/{pl-Cqo1FJwM.js → pl-BvjbUcJV.js} +1 -1
- package/dist/assets/{projectMeta-D1Ytss9U.js → projectMeta-AxnyOG6N.js} +1 -1
- package/dist/assets/prompt-attachment-upload-9fjmgafL.js +1 -0
- package/dist/assets/{pt-BR-C930XU1k.js → pt-BR-D71qrP91.js} +1 -1
- package/dist/assets/{pwa-CXupOTsD.js → pwa-BGo_AGpg.js} +1 -1
- package/dist/assets/{queue-abort-optimistic-CQXpIlq6.js → queue-abort-optimistic-CZ3DN-Qo.js} +1 -1
- package/dist/assets/{react-CgRToPwO.js → react-CTU-HLp4.js} +1 -1
- package/dist/assets/{readiness-BfuZm6Yw.js → readiness-Bu7mTG2d.js} +2 -2
- package/dist/assets/reference-history-n4Bw_yN2.js +1 -0
- package/dist/assets/{remote-input-store-BOdCWpQY.js → remote-input-store-84i8uDyM.js} +1 -1
- package/dist/assets/remoteProjectQueries-BZjiHj-6.js +1 -0
- package/dist/assets/remoteSessionReference-CQ0m6LgV.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-B8nOPC1J.js +2 -0
- package/dist/assets/renderMobileApp-BvamjumJ.js +29 -0
- package/dist/assets/{runtimeConfig-tHm7o_0I.js → runtimeConfig-CbHzjd7l.js} +1 -1
- package/dist/assets/runtimeEndpointReset-CMyx_9Vr.js +151 -0
- package/dist/assets/scheduledTaskNavigation-y5g8D2ee.js +1 -0
- package/dist/assets/{select-B1On-Y4Z.js → select-Df_svQ9u.js} +1 -1
- package/dist/assets/sessionLookup-BN82Y0hu.js +1 -0
- package/dist/assets/{sortable-tabs-strip-nD1Me06z.js → sortable-tabs-strip-ByO3KYNT.js} +1 -1
- package/dist/assets/{speechSettingsQueries-BYhNpzDJ.js → speechSettingsQueries-DRAueMIJ.js} +1 -1
- package/dist/assets/src-INJJ62RE.css +2 -0
- package/dist/assets/{store-DunGyOfe.js → store-BOD3jjMl.js} +3 -3
- package/dist/assets/{terminalApi-madXrfqA.js → terminalApi-Cq0vjFe1.js} +1 -1
- package/dist/assets/{textarea-Qt06OhhX.js → textarea-BYUo-pZK.js} +1 -1
- package/dist/assets/{tooltip-D382RCy1.js → tooltip-CBCE3mxe.js} +1 -1
- package/dist/assets/tour-CMXP3Kif.js +1 -0
- package/dist/assets/{types-CHszLAS3.js → types-Bj4r_-Qe.js} +1 -1
- package/dist/assets/{uk-OXQSdzuT.js → uk-C7c1Zece.js} +1 -1
- package/dist/assets/{useAppFontEffects-CqXrCJVt.js → useAppFontEffects-DxY0a-0K.js} +61 -61
- package/dist/assets/useDesktopWindowControlsLayout-I02la7LE.js +1 -0
- package/dist/assets/{useDictation-Bs7TWO9r.js → useDictation-De8WB_Z7.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-CCKRdyK9.js → useEffectiveDirectory-CYzFju6z.js} +1 -1
- package/dist/assets/{useFontPreferences-CPrl1_3z.js → useFontPreferences-CO-L-Gd7.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-BNtVrnSw.js → useMobileNavigationStore-7nhBtrXS.js} +9 -9
- package/dist/assets/{usePluginsStore-bMuGciUE.js → usePluginsStore-1D6-GAgq.js} +1 -1
- package/dist/assets/{useProjectRuntimeAPIs-BFCXBu2J.js → useProjectRuntimeAPIs-CNOqSvoZ.js} +1 -1
- package/dist/assets/{useStreamingTextThrottle-C8xAqcgP.js → useStreamingTextThrottle-BsaiiBxk.js} +1 -1
- package/dist/assets/{vendor-opencode-client-cQ47ywrT.js → vendor-opencode-client-BM2r1f0o.js} +3 -3
- package/dist/assets/{vendor-opencode-plugin-BmdTE4Te.js → vendor-opencode-plugin-ZhpPgHCL.js} +1 -1
- package/dist/assets/{vendor-solid-js-D98iXT7C.js → vendor-solid-js-BBVUd3Hw.js} +1 -1
- package/dist/assets/{zh-CN-B5X8yCZV.js → zh-CN-D2ENuI1-.js} +1 -1
- package/dist/assets/{zh-TW-CF6zr1fk.js → zh-TW-C40BXFhK.js} +1 -1
- package/dist/index.html +11 -11
- package/dist/mini-chat.html +11 -11
- package/dist/mobile.html +2 -2
- package/package.json +1 -1
- package/server/index.js +1 -0
- package/server/lib/assistants/DOCUMENTATION.md +87 -0
- package/server/lib/assistants/assign.js +10 -7
- package/server/lib/assistants/builtin-skills.js +1 -0
- package/server/lib/assistants/builtin-skills.test.js +1 -1
- package/server/lib/assistants/cards.js +6 -1
- package/server/lib/assistants/contact-store.js +22 -5
- package/server/lib/assistants/contact-tools.js +46 -26
- package/server/lib/assistants/execution-target.js +136 -0
- package/server/lib/assistants/opencode-tools.js +22 -9
- package/server/lib/assistants/remote-execution.test.js +378 -0
- package/server/lib/assistants/remote-watch-reconciler.js +43 -0
- package/server/lib/assistants/remote-watch-reconciler.test.js +88 -0
- package/server/lib/assistants/routes.js +1 -0
- package/server/lib/assistants/service.js +302 -99
- package/server/lib/assistants/yuri-project.http.test.js +2 -2
- package/server/lib/gui-customization/DOCUMENTATION.md +8 -2
- package/server/lib/gui-customization/projects-client.mjs +10 -8
- package/server/lib/gui-customization/projects-remote.js +101 -0
- package/server/lib/gui-customization/projects-remote.test.js +125 -0
- package/server/lib/gui-customization/projects.js +30 -6
- package/server/lib/gui-customization/projects.test.js +66 -1
- package/server/lib/gui-customization/session-skill.js +2 -2
- package/server/lib/gui-customization/session-skill.test.js +4 -0
- package/server/lib/gui-customization/skill/SKILL.md +3 -1
- package/server/lib/gui-customization/skill/references/projects.md +30 -3
- package/server/lib/gui-customization/skill/references/remote-connections.md +2 -0
- package/server/lib/opencode/DOCUMENTATION.md +6 -0
- package/server/lib/opencode/feature-routes-runtime.js +2 -0
- package/server/lib/opencode/v2-client.js +9 -4
- package/server/lib/remote-hosts/DOCUMENTATION.md +58 -0
- package/server/lib/remote-hosts/gateway.js +149 -40
- package/server/lib/remote-hosts/json-lifecycle.test.js +35 -0
- package/server/lib/remote-hosts/routes.js +10 -13
- package/server/lib/remote-hosts/routes.test.js +302 -1
- package/server/lib/remote-hosts/store.js +17 -3
- package/server/lib/remote-hosts/store.test.js +19 -0
- package/server/lib/remote-hosts/task-client.js +25 -0
- package/server/lib/remote-hosts/task-client.test.js +60 -0
- package/server/lib/remote-hosts/transport.js +7 -2
- package/server/lib/request-cors.js +1 -1
- package/server/lib/request-cors.test.js +1 -0
- package/server/lib/scheduled-tasks/session-skill.test.js +33 -2
- package/dist/assets/AssistantConversationSurface-BnK_KTBO.js +0 -3
- package/dist/assets/AssistantConversationSurface-n9w_Av0k.css +0 -1
- package/dist/assets/MobileDetailNavigation-xgwvsQuR.js +0 -1
- package/dist/assets/MobileSurface-DmYgZONB.js +0 -2
- package/dist/assets/gitApiHttp-DvTBxvX8.js +0 -3
- package/dist/assets/insertionBoundaries-DZtQt2Ah.js +0 -1
- package/dist/assets/main-BMFY9mtb.js +0 -2
- package/dist/assets/miniChat-BbJ0GKpk.js +0 -2
- package/dist/assets/mobile-_zUth69Z.js +0 -2
- package/dist/assets/prompt-attachment-upload-BNhDXymd.js +0 -1
- package/dist/assets/remoteProjectQueries-CkxdZNw4.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-pJ59iC34.js +0 -2
- package/dist/assets/renderMobileApp-BQFC-gOA.js +0 -29
- package/dist/assets/runtimeEndpointReset-BhHWFNvo.js +0 -150
- package/dist/assets/scheduledTaskNavigation-BIDtQ4wN.js +0 -1
- package/dist/assets/sessionLookup-RcyTTDOy.js +0 -1
- package/dist/assets/src-BZCFf9_1.css +0 -2
- package/dist/assets/tour-CQMBn8gJ.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-KH4UP7Gj.js +0 -1
- /package/dist/assets/{sessionLookup-8C8nv-EP.css → reference-history-8C8nv-EP.css} +0 -0
|
@@ -25,6 +25,7 @@ import { registerFsRoutes } from '../fs/routes.js';
|
|
|
25
25
|
import { createTerminalRuntime } from '../terminal/runtime.js';
|
|
26
26
|
import { readTerminalWsControlFrame, createTerminalWsControlFrame } from '../terminal/terminal-ws-protocol.js';
|
|
27
27
|
import { createTranscriptCacheService } from '../transcript-cache/service.js';
|
|
28
|
+
import { runRemoteProjectOperation } from '../gui-customization/projects-remote.js';
|
|
28
29
|
|
|
29
30
|
const require = createRequire(import.meta.url);
|
|
30
31
|
const disposers = [];
|
|
@@ -182,6 +183,186 @@ async function aggregate(options = {}) {
|
|
|
182
183
|
}
|
|
183
184
|
|
|
184
185
|
describe('Remote Host production HTTP contract', () => {
|
|
186
|
+
it('forwards metadata writes with their directory and patch, but rejects other methods and stale targets', async () => {
|
|
187
|
+
const { hub, remote } = await aggregate();
|
|
188
|
+
const writes = [];
|
|
189
|
+
remote.app.put('/api/yuri/sessions/:id/metadata', express.json(), (req, res) => {
|
|
190
|
+
writes.push({ id: req.params.id, body: req.body });
|
|
191
|
+
res.json({ metadata: req.body.patch });
|
|
192
|
+
});
|
|
193
|
+
const route = '/api/hosts/remote-1/api/yuri/sessions/same-id/metadata';
|
|
194
|
+
const body = { directory: '/same/path', patch: { yuri: { label: 'metadata' } } };
|
|
195
|
+
const response = await hub.call(route, 'PUT', body);
|
|
196
|
+
expect(response.status).toBe(200);
|
|
197
|
+
expect(await response.json()).toEqual({ metadata: body.patch });
|
|
198
|
+
expect(writes).toEqual([{ id: 'same-id', body }]);
|
|
199
|
+
expect((await hub.call(route, 'POST', body)).status).toBe(403);
|
|
200
|
+
expect((await fetch(`${hub.url}${route}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).status).toBe(401);
|
|
201
|
+
const rejected = await fetch(`${hub.url}${route}`, { method: 'PUT', headers: { ...hub.headers, 'x-yuri-target-instance': 'other-instance' }, body: JSON.stringify(body) });
|
|
202
|
+
expect(rejected.status).toBe(409);
|
|
203
|
+
expect(writes).toHaveLength(1);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it('routes deletion to the target Host without deleting the same-ID Hub session', async () => {
|
|
207
|
+
const { hub, remote } = await aggregate();
|
|
208
|
+
const remoteDelete = vi.fn((req, res) => res.json({ deleted: req.params.id }));
|
|
209
|
+
const localDelete = vi.fn((_req, res) => res.status(500).json({ error: 'Must not delete locally' }));
|
|
210
|
+
remote.app.delete('/api/session/:id', remoteDelete);
|
|
211
|
+
hub.app.delete('/api/session/:id', localDelete);
|
|
212
|
+
const response = await hub.call('/api/hosts/remote-1/api/session/same-id', 'DELETE');
|
|
213
|
+
expect(response.status).toBe(200);
|
|
214
|
+
expect(await response.json()).toEqual({ deleted: 'same-id' });
|
|
215
|
+
expect(remoteDelete).toHaveBeenCalledOnce();
|
|
216
|
+
expect(localDelete).not.toHaveBeenCalled();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('forwards archive and unarchive only to the authenticated target Host', async () => {
|
|
220
|
+
const { hub, remote } = await aggregate();
|
|
221
|
+
const received = [];
|
|
222
|
+
remote.app.put('/api/yuri/sessions/:id/archive', express.json(), (req, res) => {
|
|
223
|
+
received.push({ id: req.params.id, body: req.body });
|
|
224
|
+
res.json({ session: { id: req.params.id, time: { archived: req.body.archivedAt } } });
|
|
225
|
+
});
|
|
226
|
+
for (const archivedAt of [123, 0]) {
|
|
227
|
+
const response = await hub.call('/api/hosts/remote-1/api/yuri/sessions/session-1/archive', 'PUT', { directory: '/same/path', archivedAt });
|
|
228
|
+
expect(response.status).toBe(200);
|
|
229
|
+
expect(await response.json()).toMatchObject({ session: { id: 'session-1', time: { archived: archivedAt } } });
|
|
230
|
+
}
|
|
231
|
+
expect(received).toEqual([123, 0].map((archivedAt) => ({ id: 'session-1', body: { directory: '/same/path', archivedAt } })));
|
|
232
|
+
for (const [route, method] of [['sessions/session-1/archive', 'POST'], ['sessions/session-1/unknown', 'PUT']]) {
|
|
233
|
+
expect((await hub.call(`/api/hosts/remote-1/api/yuri/${route}`, method, {})).status).toBe(403);
|
|
234
|
+
}
|
|
235
|
+
expect(received).toHaveLength(2);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it('rejects a connection retarget before reading or mutating the replacement authority', async () => {
|
|
239
|
+
const { hub, remote, setHosts } = await aggregate();
|
|
240
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
241
|
+
expect(hub.store.projects()[0].instanceId).toBe(remote.store.hubId);
|
|
242
|
+
const replacement = await host();
|
|
243
|
+
setHosts([{ id: 'remote-1', source: 'direct', apiUrl: replacement.url, clientToken: replacement.issued.token }]);
|
|
244
|
+
const response = await hub.call('/api/hosts/remote-1/api/session/same-id/message', 'POST', { text: 'do not send' });
|
|
245
|
+
expect(response.status).toBe(409);
|
|
246
|
+
expect(await response.json()).toMatchObject({ code: 'remote_instance_mismatch' });
|
|
247
|
+
expect(replacement.messageHeaders).toBeUndefined();
|
|
248
|
+
expect(hub.store.projects()[0].instanceId).toBe(remote.store.hubId);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('checks an explicit target authority without forwarding the Hub-only marker', async () => {
|
|
252
|
+
const { hub, remote } = await aggregate();
|
|
253
|
+
const route = `${hub.url}/api/hosts/remote-1/api/session/same-id/message`;
|
|
254
|
+
const send = (instanceId) => fetch(route, { method: 'POST', headers: { ...hub.headers, 'x-yuri-target-instance': instanceId }, body: '{}' });
|
|
255
|
+
expect((await send('other-instance')).status).toBe(409);
|
|
256
|
+
expect(remote.messageHeaders).toBeUndefined();
|
|
257
|
+
expect((await send(remote.store.hubId)).status).toBe(200);
|
|
258
|
+
expect(remote.messageHeaders['x-yuri-target-instance']).toBeUndefined();
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it('retains only the task host status stream without a UI and releases it on completion', async () => {
|
|
262
|
+
const { hub, remote, setHosts } = await aggregate();
|
|
263
|
+
const other = await host();
|
|
264
|
+
setHosts([
|
|
265
|
+
{ id: 'remote-1', source: 'direct', apiUrl: remote.url, clientToken: remote.issued.token },
|
|
266
|
+
{ id: 'remote-2', source: 'direct', apiUrl: other.url, clientToken: other.issued.token },
|
|
267
|
+
]);
|
|
268
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
269
|
+
await hub.call('/api/hosts/remote-2/projects', 'POST', { path: '/same/path' });
|
|
270
|
+
const onEvent = vi.fn();
|
|
271
|
+
const lease = await hub.gateway.acquireTask('remote-1', { instanceId: remote.store.hubId, onEvent });
|
|
272
|
+
expect(lease.target).toEqual({ hubId: hub.store.hubId, hostId: 'remote-1', instanceId: remote.store.hubId });
|
|
273
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
274
|
+
expect(hub.liveClients).toBe(0);
|
|
275
|
+
expect(other.statusStreams).toBe(0);
|
|
276
|
+
expect(other.indexRequests).toBe(0);
|
|
277
|
+
const uiAbort = new AbortController();
|
|
278
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: uiAbort.signal });
|
|
279
|
+
await wait(() => expect(other.statusStreams).toBe(1));
|
|
280
|
+
uiAbort.abort(); await stream.body.cancel().catch(() => {});
|
|
281
|
+
await wait(() => expect(other.statusStreams).toBe(0));
|
|
282
|
+
expect(remote.statusStreams).toBe(1);
|
|
283
|
+
remote.emit({ type: 'session.execution.succeeded', data: { sessionID: 'same-id', directory: '/same/path' } });
|
|
284
|
+
await wait(() => expect(onEvent.mock.calls.some(([event]) => event.payload.type === 'session.execution.succeeded')).toBe(true));
|
|
285
|
+
remote.emit({ type: 'session.execution.interrupted', data: { sessionID: 'same-id', directory: '/same/path', reason: 'user',
|
|
286
|
+
error: { name: 'MessageAbortedError', message: 'private error body', stack: 'private stack' } } });
|
|
287
|
+
await wait(() => expect(onEvent.mock.calls.some(([event]) => event.payload.type === 'session.execution.interrupted')).toBe(true));
|
|
288
|
+
const interrupted = onEvent.mock.calls.find(([event]) => event.payload.type === 'session.execution.interrupted')[0];
|
|
289
|
+
expect(interrupted.payload.data).toEqual({ sessionID: 'same-id', directory: '/same/path', reason: 'user', error: { name: 'MessageAbortedError' } });
|
|
290
|
+
expect(JSON.stringify(interrupted)).not.toContain('private');
|
|
291
|
+
const sibling = await hub.gateway.acquireTask('remote-1', { onEvent: vi.fn() });
|
|
292
|
+
lease.release(); lease.release();
|
|
293
|
+
expect(remote.statusStreams).toBe(1);
|
|
294
|
+
sibling.release();
|
|
295
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
296
|
+
await expect(lease.json('/api/projects')).rejects.toThrow();
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('cancels task reads and rejects stale leases after descriptor revocation', async () => {
|
|
300
|
+
const { hub, remote, setHosts } = await aggregate();
|
|
301
|
+
const abort = new AbortController();
|
|
302
|
+
const lease = await hub.gateway.acquireTask('remote-1', { signal: abort.signal });
|
|
303
|
+
expect(remote.statusStreams).toBe(0);
|
|
304
|
+
expect(await lease.json('/api/projects')).toEqual({ projects: [] });
|
|
305
|
+
let entered;
|
|
306
|
+
const receiving = new Promise((resolve) => { entered = resolve; });
|
|
307
|
+
remote.app.get('/api/session/slow-task', (_req, res) => {
|
|
308
|
+
res.type('application/json').write('{"unfinished":');
|
|
309
|
+
entered();
|
|
310
|
+
});
|
|
311
|
+
const pending = expect(lease.json('/api/session/slow-task')).rejects.toThrow();
|
|
312
|
+
await receiving;
|
|
313
|
+
abort.abort();
|
|
314
|
+
await pending;
|
|
315
|
+
await expect(lease.json('/api/projects')).rejects.toThrow();
|
|
316
|
+
const active = await hub.gateway.acquireTask('remote-1');
|
|
317
|
+
setHosts([]);
|
|
318
|
+
await expect(active.json('/api/projects')).rejects.toMatchObject({ code: 'host_unavailable' });
|
|
319
|
+
active.release();
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
it('closes server task demand before its database on shutdown and tolerates late release', async () => {
|
|
323
|
+
const { hub, remote } = await aggregate();
|
|
324
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
325
|
+
const task = await hub.gateway.acquireTask('remote-1', { onEvent: vi.fn() });
|
|
326
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
327
|
+
hub.gateway.stop();
|
|
328
|
+
task.release();
|
|
329
|
+
hub.gateway.stop();
|
|
330
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
331
|
+
await expect(task.json('/api/projects')).rejects.toThrow();
|
|
332
|
+
await expect(hub.gateway.list()).rejects.toMatchObject({ code: 'host_unavailable' });
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it('delivers task status for authorized sessions without adding Hub project references or indexing them', async () => {
|
|
336
|
+
const { hub, remote } = await aggregate();
|
|
337
|
+
const onEvent = vi.fn();
|
|
338
|
+
const task = await hub.gateway.acquireTask('remote-1', { instanceId: remote.store.hubId, onEvent });
|
|
339
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
340
|
+
expect(hub.store.projects()).toEqual([]);
|
|
341
|
+
remote.emit({ type: 'session.execution.interrupted', data: { sessionID: 'not-in-hub', reason: 'user',
|
|
342
|
+
error: { name: 'MessageAbortedError', message: 'private body' } } });
|
|
343
|
+
await wait(() => expect(onEvent.mock.calls.some(([event]) => event.payload.type === 'session.execution.interrupted')).toBe(true));
|
|
344
|
+
expect(onEvent.mock.calls.find(([event]) => event.payload.type === 'session.execution.interrupted')[0].payload.data)
|
|
345
|
+
.toEqual({ sessionID: 'not-in-hub', reason: 'user', error: { name: 'MessageAbortedError' } });
|
|
346
|
+
expect(hub.store.projects()).toEqual([]);
|
|
347
|
+
expect((await hub.call('/api/hosts/remote-1/summaries')).status).toBe(404);
|
|
348
|
+
expect(remote.indexRequests).toBe(0);
|
|
349
|
+
task.release();
|
|
350
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
it('shares admission and one HTTP status stream across 50 background task leases', async () => {
|
|
354
|
+
const { hub, remote } = await aggregate();
|
|
355
|
+
const tasks = await Promise.all(Array.from({ length: 50 }, () => hub.gateway.acquireTask('remote-1', { onEvent: vi.fn() })));
|
|
356
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
357
|
+
expect(remote.capabilityRequests).toBe(1);
|
|
358
|
+
expect(remote.indexRequests).toBe(0);
|
|
359
|
+
expect(hub.liveClients).toBe(0);
|
|
360
|
+
for (const task of tasks.slice(0, -1)) task.release();
|
|
361
|
+
expect(remote.statusStreams).toBe(1);
|
|
362
|
+
tasks.at(-1).release();
|
|
363
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
364
|
+
});
|
|
365
|
+
|
|
185
366
|
it('forwards worktree dialog GitHub reads and prompt templates without allowing machine mutations', async () => {
|
|
186
367
|
const { hub, remote } = await aggregate();
|
|
187
368
|
const reads = ['/api/github/auth/status', '/api/github/issues/list', '/api/github/pulls/list',
|
|
@@ -685,6 +866,58 @@ describe('Remote Host production HTTP contract', () => {
|
|
|
685
866
|
expect(remote.indexRequests).toBe(0);
|
|
686
867
|
});
|
|
687
868
|
|
|
869
|
+
it('allows an Agent to discover an unassociated machine and add its first project through the same persisted UI authority', async () => {
|
|
870
|
+
const { hub, remote } = await aggregate();
|
|
871
|
+
const discovery = await runRemoteProjectOperation(hub.gateway, 'remote-hosts', {});
|
|
872
|
+
expect(discovery).toMatchObject({ hosts: [{ name: 'Remote', target: { hubId: hub.store.hubId, hostId: 'remote-1', instanceId: remote.store.hubId } }], complete: true });
|
|
873
|
+
expect(hub.store.projects()).toEqual([]);
|
|
874
|
+
const target = discovery.hosts[0].target;
|
|
875
|
+
const tip = vi.fn(); const unsubscribe = hub.broadcast.subscribe(tip);
|
|
876
|
+
try {
|
|
877
|
+
const added = await runRemoteProjectOperation(hub.gateway, 'add-remote', { target, path: '/remote-only/项目 & # 100%', label: 'Remote project' });
|
|
878
|
+
expect(added).toMatchObject({ created: true, target, project: { hostId: 'remote-1', instanceId: target.instanceId, path: '/remote-only/项目 & # 100%', label: 'Remote project' } });
|
|
879
|
+
expect(remote.projects).toHaveLength(1);
|
|
880
|
+
expect(hub.projects).toEqual([]);
|
|
881
|
+
expect((await (await hub.call('/api/hosts/projects')).json()).projects).toEqual([added.project]);
|
|
882
|
+
expect(tip.mock.calls.filter(([event]) => event.type === 'yuri:project-order-changed')).toHaveLength(1);
|
|
883
|
+
const repeated = await (await hub.call('/api/hosts/remote-1/projects', 'POST', { path: added.project.path, label: 'Do not rename' })).json();
|
|
884
|
+
expect(repeated).toEqual({ project: added.project, created: false });
|
|
885
|
+
expect(tip.mock.calls.filter(([event]) => event.type === 'yuri:project-order-changed')).toHaveLength(1);
|
|
886
|
+
expect(hub.gateway.assertProjectDirectory(target.hostId, added.project.path)).toBe(added.project.path);
|
|
887
|
+
const remoteCreate = vi.fn((req, res) => res.json({ data: { ...req.body, time: { created: 1, updated: 1 } } }));
|
|
888
|
+
const localCreate = vi.fn((_req, res) => res.status(500).end());
|
|
889
|
+
remote.app.post('/api/session', express.json(), remoteCreate);
|
|
890
|
+
hub.app.post('/api/session', express.json(), localCreate);
|
|
891
|
+
const created = await runRemoteProjectOperation(hub.gateway, 'create-session', {
|
|
892
|
+
target, directory: added.project.path, sessionID: 'ses_remote_new', title: 'Remote worker',
|
|
893
|
+
});
|
|
894
|
+
expect(created).toMatchObject({ created: true, session: { sessionID: 'ses_remote_new', directory: added.project.path, target } });
|
|
895
|
+
expect(remoteCreate).toHaveBeenCalledOnce();
|
|
896
|
+
expect(localCreate).not.toHaveBeenCalled();
|
|
897
|
+
expect(remote.statusStreams).toBe(0);
|
|
898
|
+
expect(remote.indexRequests).toBe(0);
|
|
899
|
+
expect(remote.content.size).toBe(0);
|
|
900
|
+
await expect(runRemoteProjectOperation(hub.gateway, 'add-remote', { target: { ...target, instanceId: 'replacement' }, path: '/wrong-target' })).rejects.toMatchObject({ code: 'remote_instance_mismatch' });
|
|
901
|
+
expect(remote.projects).toHaveLength(1);
|
|
902
|
+
} finally { unsubscribe(); }
|
|
903
|
+
});
|
|
904
|
+
|
|
905
|
+
it('retains remote registration after an Agent Hub write failure and safely completes the same association on retry', async () => {
|
|
906
|
+
const { hub, remote } = await aggregate({ failHubWrite: true });
|
|
907
|
+
const { hosts } = await runRemoteProjectOperation(hub.gateway, 'remote-hosts', {});
|
|
908
|
+
const input = { target: hosts[0].target, path: '/remote-only' };
|
|
909
|
+
await expect(runRemoteProjectOperation(hub.gateway, 'add-remote', input)).rejects.toThrow('injected disk failure');
|
|
910
|
+
expect(remote.projects).toHaveLength(1);
|
|
911
|
+
expect(hub.store.projects()).toEqual([]);
|
|
912
|
+
const saved = await runRemoteProjectOperation(hub.gateway, 'add-remote', input);
|
|
913
|
+
expect(saved.created).toBe(true);
|
|
914
|
+
expect((await runRemoteProjectOperation(hub.gateway, 'add-remote', input)).created).toBe(false);
|
|
915
|
+
expect(remote.projects).toHaveLength(1);
|
|
916
|
+
expect(hub.store.projects()).toHaveLength(1);
|
|
917
|
+
expect(hub.projects).toEqual([]);
|
|
918
|
+
expect(remote.statusStreams).toBe(0);
|
|
919
|
+
});
|
|
920
|
+
|
|
688
921
|
it('multiplexes one lightweight status stream, retains SQLite summaries offline and releases all streams on revoke', async () => {
|
|
689
922
|
const { hub, remote } = await aggregate();
|
|
690
923
|
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
@@ -811,7 +1044,8 @@ describe('Remote Host production HTTP contract', () => {
|
|
|
811
1044
|
let serviceReady;
|
|
812
1045
|
const sshGate = new Promise((resolve) => { sshReady = resolve; });
|
|
813
1046
|
remote.setCapabilityGate(new Promise((resolve) => { serviceReady = resolve; }));
|
|
814
|
-
|
|
1047
|
+
let progress;
|
|
1048
|
+
const prepareHost = vi.fn(async (_id, { onProgress }) => { progress = onProgress; await sshGate; return descriptor; });
|
|
815
1049
|
const hub = await host({ adapter: { listHosts: async () => [descriptor], prepareHost }, requestTimeoutMs: 5000 });
|
|
816
1050
|
let completed = false;
|
|
817
1051
|
const connection = hub.call('/api/hosts/ssh-cold/connect', 'POST').then((response) => { completed = true; return response; });
|
|
@@ -819,8 +1053,17 @@ describe('Remote Host production HTTP contract', () => {
|
|
|
819
1053
|
await wait(() => expect(prepareHost).toHaveBeenCalledOnce());
|
|
820
1054
|
expect(completed).toBe(false);
|
|
821
1055
|
expect(remote.requests).toBe(0);
|
|
1056
|
+
for (const phase of ['checking', 'installing', 'updating', 'starting']) {
|
|
1057
|
+
progress(phase);
|
|
1058
|
+
const catalog = await (await hub.call('/api/hosts')).json();
|
|
1059
|
+
expect(catalog.hosts[0]).toMatchObject({ state: 'connecting', preparationPhase: phase });
|
|
1060
|
+
}
|
|
1061
|
+
progress('private native detail');
|
|
1062
|
+
expect((await (await hub.call('/api/hosts')).json()).hosts[0].preparationPhase).toBe('starting');
|
|
822
1063
|
sshReady();
|
|
823
1064
|
await wait(() => expect(remote.capabilityRequests).toBe(1));
|
|
1065
|
+
progress('updating');
|
|
1066
|
+
expect((await (await hub.call('/api/hosts')).json()).hosts[0].preparationPhase).toBeUndefined();
|
|
824
1067
|
expect(completed).toBe(false);
|
|
825
1068
|
serviceReady();
|
|
826
1069
|
const response = await connection;
|
|
@@ -835,6 +1078,46 @@ describe('Remote Host production HTTP contract', () => {
|
|
|
835
1078
|
}
|
|
836
1079
|
});
|
|
837
1080
|
|
|
1081
|
+
it('broadcasts safe SSH progress on the existing client stream and clears failed/late preparation before retry', async () => {
|
|
1082
|
+
const remote = await host();
|
|
1083
|
+
const descriptor = { id: 'ssh-cold', source: 'ssh', apiUrl: remote.url, clientToken: remote.issued.token };
|
|
1084
|
+
let progress;
|
|
1085
|
+
let rejectPreparation;
|
|
1086
|
+
const gate = new Promise((_resolve, reject) => { rejectPreparation = reject; });
|
|
1087
|
+
const prepareHost = vi.fn(async (_id, { onProgress }) => { progress = onProgress; await gate; return descriptor; });
|
|
1088
|
+
const hub = await host({ adapter: { listHosts: async () => [descriptor], prepareHost } });
|
|
1089
|
+
const abort = new AbortController();
|
|
1090
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
1091
|
+
const reader = stream.body.getReader();
|
|
1092
|
+
const events = [];
|
|
1093
|
+
const read = (async () => { try {
|
|
1094
|
+
for (;;) { const value = await reader.read(); if (value.done) break; events.push(new TextDecoder().decode(value.value)); }
|
|
1095
|
+
} catch { /* abort closes the stream */ } })();
|
|
1096
|
+
const connection = hub.call('/api/hosts/ssh-cold/connect', 'POST');
|
|
1097
|
+
try {
|
|
1098
|
+
await wait(() => expect(prepareHost).toHaveBeenCalledOnce());
|
|
1099
|
+
progress('updating');
|
|
1100
|
+
await wait(() => expect(events.join('')).toContain('"preparationPhase":"updating"'));
|
|
1101
|
+
rejectPreparation(Object.assign(new Error('private native details'), { code: 'remote_ssh_unavailable' }));
|
|
1102
|
+
expect((await connection).status).toBe(503);
|
|
1103
|
+
await wait(() => expect(events.join('')).toContain('"state":"offline"'));
|
|
1104
|
+
expect(events.join('')).not.toContain('private native details');
|
|
1105
|
+
progress('installing');
|
|
1106
|
+
expect((await (await hub.call('/api/hosts')).json()).hosts[0].preparationPhase).toBeUndefined();
|
|
1107
|
+
expect(events.join('')).not.toContain('"preparationPhase":"installing"');
|
|
1108
|
+
prepareHost.mockImplementation(async (_id, { onProgress }) => {
|
|
1109
|
+
onProgress('checking');
|
|
1110
|
+
progress('installing');
|
|
1111
|
+
expect((await (await hub.call('/api/hosts')).json()).hosts[0].preparationPhase).toBe('checking');
|
|
1112
|
+
return descriptor;
|
|
1113
|
+
});
|
|
1114
|
+
expect((await hub.call('/api/hosts/ssh-cold/connect', 'POST')).status).toBe(200);
|
|
1115
|
+
} finally {
|
|
1116
|
+
rejectPreparation(new Error('test cleanup')); await connection;
|
|
1117
|
+
abort.abort(); await read;
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
|
|
838
1121
|
it('isolates colliding host/session paths, keeps offline partitions and fairly bounds refresh work with a stalled host', async () => {
|
|
839
1122
|
const stats = { active: 0, max: 0 };
|
|
840
1123
|
const remotes = await Promise.all(Array.from({ length: 3 }, () => host({ indexStats: stats })));
|
|
@@ -1153,6 +1436,15 @@ describe('Remote Host production HTTP contract', () => {
|
|
|
1153
1436
|
const created = await hub.call('/api/hosts/relay-only/projects', 'POST', { path: '/same/path' });
|
|
1154
1437
|
expect({ status: created.status, body: await created.json() }).toMatchObject({ status: 200,
|
|
1155
1438
|
body: { project: { hostId: 'relay-only', path: '/same/path' } } });
|
|
1439
|
+
const { hosts: authenticatedHosts } = await runRemoteProjectOperation(hub.gateway, 'remote-hosts', {});
|
|
1440
|
+
const target = authenticatedHosts[0].target;
|
|
1441
|
+
const registered = await runRemoteProjectOperation(hub.gateway, 'add-remote', { target, path: '/agent-relay-project' });
|
|
1442
|
+
expect(registered).toMatchObject({ created: true, target, project: { path: '/agent-relay-project', hostId: 'relay-only' } });
|
|
1443
|
+
const createSession = vi.fn((req, res) => res.json({ data: { ...req.body, time: { created: 1, updated: 1 } } }));
|
|
1444
|
+
remote.app.post('/api/session', express.json(), createSession);
|
|
1445
|
+
expect(await runRemoteProjectOperation(hub.gateway, 'create-session', { target, directory: registered.project.path, sessionID: 'ses_relay_new' }))
|
|
1446
|
+
.toMatchObject({ created: true, session: { sessionID: 'ses_relay_new', directory: registered.project.path, target } });
|
|
1447
|
+
expect(createSession).toHaveBeenCalledOnce();
|
|
1156
1448
|
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
1157
1449
|
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/relay-only/api/terminal/ws`, { headers: hub.headers });
|
|
1158
1450
|
disposers.push(() => socket.terminate());
|
|
@@ -1172,5 +1464,14 @@ describe('Remote Host production HTTP contract', () => {
|
|
|
1172
1464
|
socket.close(); await once(socket, 'close');
|
|
1173
1465
|
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
1174
1466
|
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
1467
|
+
const onEvent = vi.fn();
|
|
1468
|
+
const task = await hub.gateway.acquireTask('relay-only', { instanceId: remote.store.hubId, onEvent });
|
|
1469
|
+
expect(hub.liveClients).toBe(0);
|
|
1470
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
1471
|
+
expect((await task.json('/api/projects')).projects[0].path).toBe('/same/path');
|
|
1472
|
+
remote.emit({ type: 'session.execution.succeeded', data: { sessionID: 'remote-worker', directory: '/same/path' } });
|
|
1473
|
+
await wait(() => expect(onEvent.mock.calls.some(([event]) => event.payload.type === 'session.execution.succeeded')).toBe(true));
|
|
1474
|
+
task.release();
|
|
1475
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
1175
1476
|
}, 20000);
|
|
1176
1477
|
});
|
|
@@ -23,17 +23,31 @@ export function createRemoteHostStore(dbPath) {
|
|
|
23
23
|
db.exec(`CREATE TABLE IF NOT EXISTS remote_organization (
|
|
24
24
|
host_id TEXT NOT NULL, kind TEXT NOT NULL, snapshot TEXT NOT NULL, PRIMARY KEY(host_id, kind));`);
|
|
25
25
|
db.exec('CREATE TABLE IF NOT EXISTS remote_host_display (id TEXT PRIMARY KEY, name TEXT NOT NULL, source TEXT NOT NULL)');
|
|
26
|
+
db.exec('CREATE TABLE IF NOT EXISTS remote_host_authority (host_id TEXT PRIMARY KEY, instance_id TEXT NOT NULL)');
|
|
26
27
|
db.prepare('INSERT INTO remote_hub_identity(id) SELECT ? WHERE NOT EXISTS (SELECT 1 FROM remote_hub_identity)')
|
|
27
28
|
.run(crypto.randomUUID());
|
|
28
29
|
const hubId = db.prepare('SELECT id FROM remote_hub_identity').get().id;
|
|
30
|
+
const instanceFor = (hostId) => db.prepare('SELECT instance_id FROM remote_host_authority WHERE host_id = ?').get(hostId)?.instance_id;
|
|
29
31
|
const decode = (row) => row && ({ id: row.id, hostId: row.host_id, path: row.path,
|
|
32
|
+
...(row.instance_id ? { instanceId: row.instance_id } : {}),
|
|
30
33
|
remoteProjectId: row.remote_project_id, remoteState: row.state,
|
|
31
34
|
...JSON.parse(row.metadata), addedAt: row.added_at, lastOpenedAt: row.added_at });
|
|
32
35
|
const projects = (hostId) => (hostId
|
|
33
|
-
? db.prepare('SELECT
|
|
34
|
-
: db.prepare('SELECT
|
|
36
|
+
? db.prepare('SELECT p.*, a.instance_id FROM remote_project p LEFT JOIN remote_host_authority a ON a.host_id = p.host_id WHERE p.host_id = ? ORDER BY p.added_at, p.id').all(hostId)
|
|
37
|
+
: db.prepare('SELECT p.*, a.instance_id FROM remote_project p LEFT JOIN remote_host_authority a ON a.host_id = p.host_id ORDER BY p.added_at, p.id').all()).map(decode);
|
|
35
38
|
return {
|
|
36
|
-
hubId, projects,
|
|
39
|
+
hubId, projects, instanceFor,
|
|
40
|
+
bindInstance(hostId, instanceId) {
|
|
41
|
+
if (typeof instanceId !== 'string' || !instanceId.trim() || instanceId !== instanceId.trim()
|
|
42
|
+
|| instanceId.length > 512 || /[\x00-\x1f]/.test(instanceId)) {
|
|
43
|
+
throw Object.assign(new Error('remote_incompatible'), { code: 'remote_incompatible', status: 409 });
|
|
44
|
+
}
|
|
45
|
+
db.prepare('INSERT OR IGNORE INTO remote_host_authority(host_id, instance_id) VALUES (?, ?)').run(hostId, instanceId);
|
|
46
|
+
if (instanceFor(hostId) !== instanceId) {
|
|
47
|
+
throw Object.assign(new Error('remote_instance_mismatch'), { code: 'remote_instance_mismatch', status: 409 });
|
|
48
|
+
}
|
|
49
|
+
return instanceId;
|
|
50
|
+
},
|
|
37
51
|
hasProjects() { return Boolean(db.prepare('SELECT 1 FROM remote_project LIMIT 1').get()); },
|
|
38
52
|
saveHost(host) {
|
|
39
53
|
db.prepare(`INSERT INTO remote_host_display VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,
|
|
@@ -4,6 +4,25 @@ import path from 'node:path';
|
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import { createRemoteHostStore } from './store.js';
|
|
6
6
|
|
|
7
|
+
it('pins authenticated instance identity across reopen and preserves legacy project references', async () => {
|
|
8
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'remote-store-authority-'));
|
|
9
|
+
const dbPath = path.join(root, 'remote.sqlite');
|
|
10
|
+
let store = createRemoteHostStore(dbPath);
|
|
11
|
+
try {
|
|
12
|
+
const reference = store.saveProject('ssh', { id: 'project', path: '/same/path' });
|
|
13
|
+
expect(reference.instanceId).toBeUndefined();
|
|
14
|
+
store.bindInstance('ssh', 'machine-a');
|
|
15
|
+
store.bindInstance('relay', 'machine-a');
|
|
16
|
+
expect(store.projects('ssh')[0]).toMatchObject({ id: reference.id, instanceId: 'machine-a' });
|
|
17
|
+
store.close(); store = createRemoteHostStore(dbPath);
|
|
18
|
+
expect(store.bindInstance('ssh', 'machine-a')).toBe('machine-a');
|
|
19
|
+
expect(() => store.bindInstance('ssh', 'machine-b')).toThrow('remote_instance_mismatch');
|
|
20
|
+
expect(store.projects('ssh')[0]).toMatchObject({ id: reference.id, instanceId: 'machine-a' });
|
|
21
|
+
for (const malformed of ['', ' bad', 'bad\nvalue', null]) expect(() => store.bindInstance('invalid', malformed)).toThrow('remote_incompatible');
|
|
22
|
+
expect(store.instanceFor('invalid')).toBeUndefined();
|
|
23
|
+
} finally { store.close(); await fs.rm(root, { recursive: true, force: true }); }
|
|
24
|
+
});
|
|
25
|
+
|
|
7
26
|
it('projects the SQLite hint and never revives a removed or replaced reference during metadata refresh', async () => {
|
|
8
27
|
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'remote-store-refresh-'));
|
|
9
28
|
const dbPath = path.join(root, 'remote.sqlite');
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
|
|
2
|
+
|
|
3
|
+
/** Official SDK forwarding over one authenticated, authority-fenced task lease.
|
|
4
|
+
* The target Yuri HTTP proxy enforces its own current OpenCode write admission.
|
|
5
|
+
* No Hub runtime contract, endpoint, credentials or protocol implementation leaks in.
|
|
6
|
+
*/
|
|
7
|
+
export function makeRemoteTaskOpenCodeClient(lease) {
|
|
8
|
+
if (!lease || typeof lease.request !== 'function' || !lease.target?.hubId || !lease.target?.hostId || !lease.target?.instanceId) {
|
|
9
|
+
throw new Error('A complete authenticated remote task lease is required');
|
|
10
|
+
}
|
|
11
|
+
return makeOpenCodeV2Client({
|
|
12
|
+
baseUrl: 'http://remote-task.invalid',
|
|
13
|
+
executionAdmission: 'target-yuri-proxy',
|
|
14
|
+
fetchImpl: async (input, init) => {
|
|
15
|
+
const request = new Request(input, init);
|
|
16
|
+
const url = new URL(request.url);
|
|
17
|
+
if (url.origin !== 'http://remote-task.invalid' || !url.pathname.startsWith('/api/')) throw new Error('Remote SDK route escaped its target proxy');
|
|
18
|
+
const mutation = !['GET', 'HEAD'].includes(request.method);
|
|
19
|
+
return lease.request(`${url.pathname}${url.search}`, {
|
|
20
|
+
method: request.method, headers: request.headers, signal: request.signal,
|
|
21
|
+
...(mutation ? { body: await request.arrayBuffer() } : {}),
|
|
22
|
+
}, { longRunning: mutation });
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { makeRemoteTaskOpenCodeClient } from './task-client.js';
|
|
3
|
+
import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
|
|
4
|
+
import { configureServerOpenCodeFetchGate } from '../opencode/server-opencode-fetch.js';
|
|
5
|
+
import { createRemoteTransport } from './transport.js';
|
|
6
|
+
|
|
7
|
+
afterEach(() => configureServerOpenCodeFetchGate(null, { allowMissingContract: true }));
|
|
8
|
+
const target = { hubId: 'hub', hostId: 'host', instanceId: 'instance' };
|
|
9
|
+
|
|
10
|
+
describe('official SDK through a remote task lease', () => {
|
|
11
|
+
it('keeps local admission blocked while forwarding remote writes with native body, headers, query and abort', async () => {
|
|
12
|
+
configureServerOpenCodeFetchGate(() => ({ executionAllowed: false }));
|
|
13
|
+
const localFetch = vi.fn();
|
|
14
|
+
const local = makeOpenCodeV2Client({ baseUrl: 'http://local.invalid', fetchImpl: localFetch });
|
|
15
|
+
await expect(local.session.create({ location: { directory: '/same/path' } })).rejects.toBeDefined();
|
|
16
|
+
expect(localFetch).not.toHaveBeenCalled();
|
|
17
|
+
const request = vi.fn(async () => Response.json({ data: { id: 'input', type: 'user' } }));
|
|
18
|
+
const remote = makeRemoteTaskOpenCodeClient({ target, request });
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
await remote.session.prompt({ sessionID: 'ses_test', id: 'msg_test', text: 'exact text', delivery: 'steer' }, { signal: controller.signal, headers: { 'x-test': 'kept' } });
|
|
21
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
22
|
+
const [route, init] = request.mock.calls[0];
|
|
23
|
+
expect(route).toBe('/api/session/ses_test/prompt');
|
|
24
|
+
expect(init.method).toBe('POST');
|
|
25
|
+
expect(request.mock.calls[0][2]).toEqual({ longRunning: true });
|
|
26
|
+
expect(new Headers(init.headers).get('x-test')).toBe('kept');
|
|
27
|
+
expect(JSON.parse(Buffer.from(init.body).toString())).toEqual({ id: 'msg_test', text: 'exact text', delivery: 'steer' });
|
|
28
|
+
controller.abort();
|
|
29
|
+
expect(init.signal.aborted).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('propagates target proxy runtime rejection without retry or a local fallback', async () => {
|
|
33
|
+
configureServerOpenCodeFetchGate(() => ({ executionAllowed: false }));
|
|
34
|
+
const request = vi.fn(async () => Response.json({ error: 'runtime_contract_execution_blocked' }, { status: 503 }));
|
|
35
|
+
const remote = makeRemoteTaskOpenCodeClient({ target, request });
|
|
36
|
+
await expect(remote.session.create({ location: { directory: '/same/path' } })).rejects.toBeDefined();
|
|
37
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('rejects missing authority/transport instead of constructing an unscoped network client', () => {
|
|
41
|
+
expect(() => makeRemoteTaskOpenCodeClient({ target: { hubId: 'hub', hostId: 'host' }, request: vi.fn() })).toThrow();
|
|
42
|
+
expect(() => makeRemoteTaskOpenCodeClient({ target })).toThrow();
|
|
43
|
+
expect(() => makeOpenCodeV2Client({ baseUrl: 'http://remote.invalid', executionAdmission: 'target-yuri-proxy' })).toThrow();
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it.each(['Headers', 'record', 'pairs'])('preserves %s request headers while the target credential overrides caller auth case-insensitively', async (kind) => {
|
|
47
|
+
const fetchImpl = vi.fn(async () => Response.json({ remoteProjects: true, protocol: 1, instanceId: 'instance' }));
|
|
48
|
+
const transport = await createRemoteTransport({ apiUrl: 'http://remote.invalid', clientToken: 'target-fixture' }, { fetchImpl });
|
|
49
|
+
const pairs = [['Content-Type', 'application/json'], ['X-Opencode-Directory', '/remote/raw path'], ['authorization', 'Bearer caller-fixture']];
|
|
50
|
+
const headers = kind === 'Headers' ? new Headers(pairs) : kind === 'record' ? Object.fromEntries(pairs) : pairs;
|
|
51
|
+
try {
|
|
52
|
+
await transport.fetch('/api/session', { method: 'POST', headers, body: '{"id":"ses_new"}' });
|
|
53
|
+
const sent = new Headers(fetchImpl.mock.lastCall[1].headers);
|
|
54
|
+
expect(sent.get('content-type')).toBe('application/json');
|
|
55
|
+
expect(sent.get('x-opencode-directory')).toBe('/remote/raw path');
|
|
56
|
+
expect(sent.get('authorization')).toBe('Bearer target-fixture');
|
|
57
|
+
expect(sent.get('authorization')).not.toContain('caller-fixture');
|
|
58
|
+
} finally { transport.close(); }
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -14,6 +14,11 @@ export async function createRemoteTransport(host, { fetchImpl = fetch, signal }
|
|
|
14
14
|
const token = host.clientToken;
|
|
15
15
|
if (!token) throw failure('remote_authorization_required', 401);
|
|
16
16
|
const headers = { ...host.requestHeaders, Authorization: `Bearer ${token}` };
|
|
17
|
+
const requestHeaders = (input) => {
|
|
18
|
+
const merged = new Headers(input);
|
|
19
|
+
for (const [name, value] of Object.entries(headers)) merged.set(name, value);
|
|
20
|
+
return Object.fromEntries(merged);
|
|
21
|
+
};
|
|
17
22
|
let base = directUrl(host.apiUrl || host.url);
|
|
18
23
|
let capabilities;
|
|
19
24
|
const readAdmission = async (response) => {
|
|
@@ -58,7 +63,7 @@ export async function createRemoteTransport(host, { fetchImpl = fetch, signal }
|
|
|
58
63
|
if (closed) throw failure('stale_host', 409);
|
|
59
64
|
return fetchImpl(new URL(route, base), { ...init,
|
|
60
65
|
signal: AbortSignal.any([...(signal ? [signal] : []), ...(init.signal ? [init.signal] : [])]),
|
|
61
|
-
redirect: 'manual', headers:
|
|
66
|
+
redirect: 'manual', headers: requestHeaders(init.headers) });
|
|
62
67
|
},
|
|
63
68
|
openWebSocket(route, protocols = [], { onMessage } = {}) {
|
|
64
69
|
if (closed) throw failure('stale_host', 409);
|
|
@@ -90,7 +95,7 @@ export async function createRemoteTransport(host, { fetchImpl = fetch, signal }
|
|
|
90
95
|
if (signal?.aborted) close();
|
|
91
96
|
const relayFetch = (route, init = {}) => tunnel.fetch(`http://remote.invalid${route}`, {
|
|
92
97
|
...init, signal: AbortSignal.any([...(signal ? [signal] : []), ...(init.signal ? [init.signal] : [])]),
|
|
93
|
-
headers:
|
|
98
|
+
headers: requestHeaders(init.headers),
|
|
94
99
|
});
|
|
95
100
|
try {
|
|
96
101
|
capabilities = await readAdmission(await relayFetch('/api/hosts/capabilities', { signal: boundedSignal(10000) }));
|
|
@@ -4,7 +4,7 @@ export const applyRuntimeCorsHeaders = ({ origin, setHeader }) => {
|
|
|
4
4
|
setHeader('Access-Control-Allow-Origin', origin);
|
|
5
5
|
setHeader('Access-Control-Allow-Credentials', 'true');
|
|
6
6
|
setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
|
|
7
|
-
setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding,X-Message-Queue-Upload-Token,X-Message-Queue-Sha256,X-Message-Queue-Content-Length,X-Yuri-Content-Length,X-Yuri-Sha256,X-Yuri-Mime,X-Yuri-Filename,X-Yuri-Gui-Revision,X-Content-SHA256,X-Content-Size,X-Attachment-Filename');
|
|
7
|
+
setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding,X-Message-Queue-Upload-Token,X-Message-Queue-Sha256,X-Message-Queue-Content-Length,X-Yuri-Content-Length,X-Yuri-Sha256,X-Yuri-Mime,X-Yuri-Filename,X-Yuri-Gui-Revision,X-Yuri-Target-Instance,X-Content-SHA256,X-Content-Size,X-Attachment-Filename');
|
|
8
8
|
// Packaged clients (Electron yuri-ui://app, Capacitor, Vite HMR) are
|
|
9
9
|
// cross-origin to the runtime API. Without an expose list, browsers hide
|
|
10
10
|
// custom response headers from JS — including the optional-read existence
|
|
@@ -31,6 +31,7 @@ describe('applyRuntimeCorsHeaders', () => {
|
|
|
31
31
|
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Content-Length');
|
|
32
32
|
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Filename');
|
|
33
33
|
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Gui-Revision');
|
|
34
|
+
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Target-Instance');
|
|
34
35
|
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-gui-revision');
|
|
35
36
|
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-gui-code');
|
|
36
37
|
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-next-cursor');
|
|
@@ -16,7 +16,7 @@ import { registerRemoteConnectionsSkill, REMOTE_CONNECTIONS_SKILL_PATH } from '.
|
|
|
16
16
|
import { registerProjectsSkill, PROJECTS_SKILL_PATH } from '../gui-customization/projects.js';
|
|
17
17
|
|
|
18
18
|
describe('built-in session skill with authenticated Host', () => {
|
|
19
|
-
let root, server, origin, ui, sessions, entries, store, password, auth, registrationFile, sdk, sync, failInstructions, failCleanup, connections, registerProject;
|
|
19
|
+
let root, server, origin, ui, sessions, entries, store, password, auth, registrationFile, sdk, sync, failInstructions, failCleanup, connections, registerProject, remoteGateway;
|
|
20
20
|
const upstreamOrigin = 'http://127.0.0.1:4096';
|
|
21
21
|
beforeEach(async () => {
|
|
22
22
|
root = await fs.mkdtemp(path.join(os.tmpdir(), 'session-skill-'));
|
|
@@ -68,8 +68,9 @@ describe('built-in session skill with authenticated Host', () => {
|
|
|
68
68
|
};
|
|
69
69
|
const router = express.Router();
|
|
70
70
|
registerProject = vi.fn(async (input) => ({ project: { id: 'registered', ...input }, created: true, settings: { password } }));
|
|
71
|
+
remoteGateway = { supported: false, acquireTask: vi.fn(), registerProject: vi.fn(), list: vi.fn() };
|
|
71
72
|
registerProjectsSkill(app, { express, getIsSharedOpenCodeService: () => true, getOpenCodeAuthHeaders: () => auth, createClient: () => sdk,
|
|
72
|
-
registerProject, readSettingsFromDiskStrict: common.readSettingsFromDiskMigrated, sanitizeProjects: common.sanitizeProjects });
|
|
73
|
+
registerProject, readSettingsFromDiskStrict: common.readSettingsFromDiskMigrated, sanitizeProjects: common.sanitizeProjects, remoteHostGateway: remoteGateway });
|
|
73
74
|
connections = { list: vi.fn(async () => ({ instances: [] })), setup: vi.fn(async () => ({ id: 'ssh_one', running: true })),
|
|
74
75
|
pair: vi.fn(async () => ({ url: 'yuri://connect?v=2&p=fixture', expiresAt: '2099-01-01' })) };
|
|
75
76
|
registerRemoteConnectionsSkill(app, { express, adapter: connections, getIsSharedOpenCodeService: () => true, getOpenCodeAuthHeaders: () => auth, createClient: () => sdk });
|
|
@@ -224,6 +225,36 @@ describe('built-in session skill with authenticated Host', () => {
|
|
|
224
225
|
expect(registerProject).toHaveBeenCalledTimes(1);
|
|
225
226
|
});
|
|
226
227
|
|
|
228
|
+
it('runs remote discovery and project registration through the exact staged commands and real auth gate', async () => {
|
|
229
|
+
const target = { hubId: 'hub', hostId: 'host', instanceId: 'instance' };
|
|
230
|
+
const release = vi.fn();
|
|
231
|
+
remoteGateway.supported = true;
|
|
232
|
+
remoteGateway.list.mockResolvedValue({ supported: true, hubId: target.hubId, hosts: [{ id: target.hostId, name: 'Build machine', source: 'ssh' }], projects: [] });
|
|
233
|
+
remoteGateway.acquireTask.mockResolvedValue({ target, release });
|
|
234
|
+
remoteGateway.registerProject.mockResolvedValue({ project: { id: 'remote-ref', hostId: target.hostId, path: '/remote/repo' }, created: true });
|
|
235
|
+
const session = await create();
|
|
236
|
+
const pointer = entries.get(`${session.id}:customization`);
|
|
237
|
+
const command = pointer.split('Bound project helper: ')[1].split('\n')[0];
|
|
238
|
+
const described = await run(command);
|
|
239
|
+
expect(described.code).toBe(0);
|
|
240
|
+
expect(described.value.remoteSupported).toBe(true);
|
|
241
|
+
const cmd = described.value.commands;
|
|
242
|
+
expect(cmd['remote-hosts']).toBeTypeOf('string');
|
|
243
|
+
expect(cmd['add-remote']).toBeTypeOf('string');
|
|
244
|
+
const discovered = await run(cmd['remote-hosts']);
|
|
245
|
+
expect(discovered).toMatchObject({ code: 0, value: { hosts: [{ name: 'Build machine', target }], complete: true } });
|
|
246
|
+
expect(release).toHaveBeenCalledOnce();
|
|
247
|
+
const input = { target: discovered.value.hosts[0].target, path: '/remote/repo' };
|
|
248
|
+
const added = await run(cmd['add-remote'], input);
|
|
249
|
+
expect(added).toMatchObject({ code: 0, value: { project: { id: 'remote-ref', path: input.path }, created: true, target } });
|
|
250
|
+
expect(remoteGateway.registerProject).toHaveBeenCalledExactlyOnceWith('host', { path: input.path }, { instanceId: 'instance', signal: expect.any(AbortSignal) });
|
|
251
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
252
|
+
expect(pointer + discovered.stdout + added.stdout + added.stderr).not.toContain(password);
|
|
253
|
+
sessions.get(session.id).metadata.yuri.scheduledTaskSkill.hostOrigin = 'http://127.0.0.1:1';
|
|
254
|
+
expect((await run(cmd['add-remote'], input)).value).toMatchObject({ status: 403, terminal: true });
|
|
255
|
+
expect(remoteGateway.registerProject).toHaveBeenCalledOnce();
|
|
256
|
+
});
|
|
257
|
+
|
|
227
258
|
it('rejects unbounded connection input and sanitizes remote errors', async () => {
|
|
228
259
|
const session = await create();
|
|
229
260
|
const request = (operation, input) => fetch(`${origin}${REMOTE_CONNECTIONS_SKILL_PATH}`, { method: 'POST',
|