Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(chat): scroll a completed turn's prompt to the top

vastsac764d8ab75fe
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index 4d9d838ca..6c9410d12 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -45,6 +45,7 @@ import {
transcriptRevealOwnership,
} from "../../../../lib/transcript-reading-position";
import { useTranscriptReadingPosition, type RestoreTranscriptReading } from "../../../../hooks/use-transcript-reading-position";
+import { useTurnCompletionScroll } from "./useTurnCompletionScroll";
type UseTranscriptScrollOptions = {
sessionId: string | undefined;
@@ -477,6 +478,13 @@ export function useTranscriptScroll({
scrollToBottom,
]);
+ // A completed turn the reader followed ends at its prompt, not its last line.
+ useTurnCompletionScroll({
+ isRunning, paneVisible, readingWindow, messages, scrollRef, contentRef,
+ isFollowing: () => pinnedRef.current && !isDisclosureAnchorHeld(),
+ onAnchored: releaseFollow,
+ });
+
useLayoutEffect(() => {
scheduleFollowScroll();
}, [
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTurnCompletionScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTurnCompletionScroll.ts
new file mode 100644
index 000000000..8ecaf5a19
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTurnCompletionScroll.ts
@@ -0,0 +1,83 @@
+import { useEffect, useRef, type RefObject } from "react";
+import type { UiMessage } from "@pi-desktop/shared";
+import {
+ scrollTurnPromptIntoView,
+ settledTurn,
+} from "../../../../lib/turn-completion-scroll";
+
+type UseTurnCompletionScrollOptions = {
+ isRunning: boolean;
+ paneVisible: boolean;
+ readingWindow: boolean;
+ messages: UiMessage[];
+ scrollRef: RefObject<HTMLDivElement | null>;
+ contentRef: RefObject<HTMLDivElement | null>;
+ /** Whether the reader is still following the stream at the bottom. */
+ isFollowing: () => boolean;
+ /** Called after the view moved, to leave follow mode at the new position. */
+ onAnchored: () => void;
+};
+
+/**
+ * When a turn this pane watched completes while the reader is still following
+ * it, scroll its prompt to the top of the viewport (issue #1889). A reader who
+ * scrolled away, a failed or aborted turn, a hidden pane, and a reply short
+ * enough that its prompt is already in view all leave the view alone.
+ */
+export function useTurnCompletionScroll({
+ isRunning,
+ paneVisible,
+ readingWindow,
+ messages,
+ scrollRef,
+ contentRef,
+ isFollowing,
+ onAnchored,
+}: UseTurnCompletionScrollOptions) {
+ // Armed by a run this pane observed; spent by the first settled outcome.
+ const armedRef = useRef(false);
+ const frameRef = useRef(0);
+ const isRunningRef = useRef(isRunning);
+ isRunningRef.current = isRunning;
+ const isFollowingRef = useRef(isFollowing);
+ isFollowingRef.current = isFollowing;
+ const onAnchoredRef = useRef(onAnchored);
+ onAnchoredRef.current = onAnchored;
+
+ useEffect(() => {
+ if (!isRunning) return;
+ armedRef.current = true;
+ // A new run owns the view again; a queued completion move is stale.
+ cancelAnimationFrame(frameRef.current);
+ frameRef.current = 0;
+ }, [isRunning]);
+
+ useEffect(() => {
+ if (isRunning || !armedRef.current) return;
+ const turn = settledTurn(messages);
+ // The session stopped before the reply's final status arrived.
+ if (turn.kind === "pending") return;
+ armedRef.current = false;
+ if (turn.kind !== "complete" || !paneVisible || readingWindow) return;
+ if (!isFollowingRef.current()) return;
+ cancelAnimationFrame(frameRef.current);
+ // One frame lets the settled reply (action row, change summary) lay out
+ // before the prompt's position is measured.
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = 0;
+ const scroller = scrollRef.current;
+ const content = contentRef.current;
+ if (!scroller || !content) return;
+ // A queued follow-up may have started, or the reader scrolled meanwhile.
+ if (isRunningRef.current || !isFollowingRef.current()) return;
+ const behavior = window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ ? "auto"
+ : "smooth";
+ if (scrollTurnPromptIntoView(scroller, content, turn.userMessageId, behavior)) {
+ onAnchoredRef.current();
+ }
+ });
+ }, [contentRef, isRunning, messages, paneVisible, readingWindow, scrollRef]);
+
+ useEffect(() => () => cancelAnimationFrame(frameRef.current), []);
+}
diff --git a/apps/desktop/src/lib/turn-completion-scroll.ts b/apps/desktop/src/lib/turn-completion-scroll.ts
new file mode 100644
index 000000000..216cbad40
--- /dev/null
+++ b/apps/desktop/src/lib/turn-completion-scroll.ts
@@ -0,0 +1,98 @@
+import type { UiMessage } from "@pi-desktop/shared";
+
+/**
+ * Turn-completion reading position (issue #1889). A reader who followed a
+ * reply to its end is left at the bottom of a long answer and has to scroll
+ * back to where it began. When the turn completes, the prompt that started it
+ * moves to the top of the viewport so the answer reads from its start.
+ */
+
+/**
+ * Gap kept above the prompt row, below the content's own top padding: that
+ * padding reserves the titlebar band the conversation top bar overlays, so a
+ * prompt aligned to the bare scroller edge would sit under the bar.
+ */
+export const TURN_COMPLETION_TOP_INSET_PX = 16;
+
+export type SettledTurn =
+ /** The reply is still streaming its final message. */
+ | { kind: "pending" }
+ /** The reply completed; `userMessageId` is the prompt row to show. */
+ | { kind: "complete"; userMessageId: string }
+ /** Failed, aborted, or no prompt/reply pair: leave the view alone. */
+ | { kind: "none" };
+
+/** Classify the newest turn once the session reports it is no longer running. */
+export function settledTurn(messages: readonly UiMessage[]): SettledTurn {
+ let userIndex = -1;
+ for (let index = messages.length - 1; index >= 0; index--) {
+ if (messages[index]?.role === "user") {
+ userIndex = index;
+ break;
+ }
+ }
+ if (userIndex < 0) return { kind: "none" };
+ let reply: UiMessage | undefined;
+ for (let index = messages.length - 1; index > userIndex; index--) {
+ if (messages[index]?.role === "assistant") {
+ reply = messages[index];
+ break;
+ }
+ }
+ if (!reply) return { kind: "none" };
+ if (reply.status === "streaming") return { kind: "pending" };
+ if (reply.status === "error" || reply.status === "aborted") return { kind: "none" };
+ return { kind: "complete", userMessageId: messages[userIndex]!.id };
+}
+
+/**
+ * Scroll offset that puts a row's top `inset` pixels below the viewport top,
+ * or `null` when the row's top is already in view (a short reply needs no
+ * move) or the geometry is unusable.
+ */
+export function turnAnchorScrollTop({
+ rowTop,
+ viewportTop,
+ scrollTop,
+ maxScrollTop,
+ inset = TURN_COMPLETION_TOP_INSET_PX,
+}: {
+ rowTop: number;
+ viewportTop: number;
+ scrollTop: number;
+ maxScrollTop: number;
+ inset?: number;
+}): number | null {
+ const offset = rowTop - viewportTop;
+ if (![offset, scrollTop, maxScrollTop].every(Number.isFinite)) return null;
+ if (offset >= inset) return null;
+ const target = Math.min(maxScrollTop, Math.max(0, scrollTop + offset - inset));
+ return target < scrollTop ? target : null;
+}
+
+/**
+ * Move `scroller` so the prompt row `userMessageId` sits at the top. Returns
+ * whether it scrolled.
+ */
+export function scrollTurnPromptIntoView(
+ scroller: HTMLElement,
+ content: HTMLElement,
+ userMessageId: string,
+ behavior: ScrollBehavior,
+): boolean {
+ const row = content.querySelector<HTMLElement>(
+ `[data-message-id="${CSS.escape(userMessageId)}"]`,
+ );
+ if (!row) return false;
+ const reserve = Number.parseFloat(getComputedStyle(content).paddingTop) || 0;
+ const top = turnAnchorScrollTop({
+ rowTop: row.getBoundingClientRect().top,
+ viewportTop: scroller.getBoundingClientRect().top,
+ scrollTop: scroller.scrollTop,
+ maxScrollTop: scroller.scrollHeight - scroller.clientHeight,
+ inset: reserve + TURN_COMPLETION_TOP_INSET_PX,
+ });
+ if (top === null) return false;
+ scroller.scrollTo({ top, behavior });
+ return true;
+}
diff --git a/apps/desktop/test/turn-completion-scroll.test.mjs b/apps/desktop/test/turn-completion-scroll.test.mjs
new file mode 100644
index 000000000..947e79aa1
--- /dev/null
+++ b/apps/desktop/test/turn-completion-scroll.test.mjs
@@ -0,0 +1,70 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ settledTurn,
+ TURN_COMPLETION_TOP_INSET_PX,
+ turnAnchorScrollTop,
+} from "../src/lib/turn-completion-scroll.ts";
+
+const createdAt = "2026-10-28T00:00:00.000Z";
+const user = (id) => ({ id, role: "user", content: id, createdAt });
+const reply = (id, status) => ({ id, role: "assistant", content: id, createdAt, status });
+const tool = (id) => ({ id, role: "tool", content: id, createdAt, toolStatus: "success" });
+
+test("a completed reply anchors on the prompt that started its turn", () => {
+ assert.deepEqual(
+ settledTurn([user("u1"), reply("a1", "complete"), user("u2"), tool("t1"), reply("a2", "complete")]),
+ { kind: "complete", userMessageId: "u2" },
+ );
+});
+
+test("a reply still streaming its final status is pending", () => {
+ assert.deepEqual(settledTurn([user("u1"), reply("a1", "streaming")]), { kind: "pending" });
+});
+
+test("failed, aborted, and reply-less turns are left alone", () => {
+ assert.deepEqual(settledTurn([user("u1"), reply("a1", "error")]), { kind: "none" });
+ assert.deepEqual(settledTurn([user("u1"), reply("a1", "aborted")]), { kind: "none" });
+ assert.deepEqual(settledTurn([user("u1"), tool("t1")]), { kind: "none" });
+ assert.deepEqual(settledTurn([reply("a0", "complete")]), { kind: "none" });
+ assert.deepEqual(settledTurn([]), { kind: "none" });
+});
+
+test("an earlier reply does not stand in for the newest prompt's missing one", () => {
+ assert.deepEqual(settledTurn([user("u1"), reply("a1", "complete"), user("u2")]), { kind: "none" });
+});
+
+test("the prompt moves to the top inset when it is above the viewport", () => {
+ assert.equal(
+ turnAnchorScrollTop({ rowTop: -1_900, viewportTop: 10, scrollTop: 2_000, maxScrollTop: 2_000 }),
+ 2_000 - 1_910 - TURN_COMPLETION_TOP_INSET_PX,
+ );
+});
+
+test("a prompt already in view needs no move", () => {
+ assert.equal(
+ turnAnchorScrollTop({ rowTop: 40, viewportTop: 10, scrollTop: 2_000, maxScrollTop: 2_000 }),
+ null,
+ );
+});
+
+test("a prompt tucked under the top inset is lifted clear of it", () => {
+ assert.equal(
+ turnAnchorScrollTop({ rowTop: 30, viewportTop: 10, scrollTop: 2_000, maxScrollTop: 2_000, inset: 62 }),
+ 2_000 + 20 - 62,
+ );
+});
+
+test("the target is clamped to the scroll range", () => {
+ assert.equal(
+ turnAnchorScrollTop({ rowTop: -500, viewportTop: 0, scrollTop: 100, maxScrollTop: 2_000 }),
+ 0,
+ );
+});
+
+test("unusable geometry is never acted on", () => {
+ assert.equal(
+ turnAnchorScrollTop({ rowTop: Number.NaN, viewportTop: 0, scrollTop: 100, maxScrollTop: 200 }),
+ null,
+ );
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index e7de9d362..87a2a0794 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -998,7 +998,7 @@ pending action cards remain reachable outside a hidden process. See
| Turn outcome | After a failed turn, a session-scoped recovery card summarizes the interruption and tool evidence. Completed turns use the existing transcript and message-scoped review rows without an extra success card; a completed turn that wrote workspace files also shows the per-turn changed-files summary below (D674). Failed turns can continue through one localized prompt without losing the transcript. |
| Session switch | A first-opened session paints at its latest record; a revisited pane paints at its own retained position. Bounded first commit and full-history expansion show the same position: no post-paint height correction may shift the visible rows, in either direction |
| Turn start (send / retry / regenerate) | Re-pins and positions the latest content before paint, even if the user had scrolled up; the later persisted user-message event does not flash the transcript at its top, and the composer collapse / indicator layout clamps during the send never release follow mode |
-| Idle (after stream) | Auto-scroll unlocked; user can scroll freely |
+| Idle (after stream) | Auto-scroll unlocked; user can scroll freely. A completed turn the user was following ends with its prompt at the top of the viewport and jump-to-latest shown, unless the prompt was already in view (D676) |
| Message-scoped review snapshot | Each successful workspace Write/Edit renders as one tool-level review row (`ReviewChangeCard`) carrying that message's added/modified/deleted status and explicit addition/deletion totals. The row itself is the file header — Git-style status letter (`A`/`M`/`D`), path, addition/deletion counts, disclosure caret — with no separate generic tool row above it, so the file header appears exactly once. It keeps the tool-row rhythm with no card border, status rail, icon plate, or status pill; hover fill is the only row chrome, and a rolled-back change is struck through. Its hunks sit in the diff body directly beneath that header behind the row's expandable disclosure: every review row (inline and in the Review tab) is collapsed by default, and the user expands it on demand. The diff body's action row keeps hash-guarded rollback and adds Copy for the hunks. The card remains after a Git commit, never becomes a bottom/global entry, and does not leak into another session's transcript. |
| Per-turn changed files | A completed reply (same mount condition as the reply plugin slots, so never while streaming and never after a failed turn) whose turn recorded at least one workspace review change shows one read-only `TurnChangesCard` below its answer and above `entryExtra` blocks (D674). It is built only from that turn's message-owned review records: one row per path in first-touched order, counts summed across edits, status `D` when the turn ends by deleting the file, else `A` if any edit created it, else `M`; a file whose every edit was rolled back stays listed, struck through, with the state in its accessible name. The header shows `Changes this turn`, the file count, and the summed `+`/`−`. Up to four files use relaxed 25px rows; more switch to dense 21px rows and add the directory count; rows past 12 fold into `+N more` plus a link that opens Review. The card is one `--ds-tile` surface with no border or rules. Clicking a row opens the originating session's Review tab, scrolls to that file's first recorded change, and expands its changes there — the card has no diff body or rollback of its own. A turn without workspace writes renders nothing. |
@@ -1648,6 +1648,7 @@ storage but compose into one assistant turn until the next user message.
| Session transition | A warm destination pane is revealed immediately with its retained content and position. If it is running or still holds a not-yet-flushed completed reply, its live renderer snapshot survives the durable revalidation read. A cold destination leaves the visible pane on its own session under a thin progress track until it commits; nothing is dimmed, hidden panes stay mounted and inert, and current stream updates are not deferred |
| Streaming | New tokens append; auto-scroll only while pinned to bottom |
| Turn start | Send / retry / regenerate re-pins follow mode and jumps to bottom |
+| Turn completion | A completed turn the user followed scrolls its prompt to the top and releases follow mode; failed, aborted, short, and manually scrolled turns keep their position (D676) |
| Thinking-only streaming | Transcript opens; the latest thinking disclosure opens unless the user has taken it over; no empty answer bubble; the tail status continues to identify the running turn |
| Running fallback | Compact animated-dot Working row throughout the running turn when no specific runtime phase or planning state is known, including pauses after partial output or completed tools |
| Running planning | Compact animated-dot Planning / Goal row in that same slot throughout the planning turn; a runtime phase takes precedence, and pending user interaction or turn completion hides it. The Composer mode chip pulses |
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index ea7245bff..8efa300a4 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -775,7 +775,13 @@ may be retained while exactly one workspace supplies the visible shell context.
- "Scroll to bottom" floating button appears as soon as manual upward scrolling
releases follow mode
- Click "Scroll to bottom" button: resumes auto-scroll and snaps to bottom
-- Stream completion: if user was auto-scrolling, keep at bottom; if manual, stay at position
+- Stream completion (D676): if the user was following a turn that completes,
+ its prompt scrolls to 16px below the titlebar band at the top of the
+ viewport so the answer
+ reads from its start, follow mode is released, and jump-to-latest appears.
+ The view does not move when the prompt is already in view, the turn failed
+ or was aborted, the pane is hidden, or a queued follow-up starts at once. If
+ the user had scrolled manually, the view stays at their position
- An asynchronously completed diagram height update follows the same rule:
ResizeObserver keeps a pinned transcript at the bottom, while a user who has
scrolled upward remains at their reading position.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 81ede2370..17653bef0 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4953,6 +4953,26 @@ window; opening a normal panel afterward must still work.
- **Milestone**: M5
- **Status**: Unit-covered (`turn-changes-card.test.mjs`); full UI scenario Draft
+#### E2E-CHAT-completed-turn-scrolls-to-prompt: A finished reply reads from its prompt
+
+- **Preconditions**: An Agent session whose next reply is longer than the
+ transcript viewport.
+- **Steps**: 1) Send a prompt and let the transcript follow the reply to its
+ end. 2) Send a prompt with a reply short enough to fit on screen. 3) Send a
+ long prompt again and scroll up while it streams. 4) Stop a long reply
+ midway. 5) Queue a follow-up while a long reply streams.
+- **Expected**: 1) When the reply completes, its prompt sits at the top of the
+ viewport and jump-to-latest appears. 2) The short reply stays at the bottom
+ in follow mode. 3) The view stays where the user scrolled. 4) The aborted
+ turn stays at the bottom. 5) The follow-up turn keeps following at the
+ bottom.
+- **Specs linked**: `04-ux/09-interaction-patterns.md` §2.2,
+ `04-ux/08-component-spec.md` §4.4, D676
+- **Acceptance**: Quality
+- **Milestone**: M5
+- **Status**: Automated (`pnpm test:e2e:transcript-turn-completion`, real
+ `useTranscriptScroll` in Electron; `turn-completion-scroll.test.mjs`)
+
#### E2E-058: Built-in interactive terminal is absent
- **Preconditions**: A workspace is open and the Agent has completed a Bash
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 349cd79b2..7a06b9d01 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -337,6 +337,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.
| D671 | Inline generative UI visualizations | **Amend D114: local sessions get a second host-owned contained root `<data_dir>/visualizations/<sessionId>/` for `.html` fragments only (Read/Write/Edit, auto-allowed like scratch, never in remote or contract sessions). A standalone `::visualize{"path","title"}` reply line renders the fragment inline through a sandboxed `pi-genui://session/<sid>/<file>` iframe (`sandbox="allow-scripts"`, strict CSP, no network). Builtin skill `pi-desktop/visualize`. No schema change.** | Interactive explanations need an embedded page; ADR gen-ui-inline-visualization. |
| D674 | Per-turn changed-files summary under a finished reply | **A completed reply whose turn recorded workspace review changes renders one read-only `TurnChangesCard` below its answer and above `entryExtra`, built only from that turn's message-owned `details.review` records (no new capture, IPC, or persistence). Rows merge edits per path (`D` if the turn ends by deleting, else `A` if any edit created the file, else `M`; counts summed; rolled-back files stay listed and struck through). Up to four files use relaxed rows, more use dense rows, and rows past 12 fold into `+N more`. Clicking a row opens Review on that file's recorded changes; the per-call review rows and the Review tab are unchanged.** | Issue #1891, design 10 (adaptive density): the per-call review rows answer "what did this call change", and Review answers it for the whole session, but nothing answered "what did this turn change" without counting rows. |
| D675 | Inline images are admitted by pixel size as well as bytes | **Amend D361: an image whose PNG/JPEG/GIF/WebP header reports a longest edge above `MAX_INLINE_IMAGE_EDGE_PX` (8000) is never inlined. Host Read refuses it with `TOOL_FAILED`; prompt attachments and restored history take the existing `@path` fallback; and the runtime's last provider view replaces any such image block (user or tool result) with a text notice naming its size. The probe reads headers only (no decoder); unknown dimensions keep the byte-only rule. No protocol, schema, or persisted-format change.** | Issue #1913: a 1.89 MB, 780 x 14182 full-page screenshot passed every byte check, the provider rejected it with a non-retriable 400, and replay made every later request in that session fail. Dropping is deterministic for the same bytes, so the request prefix and prompt caching stay stable; resampling would need an image decoder and is deferred. |
+| D676 | A completed turn the reader followed ends at its prompt | **Amend the stream-completion rule: when a turn completes while the transcript is visible and still following the stream, the renderer scrolls that turn's newest user message to 16px below the titlebar band the transcript reserves at its top (smooth unless reduced motion), releases follow mode, and shows jump-to-latest. Nothing moves when the prompt is already in view, the reply failed or was aborted, the pane is hidden or in a reading window, a disclosure position is held, or a new run starts before the move. Renderer only; no setting, IPC, or persistence change.** | Issue #1889: after a long reply the reader sat at its last line and had to scroll back up to find where it began. |
## M0. Model catalog decisions
@@ -8040,3 +8041,19 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
`packages/agent-runtime/src/attachment-history.test.ts`,
`apps/desktop/test/prompt-inline-attachments.test.mjs`, and host-core
`tools::image_dimensions` / `read_refuses_images_past_the_pixel_limit` tests.
+
+## 2026-10-28 — Completed turns end at their prompt (D676)
+
+- D676 replaces "stream completion keeps a following reader at the bottom":
+ when a followed turn completes, its prompt scrolls to the top of the
+ viewport and jump-to-latest appears (issue #1889). A reader who scrolled
+ away keeps their position.
+- The move waits for the reply's final status, runs one frame after the
+ settled reply lays out, and is skipped for failed or aborted turns, a prompt
+ already in view, a hidden pane or reading window, a held disclosure
+ position, and a queued follow-up that starts first.
+- Logic lives in `apps/desktop/src/lib/turn-completion-scroll.ts` and the
+ `useTurnCompletionScroll` hook beside `useTranscriptScroll`. Covered by
+ `apps/desktop/test/turn-completion-scroll.test.mjs` and
+ `pnpm test:e2e:transcript-turn-completion`
+ (E2E-CHAT-completed-turn-scrolls-to-prompt).
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 65939fcfa..7a4a45ade 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -641,7 +641,7 @@ expanded/collapsed 侧边栏仍为 20px/18px 且启动画面为 64 像素。
| 回合结果 | 回合失败后,会话范围的恢复卡会总结中断和工具证据。已完成的轮次使用现有的记录和消息范围的审核行,无需额外的成功卡;写过工作区文件的已完成回合还会在下方显示按轮文件变更汇总(D674)。失败的回合可以重试而不会丢失转录本。 |
| 会话切换 | 首次打开的会话在它最新的记录处绘制;重新访问的面板在它自己保留的位置处绘制。有界的首次提交与全量历史展开显示同一个位置:绘制之后的高度校正不得在任何方向上移动可见行 |
| 启动(发送/重试/重新生成) | 即使用户向上滚动,在绘制之前重新固定和定位最新内容;后来保留的用户消息事件不会在其顶部闪烁记录,并且发送期间的输入框折叠/指示器布局夹紧永远不会释放跟随模式 |
-| 空闲(流后) | 自动滚动解锁;用户可以自由滚动 |
+| 空闲(流后) | 自动滚动解锁;用户可以自由滚动。用户一直跟随的回合完成后,其提示停在视口顶部并显示“滚动到底部”,除非提示本来就在视野内(D676) |
| 消息范围的审核快照 | 每个成功的工作区 Write/Edit 渲染为一条工具级审核行(`ReviewChangeCard`),其中包含该消息的 added/modified/deleted 状态和显式 addition/deletion 总计。该行本身就是文件标题——Git 风格状态字母(`A`/`M`/`D`)、路径、增删计数、披露 caret——上方不再渲染通用工具行,因此文件标题只出现一次。它沿用工具行的节奏,没有卡片边框、状态竖线、图标底板或状态药丸;悬停填充是唯一的行装饰,已回滚的更改显示删除线。hunks 位于标题正下方的 diff 正文中,由该行自身的披露控制:默认情况下,每条审核行(转录内与“审核”选项卡)都收起,用户按需展开。diff 正文的操作行保留哈希保护的回滚,并新增复制 hunks 的 Copy。该卡在 Git 提交后保留,永远不会成为 bottom/global 条目,也不会泄漏到另一个会话的转录中。 |
| 按轮文件变更 | 已完成的回复(与回复插件槽相同的挂载条件,因此流式期间和失败回合都不显示)若其回合记录了至少一条工作区审核变更,就在回答下方、`entryExtra` 块上方显示一张只读的 `TurnChangesCard`(D674)。它只由该回合消息拥有的审核记录构建:每个路径一行,按首次改动顺序排列,计数在多次编辑间累加;回合以删除该文件结束时状态为 `D`,否则只要有一次创建即为 `A`,其余为 `M`;所有编辑都已回滚的文件仍保留在列表中,显示删除线,并在可访问名称中带上该状态。标题显示 `本轮改动`、文件数和合计 `+`/`−`。不超过四个文件时用 25px 宽松行;更多时切换为 21px 密集行并补充目录数;超过 12 行的部分折叠为 `+N more`,并提供打开审阅的链接。卡片是一个 `--ds-tile` 平面,没有边框或分割线。点击一行会打开来源会话的审阅选项卡,滚动到该文件的第一条记录并展开其变更——卡片本身没有 diff 正文,也不提供回滚。没有工作区写入的回合不渲染任何内容。 |
@@ -1151,6 +1151,7 @@ SESSIONS [msg+][↕]
| 会话转换 | 热目标面板立即以其保留的内容和位置被揭示。若它仍在运行或仍持有尚未刷入的已完成回复,其实时渲染器快照在持久化再验证中保留。冷目标让可见面板在一条细进度轨道下停留在它自己的会话上,直到目标提交;没有任何内容被调暗,隐藏的面板保持挂载且惰性,当前流更新不会延迟 |
| 流媒体 | 追加新令牌;仅在固定到底部时自动滚动 |
| 回合开始 | 发送/重试/重新生成重新固定跟随模式并跳转到底部 |
+| 回合完成 | 用户跟随的已完成回合把提示滚动到顶部并退出跟随模式;失败、中止、较短以及手动滚动过的回合保持原位(D676) |
| 仅思考流式输出 | 转录打开;最新思考披露展开,除非用户已接管;没有空回答气泡,底部状态继续标明回合仍在运行 |
| 运行中兜底 | 未知具体运行时阶段且不在规划状态时,整轮显示带跳动圆点的紧凑 Working 行,包括部分输出暂停和工具完成后的空档 |
| 运行中规划 | 整轮在同一位置显示带跳动圆点的紧凑规划/目标行,具体运行时阶段优先;等待用户操作或回合结束时隐藏。Composer 模式芯片脉冲 |
diff --git a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
index 69b290e77..f587f6ef3 100644
--- a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
+++ b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
@@ -567,7 +567,10 @@
- 手动向上滚动时立即出现“滚动到底部”浮动按钮
释放跟随模式
- 单击“滚动到底部”按钮:恢复自动滚动并捕捉到底部
-- 流完成:如果用户自动滚动,则保持在底部;如果是手动,则停留在该位置
+- 流完成(D676):如果用户一直在跟随一个完成的回合,该回合的提示会滚动到视口
+ 顶部(标题栏带下方 16px),让回答从开头读起,同时退出跟随模式并显示“滚动到底部”。
+ 提示已在视野内、回合失败或被中止、面板隐藏、或排队的后续提示立即开始时,视图
+ 不动。如果用户手动滚动过,则停留在该位置
- 异步完成的图表高度更新遵循相同的规则:
ResizeObserver 在底部保留固定的记录,而拥有
向上滚动保持在其阅读位置。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 943c5867f..d2115f62b 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -2528,6 +2528,22 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的
- **里程碑**:M5
- **状态**:单元覆盖(`turn-changes-card.test.mjs`);完整的 UI 场景草稿
+#### E2E-CHAT-completed-turn-scrolls-to-prompt:完成的回复从它的提示读起
+
+- **先决条件**:一个 Agent 会话,其下一条回复比转录视口更长。
+- **步骤**:1) 发送提示,让转录跟随回复直到结束。2) 发送一个回复短到能在屏幕内
+ 放下的提示。3) 再发送一个长回复的提示,并在流式期间向上滚动。4) 在长回复中途
+ 停止。5) 在长回复流式期间排队一个后续提示。
+- **预期**:1) 回复完成时,它的提示位于视口顶部并出现“滚动到底部”。2) 短回复
+ 停留在底部并保持跟随。3) 视图停留在用户滚动到的位置。4) 被中止的回合停在底部。
+ 5) 后续回合继续在底部跟随。
+- **链接规格**:`04-ux/09-interaction-patterns.md` §2.2,
+ `04-ux/08-component-spec.md` §4.4,D676
+- **验收**:质量
+- **里程碑**:M5
+- **状态**:已自动化(`pnpm test:e2e:transcript-turn-completion`,在 Electron 中
+ 运行真实的 `useTranscriptScroll`;`turn-completion-scroll.test.mjs`)
+
#### E2E-058:内置交互式终端已移除
- **前提**:已打开工作区,Agent 已完成一次 Bash 工具调用。
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index cbacd7afe..9eb208044 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -340,6 +340,7 @@
| D671 | 对话内联生成式 UI 可视化 | **修订 D114:本地会话新增第二个由宿主拥有的受控根目录 `<data_dir>/visualizations/<sessionId>/`,仅用于 `.html` 片段(Read/Write/Edit,与 scratch 一样免确认,远程会话和合约会话中不提供)。回复中单独一行 `::visualize{"path","title"}` 会通过沙箱化的 `pi-genui://session/<sid>/<file>` iframe(`sandbox="allow-scripts"`、严格 CSP、无网络)内联渲染该片段。内置 skill `pi-desktop/visualize`。不改变 schema。** | 交互式讲解需要内嵌页面;见 ADR gen-ui-inline-visualization。 |
| D674 | 已完成回复下方的按轮文件变更汇总 | **回合记录了工作区审核变更的已完成回复,会在回答下方、`entryExtra` 上方渲染一张只读的 `TurnChangesCard`,只由该回合消息拥有的 `details.review` 记录构建(不新增采集、IPC 或持久化)。按路径合并多次编辑(回合以删除结束为 `D`,否则有创建即为 `A`,其余为 `M`;计数累加;已回滚文件保留并显示删除线)。不超过四个文件用宽松行,更多用密集行,超过 12 行折叠为 `+N more`。点击一行会在审阅中打开该文件的记录变更;逐次调用的审核行和审阅选项卡保持不变。** | Issue #1891,设计 10(自适应密度):逐次调用的审核行回答“这次调用改了什么”,审阅回答整个会话的问题,但回答“这一轮改了什么”仍需自己数工具行。 |
| D675 | 内联图片同时按像素尺寸与字节准入 | **修订 D361:PNG/JPEG/GIF/WebP 文件头显示最长边超过 `MAX_INLINE_IMAGE_EDGE_PX`(8000)的图片永不内联。Host Read 以 `TOOL_FAILED` 拒绝;提示附件与恢复的历史走既有的 `@path` 回退;运行时在最后的提供商视图中把这类图片块(用户或工具结果)替换为写明尺寸的文本说明。探测只读文件头(无解码器);读不出尺寸时保留仅按字节的规则。不改变协议、schema 或持久化格式。** | Issue #1913:一张 1.89 MB、780 x 14182 的整页截图通过了所有字节检查,提供商以不可重试的 400 拒绝,重放使该会话此后每个请求都失败。同样的字节总是被同样地丢弃,请求前缀与提示缓存保持稳定;重采样需要图像解码器,留待以后。 |
+| D676 | 读者跟随的已完成回合停在它的提示处 | **修订流完成规则:转录可见且仍在跟随流时回合完成,渲染层会把该回合最新的用户消息滚动到转录顶部预留的标题栏带下方 16px 处(除非减少动态效果,否则平滑滚动),退出跟随模式并显示“滚动到底部”。提示已在视野内、回复失败或被中止、面板隐藏或处于阅读窗口、披露位置被保持、或在移动前开始了新的运行时,都不移动。仅渲染层;不新增设置,不改变 IPC 或持久化。** | Issue #1889:长回复结束后读者停在最后一行,得自己往上滑才能找到回答的开头。 |
## M0. 模型目录决策
@@ -5605,3 +5606,16 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
`packages/agent-runtime/src/attachment-history.test.ts`、
`apps/desktop/test/prompt-inline-attachments.test.mjs` 以及 host-core 的
`tools::image_dimensions` / `read_refuses_images_past_the_pixel_limit` 测试覆盖。
+
+## 2026-10-28 — 已完成回合停在它的提示处(D676)
+
+- D676 取代“流完成时保持跟随的读者在底部”:被跟随的回合完成时,它的提示滚动到
+ 视口顶部并出现“滚动到底部”(issue #1889)。滚动离开的读者保持原位。
+- 移动会等待回复的最终状态,在完成后的回复布局好之后再等一帧执行;回合失败或被
+ 中止、提示已在视野内、面板隐藏或处于阅读窗口、披露位置被保持、以及排队的后续
+ 提示先开始时都会跳过。
+- 逻辑位于 `apps/desktop/src/lib/turn-completion-scroll.ts` 以及
+ `useTranscriptScroll` 旁的 `useTurnCompletionScroll` hook。由
+ `apps/desktop/test/turn-completion-scroll.test.mjs` 与
+ `pnpm test:e2e:transcript-turn-completion`
+ (E2E-CHAT-completed-turn-scrolls-to-prompt)覆盖。
diff --git a/package.json b/package.json
index a71c99c32..babea917c 100644
--- a/package.json
+++ b/package.json
@@ -48,6 +48,7 @@
"test:e2e:copy-tex": "node scripts/e2e-copy-tex.mjs",
"test:e2e:radial-menu": "node scripts/e2e-radial-menu.mjs",
"test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",
+ "test:e2e:transcript-turn-completion": "node scripts/e2e-transcript-turn-completion.mjs",
"test:e2e:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs && node scripts/e2e-image-chat.mjs",
"test:e2e:provider-client-certificate": "node --test scripts/e2e/wait-for-child-exit.test.mjs && node scripts/e2e-provider-client-certificate.mjs",
"test:e2e:provider-order": "node scripts/e2e-provider-order.mjs",
diff --git a/scripts/e2e-transcript-turn-completion.mjs b/scripts/e2e-transcript-turn-completion.mjs
new file mode 100644
index 000000000..0d984e8bd
--- /dev/null
+++ b/scripts/e2e-transcript-turn-completion.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+/**
+ * Real React/Chromium regression for issue #1889: when a turn the reader
+ * followed completes, its prompt moves to the top of the viewport so the
+ * answer reads from its start. A short reply, a reader who scrolled away, an
+ * aborted turn, and a follow-up that starts at once all keep their position.
+ *
+ * The fixture mounts the real `useTranscriptScroll` in a real 600 CSS px
+ * scroller; rows are plain blocks with the product's `data-message-id`.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(
+ join(root, "packages/agent-runtime/package.json"),
+);
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(tmpdir(), "pi-transcript-turn-completion-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/transcript-turn-completion.tsx")],
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "iife",
+ jsx: "automatic",
+ define: {
+ "process.env.NODE_ENV": '"production"',
+ "import.meta.env": '{"DEV":false,"MODE":"production"}',
+ },
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(
+ join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><title>Transcript turn completion regression</title><script src="renderer.js"></script>',
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({
+ show: false,
+ webPreferences: {
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ // A hidden window still has to deliver ResizeObserver callbacks and
+ // animation frames, because that is what the product scroll logic uses.
+ backgroundThrottling: false,
+ },
+ });
+ window.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ const result = await window.webContents.executeJavaScript("globalThis.transcriptTurnCompletionProbe()");
+ console.log("TRANSCRIPT_TURN_COMPLETION_PROBE " + JSON.stringify(result));
+ app.quit();
+ } catch (error) {
+ console.error("TRANSCRIPT_TURN_COMPLETION_PROBE " + JSON.stringify({ ok: false, error: String(error) }));
+ app.exit(1);
+ }
+});
+`,
+ );
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr])
+ stream.on("data", (data) => {
+ output += data;
+ });
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 60_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+ const line = output
+ .split(/\r?\n/)
+ .find((line) => line.startsWith("TRANSCRIPT_TURN_COMPLETION_PROBE "));
+ assert(
+ line,
+ `renderer returned no probe result (exit=${code}): ${output.slice(-2000)}`,
+ );
+ const result = JSON.parse(line.slice("TRANSCRIPT_TURN_COMPLETION_PROBE ".length));
+ console.log("TRANSCRIPT_TURN_COMPLETION_PROBE " + JSON.stringify(result));
+ assert.equal(code, 0, output.slice(-6000));
+ assert.equal(result.ok, true);
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/transcript-turn-completion.tsx b/scripts/e2e/transcript-turn-completion.tsx
new file mode 100644
index 000000000..074c917f4
--- /dev/null
+++ b/scripts/e2e/transcript-turn-completion.tsx
@@ -0,0 +1,230 @@
+import { createRoot, type Root } from "react-dom/client";
+import { flushSync } from "react-dom";
+import type { UiMessage } from "@pi-desktop/shared";
+import { useTranscriptScroll } from "../../apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll";
+import { TURN_COMPLETION_TOP_INSET_PX } from "../../apps/desktop/src/lib/turn-completion-scroll";
+
+declare global {
+ var transcriptTurnCompletionProbe: () => Promise<unknown>;
+}
+
+function assert(value: unknown, message: string): asserts value {
+ if (!value) throw new Error(message);
+}
+
+const createdAt = "2026-10-28T00:00:00.000Z";
+const TOOLBAR_BAND_PX = 46;
+
+function message(
+ id: string,
+ role: UiMessage["role"],
+ content: string,
+ extra: Partial<UiMessage> = {},
+): UiMessage {
+ return { id, role, content, createdAt, ...extra };
+}
+
+/** A finished earlier turn, then the prompt and reply this scenario drives. */
+function turn(replyLines: number, status: UiMessage["status"]): UiMessage[] {
+ return [
+ message("old-user", "user", "earlier question"),
+ message("old-reply", "assistant", "earlier answer", { status: "complete" }),
+ message("prompt", "user", "summarize the change"),
+ message(
+ "reply",
+ "assistant",
+ Array.from({ length: replyLines }, (_value, index) => `line ${index}`).join("\n"),
+ { status },
+ ),
+ ];
+}
+
+/**
+ * The real transcript scroll hook in a real 600 CSS px scroller. Rows are
+ * plain blocks carrying the same `data-message-id` the product rows carry, so
+ * geometry comes from inline heights, not the app stylesheet.
+ */
+function Fixture({ messages, isRunning }: { messages: UiMessage[]; isRunning: boolean }) {
+ const { scrollRef, wrapRef, contentRef, handleScroll, showJump } = useTranscriptScroll({
+ sessionId: undefined,
+ messages,
+ hasMoreBefore: false,
+ isRunning,
+ askPending: false,
+ approvalPending: false,
+ paneVisible: true,
+ searchTarget: null,
+ readingWindow: false,
+ });
+ return (
+ <div ref={wrapRef} style={{ height: "100%", position: "relative" }}>
+ <div
+ ref={scrollRef}
+ className="thread-scroll"
+ data-scroll-owner="transcript"
+ onScroll={handleScroll}
+ style={{ height: "100%", overflowY: "auto", overflowAnchor: "none" }}
+ >
+ {/* The product reserves the 46px titlebar band the same way. */}
+ <div ref={contentRef} className="thread-content" style={{ paddingTop: TOOLBAR_BAND_PX }}>
+ {messages.map((row) => (
+ <div
+ key={row.id}
+ data-message-id={row.id}
+ style={{
+ whiteSpace: "pre",
+ lineHeight: "20px",
+ minHeight: row.role === "user" ? 48 : 20,
+ margin: "0 0 12px",
+ }}
+ >
+ {row.content}
+ </div>
+ ))}
+ </div>
+ </div>
+ {showJump ? <div data-jump-to-latest /> : null}
+ </div>
+ );
+}
+
+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+/** Wait until the scroll offset holds still for several frames (smooth scroll included). */
+async function settle(scroller: HTMLElement): Promise<void> {
+ let last = Number.NaN;
+ let still = 0;
+ for (let index = 0; index < 240 && still < 6; index++) {
+ await frame();
+ still = scroller.scrollTop === last ? still + 1 : 0;
+ last = scroller.scrollTop;
+ }
+}
+
+type Scenario = {
+ root: Root;
+ container: HTMLElement;
+ scroller: HTMLElement;
+ render: (messages: UiMessage[], isRunning: boolean) => void;
+};
+
+function mount(host: HTMLElement): Scenario {
+ const container = document.createElement("div");
+ container.style.height = "600px";
+ container.style.width = "640px";
+ host.append(container);
+ const root = createRoot(container);
+ const render = (messages: UiMessage[], isRunning: boolean) =>
+ flushSync(() => root.render(<Fixture messages={messages} isRunning={isRunning} />));
+ render(turn(1, "streaming").slice(0, 3), false);
+ const scroller = container.querySelector<HTMLElement>(".thread-scroll");
+ assert(scroller, "fixture did not render a scroller");
+ return { root, container, scroller, render };
+}
+
+function promptTop(scenario: Scenario): number {
+ const row = scenario.container.querySelector<HTMLElement>('[data-message-id="prompt"]');
+ assert(row, "prompt row missing");
+ return row.getBoundingClientRect().top - scenario.scroller.getBoundingClientRect().top;
+}
+
+function distanceFromBottom(scroller: HTMLElement): number {
+ return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
+}
+
+function jumpShown(scenario: Scenario): boolean {
+ return scenario.container.querySelector("[data-jump-to-latest]") !== null;
+}
+
+/** Start a turn, stream a reply of `lines`, and end it with `status`. */
+async function runTurn(
+ scenario: Scenario,
+ lines: number,
+ status: UiMessage["status"],
+ duringRun?: () => Promise<void>,
+): Promise<void> {
+ scenario.render(turn(1, "streaming"), true);
+ await settle(scenario.scroller);
+ scenario.render(turn(lines, "streaming"), true);
+ await settle(scenario.scroller);
+ assert(
+ Math.abs(distanceFromBottom(scenario.scroller)) < 1,
+ `the streaming reply was not followed: ${distanceFromBottom(scenario.scroller)}`,
+ );
+ await duringRun?.();
+ scenario.render(turn(lines, status), false);
+ await settle(scenario.scroller);
+}
+
+globalThis.transcriptTurnCompletionProbe = async () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const roots: Root[] = [];
+ const open = () => {
+ const scenario = mount(host);
+ roots.push(scenario.root);
+ return scenario;
+ };
+ try {
+ // A long reply the reader followed ends with its prompt at the top.
+ const followed = open();
+ await runTurn(followed, 120, "complete");
+ const followedTop = promptTop(followed);
+ const expectedTop = TOOLBAR_BAND_PX + TURN_COMPLETION_TOP_INSET_PX;
+ assert(
+ Math.abs(followedTop - expectedTop) < 2,
+ `the prompt should sit ${expectedTop}px below the top, clear of the titlebar band, got ${followedTop}`,
+ );
+ assert(jumpShown(followed), "leaving follow mode should offer jump to latest");
+ assert(distanceFromBottom(followed.scroller) > 1000, "the view should have left the bottom");
+
+ // A reply short enough that its prompt is already visible does not move.
+ const short = open();
+ await runTurn(short, 3, "complete");
+ assert(Math.abs(distanceFromBottom(short.scroller)) < 1, "a short reply should stay at the bottom");
+ assert(!jumpShown(short), "a short reply should stay in follow mode");
+
+ // A reader who scrolled up during the run keeps their own position.
+ const reading = open();
+ let readingTop = 0;
+ await runTurn(reading, 120, "complete", async () => {
+ reading.scroller.dispatchEvent(new WheelEvent("wheel", { deltaY: -400, bubbles: true }));
+ reading.scroller.scrollTop -= 400;
+ await settle(reading.scroller);
+ readingTop = reading.scroller.scrollTop;
+ });
+ assert(
+ Math.abs(reading.scroller.scrollTop - readingTop) < 1,
+ `a reader's own position moved from ${readingTop} to ${reading.scroller.scrollTop}`,
+ );
+
+ // An aborted turn is not a completed answer to read from the top.
+ const aborted = open();
+ await runTurn(aborted, 120, "aborted");
+ assert(Math.abs(distanceFromBottom(aborted.scroller)) < 1, "an aborted turn should stay at the bottom");
+
+ // A queued follow-up that starts at once keeps following the new turn.
+ const queued = open();
+ queued.render(turn(1, "streaming"), true);
+ await settle(queued.scroller);
+ queued.render(turn(120, "streaming"), true);
+ await settle(queued.scroller);
+ // Both commits land in one task, before the completion frame runs.
+ queued.render(turn(120, "complete"), false);
+ queued.render([...turn(120, "complete"), message("next", "user", "next prompt")], true);
+ await settle(queued.scroller);
+ assert(
+ Math.abs(distanceFromBottom(queued.scroller)) < 1,
+ `a follow-up turn should stay at the bottom: ${distanceFromBottom(queued.scroller)}`,
+ );
+
+ return {
+ ok: true,
+ followed: { promptTop: followedTop, scrollTop: followed.scroller.scrollTop },
+ reading: { scrollTop: reading.scroller.scrollTop },
+ };
+ } finally {
+ for (const root of roots) flushSync(() => root.unmount());
+ host.remove();
+ }
+};