Skip to content
Open
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
16 changes: 16 additions & 0 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { observeResize } from "~/lib/observeResize";
import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
import { useUnseenDivider } from "./chat/useUnseenDivider";
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
import { ChatRightPanel } from "./chat/ChatRightPanel";
import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting";
Expand Down Expand Up @@ -1661,6 +1662,16 @@ export default function ChatView(props: ChatViewProps) {
: (activeThreadShell?.source.seenMessageByFounder?.[viewerFounder] ?? null),
onRecorded: recordSeenPlace,
});
const unseenDivider = useUnseenDivider({
threadKey: isServerThread ? activeThreadKey : null,
viewer: viewerFounder,
shellReady: activeThreadShell != null,
lastSeenMessageId:
viewerFounder == null
? null
: (activeThreadShell?.source.seenMessageByFounder?.[viewerFounder] ?? null),
messages: serverProjection?.messages,
});
const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey);
const {
worktreeSetup,
Expand Down Expand Up @@ -3595,10 +3606,15 @@ export default function ChatView(props: ChatViewProps) {
draftEntries={isServerThread ? null : draftTimelineEntries}
activeThreadKey={activeThreadKey}
collapseActivity={activityCollapsed}
unseenDivider={unseenDivider}
includeOtherActivity={isStandingBot}
decisionRequestedAt={
activeThreadShell?.source.inbox?.decisionRequest?.requestedAt
}
inFounderInbox={
activeThreadShell?.source.inbox !== undefined &&
activeThreadShell.source.inbox.audience !== "agent-only"
}
sharedThread={activeThreadShell?.source.inbox?.audience === "shared"}
syncing={threadSyncPhase !== null}
detailLoading={threadDetailLoading}
Expand Down
70 changes: 70 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,76 @@ it("keeps a model-hidden note visible and only promotes it after an explicit cli
expect(remounted.buttons("Promote to agent")).toHaveLength(0);
});

function messageAt(minute: number, text: string, overrides = {}, id = `message-${minute}`): Entry {
const createdAt = `2026-03-17T19:${String(minute).padStart(2, "0")}:00.000Z`;
const base = message(text, { createdAt, updatedAt: createdAt, ...overrides }, id);
return { ...base, createdAt } as Entry;
}

describe("MessagesTimeline new since you last looked", () => {
const longText = (label: string) => `${label}\n\n${"filler line\n\n".repeat(12)}`;
const thread = () =>
Array.from({ length: 24 }, (_, index) =>
messageAt(index, longText(`message ${index}`), index % 2 === 0 ? {} : { role: "assistant" }),
);

it("shows a divider and a jump pill while the divider is off screen, and jump clears the pill", async () => {
setup();
await using screen = await renderTimeline(thread(), {
unseenDivider: { afterMessageId: MessageId.make("message-2"), count: 11 },
});
await vi.waitFor(() => expect(screen.text()).toContain("11 new since you last looked"));
await click(screen.button(/new since you last looked/));
await vi.waitFor(() => expect(document.querySelector("[data-new-since-last-seen]")).toBeNull());
// The list virtualizes, so the divider mounts only once the jump brings it into range.
await vi.waitFor(
() => {
const divider = document.querySelector("[data-new-messages-divider]");
expect(divider).not.toBeNull();
expect(divider!.getBoundingClientRect().top).toBeGreaterThanOrEqual(0);
expect(divider!.getBoundingClientRect().top).toBeLessThan(window.innerHeight);
},
{ timeout: 6000 },
);
});

it("places the line after a queued message whose timeline row starts later than its record", async () => {
setup();
const queued = messageAt(1, "queued question", {}, "queued");
const entries = [
messageAt(0, "prior question"),
messageAt(2, "earlier reply", { role: "assistant" }),
{ ...queued, createdAt: "2026-03-17T19:05:00.000Z" } as Entry,
messageAt(6, "fresh reply", { role: "assistant" }),
];
await using screen = await renderTimeline(entries, {
unseenDivider: { afterMessageId: MessageId.make("queued"), count: 1 },
});
await vi.waitFor(() =>
expect(document.querySelector("[data-new-messages-divider]")).not.toBeNull(),
);
const top = (text: string) =>
[...document.querySelectorAll<HTMLElement>("[data-timeline-row-id]")]
.find((row) => row.textContent?.includes(text))!
.getBoundingClientRect().top;
const divider = document
.querySelector("[data-new-messages-divider]")!
.getBoundingClientRect().top;
expect(divider).toBeGreaterThan(top("queued question"));
expect(divider).toBeLessThan(top("fresh reply"));
});

it("dismisses the pill", async () => {
setup();
await using screen = await renderTimeline(thread(), {
unseenDivider: { afterMessageId: MessageId.make("message-2"), count: 3 },
});
await vi.waitFor(() => expect(screen.text()).toContain("3 new since you last looked"));
await click(screen.button("Dismiss new messages"));
expect(document.querySelector("[data-new-since-last-seen]")).toBeNull();
});
});

const TASK_ID = ScheduledTaskId.make("task-1");
const AUTOMATION_PROMPT = "Triage the inbox\n\nLabel every new issue and close duplicates.";

Expand Down
63 changes: 49 additions & 14 deletions apps/web/src/components/chat/MessagesTimeline.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
collapseTimelineActivity,
activityUpdateSummary,
activityPillIdForEntry,
insertNewMessagesDivider,
timelineActivityContext,
timelineTurnFoldRunIdsByEntryId,
liveAnswerPreview,
Expand Down Expand Up @@ -5329,6 +5330,43 @@ describe("collapsing non-human activity", () => {
).toBe("1 agent update · 1 system notice · 1 automation");
});

it("puts the new-messages divider before the first row after the stored place", () => {
const base = [
messageRow("seen", 0, person("kameron")),
messageRow("later", 2, { role: "assistant" }),
messageRow("latest", 3, { role: "assistant" }),
];
const withDivider = insertNewMessagesDivider(base, { afterCreatedAt: time(1), count: 2 });
expect(withDivider.map(({ id }) => id)).toEqual([
"seen",
"new-messages-divider",
"later",
"latest",
]);
expect(withDivider[1]).toMatchObject({ kind: "new-messages-divider", count: 2 });
expect(insertNewMessagesDivider(base, { afterCreatedAt: time(3), count: 1 })).toBe(base);
expect(insertNewMessagesDivider(base, null)).toBe(base);
});

it("keeps the newest agent-run reply unfolded in a founder's inbox", () => {
const botRun = RunId.make("inbox-run");
const conversation = [
messageRow("brief", 0, { runId: botRun, createdBy: "agent" }),
messageRow("audit", 1, { runId: botRun, role: "assistant" }),
];
const entries = conversation.flatMap((row): TimelineEntry[] =>
row.kind === "message" ? [{ ...row, kind: "message" }] : [],
);
const ids = (keepLatestReply: boolean) =>
collapseTimelineActivity(
conversation,
new Set(),
timelineActivityContext(entries, [], false, undefined, keepLatestReply),
).map(({ id }) => id);
expect(ids(false)).toEqual(["activity:brief"]);
expect(ids(true)).toEqual(["activity:brief", "audit"]);
});

it("keeps direct replies, notes, sent messages and founder mentions outside bot runs", () => {
const botRun = RunId.make("bot-run");
const conversation = [
Expand Down Expand Up @@ -5359,7 +5397,7 @@ describe("collapsing non-human activity", () => {
expect(activityPillIdForEntry(conversation, "note", context)).toBeUndefined();
});

it("opens for newly failed child runs and pending approvals, including grouped items", () => {
it("keeps groups with failed child runs and pending approvals collapsed but marked", () => {
const event = (
id: string,
item: Partial<OrchestrationV2TurnItem>,
Expand All @@ -5378,20 +5416,17 @@ describe("collapsing non-human activity", () => {
child.projectedItem,
],
};
const folded = collapseTimelineActivity([rows[2]!, group], new Set());
const pill = folded[0]!;
expect(pill).toMatchObject({ id: "activity:agent-1", expanded: true });
if (pill.kind !== "activity" || pill.attention === null)
throw new Error("Expected attention pill");
const dismissed = new Map([[pill.id, pill.attention]]);
expect(
collapseTimelineActivity([rows[2]!, group], new Set(), undefined, dismissed),
).toHaveLength(1);
expect(collapseTimelineActivity([rows[2]!, group], new Set())).toMatchObject([
{ id: "activity:agent-1", expanded: false, attention: true },
]);
expect(
collapseTimelineActivity([rows[2]!, group, approval], new Set(), undefined, dismissed).map(
collapseTimelineActivity([rows[2]!, group, approval], new Set(["activity:agent-1"])).map(
({ id }) => id,
),
).toEqual([pill.id, "agent-1", "child", "approval"]);
).toEqual(["activity:agent-1", "agent-1", "child", "approval"]);
expect(collapseTimelineActivity([rows[2]!], new Set())).toMatchObject([
{ expanded: false, attention: false },
]);
});

it("reveals a failed bot run and keeps the reply that raises a founder decision visible", () => {
Expand Down Expand Up @@ -5434,13 +5469,13 @@ describe("collapsing non-human activity", () => {
const entries = [relay, decision];
const failed = timelineActivityContext(entries, [{ id: botRun, status: "failed" }], false);
expect(collapseTimelineActivity(entries, new Set(), failed)[0]).toMatchObject({
expanded: true,
expanded: false,
attention: true,
});

const pending = timelineActivityContext(entries, [], false, time(1));
expect(collapseTimelineActivity(entries, new Set(), pending).map(({ id }) => id)).toEqual([
"activity:relay",
"relay",
"reply",
]);
});
Expand Down
48 changes: 42 additions & 6 deletions apps/web/src/components/chat/MessagesTimeline.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,15 @@ type MessagesTimelineRowContent =
count: number;
summary: string;
expanded: boolean;
attention: string | null;
/** The run holds a failure or a pending request; the collapsed pill says so. */
attention: boolean;
}
| {
/** The line between what the viewer had been shown and what arrived since. */
kind: "new-messages-divider";
id: string;
createdAt: string | null;
count: number;
}
| {
kind: "turn-fold";
Expand Down Expand Up @@ -2442,6 +2450,7 @@ export function timelineActivityContext(
runs: Parameters<typeof chatActivityContext>[1],
includeOtherActivity: boolean,
decisionRequestedAt?: string,
keepLatestReply = false,
): ChatActivityContext {
return chatActivityContext(
entries.map((entry) => ({
Expand All @@ -2463,6 +2472,7 @@ export function timelineActivityContext(
runs,
includeOtherActivity,
decisionRequestedAt,
keepLatestReply,
);
}

Expand Down Expand Up @@ -2532,7 +2542,6 @@ export function collapseTimelineActivity(
rows: MessagesTimelineRow[],
expandedIds: ReadonlySet<string>,
context?: ChatActivityContext,
dismissedAttention?: ReadonlyMap<string, string>,
): MessagesTimelineRow[] {
const collapsed: MessagesTimelineRow[] = [];
let hasActivity = false;
Expand Down Expand Up @@ -2571,9 +2580,8 @@ export function collapseTimelineActivity(
createdAt: run[0]!.createdAt,
count: run.length,
summary: activityUpdateSummary(run),
expanded:
expandedIds.has(id) || (attention !== null && dismissedAttention?.get(id) !== attention),
attention,
expanded: expandedIds.has(id),
attention: attention !== null,
};
collapsed.push(pill);
if (pill.expanded) {
Expand All @@ -2589,6 +2597,30 @@ export function collapseTimelineActivity(
return hasActivity ? collapsed : rows;
}

const NEW_MESSAGES_DIVIDER_ROW_ID = "new-messages-divider";

/** Puts the divider before the first row that appeared after `divider.afterCreatedAt`. */
export function insertNewMessagesDivider(
rows: MessagesTimelineRow[],
divider: { readonly afterCreatedAt: string; readonly count: number } | null | undefined,
): MessagesTimelineRow[] {
if (!divider) return rows;
const after = Date.parse(divider.afterCreatedAt);
if (Number.isNaN(after)) return rows;
const index = rows.findIndex((row) => row.createdAt != null && Date.parse(row.createdAt) > after);
if (index < 0) return rows;
return [
...rows.slice(0, index),
{
kind: "new-messages-divider",
id: NEW_MESSAGES_DIVIDER_ROW_ID,
createdAt: rows[index]!.createdAt,
count: divider.count,
},
...rows.slice(index),
];
}

/** The pill hiding `entryId`, if one does, so a search hit or a restored scroll position can open it. */
export function activityPillIdForEntry(
rows: MessagesTimelineRow[],
Expand Down Expand Up @@ -3083,10 +3115,14 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
a.createdAt === ba.createdAt &&
a.count === ba.count &&
a.summary === ba.summary &&
a.expanded === ba.expanded
a.expanded === ba.expanded &&
a.attention === ba.attention
);
}

case "new-messages-divider":
return a.createdAt === (b as typeof a).createdAt && a.count === (b as typeof a).count;

case "message": {
const bm = b as typeof a;
return (
Expand Down
Loading
Loading