: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): redesign the task timeline as a one-line event feed (#81410)
Shy Alter3e5b33409471
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 2d112ed22ad2..2bd178165371 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -103,6 +103,7 @@ import type {TaskActivityPage,TaskActivityReadMarker,TaskChannel,+ TaskCommentThreadSummary,TaskMention,TaskRun,TaskRunArtefact,@@ -2908,6 +2909,33 @@ export class PostHogAPIClient {return (await response.json()) as TaskThreadMessage[];}+ /** One request for the whole task, so the panel never fans out per artifact the way the+ * Comments tab has to.+ *+ * A backend predating the read layer has no such route, so a 404 means "no comment rows+ * yet" rather than a failure and the timeline comes alive once the endpoint exists. */+ async getTaskCommentActivity(+ taskId: string,+ ): Promise<TaskCommentThreadSummary[]> {+ const teamId = await this.getTeamId();+ const urlPath = `/api/projects/${teamId}/tasks/${taskId}/thread_messages/comment_activity/`;+ const response = await this.api.fetcher.fetch({+ method: "get",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ });+ if (response.status === 404) return [];+ if (!response.ok) {+ throw new Error(+ `Failed to fetch comment activity: ${response.statusText}`,+ );+ }+ const body = (await response.json()) as {+ comments?: TaskCommentThreadSummary[];+ };+ return body.comments ?? [];+ }+async createTaskThreadMessage(taskId: string,content: string,diff --git a/products/desktop/packages/core/src/canvas/activityEvents.ts b/products/desktop/packages/core/src/canvas/activityEvents.tsnew file mode 100644index 000000000000..5995cb003618--- /dev/null+++ b/products/desktop/packages/core/src/canvas/activityEvents.ts@@ -0,0 +1,218 @@+/**+ * The vocabulary of server-emitted task events the activity timeline renders.+ *+ * Mirrors `TaskActivityEvent` in `products/tasks/backend/models.py`; a test asserts the+ * two lists match. `parseActivityEvent` returns `null` for anything it doesn't know, which+ * is what lets the backend emit a new event before this client can draw it.+ */++export const ACTIVITY_EVENTS = [+ "run_started",+ "run_failed",+ "commits_pushed",+ "awaiting_input",+ "artifact_created",+ "artifact_revised",+ "canvas_created",+ "pr_created",+ "pr_merged",+ "pr_closed",+ "message_forwarded",+] as const;++export type ActivityEventKind = (typeof ACTIVITY_EVENTS)[number];++const ACTIVITY_EVENT_SET: ReadonlySet<string> = new Set(ACTIVITY_EVENTS);++export interface RunStartedPayload {+ runId: string;+ environment: string;+ branch: string;+}++export interface RunFailedPayload {+ runId: string;+ errorSummary: string;+}++export interface CommitsPushedPayload {+ runId: string;+ branch: string;+ repository: string | null;+ commits: { sha: string; subject: string; url: string | null }[];+ /** How many the push carried; `commits` is capped, so this can be larger. */+ total: number;+}++export interface AwaitingInputPayload {+ runId: string;+}++export interface ArtifactPayload {+ artifactId: string;+ name: string;+ artifactType: string;+ version: number;+}++export interface CanvasCreatedPayload {+ name: string;+ url: string | null;+}++export interface PrPayload {+ prUrl: string;+ repository: string | null;+ prNumber: number | null;+ actor: string | null;+}++export interface MessageForwardedPayload {+ messageId: string;+ runId: string;+}++export type ActivityEvent =+ | { kind: "run_started"; payload: RunStartedPayload }+ | { kind: "run_failed"; payload: RunFailedPayload }+ | { kind: "commits_pushed"; payload: CommitsPushedPayload }+ | { kind: "awaiting_input"; payload: AwaitingInputPayload }+ | { kind: "artifact_created"; payload: ArtifactPayload }+ | { kind: "artifact_revised"; payload: ArtifactPayload }+ | { kind: "canvas_created"; payload: CanvasCreatedPayload }+ | { kind: "pr_created"; payload: PrPayload }+ | { kind: "pr_merged"; payload: PrPayload }+ | { kind: "pr_closed"; payload: PrPayload }+ | { kind: "message_forwarded"; payload: MessageForwardedPayload };++function str(value: unknown, fallback = ""): string {+ return typeof value === "string" ? value : fallback;+}++function num(value: unknown, fallback: number): number {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++function optionalStr(value: unknown): string | null {+ return typeof value === "string" && value ? value : null;+}++function prPayload(payload: Record<string, unknown>): PrPayload {+ return {+ prUrl: str(payload.pr_url),+ repository: optionalStr(payload.repository),+ prNumber: typeof payload.pr_number === "number" ? payload.pr_number : null,+ actor: optionalStr(payload.actor),+ };+}++function artifactPayload(payload: Record<string, unknown>): ArtifactPayload {+ return {+ artifactId: str(payload.artifact_id),+ name: str(payload.name, "Artifact"),+ artifactType: str(payload.artifact_type),+ version: num(payload.version, 1),+ };+}++export function isActivityEventKind(event: string): event is ActivityEventKind {+ return ACTIVITY_EVENT_SET.has(event);+}++/**+ * The typed event a thread message carries, or `null` when the message isn't one this+ * client renders: a human message, an older event, or one added after this release.+ */+export function parseActivityEvent(message: {+ event?: string;+ payload?: Record<string, unknown>;+}): ActivityEvent | null {+ const event = message.event ?? "";+ if (!isActivityEventKind(event)) return null;+ const payload = message.payload ?? {};+ switch (event) {+ case "run_started":+ return {+ kind: event,+ payload: {+ runId: str(payload.run_id),+ environment: str(payload.environment),+ branch: str(payload.branch),+ },+ };+ case "run_failed":+ return {+ kind: event,+ payload: {+ runId: str(payload.run_id),+ errorSummary: str(payload.error_summary),+ },+ };+ case "commits_pushed": {+ const raw = Array.isArray(payload.commits) ? payload.commits : [];+ const commits = raw.flatMap((entry) => {+ if (typeof entry !== "object" || entry === null) return [];+ const commit = entry as Record<string, unknown>;+ const sha = str(commit.sha);+ return sha+ ? [+ {+ sha,+ subject: str(commit.subject),+ url: optionalStr(commit.url),+ },+ ]+ : [];+ });+ // A push with no readable commit can't be drawn, so it isn't a row.+ return commits.length+ ? {+ kind: event,+ payload: {+ runId: str(payload.run_id),+ branch: str(payload.branch),+ repository: optionalStr(payload.repository),+ commits,+ total: num(payload.total, commits.length),+ },+ }+ : null;+ }+ case "awaiting_input":+ return { kind: event, payload: { runId: str(payload.run_id) } };+ case "artifact_created":+ case "artifact_revised":+ return { kind: event, payload: artifactPayload(payload) };+ case "canvas_created":+ return {+ kind: event,+ payload: {+ name: str(payload.canvas_name, "Canvas"),+ url: optionalStr(payload.canvas_url),+ },+ };+ case "pr_created":+ case "pr_merged":+ case "pr_closed": {+ const parsed = prPayload(payload);+ // A PR row with no url can't be labelled or opened, so it isn't a row.+ return parsed.prUrl ? { kind: event, payload: parsed } : null;+ }+ case "message_forwarded":+ return {+ kind: event,+ payload: {+ messageId: str(payload.message_id),+ runId: str(payload.run_id),+ },+ };+ }+}++/** "owner/repo#12" when the event knows both, else the bare url. */+export function prLabel(payload: PrPayload): string {+ if (payload.repository && payload.prNumber !== null) {+ return `${payload.repository}#${payload.prNumber}`;+ }+ return payload.prUrl;+}diff --git a/products/desktop/packages/core/src/canvas/activityTimeline.test.ts b/products/desktop/packages/core/src/canvas/activityTimeline.test.tsnew file mode 100644index 000000000000..99f246760bb2--- /dev/null+++ b/products/desktop/packages/core/src/canvas/activityTimeline.test.ts@@ -0,0 +1,420 @@+import {+ ACTIVITY_EVENTS,+ parseActivityEvent,+} from "@posthog/core/canvas/activityEvents";+import {+ type ActivityTaskLike,+ buildActivityTimeline,+ type CommentThreadLike,+} from "@posthog/core/canvas/activityTimeline";+import type { ThreadMessageLike } from "@posthog/core/canvas/threadTimeline";+import { describe, expect, it } from "vitest";++const task: ActivityTaskLike = {+ id: "task-1",+ createdAt: "2026-08-01T10:00:00Z",+ updatedAt: "2026-08-01T12:00:00Z",+};++function eventMessage(+ id: string,+ event: string,+ payload: Record<string, unknown>,+ createdAt: string,+): ThreadMessageLike {+ return {+ id,+ content: "",+ created_at: createdAt,+ author_kind: "agent",+ event,+ payload,+ };+}++function thread(overrides: Partial<CommentThreadLike> = {}): CommentThreadLike {+ return {+ id: "thread-1",+ lastActivityAt: "2026-08-01T11:00:00Z",+ mentionedUserIds: [],+ resolved: false,+ stateEvent: null,+ ...overrides,+ };+}++function build(input: {+ messages?: ThreadMessageLike[];+ commentThreads?: CommentThreadLike[];+ taskOverrides?: Partial<ActivityTaskLike>;+}) {+ return buildActivityTimeline({+ task: { ...task, ...input.taskOverrides },+ messages: input.messages ?? [],+ commentThreads: input.commentThreads ?? [],+ });+}++describe("activity timeline", () => {+ it("leads with the task's creation", () => {+ const rows = build({});++ expect(rows.map((row) => row.kind)).toEqual(["task_created"]);+ });++ it("orders every source by time", () => {+ const rows = build({+ messages: [+ eventMessage(+ "m2",+ "run_started",+ { run_id: "run-1" },+ "2026-08-01T10:30:00Z",+ ),+ {+ id: "m1",+ content: "what about mobile?",+ created_at: "2026-08-01T10:15:00Z",+ },+ ],+ commentThreads: [thread()],+ });++ expect(rows.map((row) => row.key)).toEqual([+ "task-created",+ "message-m1",+ "event-m2",+ "comment-thread-1",+ ]);+ });++ it("places a comment thread at its newest activity, not its start", () => {+ // A thread that keeps getting replies has to stay one row that moves, or a five-reply+ // exchange pushes everything else off the panel.+ const rows = build({+ messages: [+ eventMessage(+ "m1",+ "run_started",+ { run_id: "run-1" },+ "2026-08-01T13:00:00Z",+ ),+ ],+ commentThreads: [thread({ lastActivityAt: "2026-08-01T14:00:00Z" })],+ });++ expect(rows.map((row) => row.kind)).toEqual([+ "task_created",+ "event",+ "comment",+ ]);+ });++ it("gives resolve its own row after the thread", () => {+ const rows = build({+ commentThreads: [+ thread({+ resolved: true,+ stateEvent: { state: "resolved", createdAt: "2026-08-01T11:30:00Z" },+ }),+ ],+ });++ expect(rows.map((row) => row.kind)).toEqual([+ "task_created",+ "comment",+ "comment_state",+ ]);+ });++ it("keeps one row when two paths announced the same pull request", () => {+ // The agent's own output and the GitHub webhook backstop can both observe a PR.+ const rows = build({+ messages: [+ eventMessage(+ "m1",+ "pr_created",+ { pr_url: "https://github.com/posthog/posthog/pull/1" },+ "2026-08-01T10:30:00Z",+ ),+ eventMessage(+ "m2",+ "pr_created",+ { pr_url: "https://github.com/posthog/posthog/pull/1" },+ "2026-08-01T10:31:00Z",+ ),+ ],+ });++ expect(rows.filter((row) => row.kind === "event")).toHaveLength(1);+ });++ it("ignores events it doesn't know, so the backend can ship first", () => {+ const rows = build({+ messages: [+ eventMessage("m1", "checks_failed_someday", {}, "2026-08-01T10:30:00Z"),+ ],+ });++ expect(rows.map((row) => row.kind)).toEqual(["task_created"]);+ });++ it("numbers runs over the feed, since the backend cannot number them", () => {+ // Counting runs server-side races two concurrent creations onto one number; the ordered+ // feed can only be read one way.+ const rows = build({+ messages: [+ eventMessage(+ "m1",+ "run_started",+ { run_id: "run-1" },+ "2026-08-01T10:30:00Z",+ ),+ eventMessage(+ "m2",+ "run_started",+ { run_id: "run-2" },+ "2026-08-01T11:30:00Z",+ ),+ ],+ });++ expect(+ rows.flatMap((row) => (row.kind === "event" ? [row.runOrdinal] : [])),+ ).toEqual([1, 2]);+ });++ it("derives an ending for tasks with no failure event", () => {+ const rows = build({+ taskOverrides: { latestRunStatus: "completed", latestRunId: "run-1" },+ });++ expect(rows.at(-1)).toMatchObject({+ kind: "run_status",+ status: "completed",+ });+ });++ it("shows a pull request recorded only on the run's output", () => {+ // Tasks from before the announcements carry the PR nowhere else, and dropping the row+ // hid the pull request from the panel entirely.+ const rows = build({+ taskOverrides: {+ latestRunId: "run-1",+ latestRunPrUrl: "https://github.com/PostHog/posthog/pull/81410",+ },+ });++ expect(rows).toContainEqual(+ expect.objectContaining({+ kind: "run_output_pr",+ prUrl: "https://github.com/PostHog/posthog/pull/81410",+ }),+ );+ });++ it("leaves the run's output alone once the thread announced the pull request", () => {+ const rows = build({+ messages: [+ eventMessage(+ "m1",+ "pr_created",+ { pr_url: "https://github.com/PostHog/posthog/pull/81410" },+ "2026-08-01T11:00:00Z",+ ),+ ],+ taskOverrides: {+ latestRunId: "run-1",+ latestRunPrUrl: "https://github.com/PostHog/posthog/pull/81410",+ },+ });++ expect(rows.filter((row) => row.kind === "run_output_pr")).toHaveLength(0);+ });++ it("keeps every ask for input a run makes, not just the first", () => {+ // The dedupe guard exists for two paths reporting one occurrence. A run that asks+ // twice is two occurrences, and collapsing them hides the second ask.+ const rows = build({+ messages: [+ eventMessage(+ "m1",+ "awaiting_input",+ { run_id: "run-1" },+ "2026-08-01T11:00:00Z",+ ),+ eventMessage(+ "m2",+ "awaiting_input",+ { run_id: "run-1" },+ "2026-08-01T12:00:00Z",+ ),+ ],+ });++ expect(+ rows.filter(+ (row) => row.kind === "event" && row.event.kind === "awaiting_input",+ ),+ ).toHaveLength(2);+ });++ it("prefers the failure event over the derived ending", () => {+ // The event carries the reason, which is the whole point of having it.+ const rows = build({+ messages: [+ eventMessage(+ "m1",+ "run_failed",+ { run_id: "run-1", error_summary: "pnpm build failed" },+ "2026-08-01T11:00:00Z",+ ),+ ],+ taskOverrides: { latestRunStatus: "failed", latestRunId: "run-1" },+ });++ expect(rows.filter((row) => row.kind === "run_status")).toHaveLength(0);+ expect(rows.at(-1)).toMatchObject({ kind: "event" });+ });+});++describe("activity events", () => {+ it("reads a run_started payload", () => {+ expect(+ parseActivityEvent({+ event: "run_started",+ payload: { run_id: "run-1", environment: "cloud", branch: "casey/x" },+ }),+ ).toEqual({+ kind: "run_started",+ payload: { runId: "run-1", environment: "cloud", branch: "casey/x" },+ });+ });++ it("falls back rather than rendering a partial payload", () => {+ expect(+ parseActivityEvent({ event: "artifact_created", payload: {} }),+ ).toEqual({+ kind: "artifact_created",+ payload: {+ artifactId: "",+ name: "Artifact",+ artifactType: "",+ version: 1,+ },+ });+ });++ it("drops a pull request event with no url, since it can't be opened", () => {+ expect(parseActivityEvent({ event: "pr_merged", payload: {} })).toBeNull();+ });++ it.each(["", "turn_complete", "something_new"])(+ "returns null for %s",+ (event) => {+ expect(parseActivityEvent({ event, payload: {} })).toBeNull();+ },+ );++ it("matches the backend vocabulary", async () => {+ // The two lists are one contract: adding an event on one side only is a silent gap.+ // `commits_pushed` is emitted by a backend layer with no desktop reporter on this+ // branch (that half is deliberately left out), so it is expected ahead of the enum.+ const emittedLater = new Set(["commits_pushed"]);+ const { readFile } = await import("node:fs/promises");+ const models = await readFile(+ new URL("../../../../../tasks/backend/models.py", import.meta.url)+ .pathname,+ "utf8",+ );+ const enumStart = models.indexOf(+ "class TaskActivityEvent(models.TextChoices):",+ );+ // This desktop change ships ahead of the layers that emit the rest of the vocabulary:+ // master's models.py has no TaskActivityEvent enum yet, and only `canvas_created` and+ // `pr_created` arrive as thread messages today. Those two are the contract until the+ // enum exists; rows for the rest parse and stay undrawn until the events show up.+ const backendEvents =+ enumStart === -1+ ? ["canvas_created", "pr_created"]+ : [+ ...models+ .slice(enumStart)+ .slice(0, models.indexOf("class TaskThreadMessage("))+ .matchAll(/^\s{4}[A-Z_]+ = "([a-z_]+)"/gm),+ ].map((match) => match[1]);+ // An event neither side has shipped yet is expectable either direction, not drift.+ const pendingBackendEvents =+ enumStart === -1+ ? new Set(+ ACTIVITY_EVENTS.filter((event) => !backendEvents.includes(event)),+ )+ : emittedLater;++ expect(+ [...ACTIVITY_EVENTS]+ .filter((event) => !pendingBackendEvents.has(event))+ .sort(),+ ).toEqual(backendEvents.sort());+ });+});++describe("commits pushed", () => {+ it("reads a push into a row with its commits", () => {+ expect(+ parseActivityEvent({+ event: "commits_pushed",+ payload: {+ run_id: "run-1",+ branch: "shy/x",+ repository: "PostHog/posthog",+ total: 3,+ commits: [+ { sha: "a41c9e2", subject: "feat: one", url: "https://x/1" },+ { sha: "7d0be55", subject: "feat: two", url: null },+ ],+ },+ }),+ ).toEqual({+ kind: "commits_pushed",+ payload: {+ runId: "run-1",+ branch: "shy/x",+ repository: "PostHog/posthog",+ total: 3,+ commits: [+ { sha: "a41c9e2", subject: "feat: one", url: "https://x/1" },+ { sha: "7d0be55", subject: "feat: two", url: null },+ ],+ },+ });+ });++ it("drops a push with no readable commit, which cannot be drawn", () => {+ expect(+ parseActivityEvent({+ event: "commits_pushed",+ payload: { run_id: "run-1", commits: [{ subject: "no sha" }] },+ }),+ ).toBeNull();+ });++ it("keys a push on its head SHA, so a retried report is one row", () => {+ const push = (id: string) =>+ eventMessage(+ id,+ "commits_pushed",+ {+ run_id: "run-1",+ branch: "shy/x",+ total: 1,+ commits: [{ sha: "head1", subject: "feat: one" }],+ },+ "2026-08-01T10:30:00Z",+ );++ const rows = build({ messages: [push("m1"), push("m2")] });++ expect(rows.filter((row) => row.kind === "event")).toHaveLength(1);+ });+});diff --git a/products/desktop/packages/core/src/canvas/activityTimeline.ts b/products/desktop/packages/core/src/canvas/activityTimeline.tsnew file mode 100644index 000000000000..9e7a566c18fb--- /dev/null+++ b/products/desktop/packages/core/src/canvas/activityTimeline.ts@@ -0,0 +1,240 @@+/**+ * Merges the task, its thread messages and its comment threads into one ordered list of rows.+ *+ * Kept out of the renderer so the ordering, collapsing and dedupe rules can be tested without+ * mounting anything, the same split `threadTimeline.ts` uses.+ */++import {+ type ActivityEvent,+ parseActivityEvent,+} from "@posthog/core/canvas/activityEvents";+import type { ThreadMessageLike } from "@posthog/core/canvas/threadTimeline";++export interface CommentThreadLike {+ id: string;+ lastActivityAt: string;+ mentionedUserIds: number[];+ resolved: boolean;+ stateEvent: { state: string; createdAt: string } | null;+}++export interface ActivityTaskLike {+ id: string;+ createdAt: string;+ updatedAt: string;+ latestRunId?: string | null;+ latestRunStatus?: string | null;+ /** Tasks from before the thread announcements record their pull request only here. */+ latestRunPrUrl?: string | null;+}++/** Only the fields the row needs, so core stays independent of the UI's item type. */+export interface UserMessageLike {+ id: string;+ content: string;+ timestamp: number;+}++export type ActivityRow<+ TMessage extends ThreadMessageLike = ThreadMessageLike,+ TComment extends CommentThreadLike = CommentThreadLike,+> =+ | { kind: "task_created"; key: string; ts: number }+ | {+ kind: "event";+ key: string;+ ts: number;+ event: ActivityEvent;+ message: TMessage;+ /** Which run of the task a `run_started` row is, counted over the feed. The backend+ * cannot number these without racing two concurrent creations onto one number. */+ runOrdinal?: number;+ }+ | { kind: "human_message"; key: string; ts: number; message: TMessage }+ | { kind: "user_message"; key: string; ts: number; item: UserMessageLike }+ | { kind: "comment"; key: string; ts: number; thread: TComment }+ | {+ kind: "comment_state";+ key: string;+ ts: number;+ thread: TComment;+ state: string;+ }+ | { kind: "run_status"; key: string; ts: number; status: string }+ | { kind: "run_output_pr"; key: string; ts: number; prUrl: string };++/** Rows sharing a timestamp still need a stable order. Ranking them beats nudging the+ * timestamps, which makes two events that genuinely share one fight over a slot. */+const KIND_RANK: Record<ActivityRow["kind"], number> = {+ task_created: 0,+ event: 1,+ human_message: 1,+ user_message: 1,+ comment: 1,+ comment_state: 2,+ run_output_pr: 2,+ run_status: 3,+};++function timestamp(value: string | undefined): number {+ const parsed = Date.parse(value ?? "");+ return Number.isFinite(parsed) ? parsed : 0;+}++export function buildActivityTimeline<+ TMessage extends ThreadMessageLike,+ TComment extends CommentThreadLike,+>({+ task,+ messages,+ commentThreads,+ userMessages = [],+}: {+ task: ActivityTaskLike;+ messages: TMessage[];+ commentThreads: TComment[];+ userMessages?: UserMessageLike[];+}): ActivityRow<TMessage, TComment>[] {+ const rows: ActivityRow<TMessage, TComment>[] = [+ {+ kind: "task_created",+ key: "task-created",+ ts: timestamp(task.createdAt),+ },+ ];++ // Two paths can observe the same thing (the agent's own output and the GitHub webhook+ // backstop), and the backend keys writes to stop that. A client-side guard on the same+ // identity covers rows written before the key existed.+ const seenEvents = new Set<string>();+ let hasTerminalEvent = false;+ let hasPrEvent = false;+ let runStartedSeen = 0;++ for (const message of messages) {+ const event = parseActivityEvent(message);+ if (!event) {+ if ((message.author_kind ?? "human") === "human") {+ rows.push({+ kind: "human_message",+ key: `message-${message.id}`,+ ts: timestamp(message.created_at),+ message,+ });+ }+ continue;+ }+ const identity = `${event.kind}:${eventIdentity(event, message)}`;+ if (seenEvents.has(identity)) continue;+ seenEvents.add(identity);+ if (event.kind === "run_failed") hasTerminalEvent = true;+ if (event.kind === "run_started") runStartedSeen += 1;+ if (+ event.kind === "pr_created" ||+ event.kind === "pr_merged" ||+ event.kind === "pr_closed"+ ) {+ hasPrEvent = true;+ }+ rows.push({+ kind: "event",+ key: `event-${message.id}`,+ ts: timestamp(message.created_at),+ event,+ message,+ ...(event.kind === "run_started" ? { runOrdinal: runStartedSeen } : {}),+ });+ }++ for (const item of userMessages) {+ rows.push({+ kind: "user_message",+ key: `user-message-${item.id}`,+ ts: item.timestamp,+ item,+ });+ }++ for (const thread of commentThreads) {+ rows.push({+ kind: "comment",+ key: `comment-${thread.id}`,+ ts: timestamp(thread.lastActivityAt),+ thread,+ });+ if (thread.stateEvent) {+ rows.push({+ kind: "comment_state",+ key: `comment-state-${thread.id}`,+ ts: timestamp(thread.stateEvent.createdAt),+ thread,+ state: thread.stateEvent.state,+ });+ }+ }++ // A run that recorded its pull request only in its output still gets a row, so a task+ // whose PR was never announced in the thread doesn't hide it entirely.+ if (task.latestRunPrUrl && !hasPrEvent) {+ rows.push({+ kind: "run_output_pr",+ key: `run-output-pr-${task.latestRunId ?? "latest"}`,+ ts: timestamp(task.updatedAt) || timestamp(task.createdAt),+ prUrl: task.latestRunPrUrl,+ });+ }++ // Fallback for tasks whose runs predate the event rows: derive the ending from the task.+ const status = task.latestRunStatus ?? null;+ if (status && isTerminalRunStatus(status) && !hasTerminalEvent) {+ rows.push({+ kind: "run_status",+ key: `run-status-${task.latestRunId ?? "latest"}`,+ ts: timestamp(task.updatedAt) || timestamp(task.createdAt),+ status,+ });+ }++ return rows.sort(+ (left, right) =>+ left.ts - right.ts ||+ KIND_RANK[left.kind] - KIND_RANK[right.kind] ||+ left.key.localeCompare(right.key),+ );+}++function isTerminalRunStatus(status: string): boolean {+ return (+ status === "completed" || status === "failed" || status === "cancelled"+ );+}++function eventIdentity(+ event: ActivityEvent,+ message: ThreadMessageLike,+): string {+ switch (event.kind) {+ case "run_started":+ case "run_failed":+ return event.payload.runId;+ // A run can ask for input more than once, and each ask is its own row. Only the kinds+ // two paths can both report need an identity that ignores which message carried them.+ case "awaiting_input":+ return `${event.payload.runId}:${message.created_at}`;+ case "commits_pushed":+ // The head SHA identifies the push, the way the backend keys it.+ return event.payload.commits.at(-1)?.sha ?? event.payload.runId;+ case "artifact_created":+ case "artifact_revised":+ return `${event.payload.artifactId}:${event.payload.version}`;+ case "canvas_created":+ return event.payload.name;+ case "pr_created":+ case "pr_merged":+ case "pr_closed":+ return event.payload.prUrl;+ case "message_forwarded":+ return event.payload.messageId;+ }+}diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex f95b197ddc7a..414227afb114 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -159,6 +159,42 @@ export interface TaskThreadMessage {author?: UserBasic | null;forwarded_to_agent_at?: string | null;forwarded_by?: UserBasic | null;+ /** Users mentioned in the row, indexed at write time. Absent on older backends. */+ mentioned_user_ids?: number[];+}++/** The latest resolve or reopen on a comment thread. */+export interface TaskCommentStateEvent {+ state: "resolved" | "open";+ author?: UserBasic | null;+ created_at: string;+}++/**+ * One comment thread on a task, collapsed the way the activity timeline shows it+ * (`/thread_messages/comment_activity/`). Mirrors `TaskCommentActivityDTO`.+ */+export interface TaskCommentThreadSummary {+ id: string;+ target: { id: string; type: string; name: string };+ content: string;+ content_truncated: boolean;+ selected_text: string | null;+ author?: UserBasic | null;+ created_at: string;+ last_activity_at: string;+ reply_count: number;+ participants: UserBasic[];+ mentioned_user_ids: number[];+ resolved: boolean;+ state_event: TaskCommentStateEvent | null;+ latest_reply: {+ author?: UserBasic | null;+ content: string;+ /** The excerpt is bounded, so a long reply comes back cut. */+ content_truncated: boolean;+ created_at: string;+ } | null;}/**diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsxindex d565d0de1048..e98e640c8ae0 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx@@ -10,9 +10,14 @@ import {vi,} from "vitest";+// Mutable so a test can render the panel mid-load. Hoisted because a plain `let`+// is initialized after the hoisted mock factories.+const loaded = vi.hoisted(() => ({ thread: true, comments: true }));+vi.mock("@posthog/ui/features/canvas/hooks/useThreadConversation", () => ({useThreadConversation: () => ({timeline: [],+ hasLoadedThread: loaded.thread,agentStatus: null,events: [],isPromptPending: false,@@ -30,6 +35,21 @@ vi.mock("@posthog/ui/features/canvas/hooks/useThreadConversation", () => ({onMentionInsert: vi.fn(),}),}));+vi.mock("@posthog/ui/features/canvas/hooks/useTaskCommentActivity", () => ({+ useTaskCommentActivity: () => ({+ threads: [],+ isLoading: false,+ hasLoaded: loaded.comments,+ }),+}));+// The panel warms this from the task id before the task itself arrives, so it is mounted+// even in the tests that never get a task.+vi.mock("@posthog/ui/features/canvas/hooks/useTaskThread", () => ({+ useTaskThread: () => ({ messages: [], isLoading: false, hasLoaded: true }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useTaskRuns", () => ({+ useTaskRuns: () => ({ runs: [], isLoading: false, refreshRuns: vi.fn() }),+}));vi.mock("@posthog/ui/features/canvas/components/ActivityTimeline", () => ({ActivityTimeline: () => <div>timeline body</div>,}));@@ -75,6 +95,8 @@ describe("ActivityPanel", () => {let scrollTo: MockInstance;beforeEach(() => {+ loaded.thread = true;+ loaded.comments = true;scrollTo = vi.spyOn(Element.prototype, "scrollTo");useCommentNavigationStore.setState({focusByTask: {},@@ -191,4 +213,36 @@ describe("ActivityPanel", () => {expect(scrollTo.mock.calls.length).toBe(timelineScrolls);});++ it("waits for both sources, then never takes the timeline away again", () => {+ // The loader belongs to the first paint only, never over rows already on screen.+ loaded.thread = false;+ loaded.comments = false;+ // A fresh element each time: React bails out of `rerender` when handed the identical one.+ const panel = () => (+ <ActivityPanel+ taskId="task-1"+ channelId="channel-1"+ task={task}+ showTaskSummary={false}+ />+ );+ const view = render(panel());+ expect(screen.getByLabelText("Loading timeline")).toBeInTheDocument();++ loaded.thread = true;+ view.rerender(panel());+ // Comments haven't answered yet, so drawing now would show a partial timeline.+ expect(screen.getByLabelText("Loading timeline")).toBeInTheDocument();++ loaded.comments = true;+ view.rerender(panel());+ expect(screen.getByText("timeline body")).toBeInTheDocument();++ // A refetch flips a query back to loading; the rows must stay put.+ loaded.thread = false;+ view.rerender(panel());+ expect(screen.getByText("timeline body")).toBeInTheDocument();+ expect(screen.queryByLabelText("Loading timeline")).toBeNull();+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsxindex 58381a1c249c..6b813d67c178 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx@@ -1,4 +1,5 @@import {+ ArrowDownIcon,ArrowSquareOutIcon,CaretRightIcon,XIcon,@@ -7,17 +8,24 @@ import { Button, Tabs, TabsList, TabsTrigger } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { Task } from "@posthog/shared/domain-types";import { ActivityTimeline } from "@posthog/ui/features/canvas/components/ActivityTimeline";+import { ActivityLoadingState } from "@posthog/ui/features/canvas/components/activityRows";import { TaskCard } from "@posthog/ui/features/canvas/components/ChannelFeedView";import { TaskArtifactsList } from "@posthog/ui/features/canvas/components/TaskArtifactsList";import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";import {AgentStatusLine,ThreadLoadingState,- ThreadReplyComposer,} from "@posthog/ui/features/canvas/components/ThreadPanel";+import { useTaskCommentActivity } from "@posthog/ui/features/canvas/hooks/useTaskCommentActivity";+import { useTaskThread } from "@posthog/ui/features/canvas/hooks/useTaskThread";import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";import { buildConversationItems } from "@posthog/ui/features/sessions/components/buildConversationItems";+import { mergeConversationItems } from "@posthog/ui/features/sessions/components/mergeConversationItems";+import {+ useOptimisticItemsForTask,+ useSessionIsCloud,+} from "@posthog/ui/features/sessions/sessionStore";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";import { track } from "@posthog/ui/shell/analytics";import { useQuery } from "@tanstack/react-query";@@ -31,9 +39,8 @@ const ACTIVITY_TABS: readonly { key: ActivityTab; label: string }[] = [{ key: "comments", label: "Comments" },] as const;-/** The 32px row this panel leads with: the tabs are the header, so the strip- * lines up with the tab bar of the pane on its left (TabbedPanel) and the- * review toolbar, which are the same fixed height and border. */+/** The tabs are this panel's header, so the strip matches the fixed height and border of+ * the tab bar on its left (TabbedPanel) and of the review toolbar. */function ActivityHeader({tab,onTabChange,@@ -125,21 +132,12 @@ function ActivityConversation({const taskId = task.id;const {timeline,+ messages,agentStatus,events,isPromptPending,- isReady,- members,+ hasLoadedThread,currentUser,- isTaskAuthor,- canForward,- draft,- setDraft,- isSubmitDisabled,- submit,- sendMessageToAgent,- deleteMessage,- onMentionInsert,} = useThreadConversation(task, { surface: "activity_panel" });const [tab, setTab] = useState<ActivityTab>("timeline");@@ -156,12 +154,38 @@ function ActivityConversation({[taskId],);+ // Runs for the whole panel, not just the tab that draws it, so leaving the timeline+ // doesn't discard a fetch already in flight.+ const { threads: commentThreads, hasLoaded: hasLoadedComments } =+ useTaskCommentActivity(taskId);+ // Draw once both durable sources have answered, and never take the timeline away again.+ // Drawing on the thread alone paints sooner but in two waves, with comment rows pushing in+ // among rows already on screen; gating on the live session (`isReady`) blinks a loader over+ // drawn rows while it connects. The latch is set on commit, because Strict Mode and+ // concurrent rendering abandon renders that would otherwise set it.+ const hasDrawnTimeline = useRef(false);+ const timelineReady =+ hasDrawnTimeline.current || (hasLoadedThread && hasLoadedComments);+ useEffect(() => {+ if (hasLoadedThread && hasLoadedComments) hasDrawnTimeline.current = true;+ }, [hasLoadedThread, hasLoadedComments]);++ // Merged exactly as the transcript merges it, because "Show in chat" hands the transcript+ // one of these item ids. A prompt still waiting on its echo is an optimistic item there and+ // the server copy is dropped, so raw events alone would name a row it does not render.+ const optimisticItems = useOptimisticItemsForTask(taskId);+ const isCloudSession = useSessionIsCloud(taskId);const conversationItems = useMemo(() =>tab === "timeline"- ? buildConversationItems(events, isPromptPending).items+ ? mergeConversationItems({+ conversationItems: buildConversationItems(events, isPromptPending)+ .items,+ optimisticItems,+ isCloud: isCloudSession,+ }): [],- [tab, events, isPromptPending],+ [tab, events, isPromptPending, optimisticItems, isCloudSession],);// A thread picked on the artifact itself lives in the Comments tab, so the@@ -172,8 +196,8 @@ function ActivityConversation({const acknowledgeCommentsTabOpen = useCommentNavigationStore((state) => state.acknowledgeCommentsTabOpen,);- // Seed requests that predate this panel, but leave later requests for other- // tasks pending until the reused panel switches to that task.+ // Seed requests that predate this panel, but leave later requests for other tasks pending+ // until the reused panel switches to that task.const seenFocus = useRef(new Map(Object.entries(focusByTask).map(([focusTaskId, focus]) => [@@ -199,15 +223,43 @@ function ActivityConversation({}, [acknowledgeCommentsTabOpen, commentFocus, tab, taskId]);const scrollRef = useRef<HTMLDivElement>(null);- // biome-ignore lint/correctness/useExhaustiveDependencies: scroll when rendered thread content changes+ // Within this much of the bottom still counts as watching the end, so a row arriving+ // mid-poll keeps following. Wide enough to survive a partially scrolled last row.+ const AT_BOTTOM_SLACK_PX = 48;+ const [hasNewerBelow, setHasNewerBelow] = useState(false);+ const scrollToLatest = useCallback(() => {+ const node = scrollRef.current;+ if (!node) return;+ node.scrollTo({ top: node.scrollHeight });+ setHasNewerBelow(false);+ }, []);+ const onScroll = useCallback(() => {+ const node = scrollRef.current;+ if (!node) return;+ const atBottom =+ node.scrollHeight - node.scrollTop - node.clientHeight <=+ AT_BOTTOM_SLACK_PX;+ if (atBottom) setHasNewerBelow(false);+ }, []);+ // biome-ignore lint/correctness/useExhaustiveDependencies: follow the end when rendered content changesuseEffect(() => {// Only the timeline reads bottom-up; the other tabs put what matters on top.if (tab !== "timeline") return;- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });+ const node = scrollRef.current;+ if (!node) return;+ // Following unconditionally yanks the panel to the bottom on every refetch while someone+ // is reading further up, so follow only for a reader already at the end.+ const atBottom =+ node.scrollHeight - node.scrollTop - node.clientHeight <=+ AT_BOTTOM_SLACK_PX;+ if (atBottom) {+ node.scrollTo({ top: node.scrollHeight });+ setHasNewerBelow(false);+ return;+ }+ setHasNewerBelow(true);}, [timeline, events.length, agentStatus?.phase, tab]);- const showComposer = tab === "timeline";-const body = () => {if (tab === "comments") {return <TaskCommentsList task={task} timeline={timeline} />;@@ -221,19 +273,16 @@ function ActivityConversation({/>);}- if (!isReady) return <ThreadLoadingState />;+ if (!timelineReady) return <ActivityLoadingState />;return (<ActivityTimelinetask={task}timeline={timeline}+ messages={messages}conversationItems={conversationItems}- currentUserUuid={currentUser?.uuid}- currentUserEmail={currentUser?.email}- isTaskAuthor={isTaskAuthor}- canForward={canForward}+ commentThreads={commentThreads}+ currentUserId={currentUser?.id}canOpenInPlace={canOpenInPlace}- onSendToAgent={sendMessageToAgent}- onDelete={deleteMessage}/>);};@@ -253,26 +302,30 @@ function ActivityConversation({<TaskCard task={task} channelId={channelId} inThread /></div>)}- <div- ref={scrollRef}- aria-busy={!isReady}- className="flex-1 overflow-y-auto"- >- {body()}+ <div className="relative flex min-h-0 flex-1 flex-col">+ <div+ ref={scrollRef}+ onScroll={onScroll}+ aria-busy={!timelineReady}+ className="flex-1 overflow-y-auto"+ >+ {body()}+ </div>+ {tab === "timeline" && hasNewerBelow && (+ <Button+ variant="default"+ size="sm"+ className="-translate-x-1/2 absolute bottom-2 left-1/2 z-20 shadow-md"+ onClick={scrollToLatest}+ >+ <ArrowDownIcon size={12} />+ New activity+ </Button>+ )}</div>- {showComposer && agentStatus && <AgentStatusLine status={agentStatus} />}-- {showComposer && (- <ThreadReplyComposer- draft={draft}- onDraftChange={setDraft}- onSubmit={submit}- members={members}- allowAgentMention={isTaskAuthor && canForward}- onMentionInsert={onMentionInsert}- disabled={isSubmitDisabled}- />+ {tab === "timeline" && agentStatus && (+ <AgentStatusLine status={agentStatus} />)}</div>);@@ -305,6 +358,11 @@ export function ActivityPanel({});const task = taskProp ?? fetchedTask;+ // Warmed from the id alone so they don't queue behind the task itself, which can take+ // seconds to arrive. Same query keys as the panel's own hooks, so this shares one fetch.+ useTaskThread(taskId, { enabled: !collapsed, markActivityRead: false });+ useTaskCommentActivity(taskId, { enabled: !collapsed });+if (collapsed) {return (<div className="flex h-full w-9 flex-col items-center border-border border-l bg-gray-1">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.tsxnew file mode 100644index 000000000000..ce6a101a26a0--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsx@@ -0,0 +1,187 @@+import { buildThreadTimeline } from "@posthog/core/canvas/threadTimeline";+import type {+ Task,+ TaskCommentThreadSummary,+ TaskThreadMessage,+} from "@posthog/shared/domain-types";+import { ActivityTimeline } from "@posthog/ui/features/canvas/components/ActivityTimeline";+import type { Meta, StoryObj } from "@storybook/react-vite";++const shy = {+ id: 9,+ uuid: "u-shy",+ first_name: "Shy",+ last_name: "Alter",+ email: "[email protected]",+};+const ben = {+ id: 7,+ uuid: "u-ben",+ first_name: "Ben",+ last_name: "White",+ email: "[email protected]",+};++const task = {+ id: "task-1",+ created_at: "2026-08-04T09:00:00Z",+ updated_at: "2026-08-05T16:00:00Z",+ created_by: shy,+ latest_run: { id: "run-1", status: "completed" },+} as unknown as Task;++function event(+ id: string,+ event: string,+ payload: Record<string, unknown>,+ createdAt: string,+): TaskThreadMessage {+ return {+ id,+ task: task.id,+ content: "",+ created_at: createdAt,+ author_kind: "agent",+ event,+ payload,+ } as TaskThreadMessage;+}++// The raw thread, as the API returns it. `timeline` is derived the way the panel derives+// it, so a story cannot show a row shape production never produces.+const messages: TaskThreadMessage[] = [+ event(+ "e1",+ "run_started",+ { run_id: "run-1", environment: "cloud", branch: "shy/activity-events" },+ "2026-08-04T09:02:00Z",+ ),+ event("e2", "awaiting_input", { run_id: "run-1" }, "2026-08-04T09:40:00Z"),+ event(+ "e3",+ "artifact_created",+ {+ artifact_id: "artifact-1",+ name: "activity-events.html",+ artifact_type: "document",+ version: 1,+ },+ "2026-08-04T10:10:00Z",+ ),+ event(+ "e4",+ "message_forwarded",+ { message_id: "m-1", run_id: "run-1" },+ "2026-08-05T09:30:00Z",+ ),+ event(+ "e5",+ "artifact_revised",+ {+ artifact_id: "artifact-1",+ name: "activity-events.html",+ artifact_type: "document",+ version: 2,+ },+ "2026-08-05T10:00:00Z",+ ),+ event(+ "e6",+ "pr_merged",+ {+ pr_url: "https://github.com/PostHog/posthog/pull/80060",+ repository: "PostHog/posthog",+ pr_number: 80060,+ actor: "benjackwhite",+ },+ "2026-08-05T15:30:00Z",+ ),+];++const timeline = buildThreadTimeline(messages);++const commentThreads: TaskCommentThreadSummary[] = [+ {+ id: "thread-1",+ target: {+ id: "artifact-1",+ type: "artifact",+ name: "activity-events.html",+ },+ content:+ "Missing the awaiting-input case — that's the one that costs us time.",+ content_truncated: false,+ selected_text: "every event should also go to the activity panel",+ author: shy,+ created_at: "2026-08-05T08:00:00Z",+ last_activity_at: "2026-08-05T08:45:00Z",+ reply_count: 3,+ participants: [shy, ben],+ mentioned_user_ids: [],+ resolved: false,+ state_event: null,+ latest_reply: {+ author: ben,+ content: "collapse looks right, keep resolve separate",+ created_at: "2026-08-05T08:45:00Z",+ },+ },+ {+ id: "thread-2",+ target: { id: "canvas-1", type: "canvas", name: "Activity mockup" },+ content:+ "@[Ben White]([email protected]) can you sanity check the collapse rule before this ships?",+ content_truncated: false,+ selected_text: null,+ author: shy,+ created_at: "2026-08-05T09:00:00Z",+ last_activity_at: "2026-08-05T09:00:00Z",+ reply_count: 0,+ participants: [shy],+ mentioned_user_ids: [ben.id],+ resolved: true,+ state_event: {+ state: "resolved",+ author: ben,+ created_at: "2026-08-05T11:00:00Z",+ },+ latest_reply: null,+ },+];++const meta: Meta<typeof ActivityTimeline> = {+ title: "Canvas/ActivityTimeline",+ component: ActivityTimeline,+ parameters: { layout: "centered" },+ decorators: [+ (Story) => (+ <div className="w-[468px] border border-border bg-gray-1">+ <Story />+ </div>+ ),+ ],+};++export default meta;++type Story = StoryObj<typeof ActivityTimeline>;++/** Every row the timeline can draw, in the order a real task produces them. */+export const FullTimeline: Story = {+ args: {+ task,+ timeline,+ messages,+ conversationItems: [+ {+ type: "user_message",+ id: "turn-1",+ content: "Add the events that belong on the activity panel.",+ timestamp: Date.parse("2026-08-04T09:05:00Z"),+ },+ // biome-ignore lint/suspicious/noExplicitAny: story fixture for the row under test+ ] as any,+ commentThreads,+ currentUserId: ben.id,+ },+};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 8d0e777678b2..2d91471e2066 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@@ -1,5 +1,6 @@-import type { Task } from "@posthog/shared/domain-types";-import { fireEvent, render, screen } from "@testing-library/react";+import { buildThreadTimeline } from "@posthog/core/canvas/threadTimeline";+import type { Task, TaskThreadMessage } from "@posthog/shared/domain-types";+import { fireEvent, render, screen, within } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("@posthog/ui/features/git-interaction/usePrDetails", () => ({@@ -41,19 +42,16 @@ function renderTimeline(canOpenInPlace?: boolean, items = conversationItems) {<ActivityTimelinetask={task}timeline={[]}+ messages={[]}// biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the rows under testconversationItems={items as any}- isTaskAuthor- canForward={false}canOpenInPlace={canOpenInPlace}- onSendToAgent={() => {}}- onDelete={() => {}}/>,);}beforeEach(() => {- useThreadNavigationStore.setState({ scrollRequests: {} });+ useThreadNavigationStore.setState({ scrollRequests: {}, listeners: {} });});describe("ActivityTimeline", () => {@@ -74,23 +72,12 @@ describe("ActivityTimeline", () => {expect(screen.queryByRole("button", { name: /SA/ })).toBeNull();});- it("asks the transcript to scroll to the clicked message", () => {+ it("opens a message to its full text", () => {renderTimeline(true);- fireEvent.click(screen.getAllByRole("button")[1]);+ fireEvent.click(screen.getByRole("button", { name: /first thing/ }));- expect(useThreadNavigationStore.getState().scrollRequests["task-1"]).toBe(- "turn-2-2-user",- );- });-- it("leaves rows inert with no transcript alongside to drive", () => {- renderTimeline();-- expect(screen.queryAllByRole("button")).toHaveLength(0);- const body = screen.getByText(/first thing/).closest("[data-slot]");- expect(body).toHaveClass("whitespace-pre-wrap", "break-words");- expect(body).not.toHaveClass("line-clamp-1");+ expect(screen.getByText(/and more detail/)).toBeInTheDocument();});it("renders structured references natively in conversation previews", () => {@@ -104,6 +91,7 @@ describe("ActivityTimeline", () => {},]);+ // The whole message fits on the row, so the preview is the content, rendered not raw.expect(screen.getByText("#73874 - Loading…")).toBeInTheDocument();expect(screen.queryByText(/<github_pr/)).toBeNull();});@@ -122,6 +110,8 @@ describe("ActivityTimeline", () => {expect(screen.getByText("Review this")).toBeInTheDocument();expect(screen.queryByText(/<channel_context/)).toBeNull();expect(screen.queryByText("Saved workspace context")).toBeNull();+ // The context lives inside the row, so open it before reaching for the fold.+ fireEvent.click(screen.getByRole("button", { name: /Review this/ }));fireEvent.click(screen.getByRole("button", { name: "#code CONTEXT.md" }));@@ -162,3 +152,275 @@ describe("ActivityTimeline", () => {expect(screen.getByText(/be terse/)).toBeInTheDocument();});});++describe("ActivityTimeline events and comments", () => {+ const threadMessage = (+ id: string,+ event: string,+ payload: Record<string, unknown>,+ createdAt = "2026-07-17T09:20:00Z",+ ) => ({+ id,+ task: "task-1",+ content: "",+ created_at: createdAt,+ author_kind: "agent" as const,+ event,+ payload,+ });++ const commentThread = (overrides = {}) => ({+ id: "thread-1",+ target: { id: "artifact-1", type: "artifact", name: "report.md" },+ content: "this needs a guard",+ content_truncated: false,+ selected_text: "every event should also go to the activity panel",+ author: { id: 7, uuid: "u2", first_name: "Ben", last_name: "White" },+ created_at: "2026-07-17T09:30:00Z",+ last_activity_at: "2026-07-17T09:35:00Z",+ reply_count: 2,+ participants: [+ { id: 7, uuid: "u2", first_name: "Ben", last_name: "White" },+ { id: 9, uuid: "u3", first_name: "Shy", last_name: "Alter" },+ ],+ mentioned_user_ids: [],+ resolved: false,+ state_event: null,+ latest_reply: null,+ ...overrides,+ });++ // `timeline` is derived the way the panel derives it, so a fixture can't hand the+ // component a row shape `buildThreadTimeline` would never emit. Event rows only render+ // if they survive that filter on their way in.+ function renderRows({+ messages = [],+ ...props+ }: Record<string, unknown> & { messages?: TaskThreadMessage[] }) {+ return render(+ <ActivityTimeline+ task={task}+ timeline={buildThreadTimeline(messages)}+ messages={messages}+ conversationItems={[]}+ // biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the rows under test+ {...(props as any)}+ />,+ );+ }++ it("keeps the failure reason one click away, not on the row", () => {+ // Rows are collapsed so the panel reads as a timeline; the detail is what opening is for.+ renderRows({+ messages: [+ threadMessage("m1", "run_failed", {+ run_id: "run-1",+ error_summary: "Command failed: pnpm build",+ }),+ ],+ });++ expect(screen.queryByText(/Command failed: pnpm build/)).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /Run failed/ }));++ expect(screen.getByText(/Command failed: pnpm build/)).toBeInTheDocument();+ });++ it("numbers a run only once the feed shows more than one", () => {+ const first = threadMessage("m1", "run_started", {+ run_id: "run-1",+ environment: "cloud",+ branch: "shy/activity",+ });+ const second = threadMessage("m2", "run_started", { run_id: "run-2" });++ const single = renderRows({ messages: [first] });+ expect(screen.getByText(/Agent started work/)).toBeInTheDocument();+ single.unmount();++ renderRows({ messages: [first, second] });+ expect(screen.getByText(/Agent started run 2/)).toBeInTheDocument();+ });++ it("keeps the anchor with the comment it points at, once opened", () => {+ renderRows({ commentThreads: [commentThread()] });++ expect(+ screen.queryByText(/every event should also go to the activity panel/),+ ).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /commented on/ }));++ expect(+ screen.getByText(/every event should also go to the activity panel/),+ ).toBeInTheDocument();+ expect(+ screen.getByText("2 replies · Ben White, Shy Alter"),+ ).toBeInTheDocument();+ });++ it("reads as a mention when the mention is of you", () => {+ renderRows({+ commentThreads: [commentThread({ mentioned_user_ids: [42] })],+ currentUserId: 42,+ });++ expect(screen.getByText("mentioned you on")).toBeInTheDocument();+ });++ it("reads as an ordinary comment when someone else was mentioned", () => {+ renderRows({+ commentThreads: [commentThread({ mentioned_user_ids: [7] })],+ currentUserId: 42,+ });++ expect(screen.getByText("commented on")).toBeInTheDocument();+ });++ it("gives resolve its own row, with who resolved it", () => {+ renderRows({+ commentThreads: [+ commentThread({+ resolved: true,+ state_event: {+ state: "resolved",+ created_at: "2026-07-17T09:40:00Z",+ author: {+ id: 9,+ uuid: "u3",+ first_name: "Shy",+ last_name: "Alter",+ },+ },+ }),+ ],+ });++ expect(screen.getByText("resolved a thread on")).toBeInTheDocument();+ });+});++describe("ActivityTimeline chat jump", () => {+ it("takes the transcript to the row's own message", () => {+ useThreadNavigationStore.getState().registerTranscript("task-1");+ renderTimeline(true);++ fireEvent.click(screen.getByRole("button", { name: /second thing/ }));+ const row = screen+ .getByRole("button", { name: /second thing/ })+ .closest(".group") as HTMLElement;+ fireEvent.click(within(row).getByRole("button", { name: "Show in chat" }));++ expect(useThreadNavigationStore.getState().scrollRequests["task-1"]).toBe(+ "turn-2-2-user",+ );+ });++ it("offers no jump on a row the transcript does not hold", () => {+ // Only a prompt is the same item in both panes. A thread reply has no counterpart to+ // scroll to, and the prompt of the surrounding turn is not what the reader clicked, so+ // the row opens to its text and offers nothing further.+ useThreadNavigationStore.getState().registerTranscript("task-1");+ const reply = {+ id: "reply-1",+ task: "task-1",+ author: { id: 7, uuid: "u2", first_name: "Ben", last_name: "White" },+ author_kind: "human" as const,+ content: "you seeing this?",+ created_at: "2026-07-17T09:30:00Z",+ };+ render(+ <ActivityTimeline+ task={task}+ // biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the row under test+ timeline={buildThreadTimeline([reply] as any)}+ // biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the row under test+ messages={[reply] as any}+ // biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the row under test+ conversationItems={conversationItems as any}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: /you seeing this/ }));++ expect(screen.queryByRole("button", { name: "Show in chat" })).toBeNull();+ });++ it("offers no jump when the chat holds no prompt to land on", () => {+ // Nothing in the transcript can be scrolled to, so the row stays inert rather than+ // growing a button that goes nowhere.+ useThreadNavigationStore.getState().registerTranscript("task-1");+ renderTimeline(true, []);++ expect(+ screen.queryByRole("button", { name: /created this task/ }),+ ).toBeNull();+ expect(screen.queryByRole("button", { name: "Show in chat" })).toBeNull();+ });++ it("offers no jump when no transcript is mounted to answer it", () => {+ renderTimeline(true);++ fireEvent.click(screen.getByRole("button", { name: /second thing/ }));++ expect(screen.queryByRole("button", { name: "Show in chat" })).toBeNull();+ });+});++describe("ActivityTimeline connectors", () => {+ it("runs the line between every pair of beads, and no further", () => {+ // Each row draws the half above and the half below its own bead, so consecutive rows+ // meet: the first row has no upper half and the last has no lower one.+ const { container } = renderTimeline(true);++ const rows = [...container.querySelectorAll(".group")];+ const halves = rows.map(+ (row) => row.querySelectorAll("[aria-hidden].w-px").length,+ );+ expect(rows.length).toBeGreaterThan(2);+ expect(halves.at(0)).toBe(1);+ expect(halves.at(-1)).toBe(1);+ expect(halves.slice(1, -1).every((count) => count === 2)).toBe(true);+ });++ it("always opens a message to its full text", () => {+ renderTimeline(true);++ fireEvent.click(screen.getByRole("button", { name: /second thing/ }));++ expect(screen.getAllByText(/second thing/).length).toBeGreaterThan(1);+ });+});++describe("ActivityTimeline thread replies", () => {+ const reply = {+ id: "reply-1",+ task: "task-1",+ author: { id: 7, uuid: "u2", first_name: "Ben", last_name: "White" },+ author_kind: "human" as const,+ content: "@[Shy Alter]([email protected]) you seeing this?\nsecond line",+ created_at: "2026-07-17T09:30:00Z",+ };++ it("collapses a legacy thread reply like every other row", () => {+ // Legacy replies collapse like every other row, so the panel reads as a timeline+ // rather than a chat log.+ render(+ <ActivityTimeline+ task={task}+ // biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the row under test+ timeline={buildThreadTimeline([reply] as any)}+ // biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the row under test+ messages={[reply] as any}+ conversationItems={[]}+ />,+ );++ expect(screen.queryByText(/second line/)).toBeNull();+ // The mention renders as a chip in the preview, not as its markup.+ expect(screen.queryByText(/@\[/)).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: /you seeing this/ }));++ expect(screen.getByText(/second line/)).toBeInTheDocument();+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsxindex c899b0bbd259..e4de94dc182c 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx@@ -1,83 +1,70 @@+import { FileTextIcon, ScrollIcon } from "@phosphor-icons/react";import {- CheckCircleIcon,- FileTextIcon,- PlusCircleIcon,- XCircleIcon,-} from "@phosphor-icons/react";+ type ActivityRow,+ buildActivityTimeline,+ type UserMessageLike,+} from "@posthog/core/canvas/activityTimeline";import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";+import { DEFAULT_TAB_IDS } from "@posthog/core/panels/panelConstants";+import { findTabInTree } from "@posthog/core/panels/panelTree";import {Collapsible,CollapsibleContent,CollapsibleTrigger,- cn,- ThreadItem,- ThreadItemAuthor,- ThreadItemBody,- ThreadItemContent,ThreadItemGroup,- ThreadItemGutter,- ThreadItemHeader,} from "@posthog/quill";import type {Task,+ TaskCommentThreadSummary,TaskThreadMessage,UserBasic,} from "@posthog/shared/domain-types";-import { isTerminalStatus } from "@posthog/shared/domain-types";-import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";-import { MentionText } from "@posthog/ui/features/canvas/components/MentionText";import {- ThreadArtifactRow,- ThreadMessageRow,-} from "@posthog/ui/features/canvas/components/ThreadPanel";-import { ThreadTimestamp } from "@posthog/ui/features/canvas/components/ThreadTimestamp";+ ActivityEventRow,+ CommentRow,+ CommentStateRow,+ CREATED_BADGE,+ MESSAGE_BADGE,+ MessageBubble,+ PersonBead,+ RunStatusRow,+ ThreadReplyRow,+ TimelineRow,+} from "@posthog/ui/features/canvas/components/activityRows";+import { MentionText } from "@posthog/ui/features/canvas/components/MentionText";+import { ThreadArtifactCard } from "@posthog/ui/features/canvas/components/ThreadPanel";import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";import type { buildConversationItems } from "@posthog/ui/features/sessions/components/buildConversationItems";+import { extractCanvasInstructions } from "@posthog/ui/features/sessions/components/session-update/canvasInstructions";import { extractChannelContext } from "@posthog/ui/features/sessions/components/session-update/channelContext";import { extractCustomInstructions } from "@posthog/ui/features/sessions/components/session-update/customInstructions";-import { useThreadNavigationStore } from "@posthog/ui/features/sessions/threadNavigationStore";-import { Fragment, type KeyboardEvent, type ReactNode, useMemo } from "react";+import { collapsePiSkillInvocation } from "@posthog/ui/features/sessions/components/session-update/piSkillInvocation";+import {+ useHasTranscriptListener,+ useThreadNavigationStore,+} from "@posthog/ui/features/sessions/threadNavigationStore";+import { Fragment, useMemo } from "react";type ConversationItem = ReturnType<typeof buildConversationItems>["items"][number];-/** A lifecycle marker (task created, run finished): an icon bubble and a single- * line, in the same size and colour as every other row's copy. Only the icon- * distinguishes it, so the pane reads as one typographic system. */-function ActivityEventRow({- icon,- label,- timestamp,-}: {- icon: ReactNode;- label: string;- timestamp: string;-}) {- return (- <div className="flex items-center gap-2 py-1.5 pr-2 pl-2">- <div className="flex w-10 shrink-0 justify-center">- <span className="relative z-10 flex size-6 items-center justify-center rounded-full bg-gray-3">- {icon}- </span>- </div>- <span className="min-w-0 truncate text-[13px]">{label}</span>- <ThreadTimestamp dateTime={timestamp} />- </div>- );-}-function UserMessageRow({author,content,timestamp,- onSelect,+ connectedAbove,+ connectedBelow,+ onShowInChat,}: {author?: UserBasic | null;content: string;timestamp: string;- /** Jumps the transcript to this message. Absent once the run is unavailable. */- onSelect?: () => void;+ connectedAbove: boolean;+ connectedBelow: boolean;+ onShowInChat?: () => void;}) {const name = author ? userDisplayName(author) : "You";const channelContext = useMemo(@@ -85,55 +72,47 @@ function UserMessageRow({[content],);const afterChannelContext = channelContext?.stripped ?? content;- const customInstructions = useMemo(- () => extractCustomInstructions(afterChannelContext),+ // Every block the chat strips has to be stripped here too, or the raw XML shows up on+ // the timeline for a viewer whose chat hid it.+ const canvasInstructions = useMemo(+ () => extractCanvasInstructions(afterChannelContext),[afterChannelContext],);- const displayContent = customInstructions?.stripped ?? afterChannelContext;- // The row itself is the hit target. `ThreadItem` renders an <article>, which a- // <button> may not wrap and which can't become one (quill's primitive takes no- // `render`), so it carries the button role and its own key handling.- //- // Deliberately no `aria-label`: the button takes its name from its contents, so- // it announces the author, time and preview a sighted user sees. A label would- // replace all three — and since every row here is authored by the task creator,- // one built from the name alone would be identical on every row.- const activation = onSelect- ? ({- role: "button",- tabIndex: 0,- onClick: onSelect,- onKeyDown: (event: KeyboardEvent<HTMLElement>) => {- if (event.key !== "Enter" && event.key !== " ") return;- event.preventDefault();- onSelect();- },- } as const)- : {};+ const afterCanvasInstructions =+ canvasInstructions?.stripped ?? afterChannelContext;+ const customInstructions = useMemo(+ () => extractCustomInstructions(afterCanvasInstructions),+ [afterCanvasInstructions],+ );+ const displayContent = collapsePiSkillInvocation(+ customInstructions?.stripped ?? afterCanvasInstructions,+ );+ const trimmed = displayContent.trim();+ const firstLine = trimmed.split("\n", 1)[0] ?? "";return (- <ThreadItem- className={cn("rounded-none", onSelect && "cursor-pointer")}- {...activation}- >- {/* Decorative: the author's name is written beside it, so keep the avatar's- initials out of the row's accessible name. */}- <ThreadItemGutter className="justify-center" aria-hidden>- <UserAvatar user={author} size="sm" className="sticky top-2" />- </ThreadItemGutter>- <ThreadItemContent>- <ThreadItemHeader>- <ThreadItemAuthor className="text-[13px]">{name}</ThreadItemAuthor>- <ThreadTimestamp dateTime={timestamp} />- </ThreadItemHeader>- <ThreadItemBody className="mt-1.5 whitespace-pre-wrap break-words text-[13px]">- <MentionText content={displayContent} />+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={<PersonBead user={author} badge={MESSAGE_BADGE} />}+ timestamp={timestamp}+ onShowInChat={onShowInChat}+ detail={+ <div className="space-y-1.5">+ <MessageBubble content={displayContent} />+ {canvasInstructions && (+ <Collapsible className="min-w-0 bg-transparent hover:bg-transparent data-open:bg-transparent">+ <CollapsibleTrigger className="min-h-0 w-full bg-transparent px-0 py-1 text-left hover:bg-transparent aria-expanded:bg-transparent">+ <ScrollIcon size={12} />+ <span className="truncate text-xs">Canvas instructions</span>+ </CollapsibleTrigger>+ <CollapsibleContent className="mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md border border-border bg-muted p-2 text-muted-foreground text-xs">+ {canvasInstructions.body}+ </CollapsibleContent>+ </Collapsible>+ )}{channelContext && (- <Collapsible className="mt-2 min-w-0 bg-transparent hover:bg-transparent data-open:bg-transparent">- <CollapsibleTrigger- className="min-h-0 w-full bg-transparent px-0 py-1 text-left hover:bg-transparent aria-expanded:bg-transparent"- onClick={(event) => event.stopPropagation()}- onKeyDown={(event) => event.stopPropagation()}- >+ <Collapsible className="min-w-0 bg-transparent hover:bg-transparent data-open:bg-transparent">+ <CollapsibleTrigger className="min-h-0 w-full bg-transparent px-0 py-1 text-left hover:bg-transparent aria-expanded:bg-transparent"><FileTextIcon size={12} /><span className="truncate text-xs">{channelContext.mention.name@@ -147,184 +126,297 @@ function UserMessageRow({</CollapsibleContent></Collapsible>)}- </ThreadItemBody>- </ThreadItemContent>- </ThreadItem>+ </div>+ }+ >+ <span className="font-medium">{name}</span>{" "}+ {/* Through MentionText like the body: a preview that prints raw mention or chip+ markup is the same bug as a body that does. */}+ <span className="text-muted-foreground">+ <MentionText content={firstLine} />+ </span>+ </TimelineRow>);}+/** An inline `= []` default is a new array on every render, which would rebuild the timeline+ * through the memo's dependency list. */+const NO_COMMENT_THREADS: TaskCommentThreadSummary[] = [];+export function ActivityTimeline({task,timeline,+ messages,conversationItems,- currentUserUuid,- currentUserEmail,- isTaskAuthor,- canForward,+ commentThreads = NO_COMMENT_THREADS,+ currentUserId,canOpenInPlace,- onSendToAgent,- onDelete,}: {task: Task;timeline: ThreadTimelineRow<TaskThreadMessage>[];+ /** The event rows live among the agent-authored messages, which `timeline` filters out,+ * so they have to arrive separately. */+ messages: TaskThreadMessage[];conversationItems: ConversationItem[];- currentUserUuid?: string;- currentUserEmail?: string | null;- isTaskAuthor: boolean;- canForward: boolean;- /** True when the task's transcript and review pane are mounted beside this- * pane. False in the channel-home sidebar, where there is nothing to drive —- * rows there stay inert and PRs open externally instead of dead-clicking. */+ commentThreads?: TaskCommentThreadSummary[];+ currentUserId?: number;+ /** True when the task's transcript and review pane are mounted beside this pane. False in+ * the channel-home sidebar, where rows stay inert and PRs open externally instead. */canOpenInPlace?: boolean;- onSendToAgent: (messageId: string) => void;- onDelete: (messageId: string) => void;}) {+ const requestCommentFocus = useCommentNavigationStore(+ (state) => state.requestCommentFocus,+ );++ const messageRows = useMemo(() => {+ const byId = new Map<string, ThreadTimelineRow<TaskThreadMessage>>();+ for (const row of timeline) byId.set(row.message.id, row);+ return byId;+ }, [timeline]);++ const rows = useMemo(+ () =>+ buildActivityTimeline({+ task: {+ id: task.id,+ createdAt: task.created_at,+ updatedAt: task.updated_at,+ latestRunId: task.latest_run?.id ?? null,+ latestRunStatus: task.latest_run?.status ?? null,+ latestRunPrUrl:+ typeof task.latest_run?.output?.pr_url === "string"+ ? task.latest_run.output.pr_url+ : null,+ },+ messages,+ commentThreads: commentThreads.map((thread) => ({+ id: thread.id,+ lastActivityAt: thread.last_activity_at,+ mentionedUserIds: thread.mentioned_user_ids ?? [],+ resolved: thread.resolved,+ stateEvent: thread.state_event+ ? {+ state: thread.state_event.state,+ createdAt: thread.state_event.created_at,+ }+ : null,+ })),+ userMessages: conversationItems.reduce<UserMessageLike[]>(+ (items, item) => {+ if (item.type === "user_message") {+ items.push({+ id: item.id,+ content: item.content,+ timestamp: item.timestamp,+ });+ }+ return items;+ },+ [],+ ),+ }),+ [task, messages, commentThreads, conversationItems],+ );++ // 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(+ (count, row) =>+ row.kind === "event" && row.event.kind === "run_started"+ ? count + 1+ : count,+ 0,+ ),+ [rows],+ );++ const threadsById = useMemo(() => {+ const byId = new Map<string, TaskCommentThreadSummary>();+ for (const thread of commentThreads) byId.set(thread.id, thread);+ return byId;+ }, [commentThreads]);++ const focusThread = (thread: TaskCommentThreadSummary) => {+ if (!canOpenInPlace) return undefined;+ return () =>+ requestCommentFocus(+ task.id,+ // The scope/itemId pair the comment stores; `task` scope points at the task itself.+ thread.target.type === "task"+ ? { scope: "task", itemId: task.id }+ : {+ scope:+ thread.target.type === "canvas"+ ? "desktop_canvas"+ : "task_artifact",+ itemId: thread.target.id,+ },+ thread.id,+ );+ };++ const hasTranscript = useHasTranscriptListener(task.id);const requestScrollToMessage = useThreadNavigationStore((state) => state.requestScrollToMessage,);+ const setActiveTab = usePanelLayoutStore((state) => state.setActiveTab);+ const chatPanelId = usePanelLayoutStore((state) => {+ const tree = state.taskLayouts[task.id]?.panelTree;+ if (!tree) return null;+ return findTabInTree(tree, DEFAULT_TAB_IDS.LOGS)?.panelId ?? null;+ });- const nodes = useMemo(() => {- const entries: { key: string; ts: number; node: ReactNode }[] = [];- const createdTs = Date.parse(task.created_at) || 0;- entries.push({- key: "task-created",- ts: createdTs,- node: (- <ActivityEventRow- icon={- <PlusCircleIcon size={14} weight="fill" className="text-gray-11" />- }- label={`${task.created_by ? userDisplayName(task.created_by) : "Someone"} created this task`}- timestamp={task.created_at}- />- ),- });+ /**+ * Offered on prompt rows only. A prompt is the one item both panes share, so the jump names+ * its own target. Every other row is a thread message, a comment or a task field, none of+ * which the transcript renders, and the nearest prompt is not what the reader clicked.+ */+ const showPromptInChat = (promptId: string) => {+ if (!hasTranscript) return undefined;+ return () => {+ // The transcript's tab stays mounted while hidden, so without this the scroll happens+ // off screen and the click reads as doing nothing.+ if (chatPanelId) setActiveTab(task.id, chatPanelId, DEFAULT_TAB_IDS.LOGS);+ requestScrollToMessage(task.id, promptId);+ };+ };- for (const item of conversationItems) {- if (item.type !== "user_message") continue;- entries.push({- key: `user-message-${item.id}`,- ts: item.timestamp,- node: (+ const renderRow = (+ row: ActivityRow<TaskThreadMessage>,+ connectedAbove: boolean,+ connectedBelow: boolean,+ ) => {+ switch (row.kind) {+ case "task_created":+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={<PersonBead user={task.created_by} badge={CREATED_BADGE} />}+ timestamp={task.created_at}+ >+ {`${task.created_by ? userDisplayName(task.created_by) : "Someone"} created this task`}+ </TimelineRow>+ );+ case "user_message":+ return (<UserMessageRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}author={task.created_by}- content={item.content}- timestamp={new Date(item.timestamp).toISOString()}- onSelect={- canOpenInPlace- ? () => requestScrollToMessage(task.id, item.id)- : undefined+ content={row.item.content}+ timestamp={new Date(row.item.timestamp).toISOString()}+ onShowInChat={showPromptInChat(row.item.id)}+ />+ );+ case "human_message":+ return (+ <ThreadReplyRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ author={row.message.author}+ content={row.message.content}+ timestamp={row.message.created_at}+ />+ );+ case "event": {+ // A canvas or pull request announcement keeps its card, as the row's detail: every+ // row in the panel opens the same way.+ const artifactRow = messageRows.get(row.message.id);+ return (+ <ActivityEventRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ event={row.event}+ timestamp={row.message.created_at}+ runCount={runStartedCount}+ runOrdinal={row.runOrdinal}+ detail={+ artifactRow?.kind === "artifact" ? (+ <ThreadArtifactCard+ artifact={artifactRow.artifact}+ openInPlaceTaskId={canOpenInPlace ? task.id : undefined}+ />+ ) : undefined}/>- ),- });- }-- let hasPrArtifact = false;- for (const row of timeline) {- if (row.kind === "artifact" && row.artifact.kind === "pr") {- hasPrArtifact = true;+ );}- entries.push({- key: `thread-${row.message.id}`,- ts: row.timestamp,- node:- row.kind === "human" ? (- <ThreadMessageRow- message={row.message}- isTaskAuthor={isTaskAuthor}- isOwnMessage={- !!currentUserUuid &&- currentUserUuid === row.message.author?.uuid- }- currentUserEmail={currentUserEmail}- canForward={canForward}- preview- onSendToAgent={() => onSendToAgent(row.message.id)}- onDelete={() => onDelete(row.message.id)}- />- ) : (- <ThreadArtifactRow- artifact={row.artifact}- createdAt={row.message.created_at}- openInPlaceTaskId={canOpenInPlace ? task.id : undefined}- />- ),- });- }-- const updatedTs = Date.parse(task.updated_at) || createdTs;- const outputPr = task.latest_run?.output?.pr_url;- if (typeof outputPr === "string" && outputPr && !hasPrArtifact) {- entries.push({- key: "output-pr",- ts: updatedTs,- node: (- <ThreadArtifactRow- artifact={{ kind: "pr", url: outputPr }}- createdAt={task.updated_at}- openInPlaceTaskId={canOpenInPlace ? task.id : undefined}+ case "comment": {+ const thread = threadsById.get(row.thread.id);+ if (!thread) return null;+ return (+ <CommentRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ thread={thread}+ isMentioned={+ !!currentUserId &&+ (thread.mentioned_user_ids ?? []).includes(currentUserId)+ }+ onSelect={focusThread(thread)}/>- ),- });- }-- const runStatus = task.latest_run?.status;- if (runStatus && isTerminalStatus(runStatus)) {- const succeeded = runStatus === "completed";- entries.push({- key: "run-status",- ts: updatedTs + 1,- node: (+ );+ }+ case "comment_state": {+ const thread = threadsById.get(row.thread.id);+ if (!thread) return null;+ return (+ <CommentStateRow+ thread={thread}+ state={row.state}+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ />+ );+ }+ case "run_output_pr":+ return (<ActivityEventRow- icon={- succeeded ? (- <CheckCircleIcon- size={14}- weight="fill"- className="text-green-9"- />- ) : (- <XCircleIcon size={14} weight="fill" className="text-red-9" />- )+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ event={{+ kind: "pr_created",+ payload: {+ prUrl: row.prUrl,+ repository: null,+ prNumber: null,+ actor: null,+ },+ }}+ timestamp={task.updated_at}+ runCount={runStartedCount}+ detail={+ <ThreadArtifactCard+ artifact={{ kind: "pr", url: row.prUrl }}+ openInPlaceTaskId={canOpenInPlace ? task.id : undefined}+ />}- label={`Task ${runStatus.replace(/_/g, " ")}`}+ />+ );+ case "run_status":+ return (+ <RunStatusRow+ status={row.status}timestamp={task.updated_at}+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}/>- ),- });+ );}-- return entries.sort((a, b) => a.ts - b.ts);- }, [- conversationItems,- timeline,- task,- isTaskAuthor,- canForward,- currentUserUuid,- currentUserEmail,- onSendToAgent,- onDelete,- canOpenInPlace,- requestScrollToMessage,- ]);+ };return (- <div className="relative">- {/* Every row centers its node in a 2.5rem gutter inset by the row's- 0.5rem padding, so the line runs through 0.5 + 2.5/2 = 1.75rem. */}- <div- aria-hidden- className="pointer-events-none absolute top-4 bottom-4 left-[1.75rem] w-px bg-border"- />- <div className="relative z-10">- <ThreadItemGroup>- {nodes.map((entry) => (- <Fragment key={entry.key}>{entry.node}</Fragment>- ))}- </ThreadItemGroup>- </div>+ <div className="px-1 py-2">+ <ThreadItemGroup>+ {rows.map((row, index) => (+ <Fragment key={row.key}>+ {renderRow(row, index > 0, index < rows.length - 1)}+ </Fragment>+ ))}+ </ThreadItemGroup></div>);}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsxindex ee0fea3017d8..8ea61a4c3e39 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx@@ -1,4 +1,4 @@-import type { Task } from "@posthog/shared/domain-types";+import type { Task, TaskThreadMessage } from "@posthog/shared/domain-types";import { Theme } from "@radix-ui/themes";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";@@ -26,6 +26,13 @@ vi.mock("@tanstack/react-router", () => ({vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskData", () => ({useChannelTaskData: () => undefined,}));+const threadMocks = vi.hoisted(() => ({+ messages: [] as TaskThreadMessage[],+}));++vi.mock("@posthog/ui/features/canvas/hooks/useTaskThread", () => ({+ useTaskThread: () => ({ messages: threadMocks.messages }),+}));vi.mock("@posthog/ui/features/sidebar/useTaskPrStatus", () => ({useTaskPrStatus: () => ({ prState: null }),}));@@ -33,7 +40,7 @@ vi.mock("@posthog/ui/features/browser-tabs/TaskTabIcon", () => ({TaskTabIcon: () => <span />,}));-import { TaskCard, TaskFeedRow } from "./ChannelFeedView";+import { ReplyFooter, TaskCard, TaskFeedRow } from "./ChannelFeedView";const task = {id: "task-1",@@ -55,6 +62,7 @@ const task = {afterEach(() => {vi.restoreAllMocks();+ threadMocks.messages = [];});// ExpandablePrompt measures how the prompt wraps to decide where to cut and@@ -133,4 +141,28 @@ describe("TaskFeedRow", () => {expect(screen.queryByRole("button")).not.toBeInTheDocument();});+ it("wears the agent's face on an agent reply", () => {+ // An agent reply carries no user, so the person avatar fell back to an initial and every+ // agent in the thread collapsed onto one slot.+ threadMocks.messages = [+ {+ id: "agent-reply",+ task: task.id,+ author_kind: "agent",+ content: "Finished the task",+ created_at: "2026-07-17T12:05:00.000Z",+ author: null,+ } as unknown as TaskThreadMessage,+ ];++ const { container } = render(+ <ReplyFooter taskId={task.id} inView onOpenThread={() => undefined} />,+ );++ expect(screen.getByText("1 reply")).toBeInTheDocument();+ expect(screen.queryByText("U")).toBeNull();+ expect(+ container.querySelector('[data-slot="avatar-fallback"] svg'),+ ).not.toBeNull();+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsxindex 2fea19e94008..2090760aca8f 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx@@ -306,7 +306,7 @@ export function TaskCard({//// The fetch/poll only runs for near-viewport rows (`inView`); off-screen rows// render the static affordance and idle, so a long feed isn't polling per row.-function ReplyFooter({+export function ReplyFooter({taskId,inView,onOpenThread,@@ -320,13 +320,20 @@ function ReplyFooter({enabled: inView,markActivityRead: false,});+ // Keyed by who authored the reply, not by author uuid: an agent reply carries no user, so+ // every agent in the thread collapsed onto one "unknown" slot and wore a person's fallback+ // initial. The whole message is kept, because drawing the agent needs its kind.const authors = useMemo(() => {- const seen = new Map<string, (typeof messages)[number]["author"]>();+ const seen = new Map<string, (typeof messages)[number]>();for (const message of messages) {- const key = message.author?.uuid ?? "unknown";- if (!seen.has(key)) seen.set(key, message.author);+ const authorKind = message.author_kind ?? "human";+ const key =+ authorKind === "human"+ ? `human:${message.author?.uuid ?? "unknown"}`+ : authorKind;+ if (!seen.has(key)) seen.set(key, message);}- return [...seen.values()].slice(0, 4);+ return [...seen.entries()].slice(0, 4);}, [messages]);if (messages.length === 0) {@@ -350,9 +357,17 @@ function ReplyFooter({return (<ThreadItemReplies onClick={onOpenThread} className="mt-1"><AvatarGroup size="xs">- {authors.map((author, index) => (- <UserAvatar key={author?.uuid ?? index} user={author} size="xs" />- ))}+ {authors.map(([key, message]) =>+ message.author_kind === "agent" ? (+ <Avatar key={key} size="xs">+ <AvatarFallback>+ <RobotIcon size={12} />+ </AvatarFallback>+ </Avatar>+ ) : (+ <UserAvatar key={key} user={message.author} size="xs" />+ ),+ )}</AvatarGroup><ThreadItemRepliesLabel>{messages.length} {messages.length === 1 ? "reply" : "replies"}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ThreadPanel.tsx b/products/desktop/packages/ui/src/features/canvas/components/ThreadPanel.tsxindex bc23b971fa54..362256987bb7 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ThreadPanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ThreadPanel.tsx@@ -311,6 +311,23 @@ export function ThreadArtifactRow({);}+/** Just the card an artifact announcement carries, without the thread row around it, for+ * surfaces that supply their own row (the activity timeline opens it as a row's detail). */+export function ThreadArtifactCard({+ artifact,+ openInPlaceTaskId,+}: {+ artifact: ThreadArtifact;+ /** Task whose review pane is mounted alongside; absent means open externally. */+ openInPlaceTaskId?: string;+}) {+ return artifact.kind === "canvas" ? (+ <CanvasArtifactCard name={artifact.name} url={artifact.url} />+ ) : (+ <PrArtifactCard url={artifact.url} openInPlaceTaskId={openInPlaceTaskId} />+ );+}+export function ThreadLoadingState() {return (<Empty className="h-full border-0">diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsxnew file mode 100644index 000000000000..33ade1ff57c5--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx@@ -0,0 +1,695 @@+/**+ * Adding an event kind means an entry in `EVENT_TONES` and `EVENT_ICONS` plus a line of copy.+ */++import {+ ArrowCounterClockwiseIcon,+ ArrowsClockwiseIcon,+ CaretRightIcon,+ ChatCircleIcon,+ CheckIcon,+ FileTextIcon,+ GitCommitIcon,+ GitMergeIcon,+ GitPullRequestIcon,+ PaperPlaneTiltIcon,+ PlayIcon,+ PlusIcon,+ ProhibitIcon,+ QuestionIcon,+ SquaresFourIcon,+ XIcon,+} from "@phosphor-icons/react";+import {+ type ActivityEvent,+ prLabel,+} from "@posthog/core/canvas/activityEvents";+import { xmlToContent } from "@posthog/core/message-editor/content";+import {+ Button,+ ChatBubble,+ ChatBubbleContent,+ cn,+ Skeleton,+} from "@posthog/quill";+import { splitMentionSegments } from "@posthog/shared";+import type {+ TaskCommentThreadSummary,+ UserBasic,+} from "@posthog/shared/domain-types";+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";+import { MentionText } from "@posthog/ui/features/canvas/components/MentionText";+import { ThreadTimestamp } from "@posthog/ui/features/canvas/components/ThreadTimestamp";+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import { ChatMarkdown } from "@posthog/ui/features/sessions/components/chat-thread/ChatMarkdown";+import { type ReactNode, useMemo, useState } from "react";++export function TimelineRow({+ gutter,+ children,+ timestamp,+ detail,+ defaultOpen = false,+ connectedAbove = true,+ connectedBelow = true,+ onShowInChat,+ ariaLabel,+}: {+ gutter: ReactNode;+ children: ReactNode;+ timestamp: string;+ detail?: ReactNode;+ /** Only a prompt row carries one, because a prompt is the same conversation item in both+ * panes and so resolves exactly. Absent when no transcript is mounted to answer. */+ onShowInChat?: () => void;+ defaultOpen?: boolean;+ connectedAbove?: boolean;+ connectedBelow?: boolean;+ ariaLabel?: string;+}) {+ const [open, setOpen] = useState(defaultOpen);+ // The jump counts as detail, so a row whose only content is the action still opens.+ const body =+ detail !== undefined && detail !== null ? (+ <div className="space-y-1.5">+ {detail}+ {onShowInChat && (+ <DetailAction onClick={onShowInChat}>Show in chat</DetailAction>+ )}+ </div>+ ) : onShowInChat ? (+ <DetailAction onClick={onShowInChat}>Show in chat</DetailAction>+ ) : null;+ const hasDetail = body !== null;+ const header = (+ <div className="flex min-w-0 flex-1 items-center gap-1.5 text-[12.5px] leading-[22px]">+ <span className="min-w-0 truncate">{children}</span>+ <ThreadTimestamp dateTime={timestamp} />+ {hasDetail && (+ <CaretRightIcon+ size={11}+ aria-hidden+ className={cn(+ "ml-auto shrink-0 text-muted-foreground opacity-0 transition-transform group-hover:opacity-60",+ open && "rotate-90 opacity-60",+ )}+ />+ )}+ </div>+ );+ return (+ <div+ className={cn(+ "group flex items-stretch gap-2 rounded-md py-2.5 pr-2 pl-2 transition-colors",+ hasDetail &&+ "cursor-pointer focus-within:bg-gray-2 hover:bg-gray-2 has-[:focus-visible]:bg-gray-2",+ )}+ >+ {/* The connector lives inside the row, so the hover fill paints behind it and+ consecutive rows' segments meet into one line. Two halves, so the first and last+ rows stop at their own bead. The offsets are the row's py-2.5: this column+ stretches only to the content box, so each segment has to cross the padding to+ reach the next row's. 11px is the bead's centre. */}+ <div className="relative flex w-10 shrink-0 justify-center self-stretch">+ {connectedAbove && (+ <span+ aria-hidden+ className="-translate-x-1/2 -top-2.5 absolute left-1/2 h-[21px] w-px bg-gray-6"+ />+ )}+ {connectedBelow && (+ <span+ aria-hidden+ className="-translate-x-1/2 -bottom-2.5 absolute top-[11px] left-1/2 w-px bg-gray-6"+ />+ )}+ {/* h-[22px] is the copy's line height, so the bead centres on the first line+ whatever the row grows to. */}+ <div className="relative z-10 flex h-[22px] items-center">{gutter}</div>+ </div>+ <div className="min-w-0 flex-1">+ {hasDetail ? (+ <>+ {/* flex, not block: an inline-level button contributes its own inherited+ line-height as a strut, which pushes the copy 3px below the bead. */}+ <button+ type="button"+ aria-expanded={open}+ aria-label={ariaLabel}+ className="flex w-full text-left focus-visible:outline-none"+ onClick={() => setOpen((current) => !current)}+ >+ {header}+ </button>+ {open && <div className="mt-1.5">{body}</div>}+ </>+ ) : (+ header+ )}+ </div>+ </div>+ );+}++/**+ * Two recipes because the sizes need different contrast. A bead uses the soft steps, which+ * stay quiet beside the copy. A badge is 12px, too small to read as a wash, so it uses solid+ * step 9 with the foreground that scale is designed for: dark on amber, light on the rest.+ */+const BEAD_TONES = {+ neutral: "border-gray-6 bg-gray-3 text-gray-11",+ blue: "border-blue-6 bg-blue-3 text-blue-11",+ green: "border-green-6 bg-green-3 text-green-11",+ amber: "border-amber-6 bg-amber-3 text-amber-11",+ violet: "border-violet-6 bg-violet-3 text-violet-11",+ red: "border-red-6 bg-red-3 text-red-11",+} as const;++const BADGE_TONES = {+ neutral: "bg-gray-10 text-gray-1",+ blue: "bg-blue-9 text-white",+ green: "bg-green-9 text-white",+ amber: "bg-amber-9 text-amber-12",+ violet: "bg-violet-9 text-white",+ red: "bg-red-9 text-white",+} as const;++type BeadTone = keyof typeof BEAD_TONES;++/** Opaque and above the connector, so the line reads as running into it. */+export function EventBead({+ children,+ tone = "neutral",+}: {+ children: ReactNode;+ tone?: BeadTone;+}) {+ return (+ <span+ className={cn(+ "relative z-10 flex size-5 items-center justify-center rounded-full border",+ BEAD_TONES[tone],+ )}+ >+ {children}+ </span>+ );+}++export function PersonBead({+ user,+ badge,+ badgeTone = "neutral",+}: {+ user?: UserBasic | null;+ badge: ReactNode;+ badgeTone?: BeadTone;+}) {+ return (+ // Decorative: the name and the action are written beside it, so keep the initials out+ // of the row's accessible name.+ <span aria-hidden className="relative z-10 block size-5">+ {/* quill's avatar is a rounded square; every bead in the gutter is a circle. */}+ <UserAvatar user={user} size="xs" className="size-5 rounded-full" />+ <span+ className={cn(+ "-right-1 -bottom-1 absolute flex size-3 items-center justify-center rounded-full ring-2 ring-background",+ BADGE_TONES[badgeTone],+ )}+ >+ {badge}+ </span>+ </span>+ );+}++export const MESSAGE_BADGE = <PaperPlaneTiltIcon size={8} weight="fill" />;+export const COMMENT_BADGE = <ChatCircleIcon size={8} weight="fill" />;+export const CREATED_BADGE = <PlusIcon size={8} weight="bold" />;++const EVENT_TONES: Record<ActivityEvent["kind"], BeadTone> = {+ run_started: "blue",+ run_failed: "red",+ commits_pushed: "neutral",+ awaiting_input: "amber",+ artifact_created: "violet",+ artifact_revised: "violet",+ canvas_created: "violet",+ pr_created: "neutral",+ pr_merged: "violet",+ pr_closed: "red",+ message_forwarded: "neutral",+};++/** No glyph here is itself a circle: a ring inside a ring reads as a mistake at this size,+ * so a failure is a bare ✕ and a success a bare ✓. */+const EVENT_ICONS: Record<ActivityEvent["kind"], ReactNode> = {+ run_started: <PlayIcon size={9} weight="fill" />,+ run_failed: <XIcon size={10} weight="bold" />,+ commits_pushed: <GitCommitIcon size={11} />,+ awaiting_input: <QuestionIcon size={11} weight="bold" />,+ artifact_created: <FileTextIcon size={11} />,+ artifact_revised: <ArrowsClockwiseIcon size={11} />,+ canvas_created: <SquaresFourIcon size={11} />,+ pr_created: <GitPullRequestIcon size={11} />,+ pr_merged: <GitMergeIcon size={11} />,+ pr_closed: <ProhibitIcon size={11} />,+ message_forwarded: <PaperPlaneTiltIcon size={9} weight="fill" />,+};++function eventLabel(+ event: ActivityEvent,+ runCount: number,+ runOrdinal: number,+): ReactNode {+ switch (event.kind) {+ case "run_started":+ return runCount > 1+ ? `Agent started run ${runOrdinal}`+ : "Agent started work";+ case "run_failed":+ return "Run failed";+ case "commits_pushed": {+ const { total, branch } = event.payload;+ const count = `${total} commit${total === 1 ? "" : "s"} pushed`;+ return branch ? (+ <>+ {count} <span className="text-muted-foreground">to {branch}</span>+ </>+ ) : (+ count+ );+ }+ case "awaiting_input":+ return "Agent needs input";+ case "artifact_created":+ return (+ <>+ Agent created{" "}+ <span className="font-medium">{event.payload.name}</span>+ </>+ );+ case "artifact_revised":+ return (+ <>+ Agent revised{" "}+ <span className="font-medium">{event.payload.name}</span>+ <span className="text-muted-foreground">+ {" "}+ · v{event.payload.version}+ </span>+ </>+ );+ case "canvas_created":+ return (+ <>+ Agent created{" "}+ <span className="font-medium">{event.payload.name}</span>+ </>+ );+ case "pr_created":+ return (+ <>+ Pull request opened+ <span className="text-muted-foreground">+ {" "}+ · {prLabel(event.payload)}+ </span>+ </>+ );+ case "pr_merged":+ case "pr_closed": {+ const verb = event.kind === "pr_merged" ? "merged" : "closed";+ return (+ <>+ {event.payload.actor+ ? `${event.payload.actor} ${verb} `+ : `Pull request ${verb} `}+ <span className="text-muted-foreground">+ {prLabel(event.payload)}+ </span>+ </>+ );+ }+ case "message_forwarded":+ return "Message sent to the agent";+ }+}++function eventDetail(event: ActivityEvent): ReactNode {+ switch (event.kind) {+ case "run_failed":+ return event.payload.errorSummary ? (+ <DetailBlock>{event.payload.errorSummary}</DetailBlock>+ ) : null;+ case "run_started": {+ const details = [+ event.payload.environment,+ event.payload.branch || null,+ ].filter(Boolean);+ return details.length > 0 ? (+ <DetailBlock>{details.join(" · ")}</DetailBlock>+ ) : null;+ }+ case "artifact_created":+ case "artifact_revised":+ return (+ <DetailBlock>+ {event.payload.name}+ <span className="text-muted-foreground">+ {" "}+ · v{event.payload.version}+ </span>+ </DetailBlock>+ );+ case "commits_pushed": {+ const { commits, total } = event.payload;+ return (+ <DetailBlock>+ <div className="space-y-1">+ {commits.map((commit) => (+ <div+ key={commit.sha}+ className="flex min-w-0 items-baseline gap-2"+ >+ <span className="shrink-0 font-mono text-[11.5px] text-muted-foreground">+ {commit.sha.slice(0, 7)}+ </span>+ <span className="min-w-0 truncate">{commit.subject}</span>+ </div>+ ))}+ {total > commits.length && (+ <div className="text-muted-foreground">+ and {total - commits.length} more+ </div>+ )}+ </div>+ </DetailBlock>+ );+ }+ case "pr_created":+ case "pr_merged":+ case "pr_closed":+ return <DetailBlock>{event.payload.prUrl}</DetailBlock>;+ default:+ return null;+ }+}++export function DetailAction({+ children,+ onClick,+}: {+ children: ReactNode;+ onClick: () => void;+}) {+ return (+ <Button variant="outline" size="xs" onClick={onClick}>+ {children}+ </Button>+ );+}++/**+ * Mention tokens and the composer's XML chips are not markdown, and a markdown parser mangles+ * them (`@[Name](email)` becomes a mailto link), so a message carrying either goes through+ * `MentionText` instead.+ */+export function MessageBody({ content }: { content: string }) {+ const hasOwnMarkup = useMemo(() => {+ const { segments } = xmlToContent(content);+ return (+ segments.some((segment) => segment.type === "chip") ||+ segments.some(+ (segment) =>+ segment.type !== "chip" &&+ splitMentionSegments(segment.text).some(+ (part) => part.type === "mention",+ ),+ )+ );+ }, [content]);+ return (+ // The chat's markdown is sized for the transcript's column, so pull its paragraphs,+ // list items and code back down to the size of the row copy.+ <div className="whitespace-pre-wrap break-words text-[12.5px] [&_code]:text-[11px]! [&_li]:text-[12.5px]! [&_p]:text-[12.5px]! [&_p]:leading-[1.55]!">+ {hasOwnMarkup ? (+ <MentionText content={content} />+ ) : (+ <ChatMarkdown content={content} />+ )}+ </div>+ );+}++export function MessageBubble({ content }: { content: string }) {+ return (+ <ChatBubble variant="default">+ {/* The bubble's own `whitespace-pre-wrap` would double markdown's block spacing. */}+ <ChatBubbleContent className="whitespace-normal">+ <MessageBody content={content} />+ </ChatBubbleContent>+ </ChatBubble>+ );+}++/** No radius, so the left edge reads as a rule rather than the outline of a box. */+export function DetailBlock({ children }: { children: ReactNode }) {+ return (+ <div className="break-words border-gray-6 border-l-2 bg-gray-2 px-2.5 py-1.5 text-[12.5px]">+ {children}+ </div>+ );+}++export function ActivityEventRow({+ event,+ timestamp,+ runCount,+ runOrdinal = 1,+ detail,+ connectedAbove = true,+ connectedBelow = true,+}: {+ connectedAbove?: boolean;+ connectedBelow?: boolean;+ event: ActivityEvent;+ timestamp: string;+ /** A single-run task doesn't say "run 1". */+ runCount: number;+ /** Which run this row starts, counted over the feed rather than stamped by the backend. */+ runOrdinal?: number;+ detail?: ReactNode;+}) {+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={+ <EventBead tone={EVENT_TONES[event.kind]}>+ {EVENT_ICONS[event.kind]}+ </EventBead>+ }+ timestamp={timestamp}+ detail={detail ?? eventDetail(event)}+ >+ {eventLabel(event, runCount, runOrdinal)}+ </TimelineRow>+ );+}++/** The ending of a run that predates the event rows, derived from the task. */+export function RunStatusRow({+ status,+ timestamp,+ connectedAbove = true,+ connectedBelow = true,+}: {+ status: string;+ timestamp: string;+ connectedAbove?: boolean;+ connectedBelow?: boolean;+}) {+ const succeeded = status === "completed";+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={+ <EventBead tone={succeeded ? "green" : "red"}>+ {succeeded ? (+ <CheckIcon size={11} weight="bold" />+ ) : (+ <XIcon size={10} weight="bold" />+ )}+ </EventBead>+ }+ timestamp={timestamp}+ >+ {`Task ${status.replace(/_/g, " ")}`}+ </TimelineRow>+ );+}++function participantNames(participants: UserBasic[]): string {+ return participants.map((person) => userDisplayName(person)).join(", ");+}++export function CommentRow({+ thread,+ isMentioned,+ onSelect,+ connectedAbove = true,+ connectedBelow = true,+}: {+ connectedAbove?: boolean;+ connectedBelow?: boolean;+ thread: TaskCommentThreadSummary;+ isMentioned: boolean;+ onSelect?: () => void;+}) {+ const author = thread.author ?? null;+ const name = userDisplayName(author);+ const verb = isMentioned ? "mentioned you on" : "commented on";+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={+ <PersonBead+ user={author}+ badge={COMMENT_BADGE}+ badgeTone={isMentioned ? "amber" : "neutral"}+ />+ }+ timestamp={thread.last_activity_at}+ detail={+ <div className="space-y-1.5">+ {/* A comment stays a quote rather than a chat bubble: it points at the text it+ was left on, which is quoted above it. */}+ <DetailBlock>+ {thread.selected_text && (+ <div className="mb-1 truncate text-muted-foreground italic">+ “{thread.selected_text}”+ </div>+ )}+ <MessageBody content={thread.content} />+ </DetailBlock>+ {thread.reply_count > 0 && (+ <div className="truncate text-[12.5px] text-muted-foreground">+ {thread.reply_count}{" "}+ {thread.reply_count === 1 ? "reply" : "replies"}+ {thread.participants.length > 0 &&+ ` · ${participantNames(thread.participants)}`}+ </div>+ )}+ {onSelect && (+ <DetailAction onClick={onSelect}>Open thread</DetailAction>+ )}+ </div>+ }+ >+ <span className="font-medium">{name}</span>{" "}+ <span className="text-muted-foreground">{verb}</span>{" "}+ <span className="font-medium">{thread.target.name}</span>+ </TimelineRow>+ );+}++export function CommentStateRow({+ thread,+ state,+ connectedAbove = true,+ connectedBelow = true,+}: {+ thread: TaskCommentThreadSummary;+ state: string;+ connectedAbove?: boolean;+ connectedBelow?: boolean;+}) {+ const author = thread.state_event?.author ?? null;+ const resolved = state === "resolved";+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={+ <PersonBead+ user={author}+ badge={+ resolved ? (+ <CheckIcon size={8} weight="bold" />+ ) : (+ <ArrowCounterClockwiseIcon size={8} weight="bold" />+ )+ }+ badgeTone={resolved ? "green" : "amber"}+ />+ }+ timestamp={thread.state_event?.created_at ?? thread.last_activity_at}+ >+ {author ? (+ <span className="font-medium">{userDisplayName(author)}</span>+ ) : (+ "Someone"+ )}{" "}+ {resolved ? "resolved a thread on" : "reopened a thread on"}{" "}+ <span className="font-medium">{thread.target.name}</span>+ </TimelineRow>+ );+}++/** Shown once, on the panel's first draw. It never returns, because a loader over rows+ * already on screen reads as the content disappearing. */+export function ActivityLoadingState() {+ return (+ <output className="relative block px-1 py-2" aria-label="Loading timeline">+ <div>+ {/* Widths vary so the block reads as copy rather than a progress bar. */}+ {[36, 52, 44, 60, 40].map((width) => (+ <div key={width} className="flex items-start gap-2 py-2.5 pr-2 pl-2">+ <div className="flex w-10 shrink-0 justify-center">+ <Skeleton className="size-5 rounded-full" />+ </div>+ <div className="min-w-0 flex-1 py-1">+ <Skeleton+ className="h-3 rounded"+ style={{ width: `${width}%` }}+ />+ </div>+ </div>+ ))}+ </div>+ </output>+ );+}++export function ThreadReplyRow({+ author,+ content,+ timestamp,+ connectedAbove = true,+ connectedBelow = true,+}: {+ author?: UserBasic | null;+ content: string;+ timestamp: string;+ connectedAbove?: boolean;+ connectedBelow?: boolean;+}) {+ const firstLine = content.trim().split("\n", 1)[0] ?? "";+ return (+ <TimelineRow+ connectedAbove={connectedAbove}+ connectedBelow={connectedBelow}+ gutter={<PersonBead user={author} badge={MESSAGE_BADGE} />}+ timestamp={timestamp}+ detail={<MessageBubble content={content} />}+ >+ <span className="font-medium">{userDisplayName(author)}</span>{" "}+ <span className="text-muted-foreground">+ <MentionText content={firstLine} />+ </span>+ </TimelineRow>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskCommentActivity.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskCommentActivity.tsnew file mode 100644index 000000000000..02cdc90d4e9c--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskCommentActivity.ts@@ -0,0 +1,38 @@+import type { TaskCommentThreadSummary } from "@posthog/shared/domain-types";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";++/** Comments move at human pace, so this polls slower than the 5s thread poll. The+ * Comments tab keeps its own faster poll for the surface people type into. */+const POLL_INTERVAL_MS = 15_000;++/**+ * Deliberately not patched by the optimistic comment writes in `useComments`: a comment you+ * just left shows up within one poll, and cross-patching two differently shaped caches is how+ * they drift apart.+ */+export function useTaskCommentActivity(+ taskId: string | undefined,+ options: { enabled?: boolean } = {},+): {+ threads: TaskCommentThreadSummary[];+ isLoading: boolean;+ /** The timeline waits on this so it draws once, complete, instead of drawing thread rows+ * and then adding comments. */+ hasLoaded: boolean;+} {+ const enabled = options.enabled !== false && !!taskId;+ const query = useAuthenticatedQuery<TaskCommentThreadSummary[]>(+ ["task-comment-activity", taskId ?? "none"],+ (client) => client.getTaskCommentActivity(taskId as string),+ {+ enabled,+ refetchInterval: POLL_INTERVAL_MS,+ staleTime: POLL_INTERVAL_MS,+ },+ );+ return {+ threads: query.data ?? [],+ isLoading: query.isLoading,+ hasLoaded: !enabled || query.isSuccess || query.isError,+ };+}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskThread.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskThread.tsindex 05e58c4ca291..c7c39925f45e 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskThread.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskThread.ts@@ -26,6 +26,9 @@ export function useTaskThread(): {messages: TaskThreadMessage[];isLoading: boolean;+ /** The thread has come back at least once. Distinct from `!isLoading`, which flips back+ * on a refetch and would blink a loader over content already on screen. */+ hasLoaded: boolean;} {const pollIntervalMs = options?.pollIntervalMs ?? THREAD_POLL_INTERVAL_MS;const enabled = options?.enabled ?? true;@@ -60,7 +63,11 @@ export function useTaskThread(opening,query.dataUpdatedAt,]);- return { messages: query.data ?? [], isLoading: query.isLoading };+ return {+ messages: query.data ?? [],+ isLoading: query.isLoading,+ hasLoaded: query.isSuccess || query.isError,+ };}export function usePostTaskThreadMessage(taskId: string | undefined) {diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useThreadConversation.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useThreadConversation.tsindex 02e01164cf7c..e8291dc5de95 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useThreadConversation.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useThreadConversation.ts@@ -36,12 +36,18 @@ type SessionEvents = ReturnType<typeof useSessionViewState>["events"];export interface ThreadConversation {timeline: ThreadTimelineRow<TaskThreadMessage>[];+ /** Every thread message, unfiltered. `timeline` is the human-facing subset, so a surface+ * that draws agent and system rows has to start here instead. */+ messages: TaskThreadMessage[];agentStatus: ThreadAgentStatus | null;events: SessionEvents;isPromptPending: boolean;isReady: boolean;+ /** The thread's own durable content has arrived. The timeline draws on this rather than+ * on `isReady`, which also waits for the live session to connect. */+ hasLoadedThread: boolean;members: UserBasic[];- currentUser: { uuid?: string; email?: string } | undefined;+ currentUser: { id?: number; uuid?: string; email?: string } | undefined;isTaskAuthor: boolean;canForward: boolean;draft: string;@@ -61,7 +67,11 @@ export function useThreadConversation(const client = useOptionalAuthenticatedClient();const { data: currentUser } = useCurrentUser({ client });- const { messages, isLoading } = useTaskThread(taskId);+ const {+ messages,+ isLoading,+ hasLoaded: hasLoadedThread,+ } = useTaskThread(taskId);const { postMessage, isPosting } = usePostTaskThreadMessage(taskId);const { postMessageToAgent, isPostingToAgent } =usePostTaskThreadMessageToAgent(taskId);@@ -194,10 +204,12 @@ export function useThreadConversation(return {timeline,+ messages,agentStatus,events,isPromptPending,isReady: !isInitializing && !isLoading,+ hasLoadedThread,members,currentUser,isTaskAuthor,diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsxindex bfa0007296d3..65e939163505 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx@@ -325,9 +325,12 @@ export function ConversationView({const handleJumpToMessage = useCallback((id: string) => {const message = userMessages.find((entry) => entry.id === id);- if (!message) return;+ // Reported, not swallowed: a request for a message this list has not built yet is+ // retried by the caller rather than dropped.+ if (!message) return false;setKeyboardFocusedMessageId(id);scrollToUserMessage(id, message.index);+ return true;},[userMessages, scrollToUserMessage],);diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex 4a65a7aabfc2..8fc24219d1b3 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -1093,6 +1093,7 @@ function ThreadScrollBody({keyboardFocusedMessageId,onUserInteract,resumeStateRef,+ autoFollowRef,}: {items: ConversationItem[];rows: TurnRow[];@@ -1104,11 +1105,10 @@ function ThreadScrollBody({onUserInteract?: () => void;/** Continuously updated so the virtualized body can take over mid-session (see {@link ThreadScrollResume}). */resumeStateRef: RefObject<ThreadScrollResume>;+ autoFollowRef: RefObject<ThreadFollowState>;}) {const keyedRows = useMemo(() => keyTurnRows(rows), [rows]);- const autoFollowRef = useRef<ThreadFollowState>(FOLLOWING_END);-// `group/thread` so the footer's hover-reveal (opacity-50 → 100 on group-hover) tracks the thread,// mirroring the legacy ConversationView container. `@container/thread` makes the thread's own// width the query basis for everything inside it — the panel is resizable and splittable, so the@@ -1257,12 +1257,35 @@ export interface ChatThreadProps extends SharedChatThreadProps {function ThreadScrollRequestBridge({taskId,jumpToMessage,+ onFocusMessage,+ autoFollowRef,}: {taskId?: string;- jumpToMessage?: (id: string) => void;+ jumpToMessage?: (id: string) => boolean;+ /** Marks the arrived-at message, so a jump from another pane lands as visibly as the+ * keyboard's own. Without it the thread moves and nothing says where to. */+ onFocusMessage?: (id: string) => void;+ autoFollowRef?: RefObject<ThreadFollowState>;}) {const { scrollToMessage } = useChatMessageScroller();- useThreadScrollRequest(taskId, jumpToMessage ?? scrollToMessage);+ const jump = jumpToMessage ?? scrollToMessage;+ const handleRequest = useCallback(+ (id: string) => {+ // A jump is the reader choosing a spot, so following lets go before the scroll rather+ // than in reaction to it: the scroll event that would release it arrives a frame late,+ // by which point following has already pulled the thread back down.+ if (autoFollowRef)+ autoFollowRef.current = { following: false, leftEnd: true };+ // Both jumps answer false while the target row is absent (from the element registry,+ // or from the row index), and the caller retries, so only claim the focus once the+ // thread actually moved.+ const landed = jump(id);+ if (landed) onFocusMessage?.(id);+ return landed;+ },+ [jump, onFocusMessage, autoFollowRef],+ );+ useThreadScrollRequest(taskId, handleRequest);return null;}@@ -1460,9 +1483,13 @@ function ChatThreadRenderer({[renderItem, keyboardFocusedMessageId],);+ // Lives here rather than in the plain body so a jump from another pane can drop the pin+ // before it scrolls.+ const autoFollowRef = useRef<ThreadFollowState>(FOLLOWING_END);+// The nav layer sits beside the scroll body so it can be handed the windowed body's jump// implementation — the engine's `scrollToMessage` only reaches mounted rows.- const renderNav = (jumpToMessage?: (id: string) => void) => (+ const renderNav = (jumpToMessage?: (id: string) => boolean) => (<><ThreadKeyboardNavitems={items}@@ -1476,6 +1503,9 @@ function ChatThreadRenderer({<ThreadScrollRequestBridgetaskId={taskId}jumpToMessage={jumpToMessage}+ onFocusMessage={setKeyboardFocusedMessageId}+ // Only the plain body needs it: the windowed body's own jump drops its pin.+ autoFollowRef={jumpToMessage ? undefined : autoFollowRef}/></>);@@ -1513,6 +1543,7 @@ function ChatThreadRenderer({) : (<><ThreadScrollBody+ autoFollowRef={autoFollowRef}items={items}rows={rows}renderItem={renderItem}diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsxindex d247dc1a2728..a67db1d1149d 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx@@ -311,9 +311,10 @@ export function VirtualThreadScrollBody({onUserInteract?: () => void;/*** Navigation layer, rendered as a sibling of the scroller so it can be handed this body's jump- * implementation — the engine's `scrollToMessage` only reaches mounted rows.+ * implementation, because the engine's `scrollToMessage` only reaches mounted rows. The jump+ * reports whether the target resolved, so a caller can retry rather than fail silently.*/- renderNav?: (jumpToMessage: (id: string) => void) => ReactNode;+ renderNav?: (jumpToMessage: (id: string) => boolean) => ReactNode;/** Where the non-virtualized body left off, read once when this body takes over mid-session. */resumeRef: RefObject<ThreadScrollResume>;}) {@@ -368,7 +369,9 @@ export function VirtualThreadScrollBody({const jumpToMessage = useCallback((id: string) => {const index = rowIndexRef.current.get(id);- if (index != null) settleToIndex(index);+ if (index == null) return false;+ settleToIndex(index);+ return true;},[settleToIndex],);diff --git a/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.test.ts b/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.test.tsindex 22ccbc91b658..d83010545a12 100644--- a/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.test.ts@@ -1,5 +1,5 @@import { act, renderHook } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {useThreadNavigationStore,useThreadScrollRequest,@@ -7,11 +7,24 @@ import {beforeEach(() => {useThreadNavigationStore.setState({ scrollRequests: {} });+ // The retry loop runs on animation frames, so the test drives them rather than waiting.+ vi.useFakeTimers();});+afterEach(() => {+ vi.useRealTimers();+});++/** Advance far enough for the loop to settle or exhaust its attempts. */+function runFrames(count: number) {+ act(() => {+ vi.advanceTimersByTime(count * 16);+ });+}+describe("useThreadScrollRequest", () => {it("serves a request from another pane and consumes it", () => {- const jump = vi.fn();+ const jump = vi.fn().mockReturnValue(true);renderHook(() => useThreadScrollRequest("task-1", jump));act(() => {@@ -19,6 +32,7 @@ describe("useThreadScrollRequest", () => {.getState().requestScrollToMessage("task-1", "turn-10-1-user");});+ runFrames(10);expect(jump).toHaveBeenCalledWith("turn-10-1-user");// Cleared, so re-rendering for any other reason can't re-fire the jump and@@ -29,18 +43,68 @@ describe("useThreadScrollRequest", () => {});it("re-fires when the same message is requested again", () => {- const jump = vi.fn();+ const jump = vi.fn().mockReturnValue(true);renderHook(() => useThreadScrollRequest("task-1", jump));- const request = () =>+ const request = () => {act(() => {useThreadNavigationStore.getState().requestScrollToMessage("task-1", "turn-10-1-user");});+ runFrames(10);+ };request();+ const afterFirst = jump.mock.calls.length;+ jump.mockClear();request();- expect(jump).toHaveBeenCalledTimes(2);+ expect(afterFirst).toBeGreaterThan(0);+ expect(jump).toHaveBeenCalledWith("turn-10-1-user");+ });++ it("keeps the request pending until the transcript can answer it", () => {+ // The row may not be mounted or measured yet, and the transcript's tab can be off screen+ // when the request arrives. Dropping the request on the first miss is what made the jump+ // work only sometimes.+ const jump = vi.fn().mockReturnValue(false);+ renderHook(() => useThreadScrollRequest("task-1", jump));++ act(() => {+ useThreadNavigationStore+ .getState()+ .requestScrollToMessage("task-1", "turn-10-1-user");+ });+ runFrames(5);++ expect(jump.mock.calls.length).toBeGreaterThan(1);+ expect(useThreadNavigationStore.getState().scrollRequests["task-1"]).toBe(+ "turn-10-1-user",+ );++ jump.mockReturnValue(true);+ runFrames(10);++ expect(useThreadNavigationStore.getState().scrollRequests["task-1"]).toBe(+ null,+ );+ });++ it("gives up on a target the transcript never renders", () => {+ // Otherwise a stale id retries for the life of the mount, and every later request queues+ // behind it.+ const jump = vi.fn().mockReturnValue(false);+ renderHook(() => useThreadScrollRequest("task-1", jump));++ act(() => {+ useThreadNavigationStore+ .getState()+ .requestScrollToMessage("task-1", "no-such-row");+ });+ runFrames(120);++ expect(useThreadNavigationStore.getState().scrollRequests["task-1"]).toBe(+ null,+ );});});diff --git a/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.ts b/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.tsindex 3e8fb3681f44..2eebbe1110e0 100644--- a/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.ts+++ b/products/desktop/packages/ui/src/features/sessions/threadNavigationStore.ts@@ -4,26 +4,30 @@ import { create } from "zustand";interface ThreadNavigationStoreState {/** taskId → conversation item id the transcript should scroll to, if any. */scrollRequests: Record<string, string | null>;+ /** taskId → how many transcripts are mounted and listening. A request with no listener+ * goes nowhere, so callers offer the jump only when this is non-zero. */+ listeners: Record<string, number>;}interface ThreadNavigationStoreActions {requestScrollToMessage: (taskId: string, messageId: string) => void;clearScrollRequest: (taskId: string) => void;+ registerTranscript: (taskId: string) => void;+ unregisterTranscript: (taskId: string) => void;}type ThreadNavigationStore = ThreadNavigationStoreState &ThreadNavigationStoreActions;/**- * Lets a pane outside the transcript ask it to scroll to a message — the- * Activity timeline sits in a sibling tree, so it can't reach the scroller's- * context or the windowed body's jump callback directly. Mirrors- * `reviewNavigationStore`'s scroll-request shape: the writer sets a request, the- * transcript consumes it and clears it.+ * Lets a pane outside the transcript ask it to scroll to a message, because the Activity+ * timeline sits in a sibling tree and can't reach the scroller's context or the windowed+ * body's jump callback directly. Mirrors `reviewNavigationStore`'s scroll-request shape.*/export const useThreadNavigationStore = create<ThreadNavigationStore>()((set) => ({scrollRequests: {},+ listeners: {},requestScrollToMessage: (taskId, messageId) =>set((state) => ({@@ -34,26 +38,88 @@ export const useThreadNavigationStore = create<ThreadNavigationStore>()(set((state) => ({scrollRequests: { ...state.scrollRequests, [taskId]: null },})),++ registerTranscript: (taskId) =>+ set((state) => ({+ listeners: {+ ...state.listeners,+ [taskId]: (state.listeners[taskId] ?? 0) + 1,+ },+ })),++ unregisterTranscript: (taskId) =>+ set((state) => {+ const next = (state.listeners[taskId] ?? 0) - 1;+ const listeners = { ...state.listeners };+ if (next > 0) listeners[taskId] = next;+ else delete listeners[taskId];+ return { listeners };+ }),}),);+/** The target row may not be registered yet, and the tab holding the transcript may only+ * just have been activated, so the first frame after a request is routinely too early. */+const JUMP_ATTEMPT_FRAMES = 60;++/** Rows above the target measure late (diffs, highlighted code, images), which moves it out+ * from under an offset already committed, so a landed jump is re-issued for a few frames. */+const JUMP_SETTLE_FRAMES = 3;+/**- * Consumes a pending request for this task, handing it to the transcript's own- * jump and clearing it. Each transcript jumps differently (DOM registry,- * virtualizer index, grouped-row index), so the store carries only the target.+ * Hands a pending request to the transcript's own jump. Each transcript jumps differently+ * (DOM registry, virtualizer index), so the store carries only the target.+ *+ * The request survives a jump that did not land and is retried until one does, so a+ * transcript mounting after the request still answers it. That is what makes the jump work+ * from a tab that was not on screen when the reader asked.*/export function useThreadScrollRequest(taskId: string | undefined,- jumpToMessage: (messageId: string) => void,+ jumpToMessage: (messageId: string) => boolean,): void {const requestedMessageId = useThreadNavigationStore((state) =>taskId ? state.scrollRequests[taskId] : null,);+ // So a pane offering the jump can hide the affordance when nothing is listening.+ useEffect(() => {+ if (!taskId) return;+ const { registerTranscript, unregisterTranscript } =+ useThreadNavigationStore.getState();+ registerTranscript(taskId);+ return () => unregisterTranscript(taskId);+ }, [taskId]);+useEffect(() => {if (!taskId || !requestedMessageId) return;- jumpToMessage(requestedMessageId);- // Clear via getState so the action isn't an effect dependency.- useThreadNavigationStore.getState().clearScrollRequest(taskId);+ let frame: number | null = null;+ let attempts = 0;+ let settles = 0;+ const step = () => {+ frame = null;+ const landed = jumpToMessage(requestedMessageId);+ if (+ landed+ ? ++settles > JUMP_SETTLE_FRAMES+ : ++attempts > JUMP_ATTEMPT_FRAMES+ ) {+ // Giving up clears too: a target the transcript never renders must not leave a+ // request pending forever. Read via getState so the action isn't an effect dependency.+ useThreadNavigationStore.getState().clearScrollRequest(taskId);+ return;+ }+ frame = requestAnimationFrame(step);+ };+ step();+ return () => {+ if (frame !== null) cancelAnimationFrame(frame);+ };}, [taskId, requestedMessageId, jumpToMessage]);}++export function useHasTranscriptListener(taskId: string | undefined): boolean {+ return useThreadNavigationStore((state) =>+ taskId ? (state.listeners[taskId] ?? 0) > 0 : false,+ );+}