Skip to content

: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.

feat(desktop): draw commit, comment, and artifact events on the task timeline (#82163)

Shy Alter80d1b2970ff1
diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts
index 0db78612d1e5..083d78ee76a5 100644
--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts
+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts
@@ -1,8 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const createSignedCommit = vi.fn();
-const reportCommitArtefacts = vi.fn();
-const reportTaskRunBranch = vi.fn();
+const reportSignedCommitActivity = vi.fn();
vi.mock("@posthog/git/signed-commit", async (importOriginal) => {
const actual =
@@ -14,8 +13,8 @@ vi.mock("@posthog/git/signed-commit", async (importOriginal) => {
});
vi.mock("../../../signed-commit-artefacts", () => ({
- reportCommitArtefacts: (...args: unknown[]) => reportCommitArtefacts(...args),
- reportTaskRunBranch: (...args: unknown[]) => reportTaskRunBranch(...args),
+ reportSignedCommitActivity: (...args: unknown[]) =>
+ reportSignedCommitActivity(...args),
}));
// Importing the tool after the mock so its transitive `createSignedCommit`
@@ -27,8 +26,7 @@ describe("signed-commit tool handler", () => {
beforeEach(() => {
createSignedCommit.mockReset();
- reportCommitArtefacts.mockReset();
- reportTaskRunBranch.mockReset();
+ reportSignedCommitActivity.mockReset();
createSignedCommit.mockResolvedValue({
branch: "posthog-code/feature",
repository: "x/y",
@@ -110,11 +108,20 @@ describe("signed-commit tool handler", () => {
{ message: "chore: bump" },
);
- expect(reportTaskRunBranch).toHaveBeenCalledWith({
+ expect(reportSignedCommitActivity).toHaveBeenCalledWith({
taskId: "task-1",
taskRunId: "run-1",
- repository: "x/y",
- branch: "posthog-code/feature",
+ result: {
+ branch: "posthog-code/feature",
+ repository: "x/y",
+ commits: [
+ {
+ sha: "deadbeef",
+ url: "https://github.com/x/y/commit/deadbeef",
+ },
+ ],
+ },
+ message: "chore: bump",
updateCheckoutBranch: true,
});
});
@@ -130,11 +137,14 @@ describe("signed-commit tool handler", () => {
{ message: "chore: bump", cwd: "." },
);
- expect(reportTaskRunBranch).toHaveBeenCalledWith({
+ expect(reportSignedCommitActivity).toHaveBeenCalledWith({
taskId: "task-1",
taskRunId: "run-1",
- repository: "x/y",
- branch: "posthog-code/feature",
+ result: expect.objectContaining({
+ repository: "x/y",
+ branch: "posthog-code/feature",
+ }),
+ message: "chore: bump",
updateCheckoutBranch: true,
});
});
@@ -153,11 +163,14 @@ describe("signed-commit tool handler", () => {
},
);
- expect(reportTaskRunBranch).toHaveBeenCalledWith({
+ expect(reportSignedCommitActivity).toHaveBeenCalledWith({
taskId: "task-1",
taskRunId: "run-1",
- repository: "x/y",
- branch: "posthog-code/feature",
+ result: expect.objectContaining({
+ repository: "x/y",
+ branch: "posthog-code/feature",
+ }),
+ message: "chore: bump",
updateCheckoutBranch: false,
});
});
diff --git a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts b/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts
index 436668223f51..0988547e4bc3 100644
--- a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts
+++ b/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts
@@ -9,10 +9,7 @@ import {
type SignedRewriteInput,
} from "@posthog/git/signed-commit";
import { z } from "zod";
-import {
- reportCommitArtefacts,
- reportTaskRunBranch,
-} from "../signed-commit-artefacts";
+import { reportSignedCommitActivity } from "../signed-commit-artefacts";
import { qualifiedLocalToolName } from "./local-tools/registry";
/**
@@ -180,29 +177,12 @@ export function runSignedCommitTool(
SIGNED_COMMIT_TOOL_NAME,
async (c, a: SignedCommitInput) => {
const result = await createSignedCommit(c, a);
- // TaskRun.branch is the branch that provisioning checks out in the task's
- // repository on resume. A task can also commit to sibling repositories by
- // passing `cwd`; persisting one of those branches here makes the next run
- // try to clone the task repository at a branch that only exists elsewhere.
- await reportTaskRunBranch({
+ await reportSignedCommitActivity({
taskId: ctx.taskId,
taskRunId: ctx.taskRunId,
- repository: result.repository,
- branch: result.branch,
- // Only the task repository branch controls the next checkout. The
- // reported head branch still lets PR webhooks bind commits made from a
- // workspace root or a sibling repository to this run.
- updateCheckoutBranch: ctx.cwd === ctx.taskRepositoryCwd,
- });
- // The "commit hook": every pushed commit becomes a `commit` artefact on the signal
- // reports this task is associated with. Best-effort and awaited inside the tool's
- // try/catch-free success path — reportCommitArtefacts never throws, so a failed
- // artefact post can't fail a commit that already landed. git_signed_rewrite is
- // intentionally not hooked (it republishes existing history).
- await reportCommitArtefacts({
- taskId: c.taskId,
result,
message: a.message,
+ updateCheckoutBranch: ctx.cwd === ctx.taskRepositoryCwd,
});
return result;
},
diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.ts
index 74f0b2ab7f0b..8872cbc851e0 100644
--- a/products/desktop/packages/agent/src/posthog-api.ts
+++ b/products/desktop/packages/agent/src/posthog-api.ts
@@ -280,6 +280,7 @@ export class PostHogAPIClient {
taskId: string,
runId: string,
payload: TaskRunUpdate,
+ signal?: AbortSignal,
): Promise<TaskRun> {
const teamId = this.getTeamId();
return this.apiRequest<TaskRun>(
@@ -287,6 +288,7 @@ export class PostHogAPIClient {
{
method: "PATCH",
body: JSON.stringify(payload),
+ signal,
},
);
}
@@ -495,10 +497,14 @@ export class PostHogAPIClient {
}
/** Signal reports the given task is associated with (via report task associations). */
- async getSignalReportIdsForTask(taskId: string): Promise<string[]> {
+ async getSignalReportIdsForTask(
+ taskId: string,
+ signal?: AbortSignal,
+ ): Promise<string[]> {
const teamId = this.getTeamId();
const response = await this.apiRequest<{ results?: { id: string }[] }>(
`/api/projects/${teamId}/signals/reports/?task_id=${encodeURIComponent(taskId)}&limit=100`,
+ { signal },
);
return (response.results ?? []).map((r) => r.id);
}
@@ -511,6 +517,7 @@ export class PostHogAPIClient {
reportId: string,
taskId: string,
body: { artefact_type: string; content: Record<string, unknown> },
+ signal?: AbortSignal,
): Promise<void> {
const teamId = this.getTeamId();
await this.apiRequest(
@@ -519,6 +526,7 @@ export class PostHogAPIClient {
method: "POST",
body: JSON.stringify(body),
headers: { "X-PostHog-Task-Id": taskId },
+ signal,
},
);
}
diff --git a/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts b/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts
index 827796b09b79..af56a6ad77d3 100644
--- a/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts
+++ b/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts
@@ -15,6 +15,7 @@ import {
parseSandboxEnv,
reportCommitArtefacts,
reportTaskRunBranch,
+ reportTaskRunCommits,
resolveSandboxPosthogApi,
} from "./signed-commit-artefacts";
@@ -437,3 +438,86 @@ describe("reportTaskRunBranch", () => {
});
});
});
+
+describe("reportTaskRunCommits", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("stores the successful push on the task run", async () => {
+ fetchMock.mockResolvedValue(
+ new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ await reportTaskRunCommits({
+ taskId: "task-1",
+ taskRunId: "run-1",
+ result: RESULT,
+ message: "feat(desktop): show commits",
+ env: ENV,
+ envFilePath: NO_ENV_FILE,
+ oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
+ });
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(String(url)).toBe(
+ "https://us.posthog.com/api/projects/7/tasks/task-1/runs/run-1/",
+ );
+ expect(init).toMatchObject({
+ method: "PATCH",
+ body: JSON.stringify({
+ output: {
+ commit_push: {
+ branch: "posthog-code/fix-foo",
+ repository: "posthog/posthog",
+ commits: RESULT.commits.map((commit) => ({
+ ...commit,
+ subject: "feat(desktop): show commits",
+ })),
+ },
+ },
+ }),
+ });
+ });
+
+ it("abandons a stalled report and cancels its request", async () => {
+ vi.useFakeTimers();
+ try {
+ // A connection that never answers: the commit already landed, so the
+ // report must give up on its own rather than wedge the tool call.
+ fetchMock.mockImplementation(() => new Promise(() => {}));
+ const pending = reportTaskRunCommits({
+ taskId: "task-1",
+ taskRunId: "run-1",
+ result: RESULT,
+ message: "feat(desktop): show commits",
+ env: ENV,
+ envFilePath: NO_ENV_FILE,
+ oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
+ });
+ await vi.advanceTimersByTimeAsync(20_000);
+ await expect(pending).resolves.toBeUndefined();
+
+ // The deadline must also abort the request so it releases its socket
+ // rather than dangling after the reporter gives up.
+ const [, init] = fetchMock.mock.calls[0];
+ const signal = (init as RequestInit).signal;
+ expect(signal).toBeInstanceOf(AbortSignal);
+ expect(signal?.aborted).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/products/desktop/packages/agent/src/signed-commit-artefacts.ts b/products/desktop/packages/agent/src/signed-commit-artefacts.ts
index b5ce88a13085..76857074a3ef 100644
--- a/products/desktop/packages/agent/src/signed-commit-artefacts.ts
+++ b/products/desktop/packages/agent/src/signed-commit-artefacts.ts
@@ -91,6 +91,32 @@ export function createSandboxPosthogClient(
});
}
+// Reports are best-effort bookkeeping for a commit that already landed, and the
+// sandbox client's fetches carry no timeout, so one stalled connection to the
+// PostHog backend would otherwise wedge the signed-commit tool indefinitely.
+const REPORT_TIMEOUT_MS = 15_000;
+
+function withReportDeadline<T>(
+ work: (signal: AbortSignal) => Promise<T>,
+ what: string,
+): Promise<T> {
+ const controller = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ // Race a timer so the reporter resolves even if the request ignores the abort,
+ // and abort on timeout so the underlying fetch releases its socket rather than
+ // dangling until undici's own header/body timeouts reclaim it.
+ return Promise.race([
+ work(controller.signal),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ controller.abort();
+ reject(new Error(`${what} timed out after ${REPORT_TIMEOUT_MS}ms`));
+ }, REPORT_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
export async function reportCommitArtefacts(opts: {
taskId: string | undefined;
result: SignedCommitResult;
@@ -113,19 +139,31 @@ export async function reportCommitArtefacts(opts: {
if (!client) {
return; // No sandbox PostHog credentials — nothing to report to.
}
- const reportIds = await client.getSignalReportIdsForTask(taskId);
+ const reportIds = await withReportDeadline(
+ (signal) => client.getSignalReportIdsForTask(taskId, signal),
+ "signal report lookup",
+ );
for (const reportId of reportIds) {
for (const commit of result.commits) {
try {
- await client.createSignalReportArtefact(reportId, taskId, {
- artefact_type: "commit",
- content: {
- repository: result.repository,
- branch: result.branch,
- commit_sha: commit.sha,
- message,
- },
- });
+ await withReportDeadline(
+ (signal) =>
+ client.createSignalReportArtefact(
+ reportId,
+ taskId,
+ {
+ artefact_type: "commit",
+ content: {
+ repository: result.repository,
+ branch: result.branch,
+ commit_sha: commit.sha,
+ message,
+ },
+ },
+ signal,
+ ),
+ "commit artefact post",
+ );
} catch (err) {
warn(
`failed to record commit ${commit.sha} on report ${reportId}: ${err}`,
@@ -148,7 +186,8 @@ export async function reportTaskRunBranch(opts: {
envFilePath?: string;
oauthEnvFilePath?: string;
}): Promise<void> {
- if (!opts.taskId || !opts.taskRunId) {
+ const { taskId, taskRunId } = opts;
+ if (!taskId || !taskRunId) {
return;
}
try {
@@ -160,23 +199,107 @@ export async function reportTaskRunBranch(opts: {
if (!client) {
return;
}
- await client.updateTaskRun(opts.taskId, opts.taskRunId, {
- ...(opts.updateCheckoutBranch !== false && { branch: opts.branch }),
- output: {
- head_branch: opts.branch,
- head_branches: [
+ await withReportDeadline(
+ (signal) =>
+ client.updateTaskRun(
+ taskId,
+ taskRunId,
{
- repository: opts.repository.trim().toLowerCase(),
- branch: opts.branch,
+ ...(opts.updateCheckoutBranch !== false && { branch: opts.branch }),
+ output: {
+ head_branch: opts.branch,
+ head_branches: [
+ {
+ repository: opts.repository.trim().toLowerCase(),
+ branch: opts.branch,
+ },
+ ],
+ },
},
- ],
- },
- });
+ signal,
+ ),
+ "branch report",
+ );
} catch (err) {
warn(`failed to attach branch ${opts.branch} to task run: ${err}`);
}
}
+export async function reportTaskRunCommits(opts: {
+ taskId: string | undefined;
+ taskRunId: string | undefined;
+ result: SignedCommitResult;
+ message: string;
+ env?: Record<string, string | undefined>;
+ envFilePath?: string;
+ oauthEnvFilePath?: string;
+}): Promise<void> {
+ const { taskId, taskRunId } = opts;
+ if (!taskId || !taskRunId || opts.result.commits.length === 0) {
+ return;
+ }
+ try {
+ const client = createSandboxPosthogClient(
+ opts.env,
+ opts.envFilePath,
+ opts.oauthEnvFilePath,
+ );
+ if (!client) {
+ return;
+ }
+ await withReportDeadline(
+ (signal) =>
+ client.updateTaskRun(
+ taskId,
+ taskRunId,
+ {
+ output: {
+ commit_push: {
+ branch: opts.result.branch,
+ repository: opts.result.repository,
+ commits: opts.result.commits.map((commit) => ({
+ ...commit,
+ subject: opts.message,
+ })),
+ },
+ },
+ },
+ signal,
+ ),
+ "commit report",
+ );
+ } catch (err) {
+ warn(`failed to report commits on task run: ${err}`);
+ }
+}
+
+export async function reportSignedCommitActivity(opts: {
+ taskId: string | undefined;
+ taskRunId: string | undefined;
+ result: SignedCommitResult;
+ message: string;
+ updateCheckoutBranch: boolean;
+}): Promise<void> {
+ await reportTaskRunBranch({
+ taskId: opts.taskId,
+ taskRunId: opts.taskRunId,
+ repository: opts.result.repository,
+ branch: opts.result.branch,
+ updateCheckoutBranch: opts.updateCheckoutBranch,
+ });
+ await reportTaskRunCommits({
+ taskId: opts.taskId,
+ taskRunId: opts.taskRunId,
+ result: opts.result,
+ message: opts.message,
+ });
+ await reportCommitArtefacts({
+ taskId: opts.taskId,
+ result: opts.result,
+ message: opts.message,
+ });
+}
+
// stderr directly (not console) — this also runs inside the Codex stdio MCP child,
// where stdout is the protocol channel.
function warn(message: string): void {
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 2bd178165371..2d112ed22ad2 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -103,7 +103,6 @@ import type {
TaskActivityPage,
TaskActivityReadMarker,
TaskChannel,
- TaskCommentThreadSummary,
TaskMention,
TaskRun,
TaskRunArtefact,
@@ -2909,33 +2908,6 @@ 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.ts
index 5995cb003618..94a9d579451f 100644
--- a/products/desktop/packages/core/src/canvas/activityEvents.ts
+++ b/products/desktop/packages/core/src/canvas/activityEvents.ts
@@ -14,6 +14,8 @@ export const ACTIVITY_EVENTS = [
"artifact_created",
"artifact_revised",
"canvas_created",
+ "comment_added",
+ "comment_state_changed",
"pr_created",
"pr_merged",
"pr_closed",
@@ -53,6 +55,8 @@ export interface ArtifactPayload {
name: string;
artifactType: string;
version: number;
+ /** Names the run whose artifact tab can open this; null on rows that predate it. */
+ runId: string | null;
}
export interface CanvasCreatedPayload {
@@ -72,6 +76,20 @@ export interface MessageForwardedPayload {
runId: string;
}
+/** Identity only: the thread body, quote, and replies are fetched when the row opens. */
+export interface CommentEventPayload {
+ commentId: string;
+ rootCommentId: string;
+ scope: string;
+ itemId: string | null;
+ /** Display name of the commented artifact; null on the task's own scope. */
+ targetName: string | null;
+}
+
+export interface CommentStateChangedPayload extends CommentEventPayload {
+ state: "resolved" | "open";
+}
+
export type ActivityEvent =
| { kind: "run_started"; payload: RunStartedPayload }
| { kind: "run_failed"; payload: RunFailedPayload }
@@ -80,6 +98,8 @@ export type ActivityEvent =
| { kind: "artifact_created"; payload: ArtifactPayload }
| { kind: "artifact_revised"; payload: ArtifactPayload }
| { kind: "canvas_created"; payload: CanvasCreatedPayload }
+ | { kind: "comment_added"; payload: CommentEventPayload }
+ | { kind: "comment_state_changed"; payload: CommentStateChangedPayload }
| { kind: "pr_created"; payload: PrPayload }
| { kind: "pr_merged"; payload: PrPayload }
| { kind: "pr_closed"; payload: PrPayload }
@@ -112,6 +132,7 @@ function artifactPayload(payload: Record<string, unknown>): ArtifactPayload {
name: str(payload.name, "Artifact"),
artifactType: str(payload.artifact_type),
version: num(payload.version, 1),
+ runId: optionalStr(payload.run_id),
};
}
@@ -191,6 +212,26 @@ export function parseActivityEvent(message: {
url: optionalStr(payload.canvas_url),
},
};
+ case "comment_added":
+ case "comment_state_changed": {
+ const rootCommentId = str(payload.root_comment_id);
+ // A row with no thread to open or fetch cannot be drawn.
+ if (!rootCommentId) return null;
+ const base = {
+ commentId: str(payload.comment_id),
+ rootCommentId,
+ scope: str(payload.scope),
+ itemId: optionalStr(payload.item_id),
+ targetName: optionalStr(payload.target_name),
+ };
+ if (event === "comment_added") {
+ return { kind: event, payload: base };
+ }
+ const state = payload.state;
+ return state === "resolved" || state === "open"
+ ? { kind: event, payload: { ...base, state } }
+ : null;
+ }
case "pr_created":
case "pr_merged":
case "pr_closed": {
diff --git a/products/desktop/packages/core/src/canvas/activityTimeline.test.ts b/products/desktop/packages/core/src/canvas/activityTimeline.test.ts
index 99f246760bb2..a0a8925f6b40 100644
--- a/products/desktop/packages/core/src/canvas/activityTimeline.test.ts
+++ b/products/desktop/packages/core/src/canvas/activityTimeline.test.ts
@@ -149,15 +149,31 @@ describe("activity timeline", () => {
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"),
- ],
- });
+ it.each([
+ ["an agent", "agent" as const],
+ ["a human", "human" as const],
+ ["an unattributed author", undefined],
+ ])(
+ "ignores an unknown event from %s, so the backend can ship first",
+ (_name, authorKind) => {
+ // A human-authored announcement the client can't parse must not surface as a reply
+ // typed by that person; the content is a fixed server string.
+ const rows = build({
+ messages: [
+ {
+ id: "m1",
+ content: "Commented",
+ created_at: "2026-08-01T10:30:00Z",
+ ...(authorKind ? { author_kind: authorKind } : {}),
+ event: "checks_failed_someday",
+ payload: {},
+ },
+ ],
+ });
- expect(rows.map((row) => row.kind)).toEqual(["task_created"]);
- });
+ 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
@@ -301,6 +317,7 @@ describe("activity events", () => {
name: "Artifact",
artifactType: "",
version: 1,
+ runId: null,
},
});
});
@@ -398,6 +415,55 @@ describe("commits pushed", () => {
}),
).toBeNull();
});
+});
+
+describe("comment events", () => {
+ it("reads identity-only comment events, and drops one with no thread to open", () => {
+ expect(
+ parseActivityEvent({
+ event: "comment_added",
+ payload: {
+ comment_id: "c-1",
+ root_comment_id: "c-1",
+ scope: "task_artifact",
+ item_id: "artifact-1",
+ },
+ }),
+ ).toEqual({
+ kind: "comment_added",
+ payload: {
+ commentId: "c-1",
+ rootCommentId: "c-1",
+ scope: "task_artifact",
+ itemId: "artifact-1",
+ targetName: null,
+ },
+ });
+ expect(
+ parseActivityEvent({
+ event: "comment_state_changed",
+ payload: {
+ comment_id: "c-2",
+ root_comment_id: "c-1",
+ scope: "task",
+ item_id: "task-1",
+ state: "resolved",
+ },
+ }),
+ ).toMatchObject({
+ kind: "comment_state_changed",
+ payload: { rootCommentId: "c-1", state: "resolved" },
+ });
+ expect(
+ parseActivityEvent({ event: "comment_added", payload: {} }),
+ ).toBeNull();
+ expect(
+ parseActivityEvent({
+ event: "comment_state_changed",
+ payload: { root_comment_id: "c-1", state: "archived" },
+ }),
+ ).toBeNull();
+ });
it("keys a push on its head SHA, so a retried report is one row", () => {
const push = (id: string) =>
diff --git a/products/desktop/packages/core/src/canvas/activityTimeline.ts b/products/desktop/packages/core/src/canvas/activityTimeline.ts
index 9e7a566c18fb..6032c0ff2a9d 100644
--- a/products/desktop/packages/core/src/canvas/activityTimeline.ts
+++ b/products/desktop/packages/core/src/canvas/activityTimeline.ts
@@ -115,7 +115,9 @@ export function buildActivityTimeline<
for (const message of messages) {
const event = parseActivityEvent(message);
if (!event) {
- if ((message.author_kind ?? "human") === "human") {
+ // A message carrying an event we couldn't parse is a future event kind, not a human
+ // reply; drawing it as one would misattribute a server announcement to the person.
+ if (!message.event && (message.author_kind ?? "human") === "human") {
rows.push({
kind: "human_message",
key: `message-${message.id}`,
@@ -230,6 +232,10 @@ function eventIdentity(
return `${event.payload.artifactId}:${event.payload.version}`;
case "canvas_created":
return event.payload.name;
+ // One row per comment id: the backend emits roots and state changes only.
+ case "comment_added":
+ case "comment_state_changed":
+ return event.payload.commentId;
case "pr_created":
case "pr_merged":
case "pr_closed":
diff --git a/products/desktop/packages/core/src/canvas/threadTimeline.ts b/products/desktop/packages/core/src/canvas/threadTimeline.ts
index ea45bfdeed6a..9ef7bfd7cdd9 100644
--- a/products/desktop/packages/core/src/canvas/threadTimeline.ts
+++ b/products/desktop/packages/core/src/canvas/threadTimeline.ts
@@ -67,7 +67,9 @@ export function buildThreadTimeline<T extends ThreadMessageLike>(
const artifact = threadMessageArtifact(message);
if (artifact) {
rows.push({ kind: "artifact", timestamp, message, artifact });
- } else if ((message.author_kind ?? "human") === "human") {
+ } else if (!message.event && (message.author_kind ?? "human") === "human") {
+ // Event-bearing rows (comment announcements) belong to the activity
+ // timeline; drawn here they would read as something the person typed.
rows.push({ kind: "human", timestamp, message });
}
}
diff --git a/products/desktop/packages/core/src/git/router-schemas.ts b/products/desktop/packages/core/src/git/router-schemas.ts
index 99273934eaa4..1f5513a6612c 100644
--- a/products/desktop/packages/core/src/git/router-schemas.ts
+++ b/products/desktop/packages/core/src/git/router-schemas.ts
@@ -473,6 +473,12 @@ export const getBranchChangedFilesInput = z.object({
});
export const getBranchChangedFilesOutput = z.array(changedFileSchema);
+export const getCommitChangedFilesInput = z.object({
+ repo: z.string(),
+ sha: z.string(),
+});
+export const getCommitChangedFilesOutput = z.array(changedFileSchema);
+
export const getLocalBranchChangedFilesInput = z.object({
directoryPath: z.string(),
branch: z.string(),
diff --git a/products/desktop/packages/host-router/src/routers/git.router.ts b/products/desktop/packages/host-router/src/routers/git.router.ts
index 219b00790a23..cb85eceff2a7 100644
--- a/products/desktop/packages/host-router/src/routers/git.router.ts
+++ b/products/desktop/packages/host-router/src/routers/git.router.ts
@@ -39,6 +39,8 @@ import {
getBranchChangedFilesOutput,
getChangedFilesHeadInput,
getChangedFilesHeadOutput,
+ getCommitChangedFilesInput,
+ getCommitChangedFilesOutput,
getCommitConventionsInput,
getCommitConventionsOutput,
getCurrentBranchInput,
@@ -629,6 +631,16 @@ export const gitRouter = router({
}),
),
+ getCommitChangedFiles: publicProcedure
+ .input(getCommitChangedFilesInput)
+ .output(getCommitChangedFilesOutput)
+ .query(({ ctx, input }) =>
+ getWorkspaceClient(ctx.container).git.getCommitChangedFiles.query({
+ repo: input.repo,
+ sha: input.sha,
+ }),
+ ),
+
getLocalBranchChangedFiles: publicProcedure
.input(getLocalBranchChangedFilesInput)
.output(getLocalBranchChangedFilesOutput)
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.tsx
index e98e640c8ae0..abeeaf33dfd8 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
@@ -12,7 +12,7 @@ import {
// 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 }));
+const loaded = vi.hoisted(() => ({ thread: true }));
vi.mock("@posthog/ui/features/canvas/hooks/useThreadConversation", () => ({
useThreadConversation: () => ({
@@ -35,13 +35,6 @@ 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", () => ({
@@ -96,7 +89,6 @@ describe("ActivityPanel", () => {
beforeEach(() => {
loaded.thread = true;
- loaded.comments = true;
scrollTo = vi.spyOn(Element.prototype, "scrollTo");
useCommentNavigationStore.setState({
focusByTask: {},
@@ -214,10 +206,9 @@ describe("ActivityPanel", () => {
expect(scrollTo.mock.calls.length).toBe(timelineScrolls);
});
- it("waits for both sources, then never takes the timeline away again", () => {
+ it("waits for the thread, 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
@@ -232,11 +223,6 @@ describe("ActivityPanel", () => {
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.
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
index 9fd72d15a0e0..d944c9ed69e8 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
@@ -16,7 +16,6 @@ import {
AgentStatusLine,
ThreadLoadingState,
} 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";
@@ -160,21 +159,15 @@ 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.
+ // Draw once the thread has answered, and never take the timeline away again.
+ // 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);
+ const timelineReady = hasDrawnTimeline.current || hasLoadedThread;
useEffect(() => {
- if (hasLoadedThread && hasLoadedComments) hasDrawnTimeline.current = true;
- }, [hasLoadedThread, hasLoadedComments]);
+ if (hasLoadedThread) hasDrawnTimeline.current = true;
+ }, [hasLoadedThread]);
// 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
@@ -286,7 +279,6 @@ function ActivityConversation({
timeline={timeline}
messages={messages}
conversationItems={conversationItems}
- commentThreads={commentThreads}
currentUserId={currentUser?.id}
canOpenInPlace={canOpenInPlace}
/>
@@ -364,10 +356,9 @@ 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.
+ // Warmed from the id alone so it doesn't queue behind the task itself, which can take
+ // seconds to arrive. Same query key as the panel's own hook, so this shares one fetch.
useTaskThread(taskId, { enabled: !collapsed, markActivityRead: false });
- useTaskCommentActivity(taskId, { enabled: !collapsed });
if (collapsed) {
return (
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.tsx
index ce6a101a26a0..26a346cc607b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.stories.tsx
@@ -5,6 +5,10 @@ import type {
TaskThreadMessage,
} from "@posthog/shared/domain-types";
import { ActivityTimeline } from "@posthog/ui/features/canvas/components/ActivityTimeline";
+import {
+ CommitFilesList,
+ DetailBlock,
+} from "@posthog/ui/features/canvas/components/activityRows";
import type { Meta, StoryObj } from "@storybook/react-vite";
const shy = {
@@ -87,6 +91,56 @@ const messages: TaskThreadMessage[] = [
),
event(
"e6",
+ "commits_pushed",
+ {
+ run_id: "run-1",
+ branch: "shy/activity-events",
+ repository: "PostHog/posthog",
+ total: 2,
+ head_sha: "9c2f1aa",
+ commits: [
+ {
+ sha: "5a0a28b",
+ subject: "feat(desktop): draw activity events on the timeline",
+ url: "https://github.com/PostHog/posthog/commit/5a0a28b",
+ },
+ {
+ sha: "9c2f1aa",
+ subject: "fix(desktop): keep the timeline scroll anchored",
+ url: "https://github.com/PostHog/posthog/commit/9c2f1aa",
+ },
+ ],
+ },
+ "2026-08-05T14:45:00Z",
+ ),
+ {
+ ...event(
+ "e6b",
+ "comment_added",
+ {
+ comment_id: "c-1",
+ root_comment_id: "c-1",
+ scope: "task_artifact",
+ item_id: "artifact-1",
+ },
+ "2026-08-05T15:00:00Z",
+ ),
+ author_kind: "human",
+ author: shy,
+ } as TaskThreadMessage,
+ event(
+ "e6c",
+ "artifact_revised",
+ {
+ artifact_id: "artifact-1",
+ name: "activity-events.html",
+ artifact_type: "document",
+ version: 3,
+ },
+ "2026-08-05T15:10:00Z",
+ ),
+ event(
+ "e7",
"pr_merged",
{
pr_url: "https://github.com/PostHog/posthog/pull/80060",
@@ -185,3 +239,45 @@ export const FullTimeline: Story = {
currentUserId: ben.id,
},
};
+
+/** The changed-file list a commit row shows once GitHub answers. In the timeline
+ * above the fetch never resolves (no workspace-server in Storybook), so the
+ * presentational list is shown on its own here. */
+export const CommitFiles: StoryObj = {
+ render: () => (
+ <div className="p-3">
+ <DetailBlock>
+ <CommitFilesList
+ files={[
+ {
+ path: "products/desktop/packages/core/src/canvas/activityEvents.ts",
+ status: "added",
+ linesAdded: 210,
+ linesRemoved: 0,
+ },
+ {
+ path: "products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx",
+ status: "modified",
+ linesAdded: 96,
+ linesRemoved: 30,
+ },
+ {
+ path: "products/desktop/packages/core/src/canvas/rows/ActivityBead.tsx",
+ status: "renamed",
+ originalPath:
+ "products/desktop/packages/ui/src/features/canvas/Bead.tsx",
+ linesAdded: 4,
+ linesRemoved: 4,
+ },
+ {
+ path: "products/desktop/packages/core/src/canvas/activityFlags.ts",
+ status: "deleted",
+ linesAdded: 0,
+ linesRemoved: 41,
+ },
+ ]}
+ />
+ </DetailBlock>
+ </div>
+ ),
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx
index e4de94dc182c..bba6cc7435ec 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx
@@ -1,4 +1,8 @@
import { FileTextIcon, ScrollIcon } from "@phosphor-icons/react";
+import type {
+ ArtifactPayload,
+ CommentEventPayload,
+} from "@posthog/core/canvas/activityEvents";
import {
type ActivityRow,
buildActivityTimeline,
@@ -21,6 +25,8 @@ import type {
} from "@posthog/shared/domain-types";
import {
ActivityEventRow,
+ ArtifactEventDetail,
+ CommentEventRow,
CommentRow,
CommentStateRow,
CREATED_BADGE,
@@ -257,6 +263,36 @@ export function ActivityTimeline({
);
};
+ const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
+ const openArtifact = (payload: ArtifactPayload) => {
+ if (!canOpenInPlace || !payload.runId || !payload.artifactId) {
+ return undefined;
+ }
+ const runId = payload.runId;
+ return () =>
+ openArtifactTab(task.id, {
+ runId,
+ artifactId: payload.artifactId,
+ name: payload.name,
+ });
+ };
+
+ const openCommentThread = (payload: CommentEventPayload) => {
+ if (!canOpenInPlace) return undefined;
+ const scope = payload.scope;
+ if (
+ scope !== "task" &&
+ scope !== "task_artifact" &&
+ scope !== "desktop_canvas"
+ ) {
+ return undefined;
+ }
+ const itemId = scope === "task" ? task.id : payload.itemId;
+ if (!itemId) return undefined;
+ return () =>
+ requestCommentFocus(task.id, { scope, itemId }, payload.rootCommentId);
+ };
+
const hasTranscript = useHasTranscriptListener(task.id);
const requestScrollToMessage = useThreadNavigationStore(
(state) => state.requestScrollToMessage,
@@ -322,6 +358,22 @@ export function ActivityTimeline({
/>
);
case "event": {
+ if (
+ row.event.kind === "comment_added" ||
+ row.event.kind === "comment_state_changed"
+ ) {
+ return (
+ <CommentEventRow
+ connectedAbove={connectedAbove}
+ connectedBelow={connectedBelow}
+ event={row.event}
+ author={row.message.author ?? null}
+ timestamp={row.message.created_at}
+ taskId={task.id}
+ onOpenThread={openCommentThread(row.event.payload)}
+ />
+ );
+ }
// 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);
@@ -339,6 +391,12 @@ export function ActivityTimeline({
artifact={artifactRow.artifact}
openInPlaceTaskId={canOpenInPlace ? task.id : undefined}
/>
+ ) : row.event.kind === "artifact_created" ||
+ row.event.kind === "artifact_revised" ? (
+ <ArtifactEventDetail
+ payload={row.event.payload}
+ onOpen={openArtifact(row.event.payload)}
+ />
) : undefined
}
/>
diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx
index 33ade1ff57c5..91d21da0a559 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx
@@ -20,10 +20,15 @@ import {
SquaresFourIcon,
XIcon,
} from "@phosphor-icons/react";
+import type { CommentScope } from "@posthog/api-client/posthog-client";
import {
type ActivityEvent,
+ type ArtifactPayload,
+ type CommentEventPayload,
+ type CommitsPushedPayload,
prLabel,
} from "@posthog/core/canvas/activityEvents";
+import type { ChangedFile } from "@posthog/core/git/router-schemas";
import { xmlToContent } from "@posthog/core/message-editor/content";
import {
Button,
@@ -41,7 +46,11 @@ 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 { useCommitChangedFiles } from "@posthog/ui/features/git-interaction/useGitQueries";
import { ChatMarkdown } from "@posthog/ui/features/sessions/components/chat-thread/ChatMarkdown";
+import { useCommentsQuery } from "@posthog/ui/features/sessions/components/useComments";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
import { type ReactNode, useMemo, useState } from "react";
export function TimelineRow({
@@ -235,6 +244,9 @@ const EVENT_TONES: Record<ActivityEvent["kind"], BeadTone> = {
artifact_created: "violet",
artifact_revised: "violet",
canvas_created: "violet",
+ // Comment rows draw the commenter's avatar bead instead; kept for the map's completeness.
+ comment_added: "neutral",
+ comment_state_changed: "green",
pr_created: "neutral",
pr_merged: "violet",
pr_closed: "red",
@@ -251,6 +263,8 @@ const EVENT_ICONS: Record<ActivityEvent["kind"], ReactNode> = {
artifact_created: <FileTextIcon size={11} />,
artifact_revised: <ArrowsClockwiseIcon size={11} />,
canvas_created: <SquaresFourIcon size={11} />,
+ comment_added: <ChatCircleIcon size={11} />,
+ comment_state_changed: <CheckIcon size={11} weight="bold" />,
pr_created: <GitPullRequestIcon size={11} />,
pr_merged: <GitMergeIcon size={11} />,
pr_closed: <ProhibitIcon size={11} />,
@@ -331,6 +345,12 @@ function eventLabel(
</>
);
}
+ case "comment_added":
+ return "Comment added";
+ case "comment_state_changed":
+ return event.payload.state === "resolved"
+ ? "Comment thread resolved"
+ : "Comment thread reopened";
case "message_forwarded":
return "Message sent to the agent";
}
@@ -363,20 +383,16 @@ function eventDetail(event: ActivityEvent): ReactNode {
</DetailBlock>
);
case "commits_pushed": {
- const { commits, total } = event.payload;
+ const { commits, total, repository } = event.payload;
return (
<DetailBlock>
- <div className="space-y-1">
+ <div className="max-h-56 space-y-1.5 overflow-y-auto overscroll-contain">
{commits.map((commit) => (
- <div
+ <PushedCommitRow
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>
+ commit={commit}
+ repository={repository}
+ />
))}
{total > commits.length && (
<div className="text-muted-foreground">
@@ -454,14 +470,193 @@ export function MessageBubble({ content }: { content: string }) {
}
/** No radius, so the left edge reads as a rule rather than the outline of a box. */
-export function DetailBlock({ children }: { children: ReactNode }) {
+export function DetailBlock({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
return (
- <div className="break-words border-gray-6 border-l-2 bg-gray-2 px-2.5 py-1.5 text-[12.5px]">
+ <div
+ className={cn(
+ "break-words border-gray-6 border-l-2 bg-gray-2 px-2.5 py-1.5 text-[12.5px]",
+ className,
+ )}
+ >
{children}
</div>
);
}
+/** Clickable when the artifact can open in the panel's artifact tab. */
+export function ArtifactEventDetail({
+ payload,
+ onOpen,
+}: {
+ payload: ArtifactPayload;
+ onOpen?: () => void;
+}) {
+ const body = (
+ <>
+ {payload.name}
+ <span className="text-muted-foreground"> · v{payload.version}</span>
+ </>
+ );
+ if (!onOpen) {
+ return <DetailBlock>{body}</DetailBlock>;
+ }
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ className="block w-full cursor-pointer text-left"
+ aria-label={`Open ${payload.name}`}
+ >
+ <DetailBlock className="transition-colors hover:border-gray-7 hover:bg-gray-3">
+ {body}
+ </DetailBlock>
+ </button>
+ );
+}
+
+function CommitSha({ sha, url }: { sha: string; url: string | null }) {
+ const short = sha.slice(0, 7);
+ // url comes from caller-controlled run output, so a bare https check would
+ // let a crafted payload open any host behind a github-looking label. Pin it
+ // to github.com, the same gate usePrArtifact applies to run-output PR links.
+ const parsed = url ? parseHttpsUrl(url) : null;
+ const safeUrl = parsed?.origin === "https://github.com" ? parsed.href : null;
+ if (!safeUrl) {
+ return (
+ <span className="shrink-0 font-mono text-[11.5px] text-muted-foreground">
+ {short}
+ </span>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={() => openExternalUrl(safeUrl)}
+ className="shrink-0 cursor-pointer font-mono text-[11.5px] text-muted-foreground hover:text-foreground hover:underline"
+ aria-label={`Open commit ${short} on GitHub`}
+ >
+ {short}
+ </button>
+ );
+}
+
+/** The payload is identity-only; TimelineRow defers this detail to the first expand,
+ * so the GitHub file fetch runs then. Without gh access the identity line stands alone. */
+function PushedCommitRow({
+ commit,
+ repository,
+}: {
+ commit: CommitsPushedPayload["commits"][number];
+ repository: string | null;
+}) {
+ const { data: files, isLoading } = useCommitChangedFiles(
+ repository,
+ commit.sha,
+ );
+ return (
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-baseline gap-2">
+ <CommitSha sha={commit.sha} url={commit.url} />
+ <span className="min-w-0 truncate">{commit.subject}</span>
+ </div>
+ {isLoading ? (
+ <CommitFilesSkeleton />
+ ) : (
+ files && files.length > 0 && <CommitFilesList files={files} />
+ )}
+ </div>
+ );
+}
+
+const FILE_STATUS_GLYPHS: Record<
+ ChangedFile["status"],
+ { letter: string; tone: string }
+> = {
+ added: { letter: "A", tone: "text-green-11" },
+ modified: { letter: "M", tone: "text-muted-foreground" },
+ deleted: { letter: "D", tone: "text-red-11" },
+ renamed: { letter: "R", tone: "text-amber-11" },
+ // Not a state GitHub's commit API produces; covered for the shared ChangedFile type.
+ untracked: { letter: "A", tone: "text-green-11" },
+};
+
+/** Mirrors CommitFileRow's geometry (letter, path, stats) so the loaded list lands without a jump. */
+function CommitFilesSkeleton() {
+ return (
+ <div className="mt-0.5 space-y-px">
+ {["w-3/5", "w-2/5", "w-1/2"].map((width) => (
+ <div key={width} className="flex h-[17px] items-center gap-1.5">
+ <Skeleton className="size-2.5 shrink-0 rounded-[3px]" />
+ <Skeleton className={cn("h-2.5", width)} />
+ <Skeleton className="ml-auto h-2.5 w-8 shrink-0" />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export function CommitFilesList({ files }: { files: ChangedFile[] }) {
+ return (
+ <div className="mt-0.5 space-y-px">
+ {files.map((file) => (
+ <CommitFileRow key={file.path} file={file} />
+ ))}
+ </div>
+ );
+}
+
+function CommitFileRow({ file }: { file: ChangedFile }) {
+ const glyph = FILE_STATUS_GLYPHS[file.status];
+ const split = file.path.lastIndexOf("/");
+ // The directory truncates first so the file name stays readable on long paths.
+ const dir = split === -1 ? "" : file.path.slice(0, split + 1);
+ const base = split === -1 ? file.path : file.path.slice(split + 1);
+ const title = file.originalPath
+ ? `${file.originalPath} → ${file.path}`
+ : file.path;
+ return (
+ <div
+ className="flex min-w-0 items-baseline gap-1.5 font-mono text-[11px] leading-[17px]"
+ title={title}
+ >
+ <span
+ className={cn("w-3 shrink-0 text-center font-semibold", glyph.tone)}
+ >
+ {glyph.letter}
+ </span>
+ <span className="flex min-w-0 flex-1 items-baseline">
+ {dir && (
+ <span className="min-w-0 truncate text-muted-foreground">{dir}</span>
+ )}
+ <span
+ className={cn(
+ "shrink-0",
+ file.status === "deleted" && "text-muted-foreground line-through",
+ )}
+ >
+ {base}
+ </span>
+ </span>
+ {((file.linesAdded ?? 0) > 0 || (file.linesRemoved ?? 0) > 0) && (
+ <span className="shrink-0 text-[10.5px] tabular-nums">
+ {(file.linesAdded ?? 0) > 0 && (
+ <span className="text-green-11">+{file.linesAdded}</span>
+ )}{" "}
+ {(file.linesRemoved ?? 0) > 0 && (
+ <span className="text-red-11">-{file.linesRemoved}</span>
+ )}
+ </span>
+ )}
+ </div>
+ );
+}
+
export function ActivityEventRow({
event,
timestamp,
@@ -639,6 +834,149 @@ export function CommentStateRow({
);
}
+export function CommentEventRow({
+ event,
+ author,
+ timestamp,
+ taskId,
+ onOpenThread,
+ connectedAbove = true,
+ connectedBelow = true,
+}: {
+ event: Extract<
+ ActivityEvent,
+ { kind: "comment_added" | "comment_state_changed" }
+ >;
+ author: UserBasic | null;
+ timestamp: string;
+ taskId: string;
+ onOpenThread?: () => void;
+ connectedAbove?: boolean;
+ connectedBelow?: boolean;
+}) {
+ const name = author ? userDisplayName(author) : "Someone";
+ const target = event.payload.targetName;
+ if (event.kind === "comment_state_changed") {
+ const resolved = event.payload.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={timestamp}
+ >
+ <span className="font-medium">{name}</span>{" "}
+ <span className="text-muted-foreground">
+ {resolved ? "resolved a thread" : "reopened a thread"}
+ {target ? " on" : ""}
+ </span>
+ {target && (
+ <>
+ {" "}
+ <span className="font-medium">{target}</span>
+ </>
+ )}
+ </TimelineRow>
+ );
+ }
+ return (
+ <TimelineRow
+ connectedAbove={connectedAbove}
+ connectedBelow={connectedBelow}
+ gutter={<PersonBead user={author} badge={COMMENT_BADGE} />}
+ timestamp={timestamp}
+ detail={
+ <CommentEventDetail
+ taskId={taskId}
+ payload={event.payload}
+ onOpenThread={onOpenThread}
+ />
+ }
+ >
+ <span className="font-medium">{name}</span>{" "}
+ <span className="text-muted-foreground">
+ commented{target ? " on" : ""}
+ </span>
+ {target && (
+ <>
+ {" "}
+ <span className="font-medium">{target}</span>
+ </>
+ )}
+ </TimelineRow>
+ );
+}
+
+const COMMENT_EVENT_SCOPES: readonly string[] = [
+ "task",
+ "task_artifact",
+ "desktop_canvas",
+];
+
+function CommentEventDetail({
+ taskId,
+ payload,
+ onOpenThread,
+}: {
+ taskId: string;
+ payload: CommentEventPayload;
+ onOpenThread?: () => void;
+}) {
+ const target =
+ COMMENT_EVENT_SCOPES.includes(payload.scope) && payload.itemId
+ ? { scope: payload.scope as CommentScope, itemId: payload.itemId }
+ : null;
+ const { data, isLoading } = useCommentsQuery(target, taskId, {
+ live: false,
+ });
+ const comments = data ?? [];
+ const root = comments.find((c) => c.id === payload.rootCommentId);
+ const replyCount = comments.filter(
+ (c) => c.source_comment === payload.rootCommentId,
+ ).length;
+ const context = root?.item_context as { anchor?: { quote?: unknown } } | null;
+ const quote =
+ typeof context?.anchor?.quote === "string" ? context.anchor.quote : null;
+ return (
+ <div className="space-y-1.5">
+ {isLoading ? (
+ <DetailBlock>
+ <Skeleton className="h-3 w-3/5" />
+ </DetailBlock>
+ ) : root ? (
+ <DetailBlock>
+ {quote && (
+ <div className="mb-1 truncate text-muted-foreground italic">
+ “{quote}”
+ </div>
+ )}
+ <MessageBody content={root.content ?? ""} />
+ </DetailBlock>
+ ) : null}
+ {replyCount > 0 && (
+ <div className="truncate text-[12.5px] text-muted-foreground">
+ {replyCount} {replyCount === 1 ? "reply" : "replies"}
+ </div>
+ )}
+ {onOpenThread && (
+ <DetailAction onClick={onOpenThread}>Open thread</DetailAction>
+ )}
+ </div>
+ );
+}
+
/** 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() {
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskCommentActivity.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskCommentActivity.ts
deleted file mode 100644
index 02cdc90d4e9c..000000000000
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskCommentActivity.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-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.ts
index c7c39925f45e..8467e17aba31 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskThread.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskThread.ts
@@ -46,6 +46,9 @@ export function useTaskThread(
enabled: !!taskId && enabled,
refetchInterval: pollIntervalMs,
staleTime: pollIntervalMs,
+ // The poll is the retry. Request-level retries also hold the timeline's
+ // first paint behind their backoff, since it gates on this query settling.
+ retry: false,
},
);
useEffect(() => {
diff --git a/products/desktop/packages/ui/src/features/git-interaction/useGitQueries.ts b/products/desktop/packages/ui/src/features/git-interaction/useGitQueries.ts
index 28c42977e25e..2265f3c20ad9 100644
--- a/products/desktop/packages/ui/src/features/git-interaction/useGitQueries.ts
+++ b/products/desktop/packages/ui/src/features/git-interaction/useGitQueries.ts
@@ -164,6 +164,21 @@ export function usePrChangedFiles(prUrl: string | null, pollFast?: boolean) {
);
}
+export function useCommitChangedFiles(repo: string | null, sha: string | null) {
+ const trpc = useHostTRPC();
+ return useQuery(
+ trpc.git.getCommitChangedFiles.queryOptions(
+ { repo: repo as string, sha: sha as string },
+ {
+ enabled: !!repo && !!sha,
+ // A commit is immutable per sha, so a fetched file list never goes stale.
+ staleTime: Number.POSITIVE_INFINITY,
+ retry: 1,
+ },
+ ),
+ );
+}
+
export function useBranchChangedFiles(
repo: string | null,
branch: string | null,
diff --git a/products/desktop/packages/workspace-server/src/services/git/schemas.ts b/products/desktop/packages/workspace-server/src/services/git/schemas.ts
index f011a887a0be..29eddac6c8da 100644
--- a/products/desktop/packages/workspace-server/src/services/git/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/schemas.ts
@@ -349,6 +349,11 @@ export const getBranchChangedFilesInput = z.object({
branch: z.string(),
});
+export const getCommitChangedFilesInput = z.object({
+ repo: z.string(),
+ sha: z.string(),
+});
+
export const getLocalBranchChangedFilesInput = z.object({
directoryPath: z.string(),
branch: z.string(),
diff --git a/products/desktop/packages/workspace-server/src/services/git/service.test.ts b/products/desktop/packages/workspace-server/src/services/git/service.test.ts
index 8e72459c41e8..47fbe0579e22 100644
--- a/products/desktop/packages/workspace-server/src/services/git/service.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/service.test.ts
@@ -70,6 +70,72 @@ describe("GitService", () => {
]);
});
+ it("maps a commit's files, including removals and renames", async () => {
+ execGhMock.mockResolvedValueOnce(
+ ghResult({
+ stdout: JSON.stringify({
+ files: [
+ {
+ filename: "docs/old.md",
+ status: "removed",
+ additions: 0,
+ deletions: 7,
+ },
+ {
+ filename: "src/new-name.ts",
+ status: "renamed",
+ previous_filename: "src/old-name.ts",
+ additions: 1,
+ deletions: 1,
+ },
+ ],
+ }),
+ }),
+ );
+
+ await expect(
+ new GitService().getCommitChangedFiles("posthog/code", "a".repeat(40)),
+ ).resolves.toEqual([
+ {
+ path: "docs/old.md",
+ status: "deleted",
+ originalPath: undefined,
+ linesAdded: 0,
+ linesRemoved: 7,
+ sha: undefined,
+ patch: undefined,
+ },
+ {
+ path: "src/new-name.ts",
+ status: "renamed",
+ originalPath: "src/old-name.ts",
+ linesAdded: 1,
+ linesRemoved: 1,
+ sha: undefined,
+ patch: undefined,
+ },
+ ]);
+ expect(execGhMock).toHaveBeenCalledWith(
+ ["api", `repos/posthog/code/commits/${"a".repeat(40)}`],
+ { timeoutMs: 10_000 },
+ );
+ });
+
+ it("returns no commit files for an unknown sha, and never queries with a malformed one", async () => {
+ execGhMock.mockResolvedValueOnce(
+ ghResult({ stderr: "gh: Not Found (HTTP 404)\n", exitCode: 1 }),
+ );
+ await expect(
+ new GitService().getCommitChangedFiles("posthog/code", "b".repeat(40)),
+ ).resolves.toEqual([]);
+
+ execGhMock.mockClear();
+ await expect(
+ new GitService().getCommitChangedFiles("posthog/code", "main..evil"),
+ ).resolves.toEqual([]);
+ expect(execGhMock).not.toHaveBeenCalled();
+ });
+
it("preserves non-404 comparison failures", async () => {
execGhMock
.mockResolvedValueOnce(ghResult({ stdout: "main\n" }))
diff --git a/products/desktop/packages/workspace-server/src/services/git/service.ts b/products/desktop/packages/workspace-server/src/services/git/service.ts
index 91b414e006fb..ad66721e619c 100644
--- a/products/desktop/packages/workspace-server/src/services/git/service.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/service.ts
@@ -128,6 +128,49 @@ function toUnifiedDiffPatch(
return `diff --git a/${oldPath} b/${filename}\n--- ${fromPath}\n+++ ${toPath}\n${rawPatch}`;
}
+/** One entry of the `files[]` array GitHub's REST diff endpoints (PR files, compare, commit) share. */
+interface GithubApiFile {
+ filename: string;
+ status: string;
+ previous_filename?: string;
+ additions: number;
+ deletions: number;
+ patch?: string;
+ sha?: string;
+}
+
+function mapGithubApiFiles(files: GithubApiFile[]): ChangedFile[] {
+ return files.map((f) => {
+ let status: ChangedFile["status"];
+ switch (f.status) {
+ case "added":
+ status = "added";
+ break;
+ case "removed":
+ status = "deleted";
+ break;
+ case "renamed":
+ status = "renamed";
+ break;
+ default:
+ status = "modified";
+ break;
+ }
+
+ return {
+ path: f.filename,
+ status,
+ originalPath: f.previous_filename,
+ linesAdded: f.additions,
+ linesRemoved: f.deletions,
+ sha: f.sha,
+ patch: f.patch
+ ? toUnifiedDiffPatch(f.patch, f.filename, f.previous_filename, status)
+ : undefined,
+ };
+ });
+}
+
/**
* Narrow GitHub GraphQL's `PullRequestState` (OPEN | CLOSED | MERGED) to the
* lowercased literal the batch schema expects. Anything unexpected falls back
@@ -1053,48 +1096,8 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
);
}
- const pages = JSON.parse(result.stdout) as Array<
- Array<{
- filename: string;
- status: string;
- previous_filename?: string;
- additions: number;
- deletions: number;
- patch?: string;
- sha?: string;
- }>
- >;
- const files = pages.flat();
-
- return files.map((f) => {
- let status: ChangedFile["status"];
- switch (f.status) {
- case "added":
- status = "added";
- break;
- case "removed":
- status = "deleted";
- break;
- case "renamed":
- status = "renamed";
- break;
- default:
- status = "modified";
- break;
- }
-
- return {
- path: f.filename,
- status,
- originalPath: f.previous_filename,
- linesAdded: f.additions,
- linesRemoved: f.deletions,
- sha: f.sha,
- patch: f.patch
- ? toUnifiedDiffPatch(f.patch, f.filename, f.previous_filename, status)
- : undefined,
- };
- });
+ const pages = JSON.parse(result.stdout) as GithubApiFile[][];
+ return mapGithubApiFiles(pages.flat());
}
/**
@@ -1245,49 +1248,42 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
}
const response = JSON.parse(result.stdout) as {
- files?: Array<{
- filename: string;
- status: string;
- previous_filename?: string;
- additions: number;
- deletions: number;
- patch?: string;
- sha?: string;
- }>;
+ files?: GithubApiFile[];
};
- const files = response.files;
-
- if (!files) return [];
-
- return files.map((f) => {
- let status: ChangedFile["status"];
- switch (f.status) {
- case "added":
- status = "added";
- break;
- case "removed":
- status = "deleted";
- break;
- case "renamed":
- status = "renamed";
- break;
- default:
- status = "modified";
- break;
+ return mapGithubApiFiles(response.files ?? []);
+ }
+
+ async getCommitChangedFiles(
+ repo: string,
+ sha: string,
+ ): Promise<ChangedFile[]> {
+ const parts = repo.split("/");
+ if (parts.length !== 2) return [];
+ // The sha comes from event payloads; the guard keeps a crafted value from
+ // steering the authenticated request to a different GitHub endpoint.
+ if (!/^[0-9a-f]{7,40}$/i.test(sha)) return [];
+
+ const [owner, repoName] = parts;
+ // A stalled fetch would otherwise hang this call forever, holding the expanded
+ // commit row on a permanent skeleton with no error the query can recover from.
+ const result = await execGh(
+ ["api", `repos/${owner}/${repoName}/commits/${sha}`],
+ { timeoutMs: 10_000 },
+ );
+
+ if (result.exitCode !== 0) {
+ if (/HTTP 404\b/.test(`${result.stderr} ${result.error ?? ""}`)) {
+ return [];
}
+ throw new Error(
+ `Failed to fetch commit files: ${result.stderr || result.error || "Unknown error"}`,
+ );
+ }
- return {
- path: f.filename,
- status,
- originalPath: f.previous_filename,
- linesAdded: f.additions,
- linesRemoved: f.deletions,
- sha: f.sha,
- patch: f.patch
- ? toUnifiedDiffPatch(f.patch, f.filename, f.previous_filename, status)
- : undefined,
- };
- });
+ const response = JSON.parse(result.stdout) as {
+ files?: GithubApiFile[];
+ };
+ return mapGithubApiFiles(response.files ?? []);
}
async getLocalBranchChangedFiles(
diff --git a/products/desktop/packages/workspace-server/src/trpc.ts b/products/desktop/packages/workspace-server/src/trpc.ts
index 8327c335ef2d..499d3579558b 100644
--- a/products/desktop/packages/workspace-server/src/trpc.ts
+++ b/products/desktop/packages/workspace-server/src/trpc.ts
@@ -69,6 +69,7 @@ import {
discardFileChangesOutput,
filePathInput,
getBranchChangedFilesInput,
+ getCommitChangedFilesInput,
getCommitConventionsInput,
getCommitConventionsOutput,
getCommitsBetweenBranchesInput,
@@ -609,6 +610,13 @@ export function createAppRouter({
gitService().getBranchChangedFiles(input.repo, input.branch),
),
+ getCommitChangedFiles: t.procedure
+ .input(getCommitChangedFilesInput)
+ .output(changedFilesOutput)
+ .query(({ input }) =>
+ gitService().getCommitChangedFiles(input.repo, input.sha),
+ ),
+
getLocalBranchChangedFiles: t.procedure
.input(getLocalBranchChangedFilesInput)
.output(changedFilesOutput)