@yuriai/web 0.2.40-beta.5 → 0.2.40-beta.6

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 (160) hide show
  1. package/dist/assets/{AgentAvatar-B7KbxN8Y.js → AgentAvatar-XDXiFZvA.js} +1 -1
  2. package/dist/assets/AssistantConversationSurface-B59k-lXE.css +1 -0
  3. package/dist/assets/AssistantConversationSurface-CQnJaKTn.js +3 -0
  4. package/dist/assets/AssistantSessionCard-DXY8-wyP.js +2 -0
  5. package/dist/assets/{AssistantUnreadBadge-vu4ZhTft.js → AssistantUnreadBadge-B-G015yE.js} +1 -1
  6. package/dist/assets/{AssistantView-CEfEWUIr.js → AssistantView-CasyQbii.js} +1 -1
  7. package/dist/assets/{DiagramView-Dlzr08J_.js → DiagramView-DhWnsM9v.js} +1 -1
  8. package/dist/assets/{FadeInOnReveal-DMRmNsau.js → FadeInOnReveal-Ca9EVP3a.js} +1 -1
  9. package/dist/assets/{GuiPluginPage-DVug4z_p.js → GuiPluginPage-DKOsUpVL.js} +1 -1
  10. package/dist/assets/{GuiPluginSurface-L43o6Xv8.js → GuiPluginSurface-BfXMBqdD.js} +1 -1
  11. package/dist/assets/{GuiPluginWindow-tHXkS18H.js → GuiPluginWindow-Dmg2Qui6.js} +1 -1
  12. package/dist/assets/{Icon-DizeYahT.js → Icon-ChyA050P.js} +1 -1
  13. package/dist/assets/{ImageLoadingPlaceholder-BZC5m_km.js → ImageLoadingPlaceholder-C8QUF5aV.js} +1 -1
  14. package/dist/assets/{LoadingImage-Csw4L-Dr.js → LoadingImage-BxRq1dMQ.js} +1 -1
  15. package/dist/assets/{MarkdownRenderer-D_0iKhQN.js → MarkdownRenderer-CvWLikEO.js} +2 -2
  16. package/dist/assets/{MarkdownRendererImpl-BZ0XgjS0.js → MarkdownRendererImpl-CcNsQOEn.js} +1 -1
  17. package/dist/assets/{MarkstreamRendererImpl-DBd6Glg9.js → MarkstreamRendererImpl-D9W5XXPo.js} +1 -1
  18. package/dist/assets/MobileDetailNavigation-CnwIZn5g.js +1 -0
  19. package/dist/assets/{MobileResizableSheet-CQQ7O-2X.js → MobileResizableSheet-Bpp079l7.js} +1 -1
  20. package/dist/assets/{MobileShareBridge-IO45gM2G.js → MobileShareBridge-C-GpJfF6.js} +1 -1
  21. package/dist/assets/MobileSurface-CrNI8cYQ.js +2 -0
  22. package/dist/assets/{MultiRunWindow-fJ3XfntS.js → MultiRunWindow-DvywQkz9.js} +1 -1
  23. package/dist/assets/{OnboardingScreen-MJS5T5rL.js → OnboardingScreen-BvueSxVk.js} +1 -1
  24. package/dist/assets/{OverlayScrollbar-jtMYTn1y.js → OverlayScrollbar-CPaH_j8g.js} +1 -1
  25. package/dist/assets/RemoteAssistantSessionCard-CFWE00xD.js +1 -0
  26. package/dist/assets/{SettingsView-ZWFLpPSI.js → SettingsView-Df6GCFPI.js} +10 -10
  27. package/dist/assets/{SettingsWindow-DGRmrIWz.js → SettingsWindow-BpaRjeR-.js} +1 -1
  28. package/dist/assets/{SetupTourDialog-BYbAubwA.js → SetupTourDialog-DD_4qiTz.js} +1 -1
  29. package/dist/assets/{TerminalView-CoJ6_9P1.js → TerminalView-CRTtNAfA.js} +1 -1
  30. package/dist/assets/{ToolOutputDialog-5xBwOJ6a.js → ToolOutputDialog-omGmWntf.js} +1 -1
  31. package/dist/assets/{VoiceSettings-CN33koSc.js → VoiceSettings-Du-Yd5MF.js} +2 -2
  32. package/dist/assets/{YuriWordmark-DnFAS-Ko.js → YuriWordmark-B7lmpLRB.js} +1 -1
  33. package/dist/assets/{capgoAdapter-CCLtBZL1.js → capgoAdapter-CqMX4zC-.js} +1 -1
  34. package/dist/assets/{checkbox-rOV6DjeG.js → checkbox-KNAgqjPZ.js} +1 -1
  35. package/dist/assets/{client-uz8O6TPX.js → client-1Fk5IbQR.js} +3 -3
  36. package/dist/assets/{collapsible-CKswuqAw.js → collapsible-CdiLY07j.js} +1 -1
  37. package/dist/assets/{context-menu-B4njwT_M.js → context-menu-CO_VRWeV.js} +1 -1
  38. package/dist/assets/{diagram-BppQ_USn.js → diagram-9b-Aaful.js} +1 -1
  39. package/dist/assets/{dialog-Bg8MJnOV.js → dialog-8YYmYPFP.js} +1 -1
  40. package/dist/assets/{fileMentionTouchSelection-D-AdTJVr.js → fileMentionTouchSelection-CLQBqWR8.js} +1 -1
  41. package/dist/assets/{gitApi-DVx_V1x6.js → gitApi-uhoLUa-e.js} +1 -1
  42. package/dist/assets/gitApiHttp-B0FJaIhU.js +3 -0
  43. package/dist/assets/{gui-DN2sVP96.js → gui-BMN3-WPc.js} +1 -1
  44. package/dist/assets/{host-DrGjjO6K.js → host-D9EDWNmx.js} +1 -1
  45. package/dist/assets/{input-DRjuZMeA.js → input-DK8VTvJw.js} +1 -1
  46. package/dist/assets/{input-store-CjUOfpyA.js → input-store-CsY-uaSj.js} +1 -1
  47. package/dist/assets/insertionBoundaries-rYqUxuB-.js +1 -0
  48. package/dist/assets/{main-D2s9J_jN.js → main-BMx-2MjO.js} +14 -14
  49. package/dist/assets/main-DzqojuZ1.js +2 -0
  50. package/dist/assets/{markdownHeightCache-BL99DlhC.js → markdownHeightCache-DAvnT6xF.js} +1 -1
  51. package/dist/assets/{mcpQueries-HzYMEVWd.js → mcpQueries-CpH8vPf1.js} +1 -1
  52. package/dist/assets/miniChat-BTE_XpRk.js +2 -0
  53. package/dist/assets/mobile-BBZOulQ1.js +2 -0
  54. package/dist/assets/{mobileBackNavigation--ZdrI-Yj.js → mobileBackNavigation-Cq08UPxZ.js} +1 -1
  55. package/dist/assets/{mobileConnections-C3eGEOPy.js → mobileConnections-ZehAozpe.js} +2 -2
  56. package/dist/assets/{multirun-CDYNyLBH.js → multirun-Cll2Meol.js} +1 -1
  57. package/dist/assets/{native-DsqzO52u.js → native-CDqNKjmz.js} +1 -1
  58. package/dist/assets/{native-config-DOawZfln.js → native-config-DtUZFauV.js} +1 -1
  59. package/dist/assets/{navigation-Ibk_Pw-q.js → navigation-J3d8PQcs.js} +2 -2
  60. package/dist/assets/openRemoteProjectSession-oJZpCDPT.js +1 -0
  61. package/dist/assets/{projectMeta-D1Ytss9U.js → projectMeta-BBpfOmij.js} +1 -1
  62. package/dist/assets/prompt-attachment-upload-9fjmgafL.js +1 -0
  63. package/dist/assets/{pwa-CXupOTsD.js → pwa-C8B1Mf_t.js} +1 -1
  64. package/dist/assets/{queue-abort-optimistic-CQXpIlq6.js → queue-abort-optimistic-B1Uskf6F.js} +1 -1
  65. package/dist/assets/{react-CgRToPwO.js → react-45rBMaUm.js} +1 -1
  66. package/dist/assets/{readiness-BfuZm6Yw.js → readiness-CrjBrUa_.js} +2 -2
  67. package/dist/assets/reference-history-DqfMBWzF.js +1 -0
  68. package/dist/assets/{remote-input-store-BOdCWpQY.js → remote-input-store-84i8uDyM.js} +1 -1
  69. package/dist/assets/remoteProjectQueries-B6lrEDMq.js +1 -0
  70. package/dist/assets/remoteSessionReference-YiGvdabX.js +1 -0
  71. package/dist/assets/renderElectronMiniChatApp-BuHQB0V8.js +2 -0
  72. package/dist/assets/renderMobileApp-D_VswCi0.js +29 -0
  73. package/dist/assets/{runtimeConfig-tHm7o_0I.js → runtimeConfig-CMbNyYbK.js} +1 -1
  74. package/dist/assets/runtimeEndpointReset-zo-HZQgX.js +151 -0
  75. package/dist/assets/scheduledTaskNavigation-y5g8D2ee.js +1 -0
  76. package/dist/assets/{select-B1On-Y4Z.js → select-VWoGVTBZ.js} +1 -1
  77. package/dist/assets/sessionLookup-JAf5UU7-.js +1 -0
  78. package/dist/assets/{sortable-tabs-strip-nD1Me06z.js → sortable-tabs-strip-Dbt3TTAs.js} +1 -1
  79. package/dist/assets/{speechSettingsQueries-BYhNpzDJ.js → speechSettingsQueries-Bidfcv0W.js} +1 -1
  80. package/dist/assets/{terminalApi-madXrfqA.js → terminalApi-Cq0vjFe1.js} +1 -1
  81. package/dist/assets/{textarea-Qt06OhhX.js → textarea-vyMsAV5p.js} +1 -1
  82. package/dist/assets/{tooltip-D382RCy1.js → tooltip-DWqHWi4N.js} +1 -1
  83. package/dist/assets/{types-CHszLAS3.js → types-DeOkRCgE.js} +1 -1
  84. package/dist/assets/{useAppFontEffects-CqXrCJVt.js → useAppFontEffects-z382Lhm_.js} +60 -60
  85. package/dist/assets/useDesktopWindowControlsLayout-BEs7i5qj.js +1 -0
  86. package/dist/assets/{useDictation-Bs7TWO9r.js → useDictation-e68rFA6y.js} +1 -1
  87. package/dist/assets/{useEffectiveDirectory-CCKRdyK9.js → useEffectiveDirectory-CcM3S1OQ.js} +1 -1
  88. package/dist/assets/{useFontPreferences-CPrl1_3z.js → useFontPreferences-CO-L-Gd7.js} +1 -1
  89. package/dist/assets/{useMobileNavigationStore-BNtVrnSw.js → useMobileNavigationStore-BA0IaUi_.js} +9 -9
  90. package/dist/assets/{usePluginsStore-bMuGciUE.js → usePluginsStore-BG5MW5LR.js} +1 -1
  91. package/dist/assets/{useProjectRuntimeAPIs-BFCXBu2J.js → useProjectRuntimeAPIs-Be4gXG7P.js} +1 -1
  92. package/dist/assets/{useStreamingTextThrottle-C8xAqcgP.js → useStreamingTextThrottle-DylP9HFC.js} +1 -1
  93. package/dist/assets/{vendor-opencode-client-cQ47ywrT.js → vendor-opencode-client-BM2r1f0o.js} +3 -3
  94. package/dist/assets/{vendor-opencode-plugin-BmdTE4Te.js → vendor-opencode-plugin-ZhpPgHCL.js} +1 -1
  95. package/dist/assets/{vendor-solid-js-D98iXT7C.js → vendor-solid-js-BBVUd3Hw.js} +1 -1
  96. package/dist/index.html +10 -10
  97. package/dist/mini-chat.html +10 -10
  98. package/dist/mobile.html +1 -1
  99. package/package.json +1 -1
  100. package/server/index.js +1 -0
  101. package/server/lib/assistants/DOCUMENTATION.md +87 -0
  102. package/server/lib/assistants/assign.js +10 -7
  103. package/server/lib/assistants/builtin-skills.js +1 -0
  104. package/server/lib/assistants/builtin-skills.test.js +1 -1
  105. package/server/lib/assistants/cards.js +6 -1
  106. package/server/lib/assistants/contact-store.js +22 -5
  107. package/server/lib/assistants/contact-tools.js +46 -26
  108. package/server/lib/assistants/execution-target.js +136 -0
  109. package/server/lib/assistants/opencode-tools.js +22 -9
  110. package/server/lib/assistants/remote-execution.test.js +378 -0
  111. package/server/lib/assistants/remote-watch-reconciler.js +43 -0
  112. package/server/lib/assistants/remote-watch-reconciler.test.js +88 -0
  113. package/server/lib/assistants/routes.js +1 -0
  114. package/server/lib/assistants/service.js +302 -99
  115. package/server/lib/assistants/yuri-project.http.test.js +2 -2
  116. package/server/lib/gui-customization/DOCUMENTATION.md +8 -2
  117. package/server/lib/gui-customization/projects-client.mjs +10 -8
  118. package/server/lib/gui-customization/projects-remote.js +101 -0
  119. package/server/lib/gui-customization/projects-remote.test.js +125 -0
  120. package/server/lib/gui-customization/projects.js +30 -6
  121. package/server/lib/gui-customization/projects.test.js +66 -1
  122. package/server/lib/gui-customization/session-skill.js +2 -2
  123. package/server/lib/gui-customization/session-skill.test.js +4 -0
  124. package/server/lib/gui-customization/skill/SKILL.md +3 -1
  125. package/server/lib/gui-customization/skill/references/projects.md +30 -3
  126. package/server/lib/gui-customization/skill/references/remote-connections.md +2 -0
  127. package/server/lib/opencode/DOCUMENTATION.md +6 -0
  128. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  129. package/server/lib/opencode/v2-client.js +9 -4
  130. package/server/lib/remote-hosts/DOCUMENTATION.md +52 -0
  131. package/server/lib/remote-hosts/gateway.js +136 -36
  132. package/server/lib/remote-hosts/json-lifecycle.test.js +35 -0
  133. package/server/lib/remote-hosts/routes.js +10 -13
  134. package/server/lib/remote-hosts/routes.test.js +251 -0
  135. package/server/lib/remote-hosts/store.js +17 -3
  136. package/server/lib/remote-hosts/store.test.js +19 -0
  137. package/server/lib/remote-hosts/task-client.js +25 -0
  138. package/server/lib/remote-hosts/task-client.test.js +60 -0
  139. package/server/lib/remote-hosts/transport.js +7 -2
  140. package/server/lib/request-cors.js +1 -1
  141. package/server/lib/request-cors.test.js +1 -0
  142. package/server/lib/scheduled-tasks/session-skill.test.js +33 -2
  143. package/dist/assets/AssistantConversationSurface-BnK_KTBO.js +0 -3
  144. package/dist/assets/AssistantConversationSurface-n9w_Av0k.css +0 -1
  145. package/dist/assets/MobileDetailNavigation-xgwvsQuR.js +0 -1
  146. package/dist/assets/MobileSurface-DmYgZONB.js +0 -2
  147. package/dist/assets/gitApiHttp-DvTBxvX8.js +0 -3
  148. package/dist/assets/insertionBoundaries-DZtQt2Ah.js +0 -1
  149. package/dist/assets/main-BMFY9mtb.js +0 -2
  150. package/dist/assets/miniChat-BbJ0GKpk.js +0 -2
  151. package/dist/assets/mobile-_zUth69Z.js +0 -2
  152. package/dist/assets/prompt-attachment-upload-BNhDXymd.js +0 -1
  153. package/dist/assets/remoteProjectQueries-CkxdZNw4.js +0 -1
  154. package/dist/assets/renderElectronMiniChatApp-pJ59iC34.js +0 -2
  155. package/dist/assets/renderMobileApp-BQFC-gOA.js +0 -29
  156. package/dist/assets/runtimeEndpointReset-BhHWFNvo.js +0 -150
  157. package/dist/assets/scheduledTaskNavigation-BIDtQ4wN.js +0 -1
  158. package/dist/assets/sessionLookup-RcyTTDOy.js +0 -1
  159. package/dist/assets/useDesktopWindowControlsLayout-KH4UP7Gj.js +0 -1
  160. /package/dist/assets/{sessionLookup-8C8nv-EP.css → reference-history-8C8nv-EP.css} +0 -0
@@ -0,0 +1,378 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { createAssistantsService } from './service.js';
7
+ import { createAssistantExecutionAccessor, parseExecutionTarget } from './execution-target.js';
8
+ import { createOpenCodeContactTools } from './opencode-tools.js';
9
+ import { configureServerOpenCodeFetchGate } from '../opencode/server-opencode-fetch.js';
10
+ import { createSessionCardPart, contactCardIdentity } from './cards.js';
11
+ import { runContactTurn as nativeRunContactTurn } from './harness.js';
12
+
13
+ vi.mock('../opencode/native-goal.js', () => ({ getNativeSessionGoal: async () => null }));
14
+ const require = createRequire(import.meta.url);
15
+ const target = (hostId = 'remote-a') => ({ hubId: 'hub', hostId, instanceId: `instance-${hostId}` });
16
+ const remoteDirectory = '/remote-only/same/project';
17
+ const fixture = ({ nativeCompletion, sessionIDs = ['ses_same'] } = {}) => {
18
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'assistant-remote-'));
19
+ const requests = [];
20
+ const leases = new Set();
21
+ const busy = new Map([['remote-a', true], ['remote-b', true]]);
22
+ const deliveries = new Map();
23
+ let unavailable = false;
24
+ let retargeted = false;
25
+ const gateway = {
26
+ store: { hubId: 'hub' },
27
+ list: async () => ({ hubId: 'hub', hosts: [{ id: 'remote-a', name: 'Machine A' }, { id: 'remote-b', name: 'Machine B' }], projects: [] }),
28
+ acquireTask: vi.fn(async (hostId, options = {}) => {
29
+ if (unavailable || retargeted || (options.instanceId && options.instanceId !== target(hostId).instanceId)) throw new Error('remote unavailable');
30
+ const lease = { target: target(hostId), options, released: false,
31
+ release() { lease.released = true; leases.delete(lease); },
32
+ async json(route, init = {}) {
33
+ if (unavailable) throw new Error('offline');
34
+ requests.push({ hostId, route, method: init.method || 'GET', body: init.body });
35
+ if (route === '/api/projects') return { projects: [{ id: 'project', path: remoteDirectory, label: `Project ${hostId}` }] };
36
+ if (route.startsWith('/api/git/worktrees')) return [];
37
+ if (route === '/api/yuri/session-index') return { directories: [{ directory: remoteDirectory, sessions: [{ id: 'ses_same', title: hostId, time: { updated: 10 } }] }] };
38
+ if (route.endsWith('/archive')) return { session: { id: 'ses_same' } };
39
+ throw new Error(`Unexpected Yuri route: ${route}`);
40
+ },
41
+ async request(route, init) {
42
+ if (unavailable) throw new Error('offline');
43
+ const bodyText = init.body ? Buffer.from(init.body).toString() : '';
44
+ const body = bodyText ? JSON.parse(bodyText) : undefined;
45
+ requests.push({ hostId, route, method: init.method, body, signal: init.signal, headers: new Headers(init.headers) });
46
+ const url = new URL(route, 'http://remote.invalid');
47
+ if (url.pathname === '/api/provider') return Response.json({ data: [{ id: hostId, name: hostId }] });
48
+ if (url.pathname === '/api/model') return Response.json({ data: [{ id: 'remote-model', providerID: hostId, capabilities: { input: { image: true } } }] });
49
+ if (url.pathname.endsWith('/model') && init.method === 'POST') return new Response(null, { status: 204 });
50
+ if (url.pathname === '/api/session/active') return Response.json({ data: busy.get(hostId) ? Object.fromEntries(sessionIDs.map((id) => [id, { type: 'running' }])) : {} });
51
+ if (url.pathname === '/api/session' && init.method === 'GET') return Response.json({ data: [{ id: 'ses_same', title: hostId, location: { directory: remoteDirectory }, time: { updated: 10 } }], cursor: {} });
52
+ if (url.pathname === '/api/session' && init.method === 'POST') return Response.json({ data: { id: 'ses_same', location: { directory: remoteDirectory } } });
53
+ if (url.pathname.endsWith('/prompt')) {
54
+ deliveries.set(hostId, body.id);
55
+ return Response.json({ data: { id: body.id || 'input', type: 'user' } });
56
+ }
57
+ if (url.pathname.endsWith('/interrupt')) { busy.set(hostId, false); return Response.json({}); }
58
+ if (url.pathname.endsWith('/message')) return Response.json({ data: [
59
+ ...(deliveries.get(hostId) ? [{ id: deliveries.get(hostId), type: 'user', time: { created: 1 }, content: [{ type: 'text', text: 'Task' }] }] : []),
60
+ { id: 'msg_worker', type: 'assistant', sessionID: 'ses_same', finish: 'stop', time: { created: 2, ...(busy.get(hostId) ? {} : { completed: 3 }) }, content: [
61
+ { type: 'text', text: `Authored worker finding ${hostId}` },
62
+ { type: 'tool', name: 'read', id: 'tool', state: { status: 'completed', output: `RAW_REMOTE_TOOL_SENTINEL_${hostId}` } },
63
+ ] },
64
+ ], cursor: {} });
65
+ if (url.pathname === '/api/session/ses_same' && init.method === 'DELETE') return new Response(null, { status: 204 });
66
+ if (sessionIDs.some((id) => url.pathname === `/api/session/${id}`)) return Response.json({ data: { id: url.pathname.split('/').at(-1), title: hostId, location: { directory: remoteDirectory }, status: { type: busy.get(hostId) ? 'busy' : 'idle' } } });
67
+ if (url.pathname === '/api/skill') return Response.json({ location: { directory: remoteDirectory }, data: [{ id: 'remote-skill', name: hostId, content: `Instructions ${hostId}` }] });
68
+ throw new Error(`Unexpected SDK route: ${init.method} ${route}`);
69
+ },
70
+ };
71
+ leases.add(lease);
72
+ options.signal?.addEventListener('abort', () => lease.release(), { once: true });
73
+ return lease;
74
+ }),
75
+ };
76
+ let action = async () => {};
77
+ const reviews = [];
78
+ let failReview = false;
79
+ const localClient = vi.fn(() => { throw new Error('LOCAL_CLIENT_MUST_NOT_BE_USED'); });
80
+ let service;
81
+ const open = () => {
82
+ service = createAssistantsService({
83
+ dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
84
+ getAllowedRoots: () => [], listProjects: async () => [], remoteHostGateway: gateway,
85
+ clientFactory: localClient, reconcileIntervalMs: 100000,
86
+ createChatCompletion: nativeCompletion || null,
87
+ runContactTurn: nativeCompletion ? nativeRunContactTurn : async ({ tools, readOnly, userText }) => {
88
+ if (readOnly) {
89
+ reviews.push(userText);
90
+ if (failReview) throw new Error('Synthetic provider failure');
91
+ return { bubbles: ['任务结果已核对。'] };
92
+ }
93
+ await action((name, params) => tools.find((tool) => tool.name === name).execute(`call_${name}`, params));
94
+ return { bubbles: ['已处理请求。'] };
95
+ },
96
+ });
97
+ return service;
98
+ };
99
+ open();
100
+ const assistant = service.createAssistant({ name: 'Hub Assistant', providerID: 'hub-only-provider', modelID: 'hub-only-model' });
101
+ let turn = 0;
102
+ return {
103
+ directory, gateway, requests, leases, busy, localClient, reviews, assistant,
104
+ get service() { return service; },
105
+ async send(next, assistantID = assistant.id) {
106
+ action = next;
107
+ const sent = await service.send(assistantID, { messageID: `user_${++turn}`, text: '执行已授权项目请求' });
108
+ const settled = await service.whenContactTurnSettled(sent.messageID);
109
+ expect(settled, JSON.stringify(settled)).toMatchObject({ status: 'complete' });
110
+ return settled;
111
+ },
112
+ async emit(hostId, type = 'session.execution.succeeded', data = {}) {
113
+ for (const lease of [...leases]) if (lease.target.hostId === hostId && lease.options.onEvent) lease.options.onEvent({ payload: { type, data: { sessionID: 'ses_same', ...data } } });
114
+ await service.reconcile();
115
+ },
116
+ offline(value) { unavailable = value; }, retarget(value) { retargeted = value; }, failReview(value) { failReview = value; },
117
+ reopen() { service.close(); return open(); },
118
+ db() { return new (require('better-sqlite3'))(path.join(directory, 'assistants.sqlite')); },
119
+ close() { service.close(); fs.rmSync(directory, { recursive: true, force: true }); },
120
+ };
121
+ };
122
+
123
+ describe('Hub assistant remote execution', () => {
124
+ it.each([{ sessionIDs: ['ses_same'] }, { sessionIDs: Array.from({ length: 20 }, (_, i) => `ses_worker_${i}`) }])('shares one authority snapshot for 20 contacts during reconciliation (%j)', async ({ sessionIDs }) => {
125
+ const f = fixture({ sessionIDs });
126
+ try {
127
+ for (let i = 0; i < 20; i++) {
128
+ const assistant = f.service.createAssistant({ name: `Watcher ${i}`, providerID: 'hub-only-provider', modelID: 'hub-only-model' });
129
+ await f.send((call) => call('watch_session', { sessionID: sessionIDs[i % sessionIDs.length], target: target() }), assistant.id);
130
+ }
131
+ await f.service.reconcile();
132
+ f.requests.length = 0;
133
+ await f.service.reconcile();
134
+ expect(f.requests.filter((request) => request.route === '/api/session/active')).toHaveLength(1);
135
+ expect(f.requests.filter((request) => sessionIDs.some((id) => request.route === `/api/session/${id}`))).toHaveLength(sessionIDs.length);
136
+ expect(f.requests.some((request) => request.route.endsWith('/message'))).toBe(false);
137
+ expect([...f.leases].filter((lease) => lease.options.onEvent)).toHaveLength(sessionIDs.length);
138
+ } finally { f.close(); }
139
+ });
140
+ it('runs native Agent discovery/read/continue/reference end to end with the exact target and no raw result storage', async () => {
141
+ let round = 0;
142
+ const nativeCall = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [
143
+ { id: `call_${round}`, type: 'function', function: { name, arguments: JSON.stringify(args) } },
144
+ ] } }] } });
145
+ const f = fixture({ nativeCompletion: async ({ body }) => {
146
+ round++;
147
+ if (round === 1) return nativeCall('list_projects', {});
148
+ if (round === 2) {
149
+ expect(JSON.stringify(body.messages)).toContain('instance-remote-a');
150
+ return nativeCall('read_session', { sessionID: 'ses_same', target: target() });
151
+ }
152
+ if (round === 3) {
153
+ expect(JSON.stringify(body.messages)).toContain('RAW_REMOTE_TOOL_SENTINEL_remote-a');
154
+ return nativeCall('assign_session', { sessionID: 'ses_same', target: target(), prompt: 'Continue remote work' });
155
+ }
156
+ if (round === 4) {
157
+ expect(body.tools.map((tool) => tool.function.name)).toEqual(['reference_resource']);
158
+ expect(JSON.stringify(body.messages)).toContain('instance-remote-a');
159
+ return nativeCall('reference_resource', { cardType: 'session', sessionID: 'ses_same', target: target() });
160
+ }
161
+ return { text: '已在目标机器继续处理。' };
162
+ } });
163
+ try {
164
+ await f.send();
165
+ expect(round).toBe(5);
166
+ const messages = f.service.contactMessages(f.assistant.id).messages;
167
+ expect(messages.flatMap((row) => row.cards)).toEqual([expect.objectContaining({ target: target(), sessionID: 'ses_same' })]);
168
+ expect(JSON.stringify(messages)).not.toContain('RAW_REMOTE_TOOL_SENTINEL');
169
+ expect(f.localClient).not.toHaveBeenCalled();
170
+ } finally { f.close(); }
171
+ });
172
+
173
+ it('discovers, lists and reads two machines with identical IDs without local access or raw tool persistence', async () => {
174
+ const f = fixture();
175
+ try {
176
+ await f.send(async (call) => {
177
+ const found = await call('list_projects', {});
178
+ expect(found.details.projects.map((item) => item.target)).toEqual([target(), target('remote-b')]);
179
+ for (const identity of [target(), target('remote-b')]) {
180
+ const listed = await call('list_sessions', { target: identity, projectID: 'project' });
181
+ expect(listed.details.sessions).toEqual([expect.objectContaining({ sessionID: 'ses_same', target: identity, title: identity.hostId })]);
182
+ const read = await call('read_session', { sessionID: 'ses_same', target: identity });
183
+ expect(read.details, JSON.stringify({ read, requests: f.requests })).toMatchObject({ target: identity, directory: remoteDirectory });
184
+ expect(read.content[0].text).toContain(`RAW_REMOTE_TOOL_SENTINEL_${identity.hostId}`);
185
+ const card = await call('reference_resource', { cardType: 'session', sessionID: 'ses_same', target: identity });
186
+ expect(card.details.card.target).toEqual(identity);
187
+ }
188
+ });
189
+ const cards = f.service.contactMessages(f.assistant.id).messages.flatMap((row) => row.cards);
190
+ expect(cards).toHaveLength(2);
191
+ expect(contactCardIdentity(cards[0])).not.toBe(contactCardIdentity(cards[1]));
192
+ expect(f.leases.size).toBe(0);
193
+ expect(f.localClient).not.toHaveBeenCalled();
194
+ const db = f.db();
195
+ try { expect(JSON.stringify(db.prepare('SELECT * FROM assistant_contact_part').all())).not.toContain('RAW_REMOTE_TOOL_SENTINEL'); }
196
+ finally { db.close(); }
197
+ f.reopen();
198
+ expect(f.service.contactMessages(f.assistant.id).messages.flatMap((row) => row.cards)).toEqual(cards);
199
+ } finally { f.close(); }
200
+ });
201
+
202
+ it('creates and continues with target-owned defaults, persists scoped watches, recovers without UI and reports once', async () => {
203
+ const f = fixture();
204
+ try {
205
+ for (const identity of [target(), target('remote-b')]) await f.send(async (call) => {
206
+ const result = await call('assign_session', { target: identity, projectPath: remoteDirectory, prompt: 'Perform task' });
207
+ expect(result.details.assigned, JSON.stringify({ result, requests: f.requests })).toMatchObject({ sessionID: 'ses_same', target: identity });
208
+ });
209
+ expect(f.requests.filter((row) => row.route.endsWith('/prompt'))).toHaveLength(2);
210
+ expect(f.requests.some((row) => row.route.includes('/model') || row.route.includes('/agent'))).toBe(false);
211
+ expect(JSON.stringify(f.requests)).not.toContain('hub-only');
212
+ expect([...f.leases].filter((lease) => lease.options.onEvent)).toHaveLength(2);
213
+ expect(f.service.snapshot().assistants[0].assignedSessions).toEqual(expect.arrayContaining([
214
+ expect.objectContaining({ target: target() }), expect.objectContaining({ target: target('remote-b') }),
215
+ ]));
216
+ // Existing contact semantics: a new user turn supersedes older result
217
+ // notifications. Explicitly rewatch A to request its eventual result again.
218
+ await f.send(async (call) => {
219
+ expect((await call('watch_session', { target: target(), sessionID: 'ses_same' })).details.watched.target).toEqual(target());
220
+ });
221
+ f.reopen();
222
+ await f.service.reconcile();
223
+ expect([...f.leases].filter((lease) => lease.options.onEvent)).toHaveLength(2);
224
+ f.busy.set('remote-a', false);
225
+ await f.emit('remote-a');
226
+ await vi.waitFor(() => expect(f.reviews).toHaveLength(1));
227
+ await vi.waitFor(() => expect([...f.leases].filter((lease) => lease.options.onEvent)).toHaveLength(1));
228
+ expect(f.reviews[0]).toContain(JSON.stringify(target()));
229
+ expect(f.reviews[0]).not.toContain('RAW_REMOTE_TOOL_SENTINEL');
230
+ await f.service.reconcile();
231
+ expect(f.reviews).toHaveLength(1);
232
+ await f.send(async (call) => {
233
+ const stopped = await call('stop_session', { target: target('remote-b'), sessionID: 'ses_same' });
234
+ expect(stopped.details.stopped).toMatchObject({ target: target('remote-b'), aborted: true });
235
+ });
236
+ expect([...f.leases].filter((lease) => lease.options.onEvent)).toHaveLength(0);
237
+ f.busy.set('remote-a', true);
238
+ await f.send(async (call) => {
239
+ const result = await call('assign_session', { target: target(), sessionID: 'ses_same', prompt: 'Continue task' });
240
+ expect(result.details.assigned).toMatchObject({ target: target(), reused: true });
241
+ });
242
+ f.service.close();
243
+ expect(f.leases.size).toBe(0);
244
+ expect(f.localClient).not.toHaveBeenCalled();
245
+ } finally { f.close(); }
246
+ });
247
+
248
+ it('routes watch/steer/archive/delete to the captured machine and rejects malformed or retargeted references', async () => {
249
+ const f = fixture();
250
+ try {
251
+ await f.send(async (call) => {
252
+ const result = await call('watch_session', { target: target(), sessionID: 'ses_same' });
253
+ expect(result.details.watched, JSON.stringify(result)).toMatchObject({ target: target() });
254
+ });
255
+ for (const name of ['steer_session', 'archive_session', 'delete_session']) await f.send(async (call) => {
256
+ const output = await call(name, { target: target(), sessionID: 'ses_same', ...(name === 'steer_session' ? { text: 'Change direction' } : {}) });
257
+ expect(output.details.result, JSON.stringify(output)).toMatchObject({ target: target(), operation: name.replace('_session', '') });
258
+ });
259
+ const count = f.requests.length;
260
+ for (const invalid of [null, {}, { hubId: 'hub', hostId: 'remote-a' }, { ...target(), extra: 'invalid' }]) await f.send(async (call) => {
261
+ const output = await call('read_session', { target: invalid, sessionID: 'ses_same' });
262
+ expect(output.details.error).toBe('validation_error');
263
+ });
264
+ f.retarget(true);
265
+ await f.send(async (call) => {
266
+ const output = await call('delete_session', { target: target(), sessionID: 'ses_same' });
267
+ expect(output.details.error).toBeDefined();
268
+ });
269
+ expect(f.requests).toHaveLength(count);
270
+ expect(f.localClient).not.toHaveBeenCalled();
271
+ } finally { f.close(); }
272
+ });
273
+
274
+ it('validates explicit worker models against only the target catalog and never changes the Hub contact', async () => {
275
+ const f = fixture();
276
+ try {
277
+ await f.send(async (call) => {
278
+ const listed = await call('list_models', { target: target('remote-b') });
279
+ expect(listed.content[0].text).toContain('remote-b');
280
+ expect(listed.content[0].text).not.toContain('hub-only-provider');
281
+ const assigned = await call('assign_session', { target: target('remote-b'), projectPath: remoteDirectory, providerID: 'remote-b', modelID: 'remote-model', prompt: 'Work with the remote model' });
282
+ expect(assigned.details.assigned, JSON.stringify(assigned)).toMatchObject({ target: target('remote-b') });
283
+ });
284
+ expect(f.requests.find((request) => request.method === 'POST' && request.route.endsWith('/model'))).toMatchObject({ hostId: 'remote-b', body: { model: { id: 'remote-model', providerID: 'remote-b' } } });
285
+ expect(f.service.snapshot().assistants[0]).toMatchObject({ providerID: 'hub-only-provider', modelID: 'hub-only-model' });
286
+ await f.send(async (call) => {
287
+ const rejected = await call('assign_session', { target: target(), projectPath: remoteDirectory, providerID: 'remote-b', modelID: 'remote-model', prompt: 'Do not borrow another Host model' });
288
+ expect(rejected.details.error).toBe('model_not_found');
289
+ });
290
+ expect(f.requests.filter((request) => request.method === 'POST' && request.route === '/api/session')).toHaveLength(1);
291
+ } finally { f.close(); }
292
+ });
293
+
294
+ it('keeps offline watches and failed terminal reviews recoverable across restart without replaying assignment', async () => {
295
+ const f = fixture();
296
+ try {
297
+ await f.send((call) => call('assign_session', { target: target(), projectPath: remoteDirectory, prompt: 'Run once' }));
298
+ f.offline(true);
299
+ await f.service.reconcile();
300
+ expect(f.service.snapshot().assistants[0].assignedSessions).toHaveLength(1);
301
+ expect(f.reviews).toHaveLength(0);
302
+ f.offline(false); f.busy.set('remote-a', false); f.failReview(true);
303
+ await f.emit('remote-a');
304
+ await vi.waitFor(() => expect(f.reviews.length).toBeGreaterThan(0));
305
+ f.reopen(); f.failReview(false);
306
+ await f.service.reconcile();
307
+ await vi.waitFor(() => expect(f.service.contactMessages(f.assistant.id).messages.some((row) => row.text === '任务结果已核对。')).toBe(true));
308
+ const db = f.db();
309
+ try {
310
+ expect(db.prepare('SELECT remote_resume_pending FROM assistant_contact_watch').get().remote_resume_pending).toBe(0);
311
+ expect(JSON.stringify(db.prepare('SELECT * FROM assistant_contact_part').all())).not.toContain('RAW_REMOTE_TOOL_SENTINEL');
312
+ } finally { db.close(); }
313
+ expect(f.requests.filter((row) => row.route.endsWith('/prompt'))).toHaveLength(1);
314
+ } finally { f.close(); }
315
+ });
316
+
317
+ it('ignores 50 unrelated session events and settles native manual interruption without waiting for a terminal message', async () => {
318
+ const f = fixture();
319
+ try {
320
+ await f.send((call) => call('watch_session', { target: target(), sessionID: 'ses_same' }));
321
+ await f.service.reconcile();
322
+ const before = f.requests.length;
323
+ const watchers = [...f.leases].filter((lease) => lease.options.onEvent);
324
+ for (let index = 0; index < 50; index++) for (const lease of watchers) lease.options.onEvent({ payload: { type: 'session.execution.started', data: { sessionID: 'ses_unrelated' } } });
325
+ await Promise.resolve();
326
+ expect(f.requests).toHaveLength(before);
327
+ await f.emit('remote-a', 'session.execution.interrupted', { reason: 'user' });
328
+ await vi.waitFor(() => expect(f.reviews).toHaveLength(1));
329
+ expect(f.reviews[0]).toContain('status: cancelled');
330
+ expect(f.reviews[0]).toContain('reason: user_interrupted');
331
+ expect([...f.leases].filter((lease) => lease.options.onEvent)).toHaveLength(0);
332
+ } finally { f.close(); }
333
+ });
334
+
335
+ it('reports one unavailable discovery independently and never stats remote directories on the Hub', async () => {
336
+ const f = fixture();
337
+ const original = f.gateway.acquireTask.getMockImplementation();
338
+ f.gateway.acquireTask.mockImplementation((hostId, options) => hostId === 'remote-a' ? Promise.reject(new Error('offline')) : original(hostId, options));
339
+ const realpath = vi.spyOn(fs, 'realpathSync');
340
+ try {
341
+ await f.send(async (call) => {
342
+ const projects = await call('list_projects', {});
343
+ expect(projects.details).toMatchObject({ partial: true, failed: [{ hostId: 'remote-a' }], projects: [{ target: target('remote-b') }] });
344
+ await call('list_sessions', { target: target('remote-b') });
345
+ await call('read_session', { target: target('remote-b'), sessionID: 'ses_same' });
346
+ });
347
+ expect(realpath.mock.calls.some(([value]) => typeof value === 'string' && value.startsWith('/remote-only'))).toBe(false);
348
+ expect(f.localClient).not.toHaveBeenCalled();
349
+ } finally { realpath.mockRestore(); f.close(); }
350
+ });
351
+
352
+ it('preserves official SDK request body/signal and delegates admission to the target proxy, not the Hub gate', async () => {
353
+ const f = fixture();
354
+ configureServerOpenCodeFetchGate(() => ({ executionAllowed: false }));
355
+ try {
356
+ const accessor = createAssistantExecutionAccessor(f.gateway);
357
+ const controller = new AbortController();
358
+ await accessor.run({ target: target(), signal: controller.signal }, async () => {
359
+ await accessor.current().api.session.prompt({ sessionID: 'ses_same', text: 'exact body', delivery: 'steer' }, { signal: controller.signal });
360
+ });
361
+ const request = f.requests.find((row) => row.route.endsWith('/prompt'));
362
+ expect(request).toMatchObject({ method: 'POST', body: { text: 'exact body', delivery: 'steer' } });
363
+ expect(request.headers.get('content-type')).toContain('application/json');
364
+ expect(request.signal).toBeInstanceOf(AbortSignal);
365
+ expect(f.leases.size).toBe(0);
366
+ const tools = createOpenCodeContactTools({ resolveClient: f.localClient, acquireExecution: accessor.acquire, directory: '/hub-only' });
367
+ const read = await tools.find((tool) => tool.name === 'read_opencode_skill').execute('skill', { target: target('remote-b'), directory: remoteDirectory, id: 'remote-skill' });
368
+ expect(read.details).toMatchObject({ target: target('remote-b'), content: 'Instructions remote-b' });
369
+ expect(f.requests.at(-1).route).not.toContain('hub-only');
370
+ expect(f.localClient).not.toHaveBeenCalled();
371
+ } finally { configureServerOpenCodeFetchGate(null, { allowMissingContract: true }); f.close(); }
372
+ });
373
+
374
+ it.each([null, {}, { hubId: 'hub', hostId: 'remote-a' }, { ...target(), instanceId: '' }])('rejects malformed card targets: %j', (invalid) => {
375
+ expect(() => parseExecutionTarget(invalid)).toThrow();
376
+ expect(() => createSessionCardPart({ sessionID: 'ses_same', directory: remoteDirectory, target: invalid })).toThrow();
377
+ });
378
+ });
@@ -0,0 +1,43 @@
1
+ import { executionTargetKey } from './execution-target.js';
2
+
3
+ /** Coalesce one machine's watch demand, without caching authority or message bodies. */
4
+ export function createRemoteWatchReconciler(readBatch) {
5
+ const hosts = new Map();
6
+ let closed = false;
7
+ return {
8
+ reconcile(watch, changed = false) {
9
+ if (closed) return Promise.resolve();
10
+ const key = executionTargetKey(watch.target);
11
+ let host = hosts.get(key);
12
+ if (!host) {
13
+ host = { pending: new Map(), reading: new Set(), flight: null };
14
+ hosts.set(key, host);
15
+ }
16
+ if (changed || !host.reading.has(watch.sessionID)) host.pending.set(watch.sessionID, watch);
17
+ if (!host.flight) {
18
+ host.flight = Promise.resolve().then(async () => {
19
+ try {
20
+ while (!closed && host.pending.size) {
21
+ const batch = [...host.pending.values()];
22
+ host.pending.clear();
23
+ host.reading = new Set(batch.map((item) => item.sessionID));
24
+ try { await readBatch(batch, (watch) => !closed && !host.pending.has(watch.sessionID)); }
25
+ catch { /* Durable watches remain pending for the next event or reconciliation. */ }
26
+ finally { host.reading.clear(); }
27
+ }
28
+ } finally { hosts.delete(key); }
29
+ });
30
+ }
31
+ return host.flight;
32
+ },
33
+ invalidate(watch) {
34
+ const host = hosts.get(executionTargetKey(watch.target));
35
+ if (!closed && host?.reading.has(watch.sessionID)) host.pending.set(watch.sessionID, watch);
36
+ },
37
+ close() {
38
+ closed = true;
39
+ for (const host of hosts.values()) host.pending.clear();
40
+ hosts.clear();
41
+ },
42
+ };
43
+ }
@@ -0,0 +1,88 @@
1
+ import { expect, it, vi } from 'vitest';
2
+ import { createRemoteWatchReconciler } from './remote-watch-reconciler.js';
3
+
4
+ const watch = (id, hostId = 'host') => ({ sessionID: id, target: { hubId: 'hub', hostId, instanceId: `instance-${hostId}` } });
5
+ const deferred = () => {
6
+ let resolve;
7
+ const promise = new Promise((done) => { resolve = done; });
8
+ return { promise, resolve };
9
+ };
10
+
11
+ it('coalesces 50 workers and 50 in-flight tips into one initial and one trailing batch', async () => {
12
+ const entered = deferred(), finish = deferred();
13
+ let current;
14
+ const read = vi.fn(async (_batch, isCurrent) => {
15
+ current = isCurrent;
16
+ if (read.mock.calls.length === 1) { entered.resolve(); await finish.promise; }
17
+ });
18
+ const scheduler = createRemoteWatchReconciler(read);
19
+ const workers = Array.from({ length: 50 }, (_, i) => watch(`session-${i}`));
20
+ const pending = workers.map((worker) => scheduler.reconcile(worker));
21
+ await entered.promise;
22
+ expect(read).toHaveBeenCalledTimes(1);
23
+ expect(read.mock.calls[0][0]).toHaveLength(50);
24
+ for (let i = 0; i < 50; i++) scheduler.reconcile(workers[0], true);
25
+ expect(current(workers[0])).toBe(false);
26
+ expect(current(workers[1])).toBe(true);
27
+ finish.resolve();
28
+ await Promise.all(pending);
29
+ expect(read).toHaveBeenCalledTimes(2);
30
+ expect(read.mock.calls[1][0]).toEqual([workers[0]]);
31
+ await scheduler.reconcile(workers[0]);
32
+ expect(read).toHaveBeenCalledTimes(3);
33
+ scheduler.close();
34
+ });
35
+
36
+ it('ordinary concurrent demand shares in-flight work; a new running event fences the older read', async () => {
37
+ const entered = deferred(), finish = deferred();
38
+ const worker = watch('same');
39
+ let current;
40
+ const read = vi.fn(async (_batch, isCurrent) => {
41
+ current = isCurrent;
42
+ if (read.mock.calls.length === 1) { entered.resolve(); await finish.promise; }
43
+ });
44
+ const scheduler = createRemoteWatchReconciler(read);
45
+ scheduler.invalidate(worker);
46
+ expect(read).not.toHaveBeenCalled();
47
+ const first = scheduler.reconcile(worker);
48
+ await entered.promise;
49
+ for (let i = 0; i < 50; i++) expect(scheduler.reconcile(worker)).toBe(first);
50
+ expect(current(worker)).toBe(true);
51
+ scheduler.invalidate(worker);
52
+ expect(current(worker)).toBe(false);
53
+ finish.resolve(); await first;
54
+ expect(read).toHaveBeenCalledTimes(2);
55
+ });
56
+
57
+ it('isolates equal session IDs across hosts and does not let a failed/blocked host stop its sibling', async () => {
58
+ const entered = deferred(), finish = deferred();
59
+ const read = vi.fn(async (batch) => {
60
+ if (batch[0].target.hostId === 'a') { entered.resolve(); await finish.promise; throw new Error('offline'); }
61
+ });
62
+ const scheduler = createRemoteWatchReconciler(read);
63
+ const a = scheduler.reconcile(watch('same', 'a'));
64
+ await entered.promise;
65
+ await scheduler.reconcile(watch('same', 'b'));
66
+ expect(read).toHaveBeenCalledTimes(2);
67
+ finish.resolve(); await a;
68
+ await scheduler.reconcile(watch('same', 'a'));
69
+ expect(read).toHaveBeenCalledTimes(3);
70
+ scheduler.close();
71
+ await scheduler.reconcile(watch('same'));
72
+ expect(read).toHaveBeenCalledTimes(3);
73
+ });
74
+
75
+ it('shutdown invalidates an in-flight result and drops queued rereads', async () => {
76
+ const entered = deferred(), finish = deferred();
77
+ let current;
78
+ const read = vi.fn(async (_batch, isCurrent) => { current = isCurrent; entered.resolve(); await finish.promise; });
79
+ const scheduler = createRemoteWatchReconciler(read);
80
+ const worker = watch('same');
81
+ const pending = scheduler.reconcile(worker);
82
+ await entered.promise;
83
+ scheduler.reconcile(worker, true);
84
+ scheduler.close();
85
+ expect(current(worker)).toBe(false);
86
+ finish.resolve(); await pending;
87
+ expect(read).toHaveBeenCalledTimes(1);
88
+ });
@@ -36,6 +36,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
36
36
  getServerId: dependencies.getServerId,
37
37
  getAllowedRoots: dependencies.getAllowedRoots,
38
38
  listProjects: dependencies.listProjects,
39
+ remoteHostGateway: dependencies.remoteHostGateway,
39
40
  registerProject: dependencies.registerProject,
40
41
  readModelPreferences: dependencies.readModelPreferences,
41
42
  listScheduledTasks: dependencies.listScheduledTasks,