Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): add comments to the agent chat with pinned screenshots (#107453)

Shy Alter4fb6f944721a
diff --git a/products/desktop/packages/core/src/sessions/commentToAgent.test.ts b/products/desktop/packages/core/src/sessions/commentToAgent.test.ts
new file mode 100644
index 000000000000..978ad39ab726
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/commentToAgent.test.ts
@@ -0,0 +1,95 @@
+import type { EditorContent } from "@posthog/core/message-editor/content";
+import { describe, expect, it, vi } from "vitest";
+import {
+ type CommentToAgentHost,
+ CommentToAgentService,
+ commentComposerContent,
+} from "./commentToAgent";
+
+function fakeHost(overrides: Partial<CommentToAgentHost> = {}) {
+ const inserted: EditorContent[] = [];
+ const host: CommentToAgentHost = {
+ persistScreenshot: vi.fn(async () => "/tmp/shot.png"),
+ getDraft: () => null,
+ hasPendingInsert: () => false,
+ insertIntoDraft: (_taskId, content) => inserted.push(content),
+ showTaskChat: vi.fn(),
+ trackCommentSent: vi.fn(),
+ ...overrides,
+ };
+ return { host, inserted };
+}
+
+describe("commentToAgent", () => {
+ it("puts the context chip before the editable comment", () => {
+ expect(
+ commentComposerContent({
+ comment: "Make this red",
+ draftEmpty: false,
+ context: { label: 'h1 "Hot stuff"', body: "- **Page** /" },
+ }).segments,
+ ).toEqual([
+ { type: "text", text: "\n" },
+ {
+ type: "chip",
+ chip: {
+ type: "comment_context",
+ id: "- **Page** /",
+ label: 'h1 "Hot stuff"',
+ },
+ },
+ { type: "text", text: " " },
+ { type: "text", text: "Make this red" },
+ ]);
+ });
+
+ it.each([
+ { name: "an empty draft", pending: false, startsOnNewLine: false },
+ { name: "a queued insert", pending: true, startsOnNewLine: true },
+ ])(
+ "starts the comment on a new line after $name",
+ async ({ pending, startsOnNewLine }) => {
+ const { host, inserted } = fakeHost({ hasPendingInsert: () => pending });
+
+ await new CommentToAgentService(host).send({
+ taskId: "task-1",
+ comment: "Fix it",
+ context: null,
+ surface: "task",
+ });
+
+ expect(inserted[0].segments[0]).toEqual(
+ startsOnNewLine
+ ? { type: "text", text: "\n" }
+ : { type: "text", text: "Fix it" },
+ );
+ },
+ );
+
+ it("adds the comment without an image when the screenshot can't be saved", async () => {
+ const { host, inserted } = fakeHost({
+ persistScreenshot: vi.fn(async () => {
+ throw new Error("disk full");
+ }),
+ });
+
+ await new CommentToAgentService(host).send({
+ taskId: "task-1",
+ comment: "Fix it",
+ context: { label: "button", body: "- **Page** /", screenshot: "data:" },
+ surface: "artifact",
+ openChat: false,
+ });
+
+ expect(inserted[0].segments[0]).toEqual({
+ type: "chip",
+ chip: { type: "comment_context", id: "- **Page** /", label: "button" },
+ });
+ expect(host.showTaskChat).not.toHaveBeenCalled();
+ expect(host.trackCommentSent).toHaveBeenCalledWith({
+ surface: "artifact",
+ with_context: true,
+ with_screenshot: false,
+ });
+ });
+});
diff --git a/products/desktop/packages/core/src/sessions/commentToAgent.ts b/products/desktop/packages/core/src/sessions/commentToAgent.ts
new file mode 100644
index 000000000000..71155fa0e76e
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/commentToAgent.ts
@@ -0,0 +1,110 @@
+import {
+ type EditorContent,
+ isContentEmpty,
+} from "@posthog/core/message-editor/content";
+import { inject, injectable } from "inversify";
+
+export type CommentAgentContext = {
+ label: string;
+ body: string;
+ screenshot?: string;
+};
+
+export type CommentSurface = "artifact" | "canvas" | "task";
+
+export interface CommentToAgentHost {
+ persistScreenshot(dataUrl: string): Promise<string>;
+ getDraft(taskId: string): EditorContent | string | null;
+ hasPendingInsert(taskId: string): boolean;
+ insertIntoDraft(taskId: string, content: EditorContent): void;
+ showTaskChat(taskId: string, options: { focus: boolean }): void;
+ trackCommentSent(properties: {
+ surface: CommentSurface;
+ with_context: boolean;
+ with_screenshot: boolean;
+ }): void;
+}
+
+export const COMMENT_TO_AGENT_HOST = Symbol.for(
+ "posthog.core.sessions.commentToAgentHost",
+);
+
+export function commentComposerContent({
+ comment,
+ draftEmpty,
+ context,
+}: {
+ comment: string;
+ draftEmpty: boolean;
+ context: (CommentAgentContext & { imagePath?: string }) | null;
+}): EditorContent {
+ const segments: EditorContent["segments"] = [];
+ if (!draftEmpty) segments.push({ type: "text", text: "\n" });
+ if (context) {
+ segments.push(
+ {
+ type: "chip",
+ chip: {
+ type: "comment_context",
+ id: context.body,
+ label: context.label,
+ ...(context.imagePath ? { imagePath: context.imagePath } : {}),
+ },
+ },
+ { type: "text", text: " " },
+ );
+ }
+ segments.push({ type: "text", text: comment });
+ return { segments };
+}
+
+@injectable()
+export class CommentToAgentService {
+ constructor(
+ @inject(COMMENT_TO_AGENT_HOST)
+ private readonly host: CommentToAgentHost,
+ ) {}
+
+ async send({
+ taskId,
+ comment,
+ context,
+ surface,
+ openChat = true,
+ }: {
+ taskId: string;
+ comment: string;
+ context: CommentAgentContext | null;
+ surface: CommentSurface;
+ openChat?: boolean;
+ }): Promise<void> {
+ const imagePath = context?.screenshot
+ ? await this.saveScreenshot(context.screenshot)
+ : undefined;
+ const draftEmpty =
+ isContentEmpty(this.host.getDraft(taskId)) &&
+ !this.host.hasPendingInsert(taskId);
+ this.host.insertIntoDraft(
+ taskId,
+ commentComposerContent({
+ comment,
+ draftEmpty,
+ context: context ? { ...context, imagePath } : null,
+ }),
+ );
+ if (openChat) this.host.showTaskChat(taskId, { focus: true });
+ this.host.trackCommentSent({
+ surface,
+ with_context: !!context,
+ with_screenshot: !!imagePath,
+ });
+ }
+
+ private async saveScreenshot(dataUrl: string): Promise<string | undefined> {
+ try {
+ return await this.host.persistScreenshot(dataUrl);
+ } catch {
+ return undefined;
+ }
+ }
+}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 19708799d996..be13346fa21b 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -301,6 +301,12 @@ export type SidebarNavItem =
| "loops"
| "more";
+export interface CommentSentToAgentProperties {
+ surface: "artifact" | "canvas" | "task";
+ with_context: boolean;
+ with_screenshot: boolean;
+}
+
/** Which sidebar shell the click came from, so the two can be compared. */
export type SidebarLayout = "code" | "channels";
@@ -1852,6 +1858,7 @@ export const ANALYTICS_EVENTS = {
LOOP_RUN_BLOCKED: "Loop run blocked",
LOOP_RUN_VIEWED: "Loop run viewed",
LOOP_LINK_COPIED: "Loop link copied",
+ COMMENT_SENT_TO_AGENT: "Comment sent to agent",
} as const;
// Event property mapping
@@ -2078,6 +2085,7 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.LOOP_RUN_BLOCKED]: LoopRunBlockedProperties;
[ANALYTICS_EVENTS.LOOP_RUN_VIEWED]: LoopRunViewedProperties;
[ANALYTICS_EVENTS.LOOP_LINK_COPIED]: LoopLinkCopiedProperties;
+ [ANALYTICS_EVENTS.COMMENT_SENT_TO_AGENT]: CommentSentToAgentProperties;
};
/**
diff --git a/products/desktop/packages/shared/src/screenshot-area.test.ts b/products/desktop/packages/shared/src/screenshot-area.test.ts
index b7d790c3b8ab..1099ecf267fe 100644
--- a/products/desktop/packages/shared/src/screenshot-area.test.ts
+++ b/products/desktop/packages/shared/src/screenshot-area.test.ts
@@ -19,6 +19,11 @@ describe("screenshotArea", () => {
element: rect(500, 400, 40, 20),
expected: { x: 340, y: 300, width: 360, height: 220 },
},
+ {
+ name: "a caret with no width still gets room around it",
+ element: rect(520, 400, 0, 20),
+ expected: { x: 340, y: 300, width: 360, height: 220 },
+ },
{
name: "an element at the top left corner stays inside the page",
element: rect(0, 0, 100, 30),
diff --git a/products/desktop/packages/shared/src/screenshot-area.ts b/products/desktop/packages/shared/src/screenshot-area.ts
index 07a1feb9eeca..644e2cba5e5c 100644
--- a/products/desktop/packages/shared/src/screenshot-area.ts
+++ b/products/desktop/packages/shared/src/screenshot-area.ts
@@ -58,7 +58,7 @@ export function screenshotArea(
const visibleRight = Math.min(viewport.width, element.right);
const visibleTop = Math.max(0, element.top);
const visibleBottom = Math.min(viewport.height, element.bottom);
- if (visibleRight <= visibleLeft || visibleBottom <= visibleTop) return null;
+ if (visibleRight < visibleLeft || visibleBottom < visibleTop) return null;
const [left, right] = span(
visibleLeft,
visibleRight,
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 91111f035ff2..af8dfdb143e6 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx
@@ -46,6 +46,10 @@ import {
} 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 {
+ type CommentResource,
+ commentAgentContext,
+} from "@posthog/ui/features/sessions/commentAgentContext";
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";
@@ -58,6 +62,7 @@ import {
useCreateComment,
useSetCommentResolved,
} from "@posthog/ui/features/sessions/components/useComments";
+import { sendCommentToAgent } from "@posthog/ui/features/sessions/sendCommentToAgent";
import { LoadingState } from "@posthog/ui/primitives/LoadingState";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -117,6 +122,30 @@ function CommentReference({
);
}
+function commentResource(source: CommentSource): CommentResource {
+ if (source.kind === "canvas") return { kind: "canvas", name: source.name };
+ if (source.kind === "task") return { kind: "task", name: source.name };
+ return { kind: "artifact", name: source.name };
+}
+
+function sendSourceCommentToAgent(
+ taskId: string,
+ source: CommentSource,
+ root: ResourceComment | null,
+ content: string,
+): void {
+ const resource = commentResource(source);
+ sendCommentToAgent({
+ taskId,
+ comment: content,
+ context: commentAgentContext(
+ root ? (readCommentContext(root)?.anchor ?? null) : { kind: "document" },
+ resource,
+ ),
+ surface: resource.kind,
+ });
+}
+
/**
* 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.
@@ -175,6 +204,9 @@ function ResourceThreadRow({
onResolve={async (resolved) => {
await setResolved.mutateAsync({ root, resolved });
}}
+ onSendReplyToAgent={(content) =>
+ sendSourceCommentToAgent(taskId, source, root, content)
+ }
/>
);
}
@@ -667,6 +699,18 @@ export function TaskCommentsList({
rows={1}
disabled={createComment.isPending}
compact
+ onSendToAgent={(content) =>
+ sendSourceCommentToAgent(
+ taskId,
+ onlySource ?? {
+ kind: "task",
+ target: composerTarget,
+ name: "This task",
+ },
+ null,
+ content,
+ )
+ }
/>
</footer>
</div>
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
index 02df13866397..083872804089 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
@@ -2,7 +2,6 @@ import { assertCanvasCapability } from "@posthog/core/canvas/canvasCapabilities"
import {
type CanvasCommentHighlight,
type CanvasNavIntent,
- type CanvasTextSelection,
type CanvasTheme,
canvasToHostMessageSchema,
} from "@posthog/core/canvas/freeformSchemas";
@@ -13,7 +12,10 @@ import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
import { useEffect, useLayoutEffect, useRef } from "react";
import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";
-import { translateCanvasTextSelection } from "./canvasSelection";
+import {
+ type HostCanvasTextSelection,
+ translateCanvasTextSelection,
+} from "./canvasSelection";
const log = logger.scope("built-canvas");
const EMPTY_COMMENT_HIGHLIGHTS: CanvasCommentHighlight[] = [];
@@ -106,7 +108,7 @@ export interface BuiltCanvasProps {
onReady?: () => void;
onRendered?: () => void;
onNavigate?: (intent: CanvasNavIntent) => void;
- onTextSelection?: (selection: CanvasTextSelection | null) => void;
+ onTextSelection?: (selection: HostCanvasTextSelection | null) => void;
onCommentActivate?: (id: string) => void;
commentHighlights?: CanvasCommentHighlight[];
clearTextSelectionKey?: number;
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 882807a0baae..f8dd7c9937d1 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx
@@ -1,10 +1,15 @@
-import type { CanvasTextSelection } from "@posthog/core/canvas/freeformSchemas";
import type { TextCommentAnchor } from "@posthog/core/comments/anchors";
import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
import { SelectionCommentOverlay } from "@posthog/ui/features/code-editor/components/SelectionCommentOverlay";
+import {
+ commentAgentContext,
+ withScreenshot,
+} from "@posthog/ui/features/sessions/commentAgentContext";
import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
import { useCreateComment } from "@posthog/ui/features/sessions/components/useComments";
+import { sendCommentToAgent } from "@posthog/ui/features/sessions/sendCommentToAgent";
+import type { HostCanvasTextSelection } from "./canvasSelection";
export function CanvasSelectionCommentAction({
selection,
@@ -14,7 +19,7 @@ export function CanvasSelectionCommentAction({
versionId,
onDismiss,
}: {
- selection: CanvasTextSelection | null;
+ selection: HostCanvasTextSelection | null;
taskId: string | null;
dashboardId: string;
canvasName: string;
@@ -49,6 +54,7 @@ export function CanvasSelectionCommentAction({
top: selection.rect.top,
endX: selection.rect.right,
bottom: selection.rect.bottom,
+ bounds: selection.frame,
},
}
: null
@@ -60,6 +66,23 @@ export function CanvasSelectionCommentAction({
showActionText
members={members}
onDismiss={onDismiss}
+ onSendToAgent={
+ anchor && taskId
+ ? (content, screenshot) =>
+ sendCommentToAgent({
+ taskId,
+ comment: content,
+ context: withScreenshot(
+ commentAgentContext(anchor, {
+ kind: "canvas",
+ name: canvasName,
+ }),
+ screenshot,
+ ),
+ surface: "canvas",
+ })
+ : undefined
+ }
onSubmit={async (_start, _end, content, mentions) => {
if (!anchor || !taskId) return;
openComments();
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
index 5aa38536e16c..3e421945ce77 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
@@ -2,7 +2,6 @@ import {
type CanvasAnalyticsConfig,
type CanvasCommentHighlight,
type CanvasNavIntent,
- type CanvasTextSelection,
canvasToHostMessageSchema,
} from "@posthog/core/canvas/freeformSchemas";
import { logger } from "@posthog/ui/shell/logger";
@@ -16,7 +15,10 @@ import {
useRef,
} from "react";
import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";
-import { translateCanvasTextSelection } from "./canvasSelection";
+import {
+ type HostCanvasTextSelection,
+ translateCanvasTextSelection,
+} from "./canvasSelection";
import { buildSandboxDocument } from "./sandboxRuntime";
const log = logger.scope("freeform-canvas");
@@ -42,7 +44,7 @@ export interface FreeformCanvasProps {
* just forwards it — the caller maps it to actual routing.
*/
onNavigate?: (intent: CanvasNavIntent) => void;
- onTextSelection?: (selection: CanvasTextSelection | null) => void;
+ onTextSelection?: (selection: HostCanvasTextSelection | null) => void;
onCommentActivate?: (id: string) => void;
commentHighlights?: CanvasCommentHighlight[];
clearTextSelectionKey?: number;
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 10b4b62fb913..aa312888f73e 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
@@ -23,7 +23,6 @@ import {
type CanvasAgentRequestResult,
type CanvasAnalyticsConfig,
type CanvasCommentHighlight,
- type CanvasTextSelection,
canvasAgentRequestInputSchema,
limitCanvasCommentHighlights,
} from "@posthog/core/canvas/freeformSchemas";
@@ -121,6 +120,7 @@ import { CanvasSidePanel } from "./CanvasSidePanel";
import { canvasChatTaskId } from "./canvasChatTask";
import { canvasCommentTaskId } from "./canvasCommentTask";
import { canvasRuntimeErrorAnalytics } from "./canvasRuntimeError";
+import type { HostCanvasTextSelection } from "./canvasSelection";
import { canvasSidePanelVisibility } from "./canvasSidePanelVisibility";
import {
canvasVersionNavigation,
@@ -188,7 +188,7 @@ export function FreeformCanvasView({
// before the canvas record's polled generationTaskId catches up.
const [startedTaskId, setStartedTaskId] = useState<string | null>(null);
const [textSelection, setTextSelection] =
- useState<CanvasTextSelection | null>(null);
+ useState<HostCanvasTextSelection | null>(null);
const [clearTextSelectionKey, setClearTextSelectionKey] = useState(0);
const dismissTextSelection = useCallback(() => {
setTextSelection(null);
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.test.ts
new file mode 100644
index 000000000000..5045112c756a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.test.ts
@@ -0,0 +1,33 @@
+import type { CanvasTextSelection } from "@posthog/core/canvas/freeformSchemas";
+import { describe, expect, it } from "vitest";
+import { translateCanvasTextSelection } from "./canvasSelection";
+
+const selection = {
+ quote: "Hot stuff",
+ prefix: "",
+ suffix: "",
+ start: 0,
+ end: 9,
+ rect: { top: 10, right: 60, bottom: 30, left: 20 },
+} as CanvasTextSelection;
+
+describe("translateCanvasTextSelection", () => {
+ it("bounds the selection by the host's frame, not by anything the canvas sends", () => {
+ const fromCanvas = {
+ ...selection,
+ frame: { top: 0, left: 0, right: 5_000, bottom: 5_000 },
+ } as CanvasTextSelection;
+
+ expect(
+ translateCanvasTextSelection(fromCanvas, {
+ top: 100,
+ left: 200,
+ right: 700,
+ bottom: 600,
+ }),
+ ).toMatchObject({
+ rect: { top: 110, right: 260, bottom: 130, left: 220 },
+ frame: { top: 100, left: 200, right: 700, bottom: 600 },
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.ts
index 2935c90d2cb7..e27184bfe196 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.ts
@@ -1,9 +1,14 @@
import type { CanvasTextSelection } from "@posthog/core/canvas/freeformSchemas";
+import type { CaptureBounds } from "@posthog/ui/features/code-editor/components/selectionScreenshot";
+
+export type HostCanvasTextSelection = CanvasTextSelection & {
+ frame?: CaptureBounds;
+};
export function translateCanvasTextSelection(
selection: CanvasTextSelection,
- frame: Pick<DOMRect, "left" | "top"> | undefined,
-): CanvasTextSelection {
+ frame: Pick<DOMRect, "left" | "top" | "right" | "bottom"> | undefined,
+): HostCanvasTextSelection {
return {
...selection,
rect: {
@@ -12,5 +17,13 @@ export function translateCanvasTextSelection(
bottom: selection.rect.bottom + (frame?.top ?? 0),
left: selection.rect.left + (frame?.left ?? 0),
},
+ frame: frame
+ ? {
+ top: frame.top,
+ left: frame.left,
+ right: frame.right,
+ bottom: frame.bottom,
+ }
+ : undefined,
};
}
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx b/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx
index 78db08643f39..b9e5e19f163d 100644
--- a/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx
+++ b/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx
@@ -8,6 +8,7 @@ import { setEnrichmentEffect } from "../extensions/postHogEnrichment";
import { useCodeMirror } from "../hooks/useCodeMirror";
import { useEditorExtensions } from "../hooks/useEditorExtensions";
import { usePendingScrollStore } from "../pendingScrollStore";
+import type { SelectionAnchor } from "./selectionScreenshot";
const selectedLineDecoration = Decoration.line({ class: "cm-selected-lines" });
const selectedLinesField = StateField.define<DecorationSet>({
@@ -42,7 +43,7 @@ export interface EditorSelection {
fromLine: number;
toLine: number;
/** Viewport position of the selection's end caret, or null when off-screen. */
- anchor: { top: number; endX: number; bottom: number } | null;
+ anchor: SelectionAnchor | null;
}
interface CodeMirrorEditorProps {
@@ -111,6 +112,7 @@ export function CodeMirrorEditor({
return;
}
const endRect = update.view.coordsAtPos(sel.to);
+ const startRect = update.view.coordsAtPos(sel.from);
cb({
text: doc.sliceString(sel.from, sel.to),
fromLine: doc.lineAt(sel.from).number,
@@ -120,6 +122,8 @@ export function CodeMirrorEditor({
top: endRect.top,
endX: endRect.right,
bottom: endRect.bottom,
+ startX: startRect?.left,
+ startTop: startRect?.top,
}
: null,
});
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 dbea7d41f3e3..69e67fafa8b5 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
@@ -2,6 +2,9 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
+vi.mock("@posthog/di/react", () => ({
+ useServiceOptional: () => undefined,
+}));
vi.mock("@posthog/ui/features/canvas/components/MentionComposer", () => ({
MentionComposer: ({
value,
@@ -151,4 +154,55 @@ describe("SelectionCommentOverlay", () => {
expect(editor).toHaveValue("Keep this draft");
expect(onDismiss).not.toHaveBeenCalled();
});
+
+ it("resets the card for a new selection on the same lines, but not when the selection moves", () => {
+ const props = {
+ open: true,
+ filePath: "report.md",
+ onSubmit: vi.fn(),
+ onDismiss: vi.fn(),
+ initiallyExpanded: true,
+ members: [],
+ };
+ const { rerender } = render(
+ <SelectionCommentOverlay
+ {...props}
+ selection={{
+ text: "first",
+ fromLine: 1,
+ toLine: 1,
+ anchor: { top: 20, endX: 20, bottom: 38 },
+ }}
+ />,
+ );
+ fireEvent.change(screen.getByLabelText("Comment draft"), {
+ target: { value: "Draft" },
+ });
+
+ rerender(
+ <SelectionCommentOverlay
+ {...props}
+ selection={{
+ text: "first",
+ fromLine: 1,
+ toLine: 1,
+ anchor: { top: 60, endX: 20, bottom: 78 },
+ }}
+ />,
+ );
+ expect(screen.getByLabelText("Comment draft")).toHaveValue("Draft");
+
+ rerender(
+ <SelectionCommentOverlay
+ {...props}
+ selection={{
+ text: "second",
+ fromLine: 1,
+ toLine: 1,
+ anchor: { top: 60, endX: 20, bottom: 78 },
+ }}
+ />,
+ );
+ expect(screen.getByLabelText("Comment draft")).toHaveValue("");
+ });
});
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 115fc82b8de7..b21f2e21f43b 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,4 +1,9 @@
import { ChatCircle, Plus } from "@phosphor-icons/react";
+import { useServiceOptional } from "@posthog/di/react";
+import {
+ type IScreenCapture,
+ SCREEN_CAPTURE_SERVICE,
+} from "@posthog/platform/screen-capture";
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";
@@ -6,8 +11,12 @@ import { CommentComposer } from "@posthog/ui/features/sessions/components/Commen
import { SelectionCommentActionButton } from "@posthog/ui/features/sessions/components/SelectionCommentActionButton";
import { computeCommentActionPlacement } from "@posthog/ui/features/sessions/components/selectionCommentAction";
import { Tooltip } from "@posthog/ui/primitives/Tooltip";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
+import {
+ captureSelectionScreenshot,
+ type SelectionAnchor,
+} from "./selectionScreenshot";
/** Selection state for the "select lines → add to chat" overlay. */
export function useSelectionComposer() {
@@ -37,6 +46,10 @@ interface SelectionCommentOverlayProps {
showActionText?: boolean;
initiallyExpanded?: boolean;
members?: UserBasic[];
+ onSendToAgent?: (text: string, screenshot: string | null) => void;
+ captureScreenshot?: boolean;
+ submitLabel?: string;
+ selectionKey?: string;
}
/**
@@ -55,12 +68,18 @@ export function SelectionCommentOverlay({
showActionText = false,
initiallyExpanded = false,
members,
+ onSendToAgent,
+ captureScreenshot = true,
+ submitLabel,
+ selectionKey,
}: SelectionCommentOverlayProps) {
if (!open || !selection?.anchor) return null;
- // Key by the range so a fresh selection remounts the card back to the "+".
return (
<SelectionComposerCard
- key={`${selection.fromLine}:${selection.toLine}`}
+ key={
+ selectionKey ??
+ `${selection.fromLine}:${selection.toLine}:${selection.text}`
+ }
anchor={selection.anchor}
fromLine={selection.fromLine}
toLine={selection.toLine}
@@ -72,6 +91,9 @@ export function SelectionCommentOverlay({
showActionText={showActionText}
initiallyExpanded={initiallyExpanded}
members={members}
+ onSendToAgent={onSendToAgent}
+ captureScreenshot={captureScreenshot}
+ submitLabel={submitLabel}
/>
);
}
@@ -88,8 +110,11 @@ function SelectionComposerCard({
showActionText,
initiallyExpanded,
members,
+ onSendToAgent,
+ captureScreenshot,
+ submitLabel,
}: {
- anchor: { top: number; endX: number; bottom: number };
+ anchor: SelectionAnchor;
fromLine: number;
toLine: number;
filePath: string;
@@ -105,7 +130,18 @@ function SelectionComposerCard({
showActionText: boolean;
initiallyExpanded: boolean;
members?: UserBasic[];
+ onSendToAgent?: (text: string, screenshot: string | null) => void;
+ captureScreenshot: boolean;
+ submitLabel?: string;
}) {
+ const screenCapture = useServiceOptional<IScreenCapture>(
+ SCREEN_CAPTURE_SERVICE,
+ );
+ const shouldCapture = !!onSendToAgent && captureScreenshot && !!screenCapture;
+ const [captureDone, setCaptureDone] = useState(false);
+ const capturing = shouldCapture && !captureDone;
+ const screenshotRef = useRef<string | null>(null);
+ const anchorRef = useRef(anchor);
const [userExpanded, setUserExpanded] = useState(false);
const expanded = initiallyExpanded || userExpanded;
const [draft, setDraft] = useState("");
@@ -120,6 +156,30 @@ function SelectionComposerCard({
expanded ? "below" : "center",
);
+ useEffect(() => {
+ if (!shouldCapture || !screenCapture) return;
+ let cancelled = false;
+ const frame = requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ void captureSelectionScreenshot(screenCapture, anchorRef.current).then(
+ (screenshot) => {
+ if (cancelled) return;
+ screenshotRef.current = screenshot;
+ setCaptureDone(true);
+ },
+ );
+ }),
+ );
+ return () => {
+ cancelled = true;
+ cancelAnimationFrame(frame);
+ };
+ }, [shouldCapture, screenCapture]);
+
+ const sendToAgent = onSendToAgent
+ ? (text: string) => onSendToAgent(text, screenshotRef.current)
+ : undefined;
+
useEffect(() => {
const dismissOutside = (event: PointerEvent) => {
if (
@@ -156,11 +216,13 @@ function SelectionComposerCard({
// The text button names itself; only the icon-only variant needs a label
// on hover.
return createPortal(
- showActionText ? (
- action
- ) : (
- <Tooltip content={actionLabel}>{action}</Tooltip>
- ),
+ <div className={capturing ? "invisible" : undefined}>
+ {showActionText ? (
+ action
+ ) : (
+ <Tooltip content={actionLabel}>{action}</Tooltip>
+ )}
+ </div>,
document.body,
);
}
@@ -168,7 +230,7 @@ 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"
+ className={`fixed z-50 w-[420px] max-w-[80vw] rounded-md border border-gray-5 bg-gray-2 shadow-lg ${capturing ? "invisible" : ""}`}
style={style}
>
{members ? (
@@ -192,6 +254,8 @@ function SelectionComposerCard({
rows={2}
disabled={submitting}
autoFocus
+ onSendToAgent={sendToAgent}
+ submitLabel={submitLabel}
/>
</div>
) : (
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/selectionScreenshot.test.ts b/products/desktop/packages/ui/src/features/code-editor/components/selectionScreenshot.test.ts
new file mode 100644
index 000000000000..ea31474a902b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/code-editor/components/selectionScreenshot.test.ts
@@ -0,0 +1,59 @@
+import type { CaptureRegion } from "@posthog/platform/screen-capture";
+import { describe, expect, it, vi } from "vitest";
+import { captureSelectionScreenshot } from "./selectionScreenshot";
+
+describe("captureSelectionScreenshot", () => {
+ it("captures the whole selection, from its start to its end", async () => {
+ const captureRegion = vi.fn(
+ async (_region: CaptureRegion): Promise<string | null> => null,
+ );
+
+ await captureSelectionScreenshot(
+ { captureRegion },
+ { top: 300, bottom: 318, endX: 700, startX: 40, startTop: 200 },
+ );
+
+ const area = captureRegion.mock.calls[0][0];
+ expect(area.x).toBeLessThanOrEqual(40);
+ expect(area.x + area.width).toBeGreaterThanOrEqual(700);
+ expect(area.y).toBeLessThanOrEqual(200);
+ expect(area.y + area.height).toBeGreaterThanOrEqual(318);
+ });
+
+ it("keeps the capture inside the frame the selection came from", async () => {
+ const captureRegion = vi.fn(
+ async (_region: CaptureRegion): Promise<string | null> => null,
+ );
+ const bounds = { top: 100, left: 300, right: 800, bottom: 600 };
+
+ await captureSelectionScreenshot(
+ { captureRegion },
+ { top: 310, bottom: 330, endX: 520, bounds },
+ );
+
+ const area = captureRegion.mock.calls[0][0];
+ expect(area.x).toBeGreaterThanOrEqual(bounds.left);
+ expect(area.y).toBeGreaterThanOrEqual(bounds.top);
+ expect(area.x + area.width).toBeLessThanOrEqual(bounds.right);
+ expect(area.y + area.height).toBeLessThanOrEqual(bounds.bottom);
+ });
+
+ it("captures nothing for a selection outside its frame", async () => {
+ const captureRegion = vi.fn(
+ async (_region: CaptureRegion): Promise<string | null> => null,
+ );
+
+ await expect(
+ captureSelectionScreenshot(
+ { captureRegion },
+ {
+ top: 20,
+ bottom: 40,
+ endX: 60,
+ bounds: { top: 100, left: 300, right: 800, bottom: 600 },
+ },
+ ),
+ ).resolves.toBeNull();
+ expect(captureRegion).not.toHaveBeenCalled();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/selectionScreenshot.ts b/products/desktop/packages/ui/src/features/code-editor/components/selectionScreenshot.ts
new file mode 100644
index 000000000000..b4f55c9bc630
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/code-editor/components/selectionScreenshot.ts
@@ -0,0 +1,113 @@
+import type { IScreenCapture } from "@posthog/platform/screen-capture";
+import { screenshotArea } from "@posthog/shared/screenshot-area";
+
+const ACCENT = "#f54e00";
+const PIN_SIZE = 22;
+
+export type CaptureBounds = {
+ top: number;
+ left: number;
+ right: number;
+ bottom: number;
+};
+
+export type SelectionAnchor = {
+ top: number;
+ endX: number;
+ bottom: number;
+ startX?: number;
+ startTop?: number;
+ bounds?: CaptureBounds;
+};
+
+function loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ image.onload = () => resolve(image);
+ image.onerror = () => reject(new Error("Screenshot did not load"));
+ image.src = src;
+ });
+}
+
+function drawPin(
+ context: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ size: number,
+): void {
+ const radius = size / 2;
+ context.save();
+ context.translate(x, y);
+ context.rotate(-Math.PI / 4);
+ context.beginPath();
+ context.moveTo(-radius, 0);
+ context.arc(0, 0, radius, Math.PI, Math.PI / 2, false);
+ context.lineTo(-radius, radius);
+ context.closePath();
+ context.fillStyle = ACCENT;
+ context.shadowColor = "rgba(0,0,0,0.35)";
+ context.shadowBlur = size / 4;
+ context.fill();
+ context.shadowBlur = 0;
+ context.lineWidth = size / 11;
+ context.strokeStyle = "#ffffff";
+ context.stroke();
+ context.restore();
+}
+
+export async function pinScreenshot(
+ dataUrl: string,
+ pin: { x: number; y: number },
+ areaWidth: number,
+): Promise<string> {
+ const image = await loadImage(dataUrl);
+ const canvas = document.createElement("canvas");
+ canvas.width = image.naturalWidth;
+ canvas.height = image.naturalHeight;
+ const context = canvas.getContext("2d");
+ if (!context) return dataUrl;
+ context.drawImage(image, 0, 0);
+ const scale = image.naturalWidth / areaWidth;
+ drawPin(context, pin.x * scale, pin.y * scale, PIN_SIZE * scale);
+ return canvas.toDataURL("image/png");
+}
+
+export async function captureSelectionScreenshot(
+ capture: IScreenCapture,
+ anchor: SelectionAnchor,
+): Promise<string | null> {
+ const bounds = {
+ left: Math.max(0, anchor.bounds?.left ?? 0),
+ top: Math.max(0, anchor.bounds?.top ?? 0),
+ right: Math.min(
+ window.innerWidth,
+ anchor.bounds?.right ?? window.innerWidth,
+ ),
+ bottom: Math.min(
+ window.innerHeight,
+ anchor.bounds?.bottom ?? window.innerHeight,
+ ),
+ };
+ const local = screenshotArea(
+ {
+ top: Math.min(anchor.startTop ?? anchor.top, anchor.top) - bounds.top,
+ bottom: anchor.bottom - bounds.top,
+ left: Math.min(anchor.startX ?? anchor.endX, anchor.endX) - bounds.left,
+ right: Math.max(anchor.startX ?? anchor.endX, anchor.endX) - bounds.left,
+ },
+ { width: bounds.right - bounds.left, height: bounds.bottom - bounds.top },
+ );
+ if (!local) return null;
+ const area = { ...local, x: local.x + bounds.left, y: local.y + bounds.top };
+ try {
+ const dataUrl = await capture.captureRegion(area);
+ if (!dataUrl) return null;
+ return await pinScreenshot(
+ dataUrl,
+ { x: anchor.endX - area.x, y: anchor.top - area.y },
+ area.width,
+ );
+ } catch {
+ return null;
+ }
+}
diff --git a/products/desktop/packages/ui/src/features/message-editor/draftStore.test.ts b/products/desktop/packages/ui/src/features/message-editor/draftStore.test.ts
new file mode 100644
index 000000000000..587fa44c6994
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/draftStore.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+import { useDraftStore } from "./draftStore";
+
+describe("draftStore pending inserts", () => {
+ it("keeps every send that arrives before the composer takes them", () => {
+ const { actions } = useDraftStore.getState();
+ actions.insertPendingContent("task-1", {
+ segments: [{ type: "text", text: "first" }],
+ });
+ actions.insertPendingContent("task-1", {
+ segments: [{ type: "text", text: "second" }],
+ });
+
+ expect(actions.takePendingInsert("task-1")).toEqual({
+ segments: [
+ { type: "text", text: "first" },
+ { type: "text", text: "second" },
+ ],
+ });
+ expect(actions.takePendingInsert("task-1")).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/draftStore.ts b/products/desktop/packages/ui/src/features/message-editor/draftStore.ts
index c0ac0bd5c67b..38394e6f99a6 100644
--- a/products/desktop/packages/ui/src/features/message-editor/draftStore.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/draftStore.ts
@@ -55,6 +55,7 @@ interface DraftActions {
/** Insert content at the cursor (append), unlike setPendingContent which replaces. */
insertPendingContent: (sessionId: SessionId, content: EditorContent) => void;
clearPendingInsert: (sessionId: SessionId) => void;
+ takePendingInsert: (sessionId: SessionId) => EditorContent | null;
/**
* Snapshot composer content before a queued-message edit overwrites it (see
* {@link DraftState.preEditDraft}). Passing null clears any existing snapshot.
@@ -164,7 +165,10 @@ export const useDraftStore = create<DraftStore>()(
insertPendingContent: (sessionId, content) =>
set((state) => {
- state.pendingInsert[sessionId] = content;
+ const pending = state.pendingInsert[sessionId];
+ state.pendingInsert[sessionId] = pending
+ ? { segments: [...pending.segments, ...content.segments] }
+ : content;
}),
clearPendingInsert: (sessionId) =>
@@ -172,6 +176,16 @@ export const useDraftStore = create<DraftStore>()(
delete state.pendingInsert[sessionId];
}),
+ takePendingInsert: (sessionId) => {
+ const content = get().pendingInsert[sessionId] ?? null;
+ if (content) {
+ set((state) => {
+ delete state.pendingInsert[sessionId];
+ });
+ }
+ return content;
+ },
+
setPreEditDraft: (sessionId, content) =>
set((state) => {
if (content === null) {
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx
index 56921c876d53..1b20d01c38e5 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx
@@ -1,5 +1,14 @@
import { act, render, screen } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { StrictMode } from "react";
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
vi.mock("@posthog/ui/shell/rendererStorage", () => ({
electronStorage: {
@@ -16,13 +25,17 @@ import { useDraftSync } from "./useDraftSync";
// A real editor rather than a stub of the commands the hook calls: what the
// restore path is worth testing for is the text a user would see in the box.
+const editors: Editor[] = [];
+
function makeEditor(): Editor {
const element = document.createElement("div");
document.body.appendChild(element);
- return new Editor({
+ const editor = new Editor({
element,
extensions: getEditorExtensions({ sessionId: "session-1" }),
});
+ editors.push(editor);
+ return editor;
}
function DraftAttachmentsProbe({ sessionId }: { sessionId: string }) {
@@ -48,6 +61,15 @@ function RestoreProbe({
}
describe("useDraftSync", () => {
+ beforeAll(() => {
+ Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
+ Range.prototype.getBoundingClientRect = () => new DOMRect();
+ });
+
+ afterEach(() => {
+ for (const editor of editors.splice(0)) editor.destroy();
+ });
+
beforeEach(() => {
vi.clearAllMocks();
useDraftStore.setState((state) => ({
@@ -57,6 +79,7 @@ describe("useDraftSync", () => {
commands: {},
focusRequested: {},
pendingContent: {},
+ pendingInsert: {},
_hasHydrated: true,
}));
});
@@ -90,6 +113,24 @@ describe("useDraftSync", () => {
expect(editor.getText()).toBe(expected);
});
+ it("inserts content sent from elsewhere once when the composer mounts", () => {
+ const editor = makeEditor();
+ useDraftStore.getState().actions.insertPendingContent("session-insert", {
+ segments: [{ type: "text", text: "Make it red" }],
+ });
+
+ render(
+ <StrictMode>
+ <RestoreProbe editor={editor} sessionId="session-insert" />
+ </StrictMode>,
+ );
+
+ expect(editor.getText()).toBe("Make it red");
+ expect(useDraftStore.getState().pendingInsert["session-insert"]).toBe(
+ undefined,
+ );
+ });
+
// Drafts land only once the store hydrates, so filling the box before that
// would show the caller's text and then swap it for what the user had typed.
it("holds initialContent until the draft store hydrates", () => {
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
index fd66ef158056..baba1430dbf4 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
@@ -96,12 +96,13 @@ export function useDraftSync(
useLayoutEffect(() => {
if (!editor || !pendingInsert) return;
+ const content = draftActions.takePendingInsert(sessionId);
+ if (!content) return;
editor.commands.focus("end");
editor.commands.insertContent(
- editorContentToTiptapJson(pendingInsert).content ?? [],
+ editorContentToTiptapJson(content).content ?? [],
);
- draftActions.clearPendingInsert(sessionId);
}, [editor, pendingInsert, sessionId, draftActions]);
// Extract restored attachments from draft on first restore
diff --git a/products/desktop/packages/ui/src/features/sessions/commentAgentContext.test.ts b/products/desktop/packages/ui/src/features/sessions/commentAgentContext.test.ts
new file mode 100644
index 000000000000..a888a0a97368
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/commentAgentContext.test.ts
@@ -0,0 +1,53 @@
+import type { CommentAnchor } from "@posthog/core/comments/anchors";
+import { describe, expect, it } from "vitest";
+import {
+ type CommentResource,
+ commentAgentContext,
+} from "./commentAgentContext";
+
+describe("commentAgentContext", () => {
+ it.each<{
+ name: string;
+ anchor: CommentAnchor | null;
+ resource: CommentResource;
+ label: string | null;
+ bodyParts: string[];
+ }>([
+ {
+ name: "an artifact quote",
+ anchor: {
+ kind: "text",
+ quote: "Revenue grew\nby 12%",
+ prefix: "",
+ suffix: "",
+ start: 0,
+ end: 20,
+ },
+ resource: { kind: "artifact", name: "report.md" },
+ label: 'report.md "Revenue grew by 12%"',
+ bodyParts: ["- **Artifact** report.md", "> Revenue grew\n> by 12%"],
+ },
+ {
+ name: "an image region",
+ anchor: { kind: "region", x: 0.1, y: 0.2, width: 0.5, height: 0.25 },
+ resource: { kind: "artifact", name: "chart.png" },
+ label: "chart.png (region)",
+ bodyParts: ["- **Region** left 10%, top 20%, width 50%, height 25%"],
+ },
+ {
+ name: "a task comment",
+ anchor: { kind: "document" },
+ resource: { kind: "task", name: "This task" },
+ label: null,
+ bodyParts: [],
+ },
+ ])(
+ "describes $name for the agent",
+ ({ anchor, resource, label, bodyParts }) => {
+ const context = commentAgentContext(anchor, resource);
+
+ expect(context?.label ?? null).toBe(label);
+ for (const part of bodyParts) expect(context?.body).toContain(part);
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/commentAgentContext.ts b/products/desktop/packages/ui/src/features/sessions/commentAgentContext.ts
new file mode 100644
index 000000000000..aebe1a4ad855
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/commentAgentContext.ts
@@ -0,0 +1,63 @@
+import type { CommentAnchor } from "@posthog/core/comments/anchors";
+import type { CommentAgentContext } from "@posthog/core/sessions/commentToAgent";
+
+export type CommentResource = {
+ kind: "artifact" | "canvas" | "task";
+ name: string;
+};
+
+const LABEL_LENGTH = 48;
+const QUOTE_LABEL_LENGTH = 32;
+
+function truncate(value: string, maxLength: number): string {
+ const flat = value.replace(/\s+/g, " ").trim();
+ return flat.length > maxLength ? `${flat.slice(0, maxLength - 1)}…` : flat;
+}
+
+function resourceLine(resource: CommentResource): string {
+ const kind = resource.kind[0].toUpperCase() + resource.kind.slice(1);
+ return `- **${kind}** ${resource.name}`;
+}
+
+export function commentAgentContext(
+ anchor: CommentAnchor | null,
+ resource: CommentResource,
+): CommentAgentContext | null {
+ if (!anchor || (anchor.kind === "document" && resource.kind === "task")) {
+ return null;
+ }
+ if (anchor.kind === "text") {
+ return {
+ label: truncate(
+ `${resource.name} "${truncate(anchor.quote, QUOTE_LABEL_LENGTH)}"`,
+ LABEL_LENGTH + QUOTE_LABEL_LENGTH,
+ ),
+ body: [
+ resourceLine(resource),
+ "",
+ ...anchor.quote.split("\n").map((line) => `> ${line}`),
+ ].join("\n"),
+ };
+ }
+ if (anchor.kind === "region") {
+ const percent = (value: number) => `${Math.round(value * 100)}%`;
+ return {
+ label: truncate(`${resource.name} (region)`, LABEL_LENGTH),
+ body: [
+ resourceLine(resource),
+ `- **Region** left ${percent(anchor.x)}, top ${percent(anchor.y)}, width ${percent(anchor.width)}, height ${percent(anchor.height)}`,
+ ].join("\n"),
+ };
+ }
+ return {
+ label: truncate(resource.name, LABEL_LENGTH),
+ body: resourceLine(resource),
+ };
+}
+
+export function withScreenshot(
+ context: CommentAgentContext | null,
+ screenshot: string | null,
+): CommentAgentContext | null {
+ return context && screenshot ? { ...context, screenshot } : context;
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/commentToAgentHost.ts b/products/desktop/packages/ui/src/features/sessions/commentToAgentHost.ts
new file mode 100644
index 000000000000..54973af7f6eb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/commentToAgentHost.ts
@@ -0,0 +1,26 @@
+import type { CommentToAgentHost } from "@posthog/core/sessions/commentToAgent";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { persistImageFile } from "@posthog/ui/features/message-editor/utils/persistFile";
+import { track } from "@posthog/ui/shell/analytics";
+import { showTaskChat } from "./showTaskChat";
+
+export const commentToAgentHost: CommentToAgentHost = {
+ persistScreenshot: async (dataUrl) => {
+ const response = await fetch(dataUrl);
+ if (!response.ok) throw new Error("Screenshot data did not load");
+ const blob = await response.blob();
+ const file = new File([blob], "comment-screenshot.png", {
+ type: blob.type || "image/png",
+ });
+ return (await persistImageFile(file)).path;
+ },
+ getDraft: (taskId) => useDraftStore.getState().actions.getDraft(taskId),
+ hasPendingInsert: (taskId) =>
+ !!useDraftStore.getState().pendingInsert[taskId],
+ insertIntoDraft: (taskId, content) =>
+ useDraftStore.getState().actions.insertPendingContent(taskId, content),
+ showTaskChat,
+ trackCommentSent: (properties) =>
+ track(ANALYTICS_EVENTS.COMMENT_SENT_TO_AGENT, properties),
+};
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 7a5d9ba42286..74d1567f2307 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
@@ -1,5 +1,6 @@
import type { ResourceComment } from "@posthog/api-client/posthog-client";
import {
+ type CommentAnchor,
commentAnchorSchema,
type TextCommentAnchor,
} from "@posthog/core/comments/anchors";
@@ -47,6 +48,7 @@ export function AnnotatedArtifactHtml({
members,
onActivateThread,
onCreate,
+ onSendToAgent,
onResolutionsChange,
}: {
html: string;
@@ -61,6 +63,11 @@ export function AnnotatedArtifactHtml({
content: string,
mentions?: number[],
) => void | Promise<void>;
+ onSendToAgent?: (
+ anchor: CommentAnchor,
+ content: string,
+ screenshot: string | null,
+ ) => void;
onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
}) {
const channelRef = useRef(`artifact-comments-${crypto.randomUUID()}`);
@@ -221,6 +228,12 @@ export function AnnotatedArtifactHtml({
onSubmit={async (_start, _end, content, mentions) => {
if (pendingAnchor) await onCreate(pendingAnchor, content, mentions);
}}
+ onSendToAgent={
+ onSendToAgent && pendingAnchor
+ ? (content, screenshot) =>
+ onSendToAgent(pendingAnchor, content, screenshot)
+ : undefined
+ }
/>
</div>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx
index 012e3d8aab87..4359dadc26ee 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactImage.tsx
@@ -1,5 +1,8 @@
import type { ResourceComment } from "@posthog/api-client/posthog-client";
-import type { RegionCommentAnchor } from "@posthog/core/comments/anchors";
+import type {
+ CommentAnchor,
+ 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";
@@ -24,6 +27,7 @@ function ImageCommentCreationLayer({
name,
members,
onCreate,
+ onSendToAgent,
onCancel,
}: {
name: string;
@@ -33,6 +37,11 @@ function ImageCommentCreationLayer({
content: string,
mentions?: number[],
) => void | Promise<void>;
+ onSendToAgent?: (
+ anchor: CommentAnchor,
+ content: string,
+ screenshot: string | null,
+ ) => void;
onCancel: () => void;
}) {
const [pendingAnchor, setPendingAnchor] =
@@ -81,6 +90,12 @@ function ImageCommentCreationLayer({
onSubmit={async (_start, _end, content, mentions) => {
if (pendingAnchor) await onCreate(pendingAnchor, content, mentions);
}}
+ onSendToAgent={
+ onSendToAgent && pendingAnchor
+ ? (content, screenshot) =>
+ onSendToAgent(pendingAnchor, content, screenshot)
+ : undefined
+ }
/>
</>
);
@@ -97,6 +112,7 @@ export function AnnotatedArtifactImage({
onCommentingChange,
onActivateThread,
onCreate,
+ onSendToAgent,
onError,
}: {
src: string;
@@ -113,6 +129,11 @@ export function AnnotatedArtifactImage({
content: string,
mentions?: number[],
) => void | Promise<void>;
+ onSendToAgent?: (
+ anchor: CommentAnchor,
+ content: string,
+ screenshot: string | null,
+ ) => void;
onError: () => void;
}) {
const rootRef = useRef<HTMLDivElement>(null);
@@ -146,6 +167,7 @@ export function AnnotatedArtifactImage({
name={name}
members={members}
onCreate={onCreate}
+ onSendToAgent={onSendToAgent}
onCancel={() => onCommentingChange(false)}
/>
)}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
index 39aaff73af81..a6a5e3bad61d 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
@@ -11,16 +11,20 @@ import {
} from "@posthog/quill";
import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
import { useState } from "react";
+import { commentAgentContext } from "../commentAgentContext";
+import { sendCommentToAgent } from "../sendCommentToAgent";
import { CommentComposer } from "./CommentComposer";
import { useCreateComment } from "./useComments";
export function ArtifactDocumentCommentAction({
target,
taskId,
+ name,
onCreated,
}: {
target: CommentTarget;
taskId: string;
+ name: string;
onCreated?: (commentId: string) => void;
}) {
const [open, setOpen] = useState(false);
@@ -64,6 +68,17 @@ export function ArtifactDocumentCommentAction({
rows={2}
disabled={createComment.isPending}
autoFocus
+ onSendToAgent={(content) =>
+ sendCommentToAgent({
+ taskId,
+ comment: content,
+ context: commentAgentContext(
+ { kind: "document" },
+ { kind: "artifact", name },
+ ),
+ surface: "artifact",
+ })
+ }
/>
</PopoverContent>
</Popover>
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 69f7c3ffc433..040e697fdc26 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
@@ -37,6 +37,8 @@ import {
useRef,
useState,
} from "react";
+import { commentAgentContext, withScreenshot } from "../commentAgentContext";
+import { sendCommentToAgent } from "../sendCommentToAgent";
import { ArtifactEditView } from "./ArtifactEditView";
import {
ArtifactPreviewContent,
@@ -392,6 +394,17 @@ export function ArtifactPreview({
members={members}
activateThread={activateThread}
createAnchoredComment={createAnchoredComment}
+ sendCommentToAgent={(anchor, content, screenshot) =>
+ sendCommentToAgent({
+ taskId,
+ comment: content,
+ context: withScreenshot(
+ commentAgentContext(anchor, { kind: "artifact", name }),
+ screenshot,
+ ),
+ surface: "artifact",
+ })
+ }
onResolutionsChange={onResolutionsChange}
imageCommenting={imageCommenting}
setImageCommenting={setImageCommenting}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx
index 33d41dcec191..eaf7bad93c68 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx
@@ -90,6 +90,7 @@ export function ArtifactPreviewContent({
members,
activateThread,
createAnchoredComment,
+ sendCommentToAgent,
onResolutionsChange,
imageCommenting,
setImageCommenting,
@@ -120,6 +121,11 @@ export function ArtifactPreviewContent({
content: string,
mentions?: number[],
) => Promise<void>;
+ sendCommentToAgent: (
+ anchor: CommentAnchor,
+ content: string,
+ screenshot: string | null,
+ ) => void;
onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
imageCommenting: boolean;
setImageCommenting: Dispatch<SetStateAction<boolean>>;
@@ -143,6 +149,7 @@ export function ArtifactPreviewContent({
<ArtifactDocumentCommentAction
target={commentTarget}
taskId={taskId}
+ name={name}
/>
}
/>
@@ -168,6 +175,7 @@ export function ArtifactPreviewContent({
members={members}
onActivateThread={activateThread}
onCreate={createAnchoredComment}
+ onSendToAgent={sendCommentToAgent}
onResolutionsChange={onResolutionsChange}
/>
</div>
@@ -199,6 +207,7 @@ export function ArtifactPreviewContent({
<ArtifactDocumentCommentAction
target={commentTarget}
taskId={taskId}
+ name={name}
/>
}
/>
@@ -213,6 +222,7 @@ export function ArtifactPreviewContent({
members={members}
onActivateThread={activateThread}
onCreate={createAnchoredComment}
+ onSendToAgent={sendCommentToAgent}
onResolutionsChange={onResolutionsChange}
/>
</div>
@@ -233,7 +243,11 @@ export function ArtifactPreviewContent({
) {
const imageActions = (
<div className="flex shrink-0 items-center gap-1">
- <ArtifactDocumentCommentAction target={commentTarget} taskId={taskId} />
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ name={name}
+ />
<Tooltip>
<TooltipTrigger
render={
@@ -279,6 +293,7 @@ export function ArtifactPreviewContent({
onCommentingChange={setImageCommenting}
onActivateThread={activateThread}
onCreate={createAnchoredComment}
+ onSendToAgent={sendCommentToAgent}
onError={onMediaError}
/>
</div>
@@ -287,7 +302,11 @@ export function ArtifactPreviewContent({
}
const documentActions = (
- <ArtifactDocumentCommentAction target={commentTarget} taskId={taskId} />
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ name={name}
+ />
);
return (
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx
index 21c948ae4faf..240254f90ee7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactTextAnnotations.tsx
@@ -1,5 +1,6 @@
import type { ResourceComment } from "@posthog/api-client/posthog-client";
import {
+ type CommentAnchor,
createTextCommentAnchor,
resolveTextCommentAnchor,
type TextCommentAnchor,
@@ -138,6 +139,11 @@ interface ArtifactTextAnnotationsProps {
content: string,
mentions?: number[],
) => void | Promise<void>;
+ onSendToAgent?: (
+ anchor: CommentAnchor,
+ content: string,
+ screenshot: string | null,
+ ) => void;
onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
}
@@ -151,6 +157,7 @@ export function ArtifactTextAnnotations({
members,
onActivateThread,
onCreate,
+ onSendToAgent,
onResolutionsChange,
}: ArtifactTextAnnotationsProps) {
const [selection, setSelection] = useState<EditorSelection | null>(null);
@@ -401,6 +408,12 @@ export function ArtifactTextAnnotations({
onSubmit={async (_start, _end, content, mentions) => {
if (pendingAnchor) await onCreate(pendingAnchor, content, mentions);
}}
+ onSendToAgent={
+ onSendToAgent && pendingAnchor
+ ? (content, screenshot) =>
+ onSendToAgent(pendingAnchor, content, screenshot)
+ : undefined
+ }
/>
</>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.stories.tsx
index b75d53e92094..524edcebc47c 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.stories.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.stories.tsx
@@ -33,3 +33,9 @@ type Story = StoryObj<typeof meta>;
export const Empty: Story = {};
export const WithText: Story = { args: { value: "Check the updated layout." } };
+export const SendToAgent: Story = {
+ args: {
+ value: "Make this heading red and a bit larger.",
+ onSendToAgent: () => {},
+ },
+};
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 494f2bbbcf6b..b66ea1fccbad 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentComposer.tsx
@@ -1,8 +1,14 @@
import { PaperPlaneRightIcon, XIcon } from "@phosphor-icons/react";
-import { InputGroupAddon, InputGroupButton } from "@posthog/quill";
+import {
+ Checkbox,
+ InputGroupAddon,
+ InputGroupButton,
+ Label,
+} 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 { useId, useState } from "react";
import { mentionIdsFromContent } from "./commentMentions";
export function CommentComposer({
@@ -16,6 +22,7 @@ export function CommentComposer({
disabled = false,
submitLabel = "Comment",
autoFocus = false,
+ onSendToAgent,
compact = false,
}: {
value: string;
@@ -29,8 +36,11 @@ export function CommentComposer({
submitLabel?: string;
/** For a composer the user just opened, so they can type straight away. */
autoFocus?: boolean;
+ onSendToAgent?: (content: string) => void;
compact?: boolean;
}) {
+ const sendToAgentId = useId();
+ const [sendToAgent, setSendToAgent] = useState(false);
const mentionsDisabledReason = useMentionsDisabledReason();
const mentionMembers = mentionsDisabledReason ? [] : members;
const showMentionsDisabled = !!mentionsDisabledReason && value.includes("@");
@@ -39,7 +49,11 @@ export function CommentComposer({
if (!content || disabled) return;
void Promise.resolve(
onSubmit(content, mentionIdsFromContent(content, mentionMembers)),
- ).catch(() => undefined);
+ )
+ .then(() => {
+ if (sendToAgent) onSendToAgent?.(content);
+ })
+ .catch(() => undefined);
};
return (
@@ -63,6 +77,20 @@ export function CommentComposer({
{mentionsDisabledReason}
</output>
)}
+ {onSendToAgent && (
+ <Label
+ htmlFor={sendToAgentId}
+ className="flex cursor-pointer items-center gap-1.5 px-1 text-muted-foreground text-xs"
+ >
+ <Checkbox
+ id={sendToAgentId}
+ checked={sendToAgent}
+ data-attr="comment-send-to-agent"
+ onCheckedChange={(value) => setSendToAgent(value === true)}
+ />
+ Add to chat
+ </Label>
+ )}
{onCancel && (
<InputGroupButton
size="icon-sm"
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
index 3496fcd8ae00..c51d52c242d4 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
@@ -155,6 +155,7 @@ export function CommentThreadCard({
onSelect,
onReply,
onResolve,
+ onSendReplyToAgent,
}: {
threadId: string;
/** Root first, then replies. */
@@ -175,6 +176,7 @@ export function CommentThreadCard({
onSelect: () => void;
onReply: (content: string, mentions: number[]) => void | Promise<void>;
onResolve: (resolved: boolean) => void | Promise<void>;
+ onSendReplyToAgent?: (content: string) => void;
}) {
const [replying, setReplying] = useState(false);
const openButtonRef = useRef<HTMLButtonElement>(null);
@@ -358,6 +360,7 @@ export function CommentThreadCard({
submitLabel="Reply"
autoFocus={replying}
compact
+ onSendToAgent={onSendReplyToAgent}
/>
</div>
)
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
index 79dd485c9856..64d1882eb812 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.test.ts
@@ -31,7 +31,12 @@ describe("withSelectionPosition", () => {
}),
).toEqual({
...selection,
- anchor: { top: 80, endX: 230, bottom: 90 },
+ anchor: {
+ top: 80,
+ endX: 230,
+ bottom: 90,
+ bounds: { top: 100, left: 200, right: 600, bottom: 500 },
+ },
});
});
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts
index d3469d0d3173..7701cd0602b3 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentPosition.ts
@@ -1,14 +1,21 @@
import type { EditorSelection } from "@posthog/ui/features/code-editor/components/CodeMirrorEditor";
+import type { SelectionAnchor } from "@posthog/ui/features/code-editor/components/selectionScreenshot";
import type { ArtifactHtmlFrameRect } from "./artifactHtmlFrameHost";
export function selectionAnchor(
frame: ArtifactHtmlFrameRect,
selection: ArtifactHtmlFrameRect,
-): { top: number; endX: number; bottom: number } {
+): SelectionAnchor {
return {
top: frame.top + selection.top,
endX: frame.left + selection.right,
bottom: frame.top + selection.bottom,
+ bounds: {
+ top: frame.top,
+ left: frame.left,
+ right: frame.right,
+ bottom: frame.bottom,
+ },
};
}
diff --git a/products/desktop/packages/ui/src/features/sessions/sendCommentToAgent.test.ts b/products/desktop/packages/ui/src/features/sessions/sendCommentToAgent.test.ts
new file mode 100644
index 000000000000..3a29995d5402
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/sendCommentToAgent.test.ts
@@ -0,0 +1,39 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const send = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("@posthog/core/sessions/commentToAgent", () => ({
+ CommentToAgentService: class {
+ send = send;
+ },
+}));
+vi.mock("@posthog/ui/primitives/toast", () => ({
+ toast: { error: toastError },
+}));
+vi.mock("./commentToAgentHost", () => ({ commentToAgentHost: {} }));
+
+import { sendCommentToAgent } from "./sendCommentToAgent";
+
+describe("sendCommentToAgent", () => {
+ beforeEach(() => {
+ send.mockReset();
+ toastError.mockReset();
+ });
+
+ it("tells the user when a saved comment could not reach the chat", async () => {
+ send.mockRejectedValue(new Error("editor gone"));
+
+ await expect(
+ sendCommentToAgent({
+ taskId: "task-1",
+ comment: "Fix it",
+ context: null,
+ surface: "task",
+ }),
+ ).resolves.toBeUndefined();
+ expect(toastError).toHaveBeenCalledWith(
+ "Couldn't add the comment to chat",
+ "Your comment is saved. Copy it into the chat to send it to the agent.",
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/sendCommentToAgent.ts b/products/desktop/packages/ui/src/features/sessions/sendCommentToAgent.ts
new file mode 100644
index 000000000000..44a2e1ad3a67
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/sendCommentToAgent.ts
@@ -0,0 +1,16 @@
+import { CommentToAgentService } from "@posthog/core/sessions/commentToAgent";
+import { toast } from "@posthog/ui/primitives/toast";
+import { commentToAgentHost } from "./commentToAgentHost";
+
+const commentToAgentService = new CommentToAgentService(commentToAgentHost);
+
+export function sendCommentToAgent(
+ input: Parameters<CommentToAgentService["send"]>[0],
+): Promise<void> {
+ return commentToAgentService.send(input).catch(() => {
+ toast.error(
+ "Couldn't add the comment to chat",
+ "Your comment is saved. Copy it into the chat to send it to the agent.",
+ );
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/sendPromptToAgent.ts b/products/desktop/packages/ui/src/features/sessions/sendPromptToAgent.ts
index 907bd1f2b150..dccb934354d2 100644
--- a/products/desktop/packages/ui/src/features/sessions/sendPromptToAgent.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sendPromptToAgent.ts
@@ -1,14 +1,11 @@
import type { ContentBlock } from "@agentclientprotocol/sdk";
import { resolveService } from "@posthog/di/container";
import { toast } from "@posthog/ui/primitives/toast";
-import { useReviewNavigationStore } from "../code-review/reviewNavigationStore";
-import { DEFAULT_TAB_IDS } from "../panels/panelConstants";
-import { usePanelLayoutStore } from "../panels/panelLayoutStore";
-import { findTabInTree } from "../panels/panelTree";
import {
AGENT_PROMPT_SENDER,
type AgentPromptSender,
} from "./agentPromptSender";
+import { showTaskChat } from "./showTaskChat";
/**
* Sends a prompt to the agent session for a task, collapses the review
@@ -32,19 +29,7 @@ export function sendPromptToAgent(
return false;
});
- const { getReviewMode, setReviewMode } = useReviewNavigationStore.getState();
- if (getReviewMode(taskId) === "expanded") {
- setReviewMode(taskId, "split");
- }
-
- const { taskLayouts, setActiveTab } = usePanelLayoutStore.getState();
- const layout = taskLayouts[taskId];
- if (layout) {
- const result = findTabInTree(layout.panelTree, DEFAULT_TAB_IDS.LOGS);
- if (result) {
- setActiveTab(taskId, result.panelId, DEFAULT_TAB_IDS.LOGS);
- }
- }
+ showTaskChat(taskId);
return sendPromise;
}
diff --git a/products/desktop/packages/ui/src/features/sessions/showTaskChat.ts b/products/desktop/packages/ui/src/features/sessions/showTaskChat.ts
new file mode 100644
index 000000000000..fbfac54d738a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/showTaskChat.ts
@@ -0,0 +1,26 @@
+import { useReviewNavigationStore } from "../code-review/reviewNavigationStore";
+import { useDraftStore } from "../message-editor/draftStore";
+import { DEFAULT_TAB_IDS } from "../panels/panelConstants";
+import { usePanelLayoutStore } from "../panels/panelLayoutStore";
+import { findTabInTree } from "../panels/panelTree";
+
+export function showTaskChat(
+ taskId: string,
+ { focus = false }: { focus?: boolean } = {},
+): void {
+ const { getReviewMode, setReviewMode } = useReviewNavigationStore.getState();
+ if (getReviewMode(taskId) === "expanded") {
+ setReviewMode(taskId, "split");
+ }
+
+ const { taskLayouts, setActiveTab } = usePanelLayoutStore.getState();
+ const layout = taskLayouts[taskId];
+ if (layout) {
+ const result = findTabInTree(layout.panelTree, DEFAULT_TAB_IDS.LOGS);
+ if (result) {
+ setActiveTab(taskId, result.panelId, DEFAULT_TAB_IDS.LOGS);
+ }
+ }
+
+ if (focus) useDraftStore.getState().actions.requestFocus(taskId);
+}