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(tasks): pin comments on images and comment on selected text (#110452)

Shy Altera8780df58797
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx
index 0ce6087b1463..8994a9be02a1 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx
@@ -846,3 +846,8 @@ export const MarkdownComments: Story = {
parameters: { msw: { mocks: commentMocks() } },
render: () => <StoryPage fileName={REPORT_FILE_NAME} commentsOpen />,
}
+
+export const ImageCommentPins: Story = {
+ parameters: { msw: { mocks: commentMocks() } },
+ render: () => <StoryPage fileName="trial-starts-by-step.svg" commentsOpen />,
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentActions.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentActions.tsx
index 61a28e07fe5e..f6149b2b859f 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentActions.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentActions.tsx
@@ -1,40 +1,64 @@
import { useActions, useValues } from 'kea'
-import { IconComment } from '@posthog/icons'
+import { IconComment, IconPin } from '@posthog/icons'
import { Button, Text, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill-primitives'
import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'
import { taskRunArtifactsLogic } from '../taskRunArtifactsLogic'
-/** The toolbar control for comments: show or hide the panel. */
+/** The toolbar controls for comments: show the panel, and on an image, pin a comment to a spot. */
export function ArtifactCommentActions({ logicProps }: { logicProps: TaskArtifactCommentsLogicProps }): JSX.Element {
- const { openCount } = useValues(taskArtifactCommentsLogic(logicProps))
+ const { openCount, pinMode } = useValues(taskArtifactCommentsLogic(logicProps))
+ const { setPinMode } = useActions(taskArtifactCommentsLogic(logicProps))
const { commentsOpen } = useValues(taskRunArtifactsLogic({ taskId: logicProps.taskId }))
const { setCommentsOpen } = useActions(taskRunArtifactsLogic({ taskId: logicProps.taskId }))
const commentsLabel = commentsOpen ? 'Hide comments' : 'Show comments'
+ const pinLabel = pinMode ? 'Stop pinning' : 'Pin a comment to a spot on the image'
return (
- <Tooltip>
- <TooltipTrigger
- delay={0}
- render={
- // Toggle cannot hold a ref, and the tooltip needs one to anchor, so this is a pressed Button.
- <Button
- aria-label={openCount > 0 ? `${commentsLabel}, ${openCount} open` : commentsLabel}
- aria-pressed={commentsOpen}
- className={cn(commentsOpen && 'bg-fill-selected')}
- onClick={() => setCommentsOpen(!commentsOpen)}
- data-attr="task-artifact-comments-toggle"
- />
- }
- >
- <IconComment />
- {openCount > 0 && (
- <Text size="xs" render={<span />} className="tabular-nums">
- {openCount}
- </Text>
- )}
- </TooltipTrigger>
- <TooltipContent>{commentsLabel}</TooltipContent>
- </Tooltip>
+ <>
+ {logicProps.kind === 'image' && (
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ // Toggle cannot hold a ref, and the tooltip needs one to anchor, so this is a pressed Button.
+ <Button
+ size="icon"
+ aria-label={pinLabel}
+ aria-pressed={pinMode}
+ className={cn(pinMode && 'bg-fill-selected')}
+ onClick={() => setPinMode(!pinMode)}
+ data-attr="task-artifact-comment-pin-mode"
+ />
+ }
+ >
+ <IconPin />
+ </TooltipTrigger>
+ <TooltipContent>{pinLabel}</TooltipContent>
+ </Tooltip>
+ )}
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <Button
+ aria-label={openCount > 0 ? `${commentsLabel}, ${openCount} open` : commentsLabel}
+ aria-pressed={commentsOpen}
+ className={cn(commentsOpen && 'bg-fill-selected')}
+ onClick={() => setCommentsOpen(!commentsOpen)}
+ data-attr="task-artifact-comments-toggle"
+ />
+ }
+ >
+ <IconComment />
+ {openCount > 0 && (
+ <Text size="xs" render={<span />} className="tabular-nums">
+ {openCount}
+ </Text>
+ )}
+ </TooltipTrigger>
+ <TooltipContent>{commentsLabel}</TooltipContent>
+ </Tooltip>
+ </>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentsPanel.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentsPanel.tsx
index c204110891a0..86f3ce84ffe5 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentsPanel.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactCommentsPanel.tsx
@@ -21,12 +21,21 @@ import {
TooltipTrigger,
} from '@posthog/quill-primitives'
+import { supportsSelectionComments } from '../artifactComments'
import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'
import { taskRunArtifactsLogic } from '../taskRunArtifactsLogic'
import { ArtifactCommentComposer } from './ArtifactCommentComposer'
import { ArtifactCommentThreadCard } from './ArtifactCommentThreadCard'
-const EMPTY_HINT = 'Comment on the whole file above.'
+function emptyHint(kind: TaskArtifactCommentsLogicProps['kind']): string {
+ if (kind === 'image') {
+ return 'Comment on the whole image above, or pin a comment to a spot on it.'
+ }
+ if (supportsSelectionComments(kind)) {
+ return 'Comment on the whole file above, or select text in the preview to comment on it.'
+ }
+ return 'Comment on the whole file above.'
+}
function ThreadList({ logicProps }: { logicProps: TaskArtifactCommentsLogicProps }): JSX.Element {
const { visibleThreads, threads, commentsLoadFailed, commentsLoading } = useValues(
@@ -76,7 +85,7 @@ function ThreadList({ logicProps }: { logicProps: TaskArtifactCommentsLogicProps
<IconComment />
</EmptyMedia>
<EmptyTitle>{threads.length > 0 ? 'No open comments' : 'No comments yet'}</EmptyTitle>
- <EmptyDescription>{EMPTY_HINT}</EmptyDescription>
+ <EmptyDescription>{emptyHint(logicProps.kind)}</EmptyDescription>
</EmptyHeader>
</Empty>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImagePins.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImagePins.tsx
new file mode 100644
index 000000000000..46cdd30f01f7
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImagePins.tsx
@@ -0,0 +1,109 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useRef } from 'react'
+
+import { cn } from '@posthog/quill-primitives'
+
+import { fullNameOrEmail } from 'lib/utils/strings'
+
+import type { RegionCommentAnchor } from '../artifactComments'
+import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'
+import { ArtifactPendingComment } from './ArtifactPendingComment'
+
+/** The point of a pin sits on its region's bottom left corner, the same spot Desktop draws it on. */
+function pinStyle(anchor: RegionCommentAnchor): { left: string; top: string } {
+ return { left: `${anchor.x * 100}%`, top: `${(anchor.y + anchor.height) * 100}%` }
+}
+
+function PinMarker({
+ label,
+ number,
+ active,
+ onClick,
+ anchor,
+ threadId,
+}: {
+ threadId?: string
+ label: string
+ number: number | null
+ active: boolean
+ onClick?: () => void
+ anchor: RegionCommentAnchor
+}): JSX.Element {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ aria-pressed={onClick ? active : undefined}
+ // A square bottom left corner makes the teardrop, and that corner is the spot the pin marks.
+ className={cn(
+ 'absolute z-20 flex size-6 -translate-y-full items-center justify-center rounded-full rounded-bl-none bg-background text-xs font-semibold text-foreground shadow-md tabular-nums',
+ active ? 'ring-2 ring-ring' : 'ring-1 ring-foreground/20',
+ onClick ? 'pointer-events-auto cursor-pointer' : 'pointer-events-none'
+ )}
+ // Pins sit at stored shares of the image size, which utility classes cannot express.
+ style={pinStyle(anchor)}
+ onClick={onClick}
+ data-thread-id={threadId}
+ data-attr="task-artifact-comment-pin-marker"
+ >
+ {number ?? '+'}
+ </button>
+ )
+}
+
+/** Comment pins on an image, and the box for a new pin. Renders inside the image viewer's overlay. */
+export function ArtifactImagePins({ logicProps }: { logicProps: TaskArtifactCommentsLogicProps }): JSX.Element {
+ const { anchoredThreads, activeThreadId, pendingAnchor } = useValues(taskArtifactCommentsLogic(logicProps))
+ const { activateThread } = useActions(taskArtifactCommentsLogic(logicProps))
+ const rootRef = useRef<HTMLDivElement>(null)
+
+ // A pick in the comments panel scrolls its pin into view when the image is zoomed in.
+ useEffect(() => {
+ if (activeThreadId) {
+ rootRef.current
+ ?.querySelector<HTMLElement>(`[data-thread-id="${CSS.escape(activeThreadId)}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' })
+ }
+ }, [activeThreadId])
+
+ const pendingRegion = pendingAnchor?.kind === 'region' ? pendingAnchor : null
+ return (
+ <div ref={rootRef} className="pointer-events-none absolute inset-0">
+ {anchoredThreads.map((thread) => {
+ if (thread.anchor?.kind !== 'region') {
+ return null
+ }
+ const author = thread.root.created_by ? fullNameOrEmail(thread.root.created_by) : 'Deleted user'
+ return (
+ <PinMarker
+ key={thread.root.id}
+ threadId={thread.root.id}
+ label={`Open pin ${thread.pinNumber} from ${author}`}
+ number={thread.pinNumber}
+ active={thread.root.id === activeThreadId}
+ onClick={() => activateThread(thread.root.id)}
+ anchor={thread.anchor}
+ />
+ )
+ })}
+ {pendingRegion && (
+ <>
+ <PinMarker label="New pin" number={null} active anchor={pendingRegion} />
+ <ArtifactPendingComment
+ logicProps={logicProps}
+ className={cn('pointer-events-auto', pendingRegion.y < 0.5 ? 'mt-1' : 'mb-8')}
+ // The box opens toward the middle of the image, so it stays on the image as far as it can.
+ style={{
+ ...(pendingRegion.y < 0.5
+ ? { top: `${(pendingRegion.y + pendingRegion.height) * 100}%` }
+ : { bottom: `${(1 - pendingRegion.y - pendingRegion.height) * 100}%` }),
+ ...(pendingRegion.x < 0.5
+ ? { left: `${pendingRegion.x * 100}%` }
+ : { right: `${(1 - pendingRegion.x - pendingRegion.width) * 100}%` }),
+ }}
+ />
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx
index e76a6974ecb3..247120536918 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx
@@ -1,4 +1,4 @@
-import { PointerEvent, useCallback, useLayoutEffect, useRef, useState } from 'react'
+import { MouseEvent, PointerEvent, ReactNode, useCallback, useLayoutEffect, useRef, useState } from 'react'
import { IconMinus, IconPlus } from '@posthog/icons'
import { Button, Separator, Text, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill-primitives'
@@ -48,8 +48,22 @@ function ZoomButton({
)
}
-/** An image preview that fits the pane, zooms in steps, and pans by drag once it overflows. */
-export function ArtifactImageViewer({ src, alt }: { src: string; alt: string }): JSX.Element {
+/**
+ * An image preview that fits the pane, zooms in steps, and pans by drag once it overflows. `overlay` sits on
+ * the image at its displayed size, so content placed in percentages stays on the same spot at every zoom.
+ * While `onPlace` is set, a click reports where it landed as shares of the image size, and drag does not pan.
+ */
+export function ArtifactImageViewer({
+ src,
+ alt,
+ overlay,
+ onPlace,
+}: {
+ src: string
+ alt: string
+ overlay?: ReactNode
+ onPlace?: (x: number, y: number) => void
+}): JSX.Element {
const paneRef = useRef<HTMLDivElement>(null)
const dragRef = useRef<{ x: number; y: number; left: number; top: number } | null>(null)
const [natural, setNatural] = useState<{ width: number; height: number } | null>(null)
@@ -82,7 +96,7 @@ export function ArtifactImageViewer({ src, alt }: { src: string; alt: string }):
const onPointerDown = (event: PointerEvent<HTMLDivElement>): void => {
const element = paneRef.current
- if (!overflows || !element || event.button !== 0) {
+ if (onPlace || !overflows || !element || event.button !== 0) {
return
}
dragRef.current = { x: event.clientX, y: event.clientY, left: element.scrollLeft, top: element.scrollTop }
@@ -98,6 +112,17 @@ export function ArtifactImageViewer({ src, alt }: { src: string; alt: string }):
element.scrollLeft = start.left - (event.clientX - start.x)
element.scrollTop = start.top - (event.clientY - start.y)
}
+ const onImageClick = (event: MouseEvent<HTMLButtonElement>): void => {
+ if (!onPlace) {
+ return
+ }
+ const box = event.currentTarget.getBoundingClientRect()
+ // A keyboard press has no pointer position, so it places the pin at the center.
+ const keyboard = event.detail === 0
+ const x = keyboard ? 0.5 : (event.clientX - box.left) / box.width
+ const y = keyboard ? 0.5 : (event.clientY - box.top) / box.height
+ onPlace(Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y)))
+ }
const endDrag = (): void => {
dragRef.current = null
setDragging(false)
@@ -115,26 +140,38 @@ export function ArtifactImageViewer({ src, alt }: { src: string; alt: string }):
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
- onDoubleClick={() => setZoom(zoom === 'fit' ? 1 : 'fit')}
+ onDoubleClick={() => !onPlace && setZoom(zoom === 'fit' ? 1 : 'fit')}
>
{/* min-size centers the image while it fits and lets the scroll area grow once it does not. */}
<div className="flex min-h-full min-w-full w-max items-center justify-center p-6">
- <img
- src={src}
- alt={alt}
- draggable={false}
- style={width ? { width } : undefined}
- className={cn(
- 'block max-w-none rounded-sm border border-border bg-white',
- !natural && 'invisible'
+ <div className="relative">
+ <img
+ src={src}
+ alt={alt}
+ draggable={false}
+ style={width ? { width } : undefined}
+ className={cn(
+ 'block max-w-none rounded-sm border border-border bg-white',
+ !natural && 'invisible'
+ )}
+ onLoad={(event) =>
+ setNatural({
+ width: event.currentTarget.naturalWidth || 1,
+ height: event.currentTarget.naturalHeight || 1,
+ })
+ }
+ />
+ {natural && onPlace && (
+ <button
+ type="button"
+ aria-label="Place a pin here"
+ className="absolute inset-0 z-10 cursor-crosshair rounded-sm"
+ onClick={onImageClick}
+ data-attr="task-artifact-image-place-pin"
+ />
)}
- onLoad={(event) =>
- setNatural({
- width: event.currentTarget.naturalWidth || 1,
- height: event.currentTarget.naturalHeight || 1,
- })
- }
- />
+ {natural && overlay}
+ </div>
</div>
</div>
{natural && (
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactPendingComment.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactPendingComment.tsx
new file mode 100644
index 000000000000..c167a2fb9f17
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactPendingComment.tsx
@@ -0,0 +1,60 @@
+import { useActions, useValues } from 'kea'
+import { CSSProperties } from 'react'
+
+import { cn } from '@posthog/quill-primitives'
+
+import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'
+import { ArtifactCommentComposer } from './ArtifactCommentComposer'
+
+export const PENDING_COMMENT_WIDTH_PX = 288
+
+/**
+ * The box for a new comment on the pinned spot or the selected text. The caller places it, because a pin
+ * and a selection measure their position in different ways.
+ */
+export function ArtifactPendingComment({
+ logicProps,
+ style,
+ className,
+}: {
+ logicProps: TaskArtifactCommentsLogicProps
+ style: CSSProperties
+ className?: string
+}): JSX.Element | null {
+ const { pendingAnchor, drafts, writing } = useValues(taskArtifactCommentsLogic(logicProps))
+ const { setDraft, submitComment, dismissPending } = useActions(taskArtifactCommentsLogic(logicProps))
+ if (!pendingAnchor) {
+ return null
+ }
+ const isText = pendingAnchor.kind === 'text'
+ return (
+ <div
+ data-quill
+ data-pending-artifact-comment
+ className={cn(
+ 'absolute z-30 w-72 rounded-md border border-border bg-background p-2 text-left shadow-md',
+ className
+ )}
+ style={style}
+ // A press inside the box must not reach the image or the text below it.
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ data-attr="task-artifact-pending-comment"
+ >
+ <ArtifactCommentComposer
+ autoFocus
+ value={drafts.pending ?? ''}
+ onChange={(value) => setDraft('pending', value)}
+ onSubmit={() => submitComment('pending')}
+ onCancel={dismissPending}
+ saving={writing === 'pending'}
+ busy={!!writing && writing !== 'pending'}
+ quote={isText ? pendingAnchor.quote : undefined}
+ label={isText ? 'Comment on the selected text' : 'Comment on this spot'}
+ placeholder={isText ? 'Add a comment about this selection' : 'Add a comment about this spot'}
+ rows={3}
+ dataAttr={isText ? 'task-artifact-comment-selection' : 'task-artifact-comment-pin'}
+ />
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactTextAnnotations.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactTextAnnotations.tsx
new file mode 100644
index 000000000000..b575fe8d0e51
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactTextAnnotations.tsx
@@ -0,0 +1,292 @@
+import { useActions, useValues } from 'kea'
+import { ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+
+import { cn } from '@posthog/quill-primitives'
+
+import { fullNameOrEmail } from 'lib/utils/strings'
+
+import { createTextCommentAnchor, resolveTextCommentAnchor } from '../artifactComments'
+import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'
+import { ArtifactPendingComment, PENDING_COMMENT_WIDTH_PX } from './ArtifactPendingComment'
+
+const EDGE_MARGIN_PX = 8
+
+interface HighlightRect {
+ id: string
+ label: string
+ left: number
+ top: number
+ width: number
+ height: number
+}
+
+interface TextNodeIndex {
+ text: string
+ entries: { node: Text; start: number; end: number }[]
+}
+
+/** The text of `root` as one string, with the text node that holds each part. */
+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 }
+}
+
+function rangeFromOffsets(index: TextNodeIndex, start: number, end: number): Range | null {
+ let startNode: Text | null = null
+ let startOffset = 0
+ for (const entry of index.entries) {
+ if (!startNode && start >= entry.start && start <= entry.end) {
+ startNode = entry.node
+ startOffset = start - entry.start
+ }
+ if (startNode && end >= entry.start && end <= entry.end) {
+ const range = document.createRange()
+ range.setStart(startNode, startOffset)
+ range.setEnd(entry.node, end - entry.start)
+ return range
+ }
+ }
+ return null
+}
+
+/** The selection as offsets into the text of `root`, the same offsets `buildTextNodeIndex` counts. */
+function selectionOffsets(root: HTMLElement, range: Range): { start: number; end: number } {
+ 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 }
+}
+
+// A fully selected inline element reports its own box and the boxes of its text, so the tints would stack.
+// Only boxes that no other box contains stay.
+function outermostRects(rects: Iterable<DOMRect>): DOMRect[] {
+ const EPSILON = 0.5
+ const contains = (outer: DOMRect, inner: DOMRect): boolean =>
+ 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) && (otherIndex < index || !contains(rect, other))
+ )
+ )
+}
+
+/**
+ * Text that people can select to comment on, with a tint on each open text thread. Offsets count the
+ * rendered text, the same way PostHog Desktop counts them, so a highlight written in either app shows in both.
+ */
+export function ArtifactTextAnnotations({
+ logicProps,
+ children,
+}: {
+ logicProps: TaskArtifactCommentsLogicProps
+ children: ReactNode
+}): JSX.Element {
+ const logic = taskArtifactCommentsLogic(logicProps)
+ const { anchoredThreads, activeThreadId, pendingAnchor, pendingPosition } = useValues(logic)
+ const { activateThread, setPendingAnchor, dismissPending } = useActions(logic)
+ const containerRef = useRef<HTMLDivElement>(null)
+ const rootRef = useRef<HTMLDivElement>(null)
+ const [rects, setRects] = useState<HighlightRect[]>([])
+
+ const textThreads = useMemo(
+ () => anchoredThreads.filter((thread) => thread.anchor?.kind === 'text'),
+ [anchoredThreads]
+ )
+
+ const recalculate = useCallback(() => {
+ const root = rootRef.current
+ const container = containerRef.current
+ if (!root || !container) {
+ return
+ }
+ const index = buildTextNodeIndex(root)
+ const box = container.getBoundingClientRect()
+ // Client rects include CSS transforms, such as the full page dialog's open animation, but the highlights
+ // are placed in the container's own layout pixels. A transform does not resize the container, so no
+ // observer measures again after it ends.
+ const scaleX = box.width / container.offsetWidth || 1
+ const scaleY = box.height / container.offsetHeight || 1
+ const next: HighlightRect[] = []
+ for (const thread of textThreads) {
+ if (thread.anchor?.kind !== 'text') {
+ continue
+ }
+ const resolved = resolveTextCommentAnchor(index.text, thread.anchor)
+ const range = resolved ? rangeFromOffsets(index, resolved.start, resolved.end) : null
+ if (!range) {
+ continue
+ }
+ const author = thread.root.created_by ? fullNameOrEmail(thread.root.created_by) : 'Deleted user'
+ for (const rect of outermostRects(range.getClientRects())) {
+ next.push({
+ id: thread.root.id,
+ label: `Open comment from ${author}`,
+ left: (rect.left - box.left) / scaleX,
+ top: (rect.top - box.top) / scaleY,
+ width: rect.width / scaleX,
+ height: rect.height / scaleY,
+ })
+ }
+ }
+ setRects(next)
+ }, [textThreads])
+
+ const recalculateRef = useRef(recalculate)
+ useEffect(() => {
+ recalculateRef.current = recalculate
+ recalculate()
+ }, [recalculate])
+
+ // Text wraps again when the pane resizes, and markdown can finish rendering after mount.
+ useEffect(() => {
+ const root = rootRef.current
+ if (!root) {
+ return
+ }
+ let frame = 0
+ const update = (): void => {
+ cancelAnimationFrame(frame)
+ frame = requestAnimationFrame(() => recalculateRef.current())
+ }
+ const resizeObserver = new ResizeObserver(update)
+ const mutationObserver = new MutationObserver(update)
+ resizeObserver.observe(root)
+ mutationObserver.observe(root, { childList: true, characterData: true, subtree: true })
+ return () => {
+ cancelAnimationFrame(frame)
+ resizeObserver.disconnect()
+ mutationObserver.disconnect()
+ }
+ }, [])
+
+ // A pick in the comments panel scrolls its quote into view.
+ useEffect(() => {
+ const root = rootRef.current
+ const thread = textThreads.find((candidate) => candidate.root.id === activeThreadId)
+ if (!root || thread?.anchor?.kind !== 'text') {
+ return
+ }
+ const index = buildTextNodeIndex(root)
+ const resolved = resolveTextCommentAnchor(index.text, thread.anchor)
+ const range = resolved ? rangeFromOffsets(index, resolved.start, resolved.end) : null
+ range?.startContainer.parentElement?.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ // Only a change of the active thread scrolls. A poll that refreshes the threads must not.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeThreadId])
+
+ useEffect(() => {
+ let frame = 0
+ const readSelection = (): void => {
+ const root = rootRef.current
+ const container = containerRef.current
+ if (!root || !container) {
+ return
+ }
+ const selection = window.getSelection()
+ const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null
+ if (
+ !range ||
+ range.collapsed ||
+ !root.contains(range.startContainer) ||
+ !root.contains(range.endContainer)
+ ) {
+ if (logic.values.pendingAnchor?.kind === 'text') {
+ dismissPending()
+ }
+ return
+ }
+ const offsets = selectionOffsets(root, range)
+ const anchor = createTextCommentAnchor(buildTextNodeIndex(root).text, offsets.start, offsets.end)
+ if (!anchor) {
+ return
+ }
+ // The box opens under the last line of the selection, where the pointer let go.
+ const rects = Array.from(range.getClientRects()).filter((rect) => rect.width > 0)
+ const end = rects.at(-1) ?? range.getBoundingClientRect()
+ const box = container.getBoundingClientRect()
+ const scaleX = box.width / container.offsetWidth || 1
+ const scaleY = box.height / container.offsetHeight || 1
+ const maxLeft = container.clientWidth - PENDING_COMMENT_WIDTH_PX - EDGE_MARGIN_PX
+ setPendingAnchor(anchor, {
+ left: Math.max(EDGE_MARGIN_PX, Math.min((end.left - box.left) / scaleX, maxLeft)),
+ top: (end.bottom - box.top) / scaleY + 6,
+ })
+ }
+ const onRelease = (event: Event): void => {
+ const target = event.target
+ if (target instanceof Element && target.closest('[data-pending-artifact-comment]')) {
+ return
+ }
+ if (event instanceof KeyboardEvent && !event.shiftKey) {
+ return
+ }
+ cancelAnimationFrame(frame)
+ frame = requestAnimationFrame(readSelection)
+ }
+ document.addEventListener('pointerup', onRelease)
+ document.addEventListener('keyup', onRelease)
+ return () => {
+ cancelAnimationFrame(frame)
+ document.removeEventListener('pointerup', onRelease)
+ document.removeEventListener('keyup', onRelease)
+ }
+ }, [logic, setPendingAnchor, dismissPending])
+
+ const firstRectIndex = new Map<string, number>()
+ rects.forEach((rect, index) => {
+ if (!firstRectIndex.has(rect.id)) {
+ firstRectIndex.set(rect.id, index)
+ }
+ })
+
+ return (
+ <div ref={containerRef} className="relative">
+ <div ref={rootRef}>{children}</div>
+ <div className="pointer-events-none absolute inset-0 z-10">
+ {rects.map((rect, index) => (
+ <button
+ // A quote can wrap over several lines, so one thread can have several boxes.
+ key={`${rect.id}-${index}`}
+ type="button"
+ tabIndex={firstRectIndex.get(rect.id) === index ? 0 : -1}
+ aria-label={rect.label}
+ // The same yellow as PostHog Desktop in both themes, so a highlight reads on dark text too.
+ className={cn(
+ 'pointer-events-auto absolute cursor-pointer rounded-xs',
+ rect.id === activeThreadId
+ ? 'border-b-2 border-warning bg-yellow-400/50'
+ : 'bg-yellow-400/30 hover:bg-yellow-400/45'
+ )}
+ // Positions come from measured text boxes, which utility classes cannot express.
+ style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height }}
+ onClick={() => activateThread(rect.id)}
+ data-attr="task-artifact-comment-highlight"
+ />
+ ))}
+ </div>
+ {pendingAnchor?.kind === 'text' && pendingPosition && (
+ <ArtifactPendingComment
+ logicProps={logicProps}
+ style={{ left: pendingPosition.left, top: pendingPosition.top }}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
index 4bb616dd1011..8cf2a6fc0224 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
@@ -72,9 +72,9 @@ import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { isCommentableArtifact } from '../artifactComments'
+import { isCommentableArtifact, regionAnchorAt, supportsSelectionComments } from '../artifactComments'
import { withStrictCsp } from '../artifactHtml'
-import { TaskArtifactCommentsLogicProps } from '../taskArtifactCommentsLogic'
+import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'
import {
ArtifactFile,
ArtifactPreviewKind,
@@ -97,7 +97,9 @@ import { ArtifactCommentsPanel } from './ArtifactCommentsPanel'
import { ArtifactEditor } from './ArtifactEditor'
import { ArtifactEditToolbar } from './ArtifactEditToolbar'
import { ArtifactIcon } from './ArtifactIcon'
+import { ArtifactImagePins } from './ArtifactImagePins'
import { ArtifactImageViewer } from './ArtifactImageViewer'
+import { ArtifactTextAnnotations } from './ArtifactTextAnnotations'
const MAX_CSV_ROWS = 500
@@ -253,6 +255,37 @@ function SourceView({ text }: { text: string }): JSX.Element {
)
}
+function MarkdownArticle({ text }: { text: string }): JSX.Element {
+ return (
+ <div className="px-6 py-8">
+ <article className="mx-auto max-w-3xl rounded-lg border border-border bg-card px-10 py-8 text-card-foreground">
+ <LemonMarkdown disableImages="all">{text}</LemonMarkdown>
+ </article>
+ </div>
+ )
+}
+
+function CommentableImage({
+ logicProps,
+ src,
+ alt,
+}: {
+ logicProps: TaskArtifactCommentsLogicProps
+ src: string
+ alt: string
+}): JSX.Element {
+ const { pinMode } = useValues(taskArtifactCommentsLogic(logicProps))
+ const { setPendingAnchor } = useActions(taskArtifactCommentsLogic(logicProps))
+ return (
+ <ArtifactImageViewer
+ src={src}
+ alt={alt}
+ overlay={<ArtifactImagePins logicProps={logicProps} />}
+ onPlace={pinMode ? (x, y) => setPendingAnchor(regionAnchorAt(x, y), null) : undefined}
+ />
+ )
+}
+
function TextLoading(): JSX.Element {
return (
<div className="px-6 py-8">
@@ -398,9 +431,17 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }
if (!selectedArtifact || !selectedKind) {
return null
}
+ const comments = commentLogicProps(taskId, selectedArtifact, selectedKind)
if (selectedKind === 'image') {
const src = artifactDownloadUrl(currentProjectId, taskId, selectedArtifact)
- return src ? <ArtifactImageViewer key={selectedArtifact.id} src={src} alt={selectedArtifact.name} /> : null
+ if (!src) {
+ return null
+ }
+ return comments ? (
+ <CommentableImage key={selectedArtifact.id} logicProps={comments} src={src} alt={selectedArtifact.name} />
+ ) : (
+ <ArtifactImageViewer key={selectedArtifact.id} src={src} alt={selectedArtifact.name} />
+ )
}
if (selectedKind === 'reference') {
return <ReferencePreview taskId={taskId} artifact={selectedArtifact} />
@@ -461,6 +502,18 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }
</Empty>
)
}
+ // Desktop counts a markdown quote in the rendered page, not in the source, so only the page takes selections.
+ if (comments && supportsSelectionComments(selectedKind) && (mode === 'rendered' || selectedKind === 'text')) {
+ return (
+ <ArtifactTextAnnotations key={selectedArtifact.id} logicProps={comments}>
+ {selectedKind === 'markdown' ? (
+ <MarkdownArticle text={selectedText.text} />
+ ) : (
+ <SourceView text={selectedText.text} />
+ )}
+ </ArtifactTextAnnotations>
+ )
+ }
if (mode === 'source') {
return <SourceView text={selectedText.text} />
}
@@ -471,13 +524,7 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }
return <CsvPreview text={selectedText.text} />
}
if (selectedKind === 'markdown') {
- return (
- <div className="px-6 py-8">
- <article className="mx-auto max-w-3xl rounded-lg border border-border bg-card px-10 py-8 text-card-foreground">
- <LemonMarkdown disableImages="all">{selectedText.text}</LemonMarkdown>
- </article>
- </div>
- )
+ return <MarkdownArticle text={selectedText.text} />
}
return <SourceView text={selectedText.text} />
}