@assistant-ui/react 0.12.28 → 0.14.0

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 (124) hide show
  1. package/dist/client/ExternalThread.d.ts.map +1 -1
  2. package/dist/client/ExternalThread.js +0 -2
  3. package/dist/client/ExternalThread.js.map +1 -1
  4. package/dist/client/InMemoryThreadList.d.ts.map +1 -1
  5. package/dist/client/InMemoryThreadList.js +3 -0
  6. package/dist/client/InMemoryThreadList.js.map +1 -1
  7. package/dist/client/SingleThreadList.d.ts.map +1 -1
  8. package/dist/client/SingleThreadList.js +3 -0
  9. package/dist/client/SingleThreadList.js.map +1 -1
  10. package/dist/context/providers/ThreadViewportProvider.d.ts.map +1 -1
  11. package/dist/context/providers/ThreadViewportProvider.js +2 -10
  12. package/dist/context/providers/ThreadViewportProvider.js.map +1 -1
  13. package/dist/context/stores/ThreadViewport.d.ts +46 -4
  14. package/dist/context/stores/ThreadViewport.d.ts.map +1 -1
  15. package/dist/context/stores/ThreadViewport.js +51 -7
  16. package/dist/context/stores/ThreadViewport.js.map +1 -1
  17. package/dist/index.d.ts +1 -29
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -28
  20. package/dist/index.js.map +1 -1
  21. package/dist/legacy-runtime/runtime-cores/assistant-transport/utils.d.ts +1 -1
  22. package/dist/legacy-runtime/runtime-cores/assistant-transport/utils.d.ts.map +1 -1
  23. package/dist/legacy-runtime/runtime-cores/assistant-transport/utils.js +1 -1
  24. package/dist/legacy-runtime/runtime-cores/assistant-transport/utils.js.map +1 -1
  25. package/dist/primitives/composer/ComposerInput.d.ts.map +1 -1
  26. package/dist/primitives/composer/ComposerInput.js +9 -4
  27. package/dist/primitives/composer/ComposerInput.js.map +1 -1
  28. package/dist/primitives/message/MessageRoot.d.ts +6 -30
  29. package/dist/primitives/message/MessageRoot.d.ts.map +1 -1
  30. package/dist/primitives/message/MessageRoot.js +68 -25
  31. package/dist/primitives/message/MessageRoot.js.map +1 -1
  32. package/dist/primitives/thread/ThreadViewport.d.ts +38 -0
  33. package/dist/primitives/thread/ThreadViewport.d.ts.map +1 -1
  34. package/dist/primitives/thread/ThreadViewport.js +53 -5
  35. package/dist/primitives/thread/ThreadViewport.js.map +1 -1
  36. package/dist/primitives/thread/ThreadViewportFooter.d.ts +2 -1
  37. package/dist/primitives/thread/ThreadViewportFooter.d.ts.map +1 -1
  38. package/dist/primitives/thread/ThreadViewportFooter.js +2 -1
  39. package/dist/primitives/thread/ThreadViewportFooter.js.map +1 -1
  40. package/dist/primitives/thread/topAnchor/computeTopAnchorSlack.d.ts +22 -0
  41. package/dist/primitives/thread/topAnchor/computeTopAnchorSlack.d.ts.map +1 -0
  42. package/dist/primitives/thread/topAnchor/computeTopAnchorSlack.js +53 -0
  43. package/dist/primitives/thread/topAnchor/computeTopAnchorSlack.js.map +1 -0
  44. package/dist/primitives/thread/topAnchor/createReserveObservers.d.ts +5 -0
  45. package/dist/primitives/thread/topAnchor/createReserveObservers.d.ts.map +1 -0
  46. package/dist/primitives/thread/topAnchor/createReserveObservers.js +38 -0
  47. package/dist/primitives/thread/topAnchor/createReserveObservers.js.map +1 -0
  48. package/dist/primitives/thread/topAnchor/mountTopAnchorReserve.d.ts +22 -0
  49. package/dist/primitives/thread/topAnchor/mountTopAnchorReserve.d.ts.map +1 -0
  50. package/dist/primitives/thread/topAnchor/mountTopAnchorReserve.js +75 -0
  51. package/dist/primitives/thread/topAnchor/mountTopAnchorReserve.js.map +1 -0
  52. package/dist/primitives/thread/topAnchor/topAnchorTurn.d.ts +15 -0
  53. package/dist/primitives/thread/topAnchor/topAnchorTurn.d.ts.map +1 -0
  54. package/dist/primitives/thread/topAnchor/topAnchorTurn.js +13 -0
  55. package/dist/primitives/thread/topAnchor/topAnchorTurn.js.map +1 -0
  56. package/dist/primitives/thread/topAnchor/topAnchorUtils.d.ts +15 -0
  57. package/dist/primitives/thread/topAnchor/topAnchorUtils.d.ts.map +1 -0
  58. package/dist/primitives/thread/topAnchor/topAnchorUtils.js +51 -0
  59. package/dist/primitives/thread/topAnchor/topAnchorUtils.js.map +1 -0
  60. package/dist/primitives/thread/topAnchor/useTopAnchorReserve.d.ts +7 -0
  61. package/dist/primitives/thread/topAnchor/useTopAnchorReserve.d.ts.map +1 -0
  62. package/dist/primitives/thread/topAnchor/useTopAnchorReserve.js +18 -0
  63. package/dist/primitives/thread/topAnchor/useTopAnchorReserve.js.map +1 -0
  64. package/dist/primitives/thread/useThreadViewportAutoScroll.d.ts.map +1 -1
  65. package/dist/primitives/thread/useThreadViewportAutoScroll.js +13 -1
  66. package/dist/primitives/thread/useThreadViewportAutoScroll.js.map +1 -1
  67. package/dist/primitives/thread.d.ts +0 -1
  68. package/dist/primitives/thread.d.ts.map +1 -1
  69. package/dist/primitives/thread.js +0 -1
  70. package/dist/primitives/thread.js.map +1 -1
  71. package/dist/primitives/threadList/ThreadListLoadMore.d.ts +13 -0
  72. package/dist/primitives/threadList/ThreadListLoadMore.d.ts.map +1 -0
  73. package/dist/primitives/threadList/ThreadListLoadMore.js +11 -0
  74. package/dist/primitives/threadList/ThreadListLoadMore.js.map +1 -0
  75. package/dist/primitives/threadList.d.ts +1 -0
  76. package/dist/primitives/threadList.d.ts.map +1 -1
  77. package/dist/primitives/threadList.js +1 -0
  78. package/dist/primitives/threadList.js.map +1 -1
  79. package/dist/utils/hooks/useManagedRef.d.ts.map +1 -1
  80. package/dist/utils/hooks/useManagedRef.js +1 -0
  81. package/dist/utils/hooks/useManagedRef.js.map +1 -1
  82. package/dist/utils/hooks/useOnResizeContent.d.ts.map +1 -1
  83. package/dist/utils/hooks/useOnResizeContent.js +1 -2
  84. package/dist/utils/hooks/useOnResizeContent.js.map +1 -1
  85. package/package.json +10 -10
  86. package/src/client/ExternalThread.ts +0 -2
  87. package/src/client/InMemoryThreadList.ts +3 -0
  88. package/src/client/SingleThreadList.ts +3 -0
  89. package/src/context/providers/ThreadViewportProvider.tsx +2 -12
  90. package/src/context/stores/ThreadViewport.ts +111 -11
  91. package/src/index.ts +0 -35
  92. package/src/legacy-runtime/runtime-cores/assistant-transport/utils.ts +1 -5
  93. package/src/primitives/composer/ComposerInput.test.tsx +232 -0
  94. package/src/primitives/composer/ComposerInput.tsx +9 -4
  95. package/src/primitives/message/MessageRoot.tsx +135 -57
  96. package/src/primitives/thread/ThreadViewport.tsx +95 -4
  97. package/src/primitives/thread/ThreadViewportFooter.tsx +2 -1
  98. package/src/primitives/thread/topAnchor/computeTopAnchorSlack.test.ts +131 -0
  99. package/src/primitives/thread/topAnchor/computeTopAnchorSlack.ts +94 -0
  100. package/src/primitives/thread/topAnchor/createReserveObservers.ts +50 -0
  101. package/src/primitives/thread/topAnchor/mountTopAnchorReserve.test.ts +131 -0
  102. package/src/primitives/thread/topAnchor/mountTopAnchorReserve.ts +127 -0
  103. package/src/primitives/thread/topAnchor/topAnchorTurn.test.ts +46 -0
  104. package/src/primitives/thread/topAnchor/topAnchorTurn.ts +30 -0
  105. package/src/primitives/thread/topAnchor/topAnchorUtils.ts +58 -0
  106. package/src/primitives/thread/topAnchor/useTopAnchorReserve.ts +19 -0
  107. package/src/primitives/thread/useThreadViewportAutoScroll.ts +15 -1
  108. package/src/primitives/thread.ts +0 -1
  109. package/src/primitives/threadList/ThreadListLoadMore.tsx +24 -0
  110. package/src/primitives/threadList.ts +1 -0
  111. package/src/tests/RemoteThreadListRuntime.adapterProvider.test.tsx +138 -0
  112. package/src/tests/RemoteThreadListRuntime.deferredProvider.test.tsx +28 -17
  113. package/src/utils/hooks/useManagedRef.ts +1 -0
  114. package/src/utils/hooks/useOnResizeContent.ts +1 -2
  115. package/dist/legacy-runtime/runtime-cores/external-store/getExternalStoreMessage.d.ts +0 -3
  116. package/dist/legacy-runtime/runtime-cores/external-store/getExternalStoreMessage.d.ts.map +0 -1
  117. package/dist/legacy-runtime/runtime-cores/external-store/getExternalStoreMessage.js +0 -3
  118. package/dist/legacy-runtime/runtime-cores/external-store/getExternalStoreMessage.js.map +0 -1
  119. package/dist/primitives/thread/ThreadViewportSlack.d.ts +0 -20
  120. package/dist/primitives/thread/ThreadViewportSlack.d.ts.map +0 -1
  121. package/dist/primitives/thread/ThreadViewportSlack.js +0 -80
  122. package/dist/primitives/thread/ThreadViewportSlack.js.map +0 -1
  123. package/src/legacy-runtime/runtime-cores/external-store/getExternalStoreMessage.ts +0 -6
  124. package/src/primitives/thread/ThreadViewportSlack.tsx +0 -116
@@ -0,0 +1,131 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import {
5
+ mountTopAnchorReserve,
6
+ type TopAnchorStore,
7
+ } from "./mountTopAnchorReserve";
8
+
9
+ class ResizeObserverMock {
10
+ observe = vi.fn();
11
+ disconnect = vi.fn();
12
+ }
13
+
14
+ class MutationObserverMock {
15
+ observe = vi.fn();
16
+ disconnect = vi.fn();
17
+ }
18
+
19
+ const defineReadonlyNumber = (
20
+ element: HTMLElement,
21
+ key: "clientHeight" | "scrollHeight" | "offsetHeight" | "offsetTop",
22
+ value: number,
23
+ ) => {
24
+ Object.defineProperty(element, key, { configurable: true, value });
25
+ };
26
+
27
+ const makeStore = (state: ReturnType<TopAnchorStore["getState"]>) => {
28
+ const listeners = new Set<() => void>();
29
+
30
+ return {
31
+ store: {
32
+ getState: () => state,
33
+ subscribe: (listener: () => void) => {
34
+ listeners.add(listener);
35
+ return () => listeners.delete(listener);
36
+ },
37
+ } satisfies TopAnchorStore,
38
+ setState: (nextState: ReturnType<TopAnchorStore["getState"]>) => {
39
+ state = nextState;
40
+ for (const listener of listeners) listener();
41
+ },
42
+ };
43
+ };
44
+
45
+ const numericClamp = { tallerThan: 160, visibleHeight: 96 };
46
+
47
+ describe("mountTopAnchorReserve", () => {
48
+ beforeEach(() => {
49
+ vi.useFakeTimers();
50
+ vi.stubGlobal("ResizeObserver", ResizeObserverMock);
51
+ vi.stubGlobal("MutationObserver", MutationObserverMock);
52
+ });
53
+
54
+ afterEach(() => {
55
+ vi.useRealTimers();
56
+ vi.unstubAllGlobals();
57
+ document.body.replaceChildren();
58
+ });
59
+
60
+ it("adds enough stable reserve after the active assistant turn to make the top anchor reachable", () => {
61
+ const viewport = document.createElement("div");
62
+ const anchor = document.createElement("div");
63
+ const target = document.createElement("div");
64
+ const reserveHost = document.createElement("div");
65
+ reserveHost.append(target);
66
+ document.body.append(reserveHost);
67
+
68
+ defineReadonlyNumber(viewport, "offsetTop", 0);
69
+ defineReadonlyNumber(viewport, "clientHeight", 400);
70
+ defineReadonlyNumber(viewport, "scrollHeight", 560);
71
+ defineReadonlyNumber(anchor, "offsetTop", 220);
72
+ defineReadonlyNumber(anchor, "offsetHeight", 64);
73
+ viewport.scrollTo = vi.fn();
74
+
75
+ const { store } = makeStore({
76
+ turnAnchor: "top",
77
+ element: { viewport, anchor, target },
78
+ targetConfig: numericClamp,
79
+ });
80
+
81
+ mountTopAnchorReserve(store);
82
+ vi.runOnlyPendingTimers();
83
+
84
+ const reserve = reserveHost.querySelector(
85
+ "[data-aui-top-anchor-reserve]",
86
+ ) as HTMLElement;
87
+
88
+ expect(reserve).not.toBe(null);
89
+ expect(reserve.previousElementSibling).toBe(target);
90
+ expect(reserve.style.height).toBe("60px");
91
+ });
92
+
93
+ it("does not repeat the smooth top-anchor scroll for the same message", () => {
94
+ const viewport = document.createElement("div");
95
+ const anchor = document.createElement("div");
96
+ const target = document.createElement("div");
97
+ document.body.append(target);
98
+
99
+ defineReadonlyNumber(viewport, "offsetTop", 0);
100
+ defineReadonlyNumber(viewport, "clientHeight", 400);
101
+ defineReadonlyNumber(viewport, "scrollHeight", 560);
102
+ defineReadonlyNumber(anchor, "offsetTop", 220);
103
+ defineReadonlyNumber(anchor, "offsetHeight", 64);
104
+ anchor.dataset.messageId = "msg-1";
105
+ viewport.scrollTo = vi.fn();
106
+
107
+ const { store, setState } = makeStore({
108
+ turnAnchor: "top",
109
+ element: { viewport, anchor, target },
110
+ targetConfig: numericClamp,
111
+ });
112
+
113
+ mountTopAnchorReserve(store);
114
+ vi.runOnlyPendingTimers();
115
+
116
+ expect(viewport.scrollTo).not.toHaveBeenCalled();
117
+
118
+ vi.runOnlyPendingTimers();
119
+
120
+ expect(viewport.scrollTo).toHaveBeenCalledTimes(1);
121
+
122
+ setState({
123
+ turnAnchor: "top",
124
+ element: { viewport, anchor, target },
125
+ targetConfig: numericClamp,
126
+ });
127
+ vi.runOnlyPendingTimers();
128
+
129
+ expect(viewport.scrollTo).toHaveBeenCalledTimes(1);
130
+ });
131
+ });
@@ -0,0 +1,127 @@
1
+ "use client";
2
+
3
+ import {
4
+ computeTopAnchorReserve,
5
+ computeTopAnchorTargetScrollTop,
6
+ } from "./computeTopAnchorSlack";
7
+ import { createReserveObservers } from "./createReserveObservers";
8
+ import {
9
+ createReserveElement,
10
+ getAnchorId,
11
+ setReserveHeight,
12
+ snapScrollTop,
13
+ } from "./topAnchorUtils";
14
+
15
+ /**
16
+ * Minimal slice of `ThreadViewportStore` that the top-anchor reserve needs.
17
+ * Decoupling from the full store keeps `mountTopAnchorReserve` testable in
18
+ * isolation and re-usable from any consumer that can adapt to this shape.
19
+ */
20
+ export type TopAnchorStore = {
21
+ getState(): {
22
+ turnAnchor: "top" | "bottom";
23
+ element: {
24
+ viewport: HTMLElement | null;
25
+ anchor: HTMLElement | null;
26
+ target: HTMLElement | null;
27
+ };
28
+ targetConfig: {
29
+ tallerThan: number;
30
+ visibleHeight: number;
31
+ } | null;
32
+ };
33
+ subscribe(fn: () => void): () => void;
34
+ };
35
+
36
+ const createFrameScheduler = (fn: () => void) => {
37
+ let frame: number | null = null;
38
+
39
+ return {
40
+ schedule: () => {
41
+ if (frame !== null) return;
42
+ frame = requestAnimationFrame(() => {
43
+ frame = null;
44
+ fn();
45
+ });
46
+ },
47
+ cancel: () => {
48
+ if (frame !== null) {
49
+ cancelAnimationFrame(frame);
50
+ frame = null;
51
+ }
52
+ },
53
+ };
54
+ };
55
+
56
+ export const mountTopAnchorReserve = (store: TopAnchorStore) => {
57
+ let reserve: HTMLElement | null = null;
58
+ let lastScrolledAnchorId: string | undefined;
59
+
60
+ function apply() {
61
+ const state = store.getState();
62
+ const { viewport, anchor, target } = state.element;
63
+ const clamp = state.targetConfig;
64
+
65
+ if (
66
+ state.turnAnchor !== "top" ||
67
+ !viewport ||
68
+ !anchor ||
69
+ !target ||
70
+ !clamp
71
+ ) {
72
+ observers.disconnect();
73
+ if (reserve) {
74
+ setReserveHeight(reserve, 0);
75
+ reserve.remove();
76
+ }
77
+ return;
78
+ }
79
+
80
+ reserve ??= createReserveElement();
81
+
82
+ if (
83
+ reserve.parentElement !== target.parentElement ||
84
+ reserve.previousElementSibling !== target
85
+ ) {
86
+ target.after(reserve);
87
+ }
88
+
89
+ observers.target(viewport, anchor, target);
90
+
91
+ const reserveChanged = setReserveHeight(
92
+ reserve,
93
+ computeTopAnchorReserve({ viewport, anchor, reserve, ...clamp }),
94
+ );
95
+
96
+ if (reserveChanged) {
97
+ scheduler.schedule();
98
+ return;
99
+ }
100
+
101
+ const anchorId = getAnchorId(anchor);
102
+ if (anchorId !== undefined && lastScrolledAnchorId === anchorId) return;
103
+
104
+ const targetScrollTop = snapScrollTop(
105
+ computeTopAnchorTargetScrollTop({ viewport, anchor, ...clamp }),
106
+ );
107
+
108
+ if (Math.abs(viewport.scrollTop - targetScrollTop) > 1) {
109
+ viewport.scrollTo({ top: targetScrollTop, behavior: "smooth" });
110
+ }
111
+
112
+ if (anchorId !== undefined) lastScrolledAnchorId = anchorId;
113
+ }
114
+
115
+ const scheduler = createFrameScheduler(apply);
116
+ const observers = createReserveObservers(scheduler.schedule);
117
+
118
+ scheduler.schedule();
119
+ const unsubscribe = store.subscribe(scheduler.schedule);
120
+
121
+ return () => {
122
+ scheduler.cancel();
123
+ unsubscribe();
124
+ observers.disconnect();
125
+ reserve?.remove();
126
+ };
127
+ };
@@ -0,0 +1,46 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ getActiveTopAnchorAnchorId,
4
+ getActiveTopAnchorTargetId,
5
+ getActiveTopAnchorTurn,
6
+ } from "./topAnchorTurn";
7
+
8
+ describe("topAnchorTurn", () => {
9
+ it("does not activate history-loaded messages", () => {
10
+ const messages = [
11
+ { id: "user-1", role: "user" },
12
+ { id: "assistant-1", role: "assistant" },
13
+ ];
14
+
15
+ expect(getActiveTopAnchorTurn({ isRunning: false, messages })).toBe(null);
16
+ });
17
+
18
+ it("activates the live user/assistant pair while running", () => {
19
+ const messages = [
20
+ { id: "assistant-1", role: "assistant" },
21
+ { id: "user-2", role: "user" },
22
+ { id: "assistant-2", role: "assistant" },
23
+ ];
24
+
25
+ expect(getActiveTopAnchorTurn({ isRunning: true, messages })).toEqual({
26
+ anchorId: "user-2",
27
+ targetId: "assistant-2",
28
+ });
29
+ expect(getActiveTopAnchorAnchorId({ isRunning: true, messages })).toBe(
30
+ "user-2",
31
+ );
32
+ expect(getActiveTopAnchorTargetId({ isRunning: true, messages })).toBe(
33
+ "assistant-2",
34
+ );
35
+ });
36
+
37
+ it("ignores running states without a trailing user/assistant pair", () => {
38
+ const messages = [
39
+ { id: "user-1", role: "user" },
40
+ { id: "assistant-1", role: "assistant" },
41
+ { id: "user-2", role: "user" },
42
+ ];
43
+
44
+ expect(getActiveTopAnchorTurn({ isRunning: true, messages })).toBe(null);
45
+ });
46
+ });
@@ -0,0 +1,30 @@
1
+ "use client";
2
+
3
+ type TopAnchorTurnMessage = {
4
+ readonly id: string;
5
+ readonly role: string;
6
+ };
7
+
8
+ export const getActiveTopAnchorTurn = ({
9
+ isRunning,
10
+ messages,
11
+ }: {
12
+ readonly isRunning: boolean;
13
+ readonly messages: readonly TopAnchorTurnMessage[];
14
+ }) => {
15
+ if (!isRunning) return null;
16
+
17
+ const target = messages.at(-1);
18
+ const anchor = messages.at(-2);
19
+ if (anchor?.role !== "user" || target?.role !== "assistant") return null;
20
+
21
+ return { anchorId: anchor.id, targetId: target.id };
22
+ };
23
+
24
+ export const getActiveTopAnchorAnchorId = (
25
+ options: Parameters<typeof getActiveTopAnchorTurn>[0],
26
+ ) => getActiveTopAnchorTurn(options)?.anchorId;
27
+
28
+ export const getActiveTopAnchorTargetId = (
29
+ options: Parameters<typeof getActiveTopAnchorTurn>[0],
30
+ ) => getActiveTopAnchorTurn(options)?.targetId;
@@ -0,0 +1,58 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Convert a supported CSS length string (`px`, `em`, `rem`) into pixels,
5
+ * resolving font-relative units against the supplied element's computed style.
6
+ * Unsupported or malformed values disable the tall-message clamp.
7
+ *
8
+ * Part of the top-anchor package's public input contract: consumers may pass
9
+ * clamp configuration as supported CSS-length strings, and this function is the
10
+ * single place that converts them into the pixel values the package operates on.
11
+ */
12
+ export const parseCssLength = (value: string, element: HTMLElement): number => {
13
+ const match = value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);
14
+ if (!match) return Number.POSITIVE_INFINITY;
15
+
16
+ const num = Number(match[1]);
17
+ const unit = match[2];
18
+
19
+ if (unit === "px") return num;
20
+ if (unit === "em") {
21
+ const fontSize = parseFloat(getComputedStyle(element).fontSize) || 16;
22
+ return num * fontSize;
23
+ }
24
+ if (unit === "rem") {
25
+ const rootFontSize =
26
+ parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
27
+ return num * rootFontSize;
28
+ }
29
+ return Number.POSITIVE_INFINITY;
30
+ };
31
+
32
+ export const getAnchorId = (anchor: HTMLElement) => anchor.dataset.messageId;
33
+
34
+ export const createReserveElement = () => {
35
+ const reserve = document.createElement("div");
36
+ reserve.dataset.auiTopAnchorReserve = "";
37
+ reserve.style.height = "0px";
38
+ reserve.style.flexShrink = "0";
39
+ reserve.style.pointerEvents = "none";
40
+ reserve.setAttribute("aria-hidden", "true");
41
+
42
+ return reserve;
43
+ };
44
+
45
+ export const setReserveHeight = (reserve: HTMLElement, height: number) => {
46
+ const nextHeight = `${height}px`;
47
+ if (reserve.style.height !== nextHeight) {
48
+ reserve.style.height = nextHeight;
49
+ return true;
50
+ }
51
+
52
+ return false;
53
+ };
54
+
55
+ export const snapScrollTop = (top: number) => {
56
+ const pixelRatio = window.devicePixelRatio || 1;
57
+ return Math.round(top * pixelRatio) / pixelRatio;
58
+ };
@@ -0,0 +1,19 @@
1
+ "use client";
2
+
3
+ import { useLayoutEffect } from "react";
4
+ import { useThreadViewportStore } from "../../../context/react/ThreadViewportContext";
5
+ import { mountTopAnchorReserve } from "./mountTopAnchorReserve";
6
+
7
+ /**
8
+ * Mounts the top-turn-anchor reserve element against the active
9
+ * `ThreadViewport` store. Call this from inside the scrollable viewport so
10
+ * the reserve `<div>` is appended next to the streaming assistant message.
11
+ */
12
+ export const useTopAnchorReserve = (enabled: boolean) => {
13
+ const threadViewportStore = useThreadViewportStore();
14
+
15
+ useLayoutEffect(() => {
16
+ if (!enabled) return;
17
+ return mountTopAnchorReserve(threadViewportStore);
18
+ }, [enabled, threadViewportStore]);
19
+ };
@@ -70,6 +70,15 @@ export const useThreadViewportAutoScroll = <TElement extends HTMLElement>({
70
70
  div.scrollTo({ top: div.scrollHeight, behavior });
71
71
  }, []);
72
72
 
73
+ const hasActiveTopAnchor = useCallback(() => {
74
+ const state = threadViewportStore.getState();
75
+ return (
76
+ state.turnAnchor === "top" &&
77
+ state.element.viewport === divRef.current &&
78
+ state.element.anchor !== null
79
+ );
80
+ }, [threadViewportStore]);
81
+
73
82
  const handleScroll = () => {
74
83
  const div = divRef.current;
75
84
  if (!div) return;
@@ -101,7 +110,10 @@ export const useThreadViewportAutoScroll = <TElement extends HTMLElement>({
101
110
 
102
111
  const resizeRef = useOnResizeContent(() => {
103
112
  const scrollBehavior = scrollingToBottomBehaviorRef.current;
104
- if (scrollBehavior) {
113
+ if (scrollBehavior && hasActiveTopAnchor()) {
114
+ // Let the top-anchor reserve own scrolling while a run starts to avoid a bottom-scroll race.
115
+ scrollingToBottomBehaviorRef.current = null;
116
+ } else if (scrollBehavior) {
105
117
  scrollToBottom(scrollBehavior);
106
118
  } else if (autoScroll && threadViewportStore.getState().isAtBottom) {
107
119
  scrollToBottom("instant");
@@ -124,6 +136,8 @@ export const useThreadViewportAutoScroll = <TElement extends HTMLElement>({
124
136
  // autoscroll on run start
125
137
  useAuiEvent("thread.runStart", () => {
126
138
  if (!scrollToBottomOnRunStart) return;
139
+ if (threadViewportStore.getState().turnAnchor === "top") return;
140
+
127
141
  scrollingToBottomBehaviorRef.current = "auto";
128
142
  requestAnimationFrame(() => {
129
143
  scrollToBottom("auto");
@@ -4,7 +4,6 @@ export { ThreadPrimitiveIf as If } from "./thread/ThreadIf";
4
4
  export { ThreadPrimitiveViewport as Viewport } from "./thread/ThreadViewport";
5
5
  export { ThreadPrimitiveViewportProvider as ViewportProvider } from "../context/providers/ThreadViewportProvider";
6
6
  export { ThreadPrimitiveViewportFooter as ViewportFooter } from "./thread/ThreadViewportFooter";
7
- export { ThreadPrimitiveViewportSlack as ViewportSlack } from "./thread/ThreadViewportSlack";
8
7
  export { ThreadPrimitiveMessages as Messages } from "./thread/ThreadMessages";
9
8
  export { ThreadPrimitiveMessageByIndex as MessageByIndex } from "./thread/ThreadMessages";
10
9
  export { ThreadPrimitiveScrollToBottom as ScrollToBottom } from "./thread/ThreadScrollToBottom";
@@ -0,0 +1,24 @@
1
+ "use client";
2
+
3
+ import {
4
+ type ActionButtonElement,
5
+ type ActionButtonProps,
6
+ createActionButton,
7
+ } from "../../utils/createActionButton";
8
+ import { useThreadListLoadMore as useThreadListLoadMoreBehavior } from "@assistant-ui/core/react";
9
+
10
+ const useThreadListLoadMore = () => {
11
+ const { loadMore, disabled } = useThreadListLoadMoreBehavior();
12
+ if (disabled) return null;
13
+ return loadMore;
14
+ };
15
+
16
+ export namespace ThreadListPrimitiveLoadMore {
17
+ export type Element = ActionButtonElement;
18
+ export type Props = ActionButtonProps<typeof useThreadListLoadMore>;
19
+ }
20
+
21
+ export const ThreadListPrimitiveLoadMore = createActionButton(
22
+ "ThreadListPrimitive.LoadMore",
23
+ useThreadListLoadMore,
24
+ );
@@ -1,4 +1,5 @@
1
1
  export { ThreadListPrimitiveNew as New } from "./threadList/ThreadListNew";
2
2
  export { ThreadListPrimitiveItems as Items } from "./threadList/ThreadListItems";
3
3
  export { ThreadListPrimitiveItemByIndex as ItemByIndex } from "./threadList/ThreadListItems";
4
+ export { ThreadListPrimitiveLoadMore as LoadMore } from "./threadList/ThreadListLoadMore";
4
5
  export { ThreadListPrimitiveRoot as Root } from "./threadList/ThreadListRoot";
@@ -0,0 +1,138 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import { act, render, waitFor } from "@testing-library/react";
4
+ import type { FC, PropsWithChildren } from "react";
5
+ import { describe, expect, it } from "vitest";
6
+ import {
7
+ RuntimeAdapterProvider,
8
+ useRemoteThreadListRuntime,
9
+ useRuntimeAdapters,
10
+ } from "@assistant-ui/core/react";
11
+ import { makeAdapter } from "./remote-thread-list-test-helpers";
12
+ import { useLocalRuntime } from "../legacy-runtime/runtime-cores/local/useLocalRuntime";
13
+ import { AssistantRuntimeProvider } from "../context";
14
+ import type { ChatModelAdapter, RemoteThreadListAdapter } from "../index";
15
+ import type {
16
+ RuntimeAdapters as RuntimeAdaptersShape,
17
+ ThreadHistoryAdapter,
18
+ } from "@assistant-ui/core";
19
+
20
+ type CapturedAdapters = RuntimeAdaptersShape | null;
21
+
22
+ const noOpAdapter: ChatModelAdapter = {
23
+ async *run() {},
24
+ };
25
+
26
+ const dummyHistory: ThreadHistoryAdapter = {
27
+ load: async () => ({ messages: [] }),
28
+ append: async () => {},
29
+ };
30
+
31
+ const makeRuntimeHook = (capture: { adapters: CapturedAdapters }) =>
32
+ function useTestRuntimeHook() {
33
+ capture.adapters = useRuntimeAdapters();
34
+ return useLocalRuntime(noOpAdapter);
35
+ };
36
+
37
+ async function renderAndWaitForBinder(
38
+ adapter: RemoteThreadListAdapter,
39
+ capture: { adapters: CapturedAdapters },
40
+ ) {
41
+ const Inner: FC = () => {
42
+ const runtime = useRemoteThreadListRuntime({
43
+ runtimeHook: makeRuntimeHook(capture),
44
+ adapter,
45
+ });
46
+ return (
47
+ <AssistantRuntimeProvider runtime={runtime}>
48
+ {null}
49
+ </AssistantRuntimeProvider>
50
+ );
51
+ };
52
+
53
+ // first thread instance arrives asynchronously via switchToNewThread.
54
+ await act(async () => {
55
+ render(<Inner />);
56
+ });
57
+ await waitFor(() => expect(capture.adapters).not.toBeNull());
58
+ }
59
+
60
+ const wrapInRuntimeAdapterProvider = (
61
+ history: ThreadHistoryAdapter,
62
+ ): FC<PropsWithChildren> =>
63
+ function Provider({ children }) {
64
+ return (
65
+ <RuntimeAdapterProvider adapters={{ history }}>
66
+ {children}
67
+ </RuntimeAdapterProvider>
68
+ );
69
+ };
70
+
71
+ describe("RemoteThreadListAdapter.unstable_Provider", () => {
72
+ it("makes RuntimeAdapterProvider context visible to the runtime hook", async () => {
73
+ const capture: { adapters: CapturedAdapters } = { adapters: null };
74
+ const adapter = makeAdapter({
75
+ unstable_Provider: wrapInRuntimeAdapterProvider(dummyHistory),
76
+ });
77
+ await renderAndWaitForBinder(adapter, capture);
78
+
79
+ expect(capture.adapters?.history).toBe(dummyHistory);
80
+ });
81
+
82
+ it("preserves modelContext from the outer runtime-core RuntimeAdapterProvider", async () => {
83
+ const capture: { adapters: CapturedAdapters } = { adapters: null };
84
+ const adapter = makeAdapter({
85
+ unstable_Provider: wrapInRuntimeAdapterProvider(dummyHistory),
86
+ });
87
+ await renderAndWaitForBinder(adapter, capture);
88
+
89
+ expect(capture.adapters?.history).toBe(dummyHistory);
90
+ expect(capture.adapters?.modelContext).toBeDefined();
91
+ });
92
+
93
+ it("returns no history when no Provider is supplied", async () => {
94
+ const capture: { adapters: CapturedAdapters } = { adapters: null };
95
+ const adapter = makeAdapter();
96
+ await renderAndWaitForBinder(adapter, capture);
97
+
98
+ expect(capture.adapters?.history).toBeUndefined();
99
+ });
100
+
101
+ it("picks up a swapped Provider on re-render", async () => {
102
+ const capture: { adapters: CapturedAdapters } = { adapters: null };
103
+ const firstHistory: ThreadHistoryAdapter = {
104
+ load: async () => ({ messages: [] }),
105
+ append: async () => {},
106
+ };
107
+ const secondHistory: ThreadHistoryAdapter = {
108
+ load: async () => ({ messages: [] }),
109
+ append: async () => {},
110
+ };
111
+
112
+ const Inner: FC<{ history: ThreadHistoryAdapter }> = ({ history }) => {
113
+ const adapter = makeAdapter({
114
+ unstable_Provider: wrapInRuntimeAdapterProvider(history),
115
+ });
116
+ const runtime = useRemoteThreadListRuntime({
117
+ runtimeHook: makeRuntimeHook(capture),
118
+ adapter,
119
+ });
120
+ return (
121
+ <AssistantRuntimeProvider runtime={runtime}>
122
+ {null}
123
+ </AssistantRuntimeProvider>
124
+ );
125
+ };
126
+
127
+ let result: ReturnType<typeof render>;
128
+ await act(async () => {
129
+ result = render(<Inner history={firstHistory} />);
130
+ });
131
+ await waitFor(() => expect(capture.adapters?.history).toBe(firstHistory));
132
+
133
+ await act(async () => {
134
+ result!.rerender(<Inner history={secondHistory} />);
135
+ });
136
+ await waitFor(() => expect(capture.adapters?.history).toBe(secondHistory));
137
+ });
138
+ });