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.

fix(desktop): fix selection comment submission and scrolling (#80247)

Shy Alter1b4c92388e8e
diff --git a/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts b/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts
index 44351f3eb6a9..c3f74725e051 100644
--- a/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts
+++ b/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts
@@ -39,6 +39,18 @@ describe("sanitizeArtifactBridgeMessage", () => {
expect(sanitized).not.toHaveProperty("untrustedPayload");
});
+ it("accepts bounded selection position updates", () => {
+ const rect = selectionMessage().rect;
+ const message = {
+ marker,
+ channel: "artifact-comments-1",
+ type: "selection-position",
+ rect,
+ };
+
+ expect(sanitizeArtifactBridgeMessage(message)).toEqual(message);
+ });
+
it.each([
["an oversized quote", { anchor: { quote: "x".repeat(10_001) } }],
[
@@ -51,6 +63,10 @@ describe("sanitizeArtifactBridgeMessage", () => {
})),
},
],
+ [
+ "an invalid selection position",
+ { type: "selection-position", rect: { top: Number.POSITIVE_INFINITY } },
+ ],
["an unsupported message", { type: "open-external" }],
])("rejects %s", (_name, override) => {
const value = selectionMessage();
diff --git a/products/desktop/apps/code/src/shared/artifact-preview-message.ts b/products/desktop/apps/code/src/shared/artifact-preview-message.ts
index b9aa47530bd7..697b53c4816f 100644
--- a/products/desktop/apps/code/src/shared/artifact-preview-message.ts
+++ b/products/desktop/apps/code/src/shared/artifact-preview-message.ts
@@ -39,6 +39,10 @@ export function sanitizeArtifactBridgeMessage(
channel: value.channel,
};
if (value.type === "ready") return { ...base, type: "ready" };
+ if (value.type === "selection-position") {
+ const rect = finiteRect(value.rect);
+ return rect ? { ...base, type: "selection-position", rect } : null;
+ }
if (
value.type === "activate" &&
boundedString(value.id, MAX_ID_LENGTH) &&
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 5543a1a699c4..31783ba01539 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
@@ -153,6 +153,7 @@ describe("activityHeadline", () => {
threadId: "comment-1",
nonce: expect.any(Number),
openCommentsTab: true,
+ intent: "navigate",
});
});
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
index 64cafa55db79..0f27d899cd47 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx
@@ -425,6 +425,7 @@ describe("TaskCommentsList", () => {
threadId: "comment-1",
nonce: expect.any(Number),
openCommentsTab: true,
+ intent: "navigate",
});
});
@@ -448,6 +449,46 @@ describe("TaskCommentsList", () => {
});
});
+ it("scrolls the comment pane without reopening the selected artifact", () => {
+ const animationFrame = vi
+ .spyOn(globalThis, "requestAnimationFrame")
+ .mockImplementation((callback) => {
+ callback(0);
+ return 0;
+ });
+ render(<TaskCommentsList task={task} timeline={[]} />);
+ const thread = screen
+ .getByText("Tighten this summary")
+ .closest("[data-comment-thread-id]") as HTMLElement;
+ const pane = thread.parentElement as HTMLElement;
+ Object.defineProperty(pane, "scrollTop", { value: 20, writable: true });
+ pane.getBoundingClientRect = () => ({ top: 0, bottom: 100 }) as DOMRect;
+ thread.getBoundingClientRect = () => ({ top: 120, bottom: 160 }) as DOMRect;
+ const paneScroll = vi.spyOn(pane, "scrollTo");
+ const outerScroll = vi.spyOn(Element.prototype, "scrollIntoView");
+
+ act(() => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "task_artifact", itemId: "a" },
+ "comment-1",
+ { intent: "reveal-thread" },
+ );
+ });
+
+ expect(paneScroll).toHaveBeenCalledWith({
+ top: 80,
+ behavior: "smooth",
+ });
+ expect(outerScroll).not.toHaveBeenCalled();
+ expect(mocks.openArtifactTab).not.toHaveBeenCalled();
+ paneScroll.mockRestore();
+ outerScroll.mockRestore();
+ animationFrame.mockRestore();
+ });
+
it("opens the saved canvas version when activity requests its thread", () => {
const onCanvasCommentOpen = vi.fn();
mocks.comments = [
@@ -745,7 +786,7 @@ describe("TaskCommentsList", () => {
});
// Not every comment belongs to a deliverable; some are about the work.
- it("posts a comment on the task itself", async () => {
+ it("posts a comment on the task itself without scrolling", async () => {
render(<TaskCommentsList task={task} timeline={[]} />);
await act(async () => {
@@ -762,13 +803,12 @@ describe("TaskCommentsList", () => {
context: { anchor: { kind: "document" } },
}),
);
- // The list is ordered by when a thread started, so the new one lands at the
- // top, away from the composer it was written in.
expect(
useCommentNavigationStore.getState().focusByTask["task-1"],
).toMatchObject({
target: { scope: "task", itemId: "task-1" },
threadId: "created-comment",
+ intent: "focus-only",
});
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
index 28968de5f4de..828b3ff5d621 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
@@ -85,6 +85,20 @@ const MAX_CONCURRENT_PR_SOURCES = 4;
type StateFilter = "open" | "resolved";
+function scrollThreadInPane(pane: HTMLElement, thread: HTMLElement): void {
+ const paneRect = pane.getBoundingClientRect();
+ const threadRect = thread.getBoundingClientRect();
+ const offset =
+ threadRect.top < paneRect.top
+ ? threadRect.top - paneRect.top
+ : threadRect.bottom > paneRect.bottom
+ ? threadRect.bottom - paneRect.bottom
+ : 0;
+ if (offset !== 0) {
+ pane.scrollTo({ top: pane.scrollTop + offset, behavior: "smooth" });
+ }
+}
+
/** 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) {
@@ -316,6 +330,7 @@ export function TaskCommentsList({
const [sourceFilter, setSourceFilter] = useState<string>(ALL_SOURCES);
const [pulseThreadId, setPulseThreadId] = useState<string | null>(null);
const [draft, setDraft] = useState("");
+ const threadListRef = useRef<HTMLDivElement>(null);
const sourceFilterTouched = useRef(false);
const previousTaskId = useRef(task.id);
@@ -556,13 +571,14 @@ export function TaskCommentsList({
: ALL_SOURCES,
);
setPulseThreadId(focus.threadId);
- openThread(focused, false);
+ if (focus.intent === "navigate") openThread(focused, false);
+ if (focus.intent === "focus-only") return;
requestAnimationFrame(() => {
- document
- .querySelector(
- `[data-comment-thread-id="${CSS.escape(focus.threadId)}"]`,
- )
- ?.scrollIntoView({ behavior: "smooth", block: "nearest" });
+ const pane = threadListRef.current;
+ const thread = pane?.querySelector<HTMLElement>(
+ `[data-comment-thread-id="${CSS.escape(focus.threadId)}"]`,
+ );
+ if (pane && thread) scrollThreadInPane(pane, thread);
});
}, [focus, openThread, threads, task.id]);
// The pulse fades on its own; owning the timer in its own effect keeps it
@@ -660,7 +676,10 @@ export function TaskCommentsList({
</DropdownMenuContent>
</DropdownMenu>
</header>
- <div className="min-h-0 flex-1 space-y-2 overflow-y-auto px-2 pt-3 pb-2">
+ <div
+ ref={threadListRef}
+ className="min-h-0 flex-1 space-y-2 overflow-y-auto px-2 pt-3 pb-2"
+ >
{loadFailed ? (
<Empty className="py-8">
<EmptyHeader>
@@ -740,10 +759,9 @@ export function TaskCommentsList({
mentions,
});
setDraft("");
- // Show the thread that was just opened. The list is ordered by when
- // a thread started, so a new one lands at the top, away from the
- // composer — focusing it clears the filters hiding it and scrolls.
- requestCommentFocus(task.id, composerTarget, created.id);
+ requestCommentFocus(task.id, composerTarget, created.id, {
+ intent: "focus-only",
+ });
}}
members={members}
placeholder={`Comment on this ${onlySource ? "canvas" : "task"}… Type @ to mention someone`}
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsx
index 3c22b24ca81f..4370f006d48b 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsx
@@ -1,4 +1,5 @@
import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CanvasSelectionCommentAction } from "./CanvasSelectionCommentAction";
@@ -41,6 +42,10 @@ describe("CanvasSelectionCommentAction", () => {
beforeEach(() => {
mutateAsync.mockReset();
useCanvasChatPanelStore.setState({ collapsed: true, tab: "chat" });
+ useCommentNavigationStore.setState({
+ focusByTask: {},
+ resolutionsByTarget: {},
+ });
});
it("creates the text-anchored comment and opens the comments tab", async () => {
@@ -65,6 +70,10 @@ describe("CanvasSelectionCommentAction", () => {
fireEvent.click(screen.getByText("Submit selection comment"));
+ expect(useCanvasChatPanelStore.getState()).toMatchObject({
+ collapsed: false,
+ tab: "comments",
+ });
expect(mutateAsync).toHaveBeenCalledWith({
content: "Please revise this",
context: {
@@ -80,11 +89,13 @@ describe("CanvasSelectionCommentAction", () => {
},
mentions: [4],
});
- await waitFor(() => {
- expect(useCanvasChatPanelStore.getState()).toMatchObject({
- collapsed: false,
- tab: "comments",
- });
- });
+ await waitFor(() =>
+ expect(
+ useCommentNavigationStore.getState().focusByTask["task-1"],
+ ).toMatchObject({
+ threadId: "comment-1",
+ intent: "focus-only",
+ }),
+ );
});
});
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx
index 3e5818798acc..882807a0baae 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx
@@ -62,6 +62,7 @@ export function CanvasSelectionCommentAction({
onDismiss={onDismiss}
onSubmit={async (_start, _end, content, mentions) => {
if (!anchor || !taskId) return;
+ openComments();
const comment = await createComment.mutateAsync({
content,
context: {
@@ -70,10 +71,11 @@ export function CanvasSelectionCommentAction({
},
mentions,
});
- openComments();
useCommentNavigationStore
.getState()
- .requestCommentFocus(taskId, target, comment.id);
+ .requestCommentFocus(taskId, target, comment.id, {
+ intent: "focus-only",
+ });
}}
/>
);
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
index 25fb443ee471..ca3e2819082f 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
@@ -345,7 +345,9 @@ export function FreeformCanvasView({
useCanvasChatPanelStore.getState().openComments();
useCommentNavigationStore
.getState()
- .requestCommentFocus(commentTaskId, commentTarget, id);
+ .requestCommentFocus(commentTaskId, commentTarget, id, {
+ intent: "reveal-thread",
+ });
},
[commentTaskId, commentTarget],
);
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
index c3ab018e0719..dbea7d41f3e3 100644
--- 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
@@ -89,6 +89,7 @@ describe("SelectionCommentOverlay", () => {
resolveSubmit = resolve;
}),
);
+ const onDismiss = vi.fn();
render(
<SelectionCommentOverlay
selection={{
@@ -100,7 +101,7 @@ describe("SelectionCommentOverlay", () => {
open
filePath="report.md"
onSubmit={onSubmit}
- onDismiss={vi.fn()}
+ onDismiss={onDismiss}
initiallyExpanded
members={[]}
/>,
@@ -115,10 +116,11 @@ describe("SelectionCommentOverlay", () => {
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(submit).toHaveAttribute("aria-disabled", "true");
+ expect(submit).toHaveAttribute("aria-busy", "true");
resolveSubmit?.();
- await waitFor(() =>
- expect(submit).toHaveAttribute("aria-disabled", "false"),
- );
+ await waitFor(() => expect(onDismiss).toHaveBeenCalledOnce());
+ expect(submit).toHaveAttribute("aria-disabled", "false");
+ expect(submit).not.toHaveAttribute("aria-busy");
});
it("keeps the draft open when comment creation fails", async () => {
diff --git a/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts b/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts
index 25276799b7fb..fba321bdbe3d 100644
--- a/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts
+++ b/products/desktop/packages/ui/src/features/sessions/commentNavigationStore.ts
@@ -5,6 +5,8 @@ import {
import type { HighlightResolution } from "@posthog/ui/features/sessions/components/commentViewTypes";
import { create } from "zustand";
+type CommentFocusIntent = "navigate" | "reveal-thread" | "focus-only";
+
/** Which thread the task's comment surfaces are pointed at right now. */
type CommentFocus = {
target: CommentTarget;
@@ -12,6 +14,7 @@ type CommentFocus = {
/** Bumped on every request so re-picking the same thread scrolls again. */
nonce: number;
openCommentsTab: boolean;
+ intent: CommentFocusIntent;
};
interface CommentNavigationStoreState {
@@ -26,6 +29,7 @@ interface CommentNavigationStoreActions {
taskId: string,
target: CommentTarget,
threadId: string,
+ options?: { intent?: CommentFocusIntent },
) => void;
setCommentResolutions: (
target: CommentTarget,
@@ -64,12 +68,18 @@ export const useCommentNavigationStore = create<CommentNavigationStore>()(
focusByTask: {},
resolutionsByTarget: {},
- requestCommentFocus: (taskId, target, threadId) => {
+ requestCommentFocus: (taskId, target, threadId, options) => {
nonce += 1;
set((state) => ({
focusByTask: {
...state.focusByTask,
- [taskId]: { target, threadId, nonce, openCommentsTab: true },
+ [taskId]: {
+ target,
+ threadId,
+ nonce,
+ openCommentsTab: true,
+ intent: options?.intent ?? "navigate",
+ },
},
}));
},
diff --git a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
index b64e87517138..405533403b90 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
@@ -10,6 +10,10 @@ import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
import { useCallback, useMemo, useRef, useState } from "react";
+import {
+ selectionAnchor,
+ withSelectionPosition,
+} from "./artifactHtmlCommentPosition";
import { ArtifactHtmlFrame } from "./artifactHtmlFrame";
import {
ARTIFACT_HTML_BRIDGE_MARKER,
@@ -91,6 +95,7 @@ export function AnnotatedArtifactHtml({
[commentsEnabled, html, initialTheme],
);
+ const selectionOpen = selection !== null;
const bridgeItems = useMemo(
() =>
comments.flatMap((comment) => {
@@ -125,16 +130,24 @@ export function AnnotatedArtifactHtml({
items: bridgeItems,
},
];
+ if (!selectionOpen) {
+ next.push({
+ marker: ARTIFACT_HTML_BRIDGE_MARKER,
+ channel: channelRef.current,
+ type: "selection-dismissed",
+ });
+ }
if (locateRequest) {
next.push({
marker: ARTIFACT_HTML_BRIDGE_MARKER,
channel: channelRef.current,
type: "locate",
id: locateRequest.id,
+ nonce: locateRequest.nonce,
});
}
return next;
- }, [bridgeItems, commentsEnabled, locateRequest, theme]);
+ }, [bridgeItems, commentsEnabled, locateRequest, selectionOpen, theme]);
const receive = useCallback(
(value: unknown, frameBox: ArtifactHtmlFrameRect) => {
@@ -167,7 +180,14 @@ export function AnnotatedArtifactHtml({
onResolutionsChange(resolutions);
return;
}
- if (data.type !== "selection" || !isFrameRect(data.triggerRect)) return;
+ if (data.type === "selection-position" && isFrameRect(data.rect)) {
+ const rect = data.rect;
+ setSelection((current) =>
+ withSelectionPosition(current, frameBox, rect),
+ );
+ return;
+ }
+ if (data.type !== "selection" || !isFrameRect(data.rect)) return;
const parsed = commentAnchorSchema.safeParse(data.anchor);
if (!parsed.success || parsed.data.kind !== "text") return;
setPendingAnchor(parsed.data);
@@ -175,11 +195,7 @@ export function AnnotatedArtifactHtml({
text: parsed.data.quote,
fromLine: parsed.data.start + 1,
toLine: parsed.data.end + 1,
- anchor: {
- top: frameBox.top + data.triggerRect.top,
- endX: frameBox.left + data.triggerRect.left,
- bottom: frameBox.top + data.triggerRect.bottom,
- },
+ anchor: selectionAnchor(frameBox, data.rect),
});
},
[onActivateThread, onResolutionsChange],
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 4c322c4276f0..ecec3024830f 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
@@ -650,6 +650,12 @@ describe("ArtifactPreview", () => {
},
mentions: [],
});
+ expect(
+ useCommentNavigationStore.getState().focusByTask["task-1"],
+ ).toMatchObject({
+ threadId: "created-comment",
+ intent: "focus-only",
+ });
});
it("dismisses the Markdown comment action when clicking away", async () => {
@@ -860,7 +866,9 @@ describe("ArtifactPreview", () => {
threadId: "comment-1",
nonce: expect.any(Number),
openCommentsTab: true,
+ intent: "reveal-thread",
});
+ expect(scrollIntoView).not.toHaveBeenCalled();
});
it("scrolls to the anchor the list asks for", async () => {
@@ -1285,13 +1293,12 @@ describe("ArtifactPreview", () => {
expect(document).toContain("posthog-artifact-comment-active");
expect(document).not.toContain("ph-artifact-comment-outline");
expect(document).toContain("<span>Comment</span>");
- 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('channel: "test-channel"');
expect(document).toContain("new MutationObserver");
+ expect(document).toContain("scrollIntoView");
expect(document).toContain("state.renderTimer");
+ expect(document).toContain('send("selection-position"');
+ expect(document).not.toMatch(/__spreadValues|cov_\w+/);
expect(document).toMatch(/script-src &#39;nonce-[^&]+&#39;/);
expect(document).not.toContain(
"script-src &#39;self&#39; &#39;unsafe-inline&#39;",
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 c232f55300a4..c7f1e3633084 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
@@ -229,7 +229,7 @@ export function ArtifactPreview({
const [locateRequest, setLocateRequest] =
useState<CommentLocateRequest | null>(null);
useEffect(() => {
- if (!focus || !focusedThreadId) return;
+ if (!focus || !focusedThreadId || focus.intent !== "navigate") return;
if (!threads.some((thread) => thread.root.id === focusedThreadId)) return;
setLocateRequest((current) =>
current?.nonce === focus.nonce
@@ -237,9 +237,19 @@ export function ArtifactPreview({
: { id: focusedThreadId, nonce: focus.nonce },
);
}, [focus, focusedThreadId, threads]);
+ const currentLocateRequest =
+ focus &&
+ focus.intent === "navigate" &&
+ focusedThreadId &&
+ locateRequest?.nonce === focus.nonce
+ ? locateRequest
+ : null;
const activateThread = useCallback(
- (id: string) => requestCommentFocus(taskId, commentTarget, id),
+ (id: string) =>
+ requestCommentFocus(taskId, commentTarget, id, {
+ intent: "reveal-thread",
+ }),
[requestCommentFocus, taskId, commentTarget],
);
const onResolutionsChange = useCallback(
@@ -254,9 +264,11 @@ export function ArtifactPreview({
context: { anchor },
mentions,
});
- activateThread(created.id);
+ requestCommentFocus(taskId, commentTarget, created.id, {
+ intent: "focus-only",
+ });
},
- [createComment, activateThread],
+ [commentTarget, createComment, requestCommentFocus, taskId],
);
const versionNav =
@@ -342,7 +354,7 @@ export function ArtifactPreview({
markdownContainerRef={markdownContainerRef}
annotationComments={annotationComments}
focusedThreadId={focusedThreadId}
- locateRequest={locateRequest}
+ locateRequest={currentLocateRequest}
members={members}
activateThread={activateThread}
createAnchoredComment={createAnchoredComment}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.integration.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.integration.test.tsx
new file mode 100644
index 000000000000..8eefc42881b7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.integration.test.tsx
@@ -0,0 +1,31 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { CommentComposer } from "./CommentComposer";
+
+describe("CommentComposer submission", () => {
+ it.each(["enter", "send"] as const)(
+ "submits the current comment with %s",
+ (input) => {
+ const onSubmit = vi.fn();
+ const { container } = render(
+ <CommentComposer
+ value="Check this"
+ onValueChange={vi.fn()}
+ onSubmit={onSubmit}
+ members={[]}
+ placeholder="Comment"
+ />,
+ );
+
+ if (input === "enter") {
+ const editor = container.querySelector(".ProseMirror");
+ expect(editor).not.toBeNull();
+ fireEvent.keyDown(editor as Element, { key: "Enter" });
+ } else {
+ fireEvent.click(screen.getByLabelText("Comment"));
+ }
+
+ expect(onSubmit).toHaveBeenCalledWith("Check this", []);
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
index dedb2f2cd682..fe042a23d131 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
@@ -72,6 +72,7 @@ export function CommentComposer({
size="icon-sm"
aria-label={submitLabel}
disabled={!value.trim() || disabled}
+ loading={disabled}
onClick={submit}
>
<PaperPlaneRightIcon />
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
index df6fd99646ac..e03f5e1f9365 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
@@ -1,6 +1,6 @@
// @ts-expect-error jsdom ships no bundled types; only the test harness needs it
import { JSDOM } from "jsdom";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { injectArtifactHtmlCommentBridge } from "./artifactHtmlCommentBridge";
import { COMMENT_ACTION_BUTTON_THEMES } from "./selectionCommentAction";
@@ -86,7 +86,12 @@ function activateAction(dom: JSDOM): void {
const element = actionButton(dom);
if (!element) throw new Error("missing comment action");
element.dispatchEvent(
- new dom.window.MouseEvent("mousedown", { bubbles: true, composed: true }),
+ new dom.window.MouseEvent("click", {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ detail: 1,
+ }),
);
}
@@ -159,18 +164,8 @@ describe("artifactHtmlCommentBridge", () => {
pressOn(dom, "p");
selectParagraph(dom);
releaseOn(dom, "p");
- const button = actionButton(dom);
- if (!button) throw new Error("missing comment action");
- button.getBoundingClientRect = () =>
- ({
- top: 32,
- left: 118,
- right: 222,
- bottom: 60,
- width: 104,
- height: 28,
- }) as DOMRect;
-
+ pressAction(dom);
+ dom.window.getSelection()?.removeAllRanges();
activateAction(dom);
expect(messages).toHaveLength(1);
@@ -193,18 +188,114 @@ describe("artifactHtmlCommentBridge", () => {
height: 20,
},
triggerRect: {
- top: 32,
- left: 118,
- right: 222,
- bottom: 60,
- width: 104,
- height: 28,
+ top: expect.any(Number),
+ left: expect.any(Number),
+ right: expect.any(Number),
+ bottom: expect.any(Number),
+ width: expect.any(Number),
+ height: expect.any(Number),
},
});
expect(actionButton(dom)?.style.display).toBe("none");
dom.window.close();
});
+ it("updates the active composer position when the artifact scrolls", () => {
+ const dom = loadBridgeDocument(
+ "<html><body><p>some selectable text here</p></body></html>",
+ );
+ const messages: Array<Record<string, unknown>> = [];
+ dom.window.postMessage = ((message: Record<string, unknown>) => {
+ messages.push(message);
+ }) as typeof dom.window.postMessage;
+
+ pressOn(dom, "p");
+ selectParagraph(dom);
+ const range = dom.window.getSelection()?.getRangeAt(0);
+ if (!range) throw new Error("missing selected range");
+ let top = 50;
+ range.getClientRects = () =>
+ [
+ {
+ top,
+ left: 70,
+ right: 110,
+ bottom: top + 10,
+ width: 40,
+ height: 10,
+ },
+ ] as unknown as DOMRectList;
+ releaseOn(dom, "p");
+ pressAction(dom);
+ dom.window.getSelection()?.removeAllRanges();
+ activateAction(dom);
+
+ top = 20;
+ dom.window.document.dispatchEvent(new dom.window.Event("scroll"));
+
+ expect(messages.at(-1)).toMatchObject({
+ type: "selection-position",
+ rect: { top: 20, right: 110, bottom: 30 },
+ });
+ const positionCount = messages.filter(
+ (message) => message.type === "selection-position",
+ ).length;
+
+ dom.window.dispatchEvent(
+ new dom.window.MessageEvent("message", {
+ data: {
+ marker: BRIDGE_MARKER,
+ channel: CHANNEL,
+ type: "selection-dismissed",
+ },
+ source: dom.window,
+ }),
+ );
+ top = 10;
+ dom.window.document.dispatchEvent(new dom.window.Event("scroll"));
+
+ expect(
+ messages.filter((message) => message.type === "selection-position"),
+ ).toHaveLength(positionCount);
+ dom.window.close();
+ });
+
+ it("locates each navigation request only once", () => {
+ const dom = loadBridgeDocument("<html><body><p>text</p></body></html>");
+ const scrollIntoView = vi.fn();
+ dom.window.Element.prototype.scrollIntoView = scrollIntoView;
+ const send = (data: Record<string, unknown>) =>
+ dom.window.dispatchEvent(
+ new dom.window.MessageEvent("message", {
+ data: { marker: BRIDGE_MARKER, channel: CHANNEL, ...data },
+ source: dom.window,
+ }),
+ );
+
+ send({
+ type: "comments",
+ items: [
+ {
+ id: "comment-1",
+ anchor: {
+ kind: "text",
+ quote: "text",
+ prefix: "",
+ suffix: "",
+ start: 0,
+ end: 4,
+ },
+ },
+ ],
+ });
+ send({ type: "locate", id: "comment-1", nonce: 1 });
+ send({ type: "locate", id: "comment-1", nonce: 1 });
+ send({ type: "locate", id: "comment-1", nonce: 2 });
+
+ expect(scrollIntoView).toHaveBeenCalledTimes(2);
+ dom.window.close();
+ });
+
it.each(["light", "dark"] as const)(
"applies the %s theme to the isolated comment action",
(theme) => {
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
index 336ebdfeb2fa..5f4dac40f83b 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
@@ -1,4 +1,7 @@
-import { resolveTextCommentAnchor } from "@posthog/core/comments/anchors";
+import {
+ resolveTextCommentAnchor,
+ type TextCommentAnchor,
+} from "@posthog/core/comments/anchors";
import {
COMMENT_ACTION_BUTTON_THEMES,
COMMENT_ACTION_ICON_SVG,
@@ -12,6 +15,432 @@ import {
const BRIDGE_MARKER = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
+type BridgeComment = {
+ id: string;
+ anchor: TextCommentAnchor;
+ active?: boolean;
+};
+
+type BridgeRect = {
+ top: number;
+ left: number;
+ right: number;
+ bottom: number;
+ width: number;
+ height: number;
+};
+
+type BridgeSelectionMessage = {
+ anchor: TextCommentAnchor;
+ rect: BridgeRect;
+ triggerRect: BridgeRect;
+};
+
+type BridgeRuntimeOptions = {
+ channel: string;
+ marker: string;
+ initialTheme: CommentSurfaceTheme;
+ themes: typeof COMMENT_ACTION_BUTTON_THEMES;
+ actionIcon: string;
+ buttonCss: string;
+ setActionTheme: typeof setCommentActionTheme;
+ placeAction: typeof computeCommentActionPlacement;
+ anchorRect: typeof commentActionAnchorRect;
+ resolveAnchor: typeof resolveTextCommentAnchor;
+ installSelectionSettleGate: typeof installSelectionSettleGate;
+};
+
+// This function is serialized into the isolated artifact document. Keep it
+// self-contained and pass every external dependency through options.
+function runArtifactHtmlCommentBridge({
+ channel,
+ marker,
+ initialTheme,
+ themes,
+ actionIcon,
+ buttonCss,
+ setActionTheme: applyActionTheme,
+ placeAction,
+ anchorRect,
+ resolveAnchor,
+ installSelectionSettleGate: installSettleGate,
+}: BridgeRuntimeOptions): void {
+ const HighlightConstructor = window.Highlight;
+ const css = Reflect.get(window, "CSS") as typeof CSS | undefined;
+ const highlightRegistry = css?.highlights;
+ const state = {
+ button: null as HTMLButtonElement | null,
+ action: null as { message: BridgeSelectionMessage; range: Range } | null,
+ activeRange: null as Range | null,
+ selectionTimer: 0,
+ renderTimer: 0,
+ positionFrame: 0,
+ locateNonce: null as number | null,
+ entries: [] as Array<{ id: string; range: Range }>,
+ items: [] as BridgeComment[],
+ theme: initialTheme as string,
+ };
+
+ document.currentScript?.remove();
+
+ const send = (type: string, payload: Record<string, unknown> = {}): void => {
+ window.parent.postMessage({ marker, channel, type, ...payload }, "*");
+ };
+
+ const documentText = (): string => document.body?.textContent ?? "";
+
+ const rangeOffsets = (range: Range): { start: number; end: number } => {
+ const before = document.createRange();
+ before.selectNodeContents(document.body);
+ before.setEnd(range.startContainer, range.startOffset);
+ const through = document.createRange();
+ through.selectNodeContents(document.body);
+ through.setEnd(range.endContainer, range.endOffset);
+ return { start: before.toString().length, end: through.toString().length };
+ };
+
+ const makeAnchor = (range: Range): TextCommentAnchor | null => {
+ const text = documentText();
+ const { start, end } = rangeOffsets(range);
+ const quote = text.slice(start, end);
+ if (!quote.trim() || quote.length > 10_000) return null;
+ return {
+ kind: "text",
+ quote,
+ prefix: text.slice(Math.max(0, start - 32), start),
+ suffix: text.slice(end, end + 32),
+ start,
+ end,
+ };
+ };
+
+ const textIndex = (): {
+ text: string;
+ entries: Array<{ node: Text; start: number; end: number }>;
+ } => {
+ const walker = document.createTreeWalker(
+ document.body,
+ NodeFilter.SHOW_TEXT,
+ );
+ const entries: Array<{ node: Text; start: number; end: number }> = [];
+ 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 };
+ };
+
+ const rangeAt = (
+ index: ReturnType<typeof textIndex>,
+ start: number,
+ end: number,
+ ): Range | null => {
+ const find = (offset: number) => {
+ let low = 0;
+ let high = index.entries.length - 1;
+ let match: (typeof index.entries)[number] | null = null;
+ while (low <= high) {
+ const middle = (low + high) >> 1;
+ const 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;
+ };
+
+ const startEntry = find(start);
+ const endEntry = find(end);
+ if (!startEntry || !endEntry) return null;
+ try {
+ const range = document.createRange();
+ range.setStart(startEntry.node, start - startEntry.start);
+ range.setEnd(endEntry.node, end - endEntry.start);
+ return range;
+ } catch {
+ return null;
+ }
+ };
+
+ const installStyles = (): void => {
+ const style = document.createElement("style");
+ style.setAttribute("data-posthog-artifact-comments", "");
+ style.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}";
+ (document.head ?? document.documentElement).appendChild(style);
+ };
+
+ const copyRect = (rect: BridgeRect): BridgeRect => ({
+ top: rect.top,
+ left: rect.left,
+ right: rect.right,
+ bottom: rect.bottom,
+ width: rect.width,
+ height: rect.height,
+ });
+
+ const hideAction = (): void => {
+ if (state.button) state.button.style.display = "none";
+ state.action = null;
+ };
+
+ const activateAction = (event: MouseEvent): void => {
+ event.preventDefault();
+ event.stopPropagation();
+ const action = state.action;
+ if (!action) {
+ hideAction();
+ return;
+ }
+ state.activeRange = action.range;
+ send("selection", action.message);
+ hideAction();
+ window.getSelection()?.removeAllRanges();
+ };
+
+ const actionButton = (): HTMLButtonElement => {
+ if (state.button?.isConnected) return state.button;
+
+ const host = document.createElement("posthog-comment-action");
+ host.setAttribute("data-selection-comment-overlay", "");
+ host.style.cssText =
+ "all:initial!important;display:block!important;position:fixed!important;top:0!important;left:0!important;width:0!important;height:0!important;overflow:visible!important;z-index:2147483647!important";
+ const root = host.attachShadow({ mode: "open" });
+ const style = document.createElement("style");
+ style.textContent = buttonCss;
+ root.appendChild(style);
+
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "ph-comment-action-button";
+ button.setAttribute("aria-label", "Comment");
+ button.innerHTML = `${actionIcon}<span>Comment</span>`;
+ applyActionTheme(state.theme, themes, button);
+ button.style.display = "none";
+ button.addEventListener("click", activateAction);
+ root.appendChild(button);
+ document.documentElement.appendChild(host);
+ state.button = button;
+ return button;
+ };
+
+ const positionAction = (): void => {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
+ hideAction();
+ return;
+ }
+ const value = selection.toString().trim();
+ if (value.length < 2 || value.length > 10_000) {
+ hideAction();
+ return;
+ }
+
+ const range = selection.getRangeAt(0);
+ const anchor = makeAnchor(range);
+ if (!anchor) {
+ hideAction();
+ return;
+ }
+ const rect = anchorRect(
+ range.getClientRects?.() ?? [],
+ range.getBoundingClientRect(),
+ );
+ if (!rect || (rect.width === 0 && rect.height === 0)) {
+ hideAction();
+ return;
+ }
+
+ const button = actionButton();
+ const buttonBox = button.getBoundingClientRect();
+ const position = placeAction(
+ { top: rect.top, right: rect.right, bottom: rect.bottom },
+ { width: window.innerWidth, height: window.innerHeight },
+ { width: buttonBox.width || 104, height: buttonBox.height || 28 },
+ );
+ button.style.left = `${position.left}px`;
+ button.style.top = `${position.top}px`;
+ button.style.display = "flex";
+
+ const triggerRect = button.getBoundingClientRect();
+ state.action = {
+ range,
+ message: {
+ anchor,
+ rect: copyRect(rect),
+ // Electron validates this legacy field before forwarding the message.
+ triggerRect: copyRect(triggerRect),
+ },
+ };
+ };
+
+ const updateComposerPosition = (): void => {
+ const range = state.activeRange;
+ if (!range) return;
+ try {
+ const rect = anchorRect(
+ range.getClientRects?.() ?? [],
+ range.getBoundingClientRect(),
+ );
+ if (rect && (rect.width > 0 || rect.height > 0)) {
+ send("selection-position", { rect: copyRect(rect) });
+ }
+ } catch {
+ state.activeRange = null;
+ }
+ };
+
+ const scheduleComposerPosition = (): void => {
+ if (state.positionFrame) return;
+ if (!window.requestAnimationFrame) {
+ updateComposerPosition();
+ return;
+ }
+ state.positionFrame = window.requestAnimationFrame(() => {
+ state.positionFrame = 0;
+ updateComposerPosition();
+ });
+ };
+
+ const selectionChanged = (): void => {
+ clearTimeout(state.selectionTimer);
+ state.selectionTimer = window.setTimeout(positionAction, 80);
+ };
+
+ const renderComments = (items: unknown): void => {
+ state.items = Array.isArray(items) ? (items as BridgeComment[]) : [];
+ state.entries = [];
+ const normal = HighlightConstructor ? new HighlightConstructor() : null;
+ const active = HighlightConstructor ? new HighlightConstructor() : null;
+ const resolutions: Array<{ id: string; status: string }> = [];
+ const index = textIndex();
+
+ for (const item of state.items) {
+ const resolved = resolveAnchor(index.text, item.anchor);
+ if (!resolved) {
+ resolutions.push({ id: item.id, status: "orphaned" });
+ continue;
+ }
+ const range = rangeAt(index, resolved.start, resolved.end);
+ if (!range) {
+ resolutions.push({ id: item.id, status: "orphaned" });
+ continue;
+ }
+ state.entries.push({ id: item.id, range });
+ resolutions.push({ id: item.id, status: resolved.status });
+ (item.active ? active : normal)?.add(range);
+ }
+
+ if (normal && active && highlightRegistry) {
+ highlightRegistry.set("posthog-artifact-comment", normal);
+ highlightRegistry.set("posthog-artifact-comment-active", active);
+ }
+ send("resolutions", { items: resolutions });
+ };
+
+ const locateComment = (id: string): void => {
+ const entry = state.entries.find((candidate) => candidate.id === id);
+ const node = entry?.range.startContainer;
+ const target =
+ node?.nodeType === Node.ELEMENT_NODE
+ ? (node as Element)
+ : node?.parentElement;
+ target?.scrollIntoView({ behavior: "smooth", block: "center" });
+ };
+
+ installSettleGate(document, {
+ onGestureStart: hideAction,
+ onSelectionSettled: positionAction,
+ onIdleSelectionChange: selectionChanged,
+ onGestureCancel: hideAction,
+ });
+ document.addEventListener(
+ "scroll",
+ () => {
+ hideAction();
+ scheduleComposerPosition();
+ },
+ true,
+ );
+ document.addEventListener(
+ "click",
+ (event) => {
+ const target = event.target;
+ const link = target instanceof Element ? target.closest("a[href]") : null;
+ if (link) {
+ event.preventDefault();
+ event.stopPropagation();
+ send("open-external", { href: (link as HTMLAnchorElement).href });
+ return;
+ }
+
+ for (const entry of state.entries) {
+ for (const rect of entry.range.getClientRects()) {
+ if (
+ event.clientX >= rect.left &&
+ event.clientX <= rect.right &&
+ event.clientY >= rect.top &&
+ event.clientY <= rect.bottom
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ send("activate", { id: entry.id });
+ return;
+ }
+ }
+ }
+ },
+ true,
+ );
+
+ new MutationObserver(() => {
+ if (state.items.length === 0 || state.renderTimer) return;
+ state.renderTimer = window.setTimeout(() => {
+ state.renderTimer = 0;
+ renderComments(state.items);
+ }, 500);
+ }).observe(document.body, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+
+ window.addEventListener("message", (event) => {
+ if (event.source !== window.parent) return;
+ const data = event.data as Record<string, unknown> | null;
+ if (!data || data.marker !== marker || data.channel !== channel) return;
+ if (data.type === "comments") renderComments(data.items);
+ else if (data.type === "selection-dismissed") {
+ state.activeRange = null;
+ if (state.positionFrame) window.cancelAnimationFrame(state.positionFrame);
+ state.positionFrame = 0;
+ } else if (
+ data.type === "locate" &&
+ typeof data.id === "string" &&
+ typeof data.nonce === "number" &&
+ data.nonce !== state.locateNonce
+ ) {
+ state.locateNonce = data.nonce;
+ locateComment(data.id);
+ } else if (
+ data.type === "theme" &&
+ (data.theme === "light" || data.theme === "dark")
+ ) {
+ state.theme = data.theme;
+ if (state.button) applyActionTheme(data.theme, themes, state.button);
+ }
+ });
+
+ installStyles();
+ send("ready");
+}
+
/**
* Runs inside the isolated artifact document. It never receives credentials
* or writes to the API; selection traffic uses a per-view host channel.
@@ -21,46 +450,22 @@ function artifactHtmlCommentBridge(
theme: CommentSurfaceTheme,
nonce?: string,
): string {
- const safeChannel = JSON.stringify(channel);
const nonceAttribute = nonce ? ` nonce="${nonce}"` : "";
- return `<script${nonceAttribute} 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:[],theme:${JSON.stringify(theme)}};
-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 THEMES=${JSON.stringify(COMMENT_ACTION_BUTTON_THEMES)};
-var ACTION_ICON=${JSON.stringify(COMMENT_ACTION_ICON_SVG)};
-var setActionTheme=${setCommentActionTheme.toString()};
-var placeAction=${computeCommentActionPlacement.toString()};
-var anchorRect=${commentActionAnchorRect.toString()};
-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}";(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 host=document.createElement("posthog-comment-action");host.setAttribute("data-selection-comment-overlay","");host.style.cssText="all:initial!important;display:block!important;position:fixed!important;top:0!important;left:0!important;width:0!important;height:0!important;overflow:visible!important;z-index:2147483647!important";var root=host.attachShadow({mode:"open"});var s=document.createElement("style");s.textContent=${JSON.stringify(commentActionButtonCss())};root.appendChild(s);var b=document.createElement("button");b.type="button";b.className="ph-comment-action-button";b.setAttribute("aria-label","Comment");b.innerHTML=ACTION_ICON+"<span>Comment</span>";setActionTheme(state.theme,THEMES,b);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()});root.appendChild(b);document.documentElement.appendChild(host);state.button=b;return b;}
-function positionButton(){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 range=sel.getRangeAt(0);var r=anchorRect(range.getClientRects?range.getClientRects():[],range.getBoundingClientRect());if(!r||(r.width===0&&r.height===0))return hide();var b=button();var box=b.getBoundingClientRect();var pos=placeAction({top:r.top,right:r.right,bottom:r.bottom},{width:innerWidth,height:innerHeight},{width:box.width||104,height:box.height||28});b.style.left=pos.left+"px";b.style.top=pos.top+"px";b.style.display="flex"}
-function selectionChanged(){clearTimeout(state.timer);state.timer=setTimeout(positionButton,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}}
-// Report the selection only once it settles, so the button doesn't chase the
-// cursor mid-drag. The settle callback re-reads the live selection, which
-// self-corrects clicks that didn't change the selection.
-var selectionSettleGate=${installSelectionSettleGate.toString()};
-selectionSettleGate(document,{onGestureStart:hide,onSelectionSettled:positionButton,onIdleSelectionChange:selectionChanged,onGestureCancel:hide});
-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);else if(d.type==="theme"&&(d.theme==="light"||d.theme==="dark")){state.theme=d.theme;if(state.button)setActionTheme(d.theme,THEMES,state.button)}});
-style();send("ready");
-})();</script>`;
+ return `<script${nonceAttribute} data-posthog-artifact-comments>
+(${runArtifactHtmlCommentBridge.toString()})({
+ channel: ${JSON.stringify(channel)},
+ marker: ${JSON.stringify(BRIDGE_MARKER)},
+ initialTheme: ${JSON.stringify(theme)},
+ themes: ${JSON.stringify(COMMENT_ACTION_BUTTON_THEMES)},
+ actionIcon: ${JSON.stringify(COMMENT_ACTION_ICON_SVG)},
+ buttonCss: ${JSON.stringify(commentActionButtonCss())},
+ setActionTheme: ${setCommentActionTheme.toString()},
+ placeAction: ${computeCommentActionPlacement.toString()},
+ anchorRect: ${commentActionAnchorRect.toString()},
+ resolveAnchor: ${resolveTextCommentAnchor.toString()},
+ installSelectionSettleGate: ${installSelectionSettleGate.toString()},
+});
+</script>`;
}
export function injectArtifactHtmlCommentBridge(
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.test.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.test.ts
new file mode 100644
index 000000000000..79dd485c9856
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.test.ts
@@ -0,0 +1,37 @@
+import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
+import { describe, expect, it } from "vitest";
+import { withSelectionPosition } from "./artifactHtmlCommentPosition";
+
+const selection = {
+ text: "selected text",
+ fromLine: 1,
+ toLine: 13,
+ anchor: { top: 110, endX: 230, bottom: 120 },
+} satisfies EditorSelection;
+
+const frame = {
+ top: 100,
+ left: 200,
+ right: 600,
+ bottom: 500,
+ width: 400,
+ height: 400,
+};
+
+describe("withSelectionPosition", () => {
+ it("keeps the composer attached to its frame-relative selection", () => {
+ expect(
+ withSelectionPosition(selection, frame, {
+ top: -20,
+ left: 10,
+ right: 30,
+ bottom: -10,
+ width: 20,
+ height: 10,
+ }),
+ ).toEqual({
+ ...selection,
+ anchor: { top: 80, endX: 230, bottom: 90 },
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts
new file mode 100644
index 000000000000..d3469d0d3173
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts
@@ -0,0 +1,26 @@
+import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
+import type { ArtifactHtmlFrameRect } from "./artifactHtmlFrameHost";
+
+export function selectionAnchor(
+ frame: ArtifactHtmlFrameRect,
+ selection: ArtifactHtmlFrameRect,
+): { top: number; endX: number; bottom: number } {
+ return {
+ top: frame.top + selection.top,
+ endX: frame.left + selection.right,
+ bottom: frame.top + selection.bottom,
+ };
+}
+
+export function withSelectionPosition(
+ current: EditorSelection | null,
+ frame: ArtifactHtmlFrameRect,
+ selection: ArtifactHtmlFrameRect,
+): EditorSelection | null {
+ return current
+ ? {
+ ...current,
+ anchor: selectionAnchor(frame, selection),
+ }
+ : null;
+}