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(comments): desktop comment engine, artifact and activity UI (#78690)

Shy Alter26734e2fa63a
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index fc57711b82c0..05490a7e78fb 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -4366,7 +4366,7 @@ export namespace Schemas {
export type ColorMode = "light" | "dark";
export type Comment = {
id: string;
- created_by: UserBasic & unknown;
+ created_by: (UserBasic & unknown) | null;
deleted?: (boolean | null) | undefined;
mentions?: Array<number> | undefined;
slug?: string | undefined;
@@ -4375,9 +4375,10 @@ export namespace Schemas {
version: number;
created_at: string;
item_id?: (string | null) | undefined;
- item_context?: null | undefined;
+ item_context?: unknown;
scope: string;
source_comment?: (string | null) | undefined;
+ completed_at?: (string | null) | undefined;
};
export type CompareItem = { label: string; value: string };
export type ConclusionEnum = "won" | "lost" | "inconclusive" | "stopped_early" | "invalid";
@@ -18454,7 +18455,7 @@ export namespace Endpoints {
path: "/api/projects/{project_id}/comments/";
requestFormat: "json";
parameters: {
- query: Partial<{ cursor: string; item_id: string; scope: string; search: string; source_comment: string }>;
+ query: Partial<{ cursor: string; item_id: string; task_id: string; scope: string; search: string; source_comment: string }>;
path: { project_id: string };
};
responses: { 200: Schemas.PaginatedCommentList };
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 7ccda6971e06..3760927ab62c 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -209,6 +209,29 @@ export interface TaskSessionStorageAccess {
content_sha256: string | null;
}
+/**
+ * The commentable resources this client knows how to address. `scope` is a
+ * free-form column on the backend `Comment` model, so adding a resource is a
+ * new member here plus a caller — no migration and no endpoint.
+ */
+export type CommentScope = "task_artifact" | "desktop_canvas" | "task";
+
+/** Named `Resource*` so it never collides with the DOM's global `Comment`.
+ * Optimistic rows do not have a server version yet, while item_context is a
+ * real JSON value despite the generated serializer's historically narrow type. */
+export type ResourceComment = Omit<Schemas.Comment, "version"> & {
+ version?: number;
+};
+
+export interface CreateResourceCommentRequest {
+ scope: CommentScope;
+ itemId: string;
+ content: string;
+ context: unknown;
+ sourceCommentId?: string;
+ mentions?: number[];
+}
+
/** Thrown when the backend rejects a cloud run with a 429 usage-limit error. */
export class CloudUsageLimitError extends Error {
limitType: UsageLimitType;
@@ -2708,8 +2731,7 @@ export class PostHogAPIClient {
return (await response.json()) as TaskMention[];
}
- // Tasks the current user is involved in (created, mentioned, or messaged),
- // one row per task, newest activity first.
+ // Task lifecycle and individual comment activity, newest first.
async getTaskActivity(options?: {
before?: string;
beforeId?: string;
@@ -2732,8 +2754,7 @@ export class PostHogAPIClient {
return (await response.json()) as TaskActivityPage;
}
- // Read state is per task, so callers name the tasks the user has seen rather than
- // clearing the whole feed.
+ // Task lifecycle activity clears by task timestamp; comment activity clears by row id.
async markTaskActivityRead(
activities: TaskActivityReadMarker[],
): Promise<TaskActivityMarkReadResult> {
@@ -3227,6 +3248,54 @@ export class PostHogAPIClient {
return data.url;
}
+ async getResourceComments(
+ scope: CommentScope,
+ itemId: string,
+ taskId: string,
+ ): Promise<ResourceComment[]> {
+ const MAX_COMMENT_PAGES = 50;
+ const teamId = await this.getTeamId();
+ const comments: ResourceComment[] = [];
+ let cursor: string | undefined;
+ for (let pageIndex = 0; pageIndex < MAX_COMMENT_PAGES; pageIndex++) {
+ const page = await this.api.get("/api/projects/{project_id}/comments/", {
+ path: { project_id: String(teamId) },
+ query: { scope, item_id: itemId, task_id: taskId, cursor },
+ });
+ comments.push(...page.results);
+ cursor = page.next
+ ? (new URL(page.next).searchParams.get("cursor") ?? undefined)
+ : undefined;
+ if (!cursor) return comments;
+ }
+ log.warn(
+ `getResourceComments hit MAX_PAGES (${MAX_COMMENT_PAGES}); returning partial results`,
+ { scope, itemId, returned: comments.length },
+ );
+ return comments;
+ }
+
+ async createResourceComment(
+ request: CreateResourceCommentRequest,
+ ): Promise<ResourceComment> {
+ const teamId = await this.getTeamId();
+ const payload = {
+ content: request.content,
+ scope: request.scope,
+ item_id: request.itemId,
+ item_context: request.context,
+ source_comment: request.sourceCommentId ?? null,
+ mentions: request.mentions ?? [],
+ // Resolution is represented by a thread-state reply so this stays on the
+ // same PAT-compatible write path as ordinary comments.
+ is_task: false,
+ };
+ return await this.api.post("/api/projects/{project_id}/comments/", {
+ path: { project_id: String(teamId) },
+ body: payload as unknown as Schemas.Comment,
+ });
+ }
+
async getTaskSessionStorageAccess(
taskId: string,
runId: string,
diff --git a/products/desktop/packages/core/src/canvas/taskActivity.test.ts b/products/desktop/packages/core/src/canvas/taskActivity.test.ts
index 09a00c8d3ca0..ebd8f1aa8d4d 100644
--- a/products/desktop/packages/core/src/canvas/taskActivity.test.ts
+++ b/products/desktop/packages/core/src/canvas/taskActivity.test.ts
@@ -40,11 +40,30 @@ describe("toTaskActivityItems", () => {
snippet: "ping @[Me]([email protected])",
author: ann,
messageId: "m1",
+ commentId: null,
+ commentTarget: null,
isUnread: true,
},
]);
});
+ it("maps a comment activity target for exact navigation", () => {
+ const [item] = toTaskActivityItems([
+ activity({
+ latest_message_id: null,
+ latest_comment_id: "comment-1",
+ latest_comment_scope: "task_artifact",
+ latest_comment_item_id: "artifact-1",
+ }),
+ ]);
+
+ expect(item.commentId).toBe("comment-1");
+ expect(item.commentTarget).toEqual({
+ scope: "task_artifact",
+ itemId: "artifact-1",
+ });
+ });
+
it("labels untitled tasks and tolerates missing optional values", () => {
const [item] = toTaskActivityItems([
activity({
diff --git a/products/desktop/packages/core/src/canvas/taskActivity.ts b/products/desktop/packages/core/src/canvas/taskActivity.ts
index 0d4b9ab422e1..d251ef43708d 100644
--- a/products/desktop/packages/core/src/canvas/taskActivity.ts
+++ b/products/desktop/packages/core/src/canvas/taskActivity.ts
@@ -3,12 +3,13 @@ import type {
TaskActivityKind,
UserBasic,
} from "@posthog/shared/domain-types";
+import type { CommentTarget } from "../comments/anchors";
/**
* The Activity feed — tasks the current user is involved in (created, mentioned
* in, or messaged in) — as served by the backend task-activity index
- * (`getTaskActivity`). One row per task, newest activity first; the client only
- * maps DTOs to items.
+ * (`getTaskActivity`). Task state collapses per task, while comment notifications
+ * are individual entries; the client only maps DTOs to items.
*/
export interface TaskActivityItem {
@@ -25,6 +26,8 @@ export interface TaskActivityItem {
snippet: string;
author: UserBasic | null;
messageId: string | null;
+ commentId?: string | null;
+ commentTarget?: CommentTarget | null;
isUnread: boolean;
}
@@ -43,6 +46,14 @@ export function toTaskActivityItems(
snippet: row.snippet,
author: row.latest_author ?? null,
messageId: row.latest_message_id ?? null,
+ commentId: row.latest_comment_id ?? null,
+ commentTarget:
+ row.latest_comment_scope && row.latest_comment_item_id
+ ? {
+ scope: row.latest_comment_scope as CommentTarget["scope"],
+ itemId: row.latest_comment_item_id,
+ }
+ : null,
isUnread: row.is_unread,
}));
}
diff --git a/products/desktop/packages/core/src/comments/anchors.test.ts b/products/desktop/packages/core/src/comments/anchors.test.ts
new file mode 100644
index 000000000000..2da4660705ec
--- /dev/null
+++ b/products/desktop/packages/core/src/comments/anchors.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vitest";
+import {
+ createTextCommentAnchor,
+ isThreadResolved,
+ parseCommentContext,
+ resolveTextCommentAnchor,
+} from "./anchors";
+
+describe("artifact text anchors", () => {
+ it("creates and resolves a verified positional anchor", () => {
+ const text = "Before selected words after";
+ const anchor = createTextCommentAnchor(text, 7, 21);
+
+ if (!anchor) throw new Error("Expected an anchor");
+ expect(resolveTextCommentAnchor(text, anchor)).toEqual({
+ start: 7,
+ end: 21,
+ status: "exact",
+ });
+ });
+
+ it("reanchors a quote after surrounding content changes", () => {
+ const original = "Before selected words after";
+ const anchor = createTextCommentAnchor(original, 7, 21);
+ if (!anchor) throw new Error("Expected an anchor");
+ const changed = `New introduction. ${original}`;
+
+ expect(resolveTextCommentAnchor(changed, anchor)).toEqual({
+ start: 25,
+ end: 39,
+ status: "reanchored",
+ });
+ });
+
+ it("uses context to disambiguate repeated quotes", () => {
+ const original = "first repeated phrase then second repeated phrase end";
+ const start = original.lastIndexOf("repeated phrase");
+ const anchor = createTextCommentAnchor(
+ original,
+ start,
+ start + "repeated phrase".length,
+ );
+ if (!anchor) throw new Error("Expected an anchor");
+ const changed = `prefix ${original}`;
+
+ expect(resolveTextCommentAnchor(changed, anchor)?.start).toBe(
+ changed.lastIndexOf("repeated phrase"),
+ );
+ });
+
+ it("orphans deleted and ambiguous text instead of guessing", () => {
+ const deleted = createTextCommentAnchor("unique text", 0, 6);
+ if (!deleted) throw new Error("Expected an anchor");
+ expect(resolveTextCommentAnchor("replacement", deleted)).toBeNull();
+
+ const ambiguous = {
+ kind: "text" as const,
+ quote: "same",
+ prefix: "",
+ suffix: "",
+ start: 100,
+ end: 104,
+ };
+ expect(resolveTextCommentAnchor("same x same", ambiguous)).toBeNull();
+ });
+
+ it("rejects whitespace-only selections", () => {
+ expect(createTextCommentAnchor("a b", 1, 4)).toBeNull();
+ });
+
+ it("rejects selections larger than the persisted anchor contract", () => {
+ const text = "x".repeat(10_001);
+ expect(createTextCommentAnchor(text, 0, text.length)).toBeNull();
+ });
+
+ it("validates versioned comment context and anchor bounds", () => {
+ expect(
+ parseCommentContext({
+ anchor: { kind: "document" },
+ canvasVersionId: "version-2",
+ }),
+ ).toEqual({
+ anchor: { kind: "document" },
+ canvasVersionId: "version-2",
+ });
+ expect(
+ parseCommentContext({
+ anchor: {
+ kind: "text",
+ quote: "x".repeat(10_001),
+ prefix: "",
+ suffix: "",
+ start: 0,
+ end: 10_001,
+ },
+ }),
+ ).toBeNull();
+ });
+
+ it("uses the latest thread-state event for resolution", () => {
+ const root = { completed_at: null };
+ const event = (state: "resolved" | "open", created_at: string) => ({
+ created_at,
+ item_context: {
+ anchor: { kind: "document" as const },
+ threadState: state,
+ },
+ });
+
+ expect(
+ isThreadResolved(root, [
+ event("resolved", "2026-01-01T00:00:00Z"),
+ event("open", "2026-01-01T00:01:00Z"),
+ ]),
+ ).toBe(false);
+ expect(
+ isThreadResolved(root, [
+ event("open", "2026-01-01T00:00:00Z"),
+ event("resolved", "2026-01-01T00:01:00Z"),
+ ]),
+ ).toBe(true);
+ });
+});
diff --git a/products/desktop/packages/core/src/comments/anchors.ts b/products/desktop/packages/core/src/comments/anchors.ts
new file mode 100644
index 000000000000..ff3458986a00
--- /dev/null
+++ b/products/desktop/packages/core/src/comments/anchors.ts
@@ -0,0 +1,189 @@
+import type { CommentScope } from "@posthog/api-client/posthog-client";
+import { z } from "zod";
+
+const CONTEXT_LENGTH = 32;
+const MAX_QUOTE_LENGTH = 10_000;
+
+/**
+ * Addresses one commentable thing. `itemId` must be the resource's STABLE id
+ * (an artifact id, a canvas row id) — never a name or a version, so comments
+ * survive renames and reverts.
+ */
+export type CommentTarget = {
+ scope: CommentScope;
+ itemId: string;
+};
+
+/** The target as one string, for map keys and cache-key membership tests. */
+export function commentTargetKey(target: CommentTarget): string {
+ return `${target.scope}:${target.itemId}`;
+}
+
+export function isSameCommentTarget(
+ a: CommentTarget | null,
+ b: CommentTarget | null,
+): boolean {
+ return a?.scope === b?.scope && a?.itemId === b?.itemId;
+}
+
+export const textCommentAnchorDataSchema = z.object({
+ quote: z.string().min(1).max(MAX_QUOTE_LENGTH),
+ prefix: z.string().max(CONTEXT_LENGTH),
+ suffix: z.string().max(CONTEXT_LENGTH),
+ start: z.number().int().nonnegative(),
+ end: z.number().int().positive(),
+});
+
+export const textCommentAnchorSchema = textCommentAnchorDataSchema
+ .extend({
+ kind: z.literal("text"),
+ })
+ .refine(({ start, end }) => end > start, {
+ message: "Text anchor end must follow its start",
+ });
+
+export const regionCommentAnchorSchema = z.object({
+ kind: z.literal("region"),
+ x: z.number().min(0).max(1),
+ y: z.number().min(0).max(1),
+ width: z.number().min(0).max(1),
+ height: z.number().min(0).max(1),
+});
+
+const documentCommentAnchorSchema = z.object({
+ kind: z.literal("document"),
+});
+
+export const commentAnchorSchema = z.discriminatedUnion("kind", [
+ textCommentAnchorSchema,
+ regionCommentAnchorSchema,
+ documentCommentAnchorSchema,
+]);
+
+export type TextCommentAnchor = z.infer<typeof textCommentAnchorSchema>;
+export type RegionCommentAnchor = z.infer<typeof regionCommentAnchorSchema>;
+export type CommentAnchor = z.infer<typeof commentAnchorSchema>;
+
+export const commentContextSchema = z.object({
+ anchor: commentAnchorSchema,
+ threadState: z.enum(["resolved", "open"]).optional(),
+ /** Immutable canvas source version rendered when the comment was made. */
+ canvasVersionId: z.string().min(1).optional(),
+ // The task the commented resource belongs to. Artifact and canvas ids live in a run's
+ // JSON rather than a table, so the server can't get back to the task without being told.
+ taskId: z.string().optional(),
+});
+
+export type CommentContext = z.infer<typeof commentContextSchema>;
+
+export function parseCommentContext(value: unknown): CommentContext | null {
+ const parsed = commentContextSchema.safeParse(value);
+ return parsed.success ? parsed.data : null;
+}
+
+export type ThreadStateComment = {
+ created_at: string;
+ item_context?: unknown;
+};
+
+export function isThreadResolved(
+ root: { completed_at?: string | null },
+ replies: ThreadStateComment[],
+): boolean {
+ const latestState = replies
+ .map((comment) => ({
+ createdAt: comment.created_at,
+ state: parseCommentContext(comment.item_context)?.threadState,
+ }))
+ .filter(
+ (
+ entry,
+ ): entry is {
+ createdAt: string;
+ state: "resolved" | "open";
+ } => !!entry.state,
+ )
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
+ .at(-1)?.state;
+ return latestState ? latestState === "resolved" : !!root.completed_at;
+}
+
+export type ResolvedTextAnchor = {
+ start: number;
+ end: number;
+ status: "exact" | "reanchored";
+};
+
+export function createTextCommentAnchor(
+ text: string,
+ start: number,
+ end: number,
+): TextCommentAnchor | null {
+ const safeStart = Math.max(0, Math.min(start, text.length));
+ const safeEnd = Math.max(safeStart, Math.min(end, text.length));
+ const quote = text.slice(safeStart, safeEnd);
+ if (!quote.trim() || quote.length > MAX_QUOTE_LENGTH) return null;
+
+ return {
+ kind: "text",
+ quote,
+ prefix: text.slice(Math.max(0, safeStart - CONTEXT_LENGTH), safeStart),
+ suffix: text.slice(safeEnd, safeEnd + CONTEXT_LENGTH),
+ start: safeStart,
+ end: safeEnd,
+ };
+}
+
+/**
+ * Resolve a persisted text quote without ever guessing. The stored position is
+ * verified first. If content moved, prefix/suffix disambiguate quote matches;
+ * ties are deliberately treated as orphaned.
+ */
+export function resolveTextCommentAnchor(
+ text: string,
+ anchor: TextCommentAnchor,
+): ResolvedTextAnchor | null {
+ if (text.slice(anchor.start, anchor.end) === anchor.quote) {
+ return { start: anchor.start, end: anchor.end, status: "exact" };
+ }
+
+ const candidates: number[] = [];
+ let from = 0;
+ while (from <= text.length - anchor.quote.length) {
+ const match = text.indexOf(anchor.quote, from);
+ if (match < 0) break;
+ candidates.push(match);
+ from = match + Math.max(anchor.quote.length, 1);
+ }
+ if (candidates.length === 0) return null;
+ if (candidates.length === 1) {
+ const start = candidates[0];
+ return {
+ start,
+ end: start + anchor.quote.length,
+ status: "reanchored",
+ };
+ }
+
+ const ranked = candidates
+ .map((start) => {
+ const end = start + anchor.quote.length;
+ const prefix = text.slice(
+ Math.max(0, start - anchor.prefix.length),
+ start,
+ );
+ const suffix = text.slice(end, end + anchor.suffix.length);
+ let score = 0;
+ if (anchor.prefix && prefix === anchor.prefix) score += 2;
+ if (anchor.suffix && suffix === anchor.suffix) score += 2;
+ return { start, score };
+ })
+ .sort((a, b) => b.score - a.score);
+ if (ranked[0].score === 0 || ranked[0].score === ranked[1].score) return null;
+
+ return {
+ start: ranked[0].start,
+ end: ranked[0].start + anchor.quote.length,
+ status: "reanchored",
+ };
+}
diff --git a/products/desktop/packages/core/src/panels/panelStoreHelpers.ts b/products/desktop/packages/core/src/panels/panelStoreHelpers.ts
index 2b41453240bf..aaff4ad4b2ad 100644
--- a/products/desktop/packages/core/src/panels/panelStoreHelpers.ts
+++ b/products/desktop/packages/core/src/panels/panelStoreHelpers.ts
@@ -62,6 +62,35 @@ export function getLeafPanel(
return panel?.type === "leaf" ? panel : null;
}
+/**
+ * The artifact the user is looking at, if any: the focused panel's active tab
+ * when that is an artifact, else any other panel's. Lets a pane elsewhere (the
+ * task's comment list) narrow itself to whatever is on screen.
+ */
+export function activeArtifactId(layout: TaskLayout): string | null {
+ const activeArtifact = (node: PanelNode): string | null => {
+ if (node.type !== "leaf") {
+ for (const child of node.children) {
+ const found = activeArtifact(child);
+ if (found) return found;
+ }
+ return null;
+ }
+ const active = node.content.tabs.find(
+ (tab) => tab.id === node.content.activeTabId,
+ );
+ return active?.data.type === "artifact" ? active.data.artifactId : null;
+ };
+
+ const focused = layout.focusedPanelId
+ ? getLeafPanel(layout.panelTree, layout.focusedPanelId)
+ : null;
+ return (
+ (focused ? activeArtifact(focused) : null) ??
+ activeArtifact(layout.panelTree)
+ );
+}
+
export function getGroupPanel(
tree: PanelNode,
panelId: string,
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index cf59a5d3196e..60cfe3c1bcdc 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -9,6 +9,10 @@ import type {
SessionConfigSelectOption,
SessionUpdate,
} from "@agentclientprotocol/sdk";
+import type {
+ CreateResourceCommentRequest,
+ ResourceComment,
+} from "@posthog/api-client/posthog-client";
import {
type AcpMessage,
type Adapter,
@@ -49,6 +53,7 @@ import {
isTerminalStatus,
type Task,
} from "@posthog/shared/domain-types";
+import type { CommentTarget } from "../comments/anchors";
import type { SpeechKind, SpeechSource } from "../speech/identifiers";
import {
CONTEXT_WINDOW_OPTION_CATEGORY,
@@ -7495,6 +7500,69 @@ export class SessionService {
}
}
+ async getResourceComments(
+ target: CommentTarget,
+ taskId: string,
+ ): Promise<ResourceComment[]> {
+ const authStatus = await this.getAuthCredentialsStatus();
+ if (authStatus.kind !== "ready") return [];
+ return authStatus.auth.client.getResourceComments(
+ target.scope,
+ target.itemId,
+ taskId,
+ );
+ }
+
+ /**
+ * Comments for several resources at once, for surfaces that centralize threads
+ * across a task's artifacts and canvases. Returns one flat list — every row
+ * already carries `scope` and `item_id`, so callers group without bookkeeping.
+ * Fanning out here (rather than in a hook) keeps the multi-source read in a
+ * service and lets the caller hold a single query.
+ */
+ async getResourceCommentsForTargets(
+ targets: CommentTarget[],
+ taskId: string,
+ ): Promise<ResourceComment[]> {
+ const authStatus = await this.getAuthCredentialsStatus();
+ if (authStatus.kind !== "ready" || targets.length === 0) return [];
+ const client = authStatus.auth.client;
+ const pages: ResourceComment[][] = Array.from(
+ { length: targets.length },
+ () => [],
+ );
+ let nextIndex = 0;
+ const worker = async () => {
+ while (nextIndex < targets.length) {
+ const index = nextIndex++;
+ const target = targets[index];
+ try {
+ pages[index] = await client.getResourceComments(
+ target.scope,
+ target.itemId,
+ taskId,
+ );
+ } catch {
+ pages[index] = [];
+ }
+ }
+ };
+ await Promise.all(
+ Array.from({ length: Math.min(4, targets.length) }, worker),
+ );
+ return pages.flat();
+ }
+
+ async createResourceComment(
+ request: CreateResourceCommentRequest,
+ ): Promise<ResourceComment> {
+ const authStatus = await this.getAuthCredentialsStatus();
+ if (authStatus.kind !== "ready") {
+ throw new Error("Sign in to comment");
+ }
+ return authStatus.auth.client.createResourceComment(request);
+ }
+
async getCloudRunArtifacts(
taskId: string,
runId: string,
diff --git a/products/desktop/packages/core/src/sessions/sessionServiceComments.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceComments.test.ts
new file mode 100644
index 000000000000..8f6030342ab5
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/sessionServiceComments.test.ts
@@ -0,0 +1,33 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import { describe, expect, it, vi } from "vitest";
+import { SessionService } from "./sessionService";
+
+describe("SessionService resource comments", () => {
+ it("keeps successful targets when one target fails", async () => {
+ const service = Object.create(SessionService.prototype) as SessionService;
+ const successfulComment = { id: "comment-2" } as ResourceComment;
+ const getResourceComments = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("unavailable"))
+ .mockResolvedValueOnce([successfulComment]);
+ vi.spyOn(
+ service as unknown as {
+ getAuthCredentialsStatus: () => Promise<unknown>;
+ },
+ "getAuthCredentialsStatus",
+ ).mockResolvedValue({
+ kind: "ready",
+ auth: { client: { getResourceComments } },
+ });
+
+ await expect(
+ service.getResourceCommentsForTargets(
+ [
+ { scope: "task_artifact", itemId: "artifact-1" },
+ { scope: "task_artifact", itemId: "artifact-2" },
+ ],
+ "task-1",
+ ),
+ ).resolves.toEqual([successfulComment]);
+ });
+});
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 648357416236..8e5d8c19269e 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -172,6 +172,8 @@ export type TaskActivityKind =
| "completed"
| "message"
| "mention"
+ | "thread_reply"
+ | "owned_item_comment"
| "created";
/**
@@ -190,6 +192,9 @@ export interface TaskActivity {
snippet: string;
latest_author?: UserBasic | null;
latest_message_id?: string | null;
+ latest_comment_id?: string | null;
+ latest_comment_scope?: string | null;
+ latest_comment_item_id?: string | null;
is_unread: boolean;
}
@@ -204,6 +209,7 @@ export interface TaskActivityPage {
export interface TaskActivityReadMarker {
task_id: string;
seen_before: string;
+ activity_id?: string;
}
export interface TaskActivityMarkReadResult {
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 5d9e374fb64a..0cb88be68621 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -49,3 +49,5 @@ export const STAGED_UPDATES_FLAG = "posthog-desktop-staged-updates";
* surfaces (see docs/ANNOUNCEMENTS.md).
*/
export const ANNOUNCEMENTS_FLAG = "posthog-desktop-announcements";
+/** Gates anchored comments across task, artifact, and Activity surfaces. */
+export const COMMENTS_FLAG = "posthog-code-comments";
diff --git a/products/desktop/packages/shared/src/git-domain.ts b/products/desktop/packages/shared/src/git-domain.ts
index 24cb09add12a..934652b4aed9 100644
--- a/products/desktop/packages/shared/src/git-domain.ts
+++ b/products/desktop/packages/shared/src/git-domain.ts
@@ -5,6 +5,7 @@ import { z } from "zod";
export const prReviewCommentUserSchema = z.object({
login: z.string(),
avatar_url: z.string(),
+ isBot: z.boolean().optional(),
});
export const prReviewCommentSchema = z.object({
@@ -156,6 +157,7 @@ export type GetPrChecksOutput = z.infer<typeof getPrChecksOutput>;
export const prConversationCommentSchema = z.object({
id: z.number(),
author: z.string(),
+ isBot: z.boolean().optional(),
avatarUrl: z.string().nullable(),
body: z.string(),
createdAt: z.string(),
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.test.tsx
index 65eeaaf72bc0..b5cf8abe1f28 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.test.tsx
@@ -1,4 +1,5 @@
-import { render, waitFor } from "@testing-library/react";
+import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -6,6 +7,9 @@ const mocks = vi.hoisted(() => ({
fetchNextPage: vi.fn(),
hasNextPage: true,
isFetchingNextPage: false,
+ items: [] as TaskActivityItem[],
+ markRead: vi.fn(),
+ commentsEnabled: true,
}));
vi.mock("@posthog/quill", () => ({
@@ -31,17 +35,30 @@ vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
useCurrentUser: () => ({ data: null }),
}));
vi.mock("@posthog/ui/features/canvas/components/ActivityView", () => ({
- ActivityRow: () => <div>Activity row</div>,
+ ActivityRow: ({
+ item,
+ onOpen,
+ }: {
+ item: TaskActivityItem;
+ onOpen: (item: TaskActivityItem) => void;
+ }) => (
+ <button type="button" onClick={() => onOpen(item)}>
+ Activity row
+ </button>
+ ),
}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
useChannels: () => ({ channels: [] }),
}));
vi.mock("@posthog/ui/features/canvas/hooks/useMarkTaskActivityRead", () => ({
- useMarkTaskActivityRead: () => ({ mutate: vi.fn(), isPending: false }),
+ useMarkTaskActivityRead: () => ({
+ mutate: mocks.markRead,
+ isPending: false,
+ }),
}));
vi.mock("@posthog/ui/features/canvas/hooks/useTaskActivity", () => ({
useTaskActivity: () => ({
- items: [],
+ items: mocks.items,
unreadCount: 0,
isLoading: false,
hasNextPage: mocks.hasNextPage,
@@ -49,6 +66,9 @@ vi.mock("@posthog/ui/features/canvas/hooks/useTaskActivity", () => ({
fetchNextPage: mocks.fetchNextPage,
}),
}));
+vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
+ useCommentsEnabled: () => mocks.commentsEnabled,
+}));
vi.mock("@posthog/ui/primitives/hooks/useInView", () => ({
useInView: () => [vi.fn(), true],
}));
@@ -61,6 +81,8 @@ describe("ActivityHoverCard", () => {
vi.clearAllMocks();
mocks.hasNextPage = true;
mocks.isFetchingNextPage = false;
+ mocks.items = [];
+ mocks.commentsEnabled = true;
});
it("loads the next page when the bottom sentinel is visible", async () => {
@@ -75,4 +97,53 @@ describe("ActivityHoverCard", () => {
await waitFor(() => expect(mocks.fetchNextPage).not.toHaveBeenCalled());
});
+
+ it("marks the exact comment activity as read", () => {
+ mocks.items = [
+ {
+ id: "activity-1",
+ taskId: "task-1",
+ activityAt: "2026-08-07T00:00:00Z",
+ activityKind: "owned_item_comment",
+ commentId: "comment-1",
+ isUnread: true,
+ } as TaskActivityItem,
+ ];
+
+ render(<ActivityHoverCard onClose={vi.fn()} />);
+ fireEvent.click(screen.getByText("Activity row"));
+
+ expect(mocks.markRead).toHaveBeenCalledWith([
+ {
+ task_id: "task-1",
+ seen_before: "2026-08-07T00:00:00Z",
+ activity_id: "activity-1",
+ },
+ ]);
+ });
+
+ it("hides only comment-derived activity while comments are disabled", () => {
+ mocks.commentsEnabled = false;
+ mocks.items = [
+ {
+ id: "comment-activity",
+ taskId: "task-1",
+ activityAt: "2026-08-07T00:00:00Z",
+ activityKind: "mention",
+ commentId: "comment-1",
+ isUnread: true,
+ } as TaskActivityItem,
+ {
+ id: "task-activity",
+ taskId: "task-2",
+ activityAt: "2026-08-07T00:01:00Z",
+ activityKind: "mention",
+ isUnread: true,
+ } as TaskActivityItem,
+ ];
+
+ render(<ActivityHoverCard onClose={vi.fn()} />);
+
+ expect(screen.getAllByText("Activity row")).toHaveLength(1);
+ });
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.tsx
index 82097a9e9723..cbc0e08a7076 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityHoverCard.tsx
@@ -15,12 +15,14 @@ import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
import { ActivityRow } from "@posthog/ui/features/canvas/components/ActivityView";
import { useMarkTaskActivityRead } from "@posthog/ui/features/canvas/hooks/useMarkTaskActivityRead";
import { useTaskActivity } from "@posthog/ui/features/canvas/hooks/useTaskActivity";
+import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import { useInView } from "@posthog/ui/primitives/hooks/useInView";
import { track } from "@posthog/ui/shell/analytics";
import { useEffect, useState } from "react";
import {
activityReadPayload,
getUnreadActivityItems,
+ getVisibleActivityItems,
markLoadedReadLabel,
} from "./activityFeed";
@@ -33,6 +35,7 @@ export function ActivityHoverCard({
onClose,
side = "right",
}: ActivityHoverCardProps) {
+ const commentsEnabled = useCommentsEnabled();
const client = useOptionalAuthenticatedClient();
const { data: currentUser } = useCurrentUser({ client });
const {
@@ -48,7 +51,8 @@ export function ActivityHoverCard({
root: scrollRoot,
rootMargin: "100px 0px",
});
- const unreadItems = getUnreadActivityItems(items);
+ const visibleItems = getVisibleActivityItems(items, commentsEnabled);
+ const unreadItems = getUnreadActivityItems(visibleItems);
const { mutate: markTasksRead, isPending: isMarkingRead } =
useMarkTaskActivityRead();
useEffect(() => {
@@ -63,8 +67,8 @@ export function ActivityHoverCard({
}
}, [fetchNextPage, hasNextPage, loadMoreInView]);
- const markRead = (taskId: string, activityAt: string) => {
- markTasksRead([{ task_id: taskId, seen_before: activityAt }]);
+ const markRead = (item: (typeof items)[number]) => {
+ markTasksRead(activityReadPayload([item]));
};
const markAllRead = () => {
@@ -94,11 +98,11 @@ export function ActivityHoverCard({
)}
</div>
<div ref={setScrollRoot} className="max-h-[480px] overflow-y-auto p-1.5">
- {isLoading && items.length === 0 ? (
+ {isLoading && visibleItems.length === 0 ? (
<div className="flex justify-center py-10">
<Spinner />
</div>
- ) : items.length === 0 ? (
+ ) : visibleItems.length === 0 ? (
<Empty className="border-0 py-8">
<EmptyHeader>
<EmptyMedia variant="icon">
@@ -112,17 +116,13 @@ export function ActivityHoverCard({
</Empty>
) : (
<div className="flex flex-col gap-0.5">
- {items.map((item) => (
+ {visibleItems.map((item) => (
<ActivityRow
- key={item.taskId}
+ key={item.id}
item={item}
channelId={item.channelId}
- onOpen={(activity) =>
- markRead(activity.taskId, activity.activityAt)
- }
- onMarkRead={(activity) =>
- markRead(activity.taskId, activity.activityAt)
- }
+ onOpen={markRead}
+ onMarkRead={markRead}
currentUser={currentUser}
surface="activity_panel"
onNavigate={onClose}
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
new file mode 100644
index 000000000000..8bf831212a4b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx
@@ -0,0 +1,208 @@
+import type { Task } from "@posthog/shared/domain-types";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type MockInstance,
+ vi,
+} from "vitest";
+
+vi.mock("@posthog/ui/features/canvas/hooks/useThreadConversation", () => ({
+ useThreadConversation: () => ({
+ timeline: [],
+ agentStatus: null,
+ events: [],
+ isPromptPending: false,
+ isReady: true,
+ members: [],
+ currentUser: null,
+ isTaskAuthor: true,
+ canForward: true,
+ draft: "",
+ setDraft: vi.fn(),
+ isSubmitDisabled: false,
+ submit: vi.fn(),
+ sendMessageToAgent: vi.fn(),
+ deleteMessage: vi.fn(),
+ onMentionInsert: vi.fn(),
+ }),
+}));
+vi.mock("@posthog/ui/features/canvas/components/ActivityTimeline", () => ({
+ ActivityTimeline: () => <div>timeline body</div>,
+}));
+vi.mock("@posthog/ui/features/canvas/components/TaskArtifactsList", () => ({
+ TaskArtifactsList: () => <div>artifacts body</div>,
+}));
+vi.mock("@posthog/ui/features/canvas/components/TaskCommentsList", () => ({
+ TaskCommentsList: () => <div>comments body</div>,
+}));
+vi.mock("@posthog/ui/features/canvas/components/ChannelFeedView", () => ({
+ TaskCard: () => <div>task card</div>,
+}));
+vi.mock("@posthog/ui/features/canvas/components/ThreadPanel", () => ({
+ AgentStatusLine: () => <div>agent status</div>,
+ ThreadLoadingState: () => <div>loading</div>,
+ ThreadReplyComposer: () => <div>composer</div>,
+}));
+vi.mock("@posthog/ui/features/tasks/queries", () => ({
+ taskDetailQuery: () => ({ queryKey: ["task"], queryFn: vi.fn() }),
+}));
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: () => ({ data: undefined }),
+}));
+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));
+
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { ActivityPanel } from "./ActivityPanel";
+
+const commentsFlag = vi.hoisted(() => ({ enabled: true }));
+
+vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
+ useCommentsEnabled: () => commentsFlag.enabled,
+}));
+
+const task = { id: "task-1", title: "Ship it" } as unknown as Task;
+
+function renderPanel(taskId = "task-1") {
+ return render(
+ <ActivityPanel
+ taskId={taskId}
+ channelId="channel-1"
+ task={{ ...task, id: taskId }}
+ showTaskSummary={false}
+ />,
+ );
+}
+
+describe("ActivityPanel", () => {
+ let scrollTo: MockInstance;
+
+ beforeEach(() => {
+ commentsFlag.enabled = true;
+ scrollTo = vi.spyOn(Element.prototype, "scrollTo");
+ useCommentNavigationStore.setState({
+ focusByTask: {},
+ resolutionsByTarget: {},
+ });
+ });
+
+ afterEach(() => {
+ scrollTo.mockRestore();
+ });
+
+ it("offers comments as a third tab beside the timeline and artifacts", () => {
+ renderPanel();
+
+ expect(screen.getByRole("tab", { name: "Timeline" })).toBeTruthy();
+ expect(screen.getByRole("tab", { name: "Artifacts" })).toBeTruthy();
+ fireEvent.click(screen.getByRole("tab", { name: "Comments" }));
+
+ expect(screen.getByText("comments body")).toBeTruthy();
+ // The composer belongs to the conversation, not to a list of threads.
+ expect(screen.queryByText("composer")).toBeNull();
+ });
+
+ it("hides the comments tab while comments are disabled", () => {
+ commentsFlag.enabled = false;
+ renderPanel();
+
+ expect(screen.queryByRole("tab", { name: "Comments" })).toBeNull();
+ });
+
+ // A thread picked on the artifact itself lands in this tab, so the pick has
+ // to bring the tab with it.
+ it("switches to comments when a thread is picked elsewhere", () => {
+ renderPanel();
+ expect(screen.getByText("timeline body")).toBeTruthy();
+
+ act(() =>
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "task_artifact", itemId: "artifact-1" },
+ "comment-1",
+ ),
+ );
+
+ expect(screen.getByText("comments body")).toBeTruthy();
+ });
+
+ it("leaves a focus request for another task alone", () => {
+ renderPanel();
+
+ act(() =>
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-2",
+ { scope: "task_artifact", itemId: "artifact-1" },
+ "comment-1",
+ ),
+ );
+
+ expect(screen.getByText("timeline body")).toBeTruthy();
+ });
+
+ // A focus left over from an earlier visit must not hijack the panel, and the
+ // panel is reused across tasks without remounting.
+ it("does not open comments for a focus that predates the task", () => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-2",
+ { scope: "task_artifact", itemId: "artifact-1" },
+ "comment-1",
+ );
+ const { rerender } = renderPanel("task-1");
+
+ rerender(
+ <ActivityPanel
+ taskId="task-2"
+ channelId="channel-1"
+ task={{ ...task, id: "task-2" }}
+ showTaskSummary={false}
+ />,
+ );
+
+ expect(screen.getByText("timeline body")).toBeTruthy();
+ });
+
+ it("keeps a fresh focus request when the panel switches tasks", () => {
+ const { rerender } = renderPanel("task-1");
+ act(() =>
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-2",
+ { scope: "task_artifact", itemId: "artifact-1" },
+ "comment-1",
+ ),
+ );
+
+ rerender(
+ <ActivityPanel
+ taskId="task-2"
+ channelId="channel-1"
+ task={{ ...task, id: "task-2" }}
+ showTaskSummary={false}
+ />,
+ );
+
+ expect(screen.getByText("comments body")).toBeTruthy();
+ });
+
+ // Only the timeline reads bottom-up; the thread lists put what matters on top.
+ it("keeps the comments list where it was scrolled to", () => {
+ renderPanel();
+ expect(scrollTo).toHaveBeenCalled();
+ const timelineScrolls = scrollTo.mock.calls.length;
+
+ fireEvent.click(screen.getByRole("tab", { name: "Comments" }));
+
+ expect(scrollTo.mock.calls.length).toBe(timelineScrolls);
+ });
+});
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 c59a26979b89..e01e25fdf4bf 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
@@ -9,23 +9,27 @@ import type { Task } from "@posthog/shared/domain-types";
import { ActivityTimeline } from "@posthog/ui/features/canvas/components/ActivityTimeline";
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 { 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 { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
import { track } from "@posthog/ui/shell/analytics";
import { useQuery } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-type ActivityTab = "timeline" | "artifacts";
+type ActivityTab = "timeline" | "artifacts" | "comments";
const ACTIVITY_TABS: readonly { key: ActivityTab; label: string }[] = [
{ key: "timeline", label: "Timeline" },
{ key: "artifacts", label: "Artifacts" },
+ { key: "comments", label: "Comments" },
] as const;
/** The 32px row this panel leads with: the tabs are the header, so the strip
@@ -33,12 +37,14 @@ const ACTIVITY_TABS: readonly { key: ActivityTab; label: string }[] = [
* review toolbar, which are the same fixed height and border. */
function ActivityHeader({
tab,
+ commentsEnabled,
onTabChange,
onClose,
onToggleCollapsed,
onOpenFull,
}: {
tab: ActivityTab;
+ commentsEnabled: boolean;
onTabChange: (tab: ActivityTab) => void;
onClose?: () => void;
onToggleCollapsed?: () => void;
@@ -59,7 +65,9 @@ function ActivityHeader({
aria-label="Activity"
className="h-[31px] gap-0.5 p-0"
>
- {ACTIVITY_TABS.map((t) => (
+ {ACTIVITY_TABS.filter(
+ (candidate) => commentsEnabled || candidate.key !== "comments",
+ ).map((t) => (
<TabsTrigger key={t.key} value={t.key} className="px-2.5">
<span className="font-medium text-[13px]">{t.label}</span>
</TabsTrigger>
@@ -120,6 +128,7 @@ function ActivityConversation({
canOpenInPlace?: boolean;
}) {
const taskId = task.id;
+ const commentsEnabled = useCommentsEnabled();
const {
timeline,
agentStatus,
@@ -161,15 +170,58 @@ function ActivityConversation({
[tab, events, isPromptPending],
);
+ // A thread picked on the artifact itself lives in the Comments tab, so the
+ // pick has to bring the tab with it. Only a fresh request switches tabs: a
+ // focus left over from an earlier visit must not hijack the panel on mount.
+ const focusByTask = useCommentNavigationStore((state) => state.focusByTask);
+ const commentFocus = focusByTask[taskId];
+ 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.
+ const seenFocus = useRef(
+ new Map(
+ Object.entries(focusByTask).map(([focusTaskId, focus]) => [
+ focusTaskId,
+ focus?.nonce ?? null,
+ ]),
+ ),
+ );
+ useEffect(() => {
+ if (
+ commentsEnabled &&
+ commentFocus?.openCommentsTab &&
+ commentFocus.nonce !== seenFocus.current.get(taskId)
+ ) {
+ seenFocus.current.set(taskId, commentFocus.nonce);
+ // Not handleTabChange: a programmatic switch isn't a user tab change.
+ setTab("comments");
+ }
+ }, [commentFocus, commentsEnabled, taskId]);
+ useEffect(() => {
+ if (!commentsEnabled && tab === "comments") setTab("timeline");
+ }, [commentsEnabled, tab]);
+ useEffect(() => {
+ if (tab === "comments" && commentFocus?.openCommentsTab) {
+ acknowledgeCommentsTabOpen(taskId, commentFocus.nonce);
+ }
+ }, [acknowledgeCommentsTabOpen, commentFocus, tab, taskId]);
+
const scrollRef = useRef<HTMLDivElement>(null);
// biome-ignore lint/correctness/useExhaustiveDependencies: scroll when rendered thread content changes
useEffect(() => {
+ // 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 });
}, [timeline, events.length, agentStatus?.phase, tab]);
const showComposer = tab === "timeline";
const body = () => {
+ if (tab === "comments") {
+ return <TaskCommentsList task={task} timeline={timeline} />;
+ }
if (tab === "artifacts") {
return (
<TaskArtifactsList
@@ -200,6 +252,7 @@ function ActivityConversation({
<div className="flex h-full min-w-0 flex-col bg-gray-1">
<ActivityHeader
tab={tab}
+ commentsEnabled={commentsEnabled}
onTabChange={handleTabChange}
onOpenFull={onOpenFull}
onToggleCollapsed={onToggleCollapsed}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx
index d2418bc6de3b..5543a1a699c4 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx
@@ -1,7 +1,27 @@
import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";
-import { render } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-import { activityHeadline } from "./ActivityView";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const navigation = vi.hoisted(() => ({
+ toChannelDashboard: vi.fn(),
+ toChannelTask: vi.fn(),
+ toTaskDetail: vi.fn(),
+}));
+const commentsFlag = vi.hoisted(() => ({ enabled: true }));
+
+vi.mock("@posthog/ui/router/navigationBridge", () => ({
+ navigateToChannelDashboard: navigation.toChannelDashboard,
+ navigateToChannelTask: navigation.toChannelTask,
+ navigateToTaskDetail: navigation.toTaskDetail,
+}));
+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));
+
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { ActivityRow, activityHeadline } from "./ActivityView";
+
+vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
+ useCommentsEnabled: () => commentsFlag.enabled,
+}));
function item(overrides: Partial<TaskActivityItem>): TaskActivityItem {
return {
@@ -21,6 +41,16 @@ function item(overrides: Partial<TaskActivityItem>): TaskActivityItem {
}
describe("activityHeadline", () => {
+ beforeEach(() => {
+ commentsFlag.enabled = true;
+ navigation.toChannelTask.mockReset();
+ navigation.toChannelDashboard.mockReset();
+ navigation.toTaskDetail.mockReset();
+ useCommentNavigationStore.setState({
+ focusByTask: {},
+ resolutionsByTarget: {},
+ });
+ });
it.each([
[
"completed run",
@@ -28,6 +58,33 @@ describe("activityHeadline", () => {
"The agent completed this task",
],
["agent reply", item({ activityKind: "message" }), "The agent replied"],
+ [
+ "thread reply",
+ item({
+ activityKind: "thread_reply",
+ author: {
+ id: 2,
+ uuid: "author",
+ email: "[email protected]",
+ first_name: "Ann",
+ },
+ }),
+ "replied to a thread you participated in",
+ ],
+ [
+ "canvas owner comment",
+ item({
+ activityKind: "owned_item_comment",
+ commentTarget: { scope: "desktop_canvas", itemId: "canvas-1" },
+ author: {
+ id: 2,
+ uuid: "author",
+ email: "[email protected]",
+ first_name: "Ann",
+ },
+ }),
+ "commented on your canvas",
+ ],
[
"own reply",
item({
@@ -59,4 +116,74 @@ describe("activityHeadline", () => {
);
expect(getByText("#me")).toBeInTheDocument();
});
+
+ it("opens an activity mention at its exact comment thread", () => {
+ const activity = item({
+ activityKind: "mention",
+ channelId: "channel-1",
+ commentId: "comment-1",
+ commentTarget: { scope: "desktop_canvas", itemId: "canvas-1" },
+ author: {
+ id: 2,
+ uuid: "author",
+ email: "[email protected]",
+ first_name: "Ann",
+ },
+ });
+
+ render(
+ <ActivityRow
+ item={activity}
+ channelId="channel-1"
+ onOpen={vi.fn()}
+ onMarkRead={vi.fn()}
+ />,
+ );
+ const activityButton = screen.getByText("mentioned you").closest("button");
+ if (!activityButton) throw new Error("Expected activity row button");
+ fireEvent.click(activityButton);
+
+ expect(navigation.toChannelDashboard).toHaveBeenCalledWith(
+ "channel-1",
+ "canvas-1",
+ );
+ expect(navigation.toChannelTask).not.toHaveBeenCalled();
+ expect(useCommentNavigationStore.getState().focusByTask["task-1"]).toEqual({
+ target: { scope: "desktop_canvas", itemId: "canvas-1" },
+ threadId: "comment-1",
+ nonce: expect.any(Number),
+ openCommentsTab: true,
+ });
+ });
+
+ it("does not open comment navigation while comments are disabled", () => {
+ commentsFlag.enabled = false;
+ const activity = item({
+ activityKind: "owned_item_comment",
+ channelId: "channel-1",
+ commentId: "comment-1",
+ commentTarget: { scope: "desktop_canvas", itemId: "canvas-1" },
+ });
+
+ render(
+ <ActivityRow
+ item={activity}
+ channelId="channel-1"
+ onOpen={vi.fn()}
+ onMarkRead={vi.fn()}
+ />,
+ );
+ const activityButton = screen
+ .getByText("commented on your canvas")
+ .closest("button");
+ if (!activityButton) throw new Error("Expected activity row button");
+ fireEvent.click(activityButton);
+
+ expect(navigation.toChannelTask).toHaveBeenCalledWith(
+ "channel-1",
+ "task-1",
+ );
+ expect(navigation.toChannelDashboard).not.toHaveBeenCalled();
+ expect(useCommentNavigationStore.getState().focusByTask).toEqual({});
+ });
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx
index cd22d7c9364d..50df665cd4d8 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx
@@ -28,8 +28,12 @@ import { MentionText } from "@posthog/ui/features/canvas/components/MentionText"
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { useMarkTaskActivityRead } from "@posthog/ui/features/canvas/hooks/useMarkTaskActivityRead";
import { useTaskActivity } from "@posthog/ui/features/canvas/hooks/useTaskActivity";
+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
+import { useThreadPanelStore } from "@posthog/ui/features/canvas/stores/threadPanelStore";
import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLink";
import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import {
PageHeader,
PageHeaderActions,
@@ -40,6 +44,7 @@ import {
PageHeaderTitleRow,
} from "@posthog/ui/primitives/PageHeader";
import {
+ navigateToChannelDashboard,
navigateToChannelTask,
navigateToTaskDetail,
} from "@posthog/ui/router/navigationBridge";
@@ -49,7 +54,9 @@ import type { ReactNode } from "react";
import { useCallback, useEffect, useMemo } from "react";
import {
activityReadPayload,
+ activityUnreadTotalForLabel,
getUnreadActivityItems,
+ getVisibleActivityItems,
markLoadedReadLabel,
} from "./activityFeed";
@@ -65,6 +72,17 @@ function ChannelSuffix({ channelName }: { channelName: string | null }) {
);
}
+function ownedItemName(item: TaskActivityItem): string {
+ switch (item.commentTarget?.scope) {
+ case "desktop_canvas":
+ return "canvas";
+ case "task_artifact":
+ return "artifact";
+ default:
+ return "task";
+ }
+}
+
/** The lead line describing what happened, chosen by the row's activity kind. */
export function activityHeadline(
item: TaskActivityItem,
@@ -112,6 +130,26 @@ export function activityHeadline(
<ChannelSuffix channelName={item.channelName} />
</>
);
+ case "thread_reply":
+ return (
+ <>
+ <Text as="span" size="1" weight="medium">
+ {userDisplayName(item.author)}
+ </Text>{" "}
+ replied to a thread you participated in
+ <ChannelSuffix channelName={item.channelName} />
+ </>
+ );
+ case "owned_item_comment":
+ return (
+ <>
+ <Text as="span" size="1" weight="medium">
+ {userDisplayName(item.author)}
+ </Text>{" "}
+ commented on your {ownedItemName(item)}
+ <ChannelSuffix channelName={item.channelName} />
+ </>
+ );
default:
return "You created this task";
}
@@ -137,6 +175,7 @@ export function ActivityRow({
onNavigate?: () => void;
compact?: boolean;
}) {
+ const commentsEnabled = useCommentsEnabled();
const isAgentActivity =
item.activityKind === "awaiting_input" ||
item.activityKind === "completed" ||
@@ -149,10 +188,27 @@ export function ActivityRow({
task_id: item.taskId,
});
onOpen(item);
+ if (commentsEnabled && item.commentId && item.commentTarget) {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(item.taskId, item.commentTarget, item.commentId);
+ }
onNavigate?.();
+ if (
+ commentsEnabled &&
+ channelId &&
+ item.commentTarget?.scope === "desktop_canvas"
+ ) {
+ useCanvasChatPanelStore.getState().openComments();
+ navigateToChannelDashboard(channelId, item.commentTarget.itemId);
+ return;
+ }
// The channel thread route is the deep-link target; unfiled tasks fall
// back to the plain task view.
if (channelId) {
+ if (item.commentId) {
+ useThreadPanelStore.getState().setCollapsed(false);
+ }
navigateToChannelTask(channelId, item.taskId);
} else {
navigateToTaskDetail(item.taskId);
@@ -252,6 +308,7 @@ export function ActivityRow({
// in, or messaged in — newest activity first. Rows clear as they are opened, not
// when the page is; merely landing here shouldn't dismiss what you haven't read.
export function ActivityView() {
+ const commentsEnabled = useCommentsEnabled();
const spacesLayout = useChannelsLayout();
const client = useOptionalAuthenticatedClient();
const { data: currentUser } = useCurrentUser({ client });
@@ -265,12 +322,31 @@ export function ActivityView() {
} = useTaskActivity();
const { mutate: markTasksRead, isPending: isMarkingRead } =
useMarkTaskActivityRead();
- const unreadItems = useMemo(() => getUnreadActivityItems(items), [items]);
+ const visibleItems = useMemo(
+ () => getVisibleActivityItems(items, commentsEnabled),
+ [commentsEnabled, items],
+ );
+ const unreadItems = useMemo(
+ () => getUnreadActivityItems(visibleItems),
+ [visibleItems],
+ );
+ const visibleUnreadCount = activityUnreadTotalForLabel({
+ commentsEnabled,
+ unreadCount,
+ loadedVisibleUnread: unreadItems.length,
+ hasNextPage,
+ });
// Opening a row is what marks it read. The server does the same when the task is
// reached any other way, so the feed converges either way.
const markRead = useCallback(
(item: TaskActivityItem) =>
- markTasksRead([{ task_id: item.taskId, seen_before: item.activityAt }]),
+ markTasksRead([
+ {
+ task_id: item.taskId,
+ seen_before: item.activityAt,
+ ...(item.commentId ? { activity_id: item.id } : {}),
+ },
+ ]),
[markTasksRead],
);
const markAllRead = useCallback(() => {
@@ -292,18 +368,18 @@ export function ActivityView() {
onClick={markAllRead}
>
<ChecksIcon size={14} />
- {markLoadedReadLabel(unreadItems.length, unreadCount)}
+ {markLoadedReadLabel(unreadItems.length, visibleUnreadCount)}
</Button>
);
// The feed body is identical in both shells; only the empty-state copy tracks
// the layout's naming ("spaces" vs "channels").
const feed =
- isLoading && items.length === 0 ? (
+ isLoading && visibleItems.length === 0 ? (
<div className="flex justify-center py-16">
<Spinner />
</div>
- ) : items.length === 0 ? (
+ ) : visibleItems.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
@@ -311,16 +387,16 @@ export function ActivityView() {
</EmptyMedia>
<EmptyTitle>No activity yet</EmptyTitle>
<EmptyDescription>
- Tasks you create, get tagged in, or reply to across{" "}
- {spacesLayout ? "spaces" : "channels"} land here.
+ Task updates and comment notifications across{" "}
+ {spacesLayout ? "spaces" : "channels"} appear here.
</EmptyDescription>
</EmptyHeader>
</Empty>
) : (
<div className="flex flex-col gap-0.5">
- {items.map((item) => (
+ {visibleItems.map((item) => (
<ActivityRow
- key={item.taskId}
+ key={item.id}
item={item}
channelId={item.channelId}
onOpen={markRead}
@@ -359,7 +435,7 @@ export function ActivityView() {
)}
</PageHeaderTitleRow>
<PageHeaderDescription>
- Tasks you're involved in across spaces.
+ Task updates and comment notifications across spaces.
</PageHeaderDescription>
</PageHeaderHeading>
</PageHeader>
@@ -379,7 +455,7 @@ export function ActivityView() {
Activity
</Text>
<Text size="2" className="block text-muted-foreground">
- Tasks you're involved in across{" "}
+ Task updates and comment notifications across{" "}
{spacesLayout ? "spaces" : "channels"}.
</Text>
</div>
diff --git a/products/desktop/packages/ui/src/features/canvas/components/MentionComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/MentionComposer.tsx
index df0826b9945c..71b1b95dfdf6 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/MentionComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/MentionComposer.tsx
@@ -29,6 +29,8 @@ interface MentionComposerProps {
placeholder?: string;
rows?: number;
inputClassName?: string;
+ /** Put the caret in the editor on mount, for a composer the user just opened. */
+ autoFocus?: boolean;
/** Rendered inside the input group after the editor (send button etc.). */
children?: ReactNode;
}
@@ -57,6 +59,7 @@ export function MentionComposer({
onValueChange,
onSubmit,
members,
+ autoFocus = false,
allowAgentMention = false,
onMentionInsert,
placeholder,
@@ -99,6 +102,7 @@ export function MentionComposer({
const editor = useEditor(
{
+ autofocus: autoFocus ? "end" : false,
extensions: [
StarterKit.configure({
heading: false,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
index a553cb8db456..e1e4c4151e0c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
@@ -1,5 +1,11 @@
import type { Task, TaskRun, TaskRunArtifact } from "@posthog/shared";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
@@ -7,6 +13,11 @@ const mocks = vi.hoisted(() => ({
openArtifactTab: vi.fn(),
openExternalUrl: vi.fn(),
getCloudAttachmentPreviewUrl: vi.fn(),
+ commentsError: false,
+}));
+
+vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
+ useCommentsEnabled: () => true,
}));
vi.mock("@posthog/core/sessions/sessionService", () => ({
@@ -43,6 +54,37 @@ vi.mock("@posthog/ui/features/pr-review/usePrComments", () => ({
vi.mock("@posthog/ui/features/pr-review/usePrReviewThreads", () => ({
usePrReviewThreads: () => ({ data: undefined }),
}));
+vi.mock("@posthog/ui/features/sessions/components/useComments", () => ({
+ useCommentsForTargetsQuery: () => ({
+ isError: mocks.commentsError,
+ data: [
+ {
+ id: "comment-1",
+ source_comment: null,
+ item_id: "a",
+ content: "Tighten this summary",
+ created_at: "2024-01-01T00:00:00Z",
+ item_context: { anchor: { kind: "document" } },
+ },
+ {
+ id: "reply-1",
+ source_comment: "comment-1",
+ item_id: "a",
+ content: "Agreed",
+ created_at: "2024-01-01T00:01:00Z",
+ item_context: { anchor: { kind: "document" } },
+ },
+ {
+ id: "comment-2",
+ source_comment: null,
+ item_id: "a",
+ content: "Second thread",
+ created_at: "2024-01-01T00:02:00Z",
+ item_context: { anchor: { kind: "document" } },
+ },
+ ],
+ }),
+}));
import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";
import { TaskArtifactsList } from "./TaskArtifactsList";
@@ -78,6 +120,7 @@ function outputFile(
describe("TaskArtifactsList", () => {
beforeEach(() => {
+ mocks.commentsError = false;
mocks.runs = [run("run-1", { prNumber: 1 }), run("run-2", { prNumber: 2 })];
mocks.openArtifactTab.mockReset();
mocks.openExternalUrl.mockReset();
@@ -134,15 +177,41 @@ describe("TaskArtifactsList", () => {
expect(screen.getByText("Pull request #2")).toBeTruthy();
});
- it("lists the files the agent uploaded, with their size", () => {
+ it("lists uploaded files with their comment count", () => {
+ mocks.runs = [
+ run("run-1", { artifacts: [outputFile({ id: "a", size: 16861 })] }),
+ ];
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ const row = screen.getByText("report.md").closest("button");
+ expect(row).not.toBeNull();
+ expect(within(row as HTMLElement).getByText("2")).toBeTruthy();
+ expect(within(row as HTMLElement).getByText("File · 17 KB")).toBeTruthy();
+ });
+
+ it("keeps artifacts visible when comment counts fail", () => {
+ mocks.commentsError = true;
+ mocks.runs = [
+ run("run-1", { artifacts: [outputFile({ id: "a", size: 16861 })] }),
+ ];
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("report.md")).toBeInTheDocument();
+ expect(screen.getByText("File · 17 KB")).toBeInTheDocument();
+ });
+
+ // The threads themselves live in the Comments tab now, so the pane must not
+ // grow a second list of them.
+ it("leaves the thread list to the Comments tab", () => {
mocks.runs = [
run("run-1", { artifacts: [outputFile({ id: "a", size: 16861 })] }),
];
render(<TaskArtifactsList task={task} timeline={[]} />);
- expect(screen.getByText("report.md")).toBeTruthy();
- expect(screen.getByText("File · 17 KB")).toBeTruthy();
+ expect(screen.queryByText("Tighten this summary")).toBeNull();
});
// The row should read like the chat's file list: markdown looks like
@@ -255,7 +324,7 @@ describe("TaskArtifactsList", () => {
render(<TaskArtifactsList task={task} timeline={[]} />);
expect(screen.getAllByText("report.md")).toHaveLength(1);
- expect(screen.getByText("File · 2 KB")).toBeTruthy();
+ expect(screen.getByText("File · 2 KB")).toBeInTheDocument();
});
it.each([
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
index 292db0c34861..e7ea51313f26 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
@@ -1,15 +1,12 @@
import {
ArrowSquareOutIcon,
+ ChatCircleIcon,
DownloadSimpleIcon,
EyeIcon,
PackageIcon,
SlackLogoIcon,
} from "@phosphor-icons/react";
-import {
- OUTPUT_ARTIFACT_TYPES,
- parseRunArtifacts,
- type RunArtifact,
-} from "@posthog/core/canvas/runArtifactSchemas";
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
import {
SESSION_SERVICE,
@@ -17,6 +14,7 @@ import {
} from "@posthog/core/sessions/sessionService";
import { useService } from "@posthog/di/react";
import {
+ Badge,
Button,
Empty,
EmptyDescription,
@@ -27,13 +25,12 @@ import {
TooltipContent,
TooltipTrigger,
} from "@posthog/quill";
-import { readPrUrls } from "@posthog/shared";
-import type {
- Task,
- TaskRun,
- TaskThreadMessage,
-} from "@posthog/shared/domain-types";
+import type { Task, TaskThreadMessage } from "@posthog/shared/domain-types";
import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
+import {
+ buildRows,
+ commentTargets,
+} from "@posthog/ui/features/canvas/components/taskArtifactRows";
import { useTaskRuns } from "@posthog/ui/features/canvas/hooks/useTaskRuns";
import { canvasArtifactOpenHandler } from "@posthog/ui/features/canvas/utils/canvasArtifactNavigation";
import { openPrInReview } from "@posthog/ui/features/code-review/openPrInReview";
@@ -41,98 +38,16 @@ import { usePrArtifact } from "@posthog/ui/features/git-interaction/usePrArtifac
import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
import { usePrComments } from "@posthog/ui/features/pr-review/usePrComments";
import { usePrReviewThreads } from "@posthog/ui/features/pr-review/usePrReviewThreads";
+import { buildCommentThreads } from "@posthog/ui/features/sessions/components/commentViewTypes";
+import { useCommentsForTargetsQuery } from "@posthog/ui/features/sessions/components/useComments";
+import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { toast } from "@posthog/ui/primitives/toast";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
import { type ReactNode, useMemo, useState } from "react";
-type ArtifactRow =
- | { kind: "pr"; key: string; url: string }
- | { kind: "canvas"; key: string; name: string; url: string | null }
- | {
- kind: "file";
- key: string;
- artifactId: string | null;
- name: string;
- runId: string | null;
- size: number | undefined;
- }
- | { kind: "slack"; key: string; url: string };
-
-function readRunOutputs(run: TaskRun): RunArtifact[] {
- return parseRunArtifacts(
- (run as { artifacts?: unknown }).artifacts,
- OUTPUT_ARTIFACT_TYPES,
- );
-}
-
-function buildRows(
- task: Task,
- timeline: ThreadTimelineRow<TaskThreadMessage>[],
- runs: TaskRun[],
-): ArtifactRow[] {
- const rows: ArtifactRow[] = [];
- const seenPrUrls = new Set<string>();
-
- const addPr = (url: string, key: string) => {
- if (seenPrUrls.has(url)) return;
- seenPrUrls.add(url);
- rows.push({ kind: "pr", key, url });
- };
-
- for (const row of timeline) {
- if (row.kind !== "artifact") continue;
- if (row.artifact.kind === "pr") {
- addPr(row.artifact.url, row.message.id);
- } else {
- rows.push({
- kind: "canvas",
- key: row.message.id,
- name: row.artifact.name,
- url: row.artifact.url,
- });
- }
- }
-
- const allRuns =
- runs.length > 0 ? runs : task.latest_run ? [task.latest_run] : [];
-
- // Re-uploading a file replaces it rather than adding a second one: agents
- // revise a deliverable and upload it again under the same name, so keeping
- // every copy would bury the current one under its own drafts.
- const newestByName = new Map<string, { file: RunArtifact; runId: string }>();
- for (const run of allRuns) {
- for (const outputPr of readPrUrls(run.output)) {
- addPr(outputPr, `output-pr:${outputPr}`);
- }
- for (const file of readRunOutputs(run)) {
- if (!file.name) continue;
- const previous = newestByName.get(file.name);
- const isNewer =
- !previous ||
- (file.uploaded_at ?? "") >= (previous.file.uploaded_at ?? "");
- if (isNewer) newestByName.set(file.name, { file, runId: run.id });
- }
- }
- for (const [name, { file, runId }] of newestByName) {
- rows.push({
- kind: "file",
- key: `file:${file.id ?? file.storage_path ?? name}`,
- artifactId: file.id ?? null,
- name,
- runId,
- size: file.size,
- });
- }
-
- const slackUrl = task.latest_run?.state?.slack_thread_url;
- if (typeof slackUrl === "string" && slackUrl) {
- rows.push({ kind: "slack", key: "slack-thread", url: slackUrl });
- }
-
- return rows;
-}
+const EMPTY_COMMENTS: ResourceComment[] = [];
function ArtifactListRow({
icon,
@@ -146,7 +61,7 @@ function ArtifactListRow({
}: {
icon: ReactNode;
title: string;
- detail?: string | null;
+ detail?: ReactNode;
external?: boolean;
onOpen?: () => void;
/** Renders a trailing button that leaves the app instead of opening the
@@ -279,13 +194,30 @@ function PrRow({
);
}
-function CanvasRow({ name, url }: { name: string; url: string | null }) {
+function CanvasRow({
+ name,
+ url,
+ commentCount,
+}: {
+ name: string;
+ url: string | null;
+ commentCount: number;
+}) {
const open = canvasArtifactOpenHandler(url);
return (
<ArtifactListRow
icon={iconForTemplate("", { size: 14, className: "text-violet-9" })}
title={name}
- detail="Canvas"
+ detail={
+ commentCount > 0 ? (
+ <Badge>
+ <ChatCircleIcon />
+ {commentCount}
+ </Badge>
+ ) : (
+ "Canvas"
+ )
+ }
onOpen={open}
/>
);
@@ -297,17 +229,21 @@ function FileRow({
artifactId,
name,
size,
+ commentCount,
}: {
taskId: string;
runId: string | null;
artifactId: string | null;
name: string;
size: number | undefined;
+ /** Supplied by the pane's single comments query so each row doesn't fetch. */
+ commentCount: number;
}) {
const sessionService = useService<SessionService>(SESSION_SERVICE);
const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
const [downloading, setDownloading] = useState(false);
const canOpen = !!runId && !!artifactId;
+ const sizeLabel = formatFileSize(size);
const onOpen = canOpen
? () => {
openArtifactTab(taskId, {
@@ -349,7 +285,17 @@ function FileRow({
<ArtifactListRow
icon={<FileIcon filename={name} size={14} />}
title={name}
- detail={["File", formatFileSize(size)].filter(Boolean).join(" · ")}
+ detail={
+ <div className="flex items-center gap-1.5">
+ <span>{sizeLabel ? `File · ${sizeLabel}` : "File"}</span>
+ {commentCount > 0 && (
+ <Badge>
+ <ChatCircleIcon />
+ {commentCount}
+ </Badge>
+ )}
+ </div>
+ }
onOpen={onOpen}
fileActions={
onDownload
@@ -371,11 +317,32 @@ export function TaskArtifactsList({
* open externally rather than into a review pane nobody is showing. */
canOpenInPlace?: boolean;
}) {
+ const commentsEnabled = useCommentsEnabled();
const { runs } = useTaskRuns(task.id);
const rows = useMemo(
() => buildRows(task, timeline, runs),
[task, timeline, runs],
);
+ // One query for every row's badge, so N resources cost one request rather
+ // than one per row. The threads themselves live in the Comments tab.
+ const targets = useMemo(() => commentTargets(rows), [rows]);
+ const commentsQuery = useCommentsForTargetsQuery(targets, task.id, {
+ enabled: commentsEnabled,
+ });
+ const comments = commentsEnabled
+ ? (commentsQuery.data ?? EMPTY_COMMENTS)
+ : EMPTY_COMMENTS;
+ // Open threads only, so a row's badge agrees with what the Comments tab
+ // shows on the same resource.
+ const openCountByItem = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const thread of buildCommentThreads(comments)) {
+ const itemId = thread.root.item_id;
+ if (thread.resolved || !itemId) continue;
+ counts.set(itemId, (counts.get(itemId) ?? 0) + 1);
+ }
+ return counts;
+ }, [comments]);
if (rows.length === 0) {
return (
@@ -404,7 +371,14 @@ export function TaskArtifactsList({
openInPlaceTaskId={canOpenInPlace ? task.id : undefined}
/>
) : row.kind === "canvas" ? (
- <CanvasRow key={row.key} name={row.name} url={row.url} />
+ <CanvasRow
+ key={row.key}
+ name={row.name}
+ url={row.url}
+ commentCount={
+ row.dashboardId ? (openCountByItem.get(row.dashboardId) ?? 0) : 0
+ }
+ />
) : row.kind === "file" ? (
<FileRow
key={row.key}
@@ -413,6 +387,9 @@ export function TaskArtifactsList({
artifactId={row.artifactId}
name={row.name}
size={row.size}
+ commentCount={
+ row.artifactId ? (openCountByItem.get(row.artifactId) ?? 0) : 0
+ }
/>
) : (
<ArtifactListRow
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx
new file mode 100644
index 000000000000..5bce35441dce
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx
@@ -0,0 +1,813 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
+import type { Task, TaskRun, TaskRunArtifact } from "@posthog/shared";
+import type { TaskThreadMessage } from "@posthog/shared/domain-types";
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ runs: [] as TaskRun[],
+ comments: [] as unknown[],
+ activeArtifactId: null as string | null,
+ prConversation: [] as unknown[],
+ prReviewThreads: [] as unknown[],
+ openArtifactTab: vi.fn(),
+ openPrInReview: vi.fn(),
+ openExternalUrl: vi.fn(),
+ requestScrollToFile: vi.fn(),
+ prReply: vi.fn(async () => true),
+ prResolve: vi.fn(async () => true),
+ createComment: vi.fn(),
+ setResolved: vi.fn(),
+ createdFor: [] as unknown[],
+ resolvedFor: [] as unknown[],
+ queriedTargets: [] as unknown[],
+ prCommentUrls: [] as string[],
+ prReviewUrls: [] as string[],
+ prTitleUrls: [] as string[],
+ prQueriesLoading: false,
+}));
+
+function openThread(body: string): void {
+ const card = screen.getByText(body).closest("[data-comment-thread-id]");
+ expect(card).not.toBeNull();
+ fireEvent.click(
+ within(card as HTMLElement).getByRole("button", {
+ name: "Open comment thread",
+ }),
+ );
+}
+
+vi.mock("@posthog/ui/features/canvas/hooks/useTaskRuns", () => ({
+ useTaskRuns: () => ({ runs: mocks.runs, isLoading: false }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({
+ useOrgMembers: () => ({ members: [] }),
+}));
+vi.mock("@posthog/ui/features/panels/panelLayoutStore", () => ({
+ usePanelLayoutStore: () => mocks.openArtifactTab,
+ useActiveArtifactId: () => mocks.activeArtifactId,
+}));
+vi.mock("@posthog/ui/features/pr-review/usePrCommentsForUrls", () => ({
+ usePrCommentsForUrls: (urls: string[]) => {
+ mocks.prCommentUrls = urls;
+ return {
+ byUrl: new Map(urls.map((url) => [url, mocks.prConversation])),
+ isLoading: mocks.prQueriesLoading,
+ };
+ },
+}));
+vi.mock("@posthog/ui/features/pr-review/usePrReviewThreadsForUrls", () => ({
+ usePrReviewThreadsForUrls: (urls: string[]) => {
+ mocks.prReviewUrls = urls;
+ return {
+ byUrl: new Map(urls.map((url) => [url, mocks.prReviewThreads])),
+ isLoading: mocks.prQueriesLoading,
+ };
+ },
+}));
+vi.mock("@posthog/ui/features/git-interaction/usePrDetails", () => ({
+ usePrTitles: (urls: string[]) => {
+ mocks.prTitleUrls = urls;
+ return {};
+ },
+}));
+vi.mock("@posthog/ui/shell/openExternal", () => ({
+ openExternalUrl: (url: string) => mocks.openExternalUrl(url),
+}));
+// GitHub bodies render through MarkdownRenderer; the wiring under test is the
+// list, not the markdown pipeline, so keep it to plain text here.
+vi.mock("@posthog/ui/features/editor/components/MarkdownRenderer", () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => (
+ <span>{content}</span>
+ ),
+}));
+vi.mock("@posthog/ui/features/code-review/openPrInReview", () => ({
+ openPrInReview: (taskId: string, url: string) =>
+ mocks.openPrInReview(taskId, url),
+}));
+vi.mock("@posthog/ui/features/code-review/reviewNavigationStore", () => ({
+ useReviewNavigationStore: {
+ getState: () => ({ requestScrollToFile: mocks.requestScrollToFile }),
+ },
+}));
+// Tiptap's editor renders no placeholder attribute and drags a lot of DOM into
+// jsdom; the wiring under test is which target a composed comment posts to.
+vi.mock("@posthog/ui/features/sessions/components/CommentComposer", () => ({
+ CommentComposer: ({
+ placeholder,
+ onSubmit,
+ }: {
+ placeholder: string;
+ onSubmit: (content: string, mentions: number[]) => void;
+ }) => (
+ <button type="button" onClick={() => onSubmit("Composed comment", [])}>
+ {placeholder}
+ </button>
+ ),
+}));
+vi.mock("@posthog/ui/features/code-review/hooks/usePrCommentActions", () => ({
+ usePrCommentActions: () => ({
+ reply: mocks.prReply,
+ resolve: mocks.prResolve,
+ }),
+}));
+vi.mock("@posthog/ui/features/sessions/components/useComments", () => ({
+ isOptimisticComment: (comment: ResourceComment) =>
+ comment.id.startsWith("optimistic-"),
+ useCommentsQuery: (target: unknown) => {
+ if (target) mocks.queriedTargets.push([target]);
+ return {
+ data: mocks.comments,
+ isLoading: false,
+ };
+ },
+ useCommentsForTargetsQuery: (targets: unknown) => {
+ if (Array.isArray(targets) && targets.length > 0) {
+ mocks.queriedTargets.push(targets);
+ }
+ return {
+ data: mocks.comments,
+ isLoading: false,
+ };
+ },
+ useCreateComment: (target: unknown) => {
+ mocks.createdFor.push(target);
+ return { mutateAsync: mocks.createComment, isPending: false };
+ },
+ useSetCommentResolved: (target: unknown) => {
+ mocks.resolvedFor.push(target);
+ return { mutate: mocks.setResolved, isPending: false };
+ },
+}));
+
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { TaskCommentsList } from "./TaskCommentsList";
+
+const task = { id: "task-1", latest_run: null } as unknown as Task;
+
+function run(artifacts: Partial<TaskRunArtifact>[], id = "run-1"): TaskRun {
+ return { id, output: null, artifacts } as unknown as TaskRun;
+}
+
+function outputFile(
+ overrides: Partial<TaskRunArtifact>,
+): Partial<TaskRunArtifact> {
+ return {
+ type: "output",
+ name: "report.md",
+ storage_path: "runs/1/report.md",
+ ...overrides,
+ };
+}
+
+function prRun(url: string): TaskRun {
+ return {
+ id: "run-pr",
+ output: { pr_url: url },
+ artifacts: [],
+ } as unknown as TaskRun;
+}
+
+function reviewThread(overrides: Record<string, unknown> = {}) {
+ return {
+ nodeId: "node-1",
+ isResolved: false,
+ rootId: 501,
+ filePath: "packages/ui/src/App.tsx",
+ comments: [
+ {
+ id: 501,
+ body: "This needs a guard",
+ path: "packages/ui/src/App.tsx",
+ line: 12,
+ user: { login: "octocat", avatar_url: "" },
+ created_at: "2024-01-02T00:00:00Z",
+ },
+ ],
+ ...overrides,
+ };
+}
+
+function comment(overrides: Partial<ResourceComment>): ResourceComment {
+ return {
+ id: "comment-1",
+ created_by: null,
+ content: "Tighten this summary",
+ created_at: "2024-01-01T00:00:00Z",
+ item_id: "a",
+ item_context: { anchor: { kind: "document" } },
+ scope: "task_artifact",
+ source_comment: null,
+ ...overrides,
+ } as ResourceComment;
+}
+
+describe("TaskCommentsList", () => {
+ beforeEach(() => {
+ mocks.runs = [
+ run([
+ outputFile({ id: "a", name: "report.md" }),
+ outputFile({
+ id: "b",
+ name: "summary.md",
+ storage_path: "runs/1/summary.md",
+ }),
+ ]),
+ ];
+ mocks.comments = [
+ comment({}),
+ comment({
+ id: "reply-1",
+ source_comment: "comment-1",
+ content: "Agreed",
+ created_at: "2024-01-01T00:01:00Z",
+ }),
+ comment({
+ id: "comment-2",
+ item_id: "b",
+ content: "Second thread",
+ created_at: "2024-01-01T00:02:00Z",
+ }),
+ ];
+ mocks.activeArtifactId = null;
+ mocks.prConversation = [];
+ mocks.prReviewThreads = [];
+ mocks.openArtifactTab.mockReset();
+ mocks.openPrInReview.mockReset();
+ mocks.openExternalUrl.mockReset();
+ mocks.requestScrollToFile.mockReset();
+ mocks.prReply.mockClear();
+ mocks.prResolve.mockClear();
+ mocks.createComment.mockReset();
+ mocks.createComment.mockResolvedValue({ id: "created-comment" });
+ mocks.setResolved.mockReset();
+ mocks.createdFor = [];
+ mocks.resolvedFor = [];
+ mocks.queriedTargets = [];
+ mocks.prCommentUrls = [];
+ mocks.prReviewUrls = [];
+ mocks.prTitleUrls = [];
+ mocks.prQueriesLoading = false;
+ useCommentNavigationStore.setState({
+ focusByTask: {},
+ resolutionsByTarget: {},
+ });
+ });
+
+ it("limits GitHub comment queries to 20 pull requests", () => {
+ mocks.runs = Array.from({ length: 25 }, (_, index) =>
+ prRun(`https://github.com/acme/repo/pull/${index + 1}`),
+ );
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ const expectedUrls = Array.from(
+ { length: 20 },
+ (_, index) => `https://github.com/acme/repo/pull/${index + 1}`,
+ );
+ expect(mocks.prCommentUrls).toEqual(expectedUrls);
+ expect(mocks.prReviewUrls).toEqual(expectedUrls);
+ expect(mocks.prTitleUrls).toEqual(expectedUrls);
+ });
+
+ it("queries and displays only the current canvas when restricted", async () => {
+ const onCanvasCommentOpen = vi.fn();
+ mocks.comments = [
+ comment({
+ item_id: "canvas-1",
+ scope: "desktop_canvas",
+ content: "Canvas feedback",
+ item_context: {
+ anchor: {
+ kind: "text",
+ quote: "important copy",
+ prefix: "",
+ suffix: "",
+ start: 0,
+ end: 14,
+ },
+ canvasVersionId: "version-2",
+ },
+ }),
+ ];
+
+ render(
+ <TaskCommentsList
+ task={task}
+ timeline={[]}
+ onlySource={{
+ kind: "canvas",
+ name: "Launch canvas",
+ target: { scope: "desktop_canvas", itemId: "canvas-1" },
+ url: null,
+ }}
+ canvasVersionId="version-2"
+ commentVersionLabel={() => "V2"}
+ onCanvasCommentOpen={onCanvasCommentOpen}
+ />,
+ );
+
+ expect(mocks.queriedTargets.at(-1)).toEqual([
+ { scope: "desktop_canvas", itemId: "canvas-1" },
+ ]);
+ expect(screen.getByText("Canvas feedback")).toBeInTheDocument();
+ expect(screen.getByText("“important copy”")).toBeInTheDocument();
+ expect(screen.getByText("V2 ·")).toBeInTheDocument();
+ expect(screen.queryByText("Selected text")).not.toBeInTheDocument();
+ expect(screen.queryByText("Whole canvas")).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("Filter by source")).not.toBeInTheDocument();
+ expect(screen.queryByText("Launch canvas")).not.toBeInTheDocument();
+ expect(mocks.createdFor.at(-1)).toEqual({
+ scope: "desktop_canvas",
+ itemId: "canvas-1",
+ });
+
+ openThread("Canvas feedback");
+ expect(onCanvasCommentOpen).toHaveBeenCalledWith("version-2");
+
+ await act(async () => {
+ fireEvent.click(screen.getByText(/Comment on this canvas/));
+ });
+ expect(mocks.createComment).toHaveBeenCalledWith({
+ content: "Composed comment",
+ context: {
+ anchor: { kind: "document" },
+ canvasVersionId: "version-2",
+ },
+ mentions: [],
+ });
+ });
+
+ it("shows selected artifact text alongside its source", () => {
+ mocks.comments = [
+ comment({
+ item_context: {
+ anchor: {
+ kind: "text",
+ quote: "Purpose",
+ prefix: "",
+ suffix: "",
+ start: 0,
+ end: 7,
+ },
+ },
+ }),
+ ];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("report.md")).toBeTruthy();
+ expect(screen.getByText("“Purpose”")).toBeTruthy();
+ });
+
+ it("loads canvas comments from a local-development artifact link", () => {
+ mocks.runs = [];
+ mocks.comments = [
+ comment({
+ item_id: "canvas-1",
+ scope: "desktop_canvas",
+ content: "Linked canvas feedback",
+ }),
+ ];
+
+ const timeline = [
+ {
+ kind: "artifact",
+ timestamp: 1,
+ message: { id: "message-1" },
+ artifact: {
+ kind: "canvas",
+ name: "Dev Joke Machine",
+ url: "http://localhost:8000/code/canvas/channel-1/canvas-1",
+ },
+ },
+ ] as unknown as ThreadTimelineRow<TaskThreadMessage>[];
+
+ render(<TaskCommentsList task={task} timeline={timeline} />);
+
+ expect(mocks.queriedTargets.at(-1)).toContainEqual({
+ scope: "desktop_canvas",
+ itemId: "canvas-1",
+ });
+ expect(screen.getByText("Linked canvas feedback")).toBeInTheDocument();
+ });
+
+ // The tab is the one place to see every thread the task produced, so each row
+ // has to say which artifact it came from.
+ it("lists open threads from every artifact, newest first", () => {
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ const newest = screen.getByText("Second thread");
+ const oldest = screen.getByText("Tighten this summary");
+ expect(
+ newest.compareDocumentPosition(oldest) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(screen.getByText("summary.md")).toBeTruthy();
+ expect(screen.getByText("report.md")).toBeTruthy();
+ expect(screen.getByText(/1 reply/)).toBeTruthy();
+ // The resolve/reopen reply is thread state, not a comment of its own.
+ expect(screen.queryByText("Agreed")).toBeTruthy();
+ });
+
+ it("opens the artifact a thread belongs to and focuses that thread", () => {
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ openThread("Tighten this summary");
+
+ expect(mocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "a",
+ name: "report.md",
+ });
+ expect(useCommentNavigationStore.getState().focusByTask["task-1"]).toEqual({
+ target: { scope: "task_artifact", itemId: "a" },
+ threadId: "comment-1",
+ nonce: expect.any(Number),
+ openCommentsTab: true,
+ });
+ });
+
+ it("opens an artifact when activity requests its comment thread", () => {
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ act(() => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "task_artifact", itemId: "a" },
+ "comment-1",
+ );
+ });
+
+ expect(mocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "a",
+ name: "report.md",
+ });
+ });
+
+ it("opens the saved canvas version when activity requests its thread", () => {
+ const onCanvasCommentOpen = vi.fn();
+ mocks.comments = [
+ comment({
+ item_id: "canvas-1",
+ scope: "desktop_canvas",
+ content: "Historical canvas feedback",
+ item_context: {
+ anchor: { kind: "document" },
+ canvasVersionId: "version-2",
+ },
+ }),
+ ];
+
+ render(
+ <TaskCommentsList
+ task={task}
+ timeline={[]}
+ onlySource={{
+ kind: "canvas",
+ name: "Launch canvas",
+ target: { scope: "desktop_canvas", itemId: "canvas-1" },
+ url: null,
+ }}
+ canvasVersionId="version-3"
+ onCanvasCommentOpen={onCanvasCommentOpen}
+ />,
+ );
+
+ act(() => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "desktop_canvas", itemId: "canvas-1" },
+ "comment-1",
+ );
+ });
+
+ expect(onCanvasCommentOpen).toHaveBeenCalledWith("version-2");
+ });
+
+ // Clicking the same thread twice has to scroll twice, so every request is a
+ // new nonce rather than a no-op set.
+ it("re-requests focus for a thread already focused", () => {
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ openThread("Tighten this summary");
+ const first = useCommentNavigationStore.getState().focusByTask["task-1"];
+ openThread("Tighten this summary");
+ const second = useCommentNavigationStore.getState().focusByTask["task-1"];
+
+ expect(second?.nonce).toBeGreaterThan(first?.nonce ?? 0);
+ });
+
+ it("filters between open and resolved threads", () => {
+ mocks.comments = [
+ comment({}),
+ comment({
+ id: "state-1",
+ source_comment: "comment-1",
+ content: "Resolved this thread",
+ created_at: "2024-01-01T00:03:00Z",
+ item_context: {
+ anchor: { kind: "document" },
+ threadState: "resolved",
+ },
+ }),
+ comment({
+ id: "comment-2",
+ item_id: "b",
+ content: "Second thread",
+ created_at: "2024-01-01T00:02:00Z",
+ }),
+ ];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("Second thread")).toBeTruthy();
+ expect(screen.queryByText("Tighten this summary")).toBeNull();
+
+ fireEvent.click(screen.getByLabelText("Filter comments"));
+ fireEvent.click(screen.getByText("Resolved (1)"));
+
+ expect(screen.getByText("Tighten this summary")).toBeTruthy();
+ expect(screen.queryByText("Second thread")).toBeNull();
+ });
+
+ it("warns when the anchored text the thread points at has changed", () => {
+ useCommentNavigationStore.setState({
+ resolutionsByTarget: {
+ "task_artifact:a": new Map([["comment-1", "orphaned" as const]]),
+ },
+ });
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("The highlighted text changed")).toBeTruthy();
+ });
+
+ it("replies and resolves against the thread's own resource", () => {
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ // Each row builds its mutations from its own target, since the list spans
+ // several resources.
+ expect(mocks.createdFor).toContainEqual({
+ scope: "task_artifact",
+ itemId: "a",
+ });
+ expect(mocks.resolvedFor).toContainEqual({
+ scope: "task_artifact",
+ itemId: "b",
+ });
+
+ const thread = screen
+ .getByText("Tighten this summary")
+ .closest("[data-comment-thread-id]") as HTMLElement;
+ fireEvent.click(within(thread).getByText("Resolve"));
+
+ expect(mocks.setResolved).toHaveBeenCalledWith({
+ root: expect.objectContaining({ id: "comment-1" }),
+ resolved: true,
+ });
+ });
+
+ // The pane follows what's on screen, but a reader who picks a source owns the
+ // filter from then on.
+ it("narrows to the artifact open in the main pane", () => {
+ mocks.activeArtifactId = "b";
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("Second thread")).toBeTruthy();
+ expect(screen.queryByText("Tighten this summary")).toBeNull();
+ });
+
+ it("labels an active artifact that has no comments", () => {
+ mocks.runs = [
+ run([
+ outputFile({ id: "a", name: "report.md" }),
+ outputFile({
+ id: "empty",
+ name: "empty.md",
+ storage_path: "runs/1/empty.md",
+ }),
+ ]),
+ ];
+ mocks.comments = [comment({})];
+ mocks.activeArtifactId = "empty";
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByLabelText("Filter by source")).toHaveTextContent(
+ "empty.md",
+ );
+ expect(screen.queryByText("Tighten this summary")).toBeNull();
+ fireEvent.click(screen.getByLabelText("Filter by source"));
+ const emptySourceOption = screen
+ .getAllByText("empty.md")
+ .at(-1)
+ ?.closest('[role="menuitemradio"]');
+ expect(emptySourceOption).toHaveTextContent("0");
+ });
+
+ it("follows an active artifact once its run data arrives", () => {
+ mocks.runs = [];
+ mocks.activeArtifactId = "late";
+ const { rerender } = render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByLabelText("Filter by source")).toHaveTextContent(
+ "All sources",
+ );
+
+ mocks.runs = [
+ run([
+ outputFile({
+ id: "late",
+ name: "late.md",
+ storage_path: "runs/1/late.md",
+ }),
+ ]),
+ ];
+ rerender(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByLabelText("Filter by source")).toHaveTextContent(
+ "late.md",
+ );
+ });
+
+ it("resumes following the main pane after All sources is selected", () => {
+ mocks.activeArtifactId = "b";
+ const { rerender } = render(<TaskCommentsList task={task} timeline={[]} />);
+
+ fireEvent.click(screen.getByLabelText("Filter by source"));
+ fireEvent.click(screen.getByText(/^All sources/));
+ mocks.activeArtifactId = "a";
+ rerender(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.queryByText("Second thread")).toBeNull();
+ expect(screen.getByText("Tighten this summary")).toBeTruthy();
+ });
+
+ it("stops following the main pane while a specific source is selected", () => {
+ mocks.activeArtifactId = null;
+ const { rerender } = render(<TaskCommentsList task={task} timeline={[]} />);
+
+ fireEvent.click(screen.getByLabelText("Filter by source"));
+ fireEvent.click(screen.getAllByText("report.md").at(-1) as HTMLElement);
+ mocks.activeArtifactId = "b";
+ rerender(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.queryByText("Second thread")).toBeNull();
+ expect(screen.getByText("Tighten this summary")).toBeTruthy();
+ });
+
+ it("lists a PR's review threads and conversation comments", () => {
+ mocks.runs = [prRun("https://github.com/acme/repo/pull/7")];
+ mocks.comments = [];
+ mocks.prReviewThreads = [reviewThread()];
+ mocks.prConversation = [
+ {
+ id: 900,
+ author: "octocat",
+ avatarUrl: null,
+ body: "Shipping this",
+ createdAt: "2024-01-03T00:00:00Z",
+ url: "https://github.com/acme/repo/pull/7#issuecomment-900",
+ },
+ ];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("This needs a guard")).toBeTruthy();
+ expect(screen.getByText("Shipping this")).toBeTruthy();
+ expect(screen.getAllByText("PR #7").length).toBe(2);
+ // Only the file-anchored thread can be resolved on GitHub.
+ expect(screen.getAllByText("Resolve")).toHaveLength(1);
+ // The conversation comment can't be handled here, so it links out instead.
+ expect(screen.getByText("View on GitHub")).toBeTruthy();
+ });
+
+ it("links a conversation comment out to GitHub", () => {
+ mocks.runs = [prRun("https://github.com/acme/repo/pull/7")];
+ mocks.comments = [];
+ mocks.prConversation = [
+ {
+ id: 900,
+ author: "octocat",
+ avatarUrl: null,
+ body: "Shipping this",
+ createdAt: "2024-01-03T00:00:00Z",
+ url: "https://github.com/acme/repo/pull/7#issuecomment-900",
+ },
+ ];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+ fireEvent.click(screen.getByText("View on GitHub"));
+
+ expect(mocks.openExternalUrl).toHaveBeenCalledWith(
+ "https://github.com/acme/repo/pull/7#issuecomment-900",
+ );
+ });
+
+ it("opens a PR thread in the review pane at its file", () => {
+ mocks.runs = [prRun("https://github.com/acme/repo/pull/7")];
+ mocks.comments = [];
+ mocks.prReviewThreads = [reviewThread()];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+ openThread("This needs a guard");
+
+ expect(mocks.openPrInReview).toHaveBeenCalledWith(
+ "task-1",
+ "https://github.com/acme/repo/pull/7",
+ );
+ expect(mocks.requestScrollToFile).toHaveBeenCalledWith(
+ "task-1",
+ "packages/ui/src/App.tsx",
+ );
+ });
+
+ it("replies and resolves a PR thread on GitHub", () => {
+ mocks.runs = [prRun("https://github.com/acme/repo/pull/7")];
+ mocks.comments = [];
+ mocks.prReviewThreads = [reviewThread()];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+ const thread = screen
+ .getByText("This needs a guard")
+ .closest("[data-comment-thread-id]") as HTMLElement;
+ fireEvent.click(within(thread).getByText("Resolve"));
+
+ expect(mocks.prResolve).toHaveBeenCalledWith("node-1", true);
+ expect(mocks.setResolved).not.toHaveBeenCalled();
+ });
+
+ // Not every comment belongs to a deliverable; some are about the work.
+ it("posts a comment on the task itself", async () => {
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ await act(async () => {
+ fireEvent.click(screen.getByText(/Comment on this task/));
+ });
+
+ expect(mocks.createdFor).toContainEqual({
+ scope: "task",
+ itemId: "task-1",
+ });
+ expect(mocks.createComment).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: "Composed comment",
+ context: { anchor: { kind: "document" } },
+ }),
+ );
+ });
+
+ it("polls at most 20 artifact comment targets plus the task", () => {
+ mocks.runs = [
+ run(
+ Array.from({ length: 25 }, (_, index) =>
+ outputFile({
+ id: `artifact-${index}`,
+ name: `artifact-${index}.md`,
+ storage_path: `runs/1/artifact-${index}.md`,
+ }),
+ ),
+ ),
+ ];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ const queriedTargets = mocks.queriedTargets.at(-1) as Array<{
+ scope: string;
+ itemId: string;
+ }>;
+ expect(queriedTargets).toHaveLength(21);
+ expect(queriedTargets[0]).toEqual({
+ scope: "task",
+ itemId: "task-1",
+ });
+ });
+
+ it("loads GitHub comments for at most four PRs at once", () => {
+ mocks.prQueriesLoading = true;
+ mocks.runs = Array.from({ length: 8 }, (_, index) =>
+ prRun(`https://github.com/acme/repo/pull/${index + 1}`),
+ );
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(mocks.prCommentUrls).toHaveLength(4);
+ expect(mocks.prReviewUrls).toHaveLength(4);
+ expect(mocks.prTitleUrls).toHaveLength(4);
+ });
+
+ it("shows an empty state pointing at the artifact surfaces", () => {
+ mocks.comments = [];
+
+ render(<TaskCommentsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("No open comments")).toBeTruthy();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
new file mode 100644
index 000000000000..7f50a2ebe03f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
@@ -0,0 +1,762 @@
+import {
+ CaretDownIcon,
+ ChatCircleIcon,
+ FunnelSimpleIcon,
+ GitPullRequestIcon,
+} from "@phosphor-icons/react";
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
+import { commentTargetKey } from "@posthog/core/comments/anchors";
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Spinner,
+} from "@posthog/quill";
+import type {
+ Task,
+ TaskThreadMessage,
+ UserBasic,
+} from "@posthog/shared/domain-types";
+import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
+import {
+ buildRows,
+ type CommentSource,
+ commentSources,
+ taskCommentTarget,
+} from "@posthog/ui/features/canvas/components/taskArtifactRows";
+import {
+ byNewestActivity,
+ prCommentThreads,
+ resourceCommentThreads,
+ type SourceKind,
+ type TaskCommentThread,
+ threadSourceOptions,
+} from "@posthog/ui/features/canvas/components/taskCommentThreads";
+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { useTaskRuns } from "@posthog/ui/features/canvas/hooks/useTaskRuns";
+import { canvasArtifactOpenHandler } from "@posthog/ui/features/canvas/utils/canvasArtifactNavigation";
+import { usePrCommentActions } from "@posthog/ui/features/code-review/hooks/usePrCommentActions";
+import { openPrInReview } from "@posthog/ui/features/code-review/openPrInReview";
+import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";
+import { usePrTitles } from "@posthog/ui/features/git-interaction/usePrDetails";
+import {
+ useActiveArtifactId,
+ usePanelLayoutStore,
+} from "@posthog/ui/features/panels/panelLayoutStore";
+import { usePrCommentsForUrls } from "@posthog/ui/features/pr-review/usePrCommentsForUrls";
+import { usePrReviewThreadsForUrls } from "@posthog/ui/features/pr-review/usePrReviewThreadsForUrls";
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { CommentComposer } from "@posthog/ui/features/sessions/components/CommentComposer";
+import { CommentThreadCard } from "@posthog/ui/features/sessions/components/CommentThreadCard";
+import type { HighlightResolution } from "@posthog/ui/features/sessions/components/commentViewTypes";
+import { readCommentContext } from "@posthog/ui/features/sessions/components/commentViewTypes";
+import {
+ isOptimisticComment,
+ useCommentsForTargetsQuery,
+ useCommentsQuery,
+ useCreateComment,
+ useSetCommentResolved,
+} from "@posthog/ui/features/sessions/components/useComments";
+import { FileIcon } from "@posthog/ui/primitives/FileIcon";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+
+const EMPTY_COMMENTS: ResourceComment[] = [];
+/** The whole task's threads in one request; slower than a single artifact's own
+ * poll because this one fans out across every resource. */
+const POLL_INTERVAL_MS = 30_000;
+const PULSE_MS = 1_200;
+const ALL_SOURCES = "all";
+// Keep task comments live, but bound the artifact and canvas poll so generated
+// output cannot turn one Comments tab into an unbounded backend request.
+const MAX_RESOURCE_COMMENT_TARGETS = 20;
+// Each PR starts three GitHub-backed queries. Keep this cap at the source so a
+// task with generated output cannot fan out into an unbounded number of requests.
+const MAX_PR_COMMENT_SOURCES = 20;
+const MAX_CONCURRENT_PR_SOURCES = 4;
+
+type StateFilter = "open" | "resolved";
+
+/** The icon a source shows wherever it's named — the card label and the
+ * filter menu — so the two always agree. */
+function sourceIcon(kind: SourceKind, label: string, size = 12) {
+ switch (kind) {
+ case "pr":
+ return (
+ <GitPullRequestIcon size={size} className="shrink-0 text-gray-11" />
+ );
+ case "canvas":
+ return iconForTemplate("", { size, className: "text-violet-9" });
+ case "task":
+ return <ChatCircleIcon size={size} className="shrink-0 text-gray-11" />;
+ default:
+ return <FileIcon filename={label} size={size} />;
+ }
+}
+
+function SourceLabel({ thread }: { thread: TaskCommentThread }) {
+ const replies = thread.entries.length - 1;
+ return (
+ <span className="mb-1 flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs">
+ {sourceIcon(thread.sourceKind, thread.sourceLabel)}
+ <span className="min-w-0 truncate" title={thread.sourceLabel}>
+ {thread.sourceLabel}
+ </span>
+ {thread.origin.kind === "pr-review" && (
+ <span className="min-w-0 truncate">
+ · {thread.origin.filePath.split("/").at(-1)}
+ </span>
+ )}
+ {replies > 0 && (
+ <span className="shrink-0">
+ · {replies} {replies === 1 ? "reply" : "replies"}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function CommentReference({
+ root,
+ versionLabel,
+}: {
+ root: ResourceComment;
+ versionLabel?: (versionId: string) => string | null;
+}) {
+ const context = readCommentContext(root);
+ const version = context?.canvasVersionId
+ ? versionLabel?.(context.canvasVersionId)
+ : null;
+ const anchor = context?.anchor;
+ const quote = anchor?.kind === "text" ? anchor.quote : null;
+ if (!version && !quote) return null;
+ return (
+ <span className="mb-1 flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs">
+ {version && <span className="shrink-0">{version} ·</span>}
+ {quote && (
+ <span className="min-w-0 truncate" title={quote}>
+ “{quote}”
+ </span>
+ )}
+ </span>
+ );
+}
+
+/**
+ * A PostHog comment thread. Its own component so it can hold the mutations for
+ * its thread's resource — the list spans several, each with its own target.
+ */
+function ResourceThreadRow({
+ thread,
+ source,
+ root,
+ taskId,
+ members,
+ selected,
+ pulsing,
+ resolution,
+ onOpen,
+ showSource = true,
+ commentVersionLabel,
+}: {
+ thread: TaskCommentThread;
+ source: CommentSource;
+ root: ResourceComment;
+ taskId: string;
+ members: UserBasic[];
+ selected: boolean;
+ pulsing: boolean;
+ resolution?: HighlightResolution;
+ onOpen: () => void;
+ showSource?: boolean;
+ commentVersionLabel?: (versionId: string) => string | null;
+}) {
+ const createComment = useCreateComment(source.target, taskId);
+ const setResolved = useSetCommentResolved(source.target);
+ const rootPending = isOptimisticComment(root);
+
+ return (
+ <CommentThreadCard
+ threadId={thread.id}
+ entries={thread.entries}
+ selected={selected}
+ pulsing={pulsing}
+ resolved={thread.resolved}
+ members={members}
+ resolution={resolution}
+ busy={createComment.isPending || setResolved.isPending}
+ source={
+ <>
+ {showSource && <SourceLabel thread={thread} />}
+ <CommentReference root={root} versionLabel={commentVersionLabel} />
+ </>
+ }
+ onSelect={onOpen}
+ canReply={!rootPending}
+ canResolve={!rootPending}
+ onReply={async (content, mentions) => {
+ await createComment.mutateAsync({
+ content,
+ sourceCommentId: root.id,
+ context: readCommentContext(root) ?? { anchor: { kind: "document" } },
+ mentions,
+ });
+ }}
+ onResolve={(resolved) => setResolved.mutate({ root, resolved })}
+ />
+ );
+}
+
+/** A GitHub thread. Reply and resolve go to GitHub, not to PostHog. */
+function PrThreadRow({
+ thread,
+ selected,
+ pulsing,
+ onOpen,
+}: {
+ thread: TaskCommentThread;
+ selected: boolean;
+ pulsing: boolean;
+ onOpen: () => void;
+}) {
+ const origin = thread.origin;
+ const prUrl = origin.kind === "resource" ? null : origin.prUrl;
+ const { reply, resolve } = usePrCommentActions(prUrl);
+ const [busy, setBusy] = useState(false);
+
+ const run = async (action: () => Promise<boolean>) => {
+ setBusy(true);
+ try {
+ if (!(await action())) throw new Error("GitHub comment action failed");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <CommentThreadCard
+ threadId={thread.id}
+ entries={thread.entries}
+ selected={selected}
+ pulsing={pulsing}
+ resolved={thread.resolved}
+ // GitHub bodies mention GitHub logins, so the org member picker would
+ // insert markup nobody on that side understands.
+ members={[]}
+ busy={busy}
+ source={<SourceLabel thread={thread} />}
+ // Only inline review threads accept replies and resolution; conversation
+ // comments are read here and linked out to GitHub to act on.
+ canReply={origin.kind === "pr-review"}
+ canResolve={origin.kind === "pr-review"}
+ viewHref={origin.kind === "pr-conversation" ? origin.url : undefined}
+ onSelect={onOpen}
+ onReply={(content) =>
+ run(() =>
+ origin.kind === "pr-review"
+ ? reply(origin.rootCommentId, content)
+ : Promise.resolve(false),
+ )
+ }
+ onResolve={(resolved) =>
+ run(() =>
+ origin.kind === "pr-review"
+ ? resolve(origin.threadNodeId, resolved)
+ : Promise.resolve(false),
+ )
+ }
+ />
+ );
+}
+
+/**
+ * Every comment thread on the task: its artifacts, its canvases, its pull
+ * requests, and the task itself. Selecting one opens where it lives and locates
+ * it there, which is why no surface carries a thread list of its own.
+ */
+export function TaskCommentsList({
+ task,
+ timeline,
+ onlySource,
+ canvasVersionId,
+ commentVersionLabel,
+ onCanvasCommentOpen,
+}: {
+ task: Task;
+ timeline: ThreadTimelineRow<TaskThreadMessage>[];
+ /** Restricts the pane to one resource known by its host, without relying on
+ * the task timeline to rediscover it. */
+ onlySource?: CommentSource;
+ canvasVersionId?: string | null;
+ commentVersionLabel?: (versionId: string) => string | null;
+ onCanvasCommentOpen?: (versionId: string | null) => void;
+}) {
+ const { runs } = useTaskRuns(onlySource ? undefined : task.id);
+ const { members } = useOrgMembers();
+ const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
+ const activeArtifactId = useActiveArtifactId(task.id);
+ const requestCommentFocus = useCommentNavigationStore(
+ (state) => state.requestCommentFocus,
+ );
+ const focus = useCommentNavigationStore(
+ (state) => state.focusByTask[task.id],
+ );
+ const resolutionsByTarget = useCommentNavigationStore(
+ (state) => state.resolutionsByTarget,
+ );
+ const [stateFilter, setStateFilter] = useState<StateFilter>("open");
+ const [sourceFilter, setSourceFilter] = useState<string>(ALL_SOURCES);
+ const [pulseThreadId, setPulseThreadId] = useState<string | null>(null);
+ const [draft, setDraft] = useState("");
+ const sourceFilterTouched = useRef(false);
+ const previousTaskId = useRef(task.id);
+
+ useEffect(() => {
+ if (previousTaskId.current === task.id) return;
+ previousTaskId.current = task.id;
+ sourceFilterTouched.current = false;
+ setSourceFilter(ALL_SOURCES);
+ setDraft("");
+ }, [task.id]);
+
+ const rows = useMemo(
+ () => buildRows(task, timeline, runs),
+ [task, timeline, runs],
+ );
+ const sources = useMemo(
+ () => (onlySource ? [onlySource] : commentSources(task.id, rows)),
+ [task.id, rows, onlySource],
+ );
+ const targets = useMemo(
+ () =>
+ onlySource
+ ? sources.map((source) => source.target)
+ : [
+ ...sources.slice(0, 1),
+ ...sources.slice(1, MAX_RESOURCE_COMMENT_TARGETS + 1),
+ ].map((source) => source.target),
+ [onlySource, sources],
+ );
+ const singleSourceComments = useCommentsQuery(
+ onlySource?.target ?? null,
+ task.id,
+ );
+ const taskComments = useCommentsForTargetsQuery(
+ onlySource ? [] : targets,
+ task.id,
+ {
+ live: true,
+ intervalMs: POLL_INTERVAL_MS,
+ },
+ );
+ const commentsQuery = onlySource ? singleSourceComments : taskComments;
+ const prUrls = useMemo(
+ () =>
+ onlySource
+ ? []
+ : rows
+ .flatMap((row) => (row.kind === "pr" ? [row.url] : []))
+ .slice(0, MAX_PR_COMMENT_SOURCES),
+ [rows, onlySource],
+ );
+ const prUrlsKey = prUrls.join("\n");
+ const [prLoadProgress, setPrLoadProgress] = useState({
+ key: "",
+ count: MAX_CONCURRENT_PR_SOURCES,
+ });
+ const loadedPrSourceCount =
+ prLoadProgress.key === prUrlsKey
+ ? prLoadProgress.count
+ : MAX_CONCURRENT_PR_SOURCES;
+ const loadedPrUrls = prUrls.slice(0, loadedPrSourceCount);
+ const prConversation = usePrCommentsForUrls(loadedPrUrls);
+ const prReviews = usePrReviewThreadsForUrls(loadedPrUrls);
+ const prTitles = usePrTitles(loadedPrUrls);
+ useEffect(() => {
+ if (
+ prConversation.isLoading ||
+ prReviews.isLoading ||
+ loadedPrSourceCount >= prUrls.length
+ ) {
+ return;
+ }
+ setPrLoadProgress({
+ key: prUrlsKey,
+ count: Math.min(
+ loadedPrSourceCount + MAX_CONCURRENT_PR_SOURCES,
+ prUrls.length,
+ ),
+ });
+ }, [
+ loadedPrSourceCount,
+ prConversation.isLoading,
+ prReviews.isLoading,
+ prUrlsKey,
+ prUrls.length,
+ ]);
+
+ const taskTarget = useMemo(() => taskCommentTarget(task.id), [task.id]);
+ const composerTarget = onlySource?.target ?? taskTarget;
+ const composerSourceKey = commentTargetKey(composerTarget);
+ const createComment = useCreateComment(composerTarget, task.id);
+
+ const threads = useMemo(() => {
+ const reviewByUrl = new Map(prReviews.byUrl);
+ const conversationByUrl = new Map(prConversation.byUrl);
+ const resourceThreads = resourceCommentThreads(
+ commentsQuery.data ?? EMPTY_COMMENTS,
+ sources,
+ );
+ const prThreads = loadedPrUrls.flatMap((prUrl) =>
+ prCommentThreads(
+ prUrl,
+ prTitles[prUrl] ?? `PR #${prUrl.split("/").at(-1)}`,
+ reviewByUrl.get(prUrl) ?? [],
+ conversationByUrl.get(prUrl) ?? [],
+ ),
+ );
+ return [...resourceThreads, ...prThreads].sort(byNewestActivity);
+ }, [
+ commentsQuery.data,
+ sources,
+ loadedPrUrls,
+ prTitles,
+ prReviews.byUrl,
+ prConversation.byUrl,
+ ]);
+
+ // Every source that could ever hold a thread, whether or not it has one yet.
+ // Validating against this rather than the loaded threads lets the filter
+ // follow an artifact whose comments haven't arrived, and lets the task and
+ // PR sources stay selectable while empty.
+ const knownSourceKeys = useMemo(() => {
+ const keys = new Set(
+ sources.map((source) => commentTargetKey(source.target)),
+ );
+ for (const prUrl of prUrls) keys.add(prUrl);
+ return keys;
+ }, [sources, prUrls]);
+ const stateFilteredThreads = useMemo(
+ () =>
+ threads.filter(
+ (thread) => thread.resolved === (stateFilter === "resolved"),
+ ),
+ [stateFilter, threads],
+ );
+ const sourceOptions = useMemo(
+ () =>
+ threadSourceOptions(stateFilteredThreads, [
+ ...sources.map((source) => ({
+ key: commentTargetKey(source.target),
+ label: source.name,
+ kind: source.kind,
+ })),
+ ...prUrls.map((prUrl) => ({
+ key: prUrl,
+ label: prTitles[prUrl] ?? `PR #${prUrl.split("/").at(-1)}`,
+ kind: "pr" as const,
+ })),
+ ]),
+ [prTitles, prUrls, sources, stateFilteredThreads],
+ );
+ const effectiveSourceFilter =
+ sourceFilter === ALL_SOURCES || knownSourceKeys.has(sourceFilter)
+ ? sourceFilter
+ : ALL_SOURCES;
+ const sourceLabel =
+ effectiveSourceFilter === ALL_SOURCES
+ ? "All sources"
+ : (sourceOptions.find((option) => option.key === effectiveSourceFilter)
+ ?.label ?? "All sources");
+
+ // Follow the artifact on screen until the reader picks a source themselves;
+ // after that the filter is theirs, not the pane's.
+ useEffect(() => {
+ if (onlySource || sourceFilterTouched.current) return;
+ setSourceFilter(
+ activeArtifactId
+ ? commentTargetKey({ scope: "task_artifact", itemId: activeArtifactId })
+ : ALL_SOURCES,
+ );
+ }, [activeArtifactId, onlySource]);
+
+ const inSource = (thread: TaskCommentThread) =>
+ effectiveSourceFilter === ALL_SOURCES ||
+ thread.sourceKey === effectiveSourceFilter;
+ const scoped = threads.filter(inSource);
+ const openCount = scoped.filter((thread) => !thread.resolved).length;
+ const resolvedCount = scoped.length - openCount;
+ const visibleThreads = stateFilteredThreads.filter(inSource);
+
+ const openThread = useCallback(
+ (thread: TaskCommentThread, requestThreadFocus = true) => {
+ const origin = thread.origin;
+ if (origin.kind === "pr-review" || origin.kind === "pr-conversation") {
+ openPrInReview(task.id, origin.prUrl);
+ if (origin.kind === "pr-review") {
+ // The review pane scrolls by file; a specific comment is as close as it
+ // gets until it grows a per-thread target.
+ useReviewNavigationStore
+ .getState()
+ .requestScrollToFile(task.id, origin.filePath);
+ }
+ return;
+ }
+ const { source, root } = origin;
+ if (source.kind === "canvas") {
+ if (requestThreadFocus) {
+ requestCommentFocus(task.id, source.target, root.id);
+ }
+ if (onCanvasCommentOpen) {
+ onCanvasCommentOpen(
+ readCommentContext(root)?.canvasVersionId ?? null,
+ );
+ return;
+ }
+ canvasArtifactOpenHandler(source.url)?.();
+ return;
+ }
+ // A thread on the task itself has nowhere else to open because it lives here.
+ if (source.kind === "task" || !source.runId) return;
+ openArtifactTab(task.id, {
+ runId: source.runId,
+ artifactId: source.target.itemId,
+ name: source.name,
+ });
+ if (requestThreadFocus) {
+ requestCommentFocus(task.id, source.target, root.id);
+ }
+ },
+ [onCanvasCommentOpen, openArtifactTab, requestCommentFocus, task.id],
+ );
+
+ // A thread picked on the artifact itself has to surface here, even when a
+ // filter is hiding it. Each request is honoured once, by nonce: resolving the
+ // focused thread later must not drag the filters along with it.
+ const focusedThreadId = focus?.threadId ?? null;
+ const handledFocusRef = useRef<string | null>(null);
+ useEffect(() => {
+ const focusKey = focus ? `${task.id}:${focus.nonce}` : null;
+ if (!focus || handledFocusRef.current === focusKey) return;
+ const focused = threads.find((thread) => thread.id === focus.threadId);
+ // The thread may still be loading, so wait rather than guess its filters.
+ if (!focused) return;
+ handledFocusRef.current = focusKey;
+ setStateFilter(focused.resolved ? "resolved" : "open");
+ setSourceFilter((current) =>
+ current === ALL_SOURCES || current === focused.sourceKey
+ ? current
+ : ALL_SOURCES,
+ );
+ setPulseThreadId(focus.threadId);
+ openThread(focused, false);
+ requestAnimationFrame(() => {
+ document
+ .querySelector(
+ `[data-comment-thread-id="${CSS.escape(focus.threadId)}"]`,
+ )
+ ?.scrollIntoView({ behavior: "smooth", block: "nearest" });
+ });
+ }, [focus, openThread, threads, task.id]);
+ // The pulse fades on its own; owning the timer in its own effect keeps it
+ // cleaned up on the next pulse or on unmount, without a stray ref.
+ useEffect(() => {
+ if (!pulseThreadId) return;
+ const timer = setTimeout(() => setPulseThreadId(null), PULSE_MS);
+ return () => clearTimeout(timer);
+ }, [pulseThreadId]);
+
+ const loading =
+ commentsQuery.isLoading || prConversation.isLoading || prReviews.isLoading;
+ const loadFailed =
+ commentsQuery.isError || prConversation.isError || prReviews.isError;
+
+ return (
+ // The parent scrolls the middle; the filters and the composer are pinned so
+ // they stay reachable however long the thread list grows.
+ <div className="flex h-full min-h-0 flex-col">
+ <header className="sticky top-0 z-10 flex shrink-0 items-center justify-end gap-1 bg-gray-1 px-2 py-2">
+ {!onlySource && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ size="sm"
+ aria-label="Filter by source"
+ title={sourceLabel}
+ >
+ <span className="max-w-40 truncate">{sourceLabel}</span>
+ <CaretDownIcon />
+ </Button>
+ }
+ />
+ {/* Wide, single-line rows: the label truncates at the end (with the
+ full name on hover) and the count is pinned right with the shared
+ ml-auto idiom, so a long PR title stays legible and aligned. */}
+ <DropdownMenuContent align="end" sideOffset={6} className="w-80">
+ <DropdownMenuRadioGroup
+ value={sourceFilter}
+ onValueChange={(value) => {
+ sourceFilterTouched.current = value !== ALL_SOURCES;
+ setSourceFilter(value);
+ }}
+ >
+ <DropdownMenuRadioItem value={ALL_SOURCES} className="gap-2">
+ <FunnelSimpleIcon
+ size={12}
+ className="shrink-0 text-gray-11"
+ />
+ <span className="min-w-0 truncate">All sources</span>
+ <span className="ml-auto shrink-0 pl-3 text-muted-foreground tabular-nums">
+ {stateFilteredThreads.length}
+ </span>
+ </DropdownMenuRadioItem>
+ {sourceOptions.map((option) => (
+ <DropdownMenuRadioItem
+ key={option.key}
+ value={option.key}
+ title={option.label}
+ className="gap-2"
+ >
+ {sourceIcon(option.kind, option.label)}
+ <span className="min-w-0 truncate">{option.label}</span>
+ <span className="ml-auto shrink-0 pl-3 text-muted-foreground tabular-nums">
+ {option.count}
+ </span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button size="sm" aria-label="Filter comments">
+ {stateFilter === "open" ? "Open" : "Resolved"}
+ <CaretDownIcon />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" sideOffset={6}>
+ <DropdownMenuRadioGroup
+ value={stateFilter}
+ onValueChange={(value) => setStateFilter(value as StateFilter)}
+ >
+ <DropdownMenuRadioItem value="open">
+ Open ({openCount})
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="resolved">
+ Resolved ({resolvedCount})
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </header>
+ <div className="min-h-0 flex-1 space-y-2 overflow-y-auto px-2 pt-3 pb-2">
+ {loadFailed ? (
+ <Empty className="py-8">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <ChatCircleIcon />
+ </EmptyMedia>
+ <EmptyTitle>Couldn't load comments</EmptyTitle>
+ <EmptyDescription>
+ Refresh the page to try again.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : loading && threads.length === 0 ? (
+ <div className="flex justify-center py-8">
+ <Spinner />
+ </div>
+ ) : visibleThreads.length === 0 ? (
+ <Empty className="py-8">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <ChatCircleIcon />
+ </EmptyMedia>
+ <EmptyTitle>
+ No {stateFilter === "open" ? "open" : "resolved"} comments
+ </EmptyTitle>
+ <EmptyDescription>
+ {stateFilter === "open"
+ ? onlySource
+ ? "Comment on this canvas to start a thread."
+ : "Comment on the task below, or open an artifact and select text to start a thread there."
+ : "Resolved threads will appear here."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ visibleThreads.map((thread) =>
+ thread.origin.kind === "resource" ? (
+ <ResourceThreadRow
+ key={thread.id}
+ thread={thread}
+ source={thread.origin.source}
+ root={thread.origin.root}
+ taskId={task.id}
+ members={members}
+ selected={thread.id === focusedThreadId}
+ pulsing={thread.id === pulseThreadId}
+ resolution={resolutionsByTarget[thread.sourceKey]?.get(
+ thread.id,
+ )}
+ onOpen={() => openThread(thread)}
+ showSource={!onlySource}
+ commentVersionLabel={commentVersionLabel}
+ />
+ ) : (
+ <PrThreadRow
+ key={thread.id}
+ thread={thread}
+ selected={thread.id === focusedThreadId}
+ pulsing={thread.id === pulseThreadId}
+ onOpen={() => openThread(thread)}
+ />
+ ),
+ )
+ )}
+ </div>
+ <footer className="sticky bottom-0 shrink-0 border-border border-t bg-background p-2">
+ <CommentComposer
+ value={draft}
+ onValueChange={setDraft}
+ onSubmit={async (content, mentions) => {
+ await createComment.mutateAsync({
+ content,
+ context: {
+ anchor: { kind: "document" },
+ ...(canvasVersionId ? { canvasVersionId } : {}),
+ },
+ mentions,
+ });
+ setDraft("");
+ // Show the thread that was just opened: open state, and a source
+ // filter that isn't hiding the task's own comments.
+ setStateFilter("open");
+ if (
+ sourceFilter !== ALL_SOURCES &&
+ sourceFilter !== composerSourceKey
+ ) {
+ setSourceFilter(ALL_SOURCES);
+ }
+ }}
+ members={members}
+ placeholder={`Comment on this ${onlySource ? "canvas" : "task"}… Type @ to mention someone`}
+ rows={2}
+ disabled={createComment.isPending}
+ />
+ </footer>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.ts b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.ts
new file mode 100644
index 000000000000..2647f423249d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.ts
@@ -0,0 +1,36 @@
+import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";
+import { describe, expect, it } from "vitest";
+import {
+ activityUnreadTotalForLabel,
+ getVisibleActivityItems,
+ markLoadedReadLabel,
+} from "./activityFeed";
+
+describe("activityFeed", () => {
+ it("hides comment activity without hiding existing task mentions", () => {
+ const taskMention = {
+ id: "task-mention",
+ activityKind: "mention",
+ } as TaskActivityItem;
+ const commentMention = {
+ id: "comment-mention",
+ activityKind: "mention",
+ commentId: "comment-1",
+ } as TaskActivityItem;
+
+ expect(
+ getVisibleActivityItems([taskMention, commentMention], false),
+ ).toEqual([taskMention]);
+ });
+
+ it("labels a partial read action as visible only", () => {
+ const total = activityUnreadTotalForLabel({
+ commentsEnabled: false,
+ unreadCount: 8,
+ loadedVisibleUnread: 3,
+ hasNextPage: true,
+ });
+
+ expect(markLoadedReadLabel(3, total)).toBe("Mark visible as read");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts
index 8cb1d13cd415..b1bd9aaf540e 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts
+++ b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts
@@ -6,10 +6,18 @@ export function getUnreadActivityItems(
return items.filter((item) => item.isUnread);
}
+export function getVisibleActivityItems(
+ items: TaskActivityItem[],
+ commentsEnabled: boolean,
+): TaskActivityItem[] {
+ return commentsEnabled ? items : items.filter((item) => !item.commentId);
+}
+
export function activityReadPayload(items: TaskActivityItem[]) {
return items.map((item) => ({
task_id: item.taskId,
seen_before: item.activityAt,
+ ...(item.commentId ? { activity_id: item.id } : {}),
}));
}
@@ -21,3 +29,18 @@ export function markLoadedReadLabel(
? "Mark all as read"
: "Mark visible as read";
}
+
+export function activityUnreadTotalForLabel({
+ commentsEnabled,
+ unreadCount,
+ loadedVisibleUnread,
+ hasNextPage,
+}: {
+ commentsEnabled: boolean;
+ unreadCount: number;
+ loadedVisibleUnread: number;
+ hasNextPage: boolean;
+}): number {
+ if (commentsEnabled) return unreadCount;
+ return loadedVisibleUnread + (hasNextPage ? 1 : 0);
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
new file mode 100644
index 000000000000..dddef1dd5c27
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
@@ -0,0 +1,201 @@
+import {
+ OUTPUT_ARTIFACT_TYPES,
+ parseRunArtifacts,
+ type RunArtifact,
+} from "@posthog/core/canvas/runArtifactSchemas";
+import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
+import {
+ type CommentTarget,
+ commentTargetKey,
+} from "@posthog/core/comments/anchors";
+import { readPrUrls } from "@posthog/shared";
+import type {
+ Task,
+ TaskRun,
+ TaskThreadMessage,
+} from "@posthog/shared/domain-types";
+import { parseHttpsUrl, parseShareLink } from "@posthog/ui/utils/posthogLinks";
+
+export type ArtifactRow =
+ | { kind: "pr"; key: string; url: string }
+ | {
+ kind: "canvas";
+ key: string;
+ name: string;
+ url: string | null;
+ /** The canvas row id, the stable comment target (never the name). */
+ dashboardId: string | null;
+ }
+ | {
+ kind: "file";
+ key: string;
+ artifactId: string | null;
+ name: string;
+ runId: string | null;
+ size: number | undefined;
+ }
+ | { kind: "slack"; key: string; url: string };
+
+/**
+ * Somewhere a task's comment threads live. Artifacts and canvases come from the
+ * task's rows; the task itself is always one, holding the threads that belong
+ * to the work rather than to any single deliverable.
+ */
+export type CommentSource =
+ | { kind: "file"; target: CommentTarget; name: string; runId: string | null }
+ | { kind: "canvas"; target: CommentTarget; name: string; url: string | null }
+ | { kind: "task"; target: CommentTarget; name: string };
+
+export function taskCommentTarget(taskId: string): CommentTarget {
+ return { scope: "task", itemId: taskId };
+}
+
+export function commentSources(
+ taskId: string,
+ rows: ArtifactRow[],
+): CommentSource[] {
+ const sources: CommentSource[] = [
+ { kind: "task", target: taskCommentTarget(taskId), name: "This task" },
+ ];
+ const seen = new Set<string>();
+ for (const row of rows) {
+ const target = targetForRow(row);
+ if (!target || seen.has(commentTargetKey(target))) continue;
+ seen.add(commentTargetKey(target));
+ if (row.kind === "file") {
+ sources.push({ kind: "file", target, name: row.name, runId: row.runId });
+ } else if (row.kind === "canvas") {
+ sources.push({ kind: "canvas", target, name: row.name, url: row.url });
+ }
+ }
+ return sources;
+}
+
+/** The canvas's stable row id, recovered from its share link. */
+function canvasDashboardId(url: string | null): string | null {
+ if (!url) return null;
+ const parsed = parseHttpsUrl(url);
+ const target = parsed ? parseShareLink(parsed.href) : null;
+ if (target?.kind === "canvas") return target.dashboardId;
+
+ // Local development emits http:// canvas links, which are deliberately not
+ // valid external share links. Recover only the exact route's final id here;
+ // this value is used for an access-checked API query, never for navigation.
+ try {
+ const localUrl = new URL(url);
+ if (localUrl.protocol !== "http:") return null;
+ const segments = localUrl.pathname.split("/").filter(Boolean);
+ if (
+ segments.length === 4 &&
+ segments[0] === "code" &&
+ segments[1] === "canvas"
+ ) {
+ return decodeURIComponent(segments[3]);
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+/** Where a row's comments live, or null when the row can't carry any. */
+function targetForRow(row: ArtifactRow): CommentTarget | null {
+ if (row.kind === "file" && row.artifactId) {
+ return { scope: "task_artifact", itemId: row.artifactId };
+ }
+ if (row.kind === "canvas" && row.dashboardId) {
+ return { scope: "desktop_canvas", itemId: row.dashboardId };
+ }
+ return null;
+}
+
+/**
+ * Every commentable resource this task produced, once each. Artifacts and
+ * canvases share the generic comments API, differing only by scope, so a pane
+ * can hold one query over all of them — and two timeline messages naming the
+ * same canvas must not fetch it twice.
+ */
+export function commentTargets(rows: ArtifactRow[]): CommentTarget[] {
+ const byKey = new Map<string, CommentTarget>();
+ for (const row of rows) {
+ const target = targetForRow(row);
+ if (target) byKey.set(commentTargetKey(target), target);
+ }
+ return [...byKey.values()];
+}
+
+function readRunOutputs(run: TaskRun): RunArtifact[] {
+ return parseRunArtifacts(
+ (run as { artifacts?: unknown }).artifacts,
+ OUTPUT_ARTIFACT_TYPES,
+ );
+}
+
+export function buildRows(
+ task: Task,
+ timeline: ThreadTimelineRow<TaskThreadMessage>[],
+ runs: TaskRun[],
+): ArtifactRow[] {
+ const rows: ArtifactRow[] = [];
+ const seenPrUrls = new Set<string>();
+
+ const addPr = (url: string, key: string) => {
+ if (seenPrUrls.has(url)) return;
+ seenPrUrls.add(url);
+ rows.push({ kind: "pr", key, url });
+ };
+
+ for (const row of timeline) {
+ if (row.kind !== "artifact") continue;
+ if (row.artifact.kind === "pr") {
+ addPr(row.artifact.url, row.message.id);
+ } else {
+ const url = row.artifact.url;
+ rows.push({
+ kind: "canvas",
+ key: row.message.id,
+ name: row.artifact.name,
+ url,
+ dashboardId: canvasDashboardId(url),
+ });
+ }
+ }
+
+ const allRuns =
+ runs.length > 0 ? runs : task.latest_run ? [task.latest_run] : [];
+
+ // Re-uploading a file replaces it rather than adding a second one: agents
+ // revise a deliverable and upload it again under the same name, so keeping
+ // every copy would bury the current one under its own drafts.
+ const newestByName = new Map<string, { file: RunArtifact; runId: string }>();
+ for (const run of allRuns) {
+ for (const outputPr of readPrUrls(run.output)) {
+ addPr(outputPr, `output-pr:${outputPr}`);
+ }
+ for (const file of readRunOutputs(run)) {
+ if (!file.name) continue;
+ const previous = newestByName.get(file.name);
+ const isNewer =
+ !previous ||
+ (file.uploaded_at ?? "") >= (previous.file.uploaded_at ?? "");
+ if (isNewer) newestByName.set(file.name, { file, runId: run.id });
+ }
+ }
+ for (const [name, { file, runId }] of newestByName) {
+ rows.push({
+ kind: "file",
+ key: `file:${file.id ?? file.storage_path ?? name}`,
+ artifactId: file.id ?? null,
+ name,
+ runId,
+ size: file.size,
+ });
+ }
+
+ const slackUrl = task.latest_run?.state?.slack_thread_url;
+ if (typeof slackUrl === "string" && slackUrl) {
+ rows.push({ kind: "slack", key: "slack-thread", url: slackUrl });
+ }
+
+ return rows;
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.test.ts b/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.test.ts
new file mode 100644
index 000000000000..08be7f9b7501
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.test.ts
@@ -0,0 +1,261 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import type { PrConversationComment, PrReviewThread } from "@posthog/shared";
+import { describe, expect, it } from "vitest";
+import type { CommentSource } from "./taskArtifactRows";
+import {
+ byNewestActivity,
+ prCommentThreads,
+ resourceCommentThreads,
+ threadSourceOptions,
+} from "./taskCommentThreads";
+
+const fileSource: CommentSource = {
+ kind: "file",
+ target: { scope: "task_artifact", itemId: "a" },
+ name: "report.md",
+ runId: "run-1",
+};
+const taskSource: CommentSource = {
+ kind: "task",
+ target: { scope: "task", itemId: "task-1" },
+ name: "This task",
+};
+
+function comment(overrides: Partial<ResourceComment>): ResourceComment {
+ return {
+ id: "c1",
+ created_by: null,
+ content: "hi",
+ created_at: "2024-01-01T00:00:00Z",
+ item_id: "a",
+ item_context: { anchor: { kind: "document" } },
+ scope: "task_artifact",
+ source_comment: null,
+ ...overrides,
+ } as ResourceComment;
+}
+
+describe("resourceCommentThreads", () => {
+ it("keeps only threads whose resource is present, tagged with it", () => {
+ const threads = resourceCommentThreads(
+ [
+ comment({ id: "c1", item_id: "a", content: "root" }),
+ comment({
+ id: "r1",
+ item_id: "a",
+ source_comment: "c1",
+ content: "reply",
+ created_at: "2024-01-01T00:01:00Z",
+ }),
+ comment({ id: "orphan", item_id: "gone", content: "no source" }),
+ ],
+ [fileSource, taskSource],
+ );
+
+ expect(threads).toHaveLength(1);
+ expect(threads[0].sourceKind).toBe("file");
+ expect(threads[0].sourceLabel).toBe("report.md");
+ expect(threads[0].entries.map((entry) => entry.body)).toEqual([
+ "root",
+ "reply",
+ ]);
+ });
+
+ // A resolve/reopen reply is thread state, not something anyone said.
+ it("drops thread-state replies from the visible entries", () => {
+ const threads = resourceCommentThreads(
+ [
+ comment({ id: "c1", content: "root" }),
+ comment({
+ id: "state",
+ source_comment: "c1",
+ content: "Resolved this thread",
+ created_at: "2024-01-01T00:02:00Z",
+ item_context: {
+ anchor: { kind: "document" },
+ threadState: "resolved",
+ },
+ }),
+ ],
+ [fileSource],
+ );
+
+ expect(threads[0].resolved).toBe(true);
+ expect(threads[0].entries).toHaveLength(1);
+ expect(threads[0].lastActivityAt).toBe("2024-01-01T00:00:00Z");
+ });
+});
+
+describe("prCommentThreads", () => {
+ const reviewThread: PrReviewThread = {
+ nodeId: "node-1",
+ isResolved: true,
+ rootId: 501,
+ filePath: "src/App.tsx",
+ comments: [
+ {
+ id: 501,
+ body: "root",
+ path: "src/App.tsx",
+ line: 3,
+ original_line: null,
+ side: "RIGHT",
+ start_line: null,
+ start_side: null,
+ diff_hunk: "",
+ user: { login: "octo", avatar_url: "http://x/a.png" },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ subject_type: "line",
+ },
+ {
+ id: 502,
+ body: "reply",
+ path: "src/App.tsx",
+ line: 3,
+ original_line: null,
+ side: "RIGHT",
+ start_line: null,
+ start_side: null,
+ diff_hunk: "",
+ user: { login: "octo", avatar_url: "" },
+ created_at: "2024-01-01T00:05:00Z",
+ updated_at: "2024-01-01T00:05:00Z",
+ subject_type: "line",
+ },
+ ],
+ };
+ const conversation: PrConversationComment = {
+ id: 900,
+ author: "octo",
+ avatarUrl: null,
+ body: "lgtm",
+ createdAt: "2024-01-02T00:00:00Z",
+ url: "https://github.com/a/b/pull/7#c",
+ };
+
+ it("carries review-thread replies, resolution and the reply/resolve ids", () => {
+ const [thread] = prCommentThreads("url", "PR #7", [reviewThread], []);
+
+ expect(thread.entries.map((entry) => entry.body)).toEqual([
+ "root",
+ "reply",
+ ]);
+ expect(thread.resolved).toBe(true);
+ expect(thread.origin).toMatchObject({
+ kind: "pr-review",
+ rootCommentId: 501,
+ threadNodeId: "node-1",
+ filePath: "src/App.tsx",
+ });
+ expect(thread.lastActivityAt).toBe("2024-01-01T00:05:00Z");
+ });
+
+ it("makes each conversation comment its own unresolvable thread", () => {
+ const [thread] = prCommentThreads("url", "PR #7", [], [conversation]);
+
+ expect(thread.entries).toHaveLength(1);
+ expect(thread.resolved).toBe(false);
+ expect(thread.origin.kind).toBe("pr-conversation");
+ });
+
+ it("omits GitHub bot comments without hiding human threads", () => {
+ const botRoot = {
+ ...reviewThread,
+ nodeId: "bot-root",
+ comments: reviewThread.comments.map((comment) => ({
+ ...comment,
+ user: { ...comment.user, isBot: true },
+ })),
+ };
+ const humanRootWithBotReply = {
+ ...reviewThread,
+ nodeId: "human-root",
+ comments: [
+ reviewThread.comments[0],
+ {
+ ...reviewThread.comments[1],
+ user: { ...reviewThread.comments[1].user, isBot: true },
+ },
+ ],
+ };
+
+ const threads = prCommentThreads(
+ "url",
+ "PR #7",
+ [botRoot, humanRootWithBotReply],
+ [conversation, { ...conversation, id: 901, isBot: true }],
+ );
+
+ expect(threads).toHaveLength(2);
+ expect(
+ threads.map((thread) => thread.entries.map((entry) => entry.body)),
+ ).toEqual([["root"], ["lgtm"]]);
+ });
+});
+
+describe("threadSourceOptions / byNewestActivity", () => {
+ it("lists each source once and sorts newest first", () => {
+ const threads = [
+ ...resourceCommentThreads(
+ [comment({ id: "c1", content: "old" })],
+ [fileSource],
+ ),
+ ...prCommentThreads(
+ "url",
+ "PR #7",
+ [],
+ [
+ {
+ id: 1,
+ author: "octo",
+ avatarUrl: null,
+ body: "new",
+ createdAt: "2025-01-01T00:00:00Z",
+ url: null,
+ },
+ ],
+ ),
+ ].sort(byNewestActivity);
+
+ expect(threads[0].entries[0].body).toBe("new");
+ // Options follow list order, which is newest-first, and carry the kind so
+ // the filter can show a matching icon.
+ expect(
+ threadSourceOptions(threads).map((option) => [option.label, option.kind]),
+ ).toEqual([
+ ["PR #7", "pr"],
+ ["report.md", "file"],
+ ]);
+ });
+
+ // The task is the one source every task has, so it sits at the top of the
+ // filter regardless of when it was last touched.
+ it("pins the task source first, keeping the rest newest-first", () => {
+ const threads = [
+ ...resourceCommentThreads(
+ [
+ comment({
+ id: "f1",
+ item_id: "a",
+ content: "file",
+ created_at: "2025-01-01T00:00:00Z",
+ }),
+ comment({
+ id: "t1",
+ item_id: "task-1",
+ scope: "task",
+ content: "task",
+ created_at: "2024-01-01T00:00:00Z",
+ }),
+ ],
+ [fileSource, taskSource],
+ ),
+ ].sort(byNewestActivity);
+
+ expect(threadSourceOptions(threads).map((option) => option.kind)).toEqual([
+ "task",
+ "file",
+ ]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts b/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts
new file mode 100644
index 000000000000..eafab64b8686
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts
@@ -0,0 +1,231 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import { commentTargetKey } from "@posthog/core/comments/anchors";
+import type { PrConversationComment, PrReviewThread } from "@posthog/shared";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import type { CommentSource } from "@posthog/ui/features/canvas/components/taskArtifactRows";
+import {
+ buildCommentThreads,
+ readCommentContext,
+} from "@posthog/ui/features/sessions/components/commentViewTypes";
+
+export type CommentEntry = {
+ id: string;
+ authorName: string;
+ /** A PostHog author, whose avatar and hue are the ones they have app-wide. */
+ user: UserBasic | null;
+ /** A GitHub author, who only comes with an avatar url. */
+ avatarUrl: string | null;
+ createdAt: string;
+ body: string;
+ /** PostHog comments carry @mention markup; GitHub bodies are markdown. */
+ format: "mentions" | "markdown";
+};
+
+/** How a thread is opened, replied to and resolved — one case per backend. */
+export type ThreadOrigin =
+ | {
+ kind: "resource";
+ source: CommentSource;
+ /** The root comment, needed to reply to and resolve the thread. */
+ root: ResourceComment;
+ }
+ | {
+ kind: "pr-review";
+ prUrl: string;
+ filePath: string;
+ /** GitHub replies target a comment id, resolution a thread node id. */
+ rootCommentId: number;
+ threadNodeId: string;
+ }
+ | { kind: "pr-conversation"; prUrl: string; url: string | null };
+
+/**
+ * One thread in the task's comment list, whichever system it came from. The
+ * list renders and sorts these; only replying, resolving and opening still care
+ * where a thread lives, which is what `origin` carries.
+ */
+export type TaskCommentThread = {
+ /** Stable across refetches: the scroll target and React key. */
+ id: string;
+ /** Groups threads for the source filter. */
+ sourceKey: string;
+ sourceLabel: string;
+ sourceKind: "file" | "canvas" | "task" | "pr";
+ entries: CommentEntry[];
+ resolved: boolean;
+ /** Newest comment in the thread, for ordering the list. */
+ lastActivityAt: string;
+ origin: ThreadOrigin;
+};
+
+function resourceAuthorName(comment: ResourceComment): string {
+ const user = comment.created_by;
+ if (!user) return "Unknown user";
+ return (
+ [user.first_name, user.last_name].filter(Boolean).join(" ") || user.email
+ );
+}
+
+function resourceEntry(comment: ResourceComment): CommentEntry {
+ return {
+ id: comment.id,
+ authorName: resourceAuthorName(comment),
+ user: comment.created_by,
+ avatarUrl: null,
+ createdAt: comment.created_at,
+ body: comment.content ?? "",
+ format: "mentions",
+ };
+}
+
+/** The task's own comment threads, tagged with the resource they belong to. */
+export function resourceCommentThreads(
+ comments: ResourceComment[],
+ sources: CommentSource[],
+): TaskCommentThread[] {
+ const byItemId = new Map<string, CommentSource>();
+ for (const source of sources) byItemId.set(source.target.itemId, source);
+
+ return buildCommentThreads(comments).flatMap((thread) => {
+ const source = thread.root.item_id
+ ? byItemId.get(thread.root.item_id)
+ : undefined;
+ if (!source) return [];
+ // A resolve/reopen reply is thread state, not something anyone said.
+ const visibleReplies = thread.replies.filter(
+ (reply) => !readCommentContext(reply)?.threadState,
+ );
+ return [
+ {
+ id: thread.root.id,
+ sourceKey: commentTargetKey(source.target),
+ sourceLabel: source.name,
+ sourceKind: source.kind,
+ entries: [thread.root, ...visibleReplies].map(resourceEntry),
+ resolved: thread.resolved,
+ lastActivityAt:
+ visibleReplies.at(-1)?.created_at ?? thread.root.created_at,
+ origin: { kind: "resource", source, root: thread.root },
+ },
+ ];
+ });
+}
+
+/**
+ * A PR's comments as threads. Inline review threads keep their replies and can
+ * be resolved; conversation comments (issue chatter, review summaries) are each
+ * a thread of one, since GitHub gives them neither replies nor resolution.
+ */
+export function prCommentThreads(
+ prUrl: string,
+ prLabel: string,
+ reviewThreads: PrReviewThread[],
+ conversation: PrConversationComment[],
+): TaskCommentThread[] {
+ const threads: TaskCommentThread[] = reviewThreads.flatMap((thread) => {
+ const root = thread.comments[0];
+ if (!root) return [];
+ const humanComments = thread.comments.filter(
+ (comment) => !comment.user.isBot,
+ );
+ if (humanComments.length === 0) return [];
+ return [
+ {
+ id: `pr-review-${thread.rootId}`,
+ sourceKey: prUrl,
+ sourceLabel: prLabel,
+ sourceKind: "pr" as const,
+ entries: humanComments.map((comment) => ({
+ id: `pr-comment-${comment.id}`,
+ authorName: comment.user.login,
+ user: null,
+ avatarUrl: comment.user.avatar_url || null,
+ createdAt: comment.created_at,
+ body: comment.body,
+ format: "markdown" as const,
+ })),
+ resolved: thread.isResolved,
+ lastActivityAt: humanComments.at(-1)?.created_at ?? root.created_at,
+ origin: {
+ kind: "pr-review" as const,
+ prUrl,
+ filePath: thread.filePath,
+ rootCommentId: thread.rootId,
+ threadNodeId: thread.nodeId,
+ },
+ },
+ ];
+ });
+
+ for (const comment of conversation) {
+ if (comment.isBot) continue;
+ threads.push({
+ // Conversation items mix issue comments and review summaries, whose ids
+ // come from different GitHub id spaces — key on the timestamp too.
+ id: `pr-conversation-${comment.id}-${comment.createdAt}`,
+ sourceKey: prUrl,
+ sourceLabel: prLabel,
+ sourceKind: "pr",
+ entries: [
+ {
+ id: `pr-conversation-${comment.id}`,
+ authorName: comment.author,
+ user: null,
+ avatarUrl: comment.avatarUrl,
+ createdAt: comment.createdAt,
+ body: comment.body,
+ format: "markdown",
+ },
+ ],
+ resolved: false,
+ lastActivityAt: comment.createdAt,
+ origin: { kind: "pr-conversation", prUrl, url: comment.url },
+ });
+ }
+
+ return threads;
+}
+
+export function byNewestActivity(
+ a: TaskCommentThread,
+ b: TaskCommentThread,
+): number {
+ return b.lastActivityAt.localeCompare(a.lastActivityAt);
+}
+
+export type SourceKind = TaskCommentThread["sourceKind"];
+export type ThreadSourceOption = {
+ key: string;
+ label: string;
+ kind: SourceKind;
+ count: number;
+};
+
+/**
+ * The available sources for the source filter, including those without a
+ * thread yet. The task itself sits at the top because every task has one.
+ */
+export function threadSourceOptions(
+ threads: TaskCommentThread[],
+ availableSources: Omit<ThreadSourceOption, "count">[] = [],
+): ThreadSourceOption[] {
+ const byKey = new Map<string, ThreadSourceOption>(
+ availableSources.map((source) => [source.key, { ...source, count: 0 }]),
+ );
+ for (const thread of threads) {
+ const source = byKey.get(thread.sourceKey);
+ if (!source) {
+ byKey.set(thread.sourceKey, {
+ key: thread.sourceKey,
+ label: thread.sourceLabel,
+ kind: thread.sourceKind,
+ count: 1,
+ });
+ } else {
+ source.count += 1;
+ }
+ }
+ return [...byKey.values()].sort(
+ (a, b) => Number(b.kind === "task") - Number(a.kind === "task"),
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useMarkTaskActivityRead.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useMarkTaskActivityRead.ts
index 4845259e8337..09c85a7a1eeb 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useMarkTaskActivityRead.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useMarkTaskActivityRead.ts
@@ -22,8 +22,17 @@ export function useMarkTaskActivityRead() {
return client.markTaskActivityRead(activities);
},
onMutate: async (activities: TaskActivityReadMarker[]) => {
- const marked = new Map(
- activities.map((activity) => [activity.task_id, activity.seen_before]),
+ const markedTasks = new Map(
+ activities.flatMap((activity) =>
+ activity.activity_id
+ ? []
+ : [[activity.task_id, activity.seen_before] as const],
+ ),
+ );
+ const markedCommentActivities = new Set(
+ activities.flatMap((activity) =>
+ activity.activity_id ? [activity.activity_id] : [],
+ ),
);
queryClient.setQueryData<InfiniteData<TaskActivityPage>>(
TASK_ACTIVITY_QUERY_KEY,
@@ -32,9 +41,13 @@ export function useMarkTaskActivityRead() {
const clearing = data.pages
.flatMap((page) => page.results)
.filter((row) => {
- const seenBefore = marked.get(row.task_id);
+ const seenBefore = markedTasks.get(row.task_id);
return (
- row.is_unread && seenBefore && row.activity_at <= seenBefore
+ row.is_unread &&
+ (markedCommentActivities.has(row.id) ||
+ (!row.latest_comment_id &&
+ !!seenBefore &&
+ row.activity_at <= seenBefore))
);
}).length;
return {
@@ -46,8 +59,11 @@ export function useMarkTaskActivityRead() {
? Math.max(0, page.unread_count - clearing)
: page.unread_count,
results: page.results.map((row) => {
- const seenBefore = marked.get(row.task_id);
- return seenBefore && row.activity_at <= seenBefore
+ const seenBefore = markedTasks.get(row.task_id);
+ return markedCommentActivities.has(row.id) ||
+ (!row.latest_comment_id &&
+ !!seenBefore &&
+ row.activity_at <= seenBefore)
? { ...row, is_unread: false }
: row;
}),
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.test.tsx
index c1f4a0075fb6..e35cfc9714b7 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.test.tsx
@@ -150,4 +150,57 @@ describe("task activity hooks", () => {
expect(hook.result.current.activity.items).toHaveLength(1);
expect(mockClient.getTaskActivity).toHaveBeenCalledOnce();
});
+
+ it("marks only the selected comment activity read", async () => {
+ const page: TaskActivityPage = {
+ results: [
+ activity({
+ id: "comment-activity-1",
+ latest_comment_id: "comment-1",
+ }),
+ activity({
+ id: "comment-activity-2",
+ latest_comment_id: "comment-2",
+ }),
+ activity({
+ id: "task-activity",
+ activity_kind: "awaiting_input",
+ latest_comment_id: null,
+ }),
+ ],
+ unread_count: 3,
+ };
+ queryClient.setQueryData(TASK_ACTIVITY_QUERY_KEY, {
+ pages: [page],
+ pageParams: [undefined],
+ });
+ mockClient.markTaskActivityRead.mockResolvedValue({
+ marked_read: 1,
+ unread_count: 1,
+ });
+
+ const hook = renderHook(() => useMarkTaskActivityRead(), { wrapper });
+ act(() => {
+ hook.result.current.mutate([
+ {
+ task_id: "task-1",
+ seen_before: "2026-07-01T10:00:00Z",
+ activity_id: "comment-activity-1",
+ },
+ ]);
+ });
+
+ await waitFor(() =>
+ expect(mockClient.markTaskActivityRead).toHaveBeenCalledOnce(),
+ );
+ const cached = queryClient.getQueryData<{
+ pages: TaskActivityPage[];
+ }>(TASK_ACTIVITY_QUERY_KEY);
+ expect(cached?.pages[0]?.results.map((row) => row.is_unread)).toEqual([
+ false,
+ true,
+ true,
+ ]);
+ expect(cached?.pages[0]?.unread_count).toBe(2);
+ });
});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.ts
index 5dd3d428ab98..0f219d499dc0 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskActivity.ts
@@ -12,9 +12,9 @@ import { TASK_ACTIVITY_QUERY_KEY } from "../task-activity/taskActivityQuery";
export { TASK_ACTIVITY_QUERY_KEY } from "../task-activity/taskActivityQuery";
/**
- * Tasks the current user is involved in — created, @-mentioned in, or messaged
- * in — one row per task, newest activity first, from the backend task-activity
- * index. Mount once per surface (sidebar badge, Activity page) — results are
+ * Task lifecycle and comment activity for the current user, newest first. Task
+ * lifecycle rows collapse per task while comment notifications remain separate.
+ * Mount once per surface (sidebar badge, Activity page); results are
* shared through the react-query cache.
*/
export function useTaskActivity(options?: { enabled?: boolean }): {
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts
index c9828e6f2544..506056a9d698 100644
--- a/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts
+++ b/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts
@@ -7,12 +7,16 @@ import { persist } from "zustand/middleware";
// Collapse and width are global user preferences (persisted) so the panel keeps
// its shape across canvases and navigation.
const DEFAULT_PANEL_WIDTH = 420;
+export type CanvasPanelTab = "chat" | "comments";
interface CanvasChatPanelState {
collapsed: boolean;
width: number;
+ tab: CanvasPanelTab;
setCollapsed: (collapsed: boolean) => void;
setWidth: (width: number) => void;
+ setTab: (tab: CanvasPanelTab) => void;
+ openComments: () => void;
}
export const useCanvasChatPanelStore = create<CanvasChatPanelState>()(
@@ -20,8 +24,11 @@ export const useCanvasChatPanelStore = create<CanvasChatPanelState>()(
(set) => ({
collapsed: false,
width: DEFAULT_PANEL_WIDTH,
+ tab: "chat",
setCollapsed: (collapsed) => set({ collapsed }),
setWidth: (width) => set({ width }),
+ setTab: (tab) => set({ tab }),
+ openComments: () => set({ collapsed: false, tab: "comments" }),
}),
{
name: "canvas-chat-panel-storage",
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx b/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx
index 8a336f8914e7..dfd7408e6d2a 100644
--- a/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx
+++ b/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx
@@ -1,18 +1,24 @@
import { Check, Code, Copy, Eye } from "@phosphor-icons/react";
-import { Flex, IconButton, Text } from "@radix-ui/themes";
-import { useState } from "react";
-import { Tooltip } from "../../../primitives/Tooltip";
+import {
+ Button,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@posthog/quill";
+import { type ReactNode, useState } from "react";
export function DocumentPreviewHeader({
label,
content,
showRendered,
onToggleRendered,
+ actions,
}: {
label: string;
content: string;
showRendered: boolean;
onToggleRendered: () => void;
+ actions?: ReactNode;
}) {
const [copied, setCopied] = useState(false);
@@ -23,42 +29,45 @@ export function DocumentPreviewHeader({
};
return (
- <Flex
- px="3"
- py="2"
- align="center"
- justify="between"
- className="shrink-0 border-b border-b-(--gray-6)"
- >
- <Text color="gray" className="font-[var(--code-font-family)] text-[13px]">
+ <div className="flex shrink-0 items-center justify-between border-b border-b-(--gray-6) px-3 py-2">
+ <span className="font-[var(--code-font-family)] text-[13px] text-muted-foreground">
{label}
- </Text>
- <Flex align="center" gap="1">
- <Tooltip content={showRendered ? "View source" : "View preview"}>
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- className="cursor-pointer"
- onClick={onToggleRendered}
- aria-label={showRendered ? "View source" : "View preview"}
- >
- {showRendered ? <Code size={14} /> : <Eye size={14} />}
- </IconButton>
+ </span>
+ <div className="flex items-center gap-1">
+ {actions}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon"
+ variant="default"
+ onClick={onToggleRendered}
+ aria-label={showRendered ? "View source" : "View preview"}
+ >
+ {showRendered ? <Code size={14} /> : <Eye size={14} />}
+ </Button>
+ }
+ />
+ <TooltipContent>
+ {showRendered ? "View source" : "View preview"}
+ </TooltipContent>
</Tooltip>
- <Tooltip content={copied ? "Copied" : "Copy source"}>
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- className="cursor-pointer"
- onClick={handleCopySource}
- aria-label="Copy source"
- >
- {copied ? <Check size={14} /> : <Copy size={14} />}
- </IconButton>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon"
+ variant="default"
+ onClick={handleCopySource}
+ aria-label="Copy source"
+ >
+ {copied ? <Check size={14} /> : <Copy size={14} />}
+ </Button>
+ }
+ />
+ <TooltipContent>{copied ? "Copied" : "Copy source"}</TooltipContent>
</Tooltip>
- </Flex>
- </Flex>
+ </div>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.test.tsx b/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.test.tsx
new file mode 100644
index 000000000000..b168517d738d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.test.tsx
@@ -0,0 +1,115 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@posthog/ui/features/canvas/components/MentionComposer", () => ({
+ MentionComposer: ({
+ value,
+ onValueChange,
+ children,
+ }: {
+ value: string;
+ onValueChange: (value: string) => void;
+ children: ReactNode;
+ }) => (
+ <div>
+ <textarea
+ aria-label="Comment draft"
+ value={value}
+ onChange={(event) => onValueChange(event.target.value)}
+ />
+ {children}
+ </div>
+ ),
+}));
+
+import { SelectionCommentOverlay } from "./SelectionCommentOverlay";
+
+describe("SelectionCommentOverlay", () => {
+ it("keeps the existing add-to-chat action available", () => {
+ render(
+ <SelectionCommentOverlay
+ selection={{
+ text: "selected",
+ fromLine: 1,
+ toLine: 1,
+ anchor: { top: 20, left: 20 },
+ }}
+ open
+ filePath="report.md"
+ onSubmit={vi.fn()}
+ onDismiss={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByLabelText("Add to chat")).toBeInTheDocument();
+ });
+ it("prevents duplicate comment creation while submitting", async () => {
+ let resolveSubmit: (() => void) | undefined;
+ const onSubmit = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveSubmit = resolve;
+ }),
+ );
+ render(
+ <SelectionCommentOverlay
+ selection={{
+ text: "selected",
+ fromLine: 1,
+ toLine: 1,
+ anchor: { top: 20, left: 20 },
+ }}
+ open
+ filePath="report.md"
+ onSubmit={onSubmit}
+ onDismiss={vi.fn()}
+ initiallyExpanded
+ members={[]}
+ />,
+ );
+
+ fireEvent.change(screen.getByLabelText("Comment draft"), {
+ target: { value: "One comment" },
+ });
+ const submit = screen.getByLabelText("Comment");
+ fireEvent.click(submit);
+ fireEvent.click(submit);
+
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(submit).toHaveAttribute("aria-disabled", "true");
+ resolveSubmit?.();
+ await waitFor(() =>
+ expect(submit).toHaveAttribute("aria-disabled", "false"),
+ );
+ });
+
+ it("keeps the draft open when comment creation fails", async () => {
+ const onDismiss = vi.fn();
+ const onSubmit = vi.fn().mockRejectedValue(new Error("offline"));
+ render(
+ <SelectionCommentOverlay
+ selection={{
+ text: "selected",
+ fromLine: 1,
+ toLine: 1,
+ anchor: { top: 20, left: 20 },
+ }}
+ open
+ filePath="report.md"
+ onSubmit={onSubmit}
+ onDismiss={onDismiss}
+ initiallyExpanded
+ members={[]}
+ />,
+ );
+
+ const editor = screen.getByLabelText("Comment draft");
+ fireEvent.change(editor, { target: { value: "Keep this draft" } });
+ fireEvent.click(screen.getByLabelText("Comment"));
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());
+ expect(editor).toHaveValue("Keep this draft");
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.tsx b/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.tsx
index 755daa1ddf9b..ccd9e28386d9 100644
--- a/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.tsx
+++ b/products/desktop/packages/ui/src/features/code-editor/components/SelectionCommentOverlay.tsx
@@ -1,9 +1,11 @@
-import { Plus } from "@phosphor-icons/react";
+import { ChatCircle, Plus } from "@phosphor-icons/react";
import { Button } from "@posthog/quill";
+import type { UserBasic } from "@posthog/shared/domain-types";
import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
import { CommentAnnotation } from "@posthog/ui/features/code-review/components/CommentAnnotation";
-import { Tooltip } from "@radix-ui/themes";
-import { useCallback, useState } from "react";
+import { CommentComposer } from "@posthog/ui/features/sessions/components/CommentComposer";
+import { Tooltip } from "@posthog/ui/primitives/Tooltip";
+import { useCallback, useEffect, useState } from "react";
import { createPortal } from "react-dom";
/** Selection state for the "select lines → add to chat" overlay. */
@@ -22,8 +24,18 @@ interface SelectionCommentOverlayProps {
selection: EditorSelection | null;
open: boolean;
filePath: string;
- onSubmit: (startLine: number, endLine: number, text: string) => void;
+ onSubmit: (
+ startLine: number,
+ endLine: number,
+ text: string,
+ mentions?: number[],
+ ) => void | Promise<void>;
onDismiss: () => void;
+ actionLabel?: string;
+ placeholder?: string;
+ showActionText?: boolean;
+ initiallyExpanded?: boolean;
+ members?: UserBasic[];
}
/**
@@ -37,6 +49,11 @@ export function SelectionCommentOverlay({
filePath,
onSubmit,
onDismiss,
+ actionLabel = "Add to chat",
+ placeholder,
+ showActionText = false,
+ initiallyExpanded = false,
+ members,
}: SelectionCommentOverlayProps) {
if (!open || !selection?.anchor) return null;
// Key by the range so a fresh selection remounts the card back to the "+".
@@ -49,6 +66,11 @@ export function SelectionCommentOverlay({
filePath={filePath}
onSubmit={onSubmit}
onDismiss={onDismiss}
+ actionLabel={actionLabel}
+ placeholder={placeholder}
+ showActionText={showActionText}
+ initiallyExpanded={initiallyExpanded}
+ members={members}
/>
);
}
@@ -60,30 +82,82 @@ function SelectionComposerCard({
filePath,
onSubmit,
onDismiss,
+ actionLabel,
+ placeholder,
+ showActionText,
+ initiallyExpanded,
+ members,
}: {
anchor: { top: number; left: number };
fromLine: number;
toLine: number;
filePath: string;
- onSubmit: (startLine: number, endLine: number, text: string) => void;
+ onSubmit: (
+ startLine: number,
+ endLine: number,
+ text: string,
+ mentions?: number[],
+ ) => void | Promise<void>;
onDismiss: () => void;
+ actionLabel: string;
+ placeholder?: string;
+ showActionText: boolean;
+ initiallyExpanded: boolean;
+ members?: UserBasic[];
}) {
- const [expanded, setExpanded] = useState(false);
- const style = { top: anchor.top + 4, left: anchor.left };
+ const [userExpanded, setUserExpanded] = useState(false);
+ const expanded = initiallyExpanded || userExpanded;
+ const [draft, setDraft] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+ const overlayWidth = expanded ? Math.min(420, window.innerWidth * 0.8) : 120;
+ const overlayHeight = expanded ? 180 : 36;
+ const style = {
+ top: Math.max(
+ 8,
+ Math.min(anchor.top + 4, window.innerHeight - overlayHeight - 8),
+ ),
+ left: Math.max(
+ 8,
+ Math.min(anchor.left, window.innerWidth - overlayWidth - 8),
+ ),
+ };
+
+ useEffect(() => {
+ const dismissOutside = (event: PointerEvent) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest("[data-selection-comment-overlay]")
+ ) {
+ return;
+ }
+ onDismiss();
+ };
+ document.addEventListener("pointerdown", dismissOutside, true);
+ return () =>
+ document.removeEventListener("pointerdown", dismissOutside, true);
+ }, [onDismiss]);
if (!expanded) {
return createPortal(
- <Tooltip content="Add to chat">
+ <Tooltip content={actionLabel}>
<Button
type="button"
variant="primary"
- size="icon-sm"
- aria-label="Add selection to chat"
+ size={showActionText ? "sm" : "icon-sm"}
+ aria-label={actionLabel}
+ data-selection-comment-overlay=""
className="fixed z-50 shadow-sm"
style={style}
- onClick={() => setExpanded(true)}
+ onClick={() => setUserExpanded(true)}
>
- <Plus size={14} weight="bold" />
+ {showActionText ? (
+ <>
+ <ChatCircle size={14} weight="bold" />
+ Comment
+ </>
+ ) : (
+ <Plus size={14} weight="bold" />
+ )}
</Button>
</Tooltip>,
document.body,
@@ -92,16 +166,42 @@ function SelectionComposerCard({
return createPortal(
<div
+ data-selection-comment-overlay=""
className="fixed z-50 w-[420px] max-w-[80vw] rounded-md border border-gray-5 bg-gray-2 shadow-lg"
style={style}
>
- <CommentAnnotation
- filePath={filePath}
- startLine={fromLine}
- endLine={toLine}
- onDismiss={onDismiss}
- onSubmitText={(text) => onSubmit(fromLine, toLine, text)}
- />
+ {members ? (
+ <div className="p-2">
+ <CommentComposer
+ value={draft}
+ onValueChange={setDraft}
+ onSubmit={async (content, mentions) => {
+ if (submitting) return;
+ setSubmitting(true);
+ try {
+ await onSubmit(fromLine, toLine, content, mentions);
+ onDismiss();
+ } finally {
+ setSubmitting(false);
+ }
+ }}
+ onCancel={onDismiss}
+ members={members}
+ placeholder={placeholder ?? "Add a comment…"}
+ rows={2}
+ disabled={submitting}
+ autoFocus
+ />
+ </div>
+ ) : (
+ <CommentAnnotation
+ filePath={filePath}
+ startLine={fromLine}
+ endLine={toLine}
+ onDismiss={onDismiss}
+ onSubmitText={(text) => onSubmit(fromLine, toLine, text)}
+ />
+ )}
</div>,
document.body,
);
diff --git a/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.test.tsx b/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.test.tsx
index 7f14fe2ee970..b6bea16ed830 100644
--- a/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.test.tsx
+++ b/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.test.tsx
@@ -18,10 +18,12 @@ vi.mock("../hooks/usePrCommentActions", () => ({
vi.mock("../../sessions/sendPromptToAgent", () => ({ sendPromptToAgent }));
-function makeComment(): PrReviewComment {
+function makeComment(
+ body = "Could this use the shared helper?",
+): PrReviewComment {
return {
id: 42,
- body: "Could this use the shared helper?",
+ body,
created_at: "2026-07-14T12:00:00Z",
user: {
login: "reviewer",
@@ -30,13 +32,13 @@ function makeComment(): PrReviewComment {
} as PrReviewComment;
}
-function makeMetadata(): PrCommentMetadata {
+function makeMetadata(body?: string): PrCommentMetadata {
return {
kind: "pr-comment",
threadId: 42,
nodeId: "thread-node",
isResolved: false,
- comments: [makeComment()],
+ comments: [makeComment(body)],
isOutdated: false,
isFileLevel: false,
startLine: 8,
@@ -45,14 +47,14 @@ function makeMetadata(): PrCommentMetadata {
};
}
-function renderThread() {
+function renderThread(body?: string) {
return render(
<Theme>
<PrCommentThread
taskId="task-1"
prUrl="https://github.com/PostHog/posthog/pull/1"
filePath="src/example.ts"
- metadata={makeMetadata()}
+ metadata={makeMetadata(body)}
/>
</Theme>,
);
@@ -66,6 +68,18 @@ describe("PrCommentThread", () => {
sendPromptToAgent.mockResolvedValue(true);
});
+ it("renders only GitHub-hosted images", () => {
+ renderThread(
+ [
+ "![GitHub image](https://user-images.githubusercontent.com/1/example.png)",
+ "![External image](https://example.com/tracking.png)",
+ ].join("\n\n"),
+ );
+
+ expect(screen.getByAltText("GitHub image")).toBeInTheDocument();
+ expect(screen.queryByAltText("External image")).toBeNull();
+ });
+
it("sends a custom chat message with the review context", async () => {
const user = userEvent.setup();
renderThread();
diff --git a/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx b/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx
index 3addfc943c40..981d3f1b003d 100644
--- a/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx
+++ b/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx
@@ -26,20 +26,14 @@ import {
useRef,
useState,
} from "react";
-import rehypeRaw from "rehype-raw";
-import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
-import type { PluggableList } from "unified";
import { isSendMessageSubmitKey } from "../../../utils/sendMessageKey";
+import { githubCommentComponents } from "../../editor/components/githubCommentImages";
+import { githubRehypePlugins } from "../../editor/components/githubMarkdownPlugins";
import { MarkdownRenderer } from "../../editor/components/MarkdownRenderer";
import { sendPromptToAgent } from "../../sessions/sendPromptToAgent";
import { usePrCommentActions } from "../hooks/usePrCommentActions";
import type { PrCommentMetadata } from "../types";
-const ghRehypePlugins: PluggableList = [
- rehypeRaw,
- [rehypeSanitize, defaultSchema],
-];
-
const MAX_COMMENT_HEIGHT = 120;
type ComposerMode = "reply" | "chat";
@@ -261,7 +255,8 @@ function CommentBody({
>
<MarkdownRenderer
content={comment.body}
- rehypePlugins={ghRehypePlugins}
+ rehypePlugins={githubRehypePlugins}
+ componentsOverride={githubCommentComponents}
/>
{!isExpanded && isOverflowing && (
<Box
@@ -524,7 +519,7 @@ export function PrCommentThread({
<div className="text-[13px] text-[var(--gray-11)] leading-relaxed">
<MarkdownRenderer
content={pendingReply}
- rehypePlugins={ghRehypePlugins}
+ rehypePlugins={githubRehypePlugins}
/>
</div>
</div>
diff --git a/products/desktop/packages/ui/src/features/editor/components/githubCommentImages.tsx b/products/desktop/packages/ui/src/features/editor/components/githubCommentImages.tsx
new file mode 100644
index 000000000000..c04cab219d58
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/githubCommentImages.tsx
@@ -0,0 +1,31 @@
+import type { Components } from "react-markdown";
+
+const GITHUB_IMAGE_HOSTS = new Set([
+ "avatars.githubusercontent.com",
+ "camo.githubusercontent.com",
+ "github.githubassets.com",
+ "private-user-images.githubusercontent.com",
+ "raw.githubusercontent.com",
+ "user-images.githubusercontent.com",
+]);
+
+export function isGitHubHostedImage(source: string | undefined): boolean {
+ if (!source) return false;
+
+ try {
+ const url = new URL(source);
+ return (
+ url.protocol === "https:" &&
+ (GITHUB_IMAGE_HOSTS.has(url.hostname) ||
+ (url.hostname === "github.com" &&
+ url.pathname.startsWith("/user-attachments/assets/")))
+ );
+ } catch {
+ return false;
+ }
+}
+
+export const githubCommentComponents: Partial<Components> = {
+ img: ({ src, alt }) =>
+ isGitHubHostedImage(src) ? <img src={src} alt={alt ?? ""} /> : null,
+};
diff --git a/products/desktop/packages/ui/src/features/editor/components/githubMarkdownPlugins.ts b/products/desktop/packages/ui/src/features/editor/components/githubMarkdownPlugins.ts
new file mode 100644
index 000000000000..400a9acf06b0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/githubMarkdownPlugins.ts
@@ -0,0 +1,14 @@
+import rehypeRaw from "rehype-raw";
+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
+import type { PluggableList } from "unified";
+
+/**
+ * GitHub comment bodies are GitHub-flavored markdown with raw HTML baked in
+ * (suggestion blocks, `<details>`, `<img>`, `<sub>`…). react-markdown drops raw
+ * HTML by default, which leaves stray `</a>` fragments in the text — so parse
+ * it with rehype-raw and sanitize what comes out.
+ */
+export const githubRehypePlugins: PluggableList = [
+ rehypeRaw,
+ [rehypeSanitize, defaultSchema],
+];
diff --git a/products/desktop/packages/ui/src/features/git-interaction/usePrDetails.ts b/products/desktop/packages/ui/src/features/git-interaction/usePrDetails.ts
index 03cc9512e97e..c049bb5c8f2e 100644
--- a/products/desktop/packages/ui/src/features/git-interaction/usePrDetails.ts
+++ b/products/desktop/packages/ui/src/features/git-interaction/usePrDetails.ts
@@ -47,6 +47,24 @@ export function usePrDetailsMap(
});
}
+/** PR titles for a set of PRs, off the same cache `usePrDetailsMap` warms. */
+export function usePrTitles(prUrls: string[]): Record<string, string> {
+ const trpc = useHostTRPC();
+ return useQueries({
+ queries: prUrls.map((prUrl) => ({
+ ...trpc.git.getPrDetailsByUrl.queryOptions({ prUrl }),
+ staleTime: 60_000,
+ retry: 1,
+ })),
+ combine: (results) =>
+ Object.fromEntries(
+ results.flatMap((result, index) =>
+ result.data?.title ? [[prUrls[index], result.data.title]] : [],
+ ),
+ ),
+ });
+}
+
export function usePrDetails(
prUrl: string | null,
options?: UsePrDetailsOptions,
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts
index 42e216a8f635..758e5672afdd 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts
+++ b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts
@@ -21,29 +21,36 @@ export function sanitizeDomain(domain: string): string {
return domain.replace(/[^a-zA-Z0-9.*:-]/g, "");
}
-export function buildCspString(csp?: McpUiResourceCsp): string {
- if (!csp) return DEFAULT_CSP;
+export function buildCspString(
+ csp?: McpUiResourceCsp,
+ scriptNonce?: string | null,
+): string {
+ if (!csp && scriptNonce === undefined) return DEFAULT_CSP;
- const resourceDomainsSuffix = csp.resourceDomains?.length
+ const resourceDomainsSuffix = csp?.resourceDomains?.length
? ` ${csp.resourceDomains.map(sanitizeDomain).join(" ")}`
: "";
const directives: string[] = [
"default-src 'none'",
- `script-src 'self' 'unsafe-inline'${resourceDomainsSuffix}`,
+ scriptNonce === undefined
+ ? `script-src 'self' 'unsafe-inline'${resourceDomainsSuffix}`
+ : scriptNonce === null
+ ? "script-src 'none'"
+ : `script-src 'nonce-${scriptNonce}'`,
`style-src 'self' 'unsafe-inline'${resourceDomainsSuffix}`,
"object-src 'none'",
"form-action 'none'",
];
- if (csp.connectDomains?.length) {
+ if (csp?.connectDomains?.length) {
const domains = csp.connectDomains.map(sanitizeDomain).join(" ");
directives.push(`connect-src ${domains}`);
} else {
directives.push("connect-src 'none'");
}
- if (csp.resourceDomains?.length) {
+ if (csp?.resourceDomains?.length) {
const domains = csp.resourceDomains.map(sanitizeDomain).join(" ");
directives.push(`img-src 'self' data: ${domains}`);
directives.push(`media-src 'self' data: ${domains}`);
@@ -53,14 +60,14 @@ export function buildCspString(csp?: McpUiResourceCsp): string {
directives.push("media-src 'self' data:");
}
- if (csp.frameDomains?.length) {
+ if (csp?.frameDomains?.length) {
const domains = csp.frameDomains.map(sanitizeDomain).join(" ");
directives.push(`frame-src ${domains}`);
} else {
directives.push("frame-src 'none'");
}
- if (csp.baseUriDomains?.length) {
+ if (csp?.baseUriDomains?.length) {
const domains = csp.baseUriDomains.map(sanitizeDomain).join(" ");
directives.push(`base-uri ${domains}`);
} else {
@@ -79,14 +86,21 @@ export function escapeAttr(str: string): string {
.replace(/>/g, "&gt;");
}
-export function buildCspMetaTag(csp?: McpUiResourceCsp): string {
- const cspString = buildCspString(csp);
+export function buildCspMetaTag(
+ csp?: McpUiResourceCsp,
+ scriptNonce?: string | null,
+): string {
+ const cspString = buildCspString(csp, scriptNonce);
return `<meta http-equiv="Content-Security-Policy" content="${escapeAttr(cspString)}">`;
}
// After any doctype, which must stay first or the frame enters quirks mode.
-export function applyCspToHtml(html: string, csp?: McpUiResourceCsp): string {
- const meta = buildCspMetaTag(csp);
+export function applyCspToHtml(
+ html: string,
+ csp?: McpUiResourceCsp,
+ scriptNonce?: string | null,
+): string {
+ const meta = buildCspMetaTag(csp, scriptNonce);
const doctype = html.match(/^\s*<!doctype[^>]*>/i);
if (doctype) {
return (
diff --git a/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts b/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts
index 4e30b343f934..9f163ec58add 100644
--- a/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts
+++ b/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts
@@ -18,7 +18,10 @@ import {
createInitialTaskLayout,
splitPanelTree,
} from "@posthog/core/panels/panelLayoutTransforms";
-import { createFileTabId } from "@posthog/core/panels/panelStoreHelpers";
+import {
+ activeArtifactId,
+ createFileTabId,
+} from "@posthog/core/panels/panelStoreHelpers";
import { findTabInTree } from "@posthog/core/panels/panelTree";
import { ANALYTICS_EVENTS, getFileExtension } from "@posthog/shared";
import {
@@ -528,3 +531,14 @@ export const usePanelLayoutStore = createWithEqualityFn<PanelLayoutStore>()(
},
),
);
+
+/**
+ * The artifact the reader is looking at, so a pane elsewhere (the task's
+ * comment list) can narrow itself to whatever is on screen.
+ */
+export function useActiveArtifactId(taskId: string): string | null {
+ return usePanelLayoutStore((state) => {
+ const layout = state.taskLayouts[taskId];
+ return layout ? activeArtifactId(layout) : null;
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/pr-review/usePrCommentsForUrls.test.ts b/products/desktop/packages/ui/src/features/pr-review/usePrCommentsForUrls.test.ts
new file mode 100644
index 000000000000..2e01a3df7368
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/pr-review/usePrCommentsForUrls.test.ts
@@ -0,0 +1,22 @@
+import type { PrConversationComment } from "@posthog/shared";
+import { describe, expect, it } from "vitest";
+import { combinePrCommentResults } from "./usePrCommentsForUrls";
+
+describe("combinePrCommentResults", () => {
+ it("keeps successful PR comments when another PR fails", () => {
+ const comment = { id: 1, body: "Looks good" } as PrConversationComment;
+ const result = combinePrCommentResults(
+ ["pr-1", "pr-2"],
+ [
+ { data: null, isLoading: false, isError: true },
+ { data: [comment], isLoading: false, isError: false },
+ ],
+ );
+
+ expect(result.byUrl).toEqual([
+ ["pr-1", []],
+ ["pr-2", [comment]],
+ ]);
+ expect(result.isError).toBe(false);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/pr-review/usePrCommentsForUrls.ts b/products/desktop/packages/ui/src/features/pr-review/usePrCommentsForUrls.ts
new file mode 100644
index 000000000000..85043859ca23
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/pr-review/usePrCommentsForUrls.ts
@@ -0,0 +1,57 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import type { PrConversationComment } from "@posthog/shared";
+import { useQueries } from "@tanstack/react-query";
+
+type PrCommentsResult = {
+ data?: PrConversationComment[] | null;
+ isLoading: boolean;
+ isError: boolean;
+};
+
+export function combinePrCommentResults(
+ prUrls: string[],
+ results: PrCommentsResult[],
+): {
+ byUrl: Array<[string, PrConversationComment[]]>;
+ isLoading: boolean;
+ isError: boolean;
+} {
+ const failed = results.filter(
+ (result) => result.isError || result.data === null,
+ ).length;
+ return {
+ byUrl: prUrls.map(
+ (prUrl, index) =>
+ [prUrl, results[index]?.data ?? []] as [
+ string,
+ PrConversationComment[],
+ ],
+ ),
+ isLoading: results.some((result) => result.isLoading),
+ isError: results.length > 0 && failed === results.length,
+ };
+}
+
+/**
+ * Conversation comments for several PRs at once. GitHub has no batch endpoint
+ * for these, so this is one request per PR — fine for the handful a task
+ * produces, and cached long enough that revisiting the pane is free.
+ *
+ * `byUrl` is a plain array of [url, comments] pairs rather than a Map so
+ * react-query's structural sharing keeps its identity stable while the data is
+ * unchanged; a Map would be a fresh object every render and defeat the memos
+ * that read it.
+ */
+export function usePrCommentsForUrls(prUrls: string[]) {
+ const trpc = useHostTRPC();
+ return useQueries({
+ queries: prUrls.map((prUrl) => ({
+ ...trpc.git.getPrComments.queryOptions({ prUrl }),
+ staleTime: 30_000,
+ placeholderData: (prev: PrConversationComment[] | null | undefined) =>
+ prev,
+ retry: 1,
+ })),
+ combine: (results) => combinePrCommentResults(prUrls, results),
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/pr-review/usePrReviewThreadsForUrls.ts b/products/desktop/packages/ui/src/features/pr-review/usePrReviewThreadsForUrls.ts
new file mode 100644
index 000000000000..e07e79ec8203
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/pr-review/usePrReviewThreadsForUrls.ts
@@ -0,0 +1,24 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import type { PrReviewThread } from "@posthog/shared";
+import { useQueries } from "@tanstack/react-query";
+
+/** Inline review threads for several PRs at once. See `usePrCommentsForUrls`. */
+export function usePrReviewThreadsForUrls(prUrls: string[]) {
+ const trpc = useHostTRPC();
+ return useQueries({
+ queries: prUrls.map((prUrl) => ({
+ ...trpc.git.getPrReviewComments.queryOptions({ prUrl }),
+ staleTime: 30_000,
+ placeholderData: (prev: PrReviewThread[] | undefined) => prev,
+ retry: 1,
+ })),
+ combine: (results) => ({
+ byUrl: prUrls.map(
+ (prUrl, index) =>
+ [prUrl, results[index]?.data ?? []] as [string, PrReviewThread[]],
+ ),
+ isLoading: results.some((result) => result.isLoading),
+ isError: results.some((result) => result.isError),
+ }),
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.test.ts b/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.test.ts
new file mode 100644
index 000000000000..0dd2fa09e557
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { useCommentNavigationStore } from "./commentNavigationStore";
+
+const artifact = { scope: "task_artifact", itemId: "a" } as const;
+const canvas = { scope: "desktop_canvas", itemId: "c" } as const;
+
+describe("commentNavigationStore", () => {
+ beforeEach(() => {
+ useCommentNavigationStore.setState({
+ focusByTask: {},
+ resolutionsByTarget: {},
+ });
+ });
+
+ // Picking the same thread again has to scroll again, so the request is the
+ // nonce rather than the thread id.
+ it("bumps the nonce for a repeated request", () => {
+ const { requestCommentFocus } = useCommentNavigationStore.getState();
+
+ requestCommentFocus("task-1", artifact, "comment-1");
+ const first = useCommentNavigationStore.getState().focusByTask["task-1"];
+ requestCommentFocus("task-1", artifact, "comment-1");
+ const second = useCommentNavigationStore.getState().focusByTask["task-1"];
+
+ expect(first?.threadId).toBe("comment-1");
+ expect(second?.nonce).toBe((first?.nonce ?? 0) + 1);
+ expect(second?.openCommentsTab).toBe(true);
+ });
+
+ it("acknowledges the tab-open request without losing durable focus", () => {
+ const { requestCommentFocus, acknowledgeCommentsTabOpen } =
+ useCommentNavigationStore.getState();
+ requestCommentFocus("task-1", artifact, "comment-1");
+ const focus = useCommentNavigationStore.getState().focusByTask["task-1"];
+
+ acknowledgeCommentsTabOpen("task-1", focus?.nonce ?? -1);
+
+ expect(
+ useCommentNavigationStore.getState().focusByTask["task-1"],
+ ).toMatchObject({
+ threadId: "comment-1",
+ openCommentsTab: false,
+ });
+ });
+
+ it("keeps each task's focus to itself", () => {
+ const { requestCommentFocus } = useCommentNavigationStore.getState();
+
+ requestCommentFocus("task-1", artifact, "comment-1");
+ requestCommentFocus("task-2", canvas, "comment-2");
+
+ const { focusByTask } = useCommentNavigationStore.getState();
+ expect(focusByTask["task-1"]?.threadId).toBe("comment-1");
+ expect(focusByTask["task-1"]?.target).toEqual(artifact);
+ expect(focusByTask["task-2"]?.threadId).toBe("comment-2");
+ });
+
+ // The surfaces recompute anchors on every scroll and resize; an unchanged
+ // result must not re-render the list that reads them.
+ it("ignores a resolution update that changes nothing", () => {
+ const { setCommentResolutions } = useCommentNavigationStore.getState();
+
+ setCommentResolutions(artifact, new Map([["comment-1", "exact"]]));
+ const first = useCommentNavigationStore.getState().resolutionsByTarget;
+ setCommentResolutions(artifact, new Map([["comment-1", "exact"]]));
+ const second = useCommentNavigationStore.getState().resolutionsByTarget;
+ setCommentResolutions(artifact, new Map([["comment-1", "orphaned"]]));
+ const third = useCommentNavigationStore.getState().resolutionsByTarget;
+
+ expect(second).toBe(first);
+ expect(third).not.toBe(second);
+ expect(third["task_artifact:a"]?.get("comment-1")).toBe("orphaned");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts b/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts
new file mode 100644
index 000000000000..25276799b7fb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts
@@ -0,0 +1,110 @@
+import {
+ type CommentTarget,
+ commentTargetKey,
+} from "@posthog/core/comments/anchors";
+import type { HighlightResolution } from "@posthog/ui/features/sessions/components/commentViewTypes";
+import { create } from "zustand";
+
+/** Which thread the task's comment surfaces are pointed at right now. */
+type CommentFocus = {
+ target: CommentTarget;
+ threadId: string;
+ /** Bumped on every request so re-picking the same thread scrolls again. */
+ nonce: number;
+ openCommentsTab: boolean;
+};
+
+interface CommentNavigationStoreState {
+ focusByTask: Record<string, CommentFocus | null>;
+ /** targetKey → threadId → resolution. Only a surface that has rendered can
+ * know this, so a missing entry means unknown, not "exact". */
+ resolutionsByTarget: Record<string, Map<string, HighlightResolution>>;
+}
+
+interface CommentNavigationStoreActions {
+ requestCommentFocus: (
+ taskId: string,
+ target: CommentTarget,
+ threadId: string,
+ ) => void;
+ setCommentResolutions: (
+ target: CommentTarget,
+ resolutions: Map<string, HighlightResolution>,
+ ) => void;
+ acknowledgeCommentsTabOpen: (taskId: string, nonce: number) => void;
+}
+
+type CommentNavigationStore = CommentNavigationStoreState &
+ CommentNavigationStoreActions;
+
+let nonce = 0;
+
+function sameResolutions(
+ current: Map<string, HighlightResolution> | undefined,
+ next: Map<string, HighlightResolution>,
+): boolean {
+ if (!current || current.size !== next.size) return false;
+ for (const [id, resolution] of next) {
+ if (current.get(id) !== resolution) return false;
+ }
+ return true;
+}
+
+/**
+ * The comment list (a tab in the activity sidebar) and the artifact surfaces (a
+ * tab in the panel layout) live in sibling React trees, so neither can reach
+ * the other's scroller. This store is the channel between them: the list writes
+ * a focus request and the surface locates the anchor, and vice versa.
+ *
+ * Focus is durable state rather than a consumed event, because an artifact tab
+ * may mount after the request is made and its comments arrive later still.
+ */
+export const useCommentNavigationStore = create<CommentNavigationStore>()(
+ (set) => ({
+ focusByTask: {},
+ resolutionsByTarget: {},
+
+ requestCommentFocus: (taskId, target, threadId) => {
+ nonce += 1;
+ set((state) => ({
+ focusByTask: {
+ ...state.focusByTask,
+ [taskId]: { target, threadId, nonce, openCommentsTab: true },
+ },
+ }));
+ },
+
+ // The surfaces recompute anchors on every scroll and resize, so an
+ // unchanged result must not become a store write the whole list re-renders on.
+ acknowledgeCommentsTabOpen: (taskId, acknowledgedNonce) =>
+ set((state) => {
+ const focus = state.focusByTask[taskId];
+ if (
+ !focus ||
+ focus.nonce !== acknowledgedNonce ||
+ !focus.openCommentsTab
+ )
+ return state;
+ return {
+ focusByTask: {
+ ...state.focusByTask,
+ [taskId]: { ...focus, openCommentsTab: false },
+ },
+ };
+ }),
+
+ setCommentResolutions: (target, resolutions) =>
+ set((state) => {
+ const key = commentTargetKey(target);
+ if (sameResolutions(state.resolutionsByTarget[key], resolutions)) {
+ return state;
+ }
+ return {
+ resolutionsByTarget: {
+ ...state.resolutionsByTarget,
+ [key]: resolutions,
+ },
+ };
+ }),
+ }),
+);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
new file mode 100644
index 000000000000..4b62468d5a4f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
@@ -0,0 +1,245 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import {
+ commentAnchorSchema,
+ type TextCommentAnchor,
+} from "@posthog/core/comments/anchors";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
+import { SelectionCommentOverlay } from "@posthog/ui/features/code-editor/components/SelectionCommentOverlay";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { artifactHtmlDocument } from "./artifactPreviewDocument";
+import {
+ type CommentLocateRequest,
+ type HighlightResolution,
+ readCommentContext,
+} from "./commentViewTypes";
+
+const BRIDGE_MARKER = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
+
+type FrameRect = {
+ top: number;
+ left: number;
+ right: number;
+ bottom: number;
+ width: number;
+ height: number;
+};
+
+function isFrameRect(value: unknown): value is FrameRect {
+ if (!value || typeof value !== "object") return false;
+ return ["top", "left", "right", "bottom", "width", "height"].every((key) => {
+ const field = (value as Record<string, unknown>)[key];
+ return typeof field === "number" && Number.isFinite(field);
+ });
+}
+
+export function AnnotatedArtifactHtml({
+ html,
+ name,
+ commentsEnabled,
+ comments,
+ activeThreadId,
+ locateRequest,
+ members,
+ onActivateThread,
+ onCreate,
+ onResolutionsChange,
+}: {
+ html: string;
+ name: string;
+ commentsEnabled: boolean;
+ comments: ResourceComment[];
+ activeThreadId: string | null;
+ locateRequest: CommentLocateRequest | null;
+ members: UserBasic[];
+ onActivateThread: (id: string) => void;
+ onCreate: (
+ anchor: TextCommentAnchor,
+ content: string,
+ mentions?: number[],
+ ) => void | Promise<void>;
+ onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
+}) {
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+ const channelRef = useRef(`artifact-comments-${crypto.randomUUID()}`);
+ const [pendingAnchor, setPendingAnchor] = useState<TextCommentAnchor | null>(
+ null,
+ );
+ const [selection, setSelection] = useState<EditorSelection | null>(null);
+ const [documentUrl, setDocumentUrl] = useState<string | null>(null);
+
+ useEffect(() => {
+ const document = artifactHtmlDocument(
+ html,
+ commentsEnabled ? channelRef.current : undefined,
+ );
+ const nextDocumentUrl = URL.createObjectURL(
+ new Blob([document], { type: "text/html" }),
+ );
+ setDocumentUrl(nextDocumentUrl);
+ return () => URL.revokeObjectURL(nextDocumentUrl);
+ }, [commentsEnabled, html]);
+
+ const bridgeItems = useMemo(
+ () =>
+ comments.flatMap((comment) => {
+ if (comment.source_comment) return [];
+ const context = readCommentContext(comment);
+ return context?.anchor.kind === "text"
+ ? [
+ {
+ id: comment.id,
+ anchor: context.anchor,
+ active: comment.id === activeThreadId,
+ },
+ ]
+ : [];
+ }),
+ [activeThreadId, comments],
+ );
+
+ const sendComments = useCallback(() => {
+ iframeRef.current?.contentWindow?.postMessage(
+ {
+ marker: BRIDGE_MARKER,
+ channel: channelRef.current,
+ type: "comments",
+ items: bridgeItems,
+ },
+ "*",
+ );
+ }, [bridgeItems]);
+
+ useEffect(() => {
+ sendComments();
+ }, [sendComments]);
+
+ const sendLocate = useCallback(() => {
+ if (!locateRequest) return;
+ iframeRef.current?.contentWindow?.postMessage(
+ {
+ marker: BRIDGE_MARKER,
+ channel: channelRef.current,
+ type: "locate",
+ id: locateRequest.id,
+ },
+ "*",
+ );
+ }, [locateRequest]);
+
+ useEffect(() => {
+ sendLocate();
+ }, [sendLocate]);
+
+ const activateThreadRef = useRef(onActivateThread);
+ const resolutionsChangeRef = useRef(onResolutionsChange);
+ const sendCommentsRef = useRef(sendComments);
+ const sendLocateRef = useRef(sendLocate);
+
+ useEffect(() => {
+ activateThreadRef.current = onActivateThread;
+ resolutionsChangeRef.current = onResolutionsChange;
+ sendCommentsRef.current = sendComments;
+ sendLocateRef.current = sendLocate;
+ }, [onActivateThread, onResolutionsChange, sendComments, sendLocate]);
+
+ useEffect(() => {
+ const receive = (event: MessageEvent) => {
+ if (event.source !== iframeRef.current?.contentWindow) return;
+ const data = event.data as Record<string, unknown> | null;
+ if (
+ !data ||
+ data.marker !== BRIDGE_MARKER ||
+ data.channel !== channelRef.current
+ ) {
+ return;
+ }
+ if (data.type === "ready") {
+ sendCommentsRef.current();
+ sendLocateRef.current();
+ return;
+ }
+ if (data.type === "open-external" && typeof data.href === "string") {
+ const url = parseHttpsUrl(data.href);
+ if (url) openExternalUrl(url.href);
+ return;
+ }
+ if (data.type === "activate" && typeof data.id === "string") {
+ activateThreadRef.current(data.id);
+ return;
+ }
+ if (data.type === "resolutions" && Array.isArray(data.items)) {
+ const resolutions = new Map<string, HighlightResolution>();
+ for (const item of data.items) {
+ if (!item || typeof item !== "object") continue;
+ const { id, status } = item as Record<string, unknown>;
+ if (
+ typeof id === "string" &&
+ (status === "exact" ||
+ status === "reanchored" ||
+ status === "orphaned")
+ ) {
+ resolutions.set(id, status);
+ }
+ }
+ resolutionsChangeRef.current(resolutions);
+ return;
+ }
+ if (data.type !== "selection" || !isFrameRect(data.triggerRect)) return;
+ const parsed = commentAnchorSchema.safeParse(data.anchor);
+ if (!parsed.success || parsed.data.kind !== "text") return;
+ const frameBox = iframeRef.current?.getBoundingClientRect();
+ if (!frameBox) return;
+ setPendingAnchor(parsed.data);
+ setSelection({
+ text: parsed.data.quote,
+ fromLine: parsed.data.start + 1,
+ toLine: parsed.data.end + 1,
+ anchor: {
+ top: frameBox.top + data.triggerRect.bottom,
+ left: Math.min(
+ frameBox.left + data.triggerRect.right + 6,
+ window.innerWidth - 440,
+ ),
+ },
+ });
+ };
+ window.addEventListener("message", receive);
+ return () => window.removeEventListener("message", receive);
+ }, []);
+
+ const dismiss = () => {
+ setPendingAnchor(null);
+ setSelection(null);
+ };
+
+ return (
+ <div className="relative size-full">
+ <iframe
+ ref={iframeRef}
+ className="size-full border-0 bg-white"
+ sandbox="allow-scripts"
+ referrerPolicy="no-referrer"
+ src={documentUrl ?? "about:blank"}
+ title={`Preview of ${name}`}
+ onLoad={sendComments}
+ />
+ <SelectionCommentOverlay
+ selection={selection}
+ open={!!selection && !!pendingAnchor}
+ filePath={name}
+ actionLabel="Add comment"
+ placeholder="Add a comment about this selection..."
+ showActionText
+ initiallyExpanded
+ members={members}
+ onDismiss={dismiss}
+ onSubmit={async (_start, _end, content, mentions) => {
+ if (pendingAnchor) await onCreate(pendingAnchor, content, mentions);
+ }}
+ />
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.test.tsx
new file mode 100644
index 000000000000..41de6bafdcaf
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.test.tsx
@@ -0,0 +1,49 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import { render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { AnnotatedArtifactImage } from "./AnnotatedArtifactImage";
+
+vi.mock("@posthog/ui/primitives/SafeImagePreview", () => ({
+ ZoomableImage: ({ overlay }: { overlay: (scale: number) => ReactNode }) =>
+ overlay(1),
+}));
+
+describe("AnnotatedArtifactImage", () => {
+ it("labels a deleted comment author neutrally", () => {
+ const comment = {
+ id: "comment-1",
+ content: "Look here",
+ created_by: null,
+ item_context: {
+ anchor: {
+ kind: "region",
+ x: 0.1,
+ y: 0.1,
+ width: 0.1,
+ height: 0.1,
+ },
+ },
+ } as unknown as ResourceComment;
+
+ render(
+ <AnnotatedArtifactImage
+ src="data:image/png;base64,"
+ name="example.png"
+ comments={[comment]}
+ activeThreadId={null}
+ locateRequest={null}
+ commenting={false}
+ members={[]}
+ onCommentingChange={vi.fn()}
+ onActivateThread={vi.fn()}
+ onCreate={vi.fn()}
+ onError={vi.fn()}
+ />,
+ );
+
+ expect(
+ screen.getByLabelText("Open comment from Deleted user"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx
new file mode 100644
index 000000000000..712e8816dd8d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx
@@ -0,0 +1,211 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import type { RegionCommentAnchor } from "@posthog/core/comments/anchors";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
+import { SelectionCommentOverlay } from "@posthog/ui/features/code-editor/components/SelectionCommentOverlay";
+import { ZoomableImage } from "@posthog/ui/primitives/SafeImagePreview";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ type CommentLocateRequest,
+ readCommentContext,
+} from "./commentViewTypes";
+
+/** Whose pin it is, for the marker's label. */
+function authorName(comment: ResourceComment): string {
+ const user = comment.created_by;
+ if (!user) return "Deleted user";
+ return (
+ [user.first_name, user.last_name].filter(Boolean).join(" ") || user.email
+ );
+}
+
+function ImageCommentCreationLayer({
+ name,
+ members,
+ onCreate,
+ onCancel,
+}: {
+ name: string;
+ members: UserBasic[];
+ onCreate: (
+ anchor: RegionCommentAnchor,
+ content: string,
+ mentions?: number[],
+ ) => void | Promise<void>;
+ onCancel: () => void;
+}) {
+ const [pendingAnchor, setPendingAnchor] =
+ useState<RegionCommentAnchor | null>(null);
+ const [selection, setSelection] = useState<EditorSelection | null>(null);
+
+ return (
+ <>
+ <button
+ type="button"
+ aria-label="Place image comment"
+ className="absolute inset-0 z-20 cursor-crosshair"
+ onClick={(event) => {
+ const box = event.currentTarget.getBoundingClientRect();
+ const keyboard = event.detail === 0;
+ const clientX = keyboard ? box.left + box.width / 2 : event.clientX;
+ const clientY = keyboard ? box.top + box.height / 2 : event.clientY;
+ const x = (clientX - box.left) / box.width;
+ const y = (clientY - box.top) / box.height;
+ const size = 0.035;
+ setPendingAnchor({
+ kind: "region",
+ x: Math.max(0, Math.min(1 - size, x - size / 2)),
+ y: Math.max(0, Math.min(1 - size, y - size / 2)),
+ width: size,
+ height: size,
+ });
+ setSelection({
+ text: "Image region",
+ fromLine: 1,
+ toLine: 1,
+ anchor: {
+ top: clientY + 4,
+ left: Math.min(clientX + 4, window.innerWidth - 440),
+ },
+ });
+ }}
+ />
+ <SelectionCommentOverlay
+ selection={selection}
+ open={!!selection && !!pendingAnchor}
+ filePath={name}
+ actionLabel="Add image comment"
+ placeholder="Add a comment about this part of the image..."
+ initiallyExpanded
+ members={members}
+ onDismiss={onCancel}
+ onSubmit={async (_start, _end, content, mentions) => {
+ if (pendingAnchor) await onCreate(pendingAnchor, content, mentions);
+ }}
+ />
+ </>
+ );
+}
+
+export function AnnotatedArtifactImage({
+ src,
+ name,
+ comments,
+ activeThreadId,
+ locateRequest,
+ commenting,
+ members,
+ onCommentingChange,
+ onActivateThread,
+ onCreate,
+ onError,
+}: {
+ src: string;
+ name: string;
+ comments: ResourceComment[];
+ activeThreadId: string | null;
+ locateRequest: CommentLocateRequest | null;
+ commenting: boolean;
+ members: UserBasic[];
+ onCommentingChange: (commenting: boolean) => void;
+ onActivateThread: (id: string) => void;
+ onCreate: (
+ anchor: RegionCommentAnchor,
+ content: string,
+ mentions?: number[],
+ ) => void | Promise<void>;
+ onError: () => void;
+}) {
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!locateRequest) return;
+ rootRef.current
+ ?.querySelector<HTMLElement>(
+ `[data-image-comment-id="${CSS.escape(locateRequest.id)}"]`,
+ )
+ ?.scrollIntoView({ behavior: "smooth", block: "center" });
+ }, [locateRequest]);
+
+ const regionComments = useMemo(
+ () =>
+ comments.flatMap((comment) => {
+ const context = readCommentContext(comment);
+ return context?.anchor.kind === "region"
+ ? [{ comment, anchor: context.anchor }]
+ : [];
+ }),
+ [comments],
+ );
+
+ // Takes the zoom scale so a pin keeps its on-screen size: the overlay is
+ // inside the transformed content, so it would otherwise grow with the image.
+ const overlay = (scale: number) => (
+ <>
+ {commenting && (
+ <ImageCommentCreationLayer
+ name={name}
+ members={members}
+ onCreate={onCreate}
+ onCancel={() => onCommentingChange(false)}
+ />
+ )}
+ <div className="pointer-events-none absolute inset-0 z-30">
+ {regionComments.map(({ comment, anchor }) => (
+ // A marker, not a quill Button: that one nudges itself down on press
+ // and keeps a dark focus ring afterwards, both of which read as a
+ // glitch on something pinned to a picture. Squaring one corner of a
+ // circle makes the teardrop, and that corner is the anchor point, so
+ // the pin hangs off the spot rather than covering it.
+ //
+ // Shell and ring are opposite ends of the grey scale, so the pin
+ // carries its own contrast onto artwork of any colour, and both steps
+ // are opaque — an avatar with transparency in it (plenty of Gravatars
+ // have) must not let the picture bleed through.
+ <button
+ key={comment.id}
+ type="button"
+ aria-label={`Open comment from ${authorName(comment)}`}
+ title={comment.content ?? "Comment"}
+ data-image-comment-id={comment.id}
+ className={`pointer-events-auto absolute flex size-8 items-center justify-center rounded-full rounded-bl-none p-1 ring-1 transition-all focus-visible:outline-(--gray-1) focus-visible:outline-2 focus-visible:outline-offset-1 ${
+ comment.id === activeThreadId
+ ? "bg-(--blue-12) ring-(--blue-10)"
+ : "bg-(--gray-12) ring-(--gray-10)"
+ }`}
+ style={{
+ left: `${anchor.x * 100}%`,
+ top: `${(anchor.y + anchor.height) * 100}%`,
+ transform: `translate(0, -100%) scale(${1 / scale})`,
+ transformOrigin: "bottom left",
+ }}
+ onClick={() => onActivateThread(comment.id)}
+ >
+ <UserAvatar
+ user={comment.created_by}
+ size="sm"
+ className="rounded-full bg-(--gray-1)"
+ />
+ </button>
+ ))}
+ </div>
+ </>
+ );
+
+ return (
+ <div
+ ref={rootRef}
+ className="relative size-full overflow-hidden bg-(--gray-2) p-4"
+ >
+ <ZoomableImage
+ src={src}
+ alt={name}
+ controls
+ overlay={overlay}
+ className="size-full"
+ onError={onError}
+ />
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
new file mode 100644
index 000000000000..c2969fe192bb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
@@ -0,0 +1,62 @@
+import { ChatCircleIcon } from "@phosphor-icons/react";
+import type { CommentTarget } from "@posthog/core/comments/anchors";
+import {
+ Button,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@posthog/quill";
+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { useState } from "react";
+import { CommentComposer } from "./CommentComposer";
+import { useCreateComment } from "./useComments";
+
+export function ArtifactDocumentCommentAction({
+ target,
+ taskId,
+ onCreated,
+}: {
+ target: CommentTarget;
+ taskId: string;
+ onCreated?: (commentId: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState("");
+ const { members } = useOrgMembers();
+ const createComment = useCreateComment(target, taskId);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={
+ <Button size="sm" variant="outline">
+ <ChatCircleIcon />
+ Comment…
+ </Button>
+ }
+ />
+ <PopoverContent align="end" sideOffset={6} className="w-96 p-2">
+ <CommentComposer
+ value={draft}
+ onValueChange={setDraft}
+ onSubmit={async (content, mentions) => {
+ const comment = await createComment.mutateAsync({
+ content,
+ context: { anchor: { kind: "document" } },
+ mentions,
+ });
+ onCreated?.(comment.id);
+ setDraft("");
+ setOpen(false);
+ }}
+ onCancel={() => setOpen(false)}
+ members={members}
+ placeholder="Comment on this artifact… Type @ to mention someone"
+ rows={2}
+ disabled={createComment.isPending}
+ autoFocus
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
index 8f2056faeec3..f358aee97585 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
@@ -1,3 +1,6 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { TooltipProvider } from "@radix-ui/react-tooltip";
import {
act,
fireEvent,
@@ -5,7 +8,16 @@ import {
screen,
waitFor,
} from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ReactNode } from "react";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type MockInstance,
+ vi,
+} from "vitest";
import { ArtifactPreview } from "./ArtifactPreview";
import {
artifactHtmlDocument,
@@ -16,7 +28,18 @@ const previewBlob = new Blob(["<h1>Artifact content</h1>"], {
type: "text/html",
});
const auth = vi.hoisted(() => ({ identity: "auth-1" as string | null }));
+const artifactComments = vi.hoisted(() => ({
+ data: [] as ResourceComment[],
+ isError: false,
+}));
+const createComment = vi.hoisted(() => vi.fn());
const useQuery = vi.hoisted(() => vi.fn());
+const commentsFlag = vi.hoisted(() => ({ enabled: true }));
+const orgMembersOptions = vi.hoisted(() => vi.fn());
+
+vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
+ useCommentsEnabled: () => commentsFlag.enabled,
+}));
vi.mock("@posthog/core/sessions/sessionService", () => ({
SESSION_SERVICE: Symbol("SESSION_SERVICE"),
@@ -35,19 +58,91 @@ vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
AUTH_SCOPED_QUERY_META: { authScoped: true },
}));
+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({
+ useOrgMembers: (options: { enabled?: boolean }) => {
+ orgMembersOptions(options);
+ return { members: [] };
+ },
+}));
+
+vi.mock("@posthog/ui/features/canvas/components/MentionComposer", () => ({
+ MentionComposer: ({
+ value,
+ onValueChange,
+ placeholder,
+ children,
+ }: {
+ value: string;
+ onValueChange: (value: string) => void;
+ placeholder?: string;
+ children: ReactNode;
+ }) => (
+ <div>
+ <textarea
+ aria-label="Comment text"
+ placeholder={placeholder}
+ value={value}
+ onChange={(event) => onValueChange(event.target.value)}
+ />
+ {children}
+ </div>
+ ),
+}));
+
vi.mock("@tanstack/react-query", () => ({
useQuery,
}));
+vi.mock("./useComments", () => ({
+ useCommentsQuery: () => ({
+ data: artifactComments.data,
+ isLoading: false,
+ isError: artifactComments.isError,
+ }),
+ useCreateComment: () => ({ mutateAsync: createComment, isPending: false }),
+}));
+
vi.mock("../../code-editor/components/CodeMirrorEditor", () => ({
CodeMirrorEditor: ({ content }: { content: string }) => (
<div data-testid="source-view">{content}</div>
),
}));
+function textComment(): ResourceComment {
+ return {
+ id: "comment-1",
+ created_by: null,
+ content: "Tighten this summary",
+ created_at: "2026-01-01T00:00:00Z",
+ item_id: "artifact-1",
+ item_context: {
+ anchor: {
+ kind: "text",
+ quote: "Report",
+ prefix: "# ",
+ suffix: "",
+ start: 2,
+ end: 8,
+ },
+ },
+ scope: "task_artifact",
+ source_comment: null,
+ completed_at: null,
+ };
+}
+
describe("ArtifactPreview", () => {
beforeEach(() => {
+ commentsFlag.enabled = true;
auth.identity = "auth-1";
+ useCommentNavigationStore.setState({
+ focusByTask: {},
+ resolutionsByTarget: {},
+ });
+ artifactComments.data = [];
+ artifactComments.isError = false;
+ createComment.mockReset();
+ createComment.mockResolvedValue({ id: "created-comment" });
useQuery.mockReset();
useQuery.mockReturnValue({
data: previewBlob,
@@ -83,6 +178,29 @@ describe("ArtifactPreview", () => {
);
});
+ it("keeps the artifact visible when comments fail to load", () => {
+ artifactComments.isError = true;
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Couldn't load comments. Refresh to try again.",
+ );
+ expect(screen.getByText("Report")).toBeInTheDocument();
+ });
+
it("disables preview fetching without an authenticated identity", () => {
auth.identity = null;
render(
@@ -99,7 +217,15 @@ describe("ArtifactPreview", () => {
);
});
- it("shows artifact content in a fully sandboxed iframe", () => {
+ it("renders authored HTML in an opaque-origin annotation iframe", () => {
+ useQuery.mockReturnValue({
+ data: {
+ kind: "html",
+ html: "<style>h1{color:red}</style><h1>Artifact content</h1>",
+ },
+ isLoading: false,
+ isError: false,
+ });
render(
<ArtifactPreview
taskId="task-1"
@@ -111,6 +237,74 @@ describe("ArtifactPreview", () => {
const frame = screen.getByTitle("Preview of report.html");
expect(frame).toHaveAttribute("src", "blob:preview");
+ expect(frame).toHaveAttribute("sandbox", "allow-scripts");
+ expect(frame).toHaveAttribute("referrerpolicy", "no-referrer");
+ });
+
+ it("keeps comment controls and the HTML bridge out while comments are disabled", async () => {
+ commentsFlag.enabled = false;
+ useQuery.mockReturnValue({
+ data: { kind: "html", html: "<h1>Artifact content</h1>" },
+ isLoading: false,
+ isError: false,
+ });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.html"
+ />,
+ );
+
+ expect(orgMembersOptions).toHaveBeenLastCalledWith({ enabled: false });
+
+ expect(screen.queryByText("Comment…")).toBeNull();
+ const documentBlob = vi.mocked(URL.createObjectURL).mock.calls[0]?.[0];
+ expect(documentBlob).toBeInstanceOf(Blob);
+ await expect(
+ new Response(documentBlob as Blob).text(),
+ ).resolves.not.toContain("__POSTHOG_ARTIFACT_COMMENT_BRIDGE__");
+ });
+
+ // Same zoom-and-annotate surface as a raster image: an <img> renders SVG in a
+ // secure static mode, so it doesn't need the sandboxed-iframe fallback.
+ it("gives SVG the image controls rather than an iframe", () => {
+ useQuery.mockReturnValue({
+ data: new Blob(["<svg/>"], { type: "image/svg+xml" }),
+ isLoading: false,
+ isError: false,
+ });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="diagram.svg"
+ />,
+ );
+
+ expect(screen.getByRole("img", { name: "diagram.svg" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Zoom in" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Pin comment…" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Comment…" })).toBeTruthy();
+ expect(screen.queryByTitle("Preview of diagram.svg")).toBeNull();
+ });
+
+ it("keeps opaque formats in a fully sandboxed iframe", () => {
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.pdf"
+ />,
+ );
+
+ const frame = screen.getByTitle("Preview of report.pdf");
+ expect(frame).toHaveAttribute("src", "blob:preview");
expect(frame).toHaveAttribute("sandbox", "");
});
@@ -132,6 +326,17 @@ describe("ArtifactPreview", () => {
expect(blob.type).toBe(mimeType);
});
+ // A download often arrives untyped, and the preview picks its surface off the
+ // blob's type, so the extension has to supply it.
+ it("types an SVG blob from its filename", async () => {
+ const blob = await artifactPreviewBlob(
+ new Blob(["<svg/>"], { type: "" }),
+ "diagram.svg",
+ );
+
+ expect(blob.type).toBe("image/svg+xml");
+ });
+
it("shows working image controls instead of an iframe", () => {
useQuery.mockReturnValue({
data: new Blob(["image"], { type: "image/png" }),
@@ -202,13 +407,6 @@ describe("ArtifactPreview", () => {
);
expect(percentage).toBeGreaterThan(100);
});
-
- // react-zoom-pan-pinch never clears its ~180ms wheel-stop alignment timer
- // on unmount; fired after jsdom teardown its requestAnimationFrame call
- // crashes the run, so wait it out here.
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 250));
- });
});
it("shows the preview error when an image cannot be decoded", () => {
@@ -264,9 +462,381 @@ describe("ArtifactPreview", () => {
).toBeInTheDocument();
});
- it("blocks network subresources in HTML artifacts", () => {
+ it("creates an anchored comment from rendered Markdown text", async () => {
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+ render(
+ <TooltipProvider>
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />
+ </TooltipProvider>,
+ );
+
+ const heading = screen.getByRole("heading", { name: "Report" });
+ const range = document.createRange();
+ range.selectNodeContents(heading);
+ range.getBoundingClientRect = () => ({ bottom: 20, right: 120 }) as DOMRect;
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ fireEvent.mouseUp(heading);
+
+ fireEvent.click(await screen.findByRole("button", { name: "Add comment" }));
+ fireEvent.change(
+ screen.getByPlaceholderText("Add a comment about this selection..."),
+ { target: { value: "Tighten this title" } },
+ );
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Comment" }));
+ });
+
+ expect(createComment).toHaveBeenCalledWith({
+ content: "Tighten this title",
+ context: {
+ anchor: expect.objectContaining({ kind: "text", quote: "Report" }),
+ },
+ mentions: [],
+ });
+ });
+
+ it("dismisses the Markdown comment action when clicking away", async () => {
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+ render(
+ <TooltipProvider>
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />
+ </TooltipProvider>,
+ );
+ const heading = screen.getByRole("heading", { name: "Report" });
+ const range = document.createRange();
+ range.selectNodeContents(heading);
+ range.getBoundingClientRect = () => ({ bottom: 20, right: 120 }) as DOMRect;
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ fireEvent.mouseUp(heading);
+ expect(
+ await screen.findByRole("button", { name: "Add comment" }),
+ ).toBeTruthy();
+
+ fireEvent.pointerDown(document.body);
+
+ expect(screen.queryByRole("button", { name: "Add comment" })).toBeNull();
+ });
+
+ it("keeps the DOM selection when it collapses outside the Markdown root", async () => {
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+ render(
+ <TooltipProvider>
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />
+ </TooltipProvider>,
+ );
+ const heading = screen.getByRole("heading", { name: "Report" });
+ const range = document.createRange();
+ range.selectNodeContents(heading);
+ range.getBoundingClientRect = () => ({ bottom: 20, right: 120 }) as DOMRect;
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ fireEvent.mouseUp(heading);
+ expect(
+ await screen.findByRole("button", { name: "Add comment" }),
+ ).toBeTruthy();
+
+ // A collapsed selection elsewhere (e.g. a caret placed in an input) must
+ // close the overlay without wiping the document selection — clearing it
+ // here steals the caret and cancels in-progress drag selections.
+ window.getSelection()?.collapse(document.body, 0);
+
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Add comment" })).toBeNull(),
+ );
+ expect(window.getSelection()?.rangeCount).toBe(1);
+ });
+
+ it("does not render resolved comment highlights", () => {
+ const root: ResourceComment = {
+ id: "comment-1",
+ created_by: null,
+ content: "Review this",
+ created_at: "2026-01-01T00:00:00Z",
+ item_id: "artifact-1",
+ item_context: {
+ anchor: {
+ kind: "text",
+ quote: "Report",
+ prefix: "# ",
+ suffix: "",
+ start: 2,
+ end: 8,
+ },
+ },
+ scope: "task_artifact",
+ source_comment: null,
+ completed_at: null,
+ };
+ artifactComments.data = [
+ root,
+ {
+ ...root,
+ id: "state-1",
+ content: "Resolved this thread",
+ created_at: "2026-01-01T00:01:00Z",
+ source_comment: root.id,
+ item_context: {
+ anchor: { kind: "document" },
+ threadState: "resolved",
+ },
+ },
+ ];
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ expect(
+ screen.queryByLabelText("Open comment from Unknown user"),
+ ).toBeNull();
+ });
+
+ it("highlights a Markdown comment that arrives after the preview renders", async () => {
+ Range.prototype.getClientRects = () =>
+ [{ left: 0, top: 0, width: 40, height: 12 }] as unknown as DOMRectList;
+ try {
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+ const view = () => (
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />
+ );
+ const { rerender } = render(view());
+ expect(
+ screen.queryByLabelText("Open comment from Unknown user"),
+ ).toBeNull();
+
+ artifactComments.data = [textComment()];
+ rerender(view());
+
+ expect(
+ await screen.findByLabelText("Open comment from Unknown user"),
+ ).toHaveStyle({
+ backgroundColor: "rgba(250, 204, 21, 0.32)",
+ });
+ } finally {
+ Reflect.deleteProperty(Range.prototype, "getClientRects");
+ }
+ });
+
+ // Both directions of the cross-pane bridge, since the list and the artifact
+ // sit in sibling React trees and can only talk through the store. jsdom has
+ // no layout, so the highlight geometry and the scroll are stubbed.
+ describe("with the comment list in the sidebar", () => {
+ const rect = { left: 0, top: 0, width: 40, height: 12 } as DOMRect;
+ let scrollIntoView: MockInstance;
+
+ beforeEach(() => {
+ scrollIntoView = vi.spyOn(Element.prototype, "scrollIntoView");
+ // jsdom has no range geometry at all, so unlike the scroll (stubbed in
+ // the shared setup) the highlight rectangles have to be supplied.
+ Range.prototype.getClientRects = () => [rect] as unknown as DOMRectList;
+ artifactComments.data = [textComment()];
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(Range.prototype, "getClientRects");
+ scrollIntoView.mockRestore();
+ });
+
+ it("hands a thread picked on the artifact over to the list", async () => {
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByLabelText("Open comment from Unknown user"),
+ );
+
+ expect(
+ useCommentNavigationStore.getState().focusByTask["task-1"],
+ ).toEqual({
+ target: { scope: "task_artifact", itemId: "artifact-1" },
+ threadId: "comment-1",
+ nonce: expect.any(Number),
+ openCommentsTab: true,
+ });
+ });
+
+ it("scrolls to the anchor the list asks for", async () => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "task_artifact", itemId: "artifact-1" },
+ "comment-1",
+ );
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalled());
+ // And the thread reads as the active one on the surface.
+ const highlight = await screen.findByLabelText(
+ "Open comment from Unknown user",
+ );
+ expect(highlight).toHaveStyle({
+ backgroundColor: "rgba(250, 204, 21, 0.48)",
+ });
+ });
+
+ // A thread from another artifact must not drag this one around.
+ it("ignores a focus request aimed at a different artifact", async () => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "task_artifact", itemId: "artifact-2" },
+ "comment-1",
+ );
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ await screen.findByLabelText("Open comment from Unknown user");
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+ });
+
+ // The pane is the artifact: its threads are listed in the task's Comments
+ // tab, so nothing here may render or toggle a second list of them.
+ it("keeps the pane free of a thread list", () => {
+ // Document-anchored, so this asserts the missing list rather than tripping
+ // over jsdom's lack of range geometry for highlights.
+ artifactComments.data = [
+ { ...textComment(), item_context: { anchor: { kind: "document" } } },
+ ];
+ useQuery.mockReturnValue({
+ data: "# Report",
+ isLoading: false,
+ isError: false,
+ });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ expect(screen.queryByRole("button", { name: /comments/i })).toBeNull();
+ expect(screen.queryByText("Tighten this summary")).toBeNull();
+ });
+
+ it("preserves authored styles and injects the inline-comment bridge", () => {
+ const document = artifactHtmlDocument(
+ '<!doctype html><html><head><style>.card{color:red}</style></head><body><div class="card" style="font-size:20px">Report</div></body></html>',
+ "test-channel",
+ );
+
+ expect(document).toContain("<style>.card{color:red}</style>");
+ expect(document).toContain('style="font-size:20px"');
+ expect(document).toContain("__POSTHOG_ARTIFACT_COMMENT_BRIDGE__");
+ expect(document).toContain("posthog-artifact-comment-active");
+ expect(document).not.toContain("ph-artifact-comment-outline");
+ expect(document).toContain("💬 Comment");
+ expect(document).toContain('var CHANNEL="test-channel"');
+ expect(document).toContain('d.type==="locate"');
+ expect(document).toContain('send("open-external",{href:link.href})');
+ expect(document).toContain('target.closest("a[href]")');
+ expect(document).toContain("scrollIntoView");
+ expect(document).toContain("new MutationObserver");
+ expect(document).toContain("state.renderTimer");
+ const nonce = document.match(
+ /<script nonce="([^"]+)" data-posthog-artifact-comments>/,
+ )?.[1];
+ expect(nonce).toBeTruthy();
+ expect(document).toContain(`script-src &#39;nonce-${nonce}&#39;`);
+ expect(document).not.toContain(
+ "script-src &#39;self&#39; &#39;unsafe-inline&#39;",
+ );
+ });
+
+ it("does not parse HTML without a possible refresh directive", () => {
+ const parse = vi.spyOn(DOMParser.prototype, "parseFromString");
+
+ artifactHtmlDocument(
+ "<!doctype html><html><body><p>Report</p></body></html>",
+ "test-channel",
+ );
+
+ expect(parse).not.toHaveBeenCalled();
+ parse.mockRestore();
+ });
+
+ it("keeps sensitive capabilities blocked in HTML artifacts", () => {
const document = artifactHtmlDocument(
- '<!doctype html><img src="https://internal.example/secret">',
+ '<!doctype html><img src="https://images.example/report.png">',
);
expect(document.indexOf("Content-Security-Policy")).toBeLessThan(
@@ -274,5 +844,25 @@ describe("ArtifactPreview", () => {
);
expect(document).toContain("connect-src &#39;none&#39;");
expect(document).toContain("frame-src &#39;none&#39;");
+ expect(document).toContain("form-action &#39;none&#39;");
+ expect(document).toContain("img-src &#39;self&#39; data:");
+ expect(document).toContain("script-src &#39;none&#39;");
+ expect(document).not.toContain(
+ "script-src &#39;self&#39; &#39;unsafe-inline&#39;",
+ );
+ });
+
+ it.each([
+ '<meta http-equiv="refresh" content="0;url=https://example.com">',
+ '<META content="5; https://example.com" HTTP-EQUIV=" Refresh ">',
+ ])("removes automatic redirects from HTML artifacts", (refreshElement) => {
+ const document = artifactHtmlDocument(
+ `<!doctype html><html><head>${refreshElement}<title>Report</title></head><body><a href="https://example.com">Open report</a></body></html>`,
+ "test-channel",
+ );
+
+ expect(document.toLowerCase()).not.toContain('http-equiv="refresh"');
+ expect(document).toContain('<a href="https://example.com">Open report</a>');
+ expect(document).toContain("__POSTHOG_ARTIFACT_COMMENT_BRIDGE__");
});
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
index 36e07c41036f..7bcecee8f031 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
@@ -1,25 +1,59 @@
+import { CrosshairSimpleIcon, XIcon } from "@phosphor-icons/react";
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import {
+ type CommentAnchor,
+ type CommentTarget,
+ isSameCommentTarget,
+} from "@posthog/core/comments/anchors";
import {
SESSION_SERVICE,
type SessionService,
} from "@posthog/core/sessions/sessionService";
import { useService } from "@posthog/di/react";
-import { Spinner } from "@posthog/quill";
+import { Button, Spinner } from "@posthog/quill";
import { isAllowedImageMimeType } from "@posthog/shared";
import {
getAuthIdentity,
useAuthStateValue,
} from "@posthog/ui/features/auth/store";
import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
-import { Flex } from "@radix-ui/themes";
+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import { useQuery } from "@tanstack/react-query";
-import { useEffect, useMemo, useState } from "react";
-import { ZoomableImage } from "../../../primitives/SafeImagePreview";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { CodeMirrorEditor } from "../../code-editor/components/CodeMirrorEditor";
import { DocumentPreviewHeader } from "../../code-editor/components/DocumentPreviewHeader";
import { MarkdownDocumentPreview } from "../../code-editor/components/MarkdownDocumentPreview";
+import { AnnotatedArtifactHtml } from "./AnnotatedArtifactHtml";
+import { AnnotatedArtifactImage } from "./AnnotatedArtifactImage";
+import { ArtifactDocumentCommentAction } from "./ArtifactDocumentCommentAction";
+import { ArtifactTextAnnotations } from "./ArtifactTextAnnotations";
import { artifactPreviewBlob } from "./artifactPreviewDocument";
+import {
+ buildCommentThreads,
+ type CommentLocateRequest,
+ type HighlightResolution,
+} from "./commentViewTypes";
+import { useCommentsQuery, useCreateComment } from "./useComments";
const MARKDOWN_EXTENSIONS = new Set(["md", "mdx", "markdown"]);
+const HTML_EXTENSIONS = new Set(["html", "htm"]);
+/** SVG is excluded from the shared image allowlist because its scripts can run
+ * when it comes from a data URL. An <img> renders SVG in a secure static mode
+ * that never runs scripts, so the zoom-and-annotate surface is safe for it. */
+const SVG_MIME_TYPE = "image/svg+xml";
+const EMPTY_COMMENTS: ResourceComment[] = [];
+
+type HtmlPreview = { kind: "html"; html: string };
+type PreviewData = string | Blob | HtmlPreview;
function extension(filename: string): string {
return filename.split(".").pop()?.toLowerCase() ?? "";
@@ -33,21 +67,25 @@ function ArtifactPreviewError() {
);
}
-function ArtifactImagePreview({ src, name }: { src: string; name: string }) {
- const [hasError, setHasError] = useState(false);
-
- if (hasError) return <ArtifactPreviewError />;
+function GenericArtifactHeader({
+ name,
+ actions,
+}: {
+ name: string;
+ actions?: ReactNode;
+}) {
return (
- <ZoomableImage
- src={src}
- alt={name}
- controls
- className="size-full bg-(--gray-2) p-4"
- onError={() => setHasError(true)}
- />
+ <header className="flex h-11 shrink-0 items-center justify-between border-border border-b px-3">
+ <span className="truncate font-[var(--code-font-family)] text-[13px] text-muted-foreground">
+ {name}
+ </span>
+ {actions}
+ </header>
);
}
+/** The artifact is the whole pane: its threads are listed in the task's
+ * Comments tab, and this only renders and locates their anchors. */
export function ArtifactPreview({
taskId,
runId,
@@ -59,10 +97,31 @@ export function ArtifactPreview({
artifactId: string;
name: string;
}) {
+ const commentsEnabled = useCommentsEnabled();
const sessionService = useService<SessionService>(SESSION_SERVICE);
const [showRendered, setShowRendered] = useState(true);
+ const markdownRootRef = useRef<HTMLDivElement>(null);
+ const markdownContainerRef = useRef<HTMLDivElement>(null);
+ const [imageError, setImageError] = useState(false);
+ const [imageCommenting, setImageCommenting] = useState(false);
const authIdentity = useAuthStateValue(getAuthIdentity);
- const { data, isLoading, isError } = useQuery({
+ const commentTarget = useMemo<CommentTarget>(
+ () => ({ scope: "task_artifact", itemId: artifactId }),
+ [artifactId],
+ );
+ const commentsQuery = useCommentsQuery(commentTarget, taskId, {
+ enabled: commentsEnabled,
+ });
+ const { members } = useOrgMembers({ enabled: commentsEnabled });
+ const createComment = useCreateComment(commentTarget, taskId);
+ const requestCommentFocus = useCommentNavigationStore(
+ (state) => state.requestCommentFocus,
+ );
+ const setCommentResolutions = useCommentNavigationStore(
+ (state) => state.setCommentResolutions,
+ );
+ const focus = useCommentNavigationStore((state) => state.focusByTask[taskId]);
+ const { data, isLoading, isError } = useQuery<PreviewData>({
queryKey: ["artifactPreview", authIdentity, taskId, runId, artifactId],
queryFn: async () => {
const url = await sessionService.getCloudAttachmentPreviewUrl(
@@ -74,8 +133,10 @@ export function ArtifactPreview({
const response = await fetch(url);
if (!response.ok) throw new Error("Artifact preview failed");
const blob = await response.blob();
- if (MARKDOWN_EXTENSIONS.has(extension(name))) {
- return blob.text();
+ const fileExtension = extension(name);
+ if (MARKDOWN_EXTENSIONS.has(fileExtension)) return blob.text();
+ if (HTML_EXTENSIONS.has(fileExtension)) {
+ return { kind: "html", html: await blob.text() };
}
return artifactPreviewBlob(blob, name);
},
@@ -88,6 +149,22 @@ export function ArtifactPreview({
() => (data instanceof Blob ? URL.createObjectURL(data) : null),
[data],
);
+ const comments = commentsEnabled
+ ? (commentsQuery.data ?? EMPTY_COMMENTS)
+ : EMPTY_COMMENTS;
+ const commentLoadError = commentsEnabled && commentsQuery.isError && (
+ <div
+ role="alert"
+ className="shrink-0 border-amber-6 border-b bg-amber-2 px-3 py-2 text-amber-12 text-xs"
+ >
+ Couldn't load comments. Refresh to try again.
+ </div>
+ );
+ const threads = useMemo(() => buildCommentThreads(comments), [comments]);
+ const openRootComments = useMemo(
+ () => threads.flatMap((thread) => (thread.resolved ? [] : [thread.root])),
+ [threads],
+ );
useEffect(() => {
return () => {
@@ -95,6 +172,57 @@ export function ArtifactPreview({
};
}, [previewUrl]);
+ /** This artifact's share of the task's focus, if the focus is on it at all. */
+ const focusedThreadId =
+ focus && isSameCommentTarget(focus.target, commentTarget)
+ ? focus.threadId
+ : null;
+ const annotationComments = useMemo(() => {
+ const focusedResolvedRoot = threads.find(
+ (thread) => thread.resolved && thread.root.id === focusedThreadId,
+ )?.root;
+ return focusedResolvedRoot
+ ? [...openRootComments, focusedResolvedRoot]
+ : openRootComments;
+ }, [focusedThreadId, openRootComments, threads]);
+ // The locate request only fires once the thread exists, so it survives the
+ // comments arriving after the request — and re-fires when the nonce moves,
+ // which is how picking the same thread twice scrolls twice.
+ const [locateRequest, setLocateRequest] =
+ useState<CommentLocateRequest | null>(null);
+ useEffect(() => {
+ if (!focus || !focusedThreadId) return;
+ if (!threads.some((thread) => thread.root.id === focusedThreadId)) return;
+ setLocateRequest((current) =>
+ current?.nonce === focus.nonce
+ ? current
+ : { id: focusedThreadId, nonce: focus.nonce },
+ );
+ }, [focus, focusedThreadId, threads]);
+
+ const activateThread = useCallback(
+ (id: string) => requestCommentFocus(taskId, commentTarget, id),
+ [requestCommentFocus, taskId, commentTarget],
+ );
+
+ const onResolutionsChange = useCallback(
+ (resolutions: Map<string, HighlightResolution>) =>
+ setCommentResolutions(commentTarget, resolutions),
+ [setCommentResolutions, commentTarget],
+ );
+
+ const createAnchoredComment = useCallback(
+ async (anchor: CommentAnchor, content: string, mentions: number[] = []) => {
+ const created = await createComment.mutateAsync({
+ content,
+ context: { anchor },
+ mentions,
+ });
+ activateThread(created.id);
+ },
+ [createComment, activateThread],
+ );
+
if (isLoading) {
return (
<div className="flex h-full items-center justify-center">
@@ -102,42 +230,158 @@ export function ArtifactPreview({
</div>
);
}
+ if (isError || imageError) return <ArtifactPreviewError />;
+
if (typeof data === "string") {
return (
- <Flex direction="column" height="100%" className="overflow-hidden">
+ <div className="flex h-full flex-col overflow-hidden">
<DocumentPreviewHeader
label={name}
content={data}
showRendered={showRendered}
onToggleRendered={() => setShowRendered((rendered) => !rendered)}
+ actions={
+ commentsEnabled ? (
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ />
+ ) : undefined
+ }
/>
+ {commentLoadError}
{showRendered ? (
- <div className="flex-1 overflow-auto">
- <MarkdownDocumentPreview
- content={data}
- components={{ img: () => null }}
- />
+ <div
+ ref={markdownContainerRef}
+ className="relative min-h-0 min-w-0 flex-1 overflow-auto"
+ >
+ <div ref={markdownRootRef}>
+ <MarkdownDocumentPreview
+ content={data}
+ components={{ img: () => null }}
+ />
+ </div>
+ {commentsEnabled && (
+ <ArtifactTextAnnotations
+ artifactName={name}
+ rootRef={markdownRootRef}
+ containerRef={markdownContainerRef}
+ comments={annotationComments}
+ activeThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ members={members}
+ onActivateThread={activateThread}
+ onCreate={createAnchoredComment}
+ onResolutionsChange={onResolutionsChange}
+ />
+ )}
</div>
) : (
- <div className="flex-1 overflow-hidden">
+ <div className="min-h-0 min-w-0 flex-1 overflow-hidden">
<CodeMirrorEditor content={data} filePath={name} readOnly />
</div>
)}
- </Flex>
+ </div>
);
}
- if (isError || !previewUrl) {
- return <ArtifactPreviewError />;
+
+ if (data && !(data instanceof Blob) && data.kind === "html") {
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <GenericArtifactHeader
+ name={name}
+ actions={
+ commentsEnabled ? (
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ />
+ ) : undefined
+ }
+ />
+ {commentLoadError}
+ <div className="min-h-0 min-w-0 flex-1">
+ <AnnotatedArtifactHtml
+ html={data.html}
+ name={name}
+ commentsEnabled={commentsEnabled}
+ comments={annotationComments}
+ activeThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ members={members}
+ onActivateThread={activateThread}
+ onCreate={createAnchoredComment}
+ onResolutionsChange={onResolutionsChange}
+ />
+ </div>
+ </div>
+ );
}
- if (data && isAllowedImageMimeType(data.type)) {
- return <ArtifactImagePreview src={previewUrl} name={name} />;
+
+ if (!previewUrl || !data) return <ArtifactPreviewError />;
+
+ if (
+ data instanceof Blob &&
+ (isAllowedImageMimeType(data.type) || data.type === SVG_MIME_TYPE)
+ ) {
+ const imageActions = commentsEnabled ? (
+ <div className="flex items-center gap-1">
+ <ArtifactDocumentCommentAction target={commentTarget} taskId={taskId} />
+ <Button
+ size="sm"
+ variant={imageCommenting ? "primary" : "outline"}
+ onClick={() => setImageCommenting((commenting) => !commenting)}
+ >
+ {imageCommenting ? <XIcon /> : <CrosshairSimpleIcon />}
+ {imageCommenting ? "Cancel" : "Pin comment…"}
+ </Button>
+ </div>
+ ) : undefined;
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <GenericArtifactHeader name={name} actions={imageActions} />
+ {commentLoadError}
+ <div className="min-h-0 min-w-0 flex-1">
+ <AnnotatedArtifactImage
+ src={previewUrl}
+ name={name}
+ comments={annotationComments}
+ activeThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ commenting={commentsEnabled && imageCommenting}
+ members={members}
+ onCommentingChange={setImageCommenting}
+ onActivateThread={activateThread}
+ onCreate={createAnchoredComment}
+ onError={() => setImageError(true)}
+ />
+ </div>
+ </div>
+ );
}
+
return (
- <iframe
- className="h-full w-full border-0 bg-white"
- sandbox=""
- src={previewUrl}
- title={`Preview of ${name}`}
- />
+ <div className="flex h-full flex-col overflow-hidden">
+ <GenericArtifactHeader
+ name={name}
+ actions={
+ commentsEnabled ? (
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ />
+ ) : undefined
+ }
+ />
+ {commentLoadError}
+ <div className="min-h-0 min-w-0 flex-1">
+ <iframe
+ className="h-full w-full border-0 bg-white"
+ sandbox=""
+ src={previewUrl}
+ title={`Preview of ${name}`}
+ />
+ </div>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.test.ts b/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.test.ts
new file mode 100644
index 000000000000..3e717881df54
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.test.ts
@@ -0,0 +1,31 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import { describe, expect, it } from "vitest";
+import {
+ buildTextNodeIndex,
+ rangeFromOffsets,
+ textHighlightLabel,
+} from "./ArtifactTextAnnotations";
+
+describe("ArtifactTextAnnotations", () => {
+ it("gives each text highlight its author label", () => {
+ const comment = {
+ created_by: {
+ first_name: "Ada",
+ last_name: "Lovelace",
+ email: "[email protected]",
+ },
+ } as ResourceComment;
+
+ expect(textHighlightLabel(comment)).toBe("Open comment from Ada Lovelace");
+ });
+
+ it("resolves several ranges from one text-node index", () => {
+ const root = document.createElement("div");
+ root.innerHTML = "One <strong>two</strong> three";
+ const index = buildTextNodeIndex(root);
+
+ expect(rangeFromOffsets(index, 0, 3)?.toString()).toBe("One");
+ expect(rangeFromOffsets(index, 4, 7)?.toString()).toBe("two");
+ expect(rangeFromOffsets(index, 8, 13)?.toString()).toBe("three");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx
new file mode 100644
index 000000000000..14ad964b2dcc
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx
@@ -0,0 +1,389 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import {
+ createTextCommentAnchor,
+ resolveTextCommentAnchor,
+ type TextCommentAnchor,
+} from "@posthog/core/comments/anchors";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
+import { SelectionCommentOverlay } from "@posthog/ui/features/code-editor/components/SelectionCommentOverlay";
+import {
+ type RefObject,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import {
+ type CommentLocateRequest,
+ type HighlightResolution,
+ readCommentContext,
+} from "./commentViewTypes";
+
+type HighlightRect = {
+ id: string;
+ label: string;
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ active: boolean;
+};
+
+export function textHighlightLabel(comment: ResourceComment): string {
+ const user = comment.created_by;
+ const author = user
+ ? [user.first_name, user.last_name].filter(Boolean).join(" ") || user.email
+ : "Unknown user";
+ return `Open comment from ${author}`;
+}
+
+type TextNodeIndex = {
+ text: string;
+ entries: Array<{ node: Text; start: number; end: number }>;
+};
+
+export function buildTextNodeIndex(root: HTMLElement): TextNodeIndex {
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ const entries: TextNodeIndex["entries"] = [];
+ let text = "";
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const textNode = node as Text;
+ const start = text.length;
+ text += textNode.data;
+ entries.push({ node: textNode, start, end: text.length });
+ }
+ return { text, entries };
+}
+
+export function rangeFromOffsets(
+ index: TextNodeIndex,
+ start: number,
+ end: number,
+): Range | null {
+ let startNode: Text | null = null;
+ let endNode: Text | null = null;
+ let startOffset = 0;
+ let endOffset = 0;
+ for (const entry of index.entries) {
+ if (!startNode && start >= entry.start && start <= entry.end) {
+ startNode = entry.node;
+ startOffset = start - entry.start;
+ }
+ if (end >= entry.start && end <= entry.end) {
+ endNode = entry.node;
+ endOffset = end - entry.start;
+ break;
+ }
+ }
+ if (!startNode || !endNode) return null;
+ const range = document.createRange();
+ range.setStart(startNode, startOffset);
+ range.setEnd(endNode, endOffset);
+ return range;
+}
+
+// Range.getClientRects() reports both an inline element's border box and its
+// inner text nodes when the element is fully selected (e.g. <strong> inside a
+// highlighted line), so translucent highlight rects stack and look doubled.
+// Keep only rects not contained by another rect.
+function dedupeClientRects(rects: Iterable<DOMRect>): DOMRect[] {
+ const EPSILON = 0.5;
+ const contains = (outer: DOMRect, inner: DOMRect) =>
+ outer.left <= inner.left + EPSILON &&
+ outer.right >= inner.right - EPSILON &&
+ outer.top <= inner.top + EPSILON &&
+ outer.bottom >= inner.bottom - EPSILON;
+ const list = Array.from(rects).filter(
+ (rect) => rect.width > 0 && rect.height > 0,
+ );
+ return list.filter(
+ (rect, index) =>
+ !list.some(
+ (other, otherIndex) =>
+ otherIndex !== index &&
+ contains(other, rect) &&
+ // Of two identical rects, keep the first.
+ (otherIndex < index || !contains(rect, other)),
+ ),
+ );
+}
+
+function selectionOffsets(root: HTMLElement, range: Range) {
+ const before = document.createRange();
+ before.selectNodeContents(root);
+ before.setEnd(range.startContainer, range.startOffset);
+ const through = document.createRange();
+ through.selectNodeContents(root);
+ through.setEnd(range.endContainer, range.endOffset);
+ return { start: before.toString().length, end: through.toString().length };
+}
+
+interface ArtifactTextAnnotationsProps {
+ artifactName: string;
+ rootRef: RefObject<HTMLElement | null>;
+ containerRef: RefObject<HTMLElement | null>;
+ comments: ResourceComment[];
+ activeThreadId: string | null;
+ locateRequest: CommentLocateRequest | null;
+ members: UserBasic[];
+ onActivateThread: (id: string) => void;
+ onCreate: (
+ anchor: TextCommentAnchor,
+ content: string,
+ mentions?: number[],
+ ) => void | Promise<void>;
+ onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
+}
+
+export function ArtifactTextAnnotations({
+ artifactName,
+ rootRef,
+ containerRef,
+ comments,
+ activeThreadId,
+ locateRequest,
+ members,
+ onActivateThread,
+ onCreate,
+ onResolutionsChange,
+}: ArtifactTextAnnotationsProps) {
+ const [selection, setSelection] = useState<EditorSelection | null>(null);
+ const [pendingAnchor, setPendingAnchor] = useState<TextCommentAnchor | null>(
+ null,
+ );
+ const [rects, setRects] = useState<HighlightRect[]>([]);
+ const textIndexRef = useRef<TextNodeIndex | null>(null);
+ const firstRectByThread = useMemo(() => {
+ const first = new Map<string, number>();
+ rects.forEach((rect, index) => {
+ if (!first.has(rect.id)) first.set(rect.id, index);
+ });
+ return first;
+ }, [rects]);
+
+ const clearOverlay = useCallback(() => {
+ setSelection(null);
+ setPendingAnchor(null);
+ }, []);
+
+ const dismiss = useCallback(() => {
+ clearOverlay();
+ window.getSelection()?.removeAllRanges();
+ }, [clearOverlay]);
+
+ const rootComments = useMemo(
+ () => comments.filter((comment) => !comment.source_comment),
+ [comments],
+ );
+
+ const recalculate = useCallback(() => {
+ const root = rootRef.current;
+ const container = containerRef.current;
+ if (!root || !container) return;
+ const textIndex = buildTextNodeIndex(root);
+ textIndexRef.current = textIndex;
+ const text = textIndex.text;
+ const containerBox = container.getBoundingClientRect();
+ const nextRects: HighlightRect[] = [];
+ const resolutions = new Map<string, HighlightResolution>();
+
+ for (const comment of rootComments) {
+ const context = readCommentContext(comment);
+ if (!context || context.anchor.kind !== "text") continue;
+ const resolved = resolveTextCommentAnchor(text, context.anchor);
+ if (!resolved) {
+ resolutions.set(comment.id, "orphaned");
+ continue;
+ }
+ resolutions.set(comment.id, resolved.status);
+ const range = rangeFromOffsets(textIndex, resolved.start, resolved.end);
+ if (!range) continue;
+ for (const box of dedupeClientRects(range.getClientRects())) {
+ nextRects.push({
+ id: comment.id,
+ label: textHighlightLabel(comment),
+ left: box.left - containerBox.left + container.scrollLeft,
+ top: box.top - containerBox.top + container.scrollTop,
+ width: box.width,
+ height: box.height,
+ active: comment.id === activeThreadId,
+ });
+ }
+ }
+ setRects(nextRects);
+ onResolutionsChange(resolutions);
+ }, [
+ activeThreadId,
+ containerRef,
+ onResolutionsChange,
+ rootComments,
+ rootRef,
+ ]);
+
+ const recalculateRef = useRef(recalculate);
+
+ useEffect(() => {
+ recalculateRef.current = recalculate;
+ }, [recalculate]);
+
+ useEffect(() => recalculate(), [recalculate]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ const root = rootRef.current;
+ if (!container || !root) return;
+ let frame = 0;
+ const update = () => {
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ recalculateRef.current();
+ });
+ };
+ const observer = new ResizeObserver(update);
+ const mutationObserver = new MutationObserver(update);
+ observer.observe(root);
+ mutationObserver.observe(root, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+ window.addEventListener("resize", update);
+ container.addEventListener("scroll", update, { passive: true });
+ return () => {
+ cancelAnimationFrame(frame);
+ observer.disconnect();
+ mutationObserver.disconnect();
+ window.removeEventListener("resize", update);
+ container.removeEventListener("scroll", update);
+ };
+ }, [containerRef, rootRef]);
+
+ const handledLocateNonce = useRef<number | null>(null);
+ useEffect(() => {
+ // Comment-list updates re-run this effect; without the nonce guard a new
+ // comment replays the previous locate request and yanks the scroll away.
+ if (!locateRequest || handledLocateNonce.current === locateRequest.nonce) {
+ return;
+ }
+ const root = rootRef.current;
+ const comment = rootComments.find(({ id }) => id === locateRequest.id);
+ const context = comment ? readCommentContext(comment) : null;
+ if (!root || context?.anchor.kind !== "text") return;
+ const textIndex = buildTextNodeIndex(root);
+ const resolved = resolveTextCommentAnchor(textIndex.text, context.anchor);
+ if (!resolved) return;
+ handledLocateNonce.current = locateRequest.nonce;
+ const range = rangeFromOffsets(textIndex, resolved.start, resolved.end);
+ const target = range?.startContainer.parentElement;
+ target?.scrollIntoView({ behavior: "smooth", block: "center" });
+ }, [locateRequest, rootComments, rootRef]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ const root = rootRef.current;
+ if (!container || !root) return;
+ let frame = 0;
+ const updateSelection = () => {
+ const domSelection = window.getSelection();
+ if (
+ !domSelection ||
+ domSelection.isCollapsed ||
+ domSelection.rangeCount === 0
+ ) {
+ if (
+ document.activeElement instanceof Element &&
+ document.activeElement.closest("[data-selection-comment-overlay]")
+ ) {
+ return;
+ }
+ // Only reset local overlay state here: clearing the DOM selection on
+ // every collapse would steal the caret from inputs elsewhere in the
+ // app and cancel drag-selections as they start.
+ clearOverlay();
+ return;
+ }
+ const range = domSelection.getRangeAt(0);
+ if (
+ !root.contains(range.startContainer) ||
+ !root.contains(range.endContainer)
+ ) {
+ clearOverlay();
+ return;
+ }
+ const offsets = selectionOffsets(root, range);
+ const documentText =
+ textIndexRef.current?.text ?? buildTextNodeIndex(root).text;
+ const anchor = createTextCommentAnchor(
+ documentText,
+ offsets.start,
+ offsets.end,
+ );
+ if (!anchor) return;
+ const box = range.getBoundingClientRect();
+ setPendingAnchor(anchor);
+ setSelection({
+ text: anchor.quote,
+ fromLine: offsets.start + 1,
+ toLine: offsets.end + 1,
+ anchor: {
+ top: box.bottom,
+ left: Math.min(box.right, window.innerWidth - 440),
+ },
+ });
+ };
+ const handleSelectionChange = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(updateSelection);
+ };
+ document.addEventListener("selectionchange", handleSelectionChange);
+ return () => {
+ cancelAnimationFrame(frame);
+ document.removeEventListener("selectionchange", handleSelectionChange);
+ };
+ }, [clearOverlay, containerRef, rootRef]);
+
+ return (
+ <>
+ <div className="pointer-events-none absolute inset-0 z-10">
+ {rects.map((rect, index) => (
+ <button
+ // A selection can span several DOM rectangles, hence the index.
+ key={`${rect.id}-${index}`}
+ type="button"
+ tabIndex={firstRectByThread.get(rect.id) === index ? 0 : -1}
+ className={`pointer-events-auto absolute rounded-[2px] ${
+ rect.active ? "" : "hover:bg-yellow-300/45"
+ }`}
+ style={{
+ left: rect.left,
+ top: rect.top,
+ width: rect.width,
+ height: rect.height,
+ backgroundColor: rect.active
+ ? "rgba(250, 204, 21, 0.48)"
+ : "rgba(250, 204, 21, 0.32)",
+ }}
+ onClick={() => onActivateThread(rect.id)}
+ aria-label={rect.label}
+ />
+ ))}
+ </div>
+ <SelectionCommentOverlay
+ selection={selection}
+ open={!!selection && !!pendingAnchor}
+ filePath={artifactName}
+ actionLabel="Add comment"
+ placeholder="Add a comment about this selection..."
+ showActionText
+ members={members}
+ onDismiss={dismiss}
+ onSubmit={async (_start, _end, content, mentions) => {
+ if (pendingAnchor) await onCreate(pendingAnchor, content, mentions);
+ }}
+ />
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.test.ts b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.test.ts
new file mode 100644
index 000000000000..d8e52029eda2
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.test.ts
@@ -0,0 +1,20 @@
+import { formatMention } from "@posthog/shared";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { describe, expect, it } from "vitest";
+import { mentionIdsFromContent } from "./commentMentions";
+
+const members = [
+ { id: 1, uuid: "user-1", email: "[email protected]", first_name: "Abe" },
+ { id: 2, uuid: "user-2", email: "[email protected]", first_name: "Max" },
+] as UserBasic[];
+
+describe("mentionIdsFromContent", () => {
+ it("returns the user IDs represented by Thread mention tokens", () => {
+ const content = `Please review ${formatMention("Abe", "[email protected]")}`;
+ expect(mentionIdsFromContent(content, members)).toEqual([1]);
+ });
+
+ it("does not notify plain-text email addresses", () => {
+ expect(mentionIdsFromContent("Email [email protected]", members)).toEqual([]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.test.tsx
new file mode 100644
index 000000000000..d03f25150c67
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.test.tsx
@@ -0,0 +1,55 @@
+import { Theme } from "@radix-ui/themes";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@posthog/ui/features/canvas/components/MentionComposer", () => ({
+ MentionComposer: ({
+ value,
+ onValueChange,
+ children,
+ }: {
+ value: string;
+ onValueChange: (value: string) => void;
+ children: ReactNode;
+ }) => (
+ <div>
+ <textarea
+ aria-label="Comment"
+ value={value}
+ onChange={(event) => onValueChange(event.target.value)}
+ />
+ {children}
+ </div>
+ ),
+}));
+
+import { MentionAvailabilityProvider } from "@posthog/ui/features/sessions/mentionAvailability";
+import { CommentComposer } from "./CommentComposer";
+
+describe("CommentComposer", () => {
+ it("explains that mentions are unavailable in the private space", () => {
+ const onValueChange = vi.fn();
+ render(
+ <Theme>
+ <MentionAvailabilityProvider disabledReason="Mentions aren’t available in #me.">
+ <CommentComposer
+ value="@"
+ onValueChange={onValueChange}
+ onSubmit={vi.fn()}
+ members={[]}
+ placeholder="Comment"
+ />
+ </MentionAvailabilityProvider>
+ </Theme>,
+ );
+
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "Mentions aren’t available in #me.",
+ );
+ fireEvent.change(screen.getByRole("textbox", { name: "Comment" }), {
+ target: { value: "private note" },
+ });
+ expect(onValueChange).toHaveBeenCalledWith("private note");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
new file mode 100644
index 000000000000..dedb2f2cd682
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
@@ -0,0 +1,83 @@
+import { PaperPlaneRightIcon, XIcon } from "@phosphor-icons/react";
+import { InputGroupAddon, InputGroupButton } from "@posthog/quill";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { MentionComposer } from "@posthog/ui/features/canvas/components/MentionComposer";
+import { useMentionsDisabledReason } from "@posthog/ui/features/sessions/mentionAvailability";
+import { mentionIdsFromContent } from "./commentMentions";
+
+export function CommentComposer({
+ value,
+ onValueChange,
+ onSubmit,
+ onCancel,
+ members,
+ placeholder,
+ rows = 3,
+ disabled = false,
+ submitLabel = "Comment",
+ autoFocus = false,
+}: {
+ value: string;
+ onValueChange: (value: string) => void;
+ onSubmit: (content: string, mentions: number[]) => void | Promise<void>;
+ onCancel?: () => void;
+ members: UserBasic[];
+ placeholder: string;
+ rows?: number;
+ disabled?: boolean;
+ submitLabel?: string;
+ /** For a composer the user just opened, so they can type straight away. */
+ autoFocus?: boolean;
+}) {
+ const mentionsDisabledReason = useMentionsDisabledReason();
+ const mentionMembers = mentionsDisabledReason ? [] : members;
+ const showMentionsDisabled = !!mentionsDisabledReason && value.includes("@");
+ const submit = () => {
+ const content = value.trim();
+ if (!content || disabled) return;
+ void Promise.resolve(
+ onSubmit(content, mentionIdsFromContent(content, mentionMembers)),
+ ).catch(() => undefined);
+ };
+
+ return (
+ <MentionComposer
+ value={value}
+ onValueChange={onValueChange}
+ onSubmit={submit}
+ members={mentionMembers}
+ autoFocus={autoFocus}
+ placeholder={placeholder}
+ rows={rows}
+ inputClassName="max-h-40 text-[13px]"
+ >
+ <InputGroupAddon align="block-end" className="p-1">
+ {showMentionsDisabled && (
+ <output className="px-1 text-muted-foreground text-xs">
+ {mentionsDisabledReason}
+ </output>
+ )}
+ {onCancel && (
+ <InputGroupButton
+ size="icon-sm"
+ aria-label="Cancel"
+ onClick={onCancel}
+ >
+ <XIcon />
+ </InputGroupButton>
+ )}
+ <span className="ml-auto">
+ <InputGroupButton
+ variant="primary"
+ size="icon-sm"
+ aria-label={submitLabel}
+ disabled={!value.trim() || disabled}
+ onClick={submit}
+ >
+ <PaperPlaneRightIcon />
+ </InputGroupButton>
+ </span>
+ </InputGroupAddon>
+ </MentionComposer>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.test.tsx
new file mode 100644
index 000000000000..e7bffeccb921
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.test.tsx
@@ -0,0 +1,121 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+import {
+ githubCommentComponents,
+ isGitHubHostedImage,
+} from "../../editor/components/githubCommentImages";
+import { MarkdownRenderer } from "../../editor/components/MarkdownRenderer";
+import { CommentThreadCard } from "./CommentThreadCard";
+
+describe("CommentThreadCard", () => {
+ it.each([
+ "https://user-images.githubusercontent.com/1/example.png",
+ "https://private-user-images.githubusercontent.com/1/example.png",
+ "https://github.com/user-attachments/assets/12345678-1234-1234-1234-123456789abc",
+ ])("allows GitHub-hosted image %s", (source) => {
+ expect(isGitHubHostedImage(source)).toBe(true);
+ });
+
+ it.each([
+ "http://user-images.githubusercontent.com/1/example.png",
+ "https://github.com.example.com/user-attachments/assets/example",
+ "https://example.com/tracking.png",
+ "http://127.0.0.1/internal.png",
+ "data:image/png;base64,aW1hZ2U=",
+ ])("blocks non-GitHub image %s", (source) => {
+ expect(isGitHubHostedImage(source)).toBe(false);
+ });
+
+ it("renders only GitHub-hosted images from comment markdown", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownRenderer
+ content={[
+ "![GitHub image](https://user-images.githubusercontent.com/1/example.png)",
+ "![External image](https://example.com/tracking.png)",
+ ].join("\n\n")}
+ componentsOverride={githubCommentComponents}
+ />,
+ );
+
+ expect(html).toContain("user-images.githubusercontent.com/1/example.png");
+ expect(html).not.toContain("example.com/tracking.png");
+ });
+
+ it("handles a rejected asynchronous resolve action", async () => {
+ const onResolve = vi.fn().mockRejectedValue(new Error("unavailable"));
+ render(
+ <CommentThreadCard
+ threadId="thread-1"
+ entries={[
+ {
+ id: "comment-1",
+ authorName: "Reviewer",
+ user: null,
+ avatarUrl: null,
+ createdAt: "2026-08-07T00:00:00Z",
+ body: "Please update this",
+ format: "mentions",
+ },
+ ]}
+ selected={false}
+ pulsing={false}
+ resolved={false}
+ members={[]}
+ busy={false}
+ onSelect={vi.fn()}
+ onReply={vi.fn()}
+ onResolve={onResolve}
+ />,
+ );
+
+ fireEvent.click(screen.getByText("Resolve"));
+
+ await waitFor(() => expect(onResolve).toHaveBeenCalledWith(true));
+ });
+
+ it("selects the thread when a reply is clicked", () => {
+ const onSelect = vi.fn();
+ render(
+ <CommentThreadCard
+ threadId="thread-1"
+ entries={[
+ {
+ id: "comment-1",
+ authorName: "Reviewer",
+ user: null,
+ avatarUrl: null,
+ createdAt: "2026-08-07T00:00:00Z",
+ body: "Root comment",
+ format: "mentions",
+ },
+ {
+ id: "comment-2",
+ authorName: "Author",
+ user: null,
+ avatarUrl: null,
+ createdAt: "2026-08-07T00:01:00Z",
+ body: "Reply text",
+ format: "mentions",
+ },
+ ]}
+ selected={false}
+ pulsing={false}
+ resolved={false}
+ members={[]}
+ busy={false}
+ onSelect={onSelect}
+ onReply={vi.fn()}
+ onResolve={vi.fn()}
+ />,
+ );
+
+ const selectThread = screen.getByLabelText("Open comment thread");
+ expect(selectThread.parentElement).toContainElement(
+ screen.getByText("Reply text"),
+ );
+ fireEvent.click(selectThread);
+
+ expect(onSelect).toHaveBeenCalledOnce();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
new file mode 100644
index 000000000000..8aef01c50c36
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
@@ -0,0 +1,218 @@
+import {
+ ArrowCounterClockwise,
+ ArrowSquareOutIcon,
+ ChatCircle,
+ CheckCircle,
+ WarningCircle,
+} from "@phosphor-icons/react";
+import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
+ Button,
+ Card,
+ CardContent,
+ Separator,
+} from "@posthog/quill";
+import { formatRelativeTimeShort } from "@posthog/shared";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import { MentionText } from "@posthog/ui/features/canvas/components/MentionText";
+import type { CommentEntry } from "@posthog/ui/features/canvas/components/taskCommentThreads";
+import { githubCommentComponents } from "@posthog/ui/features/editor/components/githubCommentImages";
+import { githubRehypePlugins } from "@posthog/ui/features/editor/components/githubMarkdownPlugins";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { type ReactNode, useState } from "react";
+import { CommentComposer } from "./CommentComposer";
+import type { HighlightResolution } from "./commentViewTypes";
+
+function CommentBody({ entry }: { entry: CommentEntry }) {
+ return (
+ <div className="flex gap-2 py-2">
+ {/* A PostHog author keeps the avatar and hue they have everywhere else;
+ a GitHub author only ever comes with a url. */}
+ {entry.user || !entry.avatarUrl ? (
+ <UserAvatar user={entry.user} size="sm" />
+ ) : (
+ <Avatar size="sm">
+ <AvatarImage src={entry.avatarUrl} alt="" />
+ <AvatarFallback>{entry.authorName.slice(0, 2)}</AvatarFallback>
+ </Avatar>
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline gap-2">
+ <span className="truncate font-medium text-xs">
+ {entry.authorName}
+ </span>
+ <span className="shrink-0 text-muted-foreground text-xs">
+ {formatRelativeTimeShort(entry.createdAt)}
+ </span>
+ </div>
+ {entry.format === "markdown" ? (
+ <div className="mt-1 break-words text-[13px] leading-relaxed [&_img]:max-w-full [&_p]:m-0 [&_pre]:max-w-full [&_pre]:overflow-x-auto">
+ <MarkdownRenderer
+ content={entry.body}
+ rehypePlugins={githubRehypePlugins}
+ componentsOverride={githubCommentComponents}
+ />
+ </div>
+ ) : (
+ <MentionText
+ content={entry.body}
+ className="mt-1 block whitespace-pre-wrap break-words text-[13px] leading-relaxed"
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * One thread, with its replies and the reply/resolve controls. Selecting it is
+ * the caller's business: in a list spanning several resources that means
+ * opening the resource and locating the anchor.
+ */
+export function CommentThreadCard({
+ threadId,
+ entries,
+ selected,
+ pulsing,
+ resolved,
+ members,
+ resolution,
+ busy,
+ source,
+ canReply = true,
+ canResolve = true,
+ viewHref,
+ onSelect,
+ onReply,
+ onResolve,
+}: {
+ threadId: string;
+ /** Root first, then replies. */
+ entries: CommentEntry[];
+ selected: boolean;
+ pulsing: boolean;
+ resolved: boolean;
+ members: UserBasic[];
+ resolution?: HighlightResolution;
+ busy: boolean;
+ /** Names the resource the thread lives on, for cross-resource lists. */
+ source?: ReactNode;
+ /** GitHub conversation comments take neither replies nor resolution. */
+ canReply?: boolean;
+ canResolve?: boolean;
+ /** Where to read/act on a thread that can't be handled in place. */
+ viewHref?: string | null;
+ onSelect: () => void;
+ onReply: (content: string, mentions: number[]) => void | Promise<void>;
+ onResolve: (resolved: boolean) => void | Promise<void>;
+}) {
+ const [replying, setReplying] = useState(false);
+ const [reply, setReply] = useState("");
+ const [root, ...replies] = entries;
+ if (!root) return null;
+
+ return (
+ <Card
+ className={`gap-0 p-0 transition-all duration-300 ${
+ selected ? "border-accent bg-accent/5" : ""
+ } ${
+ // Inset, so a pane that clips its overflow can't shave the highlight.
+ pulsing ? "ring-2 ring-accent ring-inset" : ""
+ } ${resolved ? "opacity-70" : ""}`}
+ data-comment-thread-id={threadId}
+ >
+ <CardContent className="relative p-3">
+ <Button
+ type="button"
+ variant="outline"
+ className="absolute inset-0 h-auto w-full opacity-0"
+ aria-label="Open comment thread"
+ onClick={onSelect}
+ />
+ <div className="pointer-events-none relative [&_a]:pointer-events-auto [&_button]:pointer-events-auto">
+ <div className="w-full text-left">
+ {source}
+ {resolution === "orphaned" && (
+ <div className="mb-1.5 flex items-center gap-1 text-amber-700 text-xs dark:text-amber-300">
+ <WarningCircle />
+ The highlighted text changed
+ </div>
+ )}
+ <CommentBody entry={root} />
+ </div>
+ </div>
+ {/* Replies sit at the root's indentation: a thread this narrow reads as
+ one conversation, and nesting only stole width from the text. */}
+ <div className="pointer-events-none relative">
+ {replies.map((entry) => (
+ <CommentBody key={entry.id} entry={entry} />
+ ))}
+ </div>
+ {/* A conversation comment can only be read here and acted on in GitHub;
+ dead Reply/Resolve buttons would just discard whatever was typed, so
+ it gets a link out instead. */}
+ {(canReply || canResolve || viewHref) && <Separator className="my-2" />}
+ {!canReply && !canResolve && viewHref ? (
+ <div className="relative">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => openExternalUrl(viewHref)}
+ >
+ <ArrowSquareOutIcon />
+ View on GitHub
+ </Button>
+ </div>
+ ) : replying ? (
+ <CommentComposer
+ value={reply}
+ onValueChange={setReply}
+ onSubmit={async (content, mentions) => {
+ await onReply(content, mentions);
+ setReply("");
+ setReplying(false);
+ }}
+ onCancel={() => setReplying(false)}
+ members={members}
+ placeholder={
+ members.length > 0 ? "Reply… Type @ to mention someone" : "Reply…"
+ }
+ rows={2}
+ disabled={busy}
+ submitLabel="Reply"
+ autoFocus
+ />
+ ) : (
+ (canReply || canResolve) && (
+ <div className="relative flex gap-1">
+ {canReply && (
+ <Button size="sm" onClick={() => setReplying(true)}>
+ <ChatCircle />
+ Reply
+ </Button>
+ )}
+ {canResolve && (
+ <Button
+ size="sm"
+ disabled={busy}
+ onClick={() => {
+ Promise.resolve(onResolve(!resolved)).catch(
+ () => undefined,
+ );
+ }}
+ >
+ {resolved ? <ArrowCounterClockwise /> : <CheckCircle />}
+ {resolved ? "Reopen" : "Resolve"}
+ </Button>
+ )}
+ </div>
+ )
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
new file mode 100644
index 000000000000..46d8e7be547b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
@@ -0,0 +1,57 @@
+import { resolveTextCommentAnchor } from "@posthog/core/comments/anchors";
+
+const BRIDGE_MARKER = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
+
+/**
+ * Runs inside an opaque-origin sandboxed artifact iframe. It never receives
+ * credentials or writes to the API: selection and highlight traffic goes
+ * through the trusted parent with a per-view channel.
+ */
+function artifactHtmlCommentBridge(channel: string, nonce: string): string {
+ const safeChannel = JSON.stringify(channel);
+ return `<script nonce="${nonce}" data-posthog-artifact-comments>(function(){
+"use strict";
+var CHANNEL=${safeChannel};
+var MARKER=${JSON.stringify(BRIDGE_MARKER)};
+var state={button:null,timer:0,renderTimer:0,entries:[],items:[]};
+var supportsHighlights=!!(window.Highlight&&window.CSS&&CSS.highlights);
+var current=document.currentScript;if(current)current.remove();
+function send(type,payload){parent.postMessage(Object.assign({marker:MARKER,channel:CHANNEL,type:type},payload||{}),"*");}
+function text(){return (document.body&&document.body.textContent)||"";}
+function offsets(range){var a=document.createRange(),b=document.createRange();a.selectNodeContents(document.body);a.setEnd(range.startContainer,range.startOffset);b.selectNodeContents(document.body);b.setEnd(range.endContainer,range.endOffset);return{start:a.toString().length,end:b.toString().length};}
+function makeAnchor(range){var all=text(),o=offsets(range),quote=all.slice(o.start,o.end);if(!quote.trim()||quote.length>10000)return null;return{kind:"text",quote:quote,prefix:all.slice(Math.max(0,o.start-32),o.start),suffix:all.slice(o.end,o.end+32),start:o.start,end:o.end};}
+function textIndex(){var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),n,all="",entries=[];while((n=w.nextNode())){var start=all.length;all+=n.data;entries.push({node:n,start:start,end:all.length})}return{text:all,entries:entries}}
+function rangeAt(index,start,end){function find(offset){var low=0,high=index.entries.length-1,match=null;while(low<=high){var middle=(low+high)>>1,entry=index.entries[middle];if(offset<entry.start)high=middle-1;else if(offset>entry.end)low=middle+1;else{match=entry;high=middle-1}}return match}var sn=find(start),en=find(end);if(!sn||!en)return null;try{var r=document.createRange();r.setStart(sn.node,start-sn.start);r.setEnd(en.node,end-en.start);return r}catch(e){return null}}
+var resolveAnchor=${resolveTextCommentAnchor.toString()};
+function resolve(all,a){return resolveAnchor(all,a)}
+function style(){var s=document.createElement("style");s.setAttribute("data-posthog-artifact-comments","");s.textContent="::highlight(posthog-artifact-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-artifact-comment-active){background:rgba(250,204,21,.48);color:inherit}.ph-artifact-comment-button{position:fixed;z-index:2147483647;display:flex;align-items:center;gap:6px;height:34px;padding:0 13px;border:1px solid #ca8a04;border-radius:9px;background:#facc15;color:#1c1917;font:600 13px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;box-shadow:0 3px 12px rgba(0,0,0,.3);cursor:pointer}.ph-artifact-comment-button:hover{background:#fde047}";(document.head||document.documentElement).appendChild(s)}
+function hide(){if(state.button)state.button.style.display="none"}
+function button(){if(state.button&&state.button.isConnected)return state.button;var b=document.createElement("button");b.type="button";b.className="ph-artifact-comment-button";b.textContent="💬 Comment";b.style.display="none";b.addEventListener("mousedown",function(e){e.preventDefault();e.stopPropagation();var sel=window.getSelection();if(!sel||sel.isCollapsed||!sel.rangeCount)return hide();var range=sel.getRangeAt(0),anchor=makeAnchor(range);if(!anchor)return hide();var r=range.getBoundingClientRect(),br=b.getBoundingClientRect();send("selection",{anchor:anchor,rect:{top:r.top,left:r.left,right:r.right,bottom:r.bottom,width:r.width,height:r.height},triggerRect:{top:br.top,left:br.left,right:br.right,bottom:br.bottom,width:br.width,height:br.height}});hide();sel.removeAllRanges()});document.documentElement.appendChild(b);state.button=b;return b;}
+function selectionChanged(){clearTimeout(state.timer);state.timer=setTimeout(function(){var sel=window.getSelection();if(!sel||sel.isCollapsed||!sel.rangeCount)return hide();var value=sel.toString().trim();if(value.length<2||value.length>10000)return hide();var r=sel.getRangeAt(0).getBoundingClientRect();if(!r||(r.width===0&&r.height===0))return hide();var b=button();b.style.left=Math.max(8,Math.min(innerWidth-110,r.left+r.width/2-50))+"px";b.style.top=Math.max(8,r.top-42)+"px";b.style.display="flex"},80)}
+function render(items){state.items=items||[];state.entries=[];var normal=supportsHighlights?new Highlight():null,active=supportsHighlights?new Highlight():null,resolutions=[],index=textIndex();state.items.forEach(function(item){var hit=resolve(index.text,item.anchor);if(!hit){resolutions.push({id:item.id,status:"orphaned"});return}var range=rangeAt(index,hit.start,hit.end);if(!range){resolutions.push({id:item.id,status:"orphaned"});return}state.entries.push({id:item.id,range:range,active:!!item.active});resolutions.push({id:item.id,status:hit.status});if(supportsHighlights){if(item.active)active.add(range);else normal.add(range)}});if(supportsHighlights){CSS.highlights.set("posthog-artifact-comment",normal);CSS.highlights.set("posthog-artifact-comment-active",active)}send("resolutions",{items:resolutions})}
+function locate(id){for(var i=0;i<state.entries.length;i++){if(state.entries[i].id!==id)continue;var node=state.entries[i].range.startContainer,parentNode=node.nodeType===1?node:node.parentElement;if(parentNode&&parentNode.scrollIntoView)parentNode.scrollIntoView({behavior:"smooth",block:"center"});return}}
+document.addEventListener("selectionchange",selectionChanged);
+document.addEventListener("scroll",hide,true);
+document.addEventListener("click",function(e){var target=e.target,link=target&&target.closest?target.closest("a[href]"):null;if(link){e.preventDefault();e.stopPropagation();send("open-external",{href:link.href});return}for(var i=0;i<state.entries.length;i++){var rects=state.entries[i].range.getClientRects();for(var j=0;j<rects.length;j++){var r=rects[j];if(e.clientX>=r.left&&e.clientX<=r.right&&e.clientY>=r.top&&e.clientY<=r.bottom){e.preventDefault();e.stopPropagation();send("activate",{id:state.entries[i].id});return}}}},true);
+new MutationObserver(function(){if(!state.items.length||state.renderTimer)return;state.renderTimer=setTimeout(function(){state.renderTimer=0;render(state.items)},500)}).observe(document.body,{childList:true,characterData:true,subtree:true});
+window.addEventListener("message",function(e){if(e.source!==parent)return;var d=e.data;if(!d||d.marker!==MARKER||d.channel!==CHANNEL)return;if(d.type==="comments")render(d.items);else if(d.type==="locate"&&typeof d.id==="string")locate(d.id)});
+style();send("ready");
+})();</script>`;
+}
+
+export function injectArtifactHtmlCommentBridge(
+ html: string,
+ channel: string,
+ nonce: string,
+): string {
+ const bridge = artifactHtmlCommentBridge(channel, nonce);
+ const bodyEnd = html.toLowerCase().lastIndexOf("</body>");
+ if (bodyEnd >= 0) {
+ return `${html.slice(0, bodyEnd)}${bridge}${html.slice(bodyEnd)}`;
+ }
+ const htmlEnd = html.toLowerCase().lastIndexOf("</html>");
+ if (htmlEnd >= 0) {
+ return `${html.slice(0, htmlEnd)}${bridge}${html.slice(htmlEnd)}`;
+ }
+ return `${html}${bridge}`;
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
index 05d0f18c1700..53ead2a2dc2d 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
@@ -1,12 +1,36 @@
import { getImageMimeType, isAllowedImageMimeType } from "@posthog/shared";
import { applyCspToHtml } from "../../mcp-apps/utils/mcp-app-csp";
+import { injectArtifactHtmlCommentBridge } from "./artifactHtmlCommentBridge";
-function extension(filename: string): string {
- return filename.split(".").pop()?.toLowerCase() ?? "";
+function removeAutomaticRedirects(html: string): string {
+ if (!/<meta\b/i.test(html) || !/http-equiv\s*=/i.test(html)) return html;
+ const document = new DOMParser().parseFromString(html, "text/html");
+ const refreshElements = Array.from(
+ document.querySelectorAll<HTMLMetaElement>("meta[http-equiv]"),
+ ).filter((element) => element.httpEquiv.trim().toLowerCase() === "refresh");
+ if (refreshElements.length === 0) return html;
+
+ for (const element of refreshElements) element.remove();
+ const doctype = html.match(/^\s*<!doctype[^>]*>/i)?.[0] ?? "";
+ return doctype + document.documentElement.outerHTML;
}
-export function artifactHtmlDocument(html: string): string {
- return applyCspToHtml(html);
+export function artifactHtmlDocument(
+ html: string,
+ commentBridgeChannel?: string,
+): string {
+ // HTML artifacts are document previews, not apps. Canvases are the supported
+ // surface for authored JavaScript; only this trusted annotation bridge runs here.
+ const safeHtml = removeAutomaticRedirects(html);
+ if (!commentBridgeChannel) {
+ return applyCspToHtml(safeHtml, undefined, null);
+ }
+ const nonce = crypto.randomUUID();
+ return applyCspToHtml(
+ injectArtifactHtmlCommentBridge(safeHtml, commentBridgeChannel, nonce),
+ undefined,
+ nonce,
+ );
}
export async function artifactPreviewBlob(
blob: Blob,
@@ -20,10 +44,12 @@ export async function artifactPreviewBlob(
if (isAllowedImageMimeType(imageMimeType)) {
return new Blob([blob], { type: imageMimeType });
}
- if (["html", "htm"].includes(extension(filename))) {
- return new Blob([artifactHtmlDocument(await blob.text())], {
- type: "text/html",
- });
+ // SVG is kept out of the shared <img> allowlist because its scripts can run
+ // when it comes from a data URL, but the artifact preview renders it from a
+ // blob in an <img>, which never runs scripts. Type it so that surface picks
+ // it up instead of the browser offering a download.
+ if (filenameMimeType === "image/svg+xml") {
+ return new Blob([blob], { type: "image/svg+xml" });
}
return blob;
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/commentMentions.ts b/products/desktop/packages/ui/src/features/sessions/components/commentMentions.ts
new file mode 100644
index 000000000000..cc871281e8cf
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/commentMentions.ts
@@ -0,0 +1,15 @@
+import { splitMentionSegments } from "@posthog/shared";
+import type { UserBasic } from "@posthog/shared/domain-types";
+
+export function mentionIdsFromContent(
+ content: string,
+ members: UserBasic[],
+): number[] {
+ const emails = new Set<string>();
+ for (const segment of splitMentionSegments(content)) {
+ if (segment.type === "mention") emails.add(segment.email.toLowerCase());
+ }
+ return members
+ .filter((member) => emails.has(member.email.toLowerCase()))
+ .map((member) => member.id);
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/commentViewTypes.test.ts b/products/desktop/packages/ui/src/features/sessions/components/commentViewTypes.test.ts
new file mode 100644
index 000000000000..217e64a4e05e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/commentViewTypes.test.ts
@@ -0,0 +1,43 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import { describe, expect, it } from "vitest";
+import { buildCommentThreads } from "./commentViewTypes";
+
+function comment(
+ id: string,
+ createdAt: string,
+ sourceComment: string | null = null,
+): ResourceComment {
+ return {
+ id,
+ created_at: createdAt,
+ source_comment: sourceComment,
+ content: id,
+ scope: "task",
+ item_id: "task-1",
+ item_context: { anchor: { kind: "document" } },
+ created_by: null,
+ deleted: false,
+ is_task: false,
+ completed_at: null,
+ completed_by: null,
+ } as ResourceComment;
+}
+
+describe("buildCommentThreads", () => {
+ it("orders replies by when they were sent regardless of API order", () => {
+ const root = comment("root", "2026-08-04T10:00:00Z");
+ const olderReply = comment("older-reply", "2026-08-04T10:05:00Z", root.id);
+ const newestReply = comment(
+ "newest-reply",
+ "2026-08-04T10:10:00Z",
+ root.id,
+ );
+
+ const [thread] = buildCommentThreads([newestReply, root, olderReply]);
+
+ expect(thread?.replies.map((reply) => reply.id)).toEqual([
+ "older-reply",
+ "newest-reply",
+ ]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/commentViewTypes.ts b/products/desktop/packages/ui/src/features/sessions/components/commentViewTypes.ts
new file mode 100644
index 000000000000..e3327a9f60e4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/commentViewTypes.ts
@@ -0,0 +1,49 @@
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import {
+ type CommentContext,
+ isThreadResolved,
+ parseCommentContext,
+} from "@posthog/core/comments/anchors";
+
+export type HighlightResolution = "exact" | "reanchored" | "orphaned";
+export type CommentLocateRequest = { id: string; nonce: number };
+
+export function readCommentContext(
+ comment: ResourceComment,
+): CommentContext | null {
+ return parseCommentContext(comment.item_context);
+}
+
+export type CommentThread = {
+ root: ResourceComment;
+ replies: ResourceComment[];
+ resolved: boolean;
+};
+
+function bySentAt(a: ResourceComment, b: ResourceComment): number {
+ return a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id);
+}
+
+export function buildCommentThreads(
+ comments: ResourceComment[],
+): CommentThread[] {
+ const roots: ResourceComment[] = [];
+ const repliesByRoot = new Map<string, ResourceComment[]>();
+ for (const comment of comments) {
+ if (!comment.source_comment) {
+ roots.push(comment);
+ continue;
+ }
+ const replies = repliesByRoot.get(comment.source_comment) ?? [];
+ replies.push(comment);
+ repliesByRoot.set(comment.source_comment, replies);
+ }
+ return roots.sort(bySentAt).map((root) => {
+ const replies = (repliesByRoot.get(root.id) ?? []).sort(bySentAt);
+ return {
+ root,
+ replies,
+ resolved: isThreadResolved(root, replies),
+ };
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/useComments.test.ts b/products/desktop/packages/ui/src/features/sessions/components/useComments.test.ts
new file mode 100644
index 000000000000..654147f6562c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/useComments.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+import { commentCacheCoversTarget } from "./useComments";
+
+const target = { scope: "task_artifact", itemId: "a" } as const;
+
+describe("commentCacheCoversTarget", () => {
+ // An optimistic reply has to land in every list showing that resource — the
+ // artifact's own query and the task-wide fan-out — and in no other.
+ it.each([
+ {
+ what: "the target's own query",
+ key: ["comments", "identity", "task-1", "task_artifact", "a"],
+ covers: true,
+ },
+ {
+ what: "a sibling resource's query",
+ key: ["comments", "identity", "task-1", "task_artifact", "b"],
+ covers: false,
+ },
+ {
+ what: "the same id under another scope",
+ key: ["comments", "identity", "task-1", "desktop_canvas", "a"],
+ covers: false,
+ },
+ {
+ what: "a fan-out including the target",
+ key: [
+ "comments",
+ "targets",
+ "identity",
+ "task-1",
+ "desktop_canvas:c,task_artifact:a",
+ ],
+ covers: true,
+ },
+ {
+ what: "a fan-out without the target",
+ key: ["comments", "targets", "identity", "task-1", "task_artifact:b"],
+ covers: false,
+ },
+ {
+ what: "a fan-out whose target only shares a prefix",
+ key: ["comments", "targets", "identity", "task-1", "task_artifact:ab"],
+ covers: false,
+ },
+ {
+ what: "an unrelated query",
+ key: ["artifactPreview", "identity", "task_artifact", "a"],
+ covers: false,
+ },
+ ])("$what", ({ key, covers }) => {
+ expect(commentCacheCoversTarget(key, target)).toBe(covers);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/useComments.ts b/products/desktop/packages/ui/src/features/sessions/components/useComments.ts
new file mode 100644
index 000000000000..fd103ff91711
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/useComments.ts
@@ -0,0 +1,273 @@
+import type {
+ CreateResourceCommentRequest,
+ ResourceComment,
+} from "@posthog/api-client/posthog-client";
+import {
+ type CommentTarget,
+ commentTargetKey,
+} from "@posthog/core/comments/anchors";
+import {
+ SESSION_SERVICE,
+ type SessionService,
+} from "@posthog/core/sessions/sessionService";
+import { useService } from "@posthog/di/react";
+import {
+ getAuthIdentity,
+ useAuthStateValue,
+} from "@posthog/ui/features/auth/store";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { toast } from "@posthog/ui/primitives/toast";
+import {
+ type QueryClient,
+ type QueryKey,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+
+function commentsQueryKey(
+ authIdentity: string | null,
+ target: CommentTarget | null,
+ taskId: string,
+) {
+ return [
+ "comments",
+ authIdentity,
+ taskId,
+ target?.scope ?? "",
+ target?.itemId ?? "",
+ ] as const;
+}
+
+/**
+ * Whether a cached comment list contains the target's comments — true for the
+ * target's own single-resource query and for any fan-out query whose set
+ * includes it. Both key shapes spell the target out, so this needs no cache
+ * contents. Matching per target rather than on the `["comments"]` prefix keeps
+ * an optimistic write out of other resources' caches.
+ */
+export function commentCacheCoversTarget(
+ queryKey: readonly unknown[],
+ target: CommentTarget,
+): boolean {
+ if (queryKey[0] !== "comments") return false;
+ if (queryKey[1] === "targets") {
+ return String(queryKey[4] ?? "")
+ .split(",")
+ .includes(commentTargetKey(target));
+ }
+ return queryKey[3] === target.scope && queryKey[4] === target.itemId;
+}
+
+/** Filter for every cached comment list an optimistic write has to patch. */
+function commentCachesCoveringTarget(target: CommentTarget) {
+ return {
+ queryKey: ["comments"] as const,
+ predicate: (query: { queryKey: readonly unknown[] }) =>
+ commentCacheCoversTarget(query.queryKey, target),
+ };
+}
+
+type CommentCacheFilter = ReturnType<typeof commentCachesCoveringTarget>;
+type CommentCacheSnapshot = [QueryKey, ResourceComment[] | undefined][];
+
+/** Only patches lists that have already loaded: appending to a pending query
+ * would fabricate a result its own fetch is about to replace. */
+function appendOptimisticComment(
+ queryClient: QueryClient,
+ caches: CommentCacheFilter,
+ optimistic: ResourceComment,
+) {
+ queryClient.setQueriesData<ResourceComment[]>(caches, (current) =>
+ current ? [...current, optimistic] : current,
+ );
+}
+
+function restoreCommentCaches(
+ queryClient: QueryClient,
+ snapshot: CommentCacheSnapshot | undefined,
+) {
+ for (const [queryKey, comments] of snapshot ?? []) {
+ queryClient.setQueryData(queryKey, comments);
+ }
+}
+
+function replaceOptimisticComment(
+ queryClient: QueryClient,
+ caches: CommentCacheFilter,
+ optimisticId: string,
+ saved: ResourceComment,
+) {
+ queryClient.setQueriesData<ResourceComment[]>(caches, (current) =>
+ current?.map((comment) => (comment.id === optimisticId ? saved : comment)),
+ );
+}
+
+export function isOptimisticComment(comment: ResourceComment): boolean {
+ return comment.id.startsWith("optimistic-");
+}
+
+export function useCommentsQuery(
+ target: CommentTarget | null,
+ taskId: string,
+ options: { enabled?: boolean; live?: boolean } = {},
+) {
+ const service = useService<SessionService>(SESSION_SERVICE);
+ const authIdentity = useAuthStateValue(getAuthIdentity);
+ return useQuery({
+ queryKey: commentsQueryKey(authIdentity, target, taskId),
+ queryFn: () =>
+ target
+ ? service.getResourceComments(target, taskId)
+ : Promise.resolve([]),
+ enabled: options.enabled !== false && authIdentity !== null && !!target,
+ staleTime: 3_000,
+ refetchInterval: options.live === false ? false : 5_000,
+ refetchIntervalInBackground: false,
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+}
+
+/**
+ * One query for every comment across a set of resources. The service does the
+ * fan-out, so this stays a single-query hook and the pane makes one request
+ * instead of one per row. `live: false` by default — a list of N resources must
+ * never turn into N polling loops, and `intervalMs` lets a live caller pick a
+ * cadence that accounts for the fan-out rather than inheriting a per-row one.
+ */
+export function useCommentsForTargetsQuery(
+ targets: CommentTarget[],
+ taskId: string,
+ options: { enabled?: boolean; live?: boolean; intervalMs?: number } = {},
+) {
+ const service = useService<SessionService>(SESSION_SERVICE);
+ const authIdentity = useAuthStateValue(getAuthIdentity);
+ // Sorted so key identity tracks the set, not row order.
+ const key = targets.map(commentTargetKey).sort().join(",");
+ return useQuery({
+ queryKey: ["comments", "targets", authIdentity, taskId, key] as const,
+ queryFn: () => service.getResourceCommentsForTargets(targets, taskId),
+ enabled:
+ options.enabled !== false && authIdentity !== null && targets.length > 0,
+ staleTime: 3_000,
+ refetchInterval: options.live ? (options.intervalMs ?? 5_000) : false,
+ refetchIntervalInBackground: false,
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+}
+
+/**
+ * @param taskId Names the task the resource belongs to, so a mention on it reaches that
+ * task's activity feed — the server can't resolve an artifact or canvas id back to a task.
+ */
+export function useCreateComment(target: CommentTarget, taskId?: string) {
+ const service = useService<SessionService>(SESSION_SERVICE);
+ const queryClient = useQueryClient();
+ const caches = commentCachesCoveringTarget(target);
+ const contextWithTask = (context: unknown) =>
+ taskId ? { ...(context as Record<string, unknown>), taskId } : context;
+
+ return useMutation({
+ mutationFn: (
+ request: Omit<CreateResourceCommentRequest, "scope" | "itemId">,
+ ) =>
+ service.createResourceComment({
+ ...request,
+ ...target,
+ context: contextWithTask(request.context),
+ }),
+ onMutate: async (request) => {
+ await queryClient.cancelQueries(caches);
+ const previous = queryClient.getQueriesData<ResourceComment[]>(caches);
+ const optimistic: ResourceComment = {
+ id: `optimistic-${crypto.randomUUID()}`,
+ created_by: null,
+ content: request.content,
+ created_at: new Date().toISOString(),
+ item_id: target.itemId,
+ item_context: contextWithTask(request.context),
+ scope: target.scope,
+ source_comment: request.sourceCommentId ?? null,
+ completed_at: null,
+ };
+ appendOptimisticComment(queryClient, caches, optimistic);
+ return { previous, optimisticId: optimistic.id };
+ },
+ onSuccess: (saved, _request, context) => {
+ replaceOptimisticComment(
+ queryClient,
+ caches,
+ context.optimisticId,
+ saved,
+ );
+ },
+ onError: (_error, _request, context) => {
+ restoreCommentCaches(queryClient, context?.previous);
+ toast.error("Couldn't save comment", {
+ description: "Try again.",
+ });
+ },
+ onSettled: () => queryClient.invalidateQueries(caches),
+ });
+}
+
+export function useSetCommentResolved(target: CommentTarget) {
+ const service = useService<SessionService>(SESSION_SERVICE);
+ const queryClient = useQueryClient();
+ const caches = commentCachesCoveringTarget(target);
+
+ return useMutation({
+ mutationFn: ({
+ root,
+ resolved,
+ }: {
+ root: ResourceComment;
+ resolved: boolean;
+ }) => {
+ const rootContext =
+ root.item_context && typeof root.item_context === "object"
+ ? root.item_context
+ : {};
+ return service.createResourceComment({
+ ...target,
+ content: resolved ? "Resolved this thread" : "Reopened this thread",
+ sourceCommentId: root.id,
+ context: {
+ ...rootContext,
+ threadState: resolved ? "resolved" : "open",
+ },
+ });
+ },
+ onMutate: async ({ root, resolved }) => {
+ await queryClient.cancelQueries(caches);
+ const previous = queryClient.getQueriesData<ResourceComment[]>(caches);
+ const rootContext =
+ root.item_context && typeof root.item_context === "object"
+ ? root.item_context
+ : {};
+ const optimistic: ResourceComment = {
+ id: `optimistic-state-${crypto.randomUUID()}`,
+ created_by: null,
+ content: resolved ? "Resolved this thread" : "Reopened this thread",
+ created_at: new Date().toISOString(),
+ item_id: target.itemId,
+ item_context: {
+ ...rootContext,
+ threadState: resolved ? "resolved" : "open",
+ },
+ scope: target.scope,
+ source_comment: root.id,
+ completed_at: null,
+ };
+ appendOptimisticComment(queryClient, caches, optimistic);
+ return { previous };
+ },
+ onError: (_error, _variables, context) => {
+ restoreCommentCaches(queryClient, context?.previous);
+ toast.error("Couldn't update comment", {
+ description: "Try again.",
+ });
+ },
+ onSettled: () => queryClient.invalidateQueries(caches),
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/mentionAvailability.tsx b/products/desktop/packages/ui/src/features/sessions/mentionAvailability.tsx
new file mode 100644
index 000000000000..43126abd46ea
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/mentionAvailability.tsx
@@ -0,0 +1,24 @@
+import { createContext, type ReactNode, useContext } from "react";
+
+export const PRIVATE_SPACE_MENTIONS_DISABLED =
+ "Mentions aren’t available in #me.";
+
+const MentionAvailabilityContext = createContext<string | null>(null);
+
+export function MentionAvailabilityProvider({
+ disabledReason,
+ children,
+}: {
+ disabledReason: string | null;
+ children: ReactNode;
+}) {
+ return (
+ <MentionAvailabilityContext.Provider value={disabledReason}>
+ {children}
+ </MentionAvailabilityContext.Provider>
+ );
+}
+
+export function useMentionsDisabledReason(): string | null {
+ return useContext(MentionAvailabilityContext);
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/useCommentsEnabled.ts b/products/desktop/packages/ui/src/features/sessions/useCommentsEnabled.ts
new file mode 100644
index 000000000000..932391761caf
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/useCommentsEnabled.ts
@@ -0,0 +1,6 @@
+import { COMMENTS_FLAG } from "@posthog/shared";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+
+export function useCommentsEnabled(): boolean {
+ return useFeatureFlag(COMMENTS_FLAG);
+}
diff --git a/products/desktop/packages/ui/src/primitives/SafeImagePreview.tsx b/products/desktop/packages/ui/src/primitives/SafeImagePreview.tsx
index 9c73fbe9f774..ccd1c30cab07 100644
--- a/products/desktop/packages/ui/src/primitives/SafeImagePreview.tsx
+++ b/products/desktop/packages/ui/src/primitives/SafeImagePreview.tsx
@@ -35,6 +35,9 @@ interface ZoomableImageProps {
style?: React.CSSProperties;
controls?: boolean;
onError?: () => void;
+ /** Content positioned over the image and transformed with zoom/pan. Given the
+ * current scale so markers can hold their on-screen size. */
+ overlay?: React.ReactNode | ((scale: number) => React.ReactNode);
}
export function ZoomableImage({
@@ -44,6 +47,7 @@ export function ZoomableImage({
style,
controls = false,
onError,
+ overlay,
}: ZoomableImageProps) {
const [scale, setScale] = useState(1);
@@ -75,13 +79,20 @@ export function ZoomableImage({
justifyContent: "center",
}}
>
- <img
- src={src}
- alt={alt}
- draggable={false}
- className="max-h-full max-w-full object-contain"
- onError={onError}
- />
+ <div className="relative flex max-h-full max-w-full">
+ <img
+ src={src}
+ alt={alt}
+ draggable={false}
+ className="max-h-full max-w-full object-contain"
+ onError={onError}
+ />
+ {overlay && (
+ <div className="absolute inset-0">
+ {typeof overlay === "function" ? overlay(scale) : overlay}
+ </div>
+ )}
+ </div>
</TransformComponent>
{controls && (
<div className="-translate-x-1/2 absolute bottom-3 left-1/2 flex items-center gap-1 rounded-md border border-(--gray-a5) bg-(--color-panel-solid) p-1 shadow-sm">
diff --git a/products/desktop/packages/ui/src/test/setup.ts b/products/desktop/packages/ui/src/test/setup.ts
index 2e27ecf82e62..ca0b839d6f4f 100644
--- a/products/desktop/packages/ui/src/test/setup.ts
+++ b/products/desktop/packages/ui/src/test/setup.ts
@@ -95,6 +95,18 @@ if (typeof Element.prototype.getAnimations !== "function") {
Element.prototype.getAnimations = () => [];
}
+// jsdom implements no scrolling at all. Panes that reveal a row — a comment
+// thread, a timeline's newest message — usually do it from an animation frame
+// or a timer, so the missing method surfaces as an uncaught exception *after*
+// the test that scheduled it has passed, failing the whole run on an unrelated
+// file. No-ops here; a test that cares about the scroll spies on these.
+if (typeof Element.prototype.scrollIntoView !== "function") {
+ Element.prototype.scrollIntoView = () => {};
+}
+if (typeof Element.prototype.scrollTo !== "function") {
+ Element.prototype.scrollTo = () => {};
+}
+
// jsdom does not implement matchMedia; UI stores (e.g. themeStore) read it at
// module load to resolve the system color scheme.
Object.defineProperty(window, "matchMedia", {
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 9cfd15795a9e..f011a887a0be 100644
--- a/products/desktop/packages/workspace-server/src/services/git/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/schemas.ts
@@ -357,6 +357,7 @@ export const getLocalBranchChangedFilesInput = z.object({
export const prReviewCommentUserSchema = z.object({
login: z.string(),
avatar_url: z.string(),
+ isBot: z.boolean().optional(),
});
export const prReviewCommentSchema = z.object({
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 83c92ef09d84..8e72459c41e8 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
@@ -84,4 +84,60 @@ describe("GitService", () => {
new GitService().getBranchChangedFiles("posthog/code", "feature/new"),
).rejects.toThrow("Failed to fetch branch files");
});
+
+ it("keeps review threads whose author account was deleted", async () => {
+ execGhMock.mockResolvedValueOnce(
+ ghResult({
+ stdout: JSON.stringify({
+ data: {
+ repository: {
+ pullRequest: {
+ reviewThreads: {
+ pageInfo: { hasNextPage: false, endCursor: null },
+ nodes: [
+ {
+ id: "thread-1",
+ isResolved: false,
+ isOutdated: false,
+ path: "src/example.ts",
+ diffSide: "RIGHT",
+ line: 4,
+ originalLine: 4,
+ startLine: null,
+ startDiffSide: null,
+ subjectType: "LINE",
+ comments: {
+ nodes: [
+ {
+ databaseId: 42,
+ body: "Still relevant",
+ path: "src/example.ts",
+ diffHunk: "@@ -1 +1 @@",
+ replyTo: null,
+ author: null,
+ createdAt: "2026-08-07T00:00:00Z",
+ updatedAt: "2026-08-07T00:00:00Z",
+ },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ }),
+ }),
+ );
+
+ const threads = await new GitService().getPrReviewComments(
+ "https://github.com/PostHog/posthog/pull/78690",
+ );
+
+ expect(threads[0]?.comments[0]?.user).toEqual({
+ login: "ghost",
+ avatar_url: "",
+ isBot: false,
+ });
+ });
});
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 71447cc0eb0c..2727d08fbd38 100644
--- a/products/desktop/packages/workspace-server/src/services/git/service.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/service.ts
@@ -1480,11 +1480,11 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
const [comments, reviewSummaries] = await Promise.all([
this.fetchPrCommentFeed(
`repos/${pr.owner}/${pr.repo}/issues/${pr.number}/comments`,
- '.[] | {id, author: (.user.login // "unknown"), avatarUrl: (.user.avatar_url // null), body: (.body // ""), createdAt: .created_at, url: (.html_url // null)}',
+ '.[] | {id, author: (.user.login // "unknown"), isBot: (.user.type == "Bot"), avatarUrl: (.user.avatar_url // null), body: (.body // ""), createdAt: .created_at, url: (.html_url // null)}',
),
this.fetchPrCommentFeed(
`repos/${pr.owner}/${pr.repo}/pulls/${pr.number}/reviews`,
- '.[] | select(.state != "PENDING") | select((.body // "") != "") | {id, author: (.user.login // "unknown"), avatarUrl: (.user.avatar_url // null), body, createdAt: (.submitted_at // ""), url: (.html_url // null)}',
+ '.[] | select(.state != "PENDING") | select((.body // "") != "") | {id, author: (.user.login // "unknown"), isBot: (.user.type == "Bot"), avatarUrl: (.user.avatar_url // null), body, createdAt: (.submitted_at // ""), url: (.html_url // null)}',
),
]);
return [...comments, ...reviewSummaries];
@@ -1546,7 +1546,7 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
path
diffHunk
replyTo { databaseId }
- author { login avatarUrl }
+ author { __typename login avatarUrl }
createdAt
updatedAt
}
@@ -1576,7 +1576,11 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
path: string;
diffHunk: string;
replyTo: { databaseId: number } | null;
- author: { login: string; avatarUrl: string };
+ author: {
+ __typename: string;
+ login: string;
+ avatarUrl: string;
+ } | null;
createdAt: string;
updatedAt: string;
}>;
@@ -1642,7 +1646,11 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
start_line: thread.startLine,
start_side: thread.startDiffSide,
in_reply_to_id: c.replyTo?.databaseId ?? null,
- user: { login: c.author.login, avatar_url: c.author.avatarUrl },
+ user: {
+ login: c.author?.login ?? "ghost",
+ avatar_url: c.author?.avatarUrl ?? "",
+ isBot: c.author?.__typename === "Bot",
+ },
created_at: c.createdAt,
updated_at: c.updatedAt,
subject_type: thread.subjectType