@agent-native/dispatch 0.43.0-nightly-20261120212328 → 0.43.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.
Files changed (296) hide show
  1. package/CHANGELOG.md +194 -174
  2. package/dist/actions/ask_app.d.ts +3 -0
  3. package/dist/actions/ask_app.js +7 -2
  4. package/dist/actions/ask_app.js.map +1 -1
  5. package/dist/actions/ask_app_status.d.ts +3 -0
  6. package/dist/actions/ask_app_status.js +5 -1
  7. package/dist/actions/ask_app_status.js.map +1 -1
  8. package/dist/actions/call_app_action.d.ts +1 -0
  9. package/dist/actions/call_app_action.js +21 -5
  10. package/dist/actions/call_app_action.js.map +1 -1
  11. package/dist/actions/create_embed_session.d.ts +3 -2
  12. package/dist/actions/create_embed_session.js +4 -2
  13. package/dist/actions/create_embed_session.js.map +1 -1
  14. package/dist/actions/create_workspace_app_embed_session.d.ts +3 -2
  15. package/dist/actions/create_workspace_app_embed_session.js +3 -1
  16. package/dist/actions/create_workspace_app_embed_session.js.map +1 -1
  17. package/dist/actions/delete-destination.d.ts +12 -12
  18. package/dist/actions/execute-action-suggestion.d.ts +44 -0
  19. package/dist/actions/execute-action-suggestion.d.ts.map +1 -0
  20. package/dist/actions/execute-action-suggestion.js +148 -0
  21. package/dist/actions/execute-action-suggestion.js.map +1 -0
  22. package/dist/actions/import-agent.d.ts +13 -13
  23. package/dist/actions/index.d.ts.map +1 -1
  24. package/dist/actions/index.js +5 -1
  25. package/dist/actions/index.js.map +1 -1
  26. package/dist/actions/list-connected-agents.js +3 -2
  27. package/dist/actions/list-connected-agents.js.map +1 -1
  28. package/dist/actions/list-workspace-connections.d.ts +1 -0
  29. package/dist/actions/list-workspace-connections.d.ts.map +1 -1
  30. package/dist/actions/list_app_actions.js +1 -1
  31. package/dist/actions/list_app_actions.js.map +1 -1
  32. package/dist/actions/list_apps.d.ts +2 -0
  33. package/dist/actions/list_apps.js +11 -3
  34. package/dist/actions/list_apps.js.map +1 -1
  35. package/dist/actions/navigate.js +1 -0
  36. package/dist/actions/navigate.js.map +1 -1
  37. package/dist/actions/open_app.d.ts +4 -0
  38. package/dist/actions/open_app.js +14 -6
  39. package/dist/actions/open_app.js.map +1 -1
  40. package/dist/actions/propose-action-suggestions.d.ts +45 -0
  41. package/dist/actions/propose-action-suggestions.d.ts.map +1 -0
  42. package/dist/actions/propose-action-suggestions.js +32 -0
  43. package/dist/actions/propose-action-suggestions.js.map +1 -0
  44. package/dist/actions/provider-api-register.d.ts +12 -12
  45. package/dist/actions/read_view.js +1 -1
  46. package/dist/actions/read_view.js.map +1 -1
  47. package/dist/actions/remember-pointer.js +1 -1
  48. package/dist/actions/remember-pointer.js.map +1 -1
  49. package/dist/actions/resolve-pointer.js +1 -1
  50. package/dist/actions/resolve-pointer.js.map +1 -1
  51. package/dist/actions/route-app-intent.d.ts +6 -0
  52. package/dist/actions/route-app-intent.js +79 -5
  53. package/dist/actions/route-app-intent.js.map +1 -1
  54. package/dist/actions/send-code-agent-remote-command.js +4 -0
  55. package/dist/actions/send-code-agent-remote-command.js.map +1 -1
  56. package/dist/actions/start-workspace-app-creation.js +1 -1
  57. package/dist/actions/start-workspace-app-creation.js.map +1 -1
  58. package/dist/actions/upsert-destination.d.ts +12 -12
  59. package/dist/actions/view-screen.d.ts +12 -1
  60. package/dist/actions/view-screen.js +53 -5
  61. package/dist/actions/view-screen.js.map +1 -1
  62. package/dist/components/chat-action-suggestions.d.ts +8 -0
  63. package/dist/components/chat-action-suggestions.d.ts.map +1 -0
  64. package/dist/components/chat-action-suggestions.js +191 -0
  65. package/dist/components/chat-action-suggestions.js.map +1 -0
  66. package/dist/components/chat-home-apps.d.ts.map +1 -1
  67. package/dist/components/chat-home-apps.js +1 -1
  68. package/dist/components/chat-home-apps.js.map +1 -1
  69. package/dist/components/google-broker-settings-group.d.ts +2 -0
  70. package/dist/components/google-broker-settings-group.d.ts.map +1 -0
  71. package/dist/components/google-broker-settings-group.js +53 -0
  72. package/dist/components/google-broker-settings-group.js.map +1 -0
  73. package/dist/components/layout/Layout.d.ts +4 -1
  74. package/dist/components/layout/Layout.d.ts.map +1 -1
  75. package/dist/components/layout/Layout.js +246 -69
  76. package/dist/components/layout/Layout.js.map +1 -1
  77. package/dist/components/messaging-setup-panel.d.ts.map +1 -1
  78. package/dist/components/messaging-setup-panel.js +47 -15
  79. package/dist/components/messaging-setup-panel.js.map +1 -1
  80. package/dist/components/workspace-app-host.d.ts +27 -4
  81. package/dist/components/workspace-app-host.d.ts.map +1 -1
  82. package/dist/components/workspace-app-host.js +355 -74
  83. package/dist/components/workspace-app-host.js.map +1 -1
  84. package/dist/config.d.ts +5 -0
  85. package/dist/config.d.ts.map +1 -1
  86. package/dist/config.js.map +1 -1
  87. package/dist/db/google-broker-admission.d.ts +36 -0
  88. package/dist/db/google-broker-admission.d.ts.map +1 -0
  89. package/dist/db/google-broker-admission.js +129 -0
  90. package/dist/db/google-broker-admission.js.map +1 -0
  91. package/dist/db/migrations.d.ts +1 -1
  92. package/dist/db/migrations.d.ts.map +1 -1
  93. package/dist/db/migrations.js +42 -0
  94. package/dist/db/migrations.js.map +1 -1
  95. package/dist/lib/action-suggestions.d.ts +20 -0
  96. package/dist/lib/action-suggestions.d.ts.map +1 -0
  97. package/dist/lib/action-suggestions.js +219 -0
  98. package/dist/lib/action-suggestions.js.map +1 -0
  99. package/dist/lib/chat-first-app-route.d.ts +11 -5
  100. package/dist/lib/chat-first-app-route.d.ts.map +1 -1
  101. package/dist/lib/chat-first-app-route.js +9 -5
  102. package/dist/lib/chat-first-app-route.js.map +1 -1
  103. package/dist/lib/chat-first-pane.d.ts +25 -1
  104. package/dist/lib/chat-first-pane.d.ts.map +1 -1
  105. package/dist/lib/chat-first-pane.js +67 -1
  106. package/dist/lib/chat-first-pane.js.map +1 -1
  107. package/dist/lib/data-intent.d.ts +3 -0
  108. package/dist/lib/data-intent.d.ts.map +1 -0
  109. package/dist/lib/data-intent.js +14 -0
  110. package/dist/lib/data-intent.js.map +1 -0
  111. package/dist/lib/dispatch-app-identity.d.ts +10 -0
  112. package/dist/lib/dispatch-app-identity.d.ts.map +1 -0
  113. package/dist/lib/dispatch-app-identity.js +18 -0
  114. package/dist/lib/dispatch-app-identity.js.map +1 -0
  115. package/dist/lib/other-apps.d.ts +15 -0
  116. package/dist/lib/other-apps.d.ts.map +1 -1
  117. package/dist/lib/other-apps.js +31 -0
  118. package/dist/lib/other-apps.js.map +1 -1
  119. package/dist/lib/workspace-app-frame-view.d.ts +15 -0
  120. package/dist/lib/workspace-app-frame-view.d.ts.map +1 -0
  121. package/dist/lib/workspace-app-frame-view.js +72 -0
  122. package/dist/lib/workspace-app-frame-view.js.map +1 -0
  123. package/dist/lib/workspace-apps.d.ts +5 -0
  124. package/dist/lib/workspace-apps.d.ts.map +1 -1
  125. package/dist/lib/workspace-apps.js +85 -23
  126. package/dist/lib/workspace-apps.js.map +1 -1
  127. package/dist/lib/workspace-apps.test.js +6 -0
  128. package/dist/lib/workspace-apps.test.js.map +1 -1
  129. package/dist/routes/pages/_index.d.ts +2 -2
  130. package/dist/routes/pages/chat.d.ts.map +1 -1
  131. package/dist/routes/pages/chat.js +33 -2
  132. package/dist/routes/pages/chat.js.map +1 -1
  133. package/dist/routes/pages/settings-page.d.ts +1 -1
  134. package/dist/routes/pages/settings-page.d.ts.map +1 -1
  135. package/dist/routes/pages/settings-page.js +3 -2
  136. package/dist/routes/pages/settings-page.js.map +1 -1
  137. package/dist/server/index.d.ts +4 -1
  138. package/dist/server/index.d.ts.map +1 -1
  139. package/dist/server/index.js +5 -5
  140. package/dist/server/index.js.map +1 -1
  141. package/dist/server/lib/action-suggestions.d.ts +41 -0
  142. package/dist/server/lib/action-suggestions.d.ts.map +1 -0
  143. package/dist/server/lib/action-suggestions.js +94 -0
  144. package/dist/server/lib/action-suggestions.js.map +1 -0
  145. package/dist/server/lib/app-action-result.d.ts +5 -0
  146. package/dist/server/lib/app-action-result.d.ts.map +1 -1
  147. package/dist/server/lib/app-action-result.js +7 -0
  148. package/dist/server/lib/app-action-result.js.map +1 -1
  149. package/dist/server/lib/app-creation-store.d.ts.map +1 -1
  150. package/dist/server/lib/app-creation-store.js +63 -13
  151. package/dist/server/lib/app-creation-store.js.map +1 -1
  152. package/dist/server/lib/curated-workspace-templates.d.ts.map +1 -1
  153. package/dist/server/lib/curated-workspace-templates.js +3 -0
  154. package/dist/server/lib/curated-workspace-templates.js.map +1 -1
  155. package/dist/server/lib/dispatch-config.d.ts +5 -0
  156. package/dist/server/lib/dispatch-config.d.ts.map +1 -0
  157. package/dist/server/lib/dispatch-config.js +11 -0
  158. package/dist/server/lib/dispatch-config.js.map +1 -0
  159. package/dist/server/lib/dispatch-pane-context.d.ts +11 -0
  160. package/dist/server/lib/dispatch-pane-context.d.ts.map +1 -0
  161. package/dist/server/lib/dispatch-pane-context.js +35 -0
  162. package/dist/server/lib/dispatch-pane-context.js.map +1 -0
  163. package/dist/server/lib/google-broker-provider.d.ts +41 -0
  164. package/dist/server/lib/google-broker-provider.d.ts.map +1 -0
  165. package/dist/server/lib/google-broker-provider.js +96 -0
  166. package/dist/server/lib/google-broker-provider.js.map +1 -0
  167. package/dist/server/lib/google-broker-rpc.d.ts +26 -0
  168. package/dist/server/lib/google-broker-rpc.d.ts.map +1 -0
  169. package/dist/server/lib/google-broker-rpc.js +52 -0
  170. package/dist/server/lib/google-broker-rpc.js.map +1 -0
  171. package/dist/server/lib/hosted-apps-settings.d.ts.map +1 -1
  172. package/dist/server/lib/hosted-apps-settings.js +4 -0
  173. package/dist/server/lib/hosted-apps-settings.js.map +1 -1
  174. package/dist/server/lib/mcp-app-discovery.d.ts +17 -0
  175. package/dist/server/lib/mcp-app-discovery.d.ts.map +1 -0
  176. package/dist/server/lib/mcp-app-discovery.js +231 -0
  177. package/dist/server/lib/mcp-app-discovery.js.map +1 -0
  178. package/dist/server/lib/mcp-gateway.d.ts +64 -21
  179. package/dist/server/lib/mcp-gateway.d.ts.map +1 -1
  180. package/dist/server/lib/mcp-gateway.js +730 -88
  181. package/dist/server/lib/mcp-gateway.js.map +1 -1
  182. package/dist/server/plugins/agent-chat.js +9 -7
  183. package/dist/server/plugins/agent-chat.js.map +1 -1
  184. package/dist/server/plugins/auth.d.ts.map +1 -1
  185. package/dist/server/plugins/auth.js +1 -0
  186. package/dist/server/plugins/auth.js.map +1 -1
  187. package/dist/server/plugins/db.d.ts.map +1 -1
  188. package/dist/server/plugins/db.js +0 -46
  189. package/dist/server/plugins/db.js.map +1 -1
  190. package/dist/server/plugins/integrations.d.ts.map +1 -1
  191. package/dist/server/plugins/integrations.js +4 -1
  192. package/dist/server/plugins/integrations.js.map +1 -1
  193. package/dist/shared/chat-first-pane.d.ts +24 -0
  194. package/dist/shared/chat-first-pane.d.ts.map +1 -1
  195. package/dist/shared/chat-first-pane.js +34 -0
  196. package/dist/shared/chat-first-pane.js.map +1 -1
  197. package/dist/shared/labs.d.ts +1 -0
  198. package/dist/shared/labs.d.ts.map +1 -1
  199. package/dist/shared/labs.js +7 -0
  200. package/dist/shared/labs.js.map +1 -1
  201. package/package.json +7 -6
  202. package/src/actions/action-suggestions.spec.ts +342 -0
  203. package/src/actions/app_actions.spec.ts +103 -0
  204. package/src/actions/ask_app.ts +9 -2
  205. package/src/actions/ask_app_status.ts +12 -1
  206. package/src/actions/call_app_action.ts +28 -8
  207. package/src/actions/create_embed_session.ts +8 -2
  208. package/src/actions/create_workspace_app_embed_session.ts +6 -1
  209. package/src/actions/execute-action-suggestion.ts +177 -0
  210. package/src/actions/index.spec.ts +6 -3
  211. package/src/actions/index.ts +5 -1
  212. package/src/actions/list-connected-agents.spec.ts +26 -1
  213. package/src/actions/list-connected-agents.ts +7 -4
  214. package/src/actions/list_app_actions.ts +1 -1
  215. package/src/actions/list_apps.spec.ts +58 -22
  216. package/src/actions/list_apps.ts +12 -5
  217. package/src/actions/navigate.ts +1 -0
  218. package/src/actions/open_app.spec.ts +17 -1
  219. package/src/actions/open_app.ts +21 -8
  220. package/src/actions/propose-action-suggestions.ts +42 -0
  221. package/src/actions/read_view.ts +1 -1
  222. package/src/actions/remember-pointer.ts +1 -1
  223. package/src/actions/resolve-pointer.ts +1 -1
  224. package/src/actions/route-app-intent.spec.ts +234 -5
  225. package/src/actions/route-app-intent.ts +89 -4
  226. package/src/actions/send-code-agent-remote-command.spec.ts +40 -0
  227. package/src/actions/send-code-agent-remote-command.ts +5 -0
  228. package/src/actions/start-workspace-app-creation.ts +1 -1
  229. package/src/actions/view-screen.bundle.spec.ts +15 -2
  230. package/src/actions/view-screen.spec.ts +81 -3
  231. package/src/actions/view-screen.ts +60 -4
  232. package/src/components/chat-action-suggestions.spec.tsx +362 -0
  233. package/src/components/chat-action-suggestions.tsx +432 -0
  234. package/src/components/chat-home-apps.spec.tsx +19 -0
  235. package/src/components/chat-home-apps.tsx +0 -1
  236. package/src/components/google-broker-settings-group.tsx +186 -0
  237. package/src/components/layout/Layout.spec.tsx +419 -28
  238. package/src/components/layout/Layout.tsx +304 -66
  239. package/src/components/messaging-setup-panel.spec.tsx +278 -4
  240. package/src/components/messaging-setup-panel.tsx +82 -19
  241. package/src/components/workspace-app-card.spec.tsx +79 -10
  242. package/src/components/workspace-app-chat-rail.spec.tsx +81 -3
  243. package/src/components/workspace-app-host.spec.tsx +269 -16
  244. package/src/components/workspace-app-host.tsx +464 -87
  245. package/src/config.ts +5 -0
  246. package/src/db/google-broker-admission.ts +160 -0
  247. package/src/db/migrations.spec.ts +165 -2
  248. package/src/db/migrations.ts +43 -1
  249. package/src/lib/action-suggestions.ts +267 -0
  250. package/src/lib/chat-first-app-route.spec.ts +15 -2
  251. package/src/lib/chat-first-app-route.ts +19 -7
  252. package/src/lib/chat-first-pane.spec.ts +71 -0
  253. package/src/lib/chat-first-pane.ts +101 -4
  254. package/src/lib/data-intent.spec.ts +21 -0
  255. package/src/lib/data-intent.ts +13 -0
  256. package/src/lib/dispatch-app-identity.ts +40 -0
  257. package/src/lib/other-apps.spec.ts +110 -1
  258. package/src/lib/other-apps.ts +41 -0
  259. package/src/lib/workspace-app-frame-view.spec.ts +13 -0
  260. package/src/lib/workspace-app-frame-view.ts +98 -0
  261. package/src/lib/workspace-apps.spec.ts +101 -0
  262. package/src/lib/workspace-apps.test.ts +18 -0
  263. package/src/lib/workspace-apps.ts +102 -24
  264. package/src/routes/pages/chat.spec.tsx +92 -1
  265. package/src/routes/pages/chat.tsx +41 -2
  266. package/src/routes/pages/settings-page.tsx +22 -17
  267. package/src/routes/pages/settings.spec.tsx +4 -0
  268. package/src/server/index.ts +6 -6
  269. package/src/server/lib/action-suggestions.ts +122 -0
  270. package/src/server/lib/app-action-result.ts +8 -0
  271. package/src/server/lib/app-creation-store.spec.ts +251 -0
  272. package/src/server/lib/app-creation-store.ts +72 -12
  273. package/src/server/lib/community-apps.spec.ts +19 -1
  274. package/src/server/lib/curated-workspace-templates.spec.ts +12 -0
  275. package/src/server/lib/curated-workspace-templates.ts +2 -0
  276. package/src/server/lib/dispatch-config.ts +15 -0
  277. package/src/server/lib/dispatch-pane-context.spec.ts +54 -0
  278. package/src/server/lib/dispatch-pane-context.ts +54 -0
  279. package/src/server/lib/google-broker-provider.ts +121 -0
  280. package/src/server/lib/google-broker-rpc.spec.ts +95 -0
  281. package/src/server/lib/google-broker-rpc.ts +107 -0
  282. package/src/server/lib/hosted-apps-settings.ts +4 -0
  283. package/src/server/lib/mcp-app-discovery.ts +318 -0
  284. package/src/server/lib/mcp-gateway.spec.ts +2252 -524
  285. package/src/server/lib/mcp-gateway.ts +1044 -181
  286. package/src/server/plugins/agent-chat.direct-mcp.spec.ts +84 -5
  287. package/src/server/plugins/agent-chat.ts +9 -7
  288. package/src/server/plugins/auth.spec.ts +5 -1
  289. package/src/server/plugins/auth.ts +1 -0
  290. package/src/server/plugins/db.ts +0 -51
  291. package/src/server/plugins/integrations.ts +4 -1
  292. package/src/shared/chat-first-pane.spec.ts +36 -0
  293. package/src/shared/chat-first-pane.ts +55 -0
  294. package/src/shared/labs.ts +8 -0
  295. package/src/server/plugins/agent-chat.spec.ts +0 -206
  296. package/src/server/plugins/integrations.spec.ts +0 -60
@@ -13,6 +13,7 @@ import {
13
13
 
14
14
  const mocks = vi.hoisted(() => ({
15
15
  discoverAgents: vi.fn(),
16
+ directoryStatus: vi.fn(),
16
17
  getBuiltinAgents: vi.fn(() => []),
17
18
  listWorkspaceApps: vi.fn(),
18
19
  getUserSetting: vi.fn(),
@@ -21,11 +22,14 @@ const mocks = vi.hoisted(() => ({
21
22
  buildEmbedStartPath: vi.fn((ticket: string) => {
22
23
  return `/_agent-native/embed/start?ticket=${encodeURIComponent(ticket)}`;
23
24
  }),
25
+ listRemoteServers: vi.fn(),
26
+ getMcpOAuthAccessToken: vi.fn(),
24
27
  managerStart: vi.fn(),
25
28
  managerGetConnectErrorStatus: vi.fn(),
26
29
  managerStop: vi.fn(),
27
30
  managerCallTool: vi.fn(),
28
31
  managerConstructor: vi.fn(),
32
+ resolveChildBrowserTab: vi.fn(),
29
33
  managerHasServer: vi.fn(),
30
34
  managerGetTool: vi.fn(),
31
35
  managerGetToolsForServer: vi.fn(),
@@ -43,9 +47,17 @@ const mocks = vi.hoisted(() => ({
43
47
 
44
48
  vi.mock("@agent-native/core/server/agent-discovery", () => ({
45
49
  discoverAgents: mocks.discoverAgents,
50
+ discoverAgentsWithDirectoryStatus: async (...args: unknown[]) => ({
51
+ agents: await mocks.discoverAgents(...args),
52
+ directory: mocks.directoryStatus(),
53
+ }),
46
54
  getBuiltinAgents: mocks.getBuiltinAgents,
47
55
  }));
48
56
 
57
+ vi.mock("./dispatch-pane-context.js", () => ({
58
+ resolveDispatchChildBrowserTab: mocks.resolveChildBrowserTab,
59
+ }));
60
+
49
61
  vi.mock("./app-creation-store.js", () => ({
50
62
  listWorkspaceApps: mocks.listWorkspaceApps,
51
63
  }));
@@ -110,6 +122,8 @@ vi.mock("@agent-native/core/org", () => ({
110
122
  }));
111
123
 
112
124
  vi.mock("@agent-native/core/mcp-client", () => ({
125
+ listRemoteServers: mocks.listRemoteServers,
126
+ getMcpOAuthAccessToken: mocks.getMcpOAuthAccessToken,
113
127
  mcpToolCallWasNotSent: (error: unknown) =>
114
128
  error instanceof Error && error.name === "NotSentFixture",
115
129
  buildMcpToolName: (serverId: string, toolName: string) =>
@@ -151,19 +165,24 @@ vi.mock("@agent-native/core/mcp-client", () => ({
151
165
 
152
166
  import { runWithRequestContext } from "@agent-native/core/server";
153
167
 
168
+ import askAppStatusAction from "../../actions/ask_app_status.js";
154
169
  import {
170
+ appHomeBaseUrl,
155
171
  callGrantedDispatchMcpAppAction,
172
+ clearGrantedAppManifestCache,
156
173
  createGrantedDispatchMcpEmbedSession,
157
174
  createGrantedDispatchMcpEmbedSessionForWorkspaceAppChat,
158
175
  createWorkspaceSsoEmbedSession,
159
176
  createWorkspaceSsoEmbedSessionForWorkspaceAppChat,
160
177
  askGrantedDispatchMcpApp,
161
178
  getGrantedDispatchMcpAppTask,
179
+ joinAppBaseUrlAndPath,
162
180
  listDispatchMcpApps,
163
181
  listGrantedDispatchMcpAppActions,
164
182
  listGrantedDispatchMcpApps,
165
183
  listGrantedDispatchMcpAppOrigins,
166
184
  openGrantedDispatchMcpApp,
185
+ registerGrantedAppManifest,
167
186
  resolveGrantedDispatchMcpApp,
168
187
  setDispatchAppActionHeaderProvider,
169
188
  } from "./mcp-gateway.js";
@@ -203,6 +222,7 @@ beforeEach(() => {
203
222
  mocks.signA2AOrgMemberDelegationToken.mockReset();
204
223
  mocks.signA2AToken.mockReset();
205
224
  mocks.discoverAgents.mockResolvedValue([analyticsAgent]);
225
+ mocks.directoryStatus.mockReturnValue({ status: "available" });
206
226
  mocks.getBuiltinAgents.mockReturnValue([]);
207
227
  mocks.listWorkspaceApps.mockResolvedValue([]);
208
228
  mocks.getUserSetting.mockResolvedValue({ mode: "all-apps" });
@@ -212,6 +232,8 @@ beforeEach(() => {
212
232
  ticketHash: "hash-123",
213
233
  expiresAt: 12345,
214
234
  });
235
+ mocks.listRemoteServers.mockReset().mockResolvedValue([]);
236
+ mocks.getMcpOAuthAccessToken.mockReset().mockResolvedValue(null);
215
237
  mocks.managerStart.mockResolvedValue(undefined);
216
238
  mocks.managerGetConnectErrorStatus.mockReturnValue(undefined);
217
239
  mocks.managerStop.mockResolvedValue(undefined);
@@ -321,6 +343,241 @@ describe("Dispatch direct app actions", () => {
321
343
  expect(mocks.managerStop).toHaveBeenCalled();
322
344
  });
323
345
 
346
+ it("keeps a same-deployment assertion when it is accepted", async () => {
347
+ defineAppConfig({ dispatch: { directAppActions: true } });
348
+ mocks.discoverAgents.mockResolvedValue([
349
+ { ...analyticsAgent, url: "http://localhost:8092/analytics" },
350
+ ]);
351
+ mocks.managerCallTool.mockResolvedValue({ content: [] });
352
+ await asOwner(() =>
353
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
354
+ );
355
+ expect(mocks.managerConstructor).toHaveBeenCalledWith({
356
+ servers: {
357
+ target: expect.objectContaining({
358
+ headers: expect.objectContaining({
359
+ Authorization: "Bearer signed-token",
360
+ }),
361
+ }),
362
+ },
363
+ });
364
+ expect(mocks.listRemoteServers).not.toHaveBeenCalled();
365
+ });
366
+
367
+ it("keeps first-party assertion connections independent of the OAuth store", async () => {
368
+ defineAppConfig({ dispatch: { directAppActions: true } });
369
+ mocks.discoverAgents.mockResolvedValue([
370
+ { ...analyticsAgent, url: "https://analytics.agent-native.com" },
371
+ ]);
372
+ mocks.listRemoteServers.mockRejectedValue(new Error("store unavailable"));
373
+ mocks.managerCallTool.mockResolvedValue({ content: [] });
374
+ await asOwner(() =>
375
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
376
+ );
377
+ expect(mocks.managerConstructor).toHaveBeenCalledWith({
378
+ servers: {
379
+ target: expect.objectContaining({
380
+ headers: expect.objectContaining({
381
+ Authorization: "Bearer signed-token",
382
+ }),
383
+ }),
384
+ },
385
+ });
386
+ expect(mocks.listRemoteServers).not.toHaveBeenCalled();
387
+ });
388
+
389
+ it("tries the scoped OAuth connection after a same-origin assertion is rejected", async () => {
390
+ defineAppConfig({ dispatch: { directAppActions: true } });
391
+ mocks.discoverAgents.mockResolvedValue([
392
+ { ...analyticsAgent, url: "http://localhost:8092/analytics" },
393
+ ]);
394
+ mocks.listRemoteServers.mockResolvedValue([
395
+ {
396
+ id: "connection-1",
397
+ name: "remote",
398
+ url: "http://localhost:8092/analytics/mcp",
399
+ oauthSecretKey: "oauth-key",
400
+ createdAt: 1,
401
+ },
402
+ ]);
403
+ mocks.getMcpOAuthAccessToken.mockResolvedValue("oauth-token");
404
+ mocks.managerGetConnectErrorStatus
405
+ .mockReturnValueOnce(401)
406
+ .mockReturnValueOnce(undefined);
407
+ mocks.managerCallTool.mockResolvedValue({ content: [] });
408
+ await asOwner(() =>
409
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
410
+ );
411
+ expect(mocks.managerConstructor).toHaveBeenCalledTimes(2);
412
+ expect(mocks.managerConstructor).toHaveBeenLastCalledWith({
413
+ servers: {
414
+ target: expect.objectContaining({
415
+ headers: expect.objectContaining({
416
+ Authorization: "Bearer oauth-token",
417
+ }),
418
+ }),
419
+ },
420
+ });
421
+ });
422
+
423
+ it("uses a caller's OAuth connection for a different deployment", async () => {
424
+ defineAppConfig({ dispatch: { directAppActions: true } });
425
+ vi.stubEnv("A2A_SECRET", "");
426
+ mocks.discoverAgents.mockResolvedValue([
427
+ { ...analyticsAgent, url: "https://remote.example.test/app" },
428
+ ]);
429
+ mocks.listRemoteServers.mockResolvedValue([
430
+ {
431
+ id: "connection-1",
432
+ name: "remote",
433
+ url: "https://remote.example.test/app/mcp",
434
+ oauthSecretKey: "oauth-key",
435
+ createdAt: 1,
436
+ },
437
+ ]);
438
+ mocks.getMcpOAuthAccessToken.mockResolvedValue("oauth-token");
439
+ mocks.managerCallTool.mockResolvedValue({ content: [] });
440
+
441
+ await asOwner(() =>
442
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
443
+ );
444
+ expect(mocks.getMcpOAuthAccessToken).toHaveBeenCalledWith({
445
+ key: "oauth-key",
446
+ scope: "user",
447
+ scopeId: "owner@example.test",
448
+ serverUrl: "https://remote.example.test/app/mcp",
449
+ throwOnTransientRefreshFailure: true,
450
+ });
451
+ expect(mocks.managerConstructor).toHaveBeenCalledWith({
452
+ servers: {
453
+ target: expect.objectContaining({
454
+ headers: expect.objectContaining({
455
+ Authorization: "Bearer oauth-token",
456
+ }),
457
+ }),
458
+ },
459
+ });
460
+ expect(mocks.signA2AToken).not.toHaveBeenCalled();
461
+ });
462
+
463
+ it("returns a connect URL when an assertion is rejected and no OAuth connection exists", async () => {
464
+ defineAppConfig({ dispatch: { directAppActions: true } });
465
+ mocks.discoverAgents.mockResolvedValue([
466
+ { ...analyticsAgent, url: "https://remote.example.test/app" },
467
+ ]);
468
+ mocks.managerGetConnectErrorStatus.mockReturnValue(401);
469
+ const error = await asOwner(() =>
470
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
471
+ ).catch((caught: unknown) => caught);
472
+ expect(error).toMatchObject({
473
+ errorCode: "authorization_required",
474
+ details: { authorizationUrl: expect.any(String) },
475
+ });
476
+ const url = new URL(
477
+ (error as { details: { authorizationUrl: string } }).details
478
+ .authorizationUrl,
479
+ );
480
+ expect(url.pathname).toBe("/_agent-native/mcp/servers/oauth/start");
481
+ expect(url.searchParams.get("url")).toBe(
482
+ "https://remote.example.test/app/mcp",
483
+ );
484
+ expect(url.searchParams.get("scope")).toBe("user");
485
+ expect(mocks.managerCallTool).not.toHaveBeenCalled();
486
+ });
487
+
488
+ it("offers reconnect when the saved credential needs authorization", async () => {
489
+ defineAppConfig({ dispatch: { directAppActions: true } });
490
+ mocks.discoverAgents.mockResolvedValue([
491
+ { ...analyticsAgent, url: "https://remote.example.test/app" },
492
+ ]);
493
+ mocks.listRemoteServers.mockResolvedValue([
494
+ {
495
+ id: "connection-1",
496
+ name: "remote",
497
+ url: "https://remote.example.test/app/mcp",
498
+ oauthSecretKey: "oauth-key",
499
+ createdAt: 1,
500
+ },
501
+ ]);
502
+ mocks.managerGetConnectErrorStatus.mockReturnValue(401);
503
+ const error = await asOwner(() =>
504
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
505
+ ).catch((caught: unknown) => caught);
506
+ expect(error).toMatchObject({ errorCode: "authorization_required" });
507
+ const url = new URL(
508
+ (error as { details: { authorizationUrl: string } }).details
509
+ .authorizationUrl,
510
+ );
511
+ expect(url.searchParams.get("serverId")).toBe("connection-1");
512
+ });
513
+
514
+ it("does not report a connection-store failure as missing authorization", async () => {
515
+ defineAppConfig({ dispatch: { directAppActions: true } });
516
+ mocks.discoverAgents.mockResolvedValue([
517
+ { ...analyticsAgent, url: "https://remote.example.test/app" },
518
+ ]);
519
+ mocks.listRemoteServers.mockRejectedValue(new Error("store unavailable"));
520
+ await expect(
521
+ asOwner(() =>
522
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
523
+ ),
524
+ ).rejects.toMatchObject({ errorCode: "app_connection_unavailable" });
525
+ expect(mocks.managerConstructor).not.toHaveBeenCalled();
526
+ });
527
+
528
+ it("does not reuse a different resource's OAuth token", async () => {
529
+ defineAppConfig({ dispatch: { directAppActions: true } });
530
+ mocks.discoverAgents.mockResolvedValue([
531
+ { ...analyticsAgent, url: "https://remote.example.test/app" },
532
+ ]);
533
+ mocks.listRemoteServers.mockResolvedValue([
534
+ {
535
+ id: "other",
536
+ name: "other",
537
+ url: "https://remote.example.test/other/mcp",
538
+ oauthSecretKey: "other-key",
539
+ createdAt: 1,
540
+ },
541
+ ]);
542
+ mocks.managerGetConnectErrorStatus.mockReturnValue(401);
543
+ await expect(
544
+ asOwner(() =>
545
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
546
+ ),
547
+ ).rejects.toMatchObject({ errorCode: "authorization_required" });
548
+ expect(mocks.getMcpOAuthAccessToken).not.toHaveBeenCalled();
549
+ });
550
+
551
+ it("distinguishes a rejected OAuth credential from an unreachable app", async () => {
552
+ defineAppConfig({ dispatch: { directAppActions: true } });
553
+ mocks.discoverAgents.mockResolvedValue([
554
+ { ...analyticsAgent, url: "https://remote.example.test/app" },
555
+ ]);
556
+ mocks.listRemoteServers.mockResolvedValue([
557
+ {
558
+ id: "connection-1",
559
+ name: "remote",
560
+ url: "https://remote.example.test/app/mcp",
561
+ oauthSecretKey: "oauth-key",
562
+ createdAt: 1,
563
+ },
564
+ ]);
565
+ mocks.getMcpOAuthAccessToken.mockResolvedValue("oauth-token");
566
+ mocks.managerGetConnectErrorStatus.mockReturnValue(403);
567
+ await expect(
568
+ asOwner(() =>
569
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
570
+ ),
571
+ ).rejects.toMatchObject({ errorCode: "app_connection_rejected" });
572
+ mocks.managerGetConnectErrorStatus.mockReturnValue(undefined);
573
+ mocks.managerHasServer.mockReturnValue(false);
574
+ await expect(
575
+ asOwner(() =>
576
+ callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
577
+ ),
578
+ ).rejects.toMatchObject({ errorCode: "app_connection_unreachable" });
579
+ });
580
+
324
581
  it("calls one action of a granted app and returns its result", async () => {
325
582
  defineAppConfig({ dispatch: { directAppActions: true } });
326
583
  mocks.managerCallTool.mockResolvedValue({
@@ -380,6 +637,30 @@ describe("Dispatch direct app actions", () => {
380
637
  }
381
638
  });
382
639
 
640
+ it("forwards the bound visible child tab on app actions", async () => {
641
+ defineAppConfig({ dispatch: { directAppActions: true } });
642
+ mocks.managerCallTool.mockResolvedValue({ content: [] });
643
+ mocks.resolveChildBrowserTab.mockResolvedValueOnce(
644
+ "fd88b908-c543-43a8-b044-425959511c70",
645
+ );
646
+ await asOwner(() =>
647
+ callGrantedDispatchMcpAppAction("analytics", "view-screen", {}),
648
+ );
649
+ expect(mocks.resolveChildBrowserTab).toHaveBeenCalledWith(
650
+ expect.objectContaining({ id: "analytics", url: analyticsAgent.url }),
651
+ );
652
+ expect(mocks.managerConstructor).toHaveBeenCalledWith({
653
+ servers: {
654
+ target: expect.objectContaining({
655
+ headers: expect.objectContaining({
656
+ "x-agent-native-browser-tab":
657
+ "fd88b908-c543-43a8-b044-425959511c70",
658
+ }),
659
+ }),
660
+ },
661
+ });
662
+ });
663
+
383
664
  it("refuses an app the caller has not granted", async () => {
384
665
  defineAppConfig({ dispatch: { directAppActions: true } });
385
666
  mocks.getUserSetting.mockResolvedValue({
@@ -439,7 +720,7 @@ describe("Dispatch direct app actions", () => {
439
720
  },
440
721
  () => callGrantedDispatchMcpAppAction("analytics", "get-project", {}),
441
722
  ),
442
- ).rejects.toThrow("The analytics app rejected this connection.");
723
+ ).rejects.toMatchObject({ errorCode: "authorization_required" });
443
724
  expect(mocks.signA2AOrgMemberDelegationToken).toHaveBeenCalledTimes(1);
444
725
  expect(mocks.managerConstructor).toHaveBeenCalledTimes(2);
445
726
  expect(mocks.managerCallTool).not.toHaveBeenCalled();
@@ -466,6 +747,220 @@ describe("Dispatch direct app actions", () => {
466
747
  });
467
748
 
468
749
  describe("Dispatch MCP gateway app discovery", () => {
750
+ it("resolves qualified workspace identities before display names and reports ties", async () => {
751
+ const asOwner = <T>(fn: () => Promise<T>) =>
752
+ runWithRequestContext(
753
+ {
754
+ userEmail: "owner@example.test",
755
+ requestOrigin: "http://localhost:8092",
756
+ },
757
+ fn,
758
+ );
759
+ mocks.discoverAgents.mockResolvedValue([
760
+ { ...analyticsAgent, id: "fleet-2", name: "Fleet" },
761
+ { ...analyticsAgent, id: "workspace/fleet", name: "Fleet" },
762
+ ]);
763
+ expect(
764
+ (await asOwner(() => resolveGrantedDispatchMcpApp("workspace/fleet"))).id,
765
+ ).toBe("workspace/fleet");
766
+ expect(
767
+ (await asOwner(() => resolveGrantedDispatchMcpApp("fleet"))).id,
768
+ ).toBe("workspace/fleet");
769
+ mocks.discoverAgents.mockResolvedValue([
770
+ { ...analyticsAgent, id: "one/fleet", name: "Fleet" },
771
+ { ...analyticsAgent, id: "two/fleet", name: "Fleet" },
772
+ ]);
773
+ await expect(
774
+ asOwner(() => resolveGrantedDispatchMcpApp("fleet")),
775
+ ).rejects.toThrow(/one\/fleet, two\/fleet/);
776
+ });
777
+
778
+ it("uses scoped directory manifests during an outage and rechecks current grants", async () => {
779
+ const workspaceFleet = {
780
+ ...analyticsAgent,
781
+ id: "workspace/fleet",
782
+ name: "Fleet",
783
+ source: "org-directory",
784
+ aliases: ["Delivery desk", "fleet-2"],
785
+ };
786
+ const templateFleet = {
787
+ ...analyticsAgent,
788
+ id: "fleet-2",
789
+ name: "Fleet",
790
+ source: "builtin",
791
+ };
792
+ const listFor = (
793
+ orgId: string,
794
+ userEmail = "directory-cache@example.test",
795
+ ) =>
796
+ runWithRequestContext(
797
+ { userEmail, orgId, requestOrigin: "http://localhost:8092" },
798
+ () => listDispatchMcpApps(),
799
+ );
800
+ mocks.discoverAgents.mockResolvedValue([workspaceFleet, templateFleet]);
801
+ mocks.listWorkspaceApps.mockResolvedValue([
802
+ { id: workspaceFleet.id, path: "/", url: workspaceFleet.url },
803
+ ]);
804
+ await listFor("directory-org");
805
+
806
+ mocks.discoverAgents.mockResolvedValue([templateFleet]);
807
+ mocks.directoryStatus.mockReturnValue({
808
+ status: "unavailable",
809
+ reason: "server-error",
810
+ });
811
+ const sameScope = await listFor("directory-org");
812
+ expect(sameScope.degradedSources).toEqual([
813
+ {
814
+ source: "workspace-directory",
815
+ status: "unavailable",
816
+ usingCache: true,
817
+ },
818
+ ]);
819
+ expect(sameScope.apps).toContainEqual(
820
+ expect.objectContaining({
821
+ id: "workspace/fleet",
822
+ aliases: ["Delivery desk", "fleet-2"],
823
+ granted: true,
824
+ }),
825
+ );
826
+ const resolve = (app: string) =>
827
+ runWithRequestContext(
828
+ {
829
+ userEmail: "directory-cache@example.test",
830
+ orgId: "directory-org",
831
+ requestOrigin: "http://localhost:8092",
832
+ },
833
+ () => resolveGrantedDispatchMcpApp(app),
834
+ );
835
+ await expect(resolve("fleet")).resolves.toMatchObject({
836
+ id: "workspace/fleet",
837
+ });
838
+ await expect(resolve("Delivery desk")).resolves.toMatchObject({
839
+ id: "workspace/fleet",
840
+ });
841
+ await expect(resolve("fleet-2")).resolves.toMatchObject({
842
+ id: "fleet-2",
843
+ });
844
+ expect((await listFor("another-org")).apps.map((app) => app.id)).toEqual([
845
+ "dispatch",
846
+ "fleet-2",
847
+ ]);
848
+ expect(
849
+ (await listFor("directory-org", "another-person@example.test")).apps.map(
850
+ (app) => app.id,
851
+ ),
852
+ ).toEqual(["dispatch", "fleet-2"]);
853
+
854
+ mocks.getOrgSetting.mockResolvedValue({
855
+ mode: "selected-apps",
856
+ selectedAppIds: ["fleet-2"],
857
+ });
858
+ await expect(resolve("workspace/fleet")).rejects.toThrow(/not granted/);
859
+ expect((await listFor("directory-org")).apps).toContainEqual(
860
+ expect.objectContaining({ id: "workspace/fleet", granted: false }),
861
+ );
862
+
863
+ mocks.listWorkspaceApps.mockResolvedValue([]);
864
+ expect((await listFor("directory-org")).apps.map((app) => app.id)).toEqual([
865
+ "dispatch",
866
+ "fleet-2",
867
+ ]);
868
+ mocks.directoryStatus.mockReturnValue({ status: "forbidden" });
869
+ expect((await listFor("directory-org")).apps.map((app) => app.id)).toEqual([
870
+ "dispatch",
871
+ "fleet-2",
872
+ ]);
873
+ mocks.directoryStatus.mockReturnValue({
874
+ status: "unavailable",
875
+ reason: "timeout",
876
+ });
877
+ expect((await listFor("directory-org")).degradedSources).toEqual([
878
+ {
879
+ source: "workspace-directory",
880
+ status: "unavailable",
881
+ usingCache: false,
882
+ },
883
+ ]);
884
+ });
885
+
886
+ it("rejects a previously registered runtime when its mount can no longer be verified", async () => {
887
+ const id = "cached-workspace-app";
888
+ const url = "https://beta.agent-workspace.builder.io";
889
+ const request = {
890
+ userEmail: "mount-cache@example.test",
891
+ orgId: "mount-cache-org",
892
+ requestOrigin: "https://beta.dispatch.agent-native.com",
893
+ };
894
+ mocks.discoverAgents.mockResolvedValue([
895
+ { ...analyticsAgent, id, url: `${url}/dispatch/apps/${id}` },
896
+ ]);
897
+ mocks.listWorkspaceApps.mockResolvedValue([
898
+ { id, path: "/actual-mount", url: `${url}/actual-mount` },
899
+ ]);
900
+ const open = () =>
901
+ runWithRequestContext(request, () => resolveGrantedDispatchMcpApp(id));
902
+ await expect(open()).resolves.toMatchObject({
903
+ homeUrl: `${url}/actual-mount`,
904
+ });
905
+ mocks.listWorkspaceApps.mockRejectedValue({ statusCode: 503 });
906
+
907
+ await expect(open()).rejects.toThrow(/mount resolves/);
908
+ const result = await runWithRequestContext(request, listDispatchMcpApps);
909
+ expect(result.degradedSources).toEqual([
910
+ {
911
+ source: "workspace-mounts",
912
+ status: "unavailable",
913
+ httpStatus: 503,
914
+ usingCache: false,
915
+ },
916
+ ]);
917
+ });
918
+
919
+ it("keeps last-known remote manifests when strict connected discovery fails", async () => {
920
+ const request = {
921
+ userEmail: "strict-discovery@example.test",
922
+ orgId: "strict-discovery-org",
923
+ requestOrigin: "http://localhost:8092",
924
+ };
925
+ const read = () => runWithRequestContext(request, listDispatchMcpApps);
926
+ mocks.discoverAgents.mockResolvedValue([
927
+ { ...analyticsAgent, id: "remote/project", source: "remote-agent" },
928
+ ]);
929
+ mocks.listWorkspaceApps.mockResolvedValue([
930
+ { id: "remote/project", path: "/", url: analyticsAgent.url },
931
+ ]);
932
+ await read();
933
+ expect(mocks.discoverAgents).toHaveBeenCalledWith("dispatch", {
934
+ requireReadableAgentSources: true,
935
+ });
936
+
937
+ mocks.discoverAgents.mockRejectedValue(new Error("directory unavailable"));
938
+ const result = await read();
939
+ expect(result.apps.map((app) => app.id)).toEqual([
940
+ "dispatch",
941
+ "remote/project",
942
+ ]);
943
+ expect(result.degradedSources).toEqual([
944
+ { source: "connected-apps", status: "unavailable", usingCache: true },
945
+ ]);
946
+
947
+ mocks.discoverAgents.mockRejectedValue(
948
+ new Error("Unable to read connected agent resources", {
949
+ cause: Object.assign(new Error("Access denied"), { status: 403 }),
950
+ }),
951
+ );
952
+ const denied = await read();
953
+ expect(denied.apps.map((app) => app.id)).toEqual(["dispatch"]);
954
+ expect(denied.degradedSources).toEqual([
955
+ {
956
+ source: "connected-apps",
957
+ status: "forbidden",
958
+ usingCache: false,
959
+ httpStatus: 403,
960
+ },
961
+ ]);
962
+ });
963
+
469
964
  it("lists a discovered app without a description as an empty description", async () => {
470
965
  const { description: _omitted, ...agent } = analyticsAgent;
471
966
  mocks.discoverAgents.mockResolvedValue([agent]);
@@ -481,18 +976,26 @@ describe("Dispatch MCP gateway app discovery", () => {
481
976
  expect(apps.find((app) => app.id === "analytics")?.description).toBe("");
482
977
  });
483
978
 
484
- it("keeps discovered agents available when mounted app lookup fails", async () => {
979
+ it("reports a mounted discovery failure while keeping other apps available", async () => {
485
980
  mocks.listWorkspaceApps.mockRejectedValue({ status: 503 });
486
981
 
487
- const apps = await runWithRequestContext(
982
+ const { apps, degradedSources } = await runWithRequestContext(
488
983
  {
489
- userEmail: "owner@example.test",
984
+ userEmail: "discovery-unavailable@example.test",
490
985
  requestOrigin: "http://localhost:8092",
491
986
  },
492
- () => listGrantedDispatchMcpApps(),
987
+ () => listDispatchMcpApps(),
493
988
  );
494
989
 
495
990
  expect(apps.map((app) => app.id)).toEqual(["dispatch", "analytics"]);
991
+ expect(degradedSources).toEqual([
992
+ {
993
+ source: "workspace-mounts",
994
+ status: "unavailable",
995
+ usingCache: false,
996
+ httpStatus: 503,
997
+ },
998
+ ]);
496
999
  });
497
1000
 
498
1001
  it("refuses a Workspace app on its Dispatch page URL while the mounted lookup is unavailable", async () => {
@@ -1395,14 +1898,21 @@ describe("askGrantedDispatchMcpApp", () => {
1395
1898
  app: "analytics",
1396
1899
  routedVia: "a2a",
1397
1900
  taskId: "task-working",
1901
+ taskHandle: expect.stringMatching(
1902
+ /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,
1903
+ ),
1398
1904
  status: "working",
1399
1905
  pollAfterMs: 1_500,
1400
1906
  poll: {
1401
1907
  tool: "ask_app_status",
1402
- arguments: { app: "analytics", taskId: "task-working" },
1403
- },
1908
+ arguments: {
1909
+ app: "analytics",
1910
+ taskId: "task-working",
1911
+ taskHandle: result.taskHandle,
1912
+ },
1913
+ },
1404
1914
  message:
1405
- 'ask_app is still working. Call ask_app_status with taskId "task-working" to retrieve the final response.',
1915
+ 'ask_app is still working. Call ask_app_status with taskId "task-working" and the returned taskHandle to retrieve the final response.',
1406
1916
  });
1407
1917
  expect(mocks.a2aSend).toHaveBeenCalledWith(
1408
1918
  expect.anything(),
@@ -1713,662 +2223,1270 @@ describe("askGrantedDispatchMcpApp", () => {
1713
2223
  ).rejects.toThrow(/not granted/);
1714
2224
  expect(mocks.a2aGetTask).not.toHaveBeenCalled();
1715
2225
  });
1716
- });
1717
2226
 
1718
- describe("openGrantedDispatchMcpApp", () => {
1719
- beforeEach(() => {
1720
- vi.stubEnv("A2A_SECRET", "shared-secret");
1721
- });
2227
+ it("polls the original sealed route with a valid taskHandle even after discovery drifts", async () => {
2228
+ vi.stubEnv("A2A_SECRET", "sealed-handle-secret");
2229
+ mocks.getOrgSetting.mockResolvedValue({
2230
+ mode: "selected-apps",
2231
+ selectedAppIds: ["analytics"],
2232
+ });
2233
+ mocks.getOrgDomain.mockResolvedValue("builder.io");
2234
+ mocks.getOrgA2ASecret.mockResolvedValue("org-specific-secret");
2235
+ mocks.a2aSend.mockResolvedValueOnce({
2236
+ id: "task-sealed-route",
2237
+ status: { state: "working" },
2238
+ });
1722
2239
 
1723
- it("opens Dispatch extension routes through the Dispatch app id", async () => {
1724
- const result = await runWithRequestContext(
2240
+ const submitted = await runWithRequestContext(
1725
2241
  {
1726
2242
  userEmail: "owner@example.test",
2243
+ orgId: "org-1",
1727
2244
  requestOrigin: "http://localhost:8092",
1728
2245
  },
1729
2246
  () =>
1730
- openGrantedDispatchMcpApp({
1731
- app: "dispatch",
1732
- path: "/extensions/ext-1/github-stars-over-time",
1733
- embed: true,
1734
- chrome: "minimal",
2247
+ askGrantedDispatchMcpApp("analytics", "Run cohort analysis.", {
2248
+ async: true,
1735
2249
  }),
1736
2250
  );
1737
2251
 
1738
- expect(result).toEqual({
1739
- app: "dispatch",
1740
- path: "/extensions/ext-1/github-stars-over-time",
1741
- url: "http://localhost:8092/extensions/ext-1/github-stars-over-time",
1742
- embed: true,
1743
- chrome: "minimal",
1744
- embedStartUrl:
1745
- "http://localhost:8092/_agent-native/embed/start?ticket=ticket-123",
1746
- embedTargetPath: "/extensions/ext-1/github-stars-over-time",
1747
- embedExpiresAt: 12345,
2252
+ expect(submitted.taskHandle).toMatch(/^v1\./);
2253
+ expect(submitted.poll).toEqual({
2254
+ tool: "ask_app_status",
2255
+ arguments: {
2256
+ app: "analytics",
2257
+ taskId: "task-sealed-route",
2258
+ taskHandle: submitted.taskHandle,
2259
+ },
1748
2260
  });
1749
- });
1750
2261
 
1751
- it("pre-mints cross-app embed sessions for MCP app hosts", async () => {
1752
- const result = await runWithRequestContext(
2262
+ mocks.discoverAgents.mockReset();
2263
+ mocks.discoverAgents.mockResolvedValue([
2264
+ { ...analyticsAgent, url: "http://localhost:9999" },
2265
+ ]);
2266
+ mocks.a2aConstructor.mockClear();
2267
+ mocks.a2aGetTask.mockResolvedValueOnce({
2268
+ id: "task-sealed-route",
2269
+ status: {
2270
+ state: "completed",
2271
+ message: {
2272
+ role: "agent",
2273
+ parts: [{ type: "text", text: "Cohort analysis complete." }],
2274
+ },
2275
+ },
2276
+ });
2277
+
2278
+ const polled = await runWithRequestContext(
1753
2279
  {
1754
2280
  userEmail: "owner@example.test",
2281
+ orgId: "org-1",
1755
2282
  requestOrigin: "http://localhost:8092",
1756
2283
  },
1757
2284
  () =>
1758
- openGrantedDispatchMcpApp({
1759
- app: "analytics",
1760
- path: "/dashboards?range=30d",
1761
- embed: true,
1762
- chrome: "minimal",
2285
+ getGrantedDispatchMcpAppTask("analytics", "task-sealed-route", {
2286
+ taskHandle: submitted.taskHandle,
1763
2287
  }),
1764
2288
  );
1765
2289
 
1766
- expect(mocks.managerCallTool).toHaveBeenCalledWith(
1767
- "mcp__target__create_embed_session",
1768
- {
1769
- url: "http://localhost:8086/dashboards?range=30d",
1770
- chrome: "minimal",
1771
- },
2290
+ expect(mocks.discoverAgents).not.toHaveBeenCalled();
2291
+ expect(mocks.a2aConstructor).toHaveBeenCalledWith(
2292
+ "http://localhost:8086",
2293
+ "signed-token",
2294
+ expect.objectContaining({ requestTimeoutMs: 10_000 }),
1772
2295
  );
1773
- expect(result).toEqual({
2296
+ expect(mocks.a2aGetTask).toHaveBeenCalledWith("task-sealed-route");
2297
+ expect(polled).toEqual({
1774
2298
  app: "analytics",
1775
- path: "/dashboards?range=30d",
1776
- url: "http://localhost:8086/dashboards?range=30d",
1777
- embed: true,
1778
- chrome: "minimal",
1779
- embedStartUrl:
1780
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
2299
+ routedVia: "a2a",
2300
+ taskId: "task-sealed-route",
2301
+ status: "completed",
2302
+ response: "Cohort analysis complete.",
1781
2303
  });
1782
2304
  });
1783
2305
 
1784
- it("reads the target embed start URL from Core MCP response metadata", async () => {
1785
- mocks.managerCallTool.mockResolvedValueOnce({
1786
- structuredContent: {
1787
- targetPath: "/dashboards?range=30d",
1788
- expiresAt: 12345,
1789
- },
1790
- _meta: {
1791
- "agent-native/embedStart": {
1792
- startUrl:
1793
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
1794
- },
1795
- },
2306
+ it("preserves taskHandle across continued pending polls and statusRead unavailable envelopes", async () => {
2307
+ vi.useFakeTimers();
2308
+ vi.setSystemTime(0);
2309
+ vi.stubEnv("A2A_SECRET", "sealed-handle-secret");
2310
+ vi.spyOn(console, "warn").mockImplementation(() => {});
2311
+ mocks.a2aSend.mockResolvedValueOnce({
2312
+ id: "task-long",
2313
+ status: { state: "working" },
1796
2314
  });
1797
2315
 
1798
- const result = await runWithRequestContext(
2316
+ const submitted = await runWithRequestContext(
1799
2317
  {
1800
2318
  userEmail: "owner@example.test",
1801
2319
  requestOrigin: "http://localhost:8092",
1802
2320
  },
1803
2321
  () =>
1804
- openGrantedDispatchMcpApp({
1805
- app: "analytics",
1806
- path: "/dashboards?range=30d",
1807
- embed: true,
1808
- chrome: "minimal",
2322
+ askGrantedDispatchMcpApp("analytics", "Generate quarterly rollup.", {
2323
+ async: true,
1809
2324
  }),
1810
2325
  );
1811
2326
 
1812
- expect(result).toMatchObject({
1813
- app: "analytics",
1814
- embedStartUrl:
1815
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
1816
- embedTargetPath: "/dashboards?range=30d",
1817
- embedExpiresAt: 12345,
2327
+ mocks.a2aGetTask.mockResolvedValueOnce({
2328
+ id: "task-long",
2329
+ status: { state: "working" },
1818
2330
  });
1819
- });
1820
-
1821
- it("answers with the link and stops the target when it is slow to mint a session", async () => {
1822
- vi.useFakeTimers();
1823
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
1824
- try {
1825
- let rejectCall: (error: Error) => void = () => {};
1826
- mocks.managerCallTool.mockImplementationOnce(
1827
- () =>
1828
- new Promise((_resolve, reject) => {
1829
- rejectCall = reject;
1830
- }),
1831
- );
1832
- // Stopping the client fails its pending call, as the SDK transport does.
1833
- mocks.managerStop.mockImplementation(async () =>
1834
- rejectCall(new Error("Connection closed")),
1835
- );
1836
- const pending = runWithRequestContext(
1837
- {
1838
- userEmail: "owner@example.test",
1839
- requestOrigin: "http://localhost:8092",
1840
- },
1841
- () =>
1842
- openGrantedDispatchMcpApp({
1843
- app: "analytics",
1844
- path: "/dashboards",
1845
- embed: true,
1846
- }),
1847
- );
1848
- await vi.advanceTimersByTimeAsync(15_000);
1849
- const result = await pending;
1850
- expect(result).toMatchObject({
1851
- app: "analytics",
1852
- url: "http://localhost:8086/dashboards",
1853
- });
1854
- expect(result).not.toHaveProperty("embedStartUrl");
1855
- await vi.advanceTimersByTimeAsync(60_000);
1856
- // The abandoned request was stopped, not retried in the background.
1857
- expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
1858
- expect(mocks.managerStop).toHaveBeenCalled();
1859
- } finally {
1860
- mocks.managerStop.mockReset();
1861
- mocks.managerStop.mockResolvedValue(undefined);
1862
- warnSpy.mockRestore();
1863
- vi.useRealTimers();
1864
- }
1865
- });
2331
+ const stillWorking = await runWithRequestContext(
2332
+ {
2333
+ userEmail: "owner@example.test",
2334
+ requestOrigin: "http://localhost:8092",
2335
+ },
2336
+ () =>
2337
+ getGrantedDispatchMcpAppTask("analytics", "task-long", {
2338
+ taskHandle: submitted.taskHandle,
2339
+ }),
2340
+ );
1866
2341
 
1867
- it("reads the target embed start URL when Core returns JSON text", async () => {
1868
- mocks.managerCallTool.mockResolvedValueOnce({
1869
- content: [
1870
- {
1871
- type: "text",
1872
- text: JSON.stringify({
1873
- targetPath: "/dashboards?range=30d",
1874
- expiresAt: 12345,
1875
- }),
1876
- },
1877
- ],
1878
- _meta: {
1879
- "agent-native/embedStart": {
1880
- startUrl:
1881
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
2342
+ expect(stillWorking).toMatchObject({
2343
+ app: "analytics",
2344
+ taskId: "task-long",
2345
+ taskHandle: submitted.taskHandle,
2346
+ status: "working",
2347
+ poll: {
2348
+ tool: "ask_app_status",
2349
+ arguments: {
2350
+ app: "analytics",
2351
+ taskId: "task-long",
2352
+ taskHandle: submitted.taskHandle,
1882
2353
  },
1883
2354
  },
1884
2355
  });
1885
2356
 
1886
- const result = await runWithRequestContext(
2357
+ mocks.a2aGetTask.mockRejectedValue(new TypeError("fetch failed"));
2358
+ const unavailablePromise = runWithRequestContext(
1887
2359
  {
1888
2360
  userEmail: "owner@example.test",
1889
2361
  requestOrigin: "http://localhost:8092",
1890
2362
  },
1891
2363
  () =>
1892
- openGrantedDispatchMcpApp({
1893
- app: "analytics",
1894
- path: "/dashboards?range=30d",
1895
- embed: true,
1896
- chrome: "minimal",
2364
+ getGrantedDispatchMcpAppTask("analytics", "task-long", {
2365
+ taskHandle: submitted.taskHandle,
1897
2366
  }),
1898
2367
  );
2368
+ await vi.advanceTimersByTimeAsync(2_500);
1899
2369
 
1900
- expect(result).toMatchObject({
2370
+ await expect(unavailablePromise).resolves.toMatchObject({
1901
2371
  app: "analytics",
1902
- embedStartUrl:
1903
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
1904
- embedTargetPath: "/dashboards?range=30d",
1905
- embedExpiresAt: 12345,
2372
+ taskId: "task-long",
2373
+ taskHandle: submitted.taskHandle,
2374
+ status: "unknown",
2375
+ statusRead: "unavailable",
2376
+ poll: {
2377
+ tool: "ask_app_status",
2378
+ arguments: {
2379
+ app: "analytics",
2380
+ taskId: "task-long",
2381
+ taskHandle: submitted.taskHandle,
2382
+ },
2383
+ },
1906
2384
  });
1907
2385
  });
1908
2386
 
1909
- it.each([408, 429, 502, 503, 504])(
1910
- "retries transient typed HTTP %i target MCP failures with HTML bodies",
1911
- async (status) => {
1912
- const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0);
1913
- mocks.managerCallTool
1914
- .mockRejectedValueOnce(
1915
- Object.assign(
1916
- new Error(
1917
- 'MCP server "target" is not connected: That URL returned a web page instead of an MCP response. Check that you pasted the Streamable HTTP endpoint, often ending in /mcp.',
1918
- ),
1919
- { code: status },
1920
- ),
1921
- )
1922
- .mockResolvedValueOnce({
1923
- structuredContent: {
1924
- startUrl:
1925
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
1926
- },
1927
- });
2387
+ it("denies a valid taskHandle when the app grant is revoked before polling", async () => {
2388
+ vi.stubEnv("A2A_SECRET", "sealed-handle-secret");
2389
+ mocks.getUserSetting.mockResolvedValue({
2390
+ mode: "selected-apps",
2391
+ selectedAppIds: ["analytics"],
2392
+ });
2393
+ mocks.a2aSend.mockResolvedValueOnce({
2394
+ id: "task-revoked",
2395
+ status: { state: "working" },
2396
+ });
1928
2397
 
1929
- const result = await runWithRequestContext(
2398
+ const submitted = await runWithRequestContext(
2399
+ {
2400
+ userEmail: "owner@example.test",
2401
+ requestOrigin: "http://localhost:8092",
2402
+ },
2403
+ () =>
2404
+ askGrantedDispatchMcpApp("analytics", "Run private export.", {
2405
+ async: true,
2406
+ }),
2407
+ );
2408
+
2409
+ mocks.getUserSetting.mockResolvedValue({
2410
+ mode: "selected-apps",
2411
+ selectedAppIds: ["dispatch"],
2412
+ });
2413
+
2414
+ await expect(
2415
+ runWithRequestContext(
1930
2416
  {
1931
2417
  userEmail: "owner@example.test",
1932
2418
  requestOrigin: "http://localhost:8092",
1933
2419
  },
1934
2420
  () =>
1935
- openGrantedDispatchMcpApp({
1936
- app: "analytics",
1937
- path: "/dashboards",
1938
- embed: true,
2421
+ getGrantedDispatchMcpAppTask("analytics", "task-revoked", {
2422
+ taskHandle: submitted.taskHandle,
1939
2423
  }),
1940
- );
2424
+ ),
2425
+ ).rejects.toThrow(/not granted/);
2426
+ expect(mocks.a2aGetTask).not.toHaveBeenCalled();
2427
+ });
1941
2428
 
1942
- expect(mocks.managerConstructor).toHaveBeenCalledTimes(2);
1943
- expect(mocks.managerStart).toHaveBeenCalledTimes(2);
1944
- expect(mocks.managerStop).toHaveBeenCalledTimes(2);
1945
- expect(mocks.managerCallTool).toHaveBeenCalledTimes(2);
1946
- expect(result).toMatchObject({
1947
- app: "analytics",
1948
- embedStartUrl:
1949
- "http://localhost:8086/_agent-native/embed/start?ticket=remote",
1950
- });
1951
- randomSpy.mockRestore();
1952
- },
1953
- );
2429
+ it("rejects tampered, cross-user, cross-org, cross-app, cross-task, and expired handles fail-closed", async () => {
2430
+ vi.useFakeTimers();
2431
+ vi.setSystemTime(1_700_000_000_000);
2432
+ vi.stubEnv("A2A_SECRET", "sealed-handle-secret");
2433
+ mocks.getOrgSetting.mockResolvedValue({ mode: "all-apps" });
2434
+ mocks.getOrgDomain.mockResolvedValue("builder.io");
2435
+ mocks.a2aSend.mockResolvedValueOnce({
2436
+ id: "task-bound",
2437
+ status: { state: "working" },
2438
+ });
1954
2439
 
1955
- it("does not retry an HTML 404 whose body mentions a gateway status", async () => {
1956
- mocks.managerCallTool.mockRejectedValueOnce(
1957
- Object.assign(
1958
- new Error(
1959
- 'MCP server "target" is not connected: That URL returned a web page instead of an MCP response. Cloudflare HTTP 502 is unrelated.',
1960
- ),
1961
- { code: 404 },
1962
- ),
2440
+ const submitted = await runWithRequestContext(
2441
+ {
2442
+ userEmail: "owner@example.test",
2443
+ orgId: "org-1",
2444
+ requestOrigin: "http://localhost:8092",
2445
+ },
2446
+ () =>
2447
+ askGrantedDispatchMcpApp("analytics", "Compute revenue.", {
2448
+ async: true,
2449
+ }),
1963
2450
  );
2451
+ const validHandle = submitted.taskHandle ?? "";
2452
+ expect(validHandle).toMatch(/^v1\./);
2453
+ const tamperedHandle = `${validHandle.slice(0, -1)}${validHandle.endsWith("a") ? "b" : "a"}`;
2454
+ const invalidHandlePattern =
2455
+ /Invalid or expired ask_app task handle\. To keep polling the same task, call ask_app_status with the app and taskId from the ask_app result and leave out taskHandle\. Do not resubmit ask_app; that can duplicate work\./;
1964
2456
 
1965
2457
  await expect(
1966
2458
  runWithRequestContext(
1967
2459
  {
1968
2460
  userEmail: "owner@example.test",
2461
+ orgId: "org-1",
1969
2462
  requestOrigin: "http://localhost:8092",
1970
2463
  },
1971
2464
  () =>
1972
- createGrantedDispatchMcpEmbedSession({
1973
- app: "analytics",
1974
- path: "/dashboards",
2465
+ getGrantedDispatchMcpAppTask("analytics", "task-bound", {
2466
+ taskHandle: tamperedHandle,
1975
2467
  }),
1976
2468
  ),
1977
- ).rejects.toThrow(/Cloudflare HTTP 502 is unrelated/);
1978
- expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
1979
- });
1980
-
1981
- it("does not retry a typed permanent 4xx MCP error", async () => {
1982
- mocks.managerCallTool.mockRejectedValueOnce(
1983
- Object.assign(
1984
- new Error(
1985
- "Streamable HTTP error: Error POSTing to endpoint: <!doctype html><html>422</html>",
1986
- ),
1987
- { code: 422 },
1988
- ),
1989
- );
2469
+ ).rejects.toThrow(invalidHandlePattern);
1990
2470
 
1991
2471
  await expect(
1992
2472
  runWithRequestContext(
1993
2473
  {
1994
2474
  userEmail: "owner@example.test",
2475
+ orgId: "org-1",
1995
2476
  requestOrigin: "http://localhost:8092",
1996
2477
  },
1997
2478
  () =>
1998
- createGrantedDispatchMcpEmbedSession({
1999
- app: "analytics",
2000
- path: "/dashboards",
2479
+ getGrantedDispatchMcpAppTask("analytics", "task-bound", {
2480
+ taskHandle: "",
2001
2481
  }),
2002
2482
  ),
2003
- ).rejects.toThrow(/Streamable HTTP error/);
2004
- expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
2005
- });
2006
-
2007
- it("sends no delegated credential to a plain-HTTP target off this machine", async () => {
2008
- mocks.discoverAgents.mockResolvedValue([
2009
- { ...analyticsAgent, url: "http://analytics.example.test" },
2010
- ]);
2011
- mocks.managerCallTool.mockClear();
2483
+ ).rejects.toThrow(invalidHandlePattern);
2012
2484
 
2013
2485
  await expect(
2014
2486
  runWithRequestContext(
2015
2487
  {
2016
- userEmail: "owner@example.test",
2488
+ userEmail: "mallory@example.test",
2489
+ orgId: "org-1",
2017
2490
  requestOrigin: "http://localhost:8092",
2018
2491
  },
2019
2492
  () =>
2020
- createGrantedDispatchMcpEmbedSession({
2021
- app: "analytics",
2022
- path: "/dashboards",
2493
+ getGrantedDispatchMcpAppTask("analytics", "task-bound", {
2494
+ taskHandle: validHandle,
2023
2495
  }),
2024
2496
  ),
2025
- ).rejects.toThrow(/HTTPS target endpoint/);
2026
- expect(mocks.managerCallTool).not.toHaveBeenCalled();
2027
- });
2028
-
2029
- it("returns the normal open URL when embed preminting fails", async () => {
2030
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
2031
- mocks.managerCallTool.mockRejectedValueOnce(
2032
- new Error("Target app did not return an embed session."),
2033
- );
2034
-
2035
- const result = await runWithRequestContext(
2036
- {
2037
- userEmail: "owner@example.test",
2038
- requestOrigin: "http://localhost:8092",
2039
- },
2040
- () =>
2041
- openGrantedDispatchMcpApp({
2042
- app: "analytics",
2043
- path: "/dashboards",
2044
- embed: true,
2045
- chrome: "minimal",
2046
- }),
2047
- );
2048
-
2049
- expect(result).toEqual({
2050
- app: "analytics",
2051
- path: "/dashboards",
2052
- url: "http://localhost:8086/dashboards",
2053
- embed: true,
2054
- chrome: "minimal",
2055
- embedUnavailable: "Target app did not return an embed session.",
2056
- });
2057
- expect(warnSpy).toHaveBeenCalled();
2058
- warnSpy.mockRestore();
2059
- });
2060
-
2061
- it("pre-mints no session for a target whose endpoint is plain HTTP off this machine", async () => {
2062
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
2063
- mocks.discoverAgents.mockResolvedValue([
2064
- { ...analyticsAgent, url: "http://analytics.example.test" },
2065
- ]);
2066
- mocks.managerCallTool.mockClear();
2067
-
2068
- const result = await runWithRequestContext(
2069
- {
2070
- userEmail: "owner@example.test",
2071
- requestOrigin: "http://localhost:8092",
2072
- },
2073
- () =>
2074
- openGrantedDispatchMcpApp({
2075
- app: "analytics",
2076
- path: "/dashboards",
2077
- embed: true,
2078
- }),
2079
- );
2080
-
2081
- expect(mocks.managerCallTool).not.toHaveBeenCalled();
2082
- expect(result).not.toHaveProperty("embedStartUrl");
2083
- expect(result).toMatchObject({
2084
- embedUnavailable: expect.stringContaining("HTTPS target endpoint"),
2085
- });
2086
- expect(warnSpy).toHaveBeenCalled();
2087
- warnSpy.mockRestore();
2088
- });
2497
+ ).rejects.toThrow(invalidHandlePattern);
2089
2498
 
2090
- it("answers with the link when the target is slow to mint a session", async () => {
2091
- vi.useFakeTimers();
2092
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
2093
- try {
2094
- let rejectCall: (error: Error) => void = () => {};
2095
- mocks.managerCallTool.mockImplementationOnce(
2499
+ await expect(
2500
+ runWithRequestContext(
2501
+ {
2502
+ userEmail: "owner@example.test",
2503
+ orgId: "org-2",
2504
+ requestOrigin: "http://localhost:8092",
2505
+ },
2096
2506
  () =>
2097
- new Promise((_resolve, reject) => {
2098
- rejectCall = reject;
2507
+ getGrantedDispatchMcpAppTask("analytics", "task-bound", {
2508
+ taskHandle: validHandle,
2099
2509
  }),
2100
- );
2101
- // Stopping the client fails its pending call, as the SDK transport does.
2102
- mocks.managerStop.mockImplementation(async () =>
2103
- rejectCall(new Error("Connection closed")),
2104
- );
2105
- const pending = runWithRequestContext(
2510
+ ),
2511
+ ).rejects.toThrow(invalidHandlePattern);
2512
+
2513
+ await expect(
2514
+ runWithRequestContext(
2106
2515
  {
2107
2516
  userEmail: "owner@example.test",
2517
+ orgId: "org-1",
2108
2518
  requestOrigin: "http://localhost:8092",
2109
2519
  },
2110
2520
  () =>
2111
- openGrantedDispatchMcpApp({
2112
- app: "analytics",
2113
- path: "/dashboards",
2114
- embed: true,
2521
+ getGrantedDispatchMcpAppTask("mail", "task-bound", {
2522
+ taskHandle: validHandle,
2115
2523
  }),
2116
- );
2117
- await vi.advanceTimersByTimeAsync(15_000);
2118
- await expect(pending).resolves.toMatchObject({
2119
- url: "http://localhost:8086/dashboards",
2120
- embedUnavailable: expect.stringContaining("within 15s"),
2121
- });
2122
- await vi.advanceTimersByTimeAsync(60_000);
2123
- // The abandoned request was stopped, not retried in the background.
2124
- expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
2125
- expect(mocks.managerStop).toHaveBeenCalled();
2126
- } finally {
2127
- mocks.managerStop.mockReset();
2128
- mocks.managerStop.mockResolvedValue(undefined);
2129
- warnSpy.mockRestore();
2130
- vi.useRealTimers();
2131
- }
2132
- });
2524
+ ),
2525
+ ).rejects.toThrow(invalidHandlePattern);
2133
2526
 
2134
- it("rejects Dispatch-owned extension routes on sibling apps", async () => {
2135
2527
  await expect(
2136
2528
  runWithRequestContext(
2137
2529
  {
2138
2530
  userEmail: "owner@example.test",
2531
+ orgId: "org-1",
2139
2532
  requestOrigin: "http://localhost:8092",
2140
2533
  },
2141
2534
  () =>
2142
- openGrantedDispatchMcpApp({
2143
- app: "analytics",
2144
- path: "/extensions/ext-1/github-stars-over-time",
2535
+ getGrantedDispatchMcpAppTask("analytics", "task-other", {
2536
+ taskHandle: validHandle,
2145
2537
  }),
2146
2538
  ),
2147
- ).rejects.toThrow(/belongs to Dispatch/);
2148
- });
2539
+ ).rejects.toThrow(invalidHandlePattern);
2149
2540
 
2150
- it("rejects traversal that normalizes into Dispatch-owned routes on sibling apps", async () => {
2541
+ vi.advanceTimersByTime(60 * 60 * 1000 + 1_000);
2151
2542
  await expect(
2152
2543
  runWithRequestContext(
2153
2544
  {
2154
2545
  userEmail: "owner@example.test",
2546
+ orgId: "org-1",
2155
2547
  requestOrigin: "http://localhost:8092",
2156
2548
  },
2157
2549
  () =>
2158
- openGrantedDispatchMcpApp({
2159
- app: "analytics",
2160
- path: "/../dispatch/extensions/ext-1",
2550
+ getGrantedDispatchMcpAppTask("analytics", "task-bound", {
2551
+ taskHandle: validHandle,
2161
2552
  }),
2162
2553
  ),
2163
- ).rejects.toThrow(/safe app-relative route/);
2164
- });
2165
- });
2554
+ ).rejects.toThrow(invalidHandlePattern);
2166
2555
 
2167
- describe("createGrantedDispatchMcpEmbedSession", () => {
2168
- beforeEach(() => {
2169
- vi.stubEnv("A2A_SECRET", "shared-secret");
2170
- });
2556
+ expect(mocks.a2aGetTask).not.toHaveBeenCalled();
2171
2557
 
2172
- it("mints Dispatch self embeds locally instead of recursively calling Dispatch MCP", async () => {
2173
- const result = await runWithRequestContext(
2558
+ mocks.a2aGetTask.mockResolvedValueOnce({
2559
+ id: "task-bound",
2560
+ status: {
2561
+ state: "completed",
2562
+ message: {
2563
+ role: "agent",
2564
+ parts: [{ type: "text", text: "Recovered via legacy poll." }],
2565
+ },
2566
+ },
2567
+ });
2568
+ const legacyRecovered = await runWithRequestContext(
2174
2569
  {
2175
2570
  userEmail: "owner@example.test",
2571
+ orgId: "org-1",
2176
2572
  requestOrigin: "http://localhost:8092",
2177
2573
  },
2178
- () =>
2179
- createGrantedDispatchMcpEmbedSession({
2180
- app: "dispatch",
2181
- path: "/extensions/ext-1/github-stars-over-time",
2182
- chrome: "minimal",
2183
- }),
2574
+ () => getGrantedDispatchMcpAppTask("analytics", "task-bound"),
2184
2575
  );
2185
-
2186
- expect(mocks.createEmbedSessionTicket).toHaveBeenCalledWith({
2187
- ownerEmail: "owner@example.test",
2188
- orgId: undefined,
2189
- targetPath: "/extensions/ext-1/github-stars-over-time",
2190
- scope: "minimal",
2191
- });
2192
- expect(mocks.managerConstructor).not.toHaveBeenCalled();
2193
- expect(result).toEqual({
2194
- app: "dispatch",
2195
- startUrl:
2196
- "http://localhost:8092/_agent-native/embed/start?ticket=ticket-123",
2197
- targetPath: "/extensions/ext-1/github-stars-over-time",
2198
- expiresAt: 12345,
2576
+ expect(legacyRecovered).toEqual({
2577
+ app: "analytics",
2578
+ routedVia: "a2a",
2579
+ taskId: "task-bound",
2580
+ status: "completed",
2581
+ response: "Recovered via legacy poll.",
2199
2582
  });
2200
2583
  });
2201
2584
 
2202
- it("pins Dispatch self embeds to configured hosts instead of request context", async () => {
2203
- vi.stubEnv("WORKSPACE_GATEWAY_URL", "");
2204
- vi.stubEnv("APP_URL", "https://dispatch.agent-native.test");
2205
- vi.stubEnv("APP_BASE_PATH", "");
2206
- vi.stubEnv("VITE_APP_BASE_PATH", "");
2585
+ it("forwards optional taskHandle through the ask_app_status action while preserving legacy callers", async () => {
2586
+ vi.stubEnv("A2A_SECRET", "sealed-handle-secret");
2587
+ mocks.a2aSend.mockResolvedValueOnce({
2588
+ id: "task-via-action",
2589
+ status: { state: "working" },
2590
+ });
2207
2591
 
2208
- const result = await runWithRequestContext(
2592
+ const submitted = await runWithRequestContext(
2209
2593
  {
2210
2594
  userEmail: "owner@example.test",
2211
- requestOrigin: "https://attacker.example",
2595
+ requestOrigin: "http://localhost:8092",
2212
2596
  },
2213
2597
  () =>
2214
- createGrantedDispatchMcpEmbedSession({
2215
- app: "dispatch",
2216
- path: "/extensions/ext-1/github-stars-over-time",
2217
- chrome: "minimal",
2598
+ askGrantedDispatchMcpApp("analytics", "Build summary.", {
2599
+ async: true,
2218
2600
  }),
2219
2601
  );
2220
2602
 
2221
- expect(result.startUrl).toBe(
2222
- "https://dispatch.agent-native.test/_agent-native/embed/start?ticket=ticket-123",
2223
- );
2224
- });
2225
-
2226
- it("logs an invalid production origin while accepting a trusted runtime origin", async () => {
2227
- const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
2228
- vi.stubEnv("APP_URL", "not-a-url");
2229
- vi.stubEnv("WORKSPACE_GATEWAY_URL", "https://runtime.example/dispatch");
2230
- vi.stubEnv("APP_BASE_PATH", "");
2603
+ mocks.discoverAgents.mockReset();
2604
+ mocks.discoverAgents.mockResolvedValue([
2605
+ { ...analyticsAgent, url: "http://localhost:9999" },
2606
+ ]);
2607
+ mocks.a2aConstructor.mockClear();
2608
+ mocks.a2aGetTask.mockResolvedValueOnce({
2609
+ id: "task-via-action",
2610
+ status: {
2611
+ state: "completed",
2612
+ message: {
2613
+ role: "agent",
2614
+ parts: [{ type: "text", text: "Summary done." }],
2615
+ },
2616
+ },
2617
+ });
2618
+
2619
+ const withHandle = await runWithRequestContext(
2620
+ {
2621
+ userEmail: "owner@example.test",
2622
+ requestOrigin: "http://localhost:8092",
2623
+ },
2624
+ () =>
2625
+ askAppStatusAction.run({
2626
+ app: "analytics",
2627
+ taskId: "task-via-action",
2628
+ taskHandle: submitted.taskHandle,
2629
+ }),
2630
+ );
2631
+ expect(withHandle).toMatchObject({
2632
+ app: "analytics",
2633
+ taskId: "task-via-action",
2634
+ status: "completed",
2635
+ response: "Summary done.",
2636
+ });
2637
+ expect(mocks.discoverAgents).not.toHaveBeenCalled();
2638
+ expect(mocks.a2aConstructor).toHaveBeenCalledWith(
2639
+ "http://localhost:8086",
2640
+ "signed-token",
2641
+ expect.objectContaining({ requestTimeoutMs: 10_000 }),
2642
+ );
2643
+
2644
+ mocks.a2aConstructor.mockClear();
2645
+ mocks.a2aGetTask.mockResolvedValueOnce({
2646
+ id: "task-via-action",
2647
+ status: {
2648
+ state: "completed",
2649
+ message: {
2650
+ role: "agent",
2651
+ parts: [{ type: "text", text: "Legacy summary done." }],
2652
+ },
2653
+ },
2654
+ });
2655
+ const withoutHandle = await runWithRequestContext(
2656
+ {
2657
+ userEmail: "owner@example.test",
2658
+ requestOrigin: "http://localhost:8092",
2659
+ },
2660
+ () =>
2661
+ askAppStatusAction.run({
2662
+ app: "analytics",
2663
+ taskId: "task-via-action",
2664
+ }),
2665
+ );
2666
+ expect(withoutHandle).toMatchObject({
2667
+ app: "analytics",
2668
+ taskId: "task-via-action",
2669
+ status: "completed",
2670
+ response: "Legacy summary done.",
2671
+ });
2672
+ expect(mocks.discoverAgents).toHaveBeenCalledTimes(1);
2673
+ expect(mocks.a2aConstructor).toHaveBeenCalledWith(
2674
+ "http://localhost:9999",
2675
+ "signed-token",
2676
+ expect.objectContaining({ requestTimeoutMs: 10_000 }),
2677
+ );
2678
+ });
2679
+ });
2680
+
2681
+ describe("openGrantedDispatchMcpApp", () => {
2682
+ beforeEach(() => {
2683
+ vi.stubEnv("A2A_SECRET", "shared-secret");
2684
+ });
2231
2685
 
2686
+ it("opens Dispatch extension routes through the Dispatch app id", async () => {
2232
2687
  const result = await runWithRequestContext(
2233
2688
  {
2234
2689
  userEmail: "owner@example.test",
2235
- requestOrigin: "https://runtime.example",
2690
+ requestOrigin: "http://localhost:8092",
2236
2691
  },
2237
2692
  () =>
2238
- createGrantedDispatchMcpEmbedSession({
2693
+ openGrantedDispatchMcpApp({
2239
2694
  app: "dispatch",
2240
2695
  path: "/extensions/ext-1/github-stars-over-time",
2696
+ embed: true,
2241
2697
  chrome: "minimal",
2242
2698
  }),
2243
2699
  );
2244
2700
 
2245
- expect(result.startUrl).toBe(
2246
- "https://runtime.example/_agent-native/embed/start?ticket=ticket-123",
2701
+ expect(result).toEqual({
2702
+ app: "dispatch",
2703
+ path: "/extensions/ext-1/github-stars-over-time",
2704
+ url: "http://localhost:8092/extensions/ext-1/github-stars-over-time",
2705
+ embed: true,
2706
+ chrome: "minimal",
2707
+ embedStartUrl:
2708
+ "http://localhost:8092/_agent-native/embed/start?ticket=ticket-123",
2709
+ embedTargetPath: "/extensions/ext-1/github-stars-over-time",
2710
+ embedExpiresAt: 12345,
2711
+ });
2712
+ });
2713
+
2714
+ it("pre-mints cross-app embed sessions for MCP app hosts", async () => {
2715
+ const result = await runWithRequestContext(
2716
+ {
2717
+ userEmail: "owner@example.test",
2718
+ requestOrigin: "http://localhost:8092",
2719
+ },
2720
+ () =>
2721
+ openGrantedDispatchMcpApp({
2722
+ app: "analytics",
2723
+ path: "/dashboards?range=30d",
2724
+ embed: true,
2725
+ chrome: "minimal",
2726
+ }),
2247
2727
  );
2248
- expect(warn).toHaveBeenCalledWith(
2249
- "[dispatch] invalid configured request origin",
2250
- { source: "production" },
2728
+
2729
+ expect(mocks.managerCallTool).toHaveBeenCalledWith(
2730
+ "mcp__target__create_embed_session",
2731
+ {
2732
+ url: "http://localhost:8086/dashboards?range=30d",
2733
+ chrome: "minimal",
2734
+ },
2251
2735
  );
2736
+ expect(result).toEqual({
2737
+ app: "analytics",
2738
+ path: "/dashboards?range=30d",
2739
+ url: "http://localhost:8086/dashboards?range=30d",
2740
+ embed: true,
2741
+ chrome: "minimal",
2742
+ embedStartUrl:
2743
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
2744
+ });
2252
2745
  });
2253
2746
 
2254
- it("keeps workspace sign-in behind the rollout flag", async () => {
2255
- mocks.isFeatureFlagEnabled.mockResolvedValue(false);
2256
-
2257
- await expect(
2747
+ it("hands off first-party opens within one second and shares the pending mint with the pane", async () => {
2748
+ vi.useFakeTimers();
2749
+ const asOwner = <T>(run: () => Promise<T>) =>
2258
2750
  runWithRequestContext(
2259
2751
  {
2260
2752
  userEmail: "owner@example.test",
2753
+ identityAuthenticatedAtMs: 1,
2261
2754
  requestOrigin: "http://localhost:8092",
2262
2755
  },
2263
- () =>
2264
- createWorkspaceSsoEmbedSession({
2265
- app: "analytics",
2266
- path: "/overview",
2267
- }),
2756
+ run,
2757
+ );
2758
+ const startUrl =
2759
+ "http://localhost:8086/_agent-native/embed/start?ticket=prefetch-fixture";
2760
+ mocks.managerCallTool.mockImplementationOnce(
2761
+ (_tool: string, { url }: { url: string }) =>
2762
+ new Promise((resolve) => {
2763
+ const { pathname, search } = new URL(url);
2764
+ setTimeout(
2765
+ () =>
2766
+ resolve({
2767
+ structuredContent: { startUrl, targetPath: pathname + search },
2768
+ }),
2769
+ 12_000,
2770
+ );
2771
+ }),
2772
+ );
2773
+
2774
+ const input = {
2775
+ app: "analytics",
2776
+ path: "/dashboards",
2777
+ chrome: "minimal",
2778
+ } as const;
2779
+ let handoff:
2780
+ | Awaited<ReturnType<typeof openGrantedDispatchMcpApp>>
2781
+ | undefined;
2782
+ const opening = asOwner(() =>
2783
+ openGrantedDispatchMcpApp(
2784
+ { ...input, embed: true },
2785
+ { prefetchEmbed: true },
2268
2786
  ),
2269
- ).rejects.toThrow(/not enabled/);
2270
- expect(mocks.managerConstructor).not.toHaveBeenCalled();
2271
- });
2787
+ ).then((result) => {
2788
+ handoff = result;
2789
+ });
2790
+ await vi.advanceTimersByTimeAsync(1_000);
2791
+ expect(handoff).toEqual({
2792
+ ...input,
2793
+ embed: true,
2794
+ url: "http://localhost:8086/dashboards",
2795
+ });
2796
+ await opening;
2797
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
2272
2798
 
2273
- it("allows Desktop workspace sign-in when Dispatch pane SSO is off", async () => {
2274
- mocks.isFeatureFlagEnabled.mockImplementation(
2275
- async (flag) => flag.key === "desktop.workspace-sso",
2799
+ await vi.advanceTimersByTimeAsync(10_500);
2800
+ const pane = asOwner(() =>
2801
+ createGrantedDispatchMcpEmbedSession(input, { bindBrowserTab: true }),
2802
+ );
2803
+ await vi.advanceTimersByTimeAsync(500);
2804
+ const { childBrowserTabId, targetPath } = await pane;
2805
+ const launchUrl = new URL(mocks.managerCallTool.mock.calls[0][1].url);
2806
+ expect(childBrowserTabId).toMatch(/^[0-9a-f-]{36}$/i);
2807
+ expect(launchUrl.searchParams.get("agentNativeTab")).toBe(
2808
+ childBrowserTabId,
2276
2809
  );
2810
+ expect(targetPath).toBe("/dashboards");
2811
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
2277
2812
 
2278
2813
  await expect(
2814
+ asOwner(() =>
2815
+ createGrantedDispatchMcpEmbedSession(input, { bindBrowserTab: true }),
2816
+ ),
2817
+ ).resolves.toMatchObject({
2818
+ startUrl: expect.not.stringContaining("prefetch-fixture"),
2819
+ });
2820
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(2);
2821
+ });
2822
+
2823
+ it("cancels a stalled prefetch claimed by the pane and runs its fallback mint", async () => {
2824
+ vi.useFakeTimers();
2825
+ const asOwner = <T>(run: () => Promise<T>) =>
2279
2826
  runWithRequestContext(
2280
2827
  {
2281
2828
  userEmail: "owner@example.test",
2282
2829
  requestOrigin: "http://localhost:8092",
2830
+ identityAuthenticatedAtMs: 1,
2283
2831
  },
2284
- () =>
2285
- createWorkspaceSsoEmbedSession({
2286
- app: "analytics",
2287
- path: "/overview",
2288
- }),
2289
- ),
2290
- ).resolves.toMatchObject({ app: "analytics" });
2832
+ run,
2833
+ );
2834
+ const input = {
2835
+ app: "analytics",
2836
+ path: "/dashboards",
2837
+ chrome: "minimal",
2838
+ } as const;
2839
+ mocks.managerCallTool.mockImplementationOnce(() => new Promise(() => {}));
2291
2840
 
2292
- expect(
2293
- mocks.isFeatureFlagEnabled.mock.calls.map(([flag]) => flag.key),
2294
- ).toEqual(["dispatch.workspace-sso", "desktop.workspace-sso"]);
2295
- expect(mocks.managerConstructor).toHaveBeenCalled();
2841
+ await asOwner(() =>
2842
+ openGrantedDispatchMcpApp(input, { prefetchEmbed: true }),
2843
+ );
2844
+ await vi.advanceTimersByTimeAsync(0);
2845
+ const pane = asOwner(() =>
2846
+ createGrantedDispatchMcpEmbedSession(input, { bindBrowserTab: true }),
2847
+ );
2848
+ await vi.advanceTimersByTimeAsync(1_000);
2849
+ await expect(pane).resolves.toMatchObject({ app: "analytics" });
2850
+ expect(mocks.managerStop).toHaveBeenCalled();
2851
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(2);
2296
2852
  });
2297
2853
 
2298
- it("allows an exact canonical app without requiring an MCP app grant", async () => {
2299
- mocks.getUserSetting.mockResolvedValue({
2300
- mode: "selected-apps",
2301
- selectedAppIds: [],
2302
- });
2303
- mocks.discoverAgents.mockResolvedValue([
2304
- {
2305
- ...analyticsAgent,
2306
- url: "https://analytics.agent-native.com",
2307
- },
2308
- ]);
2854
+ it("checks the current grant and keeps prefetched tickets within the initiating workspace", async () => {
2855
+ vi.useFakeTimers();
2856
+ const asOwner = <T>(orgId: string, run: () => Promise<T>) =>
2857
+ runWithRequestContext(
2858
+ {
2859
+ userEmail: "owner@example.test",
2860
+ identityAuthenticatedAtMs: 1,
2861
+ orgId,
2862
+ requestOrigin: "http://localhost:8092",
2863
+ },
2864
+ run,
2865
+ );
2866
+ const startUrl =
2867
+ "http://localhost:8086/_agent-native/embed/start?ticket=workspace-fixture";
2309
2868
  mocks.managerCallTool.mockResolvedValueOnce({
2310
- structuredContent: {
2311
- startUrl:
2312
- "https://analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
2313
- },
2869
+ structuredContent: { startUrl },
2314
2870
  });
2315
-
2316
- const result = await runWithRequestContext(
2317
- {
2318
- userEmail: "owner@example.test",
2319
- requestOrigin: "https://dispatch.agent-native.com",
2320
- },
2321
- () =>
2322
- createWorkspaceSsoEmbedSession({
2323
- app: "analytics",
2324
- path: "/overview",
2325
- chrome: "minimal",
2326
- }),
2871
+ const input = {
2872
+ app: "analytics",
2873
+ path: "/dashboards",
2874
+ chrome: "minimal",
2875
+ } as const;
2876
+ await asOwner("prefetch-workspace", () =>
2877
+ openGrantedDispatchMcpApp(input, { prefetchEmbed: true }),
2327
2878
  );
2879
+ await vi.advanceTimersByTimeAsync(0);
2328
2880
 
2329
- expect(result).toMatchObject({
2330
- app: "analytics",
2331
- startUrl:
2332
- "https://analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
2881
+ await expect(
2882
+ asOwner("another-workspace", () =>
2883
+ createGrantedDispatchMcpEmbedSession(input, { bindBrowserTab: true }),
2884
+ ),
2885
+ ).resolves.toMatchObject({
2886
+ startUrl: expect.not.stringContaining("workspace-fixture"),
2333
2887
  });
2334
- expect(mocks.managerConstructor).toHaveBeenCalled();
2335
- });
2336
2888
 
2337
- it("keeps canonical workspace SSO apps eligible on the beta lane", async () => {
2338
- mocks.getUserSetting.mockResolvedValue({
2889
+ mocks.getOrgSetting.mockResolvedValue({
2339
2890
  mode: "selected-apps",
2340
- selectedAppIds: [],
2891
+ selectedAppIds: ["dispatch"],
2341
2892
  });
2342
- mocks.discoverAgents.mockResolvedValue([
2343
- {
2344
- ...analyticsAgent,
2345
- url: "https://analytics.agent-native.com",
2346
- },
2347
- ]);
2893
+ await expect(
2894
+ asOwner("prefetch-workspace", () =>
2895
+ createGrantedDispatchMcpEmbedSession(input, { bindBrowserTab: true }),
2896
+ ),
2897
+ ).rejects.toThrow(/not granted/);
2898
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(2);
2899
+ await vi.advanceTimersByTimeAsync(15_000);
2900
+ });
2901
+
2902
+ it("reads the target embed start URL from Core MCP response metadata", async () => {
2348
2903
  mocks.managerCallTool.mockResolvedValueOnce({
2349
2904
  structuredContent: {
2350
- startUrl:
2351
- "https://beta.analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
2905
+ targetPath: "/dashboards?range=30d",
2906
+ expiresAt: 12345,
2907
+ },
2908
+ _meta: {
2909
+ "agent-native/embedStart": {
2910
+ startUrl:
2911
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
2912
+ },
2352
2913
  },
2353
2914
  });
2354
2915
 
2355
2916
  const result = await runWithRequestContext(
2356
2917
  {
2357
2918
  userEmail: "owner@example.test",
2358
- requestOrigin: "https://beta.dispatch.agent-native.com",
2919
+ requestOrigin: "http://localhost:8092",
2359
2920
  },
2360
2921
  () =>
2361
- createWorkspaceSsoEmbedSession({
2922
+ openGrantedDispatchMcpApp({
2362
2923
  app: "analytics",
2363
- path: "/overview",
2924
+ path: "/dashboards?range=30d",
2925
+ embed: true,
2926
+ chrome: "minimal",
2364
2927
  }),
2365
2928
  );
2366
2929
 
2367
2930
  expect(result).toMatchObject({
2368
2931
  app: "analytics",
2369
- startUrl:
2370
- "https://beta.analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
2371
- });
2932
+ embedStartUrl:
2933
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
2934
+ embedTargetPath: "/dashboards?range=30d",
2935
+ embedExpiresAt: 12345,
2936
+ });
2937
+ });
2938
+
2939
+ it("answers with the link and stops the target when it is slow to mint a session", async () => {
2940
+ vi.useFakeTimers();
2941
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
2942
+ try {
2943
+ let rejectCall: (error: Error) => void = () => {};
2944
+ mocks.managerCallTool.mockImplementationOnce(
2945
+ () =>
2946
+ new Promise((_resolve, reject) => {
2947
+ rejectCall = reject;
2948
+ }),
2949
+ );
2950
+ // Stopping the client fails its pending call, as the SDK transport does.
2951
+ mocks.managerStop.mockImplementation(async () =>
2952
+ rejectCall(new Error("Connection closed")),
2953
+ );
2954
+ const pending = runWithRequestContext(
2955
+ {
2956
+ userEmail: "owner@example.test",
2957
+ requestOrigin: "http://localhost:8092",
2958
+ },
2959
+ () =>
2960
+ openGrantedDispatchMcpApp({
2961
+ app: "analytics",
2962
+ path: "/dashboards",
2963
+ embed: true,
2964
+ }),
2965
+ );
2966
+ await vi.advanceTimersByTimeAsync(15_000);
2967
+ const result = await pending;
2968
+ expect(result).toMatchObject({
2969
+ app: "analytics",
2970
+ url: "http://localhost:8086/dashboards",
2971
+ });
2972
+ expect(result).not.toHaveProperty("embedStartUrl");
2973
+ await vi.advanceTimersByTimeAsync(60_000);
2974
+ // The abandoned request was stopped, not retried in the background.
2975
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
2976
+ expect(mocks.managerStop).toHaveBeenCalled();
2977
+ } finally {
2978
+ mocks.managerStop.mockReset();
2979
+ mocks.managerStop.mockResolvedValue(undefined);
2980
+ warnSpy.mockRestore();
2981
+ vi.useRealTimers();
2982
+ }
2983
+ });
2984
+
2985
+ it("reads the target embed start URL when Core returns JSON text", async () => {
2986
+ mocks.managerCallTool.mockResolvedValueOnce({
2987
+ content: [
2988
+ {
2989
+ type: "text",
2990
+ text: JSON.stringify({
2991
+ targetPath: "/dashboards?range=30d",
2992
+ expiresAt: 12345,
2993
+ }),
2994
+ },
2995
+ ],
2996
+ _meta: {
2997
+ "agent-native/embedStart": {
2998
+ startUrl:
2999
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
3000
+ },
3001
+ },
3002
+ });
3003
+
3004
+ const result = await runWithRequestContext(
3005
+ {
3006
+ userEmail: "owner@example.test",
3007
+ requestOrigin: "http://localhost:8092",
3008
+ },
3009
+ () =>
3010
+ openGrantedDispatchMcpApp({
3011
+ app: "analytics",
3012
+ path: "/dashboards?range=30d",
3013
+ embed: true,
3014
+ chrome: "minimal",
3015
+ }),
3016
+ );
3017
+
3018
+ expect(result).toMatchObject({
3019
+ app: "analytics",
3020
+ embedStartUrl:
3021
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
3022
+ embedTargetPath: "/dashboards?range=30d",
3023
+ embedExpiresAt: 12345,
3024
+ });
3025
+ });
3026
+
3027
+ it.each([408, 429, 502, 503, 504])(
3028
+ "retries transient typed HTTP %i target MCP failures with HTML bodies",
3029
+ async (status) => {
3030
+ const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0);
3031
+ mocks.managerCallTool
3032
+ .mockRejectedValueOnce(
3033
+ Object.assign(
3034
+ new Error(
3035
+ 'MCP server "target" is not connected: That URL returned a web page instead of an MCP response. Check that you pasted the Streamable HTTP endpoint, often ending in /mcp.',
3036
+ ),
3037
+ { code: status },
3038
+ ),
3039
+ )
3040
+ .mockResolvedValueOnce({
3041
+ structuredContent: {
3042
+ startUrl:
3043
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
3044
+ },
3045
+ });
3046
+
3047
+ const result = await runWithRequestContext(
3048
+ {
3049
+ userEmail: "owner@example.test",
3050
+ requestOrigin: "http://localhost:8092",
3051
+ },
3052
+ () =>
3053
+ openGrantedDispatchMcpApp({
3054
+ app: "analytics",
3055
+ path: "/dashboards",
3056
+ embed: true,
3057
+ }),
3058
+ );
3059
+
3060
+ expect(mocks.managerConstructor).toHaveBeenCalledTimes(2);
3061
+ expect(mocks.managerStart).toHaveBeenCalledTimes(2);
3062
+ expect(mocks.managerStop).toHaveBeenCalledTimes(2);
3063
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(2);
3064
+ expect(result).toMatchObject({
3065
+ app: "analytics",
3066
+ embedStartUrl:
3067
+ "http://localhost:8086/_agent-native/embed/start?ticket=remote",
3068
+ });
3069
+ randomSpy.mockRestore();
3070
+ },
3071
+ );
3072
+
3073
+ it("does not retry an HTML 404 whose body mentions a gateway status", async () => {
3074
+ mocks.managerCallTool.mockRejectedValueOnce(
3075
+ Object.assign(
3076
+ new Error(
3077
+ 'MCP server "target" is not connected: That URL returned a web page instead of an MCP response. Cloudflare HTTP 502 is unrelated.',
3078
+ ),
3079
+ { code: 404 },
3080
+ ),
3081
+ );
3082
+
3083
+ await expect(
3084
+ runWithRequestContext(
3085
+ {
3086
+ userEmail: "owner@example.test",
3087
+ requestOrigin: "http://localhost:8092",
3088
+ },
3089
+ () =>
3090
+ createGrantedDispatchMcpEmbedSession({
3091
+ app: "analytics",
3092
+ path: "/dashboards",
3093
+ }),
3094
+ ),
3095
+ ).rejects.toThrow(/Cloudflare HTTP 502 is unrelated/);
3096
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
3097
+ });
3098
+
3099
+ it("does not retry a typed permanent 4xx MCP error", async () => {
3100
+ mocks.managerCallTool.mockRejectedValueOnce(
3101
+ Object.assign(
3102
+ new Error(
3103
+ "Streamable HTTP error: Error POSTing to endpoint: <!doctype html><html>422</html>",
3104
+ ),
3105
+ { code: 422 },
3106
+ ),
3107
+ );
3108
+
3109
+ await expect(
3110
+ runWithRequestContext(
3111
+ {
3112
+ userEmail: "owner@example.test",
3113
+ requestOrigin: "http://localhost:8092",
3114
+ },
3115
+ () =>
3116
+ createGrantedDispatchMcpEmbedSession({
3117
+ app: "analytics",
3118
+ path: "/dashboards",
3119
+ }),
3120
+ ),
3121
+ ).rejects.toThrow(/Streamable HTTP error/);
3122
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
3123
+ });
3124
+
3125
+ it("sends no delegated credential to a plain-HTTP target off this machine", async () => {
3126
+ mocks.discoverAgents.mockResolvedValue([
3127
+ { ...analyticsAgent, url: "http://analytics.example.test" },
3128
+ ]);
3129
+ mocks.managerCallTool.mockClear();
3130
+
3131
+ await expect(
3132
+ runWithRequestContext(
3133
+ {
3134
+ userEmail: "owner@example.test",
3135
+ requestOrigin: "http://localhost:8092",
3136
+ },
3137
+ () =>
3138
+ createGrantedDispatchMcpEmbedSession({
3139
+ app: "analytics",
3140
+ path: "/dashboards",
3141
+ }),
3142
+ ),
3143
+ ).rejects.toThrow(/HTTPS target endpoint/);
3144
+ expect(mocks.managerCallTool).not.toHaveBeenCalled();
3145
+ });
3146
+
3147
+ it("returns the normal open URL when embed preminting fails", async () => {
3148
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
3149
+ mocks.managerCallTool.mockRejectedValueOnce(
3150
+ new Error("Target app did not return an embed session."),
3151
+ );
3152
+
3153
+ const result = await runWithRequestContext(
3154
+ {
3155
+ userEmail: "owner@example.test",
3156
+ requestOrigin: "http://localhost:8092",
3157
+ },
3158
+ () =>
3159
+ openGrantedDispatchMcpApp({
3160
+ app: "analytics",
3161
+ path: "/dashboards",
3162
+ embed: true,
3163
+ chrome: "minimal",
3164
+ }),
3165
+ );
3166
+
3167
+ expect(result).toEqual({
3168
+ app: "analytics",
3169
+ path: "/dashboards",
3170
+ url: "http://localhost:8086/dashboards",
3171
+ embed: true,
3172
+ chrome: "minimal",
3173
+ embedUnavailable: "Target app did not return an embed session.",
3174
+ });
3175
+ expect(warnSpy).toHaveBeenCalled();
3176
+ warnSpy.mockRestore();
3177
+ });
3178
+
3179
+ it("pre-mints no session for a target whose endpoint is plain HTTP off this machine", async () => {
3180
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
3181
+ mocks.discoverAgents.mockResolvedValue([
3182
+ { ...analyticsAgent, url: "http://analytics.example.test" },
3183
+ ]);
3184
+ mocks.managerCallTool.mockClear();
3185
+
3186
+ const result = await runWithRequestContext(
3187
+ {
3188
+ userEmail: "owner@example.test",
3189
+ requestOrigin: "http://localhost:8092",
3190
+ },
3191
+ () =>
3192
+ openGrantedDispatchMcpApp({
3193
+ app: "analytics",
3194
+ path: "/dashboards",
3195
+ embed: true,
3196
+ }),
3197
+ );
3198
+
3199
+ expect(mocks.managerCallTool).not.toHaveBeenCalled();
3200
+ expect(result).not.toHaveProperty("embedStartUrl");
3201
+ expect(result).toMatchObject({
3202
+ embedUnavailable: expect.stringContaining("HTTPS target endpoint"),
3203
+ });
3204
+ expect(warnSpy).toHaveBeenCalled();
3205
+ warnSpy.mockRestore();
3206
+ });
3207
+
3208
+ it("answers with the link when the target is slow to mint a session", async () => {
3209
+ vi.useFakeTimers();
3210
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
3211
+ try {
3212
+ let rejectCall: (error: Error) => void = () => {};
3213
+ mocks.managerCallTool.mockImplementationOnce(
3214
+ () =>
3215
+ new Promise((_resolve, reject) => {
3216
+ rejectCall = reject;
3217
+ }),
3218
+ );
3219
+ // Stopping the client fails its pending call, as the SDK transport does.
3220
+ mocks.managerStop.mockImplementation(async () =>
3221
+ rejectCall(new Error("Connection closed")),
3222
+ );
3223
+ const pending = runWithRequestContext(
3224
+ {
3225
+ userEmail: "owner@example.test",
3226
+ requestOrigin: "http://localhost:8092",
3227
+ },
3228
+ () =>
3229
+ openGrantedDispatchMcpApp({
3230
+ app: "analytics",
3231
+ path: "/dashboards",
3232
+ embed: true,
3233
+ }),
3234
+ );
3235
+ await vi.advanceTimersByTimeAsync(15_000);
3236
+ await expect(pending).resolves.toMatchObject({
3237
+ url: "http://localhost:8086/dashboards",
3238
+ embedUnavailable: expect.stringContaining("within 15s"),
3239
+ });
3240
+ await vi.advanceTimersByTimeAsync(60_000);
3241
+ // The abandoned request was stopped, not retried in the background.
3242
+ expect(mocks.managerCallTool).toHaveBeenCalledTimes(1);
3243
+ expect(mocks.managerStop).toHaveBeenCalled();
3244
+ } finally {
3245
+ mocks.managerStop.mockReset();
3246
+ mocks.managerStop.mockResolvedValue(undefined);
3247
+ warnSpy.mockRestore();
3248
+ vi.useRealTimers();
3249
+ }
3250
+ });
3251
+
3252
+ it("rejects Dispatch-owned extension routes on sibling apps", async () => {
3253
+ await expect(
3254
+ runWithRequestContext(
3255
+ {
3256
+ userEmail: "owner@example.test",
3257
+ requestOrigin: "http://localhost:8092",
3258
+ },
3259
+ () =>
3260
+ openGrantedDispatchMcpApp({
3261
+ app: "analytics",
3262
+ path: "/extensions/ext-1/github-stars-over-time",
3263
+ }),
3264
+ ),
3265
+ ).rejects.toThrow(/belongs to Dispatch/);
3266
+ });
3267
+
3268
+ it("rejects traversal that normalizes into Dispatch-owned routes on sibling apps", async () => {
3269
+ await expect(
3270
+ runWithRequestContext(
3271
+ {
3272
+ userEmail: "owner@example.test",
3273
+ requestOrigin: "http://localhost:8092",
3274
+ },
3275
+ () =>
3276
+ openGrantedDispatchMcpApp({
3277
+ app: "analytics",
3278
+ path: "/../dispatch/extensions/ext-1",
3279
+ }),
3280
+ ),
3281
+ ).rejects.toThrow(/safe app-relative route/);
3282
+ });
3283
+ });
3284
+
3285
+ describe("createGrantedDispatchMcpEmbedSession", () => {
3286
+ beforeEach(() => {
3287
+ vi.stubEnv("A2A_SECRET", "shared-secret");
3288
+ });
3289
+
3290
+ it("mints Dispatch self embeds locally instead of recursively calling Dispatch MCP", async () => {
3291
+ const result = await runWithRequestContext(
3292
+ {
3293
+ userEmail: "owner@example.test",
3294
+ requestOrigin: "http://localhost:8092",
3295
+ },
3296
+ () =>
3297
+ createGrantedDispatchMcpEmbedSession({
3298
+ app: "dispatch",
3299
+ path: "/extensions/ext-1/github-stars-over-time",
3300
+ chrome: "minimal",
3301
+ }),
3302
+ );
3303
+
3304
+ expect(mocks.createEmbedSessionTicket).toHaveBeenCalledWith({
3305
+ ownerEmail: "owner@example.test",
3306
+ orgId: undefined,
3307
+ targetPath: "/extensions/ext-1/github-stars-over-time",
3308
+ scope: "minimal",
3309
+ });
3310
+ expect(mocks.managerConstructor).not.toHaveBeenCalled();
3311
+ expect(result).toEqual({
3312
+ app: "dispatch",
3313
+ startUrl:
3314
+ "http://localhost:8092/_agent-native/embed/start?ticket=ticket-123",
3315
+ targetPath: "/extensions/ext-1/github-stars-over-time",
3316
+ expiresAt: 12345,
3317
+ });
3318
+ });
3319
+
3320
+ it("pins Dispatch self embeds to configured hosts instead of request context", async () => {
3321
+ vi.stubEnv("WORKSPACE_GATEWAY_URL", "");
3322
+ vi.stubEnv("APP_URL", "https://dispatch.agent-native.test");
3323
+ vi.stubEnv("APP_BASE_PATH", "");
3324
+ vi.stubEnv("VITE_APP_BASE_PATH", "");
3325
+
3326
+ const result = await runWithRequestContext(
3327
+ {
3328
+ userEmail: "owner@example.test",
3329
+ requestOrigin: "https://attacker.example",
3330
+ },
3331
+ () =>
3332
+ createGrantedDispatchMcpEmbedSession({
3333
+ app: "dispatch",
3334
+ path: "/extensions/ext-1/github-stars-over-time",
3335
+ chrome: "minimal",
3336
+ }),
3337
+ );
3338
+
3339
+ expect(result.startUrl).toBe(
3340
+ "https://dispatch.agent-native.test/_agent-native/embed/start?ticket=ticket-123",
3341
+ );
3342
+ });
3343
+
3344
+ it("logs an invalid production origin while accepting a trusted runtime origin", async () => {
3345
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
3346
+ vi.stubEnv("APP_URL", "not-a-url");
3347
+ vi.stubEnv("WORKSPACE_GATEWAY_URL", "https://runtime.example/dispatch");
3348
+ vi.stubEnv("APP_BASE_PATH", "");
3349
+
3350
+ const result = await runWithRequestContext(
3351
+ {
3352
+ userEmail: "owner@example.test",
3353
+ requestOrigin: "https://runtime.example",
3354
+ },
3355
+ () =>
3356
+ createGrantedDispatchMcpEmbedSession({
3357
+ app: "dispatch",
3358
+ path: "/extensions/ext-1/github-stars-over-time",
3359
+ chrome: "minimal",
3360
+ }),
3361
+ );
3362
+
3363
+ expect(result.startUrl).toBe(
3364
+ "https://runtime.example/_agent-native/embed/start?ticket=ticket-123",
3365
+ );
3366
+ expect(warn).toHaveBeenCalledWith(
3367
+ "[dispatch] invalid configured request origin",
3368
+ { source: "production" },
3369
+ );
3370
+ });
3371
+
3372
+ it("keeps workspace sign-in behind the rollout flag", async () => {
3373
+ mocks.isFeatureFlagEnabled.mockResolvedValue(false);
3374
+
3375
+ await expect(
3376
+ runWithRequestContext(
3377
+ {
3378
+ userEmail: "owner@example.test",
3379
+ requestOrigin: "http://localhost:8092",
3380
+ },
3381
+ () =>
3382
+ createWorkspaceSsoEmbedSession({
3383
+ app: "analytics",
3384
+ path: "/overview",
3385
+ }),
3386
+ ),
3387
+ ).rejects.toThrow(/not enabled/);
3388
+ expect(mocks.managerConstructor).not.toHaveBeenCalled();
3389
+ });
3390
+
3391
+ it("allows Desktop workspace sign-in when Dispatch pane SSO is off", async () => {
3392
+ mocks.isFeatureFlagEnabled.mockImplementation(
3393
+ async (flag) => flag.key === "desktop.workspace-sso",
3394
+ );
3395
+
3396
+ await expect(
3397
+ runWithRequestContext(
3398
+ {
3399
+ userEmail: "owner@example.test",
3400
+ requestOrigin: "http://localhost:8092",
3401
+ },
3402
+ () =>
3403
+ createWorkspaceSsoEmbedSession({
3404
+ app: "analytics",
3405
+ path: "/overview",
3406
+ }),
3407
+ ),
3408
+ ).resolves.toMatchObject({ app: "analytics" });
3409
+
3410
+ expect(
3411
+ mocks.isFeatureFlagEnabled.mock.calls.map(([flag]) => flag.key),
3412
+ ).toEqual(["dispatch.workspace-sso", "desktop.workspace-sso"]);
3413
+ expect(mocks.managerConstructor).toHaveBeenCalled();
3414
+ });
3415
+
3416
+ it("allows an exact canonical app without requiring an MCP app grant", async () => {
3417
+ mocks.getUserSetting.mockResolvedValue({
3418
+ mode: "selected-apps",
3419
+ selectedAppIds: [],
3420
+ });
3421
+ mocks.discoverAgents.mockResolvedValue([
3422
+ {
3423
+ ...analyticsAgent,
3424
+ url: "https://analytics.agent-native.com",
3425
+ },
3426
+ ]);
3427
+ mocks.managerCallTool.mockResolvedValueOnce({
3428
+ structuredContent: {
3429
+ startUrl:
3430
+ "https://analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
3431
+ },
3432
+ });
3433
+
3434
+ const result = await runWithRequestContext(
3435
+ {
3436
+ userEmail: "owner@example.test",
3437
+ requestOrigin: "https://dispatch.agent-native.com",
3438
+ },
3439
+ () =>
3440
+ createWorkspaceSsoEmbedSession({
3441
+ app: "analytics",
3442
+ path: "/overview",
3443
+ chrome: "minimal",
3444
+ }),
3445
+ );
3446
+
3447
+ expect(result).toMatchObject({
3448
+ app: "analytics",
3449
+ startUrl:
3450
+ "https://analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
3451
+ });
3452
+ expect(mocks.managerConstructor).toHaveBeenCalled();
3453
+ });
3454
+
3455
+ it("keeps canonical workspace SSO apps eligible on the beta lane", async () => {
3456
+ mocks.getUserSetting.mockResolvedValue({
3457
+ mode: "selected-apps",
3458
+ selectedAppIds: [],
3459
+ });
3460
+ mocks.discoverAgents.mockResolvedValue([
3461
+ {
3462
+ ...analyticsAgent,
3463
+ url: "https://analytics.agent-native.com",
3464
+ },
3465
+ ]);
3466
+ mocks.managerCallTool.mockResolvedValueOnce({
3467
+ structuredContent: {
3468
+ startUrl:
3469
+ "https://beta.analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
3470
+ },
3471
+ });
3472
+
3473
+ const result = await runWithRequestContext(
3474
+ {
3475
+ userEmail: "owner@example.test",
3476
+ requestOrigin: "https://beta.dispatch.agent-native.com",
3477
+ },
3478
+ () =>
3479
+ createWorkspaceSsoEmbedSession({
3480
+ app: "analytics",
3481
+ path: "/overview",
3482
+ }),
3483
+ );
3484
+
3485
+ expect(result).toMatchObject({
3486
+ app: "analytics",
3487
+ startUrl:
3488
+ "https://beta.analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
3489
+ });
2372
3490
  expect(mocks.managerConstructor).toHaveBeenCalled();
2373
3491
  });
2374
3492
 
@@ -2532,23 +3650,24 @@ describe("createGrantedDispatchMcpEmbedSession", () => {
2532
3650
  isDispatch: false,
2533
3651
  },
2534
3652
  ]);
2535
- mocks.managerCallTool.mockImplementation(async (_tool, args) =>
2536
- args.runtime
2537
- ? {
2538
- structuredContent: {
2539
- runtime: "workspace-app-chat",
2540
- token: "private-chat-credential",
2541
- targetPath: "/",
2542
- expiresAt: Date.now() + 900000,
2543
- },
2544
- }
2545
- : {
2546
- structuredContent: {
2547
- startUrl:
2548
- "https://beta.agent-workspace.builder.io/dispatch/_agent-native/embed/start?ticket=remote",
2549
- },
3653
+ mocks.managerCallTool.mockImplementation(async (_tool, args) => {
3654
+ if (args.runtime) {
3655
+ return {
3656
+ structuredContent: {
3657
+ runtime: "workspace-app-chat",
3658
+ token: "private-chat-credential",
3659
+ targetPath: "/",
3660
+ expiresAt: Date.now() + 900000,
2550
3661
  },
2551
- );
3662
+ };
3663
+ }
3664
+ return {
3665
+ structuredContent: {
3666
+ startUrl:
3667
+ "https://beta.agent-workspace.builder.io/dispatch/_agent-native/embed/start?ticket=remote",
3668
+ },
3669
+ };
3670
+ });
2552
3671
 
2553
3672
  // Independent auth review: retain the document assertion, then pin the
2554
3673
  // separate chat caller's explicit purpose. Public inputs cannot escalate it.
@@ -2573,6 +3692,27 @@ describe("createGrantedDispatchMcpEmbedSession", () => {
2573
3692
  },
2574
3693
  );
2575
3694
 
3695
+ expect(mocks.managerConstructor).toHaveBeenCalledWith(
3696
+ expect.objectContaining({
3697
+ servers: {
3698
+ target: expect.objectContaining({
3699
+ url: "https://beta.agent-workspace.builder.io/dispatch/mcp",
3700
+ }),
3701
+ },
3702
+ }),
3703
+ );
3704
+ expect(mocks.signA2AToken).toHaveBeenCalledWith(
3705
+ "owner@example.test",
3706
+ undefined,
3707
+ undefined,
3708
+ expect.objectContaining({
3709
+ audience: "https://beta.agent-workspace.builder.io/dispatch/mcp",
3710
+ preferGlobalSecret: true,
3711
+ }),
3712
+ );
3713
+ mocks.managerConstructor.mockClear();
3714
+ mocks.signA2AToken.mockClear();
3715
+
2576
3716
  const session = await runWithRequestContext(
2577
3717
  {
2578
3718
  userEmail: "owner@example.test",
@@ -2585,11 +3725,11 @@ describe("createGrantedDispatchMcpEmbedSession", () => {
2585
3725
  ),
2586
3726
  );
2587
3727
 
2588
- expect(mocks.managerConstructor).toHaveBeenCalledWith(
3728
+ expect(mocks.managerConstructor).toHaveBeenLastCalledWith(
2589
3729
  expect.objectContaining({
2590
3730
  servers: {
2591
3731
  target: expect.objectContaining({
2592
- url: "https://beta.agent-workspace.builder.io/dispatch/mcp",
3732
+ url: "https://beta.agent-workspace.builder.io/customer-ticket-triage/mcp",
2593
3733
  }),
2594
3734
  },
2595
3735
  }),
@@ -2599,7 +3739,8 @@ describe("createGrantedDispatchMcpEmbedSession", () => {
2599
3739
  undefined,
2600
3740
  undefined,
2601
3741
  expect.objectContaining({
2602
- audience: "https://beta.agent-workspace.builder.io/dispatch/mcp",
3742
+ audience:
3743
+ "https://beta.agent-workspace.builder.io/customer-ticket-triage/mcp",
2603
3744
  preferGlobalSecret: true,
2604
3745
  }),
2605
3746
  );
@@ -2881,6 +4022,124 @@ describe("createGrantedDispatchMcpEmbedSession", () => {
2881
4022
  },
2882
4023
  );
2883
4024
 
4025
+ it.each(["workspace-sso", "dispatch-grant"] as const)(
4026
+ "routes root-mounted Workspace app chat directly through %s without changing document embeds",
4027
+ async (route) => {
4028
+ vi.stubEnv("A2A_SECRET", "test-a2a-secret");
4029
+ vi.stubEnv("APP_URL", "https://beta.agent-workspace.builder.io");
4030
+ vi.stubEnv(
4031
+ "WORKSPACE_GATEWAY_URL",
4032
+ "https://beta.agent-workspace.builder.io/dispatch",
4033
+ );
4034
+ vi.stubEnv("APP_BASE_PATH", "");
4035
+ vi.stubEnv("VITE_APP_BASE_PATH", "");
4036
+ vi.stubEnv(
4037
+ "IDENTITY_SSO_APP_REGISTRY_JSON",
4038
+ JSON.stringify([
4039
+ {
4040
+ appId: "customer-ticket-triage",
4041
+ clientId: "workspace-client",
4042
+ origin: "https://beta.agent-workspace.builder.io",
4043
+ callbackPath: "/_agent-native/identity/callback",
4044
+ capabilities: ["identity-sso"],
4045
+ },
4046
+ ]),
4047
+ );
4048
+ const workspaceApp = {
4049
+ id: "customer-ticket-triage",
4050
+ name: "Customer Ticket Triage",
4051
+ description: "Triage customer tickets",
4052
+ path: "/",
4053
+ url: "https://beta.agent-workspace.builder.io",
4054
+ isDispatch: false,
4055
+ };
4056
+ mocks.listWorkspaceApps.mockResolvedValue([workspaceApp]);
4057
+ mocks.discoverAgents.mockResolvedValue([
4058
+ { ...workspaceApp, color: "#14B8A6" },
4059
+ ]);
4060
+ mocks.managerCallTool.mockImplementation(async (_tool, args) =>
4061
+ args.runtime
4062
+ ? {
4063
+ structuredContent: {
4064
+ runtime: "workspace-app-chat",
4065
+ token: "private-chat-credential",
4066
+ targetPath: "/",
4067
+ expiresAt: Date.now() + 900000,
4068
+ },
4069
+ }
4070
+ : {
4071
+ structuredContent: {
4072
+ startUrl:
4073
+ "https://beta.agent-workspace.builder.io/dispatch/_agent-native/embed/start?ticket=remote",
4074
+ },
4075
+ },
4076
+ );
4077
+ const context = {
4078
+ userEmail: "owner@example.test",
4079
+ identityAuthenticatedAtMs: Date.now() - 1000,
4080
+ requestOrigin: "https://beta.dispatch.agent-native.com",
4081
+ };
4082
+
4083
+ const document = await runWithRequestContext(context, () => {
4084
+ const input = {
4085
+ app: workspaceApp.id,
4086
+ path: "/",
4087
+ chrome: "minimal" as const,
4088
+ };
4089
+ return route === "workspace-sso"
4090
+ ? createWorkspaceSsoEmbedSession(input)
4091
+ : createGrantedDispatchMcpEmbedSession(input);
4092
+ });
4093
+ expect(mocks.managerConstructor).toHaveBeenLastCalledWith(
4094
+ expect.objectContaining({
4095
+ servers: {
4096
+ target: expect.objectContaining({
4097
+ url: "https://beta.agent-workspace.builder.io/dispatch/mcp",
4098
+ }),
4099
+ },
4100
+ }),
4101
+ );
4102
+ expect(mocks.managerCallTool).toHaveBeenLastCalledWith(
4103
+ "mcp__target__create_embed_session",
4104
+ { url: "https://beta.agent-workspace.builder.io/", chrome: "minimal" },
4105
+ );
4106
+ expect(document.startUrl).toBe(
4107
+ "https://beta.agent-workspace.builder.io/dispatch/_agent-native/embed/start?ticket=remote",
4108
+ );
4109
+
4110
+ const chat = await runWithRequestContext(context, () =>
4111
+ route === "workspace-sso"
4112
+ ? createWorkspaceSsoEmbedSessionForWorkspaceAppChat(workspaceApp.id)
4113
+ : createGrantedDispatchMcpEmbedSessionForWorkspaceAppChat(
4114
+ workspaceApp.id,
4115
+ ),
4116
+ );
4117
+ expect.soft(mocks.managerConstructor).toHaveBeenLastCalledWith(
4118
+ expect.objectContaining({
4119
+ servers: {
4120
+ target: expect.objectContaining({
4121
+ url: "https://beta.agent-workspace.builder.io/mcp",
4122
+ }),
4123
+ },
4124
+ }),
4125
+ );
4126
+ expect(mocks.managerCallTool).toHaveBeenLastCalledWith(
4127
+ "mcp__target__create_embed_session",
4128
+ {
4129
+ url: "https://beta.agent-workspace.builder.io/",
4130
+ chrome: "minimal",
4131
+ runtime: "workspace-app-chat",
4132
+ },
4133
+ );
4134
+ expect.soft(chat).toEqual({
4135
+ token: "private-chat-credential",
4136
+ targetPath: "/",
4137
+ expiresAt: expect.any(Number),
4138
+ appBaseUrl: "https://beta.agent-workspace.builder.io",
4139
+ });
4140
+ },
4141
+ );
4142
+
2884
4143
  it.each(["workspace-sso", "dispatch-grant"] as const)(
2885
4144
  "retains the Workspace gateway path for discovered-only app chats through %s",
2886
4145
  async (route) => {
@@ -3215,7 +4474,15 @@ describe("createGrantedDispatchMcpEmbedSession", () => {
3215
4474
  "owner@example.test",
3216
4475
  undefined,
3217
4476
  undefined,
3218
- expect.not.objectContaining({ extraClaims: expect.anything() }),
4477
+ expect.objectContaining({
4478
+ audience: "https://custom.example.com/mcp",
4479
+ preferGlobalSecret: true,
4480
+ extraClaims: {
4481
+ jti: expect.any(String),
4482
+ scope: "mcp-connect",
4483
+ agent_native_first_party_mcp: true,
4484
+ },
4485
+ }),
3219
4486
  );
3220
4487
  expect(result.app).toBe("custom-agent");
3221
4488
  });
@@ -3935,85 +5202,546 @@ it.each([
3935
5202
  },
3936
5203
  );
3937
5204
 
3938
- it("refuses private chat credentials on the public browser document wrapper", async () => {
5205
+ it("refuses private chat credentials on the public browser document wrapper", async () => {
5206
+ vi.stubEnv("A2A_SECRET", "test-a2a-secret");
5207
+ mocks.discoverAgents.mockResolvedValue([
5208
+ { ...analyticsAgent, url: "https://analytics.agent-native.com" },
5209
+ ]);
5210
+ mocks.managerCallTool.mockResolvedValue({
5211
+ structuredContent: {
5212
+ runtime: "workspace-app-chat",
5213
+ token: "private-chat-credential",
5214
+ targetPath: "/",
5215
+ expiresAt: Date.now() + 900000,
5216
+ },
5217
+ });
5218
+ await expect(
5219
+ runWithRequestContext(
5220
+ {
5221
+ userEmail: "owner@example.test",
5222
+ requestOrigin: "https://dispatch.agent-native.com",
5223
+ identityAuthenticatedAtMs: Date.now() - 1000,
5224
+ },
5225
+ () => createWorkspaceSsoEmbedSession({ app: "analytics", path: "/" }),
5226
+ ),
5227
+ ).rejects.toThrow("embed start URL");
5228
+ });
5229
+
5230
+ it("resolves both document and chat trust from the application config layer ahead of env", async () => {
5231
+ vi.stubEnv("A2A_SECRET", "test-a2a-secret");
5232
+ vi.stubEnv("IDENTITY_SSO_APP_REGISTRY_JSON", "[]");
5233
+ // The app layer has precedence over the environment; both runtime paths must honor it.
5234
+ defineAppConfig({
5235
+ auth: {
5236
+ identitySsoAppRegistryJson: JSON.stringify([
5237
+ {
5238
+ appId: "workspace",
5239
+ clientId: "workspace-client",
5240
+ origin: "https://workspace.example.com",
5241
+ callbackPath: "/_agent-native/identity/callback",
5242
+ capabilities: ["identity-sso"],
5243
+ },
5244
+ ]),
5245
+ },
5246
+ } as Parameters<typeof defineAppConfig>[0]);
5247
+ mocks.discoverAgents.mockResolvedValue([
5248
+ {
5249
+ ...analyticsAgent,
5250
+ id: "workspace",
5251
+ name: "Workspace",
5252
+ url: "https://workspace.example.com",
5253
+ },
5254
+ ]);
5255
+ mocks.managerCallTool.mockResolvedValueOnce({
5256
+ structuredContent: {
5257
+ startUrl:
5258
+ "https://workspace.example.com/_agent-native/embed/start?ticket=remote",
5259
+ },
5260
+ });
5261
+ const context = {
5262
+ userEmail: "owner@example.test",
5263
+ requestOrigin: "https://dispatch.agent-native.com",
5264
+ identityAuthenticatedAtMs: Date.now() - 1000,
5265
+ };
5266
+ const document = await runWithRequestContext(context, () =>
5267
+ createWorkspaceSsoEmbedSession({ app: "workspace", path: "/" }),
5268
+ );
5269
+ expect(document.startUrl).toContain("https://workspace.example.com/");
5270
+ expect(mocks.signA2AToken).toHaveBeenCalledWith(
5271
+ "owner@example.test",
5272
+ undefined,
5273
+ undefined,
5274
+ expect.objectContaining({
5275
+ audience: "https://workspace.example.com/mcp",
5276
+ preferGlobalSecret: true,
5277
+ extraClaims: {
5278
+ jti: expect.any(String),
5279
+ scope: "mcp-connect",
5280
+ agent_native_first_party_mcp: true,
5281
+ },
5282
+ }),
5283
+ );
5284
+ mocks.managerCallTool.mockResolvedValueOnce({
5285
+ structuredContent: {
5286
+ runtime: "workspace-app-chat",
5287
+ token: "private-chat-credential",
5288
+ targetPath: "/",
5289
+ expiresAt: Date.now() + 900000,
5290
+ },
5291
+ });
5292
+ const chat = await runWithRequestContext(context, () =>
5293
+ createWorkspaceSsoEmbedSessionForWorkspaceAppChat("workspace"),
5294
+ );
5295
+ expect(chat).toMatchObject({
5296
+ token: "private-chat-credential",
5297
+ appBaseUrl: "https://workspace.example.com",
5298
+ });
5299
+ expect(chat).not.toHaveProperty("startUrl");
5300
+ });
5301
+
5302
+ it("grants first-party MCP claims for granted document embeds to canonical workspace apps", async () => {
3939
5303
  vi.stubEnv("A2A_SECRET", "test-a2a-secret");
5304
+ mocks.getOrgDomain.mockResolvedValue("example.test");
3940
5305
  mocks.discoverAgents.mockResolvedValue([
3941
5306
  { ...analyticsAgent, url: "https://analytics.agent-native.com" },
3942
5307
  ]);
3943
- mocks.managerCallTool.mockResolvedValue({
5308
+ mocks.getUserSetting.mockResolvedValue({ mode: "all-apps" });
5309
+ mocks.managerCallTool.mockResolvedValueOnce({
3944
5310
  structuredContent: {
3945
- runtime: "workspace-app-chat",
3946
- token: "private-chat-credential",
3947
- targetPath: "/",
3948
- expiresAt: Date.now() + 900000,
5311
+ startUrl:
5312
+ "https://analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
3949
5313
  },
3950
5314
  });
5315
+
5316
+ const result = await runWithRequestContext(
5317
+ {
5318
+ userEmail: "owner@example.test",
5319
+ orgId: "org-1",
5320
+ requestOrigin: "https://dispatch.agent-native.com",
5321
+ },
5322
+ () =>
5323
+ createGrantedDispatchMcpEmbedSession({
5324
+ app: "analytics",
5325
+ path: "/dashboards",
5326
+ }),
5327
+ );
5328
+
5329
+ expect(result.startUrl).toBe(
5330
+ "https://analytics.agent-native.com/_agent-native/embed/start?ticket=remote",
5331
+ );
5332
+ expect(mocks.signA2AToken).toHaveBeenCalledWith(
5333
+ "owner@example.test",
5334
+ "example.test",
5335
+ undefined,
5336
+ expect.objectContaining({
5337
+ audience: "https://analytics.agent-native.com/mcp",
5338
+ preferGlobalSecret: true,
5339
+ extraClaims: {
5340
+ jti: expect.any(String),
5341
+ scope: "mcp-connect",
5342
+ agent_native_first_party_mcp: true,
5343
+ },
5344
+ }),
5345
+ );
5346
+
5347
+ mocks.getOrgDomain.mockResolvedValue(null);
5348
+ mocks.managerConstructor.mockClear();
3951
5349
  await expect(
3952
5350
  runWithRequestContext(
3953
5351
  {
3954
5352
  userEmail: "owner@example.test",
5353
+ orgId: "org-1",
3955
5354
  requestOrigin: "https://dispatch.agent-native.com",
3956
- identityAuthenticatedAtMs: Date.now() - 1000,
3957
5355
  },
3958
- () => createWorkspaceSsoEmbedSession({ app: "analytics", path: "/" }),
5356
+ () =>
5357
+ createGrantedDispatchMcpEmbedSession({
5358
+ app: "analytics",
5359
+ path: "/",
5360
+ }),
3959
5361
  ),
3960
- ).rejects.toThrow("embed start URL");
5362
+ ).rejects.toThrow("Workspace organization domain is unavailable.");
5363
+ expect(mocks.managerConstructor).not.toHaveBeenCalled();
3961
5364
  });
3962
5365
 
3963
- it("resolves both document and chat trust from the application config layer ahead of env", async () => {
5366
+ it("grants first-party MCP claims for granted document embeds to SSO-registered mounted targets", async () => {
3964
5367
  vi.stubEnv("A2A_SECRET", "test-a2a-secret");
3965
- vi.stubEnv("IDENTITY_SSO_APP_REGISTRY_JSON", "[]");
3966
- // The app layer has precedence over the environment; both runtime paths must honor it.
5368
+ vi.stubEnv("WORKSPACE_GATEWAY_URL", "https://labs.agent-native.com");
5369
+ vi.stubEnv("APP_BASE_PATH", "/dispatch");
5370
+ vi.stubEnv("VITE_APP_BASE_PATH", "");
5371
+ mocks.getOrgDomain.mockResolvedValue("example.test");
3967
5372
  defineAppConfig({
3968
5373
  auth: {
3969
5374
  identitySsoAppRegistryJson: JSON.stringify([
3970
5375
  {
3971
- appId: "workspace",
3972
- clientId: "workspace-client",
3973
- origin: "https://workspace.example.com",
5376
+ appId: "analytics-2",
5377
+ clientId: "labs-analytics-2",
5378
+ origin: "https://labs.agent-native.com",
3974
5379
  callbackPath: "/_agent-native/identity/callback",
3975
5380
  capabilities: ["identity-sso"],
3976
5381
  },
3977
5382
  ]),
3978
5383
  },
3979
5384
  } as Parameters<typeof defineAppConfig>[0]);
5385
+ const mountedAnalytics = {
5386
+ id: "analytics-2",
5387
+ name: "Analytics",
5388
+ description: "Analytics workspace app",
5389
+ path: "/analytics-2",
5390
+ url: "https://labs.agent-native.com/analytics-2",
5391
+ isDispatch: false,
5392
+ };
5393
+ mocks.listWorkspaceApps.mockResolvedValue([mountedAnalytics]);
3980
5394
  mocks.discoverAgents.mockResolvedValue([
3981
5395
  {
3982
- ...analyticsAgent,
3983
- id: "workspace",
3984
- name: "Workspace",
3985
- url: "https://workspace.example.com",
5396
+ id: mountedAnalytics.id,
5397
+ name: mountedAnalytics.name,
5398
+ description: mountedAnalytics.description,
5399
+ url: mountedAnalytics.url,
5400
+ color: "#14B8A6",
3986
5401
  },
3987
5402
  ]);
5403
+ mocks.getUserSetting.mockResolvedValue({ mode: "all-apps" });
3988
5404
  mocks.managerCallTool.mockResolvedValueOnce({
3989
5405
  structuredContent: {
3990
5406
  startUrl:
3991
- "https://workspace.example.com/_agent-native/embed/start?ticket=remote",
5407
+ "https://labs.agent-native.com/analytics-2/_agent-native/embed/start?ticket=remote",
3992
5408
  },
3993
5409
  });
3994
- const context = {
3995
- userEmail: "owner@example.test",
3996
- requestOrigin: "https://dispatch.agent-native.com",
3997
- identityAuthenticatedAtMs: Date.now() - 1000,
5410
+
5411
+ const result = await runWithRequestContext(
5412
+ {
5413
+ userEmail: "owner@example.test",
5414
+ orgId: "org-1",
5415
+ requestOrigin: "https://labs.agent-native.com",
5416
+ },
5417
+ () =>
5418
+ createGrantedDispatchMcpEmbedSession({
5419
+ app: "analytics-2",
5420
+ path: "/",
5421
+ }),
5422
+ );
5423
+
5424
+ expect(result.startUrl).toBe(
5425
+ "https://labs.agent-native.com/analytics-2/_agent-native/embed/start?ticket=remote",
5426
+ );
5427
+ expect(mocks.managerConstructor).toHaveBeenCalledWith(
5428
+ expect.objectContaining({
5429
+ servers: {
5430
+ target: expect.objectContaining({
5431
+ url: "https://labs.agent-native.com/analytics-2/mcp",
5432
+ headers: {
5433
+ Authorization: "Bearer signed-token",
5434
+ "x-agent-native-mcp-inline-apps": "1",
5435
+ },
5436
+ }),
5437
+ },
5438
+ }),
5439
+ );
5440
+ expect(mocks.signA2AToken).toHaveBeenCalledWith(
5441
+ "owner@example.test",
5442
+ "example.test",
5443
+ undefined,
5444
+ expect.objectContaining({
5445
+ audience: "https://labs.agent-native.com/analytics-2/mcp",
5446
+ preferGlobalSecret: true,
5447
+ extraClaims: {
5448
+ jti: expect.any(String),
5449
+ scope: "mcp-connect",
5450
+ agent_native_first_party_mcp: true,
5451
+ },
5452
+ }),
5453
+ );
5454
+ });
5455
+
5456
+ it("withholds first-party MCP claims for granted document embeds to unregistered targets even on the same origin", async () => {
5457
+ vi.stubEnv("A2A_SECRET", "test-a2a-secret");
5458
+ vi.stubEnv("WORKSPACE_GATEWAY_URL", "https://labs.agent-native.com");
5459
+ vi.stubEnv("APP_BASE_PATH", "/dispatch");
5460
+ vi.stubEnv("VITE_APP_BASE_PATH", "");
5461
+ vi.stubEnv("IDENTITY_SSO_APP_REGISTRY_JSON", "[]");
5462
+ mocks.getOrgDomain.mockResolvedValue("example.test");
5463
+ const unregisteredMounted = {
5464
+ id: "analytics-2",
5465
+ name: "Analytics",
5466
+ description: "Analytics workspace app",
5467
+ path: "/analytics-2",
5468
+ url: "https://labs.agent-native.com/analytics-2",
5469
+ isDispatch: false,
3998
5470
  };
3999
- const document = await runWithRequestContext(context, () =>
4000
- createWorkspaceSsoEmbedSession({ app: "workspace", path: "/" }),
5471
+ mocks.listWorkspaceApps.mockResolvedValue([unregisteredMounted]);
5472
+ mocks.discoverAgents.mockResolvedValue([
5473
+ {
5474
+ id: unregisteredMounted.id,
5475
+ name: unregisteredMounted.name,
5476
+ description: unregisteredMounted.description,
5477
+ url: unregisteredMounted.url,
5478
+ color: "#14B8A6",
5479
+ },
5480
+ ]);
5481
+ mocks.getUserSetting.mockResolvedValue({ mode: "all-apps" });
5482
+ mocks.managerCallTool.mockResolvedValueOnce({
5483
+ structuredContent: {
5484
+ startUrl:
5485
+ "https://labs.agent-native.com/analytics-2/_agent-native/embed/start?ticket=remote",
5486
+ },
5487
+ });
5488
+
5489
+ await runWithRequestContext(
5490
+ {
5491
+ userEmail: "owner@example.test",
5492
+ orgId: "org-1",
5493
+ requestOrigin: "https://labs.agent-native.com",
5494
+ },
5495
+ () =>
5496
+ createGrantedDispatchMcpEmbedSession({
5497
+ app: "analytics-2",
5498
+ path: "/",
5499
+ }),
4001
5500
  );
4002
- expect(document.startUrl).toContain("https://workspace.example.com/");
5501
+
5502
+ expect(mocks.signA2AToken).toHaveBeenCalledWith(
5503
+ "owner@example.test",
5504
+ undefined,
5505
+ undefined,
5506
+ expect.not.objectContaining({ extraClaims: expect.anything() }),
5507
+ );
5508
+
5509
+ mocks.signA2AToken.mockClear();
5510
+ mocks.listWorkspaceApps.mockResolvedValue([]);
5511
+ mocks.discoverAgents.mockResolvedValue([
5512
+ {
5513
+ id: "third-party-agent",
5514
+ name: "Third Party Agent",
5515
+ description: "External unregistered app",
5516
+ url: "https://third-party.example.com",
5517
+ color: "#000000",
5518
+ },
5519
+ ]);
4003
5520
  mocks.managerCallTool.mockResolvedValueOnce({
4004
5521
  structuredContent: {
4005
- runtime: "workspace-app-chat",
4006
- token: "private-chat-credential",
4007
- targetPath: "/",
4008
- expiresAt: Date.now() + 900000,
5522
+ startUrl:
5523
+ "https://third-party.example.com/_agent-native/embed/start?ticket=remote",
4009
5524
  },
4010
5525
  });
4011
- const chat = await runWithRequestContext(context, () =>
4012
- createWorkspaceSsoEmbedSessionForWorkspaceAppChat("workspace"),
5526
+
5527
+ await runWithRequestContext(
5528
+ {
5529
+ userEmail: "owner@example.test",
5530
+ orgId: "org-1",
5531
+ requestOrigin: "https://labs.agent-native.com",
5532
+ },
5533
+ () =>
5534
+ createGrantedDispatchMcpEmbedSession({
5535
+ app: "third-party-agent",
5536
+ path: "/",
5537
+ }),
4013
5538
  );
4014
- expect(chat).toMatchObject({
4015
- token: "private-chat-credential",
4016
- appBaseUrl: "https://workspace.example.com",
5539
+
5540
+ expect(mocks.signA2AToken).toHaveBeenCalledWith(
5541
+ "owner@example.test",
5542
+ undefined,
5543
+ undefined,
5544
+ expect.not.objectContaining({ extraClaims: expect.anything() }),
5545
+ );
5546
+ });
5547
+
5548
+ describe("A2A tab/viewport propagation, double-prefix prevention, and manifest v2 open_app validation", () => {
5549
+ afterEach(() => {
5550
+ clearGrantedAppManifestCache();
5551
+ });
5552
+
5553
+ it("forwards childBrowserTabId and foreground viewportMode on ask_app when the target app is bound in the pane", async () => {
5554
+ mocks.resolveChildBrowserTab.mockResolvedValueOnce(
5555
+ "a1b2c3d4-5678-4abc-9def-1234567890ab",
5556
+ );
5557
+ mocks.a2aSend.mockResolvedValueOnce({
5558
+ id: "task-tab-1",
5559
+ status: {
5560
+ state: "completed",
5561
+ message: { role: "agent", parts: [{ type: "text", text: "opened" }] },
5562
+ timestamp: "2026-11-23T00:00:00Z",
5563
+ },
5564
+ });
5565
+
5566
+ await runWithRequestContext(
5567
+ { userEmail: "owner@example.test", orgId: "org-1" },
5568
+ () => askGrantedDispatchMcpApp("analytics", "switch to revenue"),
5569
+ );
5570
+
5571
+ expect(mocks.a2aConstructor).toHaveBeenCalledWith(
5572
+ analyticsAgent.url,
5573
+ undefined,
5574
+ expect.objectContaining({
5575
+ transportHeaders: {
5576
+ "x-agent-native-browser-tab": "a1b2c3d4-5678-4abc-9def-1234567890ab",
5577
+ "x-agent-native-viewport-mode": "foreground",
5578
+ },
5579
+ }),
5580
+ );
5581
+ expect(mocks.a2aSend).toHaveBeenCalledWith(
5582
+ expect.anything(),
5583
+ expect.objectContaining({
5584
+ metadata: expect.objectContaining({
5585
+ browserTabId: "a1b2c3d4-5678-4abc-9def-1234567890ab",
5586
+ viewportMode: "foreground",
5587
+ }),
5588
+ }),
5589
+ );
5590
+ });
5591
+
5592
+ it("forwards viewportMode=background on ask_app without binding the foreground child tab", async () => {
5593
+ mocks.a2aSend.mockResolvedValueOnce({
5594
+ id: "task-bg-1",
5595
+ status: {
5596
+ state: "completed",
5597
+ message: { role: "agent", parts: [{ type: "text", text: "found" }] },
5598
+ timestamp: "2026-11-23T00:00:00Z",
5599
+ },
5600
+ });
5601
+
5602
+ await runWithRequestContext(
5603
+ { userEmail: "owner@example.test", orgId: "org-1" },
5604
+ () =>
5605
+ askGrantedDispatchMcpApp("analytics", "look up metric", {
5606
+ viewportMode: "background",
5607
+ }),
5608
+ );
5609
+
5610
+ expect(mocks.resolveChildBrowserTab).not.toHaveBeenCalled();
5611
+ expect(mocks.a2aConstructor).toHaveBeenCalledWith(
5612
+ analyticsAgent.url,
5613
+ undefined,
5614
+ expect.objectContaining({
5615
+ transportHeaders: {
5616
+ "x-agent-native-viewport-mode": "background",
5617
+ },
5618
+ }),
5619
+ );
5620
+ expect(mocks.a2aSend).toHaveBeenCalledWith(
5621
+ expect.anything(),
5622
+ expect.objectContaining({
5623
+ metadata: expect.objectContaining({
5624
+ viewportMode: "background",
5625
+ }),
5626
+ }),
5627
+ );
5628
+ });
5629
+
5630
+ it("prevents /<app>/<app> double base-path prefixing in appHomeBaseUrl, joinAppBaseUrlAndPath, and open_app", async () => {
5631
+ expect(
5632
+ appHomeBaseUrl({
5633
+ url: "https://workspace.example.test/decks-2/decks-2",
5634
+ }),
5635
+ ).toBe("https://workspace.example.test/decks-2");
5636
+ expect(
5637
+ joinAppBaseUrlAndPath(
5638
+ "https://workspace.example.test/decks-2",
5639
+ "/decks-2",
5640
+ ),
5641
+ ).toBe("https://workspace.example.test/decks-2/");
5642
+ expect(
5643
+ joinAppBaseUrlAndPath(
5644
+ "https://workspace.example.test/decks-2",
5645
+ "/decks-2/docs/deck-1?slide=2",
5646
+ ),
5647
+ ).toBe("https://workspace.example.test/decks-2/docs/deck-1?slide=2");
5648
+
5649
+ mocks.discoverAgents.mockResolvedValue([
5650
+ {
5651
+ id: "decks-2",
5652
+ name: "Decks",
5653
+ description: "Slide decks",
5654
+ url: "https://workspace.example.test/decks-2",
5655
+ color: "#222222",
5656
+ },
5657
+ ]);
5658
+ mocks.listWorkspaceApps.mockResolvedValue([
5659
+ {
5660
+ id: "decks-2",
5661
+ name: "Decks",
5662
+ path: "/decks-2",
5663
+ url: "https://workspace.example.test/decks-2",
5664
+ },
5665
+ ]);
5666
+
5667
+ const result = await runWithRequestContext(
5668
+ { userEmail: "owner@example.test", orgId: "org-1" },
5669
+ () =>
5670
+ openGrantedDispatchMcpApp({
5671
+ app: "decks-2",
5672
+ path: "/decks-2/docs/q4",
5673
+ focus: true,
5674
+ }),
5675
+ );
5676
+
5677
+ expect(result.url).toBe("https://workspace.example.test/decks-2/docs/q4");
5678
+ expect(result.focus).toBe(true);
5679
+ });
5680
+
5681
+ it("validates open_app routes and expands { screen, params } against a v2 manifest", async () => {
5682
+ mocks.discoverAgents.mockResolvedValue([
5683
+ {
5684
+ id: "decks-2",
5685
+ name: "Decks",
5686
+ description: "Slide decks",
5687
+ url: "https://workspace.example.test/decks-2",
5688
+ color: "#222222",
5689
+ },
5690
+ ]);
5691
+ mocks.listWorkspaceApps.mockResolvedValue([
5692
+ {
5693
+ id: "decks-2",
5694
+ name: "Decks",
5695
+ path: "/decks-2",
5696
+ url: "https://workspace.example.test/decks-2",
5697
+ },
5698
+ ]);
5699
+ registerGrantedAppManifest("decks-2", {
5700
+ version: 2,
5701
+ screens: {
5702
+ home: { route: "/", action: "navigate" },
5703
+ deck: { route: "/docs/:deckId", action: "navigate" },
5704
+ },
5705
+ supportsViewOverlay: true,
5706
+ });
5707
+
5708
+ const validPath = await runWithRequestContext(
5709
+ { userEmail: "owner@example.test", orgId: "org-1" },
5710
+ () =>
5711
+ openGrantedDispatchMcpApp({
5712
+ app: "decks-2",
5713
+ path: "/docs/deck-42",
5714
+ }),
5715
+ );
5716
+ expect(validPath.url).toBe(
5717
+ "https://workspace.example.test/decks-2/docs/deck-42",
5718
+ );
5719
+
5720
+ const byScreen = await runWithRequestContext(
5721
+ { userEmail: "owner@example.test", orgId: "org-1" },
5722
+ () =>
5723
+ openGrantedDispatchMcpApp({
5724
+ app: "decks-2",
5725
+ screen: "deck",
5726
+ params: { deckId: "deck-42", slide: 3 },
5727
+ }),
5728
+ );
5729
+ expect(byScreen.path).toBe("/docs/deck-42");
5730
+ expect(byScreen.url).toBe(
5731
+ "https://workspace.example.test/decks-2/docs/deck-42?slide=3",
5732
+ );
5733
+
5734
+ await expect(
5735
+ runWithRequestContext(
5736
+ { userEmail: "owner@example.test", orgId: "org-1" },
5737
+ () =>
5738
+ openGrantedDispatchMcpApp({
5739
+ app: "decks-2",
5740
+ path: "/totally/invalid",
5741
+ }),
5742
+ ),
5743
+ ).rejects.toThrow(
5744
+ /Invalid route "\/totally\/invalid" for app "decks-2".*deck \(\/docs\/:deckId\)/,
5745
+ );
4017
5746
  });
4018
- expect(chat).not.toHaveProperty("startUrl");
4019
5747
  });