diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b3a48acf15393..ba0f370de9dca 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -402,6 +402,10 @@ import { makeThreadErrorSetter, } from "./ChatView.logic"; +const activityCollapsedThreadsSchema = Schema.NullOr( + Schema.Record(Schema.String, Schema.Boolean), +); + const EMPTY_SEEN_MESSAGES: ReadonlyArray = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = []; @@ -1818,6 +1822,24 @@ export default function ChatView(props: ChatViewProps) { selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), ); const isStandingBot = activeStanding !== null; + // A coordinator thread buries the founder under agent relays, so those collapse + // until he asks for everything. Remembered per thread; ordinary threads stay flat. + const [activityCollapsedThreads, setActivityCollapsedThreads] = useLocalStorage( + "t3code:activity-collapsed-threads", + null, + activityCollapsedThreadsSchema, + ); + const activityCollapsed = + activeThreadKey === null || + activityCollapsedThreads === null || + activityCollapsedThreads[activeThreadKey] !== false; + const toggleActivityCollapsed = () => { + if (activeThreadKey === null) return; + setActivityCollapsedThreads((stored) => ({ + ...stored, + [activeThreadKey]: !activityCollapsed, + })); + }; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- folds a bot's details card (branch, worktree, PR) the first time this client shows that bot; the panel toggle reopens it and that choice persists useEffect(() => { if (!isStandingBot || !activeThreadRef || !activeThreadKey) return; @@ -3425,6 +3447,11 @@ export default function ChatView(props: ChatViewProps) { : {})} {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})} standing={activeStanding} + activityCollapsed={ + isStandingBot && activeThreadKey !== null + ? { on: activityCollapsed, onToggle: toggleActivityCollapsed } + : null + } /> )} @@ -3482,6 +3509,7 @@ export default function ChatView(props: ChatViewProps) { entriesInput={timelineEntriesInput} draftEntries={isServerThread ? null : draftTimelineEntries} activeThreadKey={activeThreadKey} + collapseActivity={isStandingBot && activityCollapsed} syncing={threadSyncPhase !== null} detailLoading={threadDetailLoading} citationRequest={citationRequest} diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index a92dd8d998aae..d79b59214744c 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -61,6 +61,11 @@ interface ChatHeaderProps { onFindInThread?: ((threadRef: ScopedThreadRef) => void) | undefined; /** A standing bot shows who it is instead of the project/thread breadcrumb. */ standing?: ThreadStanding | null | undefined; + /** + * Collapse agent, automation and system activity, or null when the thread has + * no toggle. A standing thread passes it. + */ + activityCollapsed?: { readonly on: boolean; readonly onToggle: () => void } | null | undefined; } function resolveRenameCommit(input: { @@ -87,6 +92,7 @@ export const ChatHeader = memo(function ChatHeader({ onOpenProjectSettings, onFindInThread, standing, + activityCollapsed = null, }: ChatHeaderProps) { const activeProjectName = activeProject?.isScratch ? "No project" : activeProject?.title; const activeProjectCwd = activeProject?.workspaceRoot ?? null; @@ -282,6 +288,7 @@ export const ChatHeader = memo(function ChatHeader({ ) : null} + {isServerThread ? : null} ); @@ -439,6 +446,46 @@ export const ChatHeader = memo(function ChatHeader({ {isServerThread ? : null} + ); }); + +/** + * Switches the timeline between the founder's conversation and everything that + * happened in the thread. Absent when the thread has nothing to collapse. + */ +function ActivityViewToggle({ + collapsed, +}: { + collapsed: { readonly on: boolean; readonly onToggle: () => void } | null; +}) { + if (collapsed === null) return null; + const label = collapsed.on ? "Human conversation" : "All activity"; + return ( + + + } + > + {label} + + + {collapsed.on + ? "Agent, automation and system updates are collapsed. Click to show everything." + : "Showing everything. Click to keep only your messages and the replies to them."} + + + ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 8d05c43e39d43..0859a66e9e9b5 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1,4 +1,4 @@ -import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts"; +import { ScheduledTaskId, ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts"; import { CheckpointRef, NodeId, @@ -30,6 +30,9 @@ import { computeStableMessagesTimelineRows, deriveMessagesTimelineRows, filterTimelineRowsBySender, + collapseTimelineActivity, + activityUpdateSummary, + activityPillIdForEntry, timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, deriveMessagesTimelineRowsWithState, @@ -5223,3 +5226,181 @@ describe("message senders in the timeline", () => { expect(kameron[1]).toMatchObject({ groupedWithPrevious: false }); }); }); + +describe("collapsing non-human activity", () => { + const runId = RunId.make("activity-run"); + const time = (second: number) => new Date(Date.UTC(2026, 0, 2, 0, 0, second)).toISOString(); + const messageRow = ( + id: string, + second: number, + extra: Record = {}, + ): MessagesTimelineRow => ({ + kind: "message", + id, + createdAt: time(second), + showAssistantMeta: false, + showAssistantCopyButton: false, + assistantCopyStreaming: false, + message: { + id: MessageId.make(id), + role: "user", + text: id, + runId, + createdAt: time(second), + updatedAt: time(second), + streaming: false, + ...extra, + }, + }); + const workRow = (id: string, second: number): MessagesTimelineRow => ({ + kind: "work", + id, + createdAt: time(second), + groupedEntries: [], + isExpandedToolGroup: false, + }); + const person = (founder: "kameron" | "jeff") => ({ + sentBy: { + sessionId: AuthSessionId.make(`session:${founder}`), + device: "laptop", + deviceType: "desktop" as const, + founder, + }, + }); + const rows: MessagesTimelineRow[] = [ + messageRow("kameron", 0, person("kameron")), + messageRow("reply", 1, { role: "assistant" }), + messageRow("agent-1", 2, { createdBy: "agent", senderThreadId: ThreadId.make("child") }), + workRow("work-1", 3), + messageRow("agent-2", 4, { createdBy: "agent" }), + messageRow("jeff", 5, person("jeff")), + messageRow("system-1", 6, { createdBy: "system" }), + ]; + + it("collapses the activity between human turns into one pill", () => { + const collapsed = collapseTimelineActivity(rows, new Set()); + expect(collapsed.map((row) => row.id)).toEqual([ + "kameron", + "reply", + "activity:reply", + "jeff", + "activity:jeff", + ]); + expect(collapsed[2]).toMatchObject({ + kind: "activity", + count: 3, + summary: "2 agent updates", + expanded: false, + }); + expect(collapsed[4]).toMatchObject({ kind: "activity", count: 1, summary: "1 system notice" }); + }); + + it("puts the collapsed rows back exactly when the pill expands", () => { + const expanded = collapseTimelineActivity(rows, new Set(["activity:reply"])); + expect(expanded.map((row) => row.id)).toEqual([ + "kameron", + "reply", + "activity:reply", + "agent-1", + "work-1", + "agent-2", + "jeff", + "activity:jeff", + ]); + expect(expanded[2]).toMatchObject({ expanded: true }); + }); + + it("keeps a thread of only activity as one pill", () => { + const activity = rows.slice(2, 5); + expect(collapseTimelineActivity(activity, new Set()).map((row) => row.id)).toEqual([ + "activity:agent-1", + ]); + expect(activityUpdateSummary(activity)).toBe("2 agent updates"); + }); + + it("names mixed activity by kind", () => { + expect( + activityUpdateSummary([ + messageRow("a", 0, { createdBy: "agent" }), + messageRow("b", 1, { createdBy: "system" }), + messageRow("c", 2, { scheduledTaskId: ScheduledTaskId.make("task-1") }), + ]), + ).toBe("1 agent update and 1 system notice and 1 automation"); + }); + + it("keeps a plan, a render and viewed images on screen", () => { + const plan: MessagesTimelineRow = { + kind: "proposed-plan", + id: "plan-1", + createdAt: time(7), + proposedPlan: { + id: "plan-1" as never, + runId, + planMarkdown: "Do the thing", + status: "active", + createdAt: time(7), + updatedAt: time(7), + }, + }; + const images: MessagesTimelineRow = { + kind: "viewed-images", + id: "images-1", + createdAt: time(8), + paths: ["shot.png"], + }; + const withCards = [rows[0]!, plan, rows[2]!, images, rows[5]!]; + expect(collapseTimelineActivity(withCards, new Set()).map((row) => row.id)).toEqual([ + "kameron", + "plan-1", + "activity:plan-1", + "images-1", + "jeff", + ]); + }); + + it("keeps a secret request and a link request on screen", () => { + const request = (id: string, type: "secret_request" | "link_request"): MessagesTimelineRow => ({ + kind: "event", + id, + createdAt: time(9), + projectedItem: { item: { type } } as never, + }); + const withRequests = [ + rows[0]!, + rows[2]!, + request("secret-1", "secret_request"), + request("link-1", "link_request"), + rows[5]!, + ]; + expect(collapseTimelineActivity(withRequests, new Set()).map((row) => row.id)).toEqual([ + "kameron", + "activity:kameron", + "secret-1", + "link-1", + "jeff", + ]); + }); + + it("names the pill after the message it follows, so streaming rows do not rename it", () => { + const grown = [...rows.slice(0, 5), workRow("work-2", 9), ...rows.slice(5)]; + expect(collapseTimelineActivity(grown, new Set()).map((row) => row.id)).toEqual( + collapseTimelineActivity(rows, new Set()).map((row) => row.id), + ); + }); + + it("finds the pill hiding a row", () => { + expect(activityPillIdForEntry(rows, "work-1")).toBe("activity:reply"); + expect(activityPillIdForEntry(rows, "system-1")).toBe("activity:jeff"); + expect(activityPillIdForEntry(rows, "kameron")).toBeUndefined(); + expect(activityPillIdForEntry(rows.slice(2, 5), "agent-2")).toBe("activity:agent-1"); + }); + + it("leaves a human conversation untouched", () => { + const conversation = [rows[0]!, rows[1]!, rows[5]!]; + expect(collapseTimelineActivity(conversation, new Set()).map((row) => row.id)).toEqual([ + "kameron", + "reply", + "jeff", + ]); + }); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index c4869c99cea24..f222edfb84a4c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -572,6 +572,18 @@ type MessagesTimelineRowContent = createdAt: string; paths: ReadonlyArray; } + | { + /** + * Consecutive non-human turns (agent relays, automations, system notices + * and the work between them) collapsed into one expandable pill. + */ + kind: "activity"; + id: string; + createdAt: string | null; + count: number; + summary: string; + expanded: boolean; + } | { kind: "turn-fold"; deferredWorkItemIds?: ReadonlyArray; @@ -2387,6 +2399,148 @@ export function deriveMessagesTimelineRows(input: { * The timeline with only `sender`'s messages, for find's "From" filter. Tool calls, plans and * other rows say nothing about who sent them, so they drop out too. */ +/** + * Rows that stay on screen in a standing thread: a person's message, a guest's, + * the model's reply, and the cards a turn hands the reader (a plan to accept, + * a render, a message the agent sent on). Work logs, agent relays, automations + * and T3 Code notices collapse instead. + */ +const KEPT_ACTIVITY_ROW_KINDS = new Set([ + "proposed-plan", + "html-render", + "mcp-app", + "sent-message", + "viewed-images", +]); + +export function timelineRowIsHumanConversation(row: MessagesTimelineRow): boolean { + if (KEPT_ACTIVITY_ROW_KINDS.has(row.kind)) return true; + // A secret or a link is answered only on its own card, so it must not fold away. + if ( + row.kind === "event" && + (row.projectedItem.item.type === "secret_request" || + row.projectedItem.item.type === "link_request") + ) { + return true; + } + if (row.kind !== "message" && row.kind !== "assistant-meta") return false; + const sender = resolveMessageSender(row.message); + return sender.kind === "person" || sender.kind === "guest" || sender.kind === "model"; +} + +/** + * The pill's key. Anchored to the human message the run sits after, or to the + * first row when the thread opens on activity, so the key survives rows + * streaming in and earlier history loading above it. A live turn's own rows use + * constant ids that vanish when the turn settles, so they never anchor a pill. + */ +function activityPillId(anchor: MessagesTimelineRow | undefined, run: MessagesTimelineRow[]): string { + return `activity:${anchor?.id ?? run[0]!.id}`; +} + +/** + * The short word for one kind of collapsed activity, pluralized with a count. + * Kinds the row does not record stay "update". + */ +function activityUpdateWord(row: MessagesTimelineRow): string { + if (row.kind !== "message" && row.kind !== "assistant-meta") return "update"; + switch (resolveMessageSender(row.message).kind) { + case "agent": + return "agent update"; + case "automation": + return "automation"; + case "system": + return "system notice"; + default: + return "update"; + } +} + +/** `14 agent updates`, `3 automations and 1 system notice`. */ +export function activityUpdateSummary(rows: ReadonlyArray): string { + const counts = new Map(); + const order: string[] = []; + for (const row of rows) { + if (row.kind !== "message" && row.kind !== "assistant-meta") continue; + const word = activityUpdateWord(row); + if (!counts.has(word)) order.push(word); + counts.set(word, (counts.get(word) ?? 0) + 1); + } + if (order.length === 0) { + return rows.length === 1 ? "1 update" : `${rows.length} updates`; + } + return order + .map((word) => { + const count = counts.get(word) ?? 0; + const plural = + word === "automation" ? (count === 1 ? "automation" : "automations") : `${word}s`; + return `${count} ${count === 1 ? word : plural}`; + }) + .join(" and "); +} + +/** + * Collapse each run of activity between human turns into one expandable pill, + * so the founder's messages and the model's replies to them stay in place. + * Expanding a run shows exactly the rows it replaced; nothing is dropped. + */ +export function collapseTimelineActivity( + rows: MessagesTimelineRow[], + expandedIds: ReadonlySet, +): MessagesTimelineRow[] { + const collapsed: MessagesTimelineRow[] = []; + let run: MessagesTimelineRow[] = []; + let anchor: MessagesTimelineRow | undefined; + const flush = () => { + if (run.length === 0) return; + const id = activityPillId(anchor, run); + const pill: MessagesTimelineRow = { + kind: "activity", + id, + createdAt: run[0]!.createdAt, + count: run.length, + summary: activityUpdateSummary(run), + expanded: expandedIds.has(id), + }; + collapsed.push(pill); + if (pill.expanded) for (const row of run) collapsed.push(row); + run = []; + }; + for (const row of rows) { + if (timelineRowIsHumanConversation(row)) { + flush(); + collapsed.push(row); + anchor = row; + } else { + run.push(row); + } + } + flush(); + return collapsed; +} + +/** The pill hiding `entryId`, if one does, so a search hit or a restored scroll position can open it. */ +export function activityPillIdForEntry( + rows: MessagesTimelineRow[], + entryId: string, +): string | undefined { + let anchor: MessagesTimelineRow | undefined; + let run: MessagesTimelineRow[] = []; + const match = (): string | undefined => + run.some((row) => row.id === entryId) ? activityPillId(anchor, run) : undefined; + for (const row of rows) { + if (timelineRowIsHumanConversation(row)) { + const found = match(); + if (found !== undefined) return found; + run = []; + anchor = row; + } else { + run.push(row); + } + } + return match(); +} + export function filterTimelineRowsBySender( rows: MessagesTimelineRow[], sender: OrchestrationMessageSenderFilter | null, @@ -2862,6 +3016,16 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean ); } + case "activity": { + const ba = b as typeof a; + return ( + a.createdAt === ba.createdAt && + a.count === ba.count && + a.summary === ba.summary && + a.expanded === ba.expanded + ); + } + 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 e381e295d7e1c..b141928e5c042 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -87,6 +87,8 @@ import { TIMELINE_MINIMAP_TARGET_OFFSET, timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, + collapseTimelineActivity, + activityPillIdForEntry, type MessagesTimelineRow, type TimelineLatestRun, } from "./MessagesTimeline.logic"; @@ -332,6 +334,12 @@ interface MessagesTimelineProps { activeFindMatch?: ThreadFindMatch | null; findNavigationId?: number; findSender?: OrchestrationMessageSenderFilter | null; + /** + * Collapse runs of agent, automation and system activity into expandable + * pills, leaving the founder's messages and the model's replies to them. + * Off by default; a standing thread turns it on. + */ + collapseActivity?: boolean; } export function MessagesTimeline(props: MessagesTimelineProps) { @@ -379,6 +387,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, findSender = null, + collapseActivity = false, latestRun, announcedRun = null, detailBehindShell = false, @@ -562,6 +571,18 @@ const ConversationTimeline = memo(function ConversationTimeline({ }; // Turn and attempt folds reveal later rows rather than growing their own row. + const onToggleActivity = (id: string) => { + preserveDisclosurePosition(id); + setExpandedActivity((existing) => { + const ids = new Set(existing.threadKey === listIdentityKey ? existing.ids : []); + if (ids.has(id)) { + ids.delete(id); + } else { + ids.add(id); + } + return { threadKey: listIdentityKey, ids }; + }); + }; const onToggleTurnFold = (runId: RunId) => { preserveDisclosurePosition(`turn-fold:${runId}`); setExpandedRunIds((existing) => { @@ -762,7 +783,42 @@ const ConversationTimeline = memo(function ConversationTimeline({ revealedMessageId, }); const stableRows = useStableRows(rawRows, listIdentityKey); - const rows = useSenderFilteredRows(stableRows, findSender); + const senderRows = useSenderFilteredRows(stableRows, findSender); + // A sender filter already removed every other message, so collapsing what it + // kept would hide the very rows it was asked to show. + const collapseRows = collapseActivity && findSender === null; + const [expandedActivity, setExpandedActivity] = useState<{ + readonly threadKey: string; + readonly ids: ReadonlySet; + }>(() => ({ 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 }); + } + // 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. + const revealedEntryId = + (findActive ? activeFindMatch?.entryId : undefined) ?? + (restoringThreadPosition && rememberedPosition?.atEnd === false + ? rememberedPosition.rowId + : undefined); + const revealedPillId = + collapseRows && revealedEntryId !== undefined + ? activityPillIdForEntry(senderRows, revealedEntryId) + : undefined; + if ( + revealedPillId !== undefined && + expandedActivity.threadKey === listIdentityKey && + !expandedActivity.ids.has(revealedPillId) + ) { + const ids = new Set(expandedActivity.ids); + ids.add(revealedPillId); + setExpandedActivity({ threadKey: listIdentityKey, ids }); + } + const rows = collapseRows ? collapseTimelineActivity(senderRows, expandedActivityIds) : senderRows; const matchedApprovalRequestIds = new Set(); for (const row of pendingApprovalRequestIds.size > 0 ? rows : []) { const entries = @@ -1140,6 +1196,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ workflowOpening, onForkFromRun, onToggleTurnFold, + onToggleActivity, onToggleAttemptFold, onToggleWorkGroup, onToggleWorkEntry: (anchorKey, collapsed, entryId) => @@ -1626,7 +1683,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time className={cn( isWorkLogRow || isSubagentGroup ? undefined - : row.kind === "turn-fold" || row.kind === "working" + : row.kind === "turn-fold" || row.kind === "activity" || row.kind === "working" ? "pb-1.5" : row.kind === "message" && row.groupedWithNext ? "pb-1" @@ -1678,6 +1735,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "thinking" ? : null} ) : null} + {row.kind === "activity" ? : null} {row.kind === "turn-fold" ? : null} {row.kind === "attempt-fold" ? : null} {row.kind === "context-compaction" ? : null} @@ -1827,6 +1885,31 @@ function WorkHistorySkeleton() { ); } +function ActivityTimelineRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + return ( +
+ +
+ ); +} + function TurnFoldTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const { loading, error, toggle } = useDeferredWorkLoading(row, () => diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 6a298fd6de049..5ac580ec8d3dd 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -91,6 +91,7 @@ export interface TimelineRowSharedState { | ((input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => Promise) | undefined; onToggleTurnFold: (runId: RunId) => void; + onToggleActivity: (id: string) => void; onToggleAttemptFold: (attemptId: RunAttemptId) => void; onFileOpen: (attachment: ChatFileAttachment) => void; onFileDownload: (attachment: ChatFileAttachment) => void;