Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/a-conversation-opens-at-its-end.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@flow-state-dev/react": patch
"@flow-state-dev/devtool": patch
"@flow-state-dev/shift-manager": patch
---

A conversation opens at its end with no scroll animation: on mount, on a switch to another session, and when its first read fills it. Only content that arrives while the reader is at the end scrolls smoothly, and a reader who scrolled up stays where they are. `@flow-state-dev/react` exports the rule as `useFollowLatest({ resetKey?, startAtEnd? })`, returning `{ ref, atEnd, follow, stay }`. The DevTool's stream view and Shift Manager's conversations use it, so Shift Manager now glides to live content instead of jumping (FIX-2346).
5 changes: 4 additions & 1 deletion apps/docs/docs/ui/common-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@ fsdev ui add conversation
```

```tsx
import { Conversation } from "@/components/flow-state/conversation";
import { Conversation, ScrollOnNewRequest } from "@/components/flow-state/conversation";

<Conversation>
<ScrollOnNewRequest items={items} />
{/* messages */}
</Conversation>
```

Put `ScrollOnNewRequest` inside to bring each new request into view. When a conversation opens, on its first load or when you switch to another session, it lands at the bottom before the first paint, with no animation. Only a request that follows one already on screen scrolls smoothly.

## Message

Individual message display with streaming Markdown rendering. Accepts either primitive props (`role`, `content`) or a Flow State `MessageItem` directly.
Expand Down
44 changes: 32 additions & 12 deletions apps/kitchen-sink/components/flow-state/conversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
useCallback,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
Expand All @@ -21,7 +22,10 @@ import type { OutputItem } from "@flow-state-dev/core/items";

type ConversationScrollContextValue = {
isAtBottom: boolean;
scrollToBottom: () => void;
/** Whether the scroll container is in the page yet, so a scroll can land. */
ready: boolean;
/** Smooth by default; `"instant"` for a conversation that is opening, not growing. */
scrollToBottom: (behavior?: "smooth" | "instant") => void;
};

const ConversationScrollContext =
Expand All @@ -46,8 +50,15 @@ export const Conversation = ({
children,
...props
}: ConversationProps) => {
const scrollRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement | null>(null);
const [ready, setReady] = useState(false);
const [isAtBottom, setIsAtBottom] = useState(true);
// A child's layout effect runs before this element's ref is set: `ready`
// re-renders it once the container is there, still before paint.
const attach = useCallback((node: HTMLDivElement | null) => {
scrollRef.current = node;
setReady(node !== null);
}, []);

const checkIsAtBottom = useCallback(() => {
const el = scrollRef.current;
Expand Down Expand Up @@ -85,16 +96,16 @@ export const Conversation = ({
};
}, [checkIsAtBottom]);

const scrollToBottom = useCallback(() => {
const scrollToBottom = useCallback((behavior: "smooth" | "instant" = "smooth") => {
const el = scrollRef.current;
if (!el) return;
el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
el.scrollTo({ top: el.scrollHeight, behavior });
}, []);

return (
<ConversationScrollContext.Provider value={{ isAtBottom, scrollToBottom }}>
<ConversationScrollContext.Provider value={{ isAtBottom, ready, scrollToBottom }}>
<div
ref={scrollRef}
ref={attach}
onScroll={checkIsAtBottom}
className={cn("relative flex-1 overflow-y-auto", className)}
role="log"
Expand Down Expand Up @@ -165,22 +176,31 @@ export const ConversationEmptyState = ({
/**
* Place inside <Conversation> to auto-scroll to bottom when a new request
* appears (e.g. user sends a message). Does NOT auto-scroll during streaming.
*
* A conversation that opens (its first load, or a switch to another session,
* where the last request shown is no longer among the items) lands at the
* bottom at once, before paint. Only a request that follows one already on
* screen scrolls smoothly.
*/
export function ScrollOnNewRequest({ items }: { items: OutputItem[] }) {
const { scrollToBottom } = useConversationScroll();
const { ready, scrollToBottom } = useConversationScroll();
const lastRequestIdRef = useRef<string | null>(null);

useEffect(() => {
// Before paint, so an opening conversation is never seen at the top.
useLayoutEffect(() => {
if (!ready) return;
if (items.length === 0) {
lastRequestIdRef.current = null;
return;
}
const shown = lastRequestIdRef.current;
const lastRequestId = items[items.length - 1].requestId;
if (lastRequestId !== lastRequestIdRef.current) {
if (lastRequestId !== shown) {
lastRequestIdRef.current = lastRequestId;
scrollToBottom();
const continued = shown !== null && items.some((item) => item.requestId === shown);
scrollToBottom(continued ? "smooth" : "instant");
}
}, [items, scrollToBottom]);
}, [items, ready, scrollToBottom]);

return null;
}
Expand All @@ -206,7 +226,7 @@ export const ConversationScrollButton = ({
"rounded-full pointer-events-auto dark:bg-background dark:hover:bg-muted",
className
)}
onClick={scrollToBottom}
onClick={() => scrollToBottom()}
size="icon"
type="button"
variant="outline"
Expand Down
1 change: 1 addition & 0 deletions labs/claude-code-style/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@flow-state-dev/fsdev": "workspace:*",
"@flow-state-dev/harness-manager": "workspace:*",
"@flow-state-dev/orchestration": "workspace:*",
"@flow-state-dev/react": "workspace:*",
"@flow-state-dev/store-sqlite": "workspace:*",
"@flow-state-dev/workforce": "workspace:*",
"@flow-state-dev/workspace": "workspace:*",
Expand Down
7 changes: 6 additions & 1 deletion labs/claude-code-style/src/components/Sheet.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useFollowLatest } from "@flow-state-dev/react";
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";

Expand Down Expand Up @@ -43,6 +44,8 @@ export function Sheet({ label, title, subtitle, onClose, children, footer }: {
footer?: ReactNode;
}) {
const { host } = useContext(SheetHost);
// Opens on the latest of the work it shows, and follows it while the reader stays there.
const feed = useFollowLatest();
useEffect(() => {
const onKey = (event: KeyboardEvent) => event.key === "Escape" && onClose();
document.addEventListener("keydown", onKey);
Expand All @@ -66,7 +69,9 @@ export function Sheet({ label, title, subtitle, onClose, children, footer }: {
×
</button>
</header>
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-5 py-4">{children}</div>
<div ref={feed.ref} className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-5 py-4">
{children}
</div>
{footer ? <footer className="border-t border-border px-5 py-3 text-xs text-muted-foreground">{footer}</footer> : null}
</section>
</div>,
Expand Down
16 changes: 8 additions & 8 deletions labs/claude-code-style/src/components/Thread.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useFollowLatest } from "@flow-state-dev/react";
import type { LabAdapter, ProjectRow, SessionRow, TaskRow } from "../adapter";
import { elapsed, useNow, useWatch } from "../lib/use-watch";
import { modeOfWorker } from "../modes";
Expand Down Expand Up @@ -34,11 +34,8 @@ export function Thread({
) ?? [];
const running = view?.running ?? false;
const now = useNow(running);
const end = useRef<HTMLDivElement>(null);
const count = view?.entries.length ?? 0;
useEffect(() => {
end.current?.scrollIntoView?.({ block: "end" });
}, [count, running]);
const feed = useFollowLatest({ resetKey: session.id });

return (
<main aria-label="Main thread" className="flex h-full min-h-0 min-w-0 flex-col">
Expand All @@ -53,7 +50,7 @@ export function Thread({
{mode?.label ?? session.worker}
</span>
</header>
<div className="flex-1 overflow-y-auto px-6 py-4">
<div ref={feed.ref} className="flex-1 overflow-y-auto px-6 py-4">
{count === 0 ? (
<div className="mx-auto mt-24 max-w-sm text-center text-sm text-muted-foreground">
{mode?.pane === "board"
Expand Down Expand Up @@ -84,7 +81,6 @@ export function Thread({
working · {elapsed(view.turnStartedAt, now)}
</div>
) : null}
<div ref={end} />
</div>
)}
</div>
Expand All @@ -96,7 +92,11 @@ export function Thread({
) : (
<Composer
running={running}
onSend={(text) => void adapter.send(session.id, text)}
onSend={(text) => {
// Your own line brings you back to the end, wherever you had scrolled to.
feed.follow();
void adapter.send(session.id, text);
}}
onStop={() => void adapter.interrupt(session.id)}
/>
)}
Expand Down
4 changes: 3 additions & 1 deletion labs/claude-code-style/src/components/ThreadView.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useFollowLatest } from "@flow-state-dev/react";
import { useState, type FormEvent } from "react";
import type { LabAdapter, TaskRow } from "../adapter";
import { useWatch } from "../lib/use-watch";
Expand Down Expand Up @@ -30,6 +31,7 @@ export function ThreadView({
[adapter, sessionId, task.id],
);
const [text, setText] = useState("");
const feed = useFollowLatest({ resetKey: task.id });
const column = statusColumn(task);
const question = task.waitingOn && task.waitingOn.kind !== "review" ? task.waitingOn : undefined;
const words = text.trim();
Expand Down Expand Up @@ -67,7 +69,7 @@ export function ThreadView({
</div>
<div className="px-4 pt-2 text-xs text-muted-foreground">{statusLine(task)}</div>
<Spend task={task} split className="px-4" />
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-4 py-2">
<div ref={feed.ref} className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-4 py-2">
{work?.entries.map((entry) => <Entry key={entry.id} entry={entry} />)}
</div>
{question ? (
Expand Down
83 changes: 82 additions & 1 deletion labs/claude-code-style/test/screen.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { StrictMode } from "react";
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, onTestFinished } from "vitest";
import { App } from "../src/App";
import { createFakeLab } from "./fake-lab";

Expand Down Expand Up @@ -34,6 +34,46 @@ async function pick(name = "vendor-notes") {
await screen.findByLabelText("Message the main session");
}


/**
* Lay the scrolling feeds out as a browser would (happy-dom lays nothing out): the main thread's
* list and a sheet's body, each 5000px of content in a 500px view. Every scroll they are asked
* for is recorded with how it moves, and lands at once. Undone by the returned function.
*/
function layOutFeeds() {
const isFeed = (el: HTMLElement) =>
el.classList.contains("overflow-y-auto") &&
(el.parentElement?.getAttribute("aria-label") === "Main thread" || el.parentElement?.getAttribute("role") === "dialog");
const names = ["scrollHeight", "clientHeight", "scrollTop", "scrollTo"] as const;
const saved = names.map((name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)] as const);
const tops = new WeakMap<HTMLElement, number>();
const scrolls: { feed: HTMLElement; behavior: ScrollBehavior | undefined }[] = [];
Object.defineProperties(HTMLElement.prototype, {
scrollHeight: { configurable: true, get(this: HTMLElement) { return isFeed(this) ? 5000 : 0; } },
clientHeight: { configurable: true, get(this: HTMLElement) { return isFeed(this) ? 500 : 0; } },
scrollTop: {
configurable: true,
get(this: HTMLElement) { return tops.get(this) ?? 0; },
set(this: HTMLElement, value: number) { tops.set(this, isFeed(this) ? Math.max(0, Math.min(value, 4500)) : 0); },
},
scrollTo: {
configurable: true,
value(this: HTMLElement, options: ScrollToOptions) {
if (isFeed(this)) scrolls.push({ feed: this, behavior: options.behavior });
this.scrollTop = options.top ?? 0;
},
},
});
const restore = () => {
for (const [name, was] of saved) {
if (was === undefined) delete (HTMLElement.prototype as unknown as Record<string, unknown>)[name];
else Object.defineProperty(HTMLElement.prototype, name, was);
}
};
return { scrolls, restore };
}
const threadFeed = () => thread().querySelector<HTMLElement>(":scope > .overflow-y-auto")!;

describe("the session-mode screen", () => {
it("lays out sessions, the main thread and the tasks pane, and opens on New session asking for a project", async () => {
render(<App adapter={fast()} />);
Expand Down Expand Up @@ -123,6 +163,47 @@ describe("the session-mode screen", () => {
expect((screen.getByLabelText("Message the main session") as HTMLTextAreaElement).value).toBe("");
});

it("opens a session already at its end, with no scroll to watch, and leaves you where you scrolled up to as it goes on", async () => {
const feeds = layOutFeeds();
onTestFinished(feeds.restore);
render(<App adapter={fast()} />);
await pick();
const sessions = screen.getByRole("navigation", { name: "Sessions" });
fireEvent.click(within(sessions).getByRole("button", { name: /Draft the launch note/ }));
await waitFor(() => expect(within(thread()).getByRole("heading").textContent).toBe("Draft the launch note"));
await waitFor(() => expect(threadFeed().scrollTop).toBe(4500));
// Opening is never an animation: every move to the end so far was instant.
expect(feeds.scrolls.length).toBeGreaterThan(0);
expect(feeds.scrolls.filter((s) => s.behavior !== "instant")).toEqual([]);

// Up to read: what the running turn adds below doesn't pull you down.
await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));
await ask("Compare Acme and Globex for us.");
const feed = threadFeed();
feed.scrollTop = 1200;
fireEvent.scroll(feed);
feeds.scrolls.length = 0;
await within(thread()).findByRole("region", { name: "Background result: Research Acme" });
expect(feeds.scrolls).toEqual([]);
expect(feed.scrollTop).toBe(1200);
});

it("opens a task's sheet already at the latest of its work", async () => {
const feeds = layOutFeeds();
onTestFinished(feeds.restore);
render(<App adapter={fast()} />);
await pick();
await ask("Compare Acme and Globex for us.");
await waitFor(() => expect(row("Research Globex")).toBeTruthy());
feeds.scrolls.length = 0;
fireEvent.click(row("Research Globex"));
const body = screen.getByRole("dialog", { name: "Work: Research Globex" }).querySelector<HTMLElement>(":scope > .overflow-y-auto")!;
expect(body.scrollTop).toBe(4500);
const opening = feeds.scrolls.filter((s) => s.feed === body);
expect(opening.length).toBeGreaterThan(0);
expect(opening.every((s) => s.behavior === "instant")).toBe(true);
});

it("shows a background result inside the running turn, then stops the other task when asked", async () => {
// A twentieth of real time: the card has about 100ms inside the turn, room for a loaded runner to see it.
render(<App adapter={createFakeLab({ speed: 0.05 })} />);
Expand Down
1 change: 1 addition & 0 deletions labs/teammates/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"@flow-state-dev/harness-manager": "workspace:*",
"@flow-state-dev/memory": "workspace:*",
"@flow-state-dev/orchestration": "workspace:*",
"@flow-state-dev/react": "workspace:*",
"@flow-state-dev/store-sqlite": "workspace:*",
"@flow-state-dev/tools": "workspace:*",
"@flow-state-dev/workforce": "workspace:*",
Expand Down
16 changes: 6 additions & 10 deletions labs/teammates/src/components/Conversation.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Fragment, useCallback, useRef, useState } from "react";
import { useFollowLatest } from "@flow-state-dev/react";
import { Fragment, useCallback, useState } from "react";
import type { BoardTask, ConversationEntry, LabAdapter, WorkerRow } from "../adapter";
import type { Look } from "../lib/looks";
import { useStatusLine } from "../lib/status";
import { useStickToBottom } from "../lib/stick-to-bottom";
import { pendingFor } from "../lib/talk";
import { useWatch } from "../lib/use-watch";
import { cn } from "../lib/utils";
Expand Down Expand Up @@ -84,11 +84,7 @@ export function Conversation({
const last = entries[entries.length - 1];
// An answer on screen, written or being written, is the sign it is answering; the line shows only before one starts.
const answering = running && last?.kind !== "assistant";
const scroller = useRef<HTMLDivElement>(null);
const { atEnd, jumpToLatest } = useStickToBottom(
scroller,
`${sessionId}:${entries.length}:${last && "text" in last ? last.text.length : 0}:${pending.length}:${answering}`,
);
const feed = useFollowLatest({ resetKey: sessionId });

// Stable, so a memoized line doesn't redraw for a new function.
const openTask = useCallback((taskId: string) => onOpen({ kind: "task", sessionId, taskId }), [onOpen, sessionId]);
Expand Down Expand Up @@ -151,7 +147,7 @@ export function Conversation({
/>
</div>
) : null}
<div ref={scroller} data-scroller className="relative flex-1 overflow-y-auto px-6 py-4">
<div ref={feed.ref} data-scroller className="relative flex-1 overflow-y-auto px-6 py-4">
<div data-column className="mx-auto flex max-w-(--thread-width) flex-col gap-3">
{entries.length === 0 ? (
<div className="mt-24 text-center text-sm text-muted-foreground">Say hello to {worker.name}. This is your one conversation with it.</div>
Expand Down Expand Up @@ -201,10 +197,10 @@ export function Conversation({
</div>
))}
</div>
{atEnd ? null : (
{feed.atEnd ? null : (
<button
type="button"
onClick={jumpToLatest}
onClick={feed.follow}
className="sticky bottom-2 mx-auto block rounded-full border border-border bg-card px-3 py-1 text-xs shadow hover:bg-accent"
>
Jump to latest
Expand Down
Loading
Loading