diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
index ff5b426c0bf3f..9048b0791e21a 100644
--- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
@@ -682,6 +682,44 @@ it("reopens a long draft scrolled to its caret without taking focus", async () =
expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1);
});
+it.each([false, true])(
+ "keeps the reading position when a draft rewraps (focused: %s)",
+ async (focused) => {
+ const value = "A long wrapped paragraph should keep the sentence being read in view. ".repeat(
+ 100,
+ );
+ const style = document.head.appendChild(document.createElement("style"));
+ style.textContent = ".composer-tiptap { width: 700px; max-height: 160px; overflow-y: auto; }";
+ using _style = { [Symbol.dispose]: () => style.remove() };
+ await using screen = await mountEditor(value);
+ const { editor } = screen;
+ const scroller = editor.view.dom;
+ await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(500));
+ if (focused) await focusAt(editor, 2000);
+ scroller.scrollTop = 300;
+ scroller.dispatchEvent(new Event("scroll"));
+ const box = scroller.getBoundingClientRect();
+ const position = editor.view.posAtCoords({
+ left: box.left + box.width / 2,
+ top: box.top + 25,
+ })!;
+ const before = editor.view.coordsAtPos(position.pos).top - box.top;
+ if (focused) await focusAt(editor, position.pos);
+ document.dispatchEvent(new Event("selectionchange"));
+ const selection = editor.state.selection.toJSON();
+ for (const width of [420, 700]) {
+ scroller.style.width = `${width}px`;
+ await vi.waitFor(() => {
+ const after =
+ editor.view.coordsAtPos(position.pos).top - scroller.getBoundingClientRect().top;
+ expect(Math.abs(after - before)).toBeLessThan(25);
+ });
+ expect(editor.state.selection.toJSON()).toEqual(selection);
+ expect(editor.view.hasFocus()).toBe(focused);
+ }
+ },
+);
+
it("does not outline the line under a click made with the node-select modifier held", async () => {
await using screen = await mountEditor("ship it");
const { editor } = screen;
diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx
index 634b7a9389e93..8ce568c117dce 100644
--- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx
+++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx
@@ -64,6 +64,7 @@ import {
pastedPathQueryLength,
} from "~/composer-logic";
import { useStableCallback } from "~/hooks/useStableCallback";
+import { preserveReadingPosition } from "~/lib/preserveReadingPosition";
import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction";
import {
collapseShownMarkdownSource,
@@ -1765,6 +1766,11 @@ function ComposerPromptEditorTiptapInner(
if (replacements.length > 0) replaceSkillChips(editor, replacements);
}, [editor, literalText, modelKeys, skills]);
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes
+ useLayoutEffect(() => {
+ if (editor) return preserveReadingPosition(editor.view.dom);
+ }, [editor]);
+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown
useLayoutEffect(() => {
if (!editor) return;
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index d15a26ca43db0..bce13bb454379 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -626,6 +626,48 @@ describe("MessagesTimeline messages", () => {
await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd));
});
+ it("keeps the visible sentence in a long message when the chat width changes", async () => {
+ setup();
+ const size = { width: window.innerWidth, height: window.innerHeight };
+ onTestFinished(() => page.viewport(size.width, size.height));
+ await page.viewport(1200, 1400);
+ const props = { ...baseProps(), liveFollowEnabled: false };
+ const paragraphs = Array.from(
+ { length: 30 },
+ (_, index) =>
+ `Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`,
+ );
+ await using screen = await renderTimeline(
+ [message(paragraphs.join("\n\n"), { role: "assistant" })],
+ props,
+ );
+ screen.container.style.width = "900px";
+ const viewport = props.listRef.current!.getScrollableNode()!;
+ const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element();
+ await vi.waitFor(() => {
+ expect(viewport.scrollHeight).toBeGreaterThan(1000);
+ expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2);
+ });
+ await props.listRef.current!.scrollToOffset({
+ offset:
+ viewport.scrollTop +
+ target.getBoundingClientRect().top -
+ viewport.getBoundingClientRect().top -
+ 24,
+ animated: false,
+ });
+ viewport.dispatchEvent(new Event("scroll"));
+ const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top;
+ expect(Math.abs(before - 24)).toBeLessThan(2);
+ for (const width of [500, 900]) {
+ screen.container.style.width = `${width}px`;
+ await vi.waitFor(() => {
+ const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top;
+ expect(Math.abs(after - before)).toBeLessThan(30);
+ });
+ }
+ });
+
it("disables the minimap's next turn button at the bottom of the thread", async () => {
setup();
const props = baseProps();
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index fe60471993e36..51c217daa32b7 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -26,6 +26,7 @@ import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
import { observeResize } from "~/lib/observeResize";
+import { preserveReadingPosition } from "~/lib/preserveReadingPosition";
import { useStableCallback } from "~/hooks/useStableCallback";
const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
@@ -1255,6 +1256,14 @@ const ConversationTimeline = memo(function ConversationTimeline({
const canvas = useChatCanvas();
const registerTimeline = canvas?.registerTimeline;
+ const shouldPreserveReadingPosition = useStableCallback(
+ () =>
+ !liveFollowEnabled &&
+ !anchoredEndSpace &&
+ !findActive &&
+ !citationPositioning &&
+ !restoringThreadPosition,
+ );
// Stable so the list attaches once per mount, not on every render.
const setTimelineList = useStableCallback((list: LegendListRef | null) => {
listRef.current = list;
@@ -1270,6 +1279,9 @@ const ConversationTimeline = memo(function ConversationTimeline({
})
: null;
viewportRef.current = viewport;
+ const stopPreservingReadingPosition = scrollNode
+ ? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition)
+ : undefined;
const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined;
const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition);
const stopDisclosureReveal = viewport?.subscribe(() => {
@@ -1298,6 +1310,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
scheduleContentSizeChanged();
return () => {
stopListeningToContentSize?.();
+ stopPreservingReadingPosition?.();
stopRememberingRelease?.();
stopDisclosureReveal?.();
if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame);
diff --git a/apps/web/src/lib/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts
new file mode 100644
index 0000000000000..a678c86a052a4
--- /dev/null
+++ b/apps/web/src/lib/preserveReadingPosition.ts
@@ -0,0 +1,118 @@
+import { observeResize } from "./observeResize";
+
+/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */
+export function preserveReadingPosition(
+ scroller: HTMLElement,
+ enabled: () => boolean = () => true,
+): () => void {
+ let width = scroller.clientWidth;
+ let anchor: { range: Range; top: number } | null = null;
+ let frame: number | null = null;
+
+ const capture = () => {
+ if (frame !== null || scroller.clientWidth !== width) return;
+ anchor = null;
+ if (!enabled() || scroller.scrollTop === 0) return;
+ const box = scroller.getBoundingClientRect();
+ const selection =
+ scroller.isContentEditable && document.activeElement === scroller
+ ? document.getSelection()
+ : null;
+ if (selection?.isCollapsed && selection.rangeCount > 0) {
+ const range = selection.getRangeAt(0).cloneRange();
+ const rect = range.getBoundingClientRect();
+ if (
+ scroller.contains(range.startContainer) &&
+ rect.top >= box.top &&
+ rect.bottom <= box.bottom
+ ) {
+ anchor = { range, top: rect.top - box.top };
+ return;
+ }
+ }
+ // A point near the top captures text rather than the paragraph's bounding box.
+ const x = box.left + box.width / 2;
+ // The first point can land in paragraph spacing. Look only within the first few lines.
+ for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) {
+ const y = box.top + inset;
+ const position = document.caretPositionFromPoint?.(x, y);
+ const range = document.createRange();
+ if (position) {
+ range.setStart(position.offsetNode, position.offset);
+ } else {
+ const fallback = document.caretRangeFromPoint?.(x, y);
+ if (!fallback) continue;
+ range.setStart(fallback.startContainer, fallback.startOffset);
+ }
+ range.collapse(true);
+ if (
+ !scroller.contains(range.startContainer) ||
+ range.startContainer.nodeType !== Node.TEXT_NODE
+ )
+ continue;
+ const top = range.getBoundingClientRect().top - box.top;
+ if (top >= 0 && top < scroller.clientHeight) {
+ anchor = { range, top };
+ break;
+ }
+ }
+ };
+ const restore = () => {
+ if (
+ !enabled() ||
+ !anchor ||
+ anchor.range.startContainer.nodeType !== Node.TEXT_NODE ||
+ !scroller.contains(anchor.range.startContainer)
+ )
+ return;
+ const delta =
+ anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top;
+ if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;
+ };
+ const stop = observeResize(scroller, () => {
+ const nextWidth = scroller.clientWidth;
+ if (nextWidth === width) {
+ capture();
+ return;
+ }
+ width = nextWidth;
+ restore();
+ if (frame !== null) cancelAnimationFrame(frame);
+ // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then.
+ frame = requestAnimationFrame(() => {
+ restore();
+ frame = null;
+ capture();
+ });
+ });
+ scroller.addEventListener("scroll", capture, { passive: true });
+ scroller.addEventListener("input", capture);
+ const captureSelection = () => {
+ if (document.activeElement === scroller) capture();
+ };
+ if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection);
+ const interrupt = () => {
+ if (frame !== null) cancelAnimationFrame(frame);
+ frame = null;
+ anchor = null;
+ // Input wins over a pending resize correction; the next frame captures the reader's new place.
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ width = scroller.clientWidth;
+ capture();
+ });
+ };
+ scroller.addEventListener("wheel", interrupt, { passive: true });
+ scroller.addEventListener("touchmove", interrupt, { passive: true });
+ scroller.addEventListener("keydown", interrupt);
+ return () => {
+ stop();
+ if (frame !== null) cancelAnimationFrame(frame);
+ scroller.removeEventListener("scroll", capture);
+ scroller.removeEventListener("input", capture);
+ document.removeEventListener("selectionchange", captureSelection);
+ scroller.removeEventListener("wheel", interrupt);
+ scroller.removeEventListener("touchmove", interrupt);
+ scroller.removeEventListener("keydown", interrupt);
+ };
+}
diff --git a/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts
new file mode 100644
index 0000000000000..4526fcefa2210
--- /dev/null
+++ b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts
@@ -0,0 +1,95 @@
+///
+import { expect } from "e2e";
+
+import { test, WEB } from "./t3.ts";
+
+const text = Array.from(
+ { length: 70 },
+ (_, index) =>
+ `Sentence ${index + 1}. Opening a side panel should keep the sentence being read visible while the text wraps to the available width. `,
+).join("");
+
+test(
+ "Opening a side panel preserves the visible text in the conversation and draft",
+ WEB,
+ async ({ t3, app, screen, browser }) => {
+ const project = await t3.project("demo");
+ const thread = await t3.thread({
+ project,
+ title: "Reading position",
+ messages: ["Start"],
+ model: "multi-turn",
+ });
+ await browser.setViewport({ width: 1440, height: 1000 });
+ await t3.open(thread);
+ await screen.getByRole("button", "Toggle thread details panel").tap();
+ await screen.getByRole("textbox").fill(text);
+ await screen.getByRole("textbox").press("Enter");
+ await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
+ await screen.getByRole("button", "Show full message").tap();
+
+ const position = (draft: boolean, place: boolean) =>
+ browser.evaluate(
+ async ({ draft, place }) => {
+ const scroller = document.querySelector(
+ draft ? ".composer-tiptap" : ".messages-timeline-scroll",
+ )!;
+ const content = draft ? scroller : scroller.querySelector("[data-user-message-body]")!;
+ const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node && (node.textContent?.length ?? 0) < 3000) node = walker.nextNode();
+ if (!node) throw new Error("The long paragraph is not rendered");
+ const range = document.createRange();
+ range.setStart(node, 2500);
+ range.collapse(true);
+ if (place) {
+ scroller.blur();
+ scroller.scrollTop +=
+ range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48;
+ }
+ await new Promise((resolve) =>
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ ),
+ );
+ return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
+ },
+ { draft, place },
+ );
+
+ const point = await browser.evaluate(() => {
+ const box = document.querySelector(".messages-timeline-scroll")!.getBoundingClientRect();
+ return { x: box.left + box.width / 2, y: box.top + 150 };
+ });
+ await browser.mouse.move(point.x, point.y);
+ await browser.mouse.wheel(0, -800);
+ // The wheel's native scroll completes asynchronously before positioning the fixture text.
+ await browser.evaluate(
+ () =>
+ new Promise((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve(null))),
+ ),
+ );
+ let timelineBefore = await position(false, true);
+ if (Math.abs(timelineBefore - 48) > 2) timelineBefore = await position(false, true);
+ if (Math.abs(timelineBefore - 48) > 2)
+ throw new Error(`The conversation did not settle at the reading position: ${timelineBefore}`);
+ await app.screenshot("conversation-panel-closed");
+ await screen.getByRole("button", "Toggle right panel").tap();
+ const timelineAfter = await position(false, false);
+ await app.screenshot("conversation-panel-open");
+ await screen.getByRole("button", "Toggle right panel").tap();
+
+ await screen.getByRole("textbox").fill(text);
+ const draftBefore = await position(true, true);
+ if (Math.abs(draftBefore - 48) > 2)
+ throw new Error("The draft did not settle at the reading position");
+ await app.screenshot("draft-panel-closed");
+ await screen.getByRole("button", "Toggle right panel").tap();
+ const draftAfter = await position(true, false);
+ await app.screenshot("draft-panel-open");
+ expect(
+ Math.max(Math.abs(timelineAfter - timelineBefore), Math.abs(draftAfter - draftBefore)),
+ ).toBeLessThan(30);
+ },
+);