: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): copy just the highlighted text, and rate agent turns (#80961)
Dylan Martin1fb3799c03eb
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 387705063cd8..4cb04a062d77 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -153,6 +153,21 @@ export interface PromptSentProperties {prompt_length_chars: number;}+/** Sentiment captured by the thumbs under an agent turn. */+export type AgentTurnFeedbackSentiment = "positive" | "negative";++/**+ * A reader's verdict on one agent turn, from the thumbs in the turn footer.+ * Feedback is analytics-only: it never changes the session. `turn_id` is+ * stable for the life of the thread, so switching thumbs re-fires the event+ * and the last one wins.+ */+export interface AgentTurnFeedbackProperties {+ task_id: string | null;+ turn_id: string;+ sentiment: AgentTurnFeedbackSentiment;+}+// Git operationsexport interface GitActionExecutedProperties {action_type: GitActionType;@@ -1330,6 +1345,7 @@ export const ANALYTICS_EVENTS = {TASK_RUN_CANCELLED: "Task run cancelled",TASK_RUN_STOPPED: "Task run stopped",PROMPT_SENT: "Prompt sent",+ AGENT_TURN_FEEDBACK: "Agent turn feedback",// Claude Code session importCLAUDE_SESSIONS_SHOWN: "Claude Code sessions shown",@@ -1514,6 +1530,7 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.TASK_RUN_CANCELLED]: TaskRunCancelledProperties;[ANALYTICS_EVENTS.TASK_RUN_STOPPED]: TaskRunStoppedProperties;[ANALYTICS_EVENTS.PROMPT_SENT]: PromptSentProperties;+ [ANALYTICS_EVENTS.AGENT_TURN_FEEDBACK]: AgentTurnFeedbackProperties;// Claude Code session import[ANALYTICS_EVENTS.CLAUDE_SESSIONS_SHOWN]: ClaudeSessionsShownProperties;diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex aa2be863cb19..b80521ad01ca 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -4,6 +4,8 @@ import {Copy,FileText,Scroll,+ ThumbsDown,+ ThumbsUp,} from "@phosphor-icons/react";import { WorkerPoolContextProvider } from "@pierre/diffs/react";import { useService } from "@posthog/di/react";@@ -36,8 +38,12 @@ import {useChatMessageScrollerScrollable,useChatMessageScrollerVisibility,} from "@posthog/quill";-import type { AcpMessage, AgentConversationEvent } from "@posthog/shared";-import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";+import type {+ AcpMessage,+ AgentConversationEvent,+ AgentTurnFeedbackSentiment,+} from "@posthog/shared";+import { ANALYTICS_EVENTS, PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";import type { Task } from "@posthog/shared/domain-types";import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";import { useSmoothedText } from "@posthog/ui/features/editor/components/useSmoothedText";@@ -83,7 +89,10 @@ import {import { buildTurnCopyText } from "@posthog/ui/features/sessions/components/chat-thread/turnCopyText";import { usePromptRecallSource } from "@posthog/ui/features/sessions/components/chat-thread/usePromptRecallSource";import { VirtualThreadScrollBody } from "@posthog/ui/features/sessions/components/chat-thread/VirtualThreadScrollBody";-import { copyFromContextMenu } from "@posthog/ui/features/sessions/components/copyContextTarget";+import {+ copyFromContextMenu,+ getSelectionWithin,+} from "@posthog/ui/features/sessions/components/copyContextTarget";import { GitActionMessage } from "@posthog/ui/features/sessions/components/GitActionMessage";import { GitActionResult } from "@posthog/ui/features/sessions/components/GitActionResult";import { isUserInitiatedConversationItem } from "@posthog/ui/features/sessions/components/isUserInitiatedConversationItem";@@ -114,6 +123,7 @@ import {import {useSessionViewActions,useShowRawLogs,+ useTurnFeedback,} from "@posthog/ui/features/sessions/sessionViewStore";import { useThreadScrollRequest } from "@posthog/ui/features/sessions/threadNavigationStore";import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";@@ -125,6 +135,7 @@ import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { SkillButtonActionMessage } from "@posthog/ui/features/skill-buttons/components/SkillButtonActionMessage";import { toast } from "@posthog/ui/primitives/toast";import { useCopy } from "@posthog/ui/primitives/useCopy";+import { track } from "@posthog/ui/shell/analytics";import {DIFF_WORKER_FACTORY,type DiffWorkerFactory,@@ -318,59 +329,146 @@ function formatTimestamp(ts: number): string {}/**- * Hover-revealed footer under a completed agent turn: the turn's timestamp plus a button copying- * the agent response. Rendered right-aligned under agent-side content — the end-aligned user bubble- * keeps its own footer — inside a `group` container, so it fades in only while that turn is- * hovered. Once per turn rather than per row, which was too noisy.+ * Hover-revealed footer under a completed agent turn: the turn's timestamp, a button copying the+ * agent response, and thumbs to rate it. Rendered right-aligned under agent-side content — the+ * end-aligned user bubble keeps its own footer — inside a `group` container, so it fades in only+ * while that turn is hovered. Once per turn rather than per row, which was too noisy.+ *+ * A rated turn keeps its footer on screen, so the reader can see which thumb they picked without+ * hovering to find out.*/function TurnFooter({+ turnId,timestamp,copyText,}: {+ turnId: string;timestamp?: number;copyText?: string;}) {+ const sentiment = useTurnFeedback(turnId);if (timestamp == null) return null;return (- <ChatMessageFooter className="mt-2 items-center justify-end gap-1 pl-0 opacity-0 transition-opacity group-hover:opacity-100">+ <ChatMessageFooter+ className={cn(+ "mt-2 items-center justify-end gap-1 pl-0 transition-opacity",+ sentiment ? "opacity-100" : "opacity-0 group-hover:opacity-100",+ )}+ ><span className="text-muted-foreground">{formatTimestamp(timestamp)}</span>{copyText && <CopyButton value={copyText} label="Copy turn" />}+ <TurnFeedback turnId={turnId} sentiment={sentiment} /></ChatMessageFooter>);}/**- * Shared copy affordance for the message and turn footers. Stays muted whether idle or just-copied —- * the icon swap is the confirmation, so the row never lights up in a colour the thread doesn't use- * elsewhere.+ * Thumbs on a completed agent turn, next to the copy button rather than behind the right-click+ * menu — rating a reply is a thing you do to the message, not to the text you happen to have+ * highlighted.+ *+ * The rating submits on the first click and is analytics-only: it never changes the session, so+ * there is nothing to confirm. Re-clicking the lit thumb is a no-op rather than a second identical+ * event; switching thumbs records the new sentiment.*/-function CopyButton({ value, label }: { value: string; label: string }) {- const { copied, copy } = useCopy();- const [hovered, setHovered] = useState(false);+function TurnFeedback({+ turnId,+ sentiment,+}: {+ turnId: string;+ sentiment: AgentTurnFeedbackSentiment | null;+}) {+ const taskId = useSessionTaskId();+ const { setTurnFeedback } = useSessionViewActions();++ const rate = (next: AgentTurnFeedbackSentiment) => {+ if (sentiment === next) return;+ setTurnFeedback(turnId, next);+ track(ANALYTICS_EVENTS.AGENT_TURN_FEEDBACK, {+ task_id: taskId,+ turn_id: turnId,+ sentiment: next,+ });+ };+return (- // Held open for the life of the `copied` window so the confirmation lands even when the click- // moves the pointer off the button; hover drives it the rest of the time.- <Tooltip open={copied || hovered} onOpenChange={setHovered}>+ <>+ <FooterIconButton label="Good response" onClick={() => rate("positive")}>+ <ThumbsUp+ size={12}+ weight={sentiment === "positive" ? "fill" : undefined}+ />+ </FooterIconButton>+ <FooterIconButton label="Bad response" onClick={() => rate("negative")}>+ <ThumbsDown+ size={12}+ weight={sentiment === "negative" ? "fill" : undefined}+ />+ </FooterIconButton>+ </>+ );+}++/**+ * Shared icon affordance for the message and turn footers. Stays muted whether idle or active — the+ * icon carries the state, so the row never lights up in a colour the thread doesn't use elsewhere.+ */+function FooterIconButton({+ label,+ tooltip,+ open,+ onOpenChange,+ onClick,+ children,+}: {+ label: string;+ /** Defaults to `label`; pass it separately when the tooltip has to say more than the button is. */+ tooltip?: string;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <Tooltip open={open} onOpenChange={onOpenChange}><TooltipTriggerrender={<Buttonvariant="default"size="icon-xs"aria-label={label}- onClick={() => copy(value)}+ onClick={onClick}className="text-muted-foreground hover:text-foreground">- {copied ? <Check size={12} /> : <Copy size={12} />}+ {children}</Button>}/>- <TooltipContent>{copied ? "Copied!" : label}</TooltipContent>+ <TooltipContent>{tooltip ?? label}</TooltipContent></Tooltip>);}+function CopyButton({ value, label }: { value: string; label: string }) {+ const { copied, copy } = useCopy();+ const [hovered, setHovered] = useState(false);+ return (+ // Held open for the life of the `copied` window so the confirmation lands even when the click+ // moves the pointer off the button; hover drives it the rest of the time.+ <FooterIconButton+ label={label}+ tooltip={copied ? "Copied!" : label}+ open={copied || hovered}+ onOpenChange={setHovered}+ onClick={() => copy(value)}+ >+ {copied ? <Check size={12} /> : <Copy size={12} />}+ </FooterIconButton>+ );+}+/*** End-aligned user bubble. The text is clamped to five lines (`max-height: 5lh` + `overflow-hidden`,* which — unlike `-webkit-line-clamp` — reliably clamps markdown's block `<p>` children); a "Show@@ -562,6 +660,10 @@ function UserBubble({* carries that menu's raw-logs toggle; without it, right-clicking a message would be the one spot* in the session where the toggle went missing.*+ * Highlighted text wins over the message: right-clicking a selection copies just that, as it does+ * outside the app. The whole message is the fallback for a right-click with nothing selected, and+ * stays reachable without the menu through the footer's copy button.+ ** The write goes through {@link copyFromContextMenu}: a synchronous write from a closing menu* rejects while focus is still being restored, and both outcomes surface as toasts — a silent* failure would leave the clipboard's previous contents where the user believes the message is.@@ -575,20 +677,27 @@ function MessageContextMenu({}) {const showRawLogs = useShowRawLogs();const { setShowRawLogs } = useSessionViewActions();+ const [selection, setSelection] = useState<string | null>(null);return (<ContextMenu>- <ContextMenuTrigger className="select-text" render={children} />+ <ContextMenuTrigger+ className="select-text"+ onContextMenu={(event) =>+ setSelection(getSelectionWithin(event.currentTarget))+ }+ render={children}+ /><ContextMenuContent><ContextMenuItemonClick={() =>- copyFromContextMenu(value, {+ copyFromContextMenu(selection ?? value, {onSuccess: () => toast.success("Copied"),onError: () => toast.error("Couldn't copy"),})}><Copy size={14} />- Copy message+ {selection ? "Copy selection" : "Copy message"}</ContextMenuItem><ContextMenuSeparator /><ContextMenuItem onClick={() => setShowRawLogs(!showRawLogs)}>@@ -719,6 +828,7 @@ const ThreadRow = memo(function ThreadRow({))}</div><TurnFooter+ turnId={item.id}timestamp={completedTurnTimestamp(item)}copyText={buildTurnCopyText(item.items) ?? undefined}/>@@ -1088,8 +1198,9 @@ const FlatRowView = memo(isTrailing={row.isTrailingInTurn}keyboardFocused={keyboardFocused}/>- {row.turnTimestamp != null && (+ {row.turnId != null && row.turnTimestamp != null && (<TurnFooter+ turnId={row.turnId}timestamp={row.turnTimestamp}copyText={row.turnCopyText}/>diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.tsindex 6f50d1bc9a4e..69e9353e4b0b 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts@@ -84,6 +84,8 @@ export interface FlatThreadRow {isTrailingInTurn: boolean;/** Set on the last row of a completed turn; renders the turn's hover timestamp under it. */turnTimestamp?: number;+ /** Set alongside {@link turnTimestamp}: identifies the turn its footer actions act on. */+ turnId?: string;/** Set alongside {@link turnTimestamp}: the agent response as plain text, for its copy button. */turnCopyText?: string;}@@ -123,6 +125,7 @@ export function flattenTurnRows(rows: TurnRow[]): FlatThreadRow[] {inTurn: true,isTrailingInTurn: isTrailing,turnTimestamp: isTrailing ? timestamp : undefined,+ turnId: isTrailing ? row.id : undefined,turnCopyText: isTrailing ? copyText : undefined,});}diff --git a/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.test.ts b/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.test.tsindex 936f0f1511e6..f3f84039f4e4 100644--- a/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";import {copyFromContextMenu,getGithubRefUrlFromEventTarget,+ getSelectionWithin,} from "./copyContextTarget";function buildDom(): {@@ -44,6 +45,85 @@ describe("getGithubRefUrlFromEventTarget", () => {});});+describe("getSelectionWithin", () => {+ interface Thread {+ first: HTMLElement;+ second: HTMLElement;+ firstText: Text;+ secondText: Text;+ }++ // Built node by node rather than from markup: the indentation between tags+ // becomes text nodes, which a cross-message range would pick up.+ function buildThread(): Thread {+ document.body.innerHTML = "";+ const thread = document.createElement("div");+ const first = document.createElement("div");+ const firstText = document.createTextNode("alpha bravo charlie");+ const second = document.createElement("div");+ const secondText = document.createTextNode("delta echo");+ first.appendChild(firstText);+ second.appendChild(secondText);+ thread.append(first, second);+ document.body.appendChild(thread);+ window.getSelection()?.removeAllRanges();+ return { first, second, firstText, secondText };+ }++ function select(+ start: Node,+ startOffset: number,+ end: Node,+ endOffset: number,+ ) {+ const range = document.createRange();+ range.setStart(start, startOffset);+ range.setEnd(end, endOffset);+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ }++ it.each<{+ name: string;+ highlight: (thread: Thread) => void;+ expected: string | null;+ }>([+ {+ name: "part of the message is highlighted",+ highlight: ({ firstText }) => select(firstText, 6, firstText, 11),+ expected: "bravo",+ },+ {+ name: "the highlight runs on into the next message",+ highlight: ({ firstText, secondText }) =>+ select(firstText, 12, secondText, 5),+ expected: "charliedelta",+ },+ { name: "nothing is highlighted", highlight: () => {}, expected: null },+ {+ name: "only another message is highlighted",+ highlight: ({ secondText }) => select(secondText, 0, secondText, 5),+ expected: null,+ },+ {+ name: "the highlight is only whitespace",+ highlight: ({ firstText }) => select(firstText, 5, firstText, 6),+ expected: null,+ },+ ])("returns $expected when $name", ({ highlight, expected }) => {+ const thread = buildThread();+ highlight(thread);+ expect(getSelectionWithin(thread.first)).toBe(expected);+ });++ it("returns null without a container to check against", () => {+ const { firstText } = buildThread();+ select(firstText, 0, firstText, 5);+ expect(getSelectionWithin(null)).toBeNull();+ });+});+describe("copyFromContextMenu", () => {it("defers the clipboard write until after the current task (focus race)", async () => {const writeText = vi.fn().mockResolvedValue(undefined);diff --git a/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.ts b/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.tsindex 79f69c8e6a76..47ffcc002802 100644--- a/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/copyContextTarget.ts@@ -18,6 +18,29 @@ export function getGithubRefUrlFromEventTarget();}+/**+ * The selected text when the selection reaches into `container`, else `null`.+ *+ * Lets a context menu inside a message copy what the reader highlighted rather+ * than the whole message, matching what right-clicking a selection does+ * everywhere else. Read it on the `contextmenu` event: once the menu opens it+ * owns focus, and the selection is no longer reliable.+ *+ * Intersection, not containment — a selection dragged across several messages+ * still copies whole from a right-click on any one of them.+ */+export function getSelectionWithin(container: Node | null): string | null {+ if (!container) return null;+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) return null;+ const text = selection.toString();+ if (!text.trim()) return null;+ for (let i = 0; i < selection.rangeCount; i++) {+ if (selection.getRangeAt(i).intersectsNode(container)) return text;+ }+ return null;+}+/*** Copy text to the clipboard from a context-menu selection.*diff --git a/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts b/products/desktop/packages/ui/src/features/sessions/sessionViewStore.tsindex 2d6c327a7e9b..f98e2585b30d 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts@@ -1,3 +1,4 @@+import type { AgentTurnFeedbackSentiment } from "@posthog/shared";import { create } from "zustand";interface SessionViewState {@@ -20,6 +21,13 @@ interface SessionViewState {string,{ collapsed: boolean; fileListKey: string }>;+ /**+ * Thumbs rating given to an agent turn, keyed by turn id. Feedback is+ * analytics-only, so this exists purely to keep the chosen thumb lit —+ * without it a rated turn would forget the click as soon as the virtualized+ * thread scrolled its row out of the window. Not persisted.+ */+ turnFeedbackByTurnId: Record<string, AgentTurnFeedbackSentiment>;}interface SessionViewActions {@@ -35,6 +43,10 @@ interface SessionViewActions {fileListKey: string,) => void;syncArtifactFilesListKey: (taskId: string, fileListKey: string) => void;+ setTurnFeedback: (+ turnId: string,+ sentiment: AgentTurnFeedbackSentiment,+ ) => void;}type SessionViewStore = SessionViewState & { actions: SessionViewActions };@@ -46,6 +58,7 @@ const useStore = create<SessionViewStore>((set) => ({groupOverrides: {},queueCollapsedByTaskId: {},artifactFilesCollapseByTaskId: {},+ turnFeedbackByTurnId: {},actions: {setShowRawLogs: (show) => set({ showRawLogs: show }),setSearchQuery: (query) => set({ searchQuery: query }),@@ -89,6 +102,13 @@ const useStore = create<SessionViewStore>((set) => ({},};}),+ setTurnFeedback: (turnId, sentiment) =>+ set((state) => ({+ turnFeedbackByTurnId: {+ ...state.turnFeedbackByTurnId,+ [turnId]: sentiment,+ },+ })),},}));@@ -109,4 +129,6 @@ export const useArtifactFilesCollapsed = ((fileListKey === undefined ||s.artifactFilesCollapseByTaskId[taskId]?.fileListKey === fileListKey),);+export const useTurnFeedback = (turnId: string) =>+ useStore((s) => s.turnFeedbackByTurnId[turnId] ?? null);export const useSessionViewActions = () => useStore((s) => s.actions);