@agent-native/dispatch 0.42.1 → 0.42.3-nightly-20261106152255

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.
@@ -122,6 +122,7 @@ import {
122
122
  navigateToWorkspaceApp,
123
123
  shouldOpenWorkspaceAppInTopWindow,
124
124
  workspaceAppIdFromRoute,
125
+ workspaceAppInitialPathFromPathname,
125
126
  workspaceAppDirectHref,
126
127
  workspaceAppDirectLaunchHref,
127
128
  workspaceAppRoute,
@@ -2508,6 +2509,16 @@ function DispatchLayout({
2508
2509
  (app) => app.id.toLowerCase() === workspaceAppId.toLowerCase(),
2509
2510
  )
2510
2511
  : undefined;
2512
+ // Layout, not the app route component, is what renders the kept-alive pane,
2513
+ // so the deep path a URL carries has to be handed to it here or every app URL
2514
+ // opens the app's home.
2515
+ const workspaceAppDeepPath = workspaceAppRouteActive
2516
+ ? workspaceAppInitialPathFromPathname(
2517
+ localPathname,
2518
+ location.search,
2519
+ location.hash,
2520
+ )
2521
+ : undefined;
2511
2522
  const workspaceAppContent =
2512
2523
  workspaceAppRouteActive && workspaceAppId ? (
2513
2524
  workspaceAppChatRegistration ? (
@@ -2517,10 +2528,20 @@ function DispatchLayout({
2517
2528
  agentPageHref={agentPageHref}
2518
2529
  onFullscreenRequest={openAskAgentFullscreen}
2519
2530
  >
2520
- <WorkspaceAppKeepAlive activeAppId={workspaceAppId} />
2531
+ <WorkspaceAppKeepAlive
2532
+ activeAppId={workspaceAppId}
2533
+ {...(workspaceAppDeepPath
2534
+ ? { initialPath: workspaceAppDeepPath }
2535
+ : {})}
2536
+ />
2521
2537
  </WorkspaceAppChatRail>
2522
2538
  ) : (
2523
- <WorkspaceAppKeepAlive activeAppId={workspaceAppId} />
2539
+ <WorkspaceAppKeepAlive
2540
+ activeAppId={workspaceAppId}
2541
+ {...(workspaceAppDeepPath
2542
+ ? { initialPath: workspaceAppDeepPath }
2543
+ : {})}
2544
+ />
2524
2545
  )
2525
2546
  ) : (
2526
2547
  <WorkspaceAppKeepAlive
@@ -171,7 +171,11 @@ vi.mock("next-themes", () => ({
171
171
  useTheme: () => ({ resolvedTheme: clientState.theme }),
172
172
  }));
173
173
 
174
- import { WorkspaceAppFrame, WorkspaceAppKeepAlive } from "./workspace-app-host";
174
+ import {
175
+ WorkspaceAppFrame,
176
+ WorkspaceAppHost,
177
+ WorkspaceAppKeepAlive,
178
+ } from "./workspace-app-host";
175
179
 
176
180
  describe("WorkspaceAppKeepAlive", () => {
177
181
  let container: HTMLDivElement;
@@ -386,7 +390,14 @@ describe("WorkspaceAppKeepAlive", () => {
386
390
  ["coach", "/", "/"],
387
391
  ["onboarding", "/accounts", "/accounts"],
388
392
  ])(
389
- "embeds %s by its own home path when its registry url is this Dispatch's page",
393
+ // Retired deliberately: this used to require a same-origin app to be
394
+ // framed through an embed session at its home path. That session is an
395
+ // ordinary embed scope, which may only read its own document and static
396
+ // assets, so the framed app could not call a single action (measured on
397
+ // Labs 11/5: 0 of 16 action calls returned 200 and the app rendered
398
+ // "Couldn't load content"; the same app framed directly returned 16 of 16).
399
+ // A same-origin app shares the workspace cookie, so it now loads directly.
400
+ "loads %s directly at its own home path when its registry url is this Dispatch's page",
390
401
  async (id, homePath, expectedPath) => {
391
402
  await act(async () => {
392
403
  root.render(
@@ -404,14 +415,41 @@ describe("WorkspaceAppKeepAlive", () => {
404
415
  await Promise.resolve();
405
416
  });
406
417
 
407
- expect(clientState.legacyMutateAsync).toHaveBeenCalledWith({
408
- app: id,
409
- path: expectedPath,
410
- chrome: "minimal",
411
- });
418
+ expect(clientState.legacyMutateAsync).not.toHaveBeenCalled();
419
+ expect(
420
+ document
421
+ .querySelector("[data-chat-first-app-embed-url]")
422
+ ?.getAttribute("data-chat-first-app-embed-url"),
423
+ ).toBe(`/${id}${expectedPath}`.replace(/\/+$/, ""));
412
424
  },
413
425
  );
414
426
 
427
+ it("keeps a same-origin app's deep route when it loads it directly", async () => {
428
+ await act(async () => {
429
+ root.render(
430
+ <WorkspaceAppFrame
431
+ app={{
432
+ id: "docs",
433
+ name: "Docs",
434
+ path: "/docs",
435
+ homePath: "/home",
436
+ url: `${window.location.origin}/dispatch/apps/docs`,
437
+ }}
438
+ initialPath="/settings/integrations/notion"
439
+ />,
440
+ );
441
+ await Promise.resolve();
442
+ await Promise.resolve();
443
+ });
444
+
445
+ expect(clientState.legacyMutateAsync).not.toHaveBeenCalled();
446
+ expect(
447
+ document
448
+ .querySelector("[data-chat-first-app-embed-url]")
449
+ ?.getAttribute("data-chat-first-app-embed-url"),
450
+ ).toBe("/docs/settings/integrations/notion");
451
+ });
452
+
415
453
  it("never falls back to framing this Dispatch's own page for the app", async () => {
416
454
  clientState.legacyMutateError = new Error("Embed failed");
417
455
  clientState.legacyErrorMutateAsync.mockRejectedValue(
@@ -929,4 +967,114 @@ describe("WorkspaceAppKeepAlive", () => {
929
967
  ).toHaveLength(3);
930
968
  expect(container.querySelectorAll("iframe")).toHaveLength(3);
931
969
  });
970
+
971
+ it("keeps a same-origin app's deep route through the host, not just the frame", async () => {
972
+ clientState.workspaceApps = [
973
+ {
974
+ id: "docs",
975
+ name: "Docs",
976
+ path: "/docs",
977
+ homePath: "/home",
978
+ url: `${window.location.origin}/dispatch/apps/docs`,
979
+ status: "ready",
980
+ },
981
+ ];
982
+ await act(async () => {
983
+ root.render(
984
+ <WorkspaceAppHost
985
+ appId="docs"
986
+ initialPath="/settings/integrations/notion"
987
+ />,
988
+ );
989
+ await Promise.resolve();
990
+ await Promise.resolve();
991
+ });
992
+
993
+ expect(clientState.legacyMutateAsync).not.toHaveBeenCalled();
994
+ expect(
995
+ container
996
+ .querySelector("[data-chat-first-app-embed-url]")
997
+ ?.getAttribute("data-chat-first-app-embed-url"),
998
+ ).toBe("/docs/settings/integrations/notion");
999
+ });
1000
+
1001
+ it("gives the kept-alive pane the deep route it is showing", async () => {
1002
+ clientState.workspaceApps = [
1003
+ {
1004
+ id: "docs",
1005
+ name: "Docs",
1006
+ path: "/docs",
1007
+ homePath: "/home",
1008
+ url: `${window.location.origin}/dispatch/apps/docs`,
1009
+ status: "ready",
1010
+ },
1011
+ ];
1012
+ await act(async () => {
1013
+ root.render(
1014
+ <WorkspaceAppKeepAlive
1015
+ activeAppId="docs"
1016
+ initialPath="/settings/integrations/notion"
1017
+ />,
1018
+ );
1019
+ await Promise.resolve();
1020
+ await Promise.resolve();
1021
+ });
1022
+
1023
+ expect(
1024
+ container
1025
+ .querySelector("[data-chat-first-app-embed-url]")
1026
+ ?.getAttribute("data-chat-first-app-embed-url"),
1027
+ ).toBe("/docs/settings/integrations/notion");
1028
+ });
1029
+
1030
+ it("keeps a neighbour's route when another app becomes active", async () => {
1031
+ clientState.workspaceApps = [
1032
+ {
1033
+ id: "docs",
1034
+ name: "Docs",
1035
+ path: "/docs",
1036
+ homePath: "/home",
1037
+ url: `${window.location.origin}/dispatch/apps/docs`,
1038
+ status: "ready",
1039
+ },
1040
+ {
1041
+ id: "mail",
1042
+ name: "Mail",
1043
+ path: "/mail",
1044
+ homePath: "/inbox",
1045
+ url: `${window.location.origin}/dispatch/apps/mail`,
1046
+ status: "ready",
1047
+ },
1048
+ ];
1049
+ await act(async () => {
1050
+ root.render(
1051
+ <WorkspaceAppKeepAlive
1052
+ activeAppId="docs"
1053
+ initialPath="/settings/integrations/notion"
1054
+ />,
1055
+ );
1056
+ await Promise.resolve();
1057
+ await Promise.resolve();
1058
+ });
1059
+ await act(async () => {
1060
+ root.render(
1061
+ <WorkspaceAppKeepAlive activeAppId="mail" initialPath="/threads/42" />,
1062
+ );
1063
+ await Promise.resolve();
1064
+ await Promise.resolve();
1065
+ });
1066
+
1067
+ const urls = Array.from(
1068
+ container.querySelectorAll("[data-dispatch-workspace-app-cache-entry]"),
1069
+ ).map((entry) =>
1070
+ [
1071
+ entry.getAttribute("data-dispatch-workspace-app-cache-entry"),
1072
+ entry
1073
+ .querySelector("[data-chat-first-app-embed-url]")
1074
+ ?.getAttribute("data-chat-first-app-embed-url"),
1075
+ ].join("="),
1076
+ );
1077
+ expect(urls).toContain("docs=/docs/settings/integrations/notion");
1078
+ expect(urls).toContain("mail=/mail/threads/42");
1079
+ });
932
1080
  });
@@ -318,6 +318,31 @@ export function WorkspaceAppFrame({
318
318
  const openInTopWindow = shouldOpenWorkspaceAppInTopWindow();
319
319
  const topWindowSsoAttemptKey = `${app.id}\u0000${app.path ?? ""}\u0000${app.url ?? ""}\u0000${embedPath ?? ""}\u0000${initialPath ?? ""}\u0000${embedAttempt}`;
320
320
  const topWindowSsoAttemptedRef = useRef<string | null>(null);
321
+ // A same-origin workspace app already shares the workspace session cookie, so
322
+ // framing it through an embed session makes it worse: an ordinary embed
323
+ // session is limited to its document and static assets (embed-session.ts
324
+ // embedSessionAllowsRequest, pinned by "limits ordinary scope ... to its
325
+ // document and static runtime requests"), which leaves the framed app unable
326
+ // to call any of its own actions. Measured on a hosted workspace: framed with
327
+ // the token the app answered none of 16 action calls with 200 and rendered its
328
+ // failure copy; framed directly it answered all 16.
329
+ // Keep the embedded presentation without the credential.
330
+ const hostPageDirectUrl = useMemo(() => {
331
+ if (!isHostPageUrl) return null;
332
+ const targetPath = embedPath ?? initialPath;
333
+ const href =
334
+ targetPath !== undefined
335
+ ? workspaceAppDirectHref(
336
+ { path: app.path ?? null, url: appUrl },
337
+ targetPath,
338
+ )
339
+ : appHref;
340
+ // No embed parameters: without a token \`embedded=1\` only changes
341
+ // batching, and the plain app URL is what the existing direct fallback
342
+ // already loads when a mint fails.
343
+ return href || null;
344
+ }, [app.path, appHref, appUrl, embedPath, initialPath, isHostPageUrl]);
345
+
321
346
  const embedInput = useMemo<EmbedSessionInput | null>(() => {
322
347
  if (embedPath !== undefined) {
323
348
  return buildChatFirstEmbedSessionInput(app.id, embedPath);
@@ -348,6 +373,7 @@ export function WorkspaceAppFrame({
348
373
  ]);
349
374
 
350
375
  useEffect(() => {
376
+ if (hostPageDirectUrl) return;
351
377
  if (openInTopWindow && useWorkspaceSso && embedInput) {
352
378
  setTopWindowNavigationFailed(false);
353
379
  return;
@@ -377,6 +403,12 @@ export function WorkspaceAppFrame({
377
403
  ]);
378
404
 
379
405
  useEffect(() => {
406
+ if (hostPageDirectUrl) {
407
+ setEmbedUrl(hostPageDirectUrl);
408
+ setEmbedError(null);
409
+ setIsDirectFallback(false);
410
+ return;
411
+ }
380
412
  const useTopWindowSso = openInTopWindow && useWorkspaceSso && !!embedInput;
381
413
  if (
382
414
  !embedInput ||
@@ -450,6 +482,7 @@ export function WorkspaceAppFrame({
450
482
  createWorkspaceSsoEmbedSession.mutateAsync,
451
483
  embedInput,
452
484
  embedPath,
485
+ hostPageDirectUrl,
453
486
  initialPath,
454
487
  embedAttempt,
455
488
  openInTopWindow,
@@ -714,12 +747,29 @@ const MAX_KEEP_ALIVE_APPS = 3;
714
747
 
715
748
  export function WorkspaceAppKeepAlive({
716
749
  activeAppId,
750
+ initialPath,
751
+ onChildRouteChange,
717
752
  }: {
718
753
  activeAppId: string | null;
754
+ /**
755
+ * The deep route for the app being shown. Without it every kept-alive pane
756
+ * opens the app's home: this wrapper is what Layout renders for an app route,
757
+ * so the route's own deep path has to reach the host through here.
758
+ */
759
+ initialPath?: string;
760
+ onChildRouteChange?: (path: string) => void;
719
761
  }) {
720
762
  const [visitedAppIds, setVisitedAppIds] = useState<string[]>(() =>
721
763
  activeAppId ? [activeAppId] : [],
722
764
  );
765
+ // Remember the route each app was last shown at. Handing the deep path only to
766
+ // the active app would reset a neighbour to its home the moment another app
767
+ // becomes active, which is exactly what keep-alive exists to prevent.
768
+ const [pathByAppId, setPathByAppId] = useState<Record<string, string>>(() =>
769
+ activeAppId && initialPath !== undefined
770
+ ? { [activeAppId]: initialPath }
771
+ : {},
772
+ );
723
773
 
724
774
  useEffect(() => {
725
775
  if (!activeAppId) return;
@@ -731,6 +781,15 @@ export function WorkspaceAppKeepAlive({
731
781
  );
732
782
  }, [activeAppId]);
733
783
 
784
+ useEffect(() => {
785
+ if (!activeAppId || initialPath === undefined) return;
786
+ setPathByAppId((current) =>
787
+ current[activeAppId] === initialPath
788
+ ? current
789
+ : { ...current, [activeAppId]: initialPath },
790
+ );
791
+ }, [activeAppId, initialPath]);
792
+
734
793
  const renderedAppIds =
735
794
  activeAppId && !visitedAppIds.includes(activeAppId)
736
795
  ? [activeAppId, ...visitedAppIds]
@@ -750,7 +809,13 @@ export function WorkspaceAppKeepAlive({
750
809
  aria-hidden={!active}
751
810
  className={active ? "h-full min-h-0" : "hidden"}
752
811
  >
753
- <WorkspaceAppHost appId={appId} />
812
+ <WorkspaceAppHost
813
+ appId={appId}
814
+ {...(Object.hasOwn(pathByAppId, appId)
815
+ ? { initialPath: pathByAppId[appId] }
816
+ : {})}
817
+ {...(active && onChildRouteChange ? { onChildRouteChange } : {})}
818
+ />
754
819
  </div>
755
820
  );
756
821
  })}
@@ -313,6 +313,19 @@ export function workspaceAppInitialPathFromSplat(
313
313
  return path === "/" ? undefined : path;
314
314
  }
315
315
 
316
+ /**
317
+ * The deep path an `/apps/<id>/<rest>` route carries, for hosts that render the
318
+ * pane from a layout rather than from the route component itself.
319
+ */
320
+ export function workspaceAppInitialPathFromPathname(
321
+ pathname: string,
322
+ search = "",
323
+ hash = "",
324
+ ): string | undefined {
325
+ const match = pathname.match(/^\/apps\/[^/]+\/(.+)$/);
326
+ return workspaceAppInitialPathFromSplat(match?.[1], search, hash);
327
+ }
328
+
316
329
  export function workspaceAppIdFromRoute(pathname: string): string | null {
317
330
  const match = pathname.match(/^\/apps\/([^/]+)(?:\/|$)/);
318
331
  if (!match) return null;
@@ -0,0 +1,96 @@
1
+ // @vitest-environment happy-dom
2
+ /**
3
+ * The sibling spec (apps.$appId.spec.tsx) mocks useParams/useLocation and the
4
+ * splat helper, so it cannot see how a real router delivers a deep workspace-app
5
+ * URL. This file mounts the real route component in a real memory router with
6
+ * the real route path and the real helper, and asserts what the host receives.
7
+ */
8
+ import React, { act } from "react";
9
+ import { createRoot, type Root } from "react-dom/client";
10
+ import {
11
+ createMemoryRouter,
12
+ RouterProvider,
13
+ type RouteObject,
14
+ } from "react-router";
15
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16
+
17
+ const captured = vi.hoisted(() => ({
18
+ initialPath: undefined as string | undefined,
19
+ appId: undefined as string | undefined,
20
+ }));
21
+
22
+ vi.mock("../../components/workspace-app-host", () => ({
23
+ WorkspaceAppHost: (props: { appId?: string; initialPath?: string }) => {
24
+ captured.appId = props.appId;
25
+ captured.initialPath = props.initialPath;
26
+ return <div data-workspace-app-id={props.appId} />;
27
+ },
28
+ }));
29
+
30
+ import WorkspaceAppRoute from "./apps.$appId";
31
+
32
+ function routes(): RouteObject[] {
33
+ return [
34
+ { path: "apps", element: <div>apps-list</div> },
35
+ { path: "apps/:appId/*", element: <WorkspaceAppRoute /> },
36
+ ];
37
+ }
38
+
39
+ async function renderAt(url: string, basename = "/"): Promise<{ root: Root }> {
40
+ const router = createMemoryRouter(routes(), {
41
+ initialEntries: [url],
42
+ basename,
43
+ });
44
+ const container = document.createElement("div");
45
+ document.body.appendChild(container);
46
+ const root = createRoot(container);
47
+ await act(async () => {
48
+ root.render(<RouterProvider router={router} />);
49
+ });
50
+ return { root };
51
+ }
52
+
53
+ describe("WorkspaceAppRoute with a real router", () => {
54
+ beforeEach(() => {
55
+ captured.initialPath = undefined;
56
+ captured.appId = undefined;
57
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
58
+ });
59
+
60
+ afterEach(() => {
61
+ vi.unstubAllGlobals();
62
+ });
63
+
64
+ it("hands the host the deep path a splat URL carries", async () => {
65
+ const { root } = await renderAt(
66
+ "/apps/content-2/settings/integrations/notion",
67
+ );
68
+ expect(captured.appId).toBe("content-2");
69
+ expect(captured.initialPath).toBe("/settings/integrations/notion");
70
+ await act(async () => root.unmount());
71
+ });
72
+
73
+ it("hands the host the documented deep path when the query parameter carries it", async () => {
74
+ const { root } = await renderAt(
75
+ "/apps/content-2?__workspace_app_path=%2Fsent",
76
+ );
77
+ expect(captured.initialPath).toBe("/sent");
78
+ await act(async () => root.unmount());
79
+ });
80
+
81
+ it("leaves the path undefined at the app root so the host can use its home path", async () => {
82
+ const { root } = await renderAt("/apps/content-2");
83
+ expect(captured.initialPath).toBeUndefined();
84
+ await act(async () => root.unmount());
85
+ });
86
+
87
+ it("hands the host the deep path under the Dispatch basename too", async () => {
88
+ const { root } = await renderAt(
89
+ "/dispatch/apps/content-2/settings/integrations/notion",
90
+ "/dispatch",
91
+ );
92
+ expect(captured.appId).toBe("content-2");
93
+ expect(captured.initialPath).toBe("/settings/integrations/notion");
94
+ await act(async () => root.unmount());
95
+ });
96
+ });