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
2 changes: 1 addition & 1 deletion apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const GUIDE_TOPICS: ReadonlyArray<GuideTopic> = [
"archive",
"restart",
],
body: `A thread is one conversation with an agent in a project. Threads are listed in the sidebar; one that needs you, finished or failed says so there. In a narrow window the sidebar floats over the thread instead of sitting beside it: the sidebar button at the top left, or Cmd+B (Ctrl+B on Windows and Linux), opens it, and picking a thread or clicking the thread puts it away.
body: `A thread is one conversation with an agent in a project. Threads are listed in the sidebar; one that needs you, finished or failed says so there. In a narrow window the sidebar floats over the thread instead of sitting beside it: the sidebar button at the top left, or Cmd+B (Ctrl+B on Windows and Linux), opens it, and picking a thread or clicking the thread puts it away. A thread you scrolled up in opens where you left it when you come back, until Threadlines reloads; one that finished, failed or needs you since then opens at the end.

The sliders button beside the project picker at the top of the sidebar groups the list by project or computer and sorts it: recent activity, newest, oldest, title, or a custom order. In the custom order you drag rows to arrange them, or use Move up and Move down in a thread's menu, and only you move a row; new threads go to the bottom, and the same button can reset the order. Pinned threads stay above a thin line in every sort, under a project's lead chat, which comes first. When the list is grouped, drag a group's header to move the whole group, in any sort; its menu has Move up, Move down and Use automatic order. These orders are kept per device, so a phone has its own.

Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/components/ChatView.browser-harness.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test

import { DEFAULT_CLIENT_SETTINGS } from "@threadlines/contracts/settings";
import { resetTestPage } from "../lib/testPage.browser-harness";
import { forgetThreadScrollExcept } from "../threadScrollMemory";

export const THREAD_ID = "thread-browser-test" as ThreadId;
export const THREAD_TITLE = "Browser test thread";
Expand Down Expand Up @@ -3204,6 +3205,8 @@ export async function dispatchInputKey(
await waitForLayout();
}

const NO_THREADS: ReadonlySet<string> = new Set();

export async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
Expand All @@ -3214,6 +3217,8 @@ export async function mountChatView(options: {
/** Mount under StrictMode, as main.tsx does, so mount-time effect cleanups run. */
strictMode?: boolean;
}): Promise<MountedChatView> {
// Where chats were left lives for the page; each mount starts with none.
forgetThreadScrollExcept(NO_THREADS);
fixture = buildFixture(options.snapshot);
options.configureFixture?.(fixture);
customWsRpcResolver = options.resolveRpc ?? null;
Expand Down Expand Up @@ -3258,6 +3263,7 @@ export async function mountChatView(options: {
const cleanup = async () => {
customWsRpcResolver = null;
await finishCleanupStep("React's unmount", screen.unmount());
forgetThreadScrollExcept(NO_THREADS);
host.remove();
await finishCleanupStep("the animation frames after unmount", waitForLayout());
};
Expand Down
126 changes: 125 additions & 1 deletion apps/web/src/components/ChatView.sidebar.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
__setEnvironmentApiOverrideForTests,
} from "../environmentApi";
import { getClientSettings, updateSettings } from "../hooks/useSettings";
import { readAfterEachPaint } from "../lib/frameProbe.browser-harness";
import { nextFrames, readAfterEachPaint } from "../lib/frameProbe.browser-harness";
import { isMacPlatform } from "../lib/utils";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useUiStateStore } from "../uiStateStore";
Expand Down Expand Up @@ -239,6 +239,130 @@ describe("ChatView (full app): sidebar", () => {
}
});

// Scroll memory (threadScrollMemory): a chat left above the end opens there
// again, from its first drawn frame; left at the end, or with news, it
// opens at the end; a find target wins.
const SCROLL_OTHER_THREAD = "thread-scroll-memory-other" as ThreadId;
const mountTwoThreads = () =>
mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: addThreadToSnapshot(
createSnapshotForTargetUser({
targetMessageId: "msg-user-scroll-memory-target" as MessageId,
targetText: "scroll memory target",
}),
SCROLL_OTHER_THREAD,
),
});
const chatList = () => document.querySelector<HTMLElement>('[data-chat-messages-list="true"]');
const listAtEnd = (list: HTMLElement) =>
list.scrollTop + list.clientHeight >= list.scrollHeight - 2;
const rowTop = (list: HTMLElement, rowId: string) => {
const row = list.querySelector(`[data-timeline-row-id="${rowId}"]`);
return row === null ? null : row.getBoundingClientRect().top - list.getBoundingClientRect().top;
};
const firstRowInView = (list: HTMLElement) => {
const listTop = list.getBoundingClientRect().top;
return [...list.querySelectorAll<HTMLElement>("[data-timeline-row-id]")].find(
(row) => row.getBoundingClientRect().bottom > listTop + 24,
)?.dataset.timelineRowId;
};
const openThread = (
mounted: Awaited<ReturnType<typeof mountTwoThreads>>,
threadId: ThreadId,
search?: Record<string, string>,
) =>
mounted.router.navigate({
to: "/$environmentId/$threadId",
params: { environmentId: LOCAL_ENVIRONMENT_ID, threadId },
...(search ? { search } : {}),
});
/** Opens the long chat at the end, then leaves it scrolled to its middle or its end. */
const leaveLongChat = async (
mounted: Awaited<ReturnType<typeof mountTwoThreads>>,
where: "middle" | "end",
) => {
const list = await waitForElement(chatList, "The chat should show its messages.");
await vi.waitFor(() => expect(listAtEnd(list)).toBe(true), { timeout: 5_000 });
if (where === "middle") {
// Scrolled up by the wheel, as a reader leaves the end.
for (let step = 0; step < 6; step += 1) {
list.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -300 }));
list.scrollTop -= 300;
await nextFrames(2);
}
await vi.waitFor(() => expect(listAtEnd(list)).toBe(false));
await nextFrames(4);
}
const rowId = firstRowInView(list)!;
const top = rowTop(list, rowId)!;
await openThread(mounted, SCROLL_OTHER_THREAD);
await vi.waitFor(() => expect(document.querySelector("[data-timeline-row-id]")).toBeNull());
return { rowId, top };
};

it("opens a chat where it was left, from the first frame it draws", async () => {
const mounted = await mountTwoThreads();
try {
const left = await leaveLongChat(mounted, "middle");
// Every frame the long chat draws on the way back.
const frames: { top: number | null; atEnd: boolean }[] = [];
const stop = readAfterEachPaint(() => {
const list = chatList();
if (list?.querySelector("[data-timeline-row-id]")) {
frames.push({ top: rowTop(list, left.rowId), atEnd: listAtEnd(list) });
}
});
await openThread(mounted, THREAD_ID);
await vi.waitFor(() => expect(frames.length).toBeGreaterThan(5), { timeout: 5_000 });
stop();
expect(frames.every((frame) => frame.top !== null && !frame.atEnd)).toBe(true);
expect(Math.abs(frames.at(-1)!.top! - left.top)).toBeLessThanOrEqual(2);
// Above the end, the way back down is offered as usual.
await expect.element(page.getByRole("button", { name: "Scroll to bottom" })).toBeVisible();
} finally {
await mounted.cleanup();
}
});

it("opens a chat left at its end at the end, and one with news at the end too", async () => {
const mounted = await mountTwoThreads();
try {
await leaveLongChat(mounted, "end");
await openThread(mounted, THREAD_ID);
await vi.waitFor(() => expect(listAtEnd(chatList()!)).toBe(true), { timeout: 5_000 });

// Left mid-history, then it came to need the user while away.
await leaveLongChat(mounted, "middle");
setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, THREAD_ID, "needs-you");
await openThread(mounted, THREAD_ID);
await vi.waitFor(() => expect(listAtEnd(chatList()!)).toBe(true), { timeout: 5_000 });
} finally {
await mounted.cleanup();
}
});

it("opens at a find target rather than where the chat was left", async () => {
const mounted = await mountTwoThreads();
try {
await leaveLongChat(mounted, "middle");
await openThread(mounted, THREAD_ID, { focusMessageId: "msg-user-1", focusQuery: "" });
await vi.waitFor(
() => {
const list = chatList()!;
const top = rowTop(list, "msg-user-1");
expect(top).not.toBeNull();
// The target sits about a third of the way down, as find puts it.
expect(top! / list.clientHeight).toBeGreaterThan(0.1);
expect(top! / list.clientHeight).toBeLessThan(0.6);
},
{ timeout: 5_000 },
);
} finally {
await mounted.cleanup();
}
});

it("shows the project's lead chat, and its menu stops it or names another thread instead", async () => {
const otherThreadId = "thread-lead-other" as ThreadId;
const withThreads = addThreadToSnapshot(
Expand Down
27 changes: 26 additions & 1 deletion apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ import {
import {
selectEnvironmentState,
selectProjectsAcrossEnvironments,
selectSidebarThreadSummaryByRef,
selectThreadDetailLoaded,
selectThreadByRef,
selectThreadExistsByRef,
Expand All @@ -161,6 +162,8 @@ import {
useStore,
} from "../store";
import { readLeadProjectName } from "../leadChat";
import { threadHasNewsForUser } from "./Sidebar.logic";
import { readThreadScroll } from "../threadScrollMemory";
import { FamilyTabs, useFamilyTabsShown } from "./chat/FamilyTabs";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
Expand Down Expand Up @@ -1210,6 +1213,19 @@ export default function ChatView(props: ChatViewProps) {
? selectThreadSeenAt(store, routeThreadKey, serverThread?.lastSeenAt)
: undefined,
);
// Something new to show in this thread, read before opening it marks it
// seen: then its chat opens at the end, not where it was left.
const activeThreadHasNews = useStore((store) => {
if (routeKind !== "server") return false;
const summary = selectSidebarThreadSummaryByRef(store, routeThreadRef);
return summary !== undefined && threadHasNewsForUser(summary, activeThreadSeenAt);
});
// Held stable: the timeline is memoized, and reads this only when it mounts.
const timelineScrollMemory = useMemo(
() =>
routeKind === "server" ? { threadKey: routeThreadKey, hasNews: activeThreadHasNews } : null,
[activeThreadHasNews, routeKind, routeThreadKey],
);
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const suppressCrossProviderWarning = settings.suppressCrossProviderSwitchWarning ?? false;
Expand Down Expand Up @@ -4944,7 +4960,14 @@ export default function ChatView(props: ChatViewProps) {
const isThreadEntry = layoutStickThreadIdRef.current !== activeThreadId;
layoutStickThreadIdRef.current = activeThreadId;
if (!activeThreadId) return;
if (isThreadEntry && timelineSearchTargetRef.current) return;
// Opening at a find target, or where the chat was left (the timeline read
// and kept or dropped that place as it rendered): not at the end.
if (
isThreadEntry &&
(timelineSearchTargetRef.current || readThreadScroll(routeThreadKey) !== null)
) {
return;
}
if (!isAtEndRef.current && !isLegendListVisiblyAtEnd(legendListRef.current)) {
return;
}
Expand Down Expand Up @@ -4978,6 +5001,7 @@ export default function ChatView(props: ChatViewProps) {
infrastructureComposerNotices.length,
providerSendPreflight,
providerStatusNoticeVisible,
routeThreadKey,
terminalState.terminalHeight,
terminalState.terminalOpen,
threadErrorNoticeVisible,
Expand Down Expand Up @@ -9020,6 +9044,7 @@ export default function ChatView(props: ChatViewProps) {
mcpAuthReconnectStatusByServerName={activeMcpAuthReconnectStatusByServerName}
onRunMcpAuthReconnect={runMcpAuthReconnect}
onIsAtEndChange={onIsAtEndChange}
scrollMemory={timelineScrollMemory}
onVisibleTurnIdsChange={handleVisibleTurnIdsChange}
searchTarget={timelineSearchTarget}
planScrollTarget={planScrollTarget}
Expand Down
35 changes: 35 additions & 0 deletions apps/web/src/components/Sidebar.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
THREAD_STATUS_DOT_CLASSES,
resolveSeenThreadStatus,
resolveThreadStatusPill,
threadHasNewsForUser,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
Expand Down Expand Up @@ -389,6 +390,40 @@ describe("isContextMenuPointerDown", () => {
});
});

describe("threadHasNewsForUser", () => {
const failed = {
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "default" as const,
latestTurn: null,
session: {
provider: ProviderDriverKind.make("codex"),
status: "error" as const,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T11:00:00.000Z",
orchestrationStatus: "error" as const,
pendingBackgroundTaskCount: 0,
},
};

it("counts a failure until it is seen, and a question while it waits", () => {
expect(threadHasNewsForUser(failed, "2026-03-09T10:30:00.000Z")).toBe(true);
// Seen since it failed: the chat may open where it was left.
expect(threadHasNewsForUser(failed, "2026-03-09T11:30:00.000Z")).toBe(false);
expect(
threadHasNewsForUser(
{
...failed,
hasPendingUserInput: true,
session: { ...failed.session, status: "running", orchestrationStatus: "running" },
},
"2026-03-09T11:30:00.000Z",
),
).toBe(true);
});
});

describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
Expand Down
27 changes: 26 additions & 1 deletion apps/web/src/components/Sidebar.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,26 @@ export function isNeedsUserStatus(status: ThreadStatusPill | null): boolean {
return status !== null && NEEDS_USER_STATUSES.has(status.label);
}

/**
* Whether opening the thread now shows the user something new: an answer or a
* failure they haven't seen since `seenAt`, or an approval or question waiting
* on them (a failure already seen is not news). The
* chat then opens at the end, not where it was left (threadScrollMemory),
* since opening it marks it seen.
*/
export function threadHasNewsForUser(
thread: ThreadStatusInput,
seenAt: string | null | undefined,
): boolean {
return (
hasUnseenCompletionSince(thread, seenAt) ||
hasUnseenSessionFailureSince(thread, seenAt) ||
isWaitingOnUserStatus(
resolveThreadStatusPill({ thread: { ...thread, lastVisitedAt: undefined } }),
)
);
}

/**
* The single word a row spends on status. Only states that stop the agent and
* hand the thread back earn one; in-flight work reads as "working" with its
Expand Down Expand Up @@ -1718,9 +1738,14 @@ const NEEDS_YOU_NOW: ReadonlySet<ThreadStatusPill["label"]> = new Set([
"Awaiting Input",
]);

/** An approval or a question waits on the user (a failure, seen or not, is not one). */
export function isWaitingOnUserStatus(status: ThreadStatusPill | null): boolean {
return status !== null && NEEDS_YOU_NOW.has(status.label);
}

/** A child that is waiting on the user's answer: never folded out of sight. */
export function isChildThreadNeedingYou(entry: InboxFamilyStatus): boolean {
return !entry.isDone && entry.status !== null && NEEDS_YOU_NOW.has(entry.status.label);
return !entry.isDone && isWaitingOnUserStatus(entry.status);
}

const IN_FLIGHT: ReadonlySet<ThreadStatusPill["label"]> = new Set([
Expand Down
Loading
Loading