:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): group repeated events on the task timeline (#86925)
Adam Leith7c65e3142ba8
diff --git a/products/desktop/packages/core/src/canvas/activityEvents.ts b/products/desktop/packages/core/src/canvas/activityEvents.tsindex 3a385ffcad48..f96e768d7bd4 100644--- a/products/desktop/packages/core/src/canvas/activityEvents.ts+++ b/products/desktop/packages/core/src/canvas/activityEvents.ts@@ -303,10 +303,24 @@ export function parseActivityEvent(message: {}}-/** "owner/repo#12" when the event knows both, else the bare url. */+const GITHUB_PR_URL = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/;++/** "owner/repo#12" when the event knows both, else read off the url, else the bare url. */export function prLabel(payload: PrPayload): string {- if (payload.repository && payload.prNumber !== null) {- return `${payload.repository}#${payload.prNumber}`;- }+ const repository = prRepository(payload);+ const number = payload.prNumber ?? prNumberFromUrl(payload.prUrl);+ if (repository && number !== null) return `${repository}#${number}`;return payload.prUrl;}++/** The repository the event names, or the one its url points at. */+export function prRepository(payload: PrPayload): string | null {+ if (payload.repository) return payload.repository;+ const match = GITHUB_PR_URL.exec(payload.prUrl);+ return match ? `${match[1]}/${match[2]}` : null;+}++function prNumberFromUrl(url: string): number | null {+ const match = GITHUB_PR_URL.exec(url);+ return match ? Number(match[3]) : null;+}diff --git a/products/desktop/packages/core/src/canvas/activityGrouping.test.ts b/products/desktop/packages/core/src/canvas/activityGrouping.test.tsnew file mode 100644index 000000000000..18318735b8bb--- /dev/null+++ b/products/desktop/packages/core/src/canvas/activityGrouping.test.ts@@ -0,0 +1,103 @@+import { parseActivityEvent } from "@posthog/core/canvas/activityEvents";+import { groupActivityRows } from "@posthog/core/canvas/activityGrouping";+import type { ActivityRow } from "@posthog/core/canvas/activityTimeline";+import type { ThreadMessageLike } from "@posthog/core/canvas/threadTimeline";+import { describe, expect, it } from "vitest";++let nextId = 0;++// Each fixture row is one tick newer than the last, which is all the order the grouping reads.+function eventRow(+ event: string,+ payload: Record<string, unknown>,+): ActivityRow {+ nextId += 1;+ const ts = nextId;+ const message: ThreadMessageLike = {+ id: `m${nextId}`,+ content: "",+ created_at: new Date(ts).toISOString(),+ author_kind: "agent",+ event,+ payload,+ };+ const parsed = parseActivityEvent(message);+ if (!parsed) throw new Error(`unparsed fixture event: ${event}`);+ return {+ kind: "event",+ key: `event-${message.id}`,+ ts,+ event: parsed,+ message,+ };+}++function push(branch: string, ...shas: string[]): ActivityRow {+ return eventRow("commits_pushed", {+ run_id: "run-1",+ branch,+ repository: "PostHog/posthog",+ commits: shas.map((sha) => ({ sha, subject: `work ${sha}` })),+ total: shas.length,+ });+}++function pr(number: number): ActivityRow {+ return eventRow("pr_created", {+ pr_url: `https://github.com/PostHog/posthog/pull/${number}`,+ });+}++const prompt: ActivityRow = {+ kind: "user_message",+ key: "user-message-1",+ ts: 0,+ item: { id: "1", content: "go", timestamp: 0 },+};++describe("activity grouping", () => {+ it("collapses repeated pushes to one branch into one row", () => {+ const grouped = groupActivityRows([+ push("main", "aaa"),+ push("main", "bbb"),+ push("main", "ccc", "ddd"),+ ]);++ expect(grouped).toHaveLength(1);+ const [row] = grouped;+ if (row?.kind !== "event_group") throw new Error("expected a group");+ expect(row.events).toHaveLength(3);+ // The newest member's, so the row reads as when the stretch of pushes ended.+ expect(row.ts).toBe(3);+ });++ it.each([+ [+ "one of each kind stays one row each",+ () => [push("main", "aaa"), pr(1)],+ ["event", "event"],+ ],+ [+ "two branches stay two rows",+ () => [+ push("main", "aaa"),+ push("side", "bbb"),+ push("main", "ccc"),+ push("side", "ddd"),+ ],+ ["event_group", "event_group"],+ ],+ [+ "a pull request between pushes doesn't split them",+ () => [push("main", "aaa"), pr(1), push("main", "bbb"), pr(2)],+ ["event_group", "event_group"],+ ],+ [+ "a prompt between pushes does",+ () => [push("main", "aaa"), prompt, push("main", "bbb")],+ ["event", "user_message", "event"],+ ],+ ])("%s", (_name, rows, expected) => {+ expect(groupActivityRows(rows()).map((row) => row.kind)).toEqual(expected);+ });+});diff --git a/products/desktop/packages/core/src/canvas/activityGrouping.ts b/products/desktop/packages/core/src/canvas/activityGrouping.tsnew file mode 100644index 000000000000..f85dd519d897--- /dev/null+++ b/products/desktop/packages/core/src/canvas/activityGrouping.ts@@ -0,0 +1,130 @@+/**+ * Collapses a stretch of repetitive event rows into one row per thing that happened.+ *+ * A run that pushes twenty times writes twenty rows saying "1 commit pushed", which buries+ * everything else in the panel and says less than one row saying "20 commits pushed". Only a+ * run of adjacent rows collapses, so a group never reaches across a prompt, a reply, a run+ * start or anything else the reader stops on.+ */++import {+ type ActivityEvent,+ prRepository,+} from "@posthog/core/canvas/activityEvents";+import type {+ ActivityRow,+ CommentThreadLike,+} from "@posthog/core/canvas/activityTimeline";+import type { ThreadMessageLike } from "@posthog/core/canvas/threadTimeline";++/** The kinds that collapse. Every other kind names something the reader has to act on. */+export type GroupableActivityEvent = Extract<+ ActivityEvent,+ { kind: "commits_pushed" | "pr_created" | "pr_merged" | "pr_closed" }+>;++export type GroupedActivityRow<+ TMessage extends ThreadMessageLike = ThreadMessageLike,+ TComment extends CommentThreadLike = CommentThreadLike,+> =+ | ActivityRow<TMessage, TComment>+ | {+ kind: "event_group";+ key: string;+ /** The newest member's, so the row reads as when the run of them ended. */+ ts: number;+ events: GroupableActivityEvent[];+ };++/** What a group of this kind is keyed on: two rows collapse only if they answer the same. */+function groupKey(event: GroupableActivityEvent): string {+ // Two pushes to one branch are one piece of news; two branches are two.+ if (event.kind === "commits_pushed") {+ return `commits_pushed:${event.payload.branch}`;+ }+ return `${event.kind}:${prRepository(event.payload) ?? ""}`;+}++export function groupActivityRows<+ TMessage extends ThreadMessageLike,+ TComment extends CommentThreadLike,+>(+ rows: ActivityRow<TMessage, TComment>[],+): GroupedActivityRow<TMessage, TComment>[] {+ const grouped: GroupedActivityRow<TMessage, TComment>[] = [];+ let index = 0;++ while (index < rows.length) {+ const row = rows[index];+ const event = row ? groupableEvent(row) : null;+ if (!row || !event) {+ if (row) grouped.push(row);+ index += 1;+ continue;+ }+ // The run is every groupable row up to the next one that isn't. Grouping within the run+ // rather than only over neighbours collapses pushes that a pull request landed between,+ // which is the shape a stack of branches arrives in.+ let end = index;+ const members = new Map<+ string,+ {+ first: ActivityRow<TMessage, TComment>;+ events: GroupableActivityEvent[];+ ts: number;+ }+ >();+ while (end < rows.length) {+ const candidate = rows[end];+ const candidateEvent = candidate ? groupableEvent(candidate) : null;+ if (!candidate || !candidateEvent) break;+ const key = groupKey(candidateEvent);+ const bucket = members.get(key);+ if (bucket) {+ bucket.events.push(candidateEvent);+ bucket.ts = Math.max(bucket.ts, candidate.ts);+ } else {+ members.set(key, {+ first: candidate,+ events: [candidateEvent],+ ts: candidate.ts,+ });+ }+ end += 1;+ }++ // Insertion order, so each group sits where the first of its members did.+ for (const bucket of members.values()) {+ if (bucket.events.length === 1) {+ grouped.push(bucket.first);+ continue;+ }+ grouped.push({+ kind: "event_group",+ key: `group-${bucket.first.key}`,+ ts: bucket.ts,+ events: bucket.events,+ });+ }+ index = end;+ }++ return grouped;+}++function groupableEvent<+ TMessage extends ThreadMessageLike,+ TComment extends CommentThreadLike,+>(row: ActivityRow<TMessage, TComment>): GroupableActivityEvent | null {+ if (row.kind !== "event") return null;+ const event = row.event;+ switch (event.kind) {+ case "commits_pushed":+ case "pr_created":+ case "pr_merged":+ case "pr_closed":+ return event;+ default:+ return null;+ }+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsxindex 26a346cc607b..a957234f24f4 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsx@@ -154,6 +154,46 @@ const messages: TaskThreadMessage[] = [const timeline = buildThreadTimeline(messages);+const BUSY_BRANCHES = ["shy/reports-panel", "shy/drop-report-tables"];++// One run's worth of noise: a push at a time, with the pull requests they opened between.+const busyMessages: TaskThreadMessage[] = [+ event(+ "b0",+ "run_started",+ { run_id: "run-2", environment: "cloud", branch: BUSY_BRANCHES[0] },+ "2026-08-05T09:00:00Z",+ ),+ ...Array.from({ length: 9 }, (_, index) =>+ event(+ `b${index + 1}`,+ "commits_pushed",+ {+ run_id: "run-2",+ branch: BUSY_BRANCHES[index % 2],+ repository: "PostHog/posthog",+ total: 1,+ commits: [+ {+ sha: `${index + 1}c0ffee`,+ subject: `chore(desktop): iterate ${index + 1}`,+ url: `https://github.com/PostHog/posthog/commit/${index + 1}c0ffee`,+ },+ ],+ },+ `2026-08-05T${10 + Math.floor(index / 3)}:${String((index % 3) * 15 + 5).padStart(2, "0")}:00Z`,+ ),+ ),+ ...[80061, 80062, 80063].map((number, index) =>+ event(+ `bp${number}`,+ "pr_created",+ { pr_url: `https://github.com/PostHog/posthog/pull/${number}` },+ `2026-08-05T13:${index * 10 + 10}:00Z`,+ ),+ ),+];+const commentThreads: TaskCommentThreadSummary[] = [{id: "thread-1",@@ -240,6 +280,17 @@ export const FullTimeline: Story = {},};+/** What a stack of branches looks like: nine pushes and three pull requests, which the+ * panel collapses into one row per branch and one row for the pull requests. */+export const GroupedRun: Story = {+ args: {+ task,+ timeline: buildThreadTimeline(busyMessages),+ messages: busyMessages,+ conversationItems: [],+ },+};+/** The changed-file list a commit row shows once GitHub answers. In the timeline* above the fetch never resolves (no workspace-server in Storybook), so the* presentational list is shown on its own here. */diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsxindex 2194ec975520..e9c3f89d021a 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsx@@ -326,6 +326,48 @@ describe("ActivityTimeline events and comments", () => {expect(screen.getByText("resolved a thread on")).toBeInTheDocument();});++ it("collapses a stretch of pushes to one branch into one row", () => {+ renderRows({+ messages: [1, 2, 3].map((index) =>+ threadMessage(+ `m${index}`,+ "commits_pushed",+ {+ run_id: "run-1",+ branch: "shy/activity",+ repository: "PostHog/posthog",+ commits: [{ sha: `sha${index}`, subject: `work ${index}` }],+ total: 1,+ },+ `2026-07-17T09:2${index}:00Z`,+ ),+ ),+ });++ expect(screen.getByText(/3 commits pushed/)).toBeInTheDocument();+ expect(screen.queryByText(/1 commit pushed/)).toBeNull();+ expect(screen.getByText(/to shy\/activity/)).toBeInTheDocument();+ });++ it("tells grouped pull requests apart by number, not by url", () => {+ // Every row said "Pull request opened · https://github.com/…", which truncates to the+ // same string, so four different pull requests read as one repeated four times.+ renderRows({+ messages: [11, 12].map((number) =>+ threadMessage(`m${number}`, "pr_created", {+ pr_url: `https://github.com/PostHog/posthog/pull/${number}`,+ }),+ ),+ });++ fireEvent.click(+ screen.getByRole("button", { name: /2 pull requests opened/ }),+ );++ expect(screen.getByText("PostHog/posthog#11")).toBeInTheDocument();+ expect(screen.getByText("PostHog/posthog#12")).toBeInTheDocument();+ });});describe("ActivityTimeline chat jump", () => {diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsxindex 56e6c998b5d7..6ca4168ded3c 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx@@ -4,7 +4,10 @@ import type {CommentEventPayload,} from "@posthog/core/canvas/activityEvents";import {- type ActivityRow,+ type GroupedActivityRow,+ groupActivityRows,+} from "@posthog/core/canvas/activityGrouping";+import {buildActivityTimeline,type UserMessageLike,} from "@posthog/core/canvas/activityTimeline";@@ -31,6 +34,7 @@ import {CommentRow,CommentStateRow,CREATED_BADGE,+ GroupedEventRow,MESSAGE_BADGE,MessageBubble,PersonBead,@@ -181,7 +185,7 @@ export function ActivityTimeline({return byId;}, [timeline]);- const rows = useMemo(() => {+ const timelineRows = useMemo(() => {const taskCreatedTimestamp = Date.parse(task.created_at);return buildActivityTimeline({task: {@@ -227,18 +231,22 @@ export function ActivityTimeline({});}, [task, messages, commentThreads, conversationItems]);+ // A stretch of rows each saying "1 commit pushed" reads as noise and buries everything+ // else, so neighbours that said the same thing collapse into one row.+ const rows = useMemo(() => groupActivityRows(timelineRows), [timelineRows]);+// Numbering a run and deciding whether to number it at all have to come from the same// population, or a task with three runs and one row labels that row "run 1".const runStartedCount = useMemo(() =>- rows.reduce(+ timelineRows.reduce((count, row) =>row.kind === "event" && row.event.kind === "run_started"? count + 1: count,0,),- [rows],+ [timelineRows],);const threadsById = useMemo(() => {@@ -324,11 +332,20 @@ export function ActivityTimeline({};const renderRow = (- row: ActivityRow<TaskThreadMessage>,+ row: GroupedActivityRow<TaskThreadMessage>,connectedAbove: boolean,connectedBelow: boolean,) => {switch (row.kind) {+ case "event_group":+ return (+ <GroupedEventRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ events={row.events}+ timestamp={new Date(row.ts).toISOString()}+ />+ );case "task_created":return (<TimelineRowdiff --git a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsxindex 83d3ed3dd896..f253b09f91ca 100644--- a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx@@ -27,8 +27,10 @@ import {type ArtifactPayload,type CommentEventPayload,type CommitsPushedPayload,+ type PrPayload,prLabel,} from "@posthog/core/canvas/activityEvents";+import type { GroupableActivityEvent } from "@posthog/core/canvas/activityGrouping";import type { ChangedFile } from "@posthog/core/git/router-schemas";import { xmlToContent } from "@posthog/core/message-editor/content";import {@@ -742,6 +744,122 @@ export function ActivityEventRow({);}+function PrGroupLink({ payload }: { payload: PrPayload }) {+ const label = prLabel(payload);+ // Same gate CommitSha applies: the url comes from run output, so a crafted+ // payload must not turn a github-looking label into a link anywhere else.+ const parsed = parseHttpsUrl(payload.prUrl);+ const safeUrl = parsed?.origin === "https://github.com" ? parsed.href : null;+ if (!safeUrl) {+ return <div className="truncate text-muted-foreground">{label}</div>;+ }+ return (+ <button+ type="button"+ onClick={() => openExternalUrl(safeUrl)}+ className="block max-w-full cursor-pointer truncate text-left hover:underline"+ >+ {label}+ </button>+ );+}++/**+ * One row for a stretch of events that each said the same thing. The count is the news; the+ * events themselves are the detail, so nothing the individual rows carried is lost.+ */+export function GroupedEventRow({+ events,+ timestamp,+ connectedAbove = true,+ connectedBelow = true,+}: {+ events: GroupableActivityEvent[];+ timestamp: string;+ connectedAbove?: boolean;+ connectedBelow?: boolean;+}) {+ const first = events[0];+ if (!first) return null;++ if (first.kind === "commits_pushed") {+ const pushes = events.flatMap((event) =>+ event.kind === "commits_pushed" ? [event.payload] : [],+ );+ const total = pushes.reduce((sum, push) => sum + push.total, 0);+ const listed = pushes.reduce((sum, push) => sum + push.commits.length, 0);+ const branch = first.payload.branch;+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={+ <EventBead tone={EVENT_TONES.commits_pushed}>+ {EVENT_ICONS.commits_pushed}+ </EventBead>+ }+ timestamp={timestamp}+ detail={+ <DetailBlock>+ <div className="max-h-56 space-y-1.5 overflow-y-auto overscroll-contain">+ {pushes.flatMap((push) =>+ push.commits.map((commit) => (+ <PushedCommitRow+ key={commit.sha}+ commit={commit}+ repository={push.repository}+ />+ )),+ )}+ {total > listed && (+ <div className="text-muted-foreground">+ and {total - listed} more+ </div>+ )}+ </div>+ </DetailBlock>+ }+ >+ {`${total} commits pushed`}+ {branch && <span className="text-muted-foreground"> to {branch}</span>}+ </TimelineRow>+ );+ }++ const verb =+ first.kind === "pr_created"+ ? "opened"+ : first.kind === "pr_merged"+ ? "merged"+ : "closed";+ const pulls = events.flatMap((event) =>+ event.kind === "commits_pushed" ? [] : [event.payload],+ );+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={+ <EventBead tone={EVENT_TONES[first.kind]}>+ {EVENT_ICONS[first.kind]}+ </EventBead>+ }+ timestamp={timestamp}+ detail={+ <DetailBlock>+ <div className="max-h-56 space-y-1 overflow-y-auto overscroll-contain">+ {pulls.map((payload) => (+ <PrGroupLink key={payload.prUrl} payload={payload} />+ ))}+ </div>+ </DetailBlock>+ }+ >+ {`${pulls.length} pull requests ${verb}`}+ </TimelineRow>+ );+}+/** The ending of a run that predates the event rows, derived from the task. */export function RunStatusRow({status,