diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index a83f96fbae2d6..1648512fc3bba 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -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"; @@ -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, @@ -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} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 4fe4ec46e43f9..35bcba6ebba8d 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -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("[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."; diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 248717437a260..14a970a5fcf95 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -33,6 +33,7 @@ import { collapseTimelineActivity, activityUpdateSummary, activityPillIdForEntry, + insertNewMessagesDivider, timelineActivityContext, timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, @@ -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 = [ @@ -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, @@ -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", () => { @@ -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", ]); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index e2a2129bee274..7e12f2296f645 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -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"; @@ -2442,6 +2450,7 @@ export function timelineActivityContext( runs: Parameters[1], includeOtherActivity: boolean, decisionRequestedAt?: string, + keepLatestReply = false, ): ChatActivityContext { return chatActivityContext( entries.map((entry) => ({ @@ -2463,6 +2472,7 @@ export function timelineActivityContext( runs, includeOtherActivity, decisionRequestedAt, + keepLatestReply, ); } @@ -2532,7 +2542,6 @@ export function collapseTimelineActivity( rows: MessagesTimelineRow[], expandedIds: ReadonlySet, context?: ChatActivityContext, - dismissedAttention?: ReadonlyMap, ): MessagesTimelineRow[] { const collapsed: MessagesTimelineRow[] = []; let hasActivity = false; @@ -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) { @@ -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[], @@ -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 ( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 366ca5ebce163..c4413df2a9f74 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -97,6 +97,7 @@ import { liveAnswerPreview, collapseTimelineActivity, activityPillIdForEntry, + insertNewMessagesDivider, timelineActivityContext, type MessagesTimelineRow, type TimelineLatestRun, @@ -111,6 +112,7 @@ import { cn } from "~/lib/utils"; import { type TimestampFormat } from "@t3tools/contracts/settings"; import { type HandoffTimelineRun } from "./V2LifecycleRow"; import { TimelineSystemDivider } from "./TimelineSystemDivider"; +import { NewSinceLastSeenPill } from "./TimelineOverlays"; import { forwardWheelToTimeline } from "./timelineMinimapWheel"; import { TimelineMinimap } from "./TimelineMinimap"; @@ -352,8 +354,12 @@ interface MessagesTimelineProps { * Off by default; a standing thread turns it on. */ collapseActivity?: boolean; + /** Messages that arrived after the place the viewer had been shown; draws a divider and a jump pill. */ + unseenDivider?: { readonly afterMessageId: MessageId; readonly count: number } | null; includeOtherActivity?: boolean; decisionRequestedAt?: string | undefined; + /** The thread is filed in a founder's inbox; the newest agent-run reply stays unfolded. */ + inFounderInbox?: boolean; /** Person messages name which founder sent them. */ sharedThread?: boolean; } @@ -404,8 +410,10 @@ const ConversationTimeline = memo(function ConversationTimeline({ findNavigationId = 0, findSender = null, collapseActivity = true, + unseenDivider = null, includeOtherActivity = false, decisionRequestedAt, + inFounderInbox = false, sharedThread = false, latestRun, announcedRun = null, @@ -629,15 +637,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ preserveDisclosurePosition(row.id); setExpandedActivity((existing) => { const ids = new Set(existing.threadKey === listIdentityKey ? existing.ids : []); - const dismissed = new Map(existing.threadKey === listIdentityKey ? existing.dismissed : []); - if (row.expanded) { - ids.delete(row.id); - if (row.attention !== null) dismissed.set(row.id, row.attention); - } else { - ids.add(row.id); - dismissed.delete(row.id); - } - return { threadKey: listIdentityKey, ids, dismissed }; + if (row.expanded) ids.delete(row.id); + else ids.add(row.id); + return { threadKey: listIdentityKey, ids }; }); }; const onToggleTurnFold = (runId: RunId) => { @@ -845,23 +847,24 @@ const ConversationTimeline = memo(function ConversationTimeline({ // kept would hide the very rows it was asked to show. const collapseRows = collapseActivity && findSender === null; const chatter = collapseRows - ? timelineActivityContext(timelineEntries, runsProp, includeOtherActivity, decisionRequestedAt) + ? timelineActivityContext( + timelineEntries, + runsProp, + includeOtherActivity, + decisionRequestedAt, + inFounderInbox, + ) : undefined; const [expandedActivity, setExpandedActivity] = useState<{ readonly threadKey: string; readonly ids: ReadonlySet; - readonly dismissed: ReadonlyMap; - }>(() => ({ threadKey: listIdentityKey, ids: new Set(), dismissed: new Map() })); + }>(() => ({ threadKey: listIdentityKey, ids: new Set() })); // Pill ids repeat across threads (`activity:` plus a message id can coincide, // and a live turn's rows share constant ids), so expansion belongs to one thread. const expandedActivityIds = expandedActivity.threadKey === listIdentityKey ? expandedActivity.ids : new Set(); if (collapseRows && expandedActivity.threadKey !== listIdentityKey) { - setExpandedActivity({ - threadKey: listIdentityKey, - ids: expandedActivityIds, - dismissed: new Map(), - }); + setExpandedActivity({ threadKey: listIdentityKey, ids: expandedActivityIds }); } // A search hit or a restored scroll position inside a collapsed run opens that // run, the way a find match opens the turn fold that hides it. @@ -884,14 +887,25 @@ const ConversationTimeline = memo(function ConversationTimeline({ ids.add(revealedPillId); setExpandedActivity({ ...expandedActivity, ids }); } - const rows = collapseRows - ? collapseTimelineActivity( - senderRows, - expandedActivityIds, - chatter, - expandedActivity.threadKey === listIdentityKey ? expandedActivity.dismissed : undefined, - ) - : senderRows; + // Rows carry the time their turn item started, which can trail the message's own stamp (a queued + // message), so the line is placed by the anchor's timeline entry rather than the message record. + const dividerAnchorAt = + unseenDivider === null || findSender !== null + ? undefined + : timelineEntries.find( + (entry) => entry.kind === "message" && entry.message.id === unseenDivider.afterMessageId, + )?.createdAt; + const rows = insertNewMessagesDivider( + collapseRows ? collapseTimelineActivity(senderRows, expandedActivityIds, chatter) : senderRows, + unseenDivider === null || dividerAnchorAt === undefined + ? null + : { afterCreatedAt: dividerAnchorAt, count: unseenDivider.count }, + ); + const dividerIndex = rows.findIndex((row) => row.kind === "new-messages-divider"); + const dividerKey = + dividerIndex < 0 || unseenDivider === null + ? null + : `${listIdentityKey}\0${unseenDivider.afterMessageId}`; const matchedApprovalRequestIds = new Set(); for (const row of pendingApprovalRequestIds.size > 0 ? rows : []) { const entries = @@ -930,6 +944,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ const listOpenedOn = nextOpening.mounted ? nextOpening.identity : null; const viewportRef = useRef(null); const navigateTimeline = () => viewportRef.current?.navigate({ releasesFollow: true }); + const restoreReady = restoringThreadPosition && rows.length > 0; // Z: syncs LegendList's scroll position with which thread it shows. The list // is not keyed per thread and reports no "new data" event, and the restore @@ -1022,6 +1037,12 @@ const ConversationTimeline = memo(function ConversationTimeline({ const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0); const [minimapCurrentIndex, setMinimapCurrentIndex] = useState(null); const [minimapAtEnd, setMinimapAtEnd] = useState(false); + const [dividerPlace, setDividerPlace] = useState<{ + readonly key: string; + readonly place: "above" | "visible" | "below"; + } | null>(null); + // Once the divider has been on screen or the pill was used, the pill stays gone for this visit. + const [settledDividerKey, setSettledDividerKey] = useState(null); const handleAnchorReady = (info: { anchorIndex: number | undefined }) => { if (anchorMessageId !== null && info.anchorIndex !== undefined) { onAnchorReady(anchorMessageId, info.anchorIndex); @@ -1050,10 +1071,27 @@ const ConversationTimeline = memo(function ConversationTimeline({ size: true, }; + const showNewSincePill = + dividerKey !== null && + unseenDivider !== null && + settledDividerKey !== dividerKey && + dividerPlace?.key === dividerKey && + dividerPlace.place !== "visible"; + const jumpToNewMessages = () => { + if (dividerKey === null) return; + setSettledDividerKey(dividerKey); + navigateTimeline(); + void listRef.current?.scrollToIndex({ + index: dividerIndex, + animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches, + viewOffset: TIMELINE_MINIMAP_TARGET_OFFSET, + }); + }; + const refreshMinimap = useStableCallback(() => { const state = listRef.current?.getState?.(); if (restoringThreadPosition || state?.data !== rows) return; - if (!state || minimapItems.length === 0) { + if (!state || (minimapItems.length === 0 && dividerKey === null)) { return; } @@ -1071,6 +1109,21 @@ const ConversationTimeline = memo(function ConversationTimeline({ firstBufferedRow.getBoundingClientRect().top : state.scroll; const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll }); + if (dividerKey !== null && visibleRange.start !== null && visibleRange.end !== null) { + const place = + dividerIndex < visibleRange.start + ? "above" + : dividerIndex > visibleRange.end + ? "below" + : "visible"; + setDividerPlace((current) => + current?.key === dividerKey && current.place === place + ? current + : { key: dividerKey, place }, + ); + if (place === "visible") setSettledDividerKey(dividerKey); + } + if (minimapItems.length === 0) return; for (const [index, item] of minimapItems.entries()) { const strip = minimapStripMap.get(item.id); const inView = isTimelineMinimapTurnVisible( @@ -1122,6 +1175,10 @@ const ConversationTimeline = memo(function ConversationTimeline({ useLayoutEffect(() => { if (!restoringThreadPosition) scheduleMinimapRefresh(); }, [restoringThreadPosition, scheduleMinimapRefresh]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a divider that appears or moves needs its place measured without waiting for a scroll + useLayoutEffect(() => { + if (dividerKey !== null && !restoringThreadPosition) scheduleMinimapRefresh(); + }, [dividerKey, restoringThreadPosition, scheduleMinimapRefresh]); // The measurement the last remember wrote, so a follow release can rewrite // it without reading render state from a listener. @@ -1621,6 +1678,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ ListHeaderComponent={listHeader} ListFooterComponent={timelineListFooter} /> + {showNewSincePill ? ( + setSettledDividerKey(dividerKey)} + /> + ) : null} ) : null} {row.kind === "activity" ? : null} + {row.kind === "new-messages-divider" ? ( +
+ +
+ ) : null} {row.kind === "turn-fold" ? : null} {row.kind === "attempt-fold" ? : null} {row.kind === "context-compaction" ? : null} @@ -1979,6 +2049,12 @@ function ActivityTimelineRow({ row }: { row: Extract {row.summary} + {row.attention ? ( + + + Needs attention + + ) : null} ); diff --git a/apps/web/src/components/chat/TimelineOverlays.tsx b/apps/web/src/components/chat/TimelineOverlays.tsx index 0fcff19e27554..72bc91257967e 100644 --- a/apps/web/src/components/chat/TimelineOverlays.tsx +++ b/apps/web/src/components/chat/TimelineOverlays.tsx @@ -1,4 +1,4 @@ -import { ChevronDownIcon, PaperclipIcon } from "lucide-react"; +import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, PaperclipIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; @@ -53,3 +53,45 @@ export function ScrollToEndButton(props: { ); } + +/** Discord's "new messages" bar: sits at the top edge while the divider is off screen. */ +export function NewSinceLastSeenPill(props: { + readonly count: number; + readonly direction: "up" | "down"; + readonly onJump: () => void; + readonly onDismiss: () => void; +}) { + const Arrow = props.direction === "up" ? ArrowUpIcon : ArrowDownIcon; + return ( +
+
+ + +
+
+ ); +} diff --git a/apps/web/src/components/chat/useUnseenDivider.ts b/apps/web/src/components/chat/useUnseenDivider.ts new file mode 100644 index 0000000000000..1d7304f832a52 --- /dev/null +++ b/apps/web/src/components/chat/useUnseenDivider.ts @@ -0,0 +1,37 @@ +import { + resolveUnseenDivider, + type SeenMessage, + type UnseenDivider, +} from "@t3tools/client-runtime/seen-marker"; +import type { Founder, MessageId } from "@t3tools/contracts"; +import { useState } from "react"; + +const NO_MESSAGES: ReadonlyArray = []; + +/** + * Where "new since you last looked" starts, fixed at the place this founder had been shown when the + * thread opened. Scrolling moves the stored place for next time, not this visit's line. + */ +export function useUnseenDivider(input: { + readonly threadKey: string | null; + readonly viewer: Founder | null; + readonly shellReady: boolean; + readonly lastSeenMessageId: MessageId | null; + readonly messages: ReadonlyArray | undefined; +}): UnseenDivider | null { + const key = + input.threadKey !== null && input.viewer !== null ? `${input.viewer}:${input.threadKey}` : null; + const [place, setPlace] = useState<{ + readonly key: string; + readonly messageId: MessageId | null; + } | null>(null); + if (key !== null && input.shellReady && place?.key !== key) { + setPlace({ key, messageId: input.lastSeenMessageId }); + } + const anchorId = place?.key === key ? place.messageId : null; + if (anchorId === null) return null; + return resolveUnseenDivider({ + messages: input.messages ?? NO_MESSAGES, + lastSeenMessageId: anchorId, + }); +} diff --git a/apps/web/src/hooks/useSeenMarkerTracking.test.ts b/apps/web/src/hooks/useSeenMarkerTracking.test.ts index cc36ea4fa150c..88832fdbbdfc7 100644 --- a/apps/web/src/hooks/useSeenMarkerTracking.test.ts +++ b/apps/web/src/hooks/useSeenMarkerTracking.test.ts @@ -156,6 +156,29 @@ describe("timeline seen sampling", () => { vi.unstubAllGlobals(); }); + it("marks the newest settled message once the list rests at the bottom", () => { + const clock = manualTimers(); + const page = host(); + const latestId = MessageId.make("message-latest"); + const sampling = startSeenMarkerSampling({ + host: page.samplingHost, + threadKey: "env:thread", + getScrollNode: () => ({ + ...scrollNode(), + scrollTop: 600, + scrollHeight: 1000, + clientHeight: 400, + }), + getMessages: () => [...messages, { id: latestId, role: "assistant" }], + now: () => new Date(seenAt), + timers: clock.timers, + }); + page.flush(); + clock.fireNext(); + expect(buildSeenMarker("env:thread")).toEqual({ lastSeenMessageId: latestId, seenAt }); + sampling.dispose(); + }); + it("does not mark a hidden or blurred window", () => { const clock = manualTimers(); const page = host(); diff --git a/apps/web/src/hooks/useSeenMarkerTracking.ts b/apps/web/src/hooks/useSeenMarkerTracking.ts index c526f491b188a..954831e142722 100644 --- a/apps/web/src/hooks/useSeenMarkerTracking.ts +++ b/apps/web/src/hooks/useSeenMarkerTracking.ts @@ -22,6 +22,9 @@ export interface SeenSamplingHost { } export interface SeenScrollNode { + readonly scrollTop?: number; + readonly scrollHeight?: number; + readonly clientHeight?: number; getBoundingClientRect(): SeenRect; querySelectorAll(selector: string): Iterable<{ getBoundingClientRect(): SeenRect; @@ -41,6 +44,17 @@ export function visibleMessageIds(node: SeenScrollNode): MessageId[] { return ids; } +const SCROLLED_TO_END_SLACK_PX = 8; + +/** Reaching the bottom shows the newest message even when a collapsed group hides it from the DOM. */ +function isScrolledToEnd(node: SeenScrollNode) { + const { scrollTop, scrollHeight, clientHeight } = node; + if (scrollTop === undefined || scrollHeight === undefined || clientHeight === undefined) { + return false; + } + return scrollHeight - scrollTop - clientHeight <= SCROLLED_TO_END_SLACK_PX; +} + export function startSeenMarkerSampling(input: { host: SeenSamplingHost; threadKey: string; @@ -71,7 +85,14 @@ export function startSeenMarkerSampling(input: { const sample = () => { const node = input.getScrollNode(); const active = doc.visibilityState === "visible" && doc.hasFocus(); - session.update({ active, visibleIds: active && node ? visibleMessageIds(node) : [] }); + const visibleIds = + active && node + ? [ + ...visibleMessageIds(node), + ...(isScrolledToEnd(node) ? input.getMessages().map((message) => message.id) : []), + ] + : []; + session.update({ active, visibleIds }); }; const requestSample = () => { if (frame !== null) return; diff --git a/packages/client-runtime/src/chatActivity.ts b/packages/client-runtime/src/chatActivity.ts index 77f3e32ba6eb9..ea9e739fac80a 100644 --- a/packages/client-runtime/src/chatActivity.ts +++ b/packages/client-runtime/src/chatActivity.ts @@ -51,6 +51,11 @@ export function chatActivityContext( runs: ReadonlyArray<{ id: RunId; status?: OrchestrationV2RunStatus }>, includeOtherActivity: boolean, decisionRequestedAt?: string, + /** + * The thread sits in a founder's inbox, so the newest reply of an agent-started run is what put + * it there. Folding it would leave the inbox row looking empty until the founder expands it. + */ + keepLatestReply = false, ) { const agentRuns = new Set(); const directRuns = new Set(); @@ -62,6 +67,7 @@ export function chatActivityContext( else attentionByRun.set(runId, new Set([id])); }; let firstReplyAfterDecision: RunId | undefined; + let latestReplyRun: RunId | undefined; let pendingDecision: { runId: RunId; startedAt: string } | undefined; for (const { createdAt, runId, message, item } of entries) { if (!runId) continue; @@ -89,6 +95,7 @@ export function chatActivityContext( pendingDecision = { runId, startedAt }; } } + if (message?.role === "assistant" && !message.humanNote) latestReplyRun = runId; if (decisionRequestedAt && message?.role === "assistant" && createdAt >= decisionRequestedAt) { firstReplyAfterDecision ??= runId; } @@ -101,6 +108,7 @@ export function chatActivityContext( } } for (const id of directRuns) agentRuns.delete(id); + if (keepLatestReply && latestReplyRun !== undefined) decisionRuns.add(latestReplyRun); for (const run of runs) { if (run.status === "failed") addAttention(run.id, run.id); } diff --git a/packages/client-runtime/src/seenMarker.test.ts b/packages/client-runtime/src/seenMarker.test.ts index eac45af2b4ba9..2f9d382d0a89c 100644 --- a/packages/client-runtime/src/seenMarker.test.ts +++ b/packages/client-runtime/src/seenMarker.test.ts @@ -7,6 +7,7 @@ import { createSeenMarkerSession, pickNewestMessageId, resetSeenMarkersForTest, + resolveUnseenDivider, type SeenTimers, } from "./seenMarker.ts"; @@ -192,6 +193,32 @@ describe("catch-up offer", () => { }); }); +describe("unseen divider", () => { + const thread = [ + { id: MessageId.make("m1"), role: "user" }, + { id: MessageId.make("m2"), role: "assistant" }, + { id: MessageId.make("m3"), role: "user" }, + { id: MessageId.make("m4"), role: "assistant" }, + { id: MessageId.make("m5"), role: "assistant", streaming: true }, + ]; + + it("counts settled replies after the stored place and anchors on its id", () => { + expect( + resolveUnseenDivider({ messages: thread, lastSeenMessageId: MessageId.make("m2") }), + ).toEqual({ afterMessageId: MessageId.make("m2"), count: 1 }); + }); + + it("draws nothing when nothing is new or the place is unknown", () => { + expect( + resolveUnseenDivider({ messages: thread, lastSeenMessageId: MessageId.make("m4") }), + ).toBeNull(); + expect( + resolveUnseenDivider({ messages: thread, lastSeenMessageId: MessageId.make("gone") }), + ).toBeNull(); + expect(resolveUnseenDivider({ messages: thread, lastSeenMessageId: null })).toBeNull(); + }); +}); + describe("per founder", () => { it("keeps a separate place for each founder of one thread", () => { const clock = manualTimers(); diff --git a/packages/client-runtime/src/seenMarker.ts b/packages/client-runtime/src/seenMarker.ts index 9bbca3a536697..f3c482d38b069 100644 --- a/packages/client-runtime/src/seenMarker.ts +++ b/packages/client-runtime/src/seenMarker.ts @@ -130,6 +130,30 @@ export function catchUpOffer(input: { export const CATCH_ME_UP_TEXT = "Catch me up"; +/** Where "new since you last looked" starts: after the message `afterMessageId`. */ +export interface UnseenDivider { + readonly afterMessageId: MessageId; + readonly count: number; +} + +/** + * The line between what this founder had been shown and what arrived since. A place the + * thread no longer holds draws nothing, since guessing would mislabel old messages as new. + */ +export function resolveUnseenDivider(input: { + readonly messages: ReadonlyArray; + readonly lastSeenMessageId: MessageId | null | undefined; +}): UnseenDivider | null { + const afterMessageId = input.lastSeenMessageId; + if (afterMessageId == null) return null; + const index = input.messages.findIndex((message) => message.id === afterMessageId); + if (index < 0) return null; + const count = input.messages + .slice(index + 1) + .filter((message) => message.role === "assistant" && message.streaming !== true).length; + return count === 0 ? null : { afterMessageId, count }; +} + export function buildSeenMarker( threadKey: string, founder?: Founder | null, diff --git a/packages/contracts/src/botAttention.test.ts b/packages/contracts/src/botAttention.test.ts index e9ca8205a4b35..cc65a9a97abaa 100644 --- a/packages/contracts/src/botAttention.test.ts +++ b/packages/contracts/src/botAttention.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { mentionedFounders, resolveBotAttention } from "./botAttention.ts"; +import { + attentionMentionsFromText, + mentionedFounders, + resolveBotAttention, +} from "./botAttention.ts"; import { makeThreadInbox, type ThreadInbox } from "./threadInbox.ts"; const bot = { kind: "agent", id: "lead" } as const; @@ -24,6 +28,23 @@ describe("mentionedFounders", () => { expect(mentionedFounders("@Jeff's draft")).toEqual(["jeff"]); expect(mentionedFounders(null)).toEqual([]); }); + + it("ignores addresses, code and names that run on", () => { + expect(mentionedFounders("sent by claude@kameron.smith@closura.ai")).toEqual([]); + expect(mentionedFounders("mail user@jeff.example.com")).toEqual([]); + expect(mentionedFounders("ping @kameron.smith or @jeff-bot")).toEqual([]); + expect(mentionedFounders("run `@kameron` then `echo @jeff`")).toEqual([]); + expect(mentionedFounders("```\nTo: @kameron\n@jeff\n```\ndone")).toEqual([]); + expect(mentionedFounders("```\nunclosed @jeff")).toEqual([]); + }); + + it("still counts a real ping beside code, punctuation or a line start", () => { + expect(mentionedFounders("`code` then @Kameron.")).toEqual(["kameron"]); + expect(mentionedFounders("(@Jeff) please look")).toEqual(["jeff"]); + expect(mentionedFounders("@kameron\nand\n@jeff,")).toEqual(["kameron", "jeff"]); + expect(mentionedFounders("```\ncode\n```\n@Jeff review")).toEqual(["jeff"]); + expect(attentionMentionsFromText("addr claude@kameron.smith@closura.ai")).toBeUndefined(); + }); }); describe("resolveBotAttention", () => { diff --git a/packages/contracts/src/botAttention.ts b/packages/contracts/src/botAttention.ts index eec5d220f9ada..0f3539be91130 100644 --- a/packages/contracts/src/botAttention.ts +++ b/packages/contracts/src/botAttention.ts @@ -23,13 +23,18 @@ const JOINT_SIGN_OFF_FOUNDERS: readonly Founder[] = Founder.literals; /** How much of a message is scanned for an @-mention. The shell stores the names, not the text. */ export const ATTENTION_MENTION_TEXT_LIMIT = 2000; -const FOUNDER_MENTION = /@(kameron|jeff)\b/gi; +// A ping is `@name` standing alone: not the tail of an address (`claude@kameron.smith@…`), and not a +// name that continues into a dotted or hyphenated word. A sentence-ending `@Kameron.` still counts. +const FOUNDER_MENTION = /(? { if (!text) return []; const found = new Set(); - for (const match of text.matchAll(FOUNDER_MENTION)) { + for (const match of text.replace(CODE_SPAN, " ").matchAll(FOUNDER_MENTION)) { const name = match[1]?.toLowerCase(); if (name === "kameron" || name === "jeff") found.add(name); }