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): chat with a report in a side panel, quote by highlighting (#87273)

Dylan Martin2f00425976b4
diff --git a/products/desktop/packages/ui/src/features/inbox/components/AskAboutSelection.tsx b/products/desktop/packages/ui/src/features/inbox/components/AskAboutSelection.tsx
new file mode 100644
index 000000000000..9a08f8093a34
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/AskAboutSelection.tsx
@@ -0,0 +1,117 @@
+import { ChatCircleIcon } from "@phosphor-icons/react";
+import { Button } from "@posthog/quill";
+import { type RefObject, useCallback, useEffect, useState } from "react";
+
+/** A text selection turned into a markdown blockquote for the chat composer. */
+export function quoteSelection(text: string): string {
+ const quoted = text
+ .trim()
+ .split("\n")
+ .map((line) => `> ${line.trim()}`)
+ .join("\n");
+ return `${quoted}\n\n`;
+}
+
+interface AskAboutSelectionProps {
+ /** Selections outside this container are ignored. */
+ containerRef: RefObject<HTMLElement | null>;
+ onAsk: (selectedText: string) => void;
+}
+
+/**
+ * The highlight-to-ask affordance: selecting text inside the container floats
+ * an "Ask about this" button by the selection; clicking it hands the passage
+ * to the chat panel as a quote. Selection state is read on mouseup rather than
+ * per selectionchange so the button doesn't chase a drag in progress.
+ */
+export function AskAboutSelection({
+ containerRef,
+ onAsk,
+}: AskAboutSelectionProps) {
+ const [anchor, setAnchor] = useState<{
+ top: number;
+ left: number;
+ text: string;
+ } | null>(null);
+
+ const readSelection = useCallback(() => {
+ const container = containerRef.current;
+ const selection = window.getSelection();
+ if (!container || !selection || selection.isCollapsed) {
+ setAnchor(null);
+ return;
+ }
+ const range = selection.getRangeAt(0);
+ if (!container.contains(range.commonAncestorContainer)) {
+ setAnchor(null);
+ return;
+ }
+ const text = selection.toString().trim();
+ if (!text) {
+ setAnchor(null);
+ return;
+ }
+ const rect = range.getBoundingClientRect();
+ setAnchor({
+ // Above the selection, clamped inside the viewport.
+ top: Math.max(8, rect.top - 36),
+ left: Math.min(
+ Math.max(8, rect.left + rect.width / 2),
+ window.innerWidth - 90,
+ ),
+ text,
+ });
+ }, [containerRef]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ const clear = () => {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed) setAnchor(null);
+ };
+ // The button is pinned to viewport coordinates captured once, so scrolling
+ // the report would strand it away from its passage. Scrolling doesn't
+ // collapse the selection, so `clear` never fires here — dismiss directly.
+ const dismissOnScroll = () => setAnchor(null);
+ container.addEventListener("mouseup", readSelection);
+ container.addEventListener("scroll", dismissOnScroll);
+ // Collapsing the selection anywhere (click, Esc, typing) dismisses the button.
+ document.addEventListener("selectionchange", clear);
+ return () => {
+ container.removeEventListener("mouseup", readSelection);
+ container.removeEventListener("scroll", dismissOnScroll);
+ document.removeEventListener("selectionchange", clear);
+ };
+ }, [containerRef, readSelection]);
+
+ if (!anchor) return null;
+
+ return (
+ <div
+ className="-translate-x-1/2 fixed z-50"
+ style={{ top: anchor.top, left: anchor.left }}
+ >
+ <Button
+ type="button"
+ variant="primary"
+ size="sm"
+ className="gap-1 shadow-md"
+ // preventDefault stops the mousedown from collapsing the selection,
+ // which would unmount the button before the click lands. Running the
+ // action on click (not mousedown) also lets Enter/Space activate it when
+ // focused; the quote comes from the captured anchor, not the live
+ // selection, so it stays correct on the mouse path.
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => {
+ onAsk(anchor.text);
+ setAnchor(null);
+ window.getSelection()?.removeAllRanges();
+ }}
+ >
+ <ChatCircleIcon size={13} />
+ Ask about this
+ </Button>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsx
new file mode 100644
index 000000000000..c8d571deff09
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsx
@@ -0,0 +1,264 @@
+import { ChatCircleIcon, XIcon } from "@phosphor-icons/react";
+import {
+ isContentEmpty,
+ textToContent,
+} from "@posthog/core/message-editor/content";
+import { Button, Spinner, Textarea } from "@posthog/quill";
+import type { SignalReport } from "@posthog/shared/types";
+import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
+import { useDiscussReport } from "@posthog/ui/features/inbox/hooks/useDiscussReport";
+import { useReportActionTracker } from "@posthog/ui/features/inbox/hooks/useReportActionTracker";
+import {
+ findLatestDiscussionTask,
+ useReportTasks,
+} from "@posthog/ui/features/inbox/hooks/useReportTasks";
+import { useReportChatPanelStore } from "@posthog/ui/features/inbox/stores/reportChatPanelStore";
+import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { EmbeddedSessionView } from "@posthog/ui/features/sessions/components/EmbeddedSessionView";
+import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
+import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useState } from "react";
+
+const isMac =
+ typeof navigator !== "undefined" && /Mac/i.test(navigator.platform);
+
+interface ReportChatSidebarProps {
+ report: SignalReport;
+}
+
+/**
+ * The report's conversation, docked beside the report so reading and asking
+ * happen on one screen (navigating away to a task page made people lose the
+ * report they were asking about). One persistent discussion per report:
+ * opening the panel resumes the report's existing discussion task, and only
+ * the first question creates one.
+ */
+export function ReportChatSidebar({ report }: ReportChatSidebarProps) {
+ const width = useReportChatPanelStore((s) => s.width);
+ const setWidth = useReportChatPanelStore((s) => s.setWidth);
+ const setOpen = useReportChatPanelStore((s) => s.setOpen);
+ const startedTaskId = useReportChatPanelStore(
+ (s) => s.startedTaskIdByReport[report.id] ?? null,
+ );
+ const [isResizing, setIsResizing] = useState(false);
+
+ // The durable association arrives via the report's task_run artefacts; a
+ // discussion started seconds ago is bridged by the store until it does.
+ const { data: reportTasks, isLoading: isLoadingTasks } = useReportTasks(
+ report.id,
+ report.status,
+ );
+ const discussionTask = findLatestDiscussionTask(reportTasks);
+ const taskId = discussionTask?.id ?? startedTaskId;
+
+ return (
+ <ResizableSidebar
+ open
+ width={width}
+ setWidth={setWidth}
+ isResizing={isResizing}
+ setIsResizing={setIsResizing}
+ side="right"
+ >
+ <div className="flex h-full min-w-0 flex-col border-border border-l bg-gray-1">
+ <div className="flex h-10 shrink-0 items-center justify-between border-b bg-chrome pr-2 pl-3">
+ <span className="flex items-center gap-1.5 font-medium text-[13px] text-gray-12">
+ <ChatCircleIcon size={14} />
+ Chat
+ </span>
+ <Button
+ size="icon-sm"
+ variant="default"
+ aria-label="Close chat"
+ onClick={() => setOpen(false)}
+ >
+ <XIcon size={14} />
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1">
+ {taskId ? (
+ <ReportChatConversation reportId={report.id} taskId={taskId} />
+ ) : isLoadingTasks ? (
+ // Until the report's tasks load we can't tell whether a discussion
+ // already exists; showing the starter here would let a fast submit
+ // open a second discussion for a report that already has one.
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ ) : (
+ <ReportChatStarter report={report} />
+ )}
+ </div>
+ </div>
+ </ResizableSidebar>
+ );
+}
+
+// Resolves the discussion's task record and renders its live session chat —
+// the same embedded view the canvas dock uses, so steering, queueing, and
+// follow-ups on a finished run all behave like they do elsewhere.
+function ReportChatConversation({
+ reportId,
+ taskId,
+}: {
+ reportId: string;
+ taskId: string;
+}) {
+ const { data: task } = useQuery(taskDetailQuery(taskId));
+
+ const pendingQuote = useReportChatPanelStore(
+ (s) => s.pendingQuoteByReport[reportId] ?? null,
+ );
+ const clearPendingQuote = useReportChatPanelStore((s) => s.clearPendingQuote);
+ const { insertPendingContent, getDraft, requestFocus } = useDraftStore(
+ (s) => s.actions,
+ );
+
+ // A highlighted passage is appended into the session composer, after anything
+ // already typed rather than replacing it. Inserting (rather than rewriting the
+ // draft) keeps chips and file attachments the user already added, and reaches
+ // the live editor even when it already holds text.
+ useEffect(() => {
+ if (!pendingQuote || !task) return;
+ const separator = isContentEmpty(getDraft(taskId)) ? "" : "\n\n";
+ insertPendingContent(taskId, textToContent(`${separator}${pendingQuote}`));
+ clearPendingQuote(reportId);
+ requestFocus(taskId);
+ }, [
+ pendingQuote,
+ task,
+ taskId,
+ reportId,
+ getDraft,
+ insertPendingContent,
+ clearPendingQuote,
+ requestFocus,
+ ]);
+
+ if (!task) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+
+ return <EmbeddedSessionView task={task} />;
+}
+
+// The report has no conversation yet: one question starts it, with the full
+// report and its evidence inlined as the agent's context.
+function ReportChatStarter({ report }: { report: SignalReport }) {
+ const queryClient = useQueryClient();
+ const fireAction = useReportActionTracker(report);
+ const rememberStartedTask = useReportChatPanelStore(
+ (s) => s.rememberStartedTask,
+ );
+ const pendingQuote = useReportChatPanelStore(
+ (s) => s.pendingQuoteByReport[report.id] ?? null,
+ );
+ const clearPendingQuote = useReportChatPanelStore((s) => s.clearPendingQuote);
+ const starterDraft = useReportChatPanelStore(
+ (s) => s.starterDraftByReport[report.id] ?? "",
+ );
+ const setStarterDraft = useReportChatPanelStore((s) => s.setStarterDraft);
+ const clearStarterDraft = useReportChatPanelStore((s) => s.clearStarterDraft);
+
+ useEffect(() => {
+ if (!pendingQuote) return;
+ const current =
+ useReportChatPanelStore.getState().starterDraftByReport[report.id] ?? "";
+ setStarterDraft(
+ report.id,
+ current.trim() ? `${current.trimEnd()}\n\n${pendingQuote}` : pendingQuote,
+ );
+ clearPendingQuote(report.id);
+ }, [pendingQuote, clearPendingQuote, setStarterDraft, report.id]);
+
+ // Discussions file into the report's space, or #general when it has none —
+ // a task without a channel shows in no space's sidebar at all.
+ const { generalChannel } = useTaskChannels();
+ const taskChannelId = report.channel_id ?? generalChannel?.id ?? null;
+
+ const { discussReport, isDiscussing } = useDiscussReport({
+ report,
+ channelId: taskChannelId,
+ redirectOnSuccess: false,
+ onTaskCreated: (task) => {
+ // Seed the detail cache with the task we already hold so the panel's
+ // useQuery resolves from cache instead of firing a GET that can 404 while
+ // the API catches up (mirrors openTask, which this non-redirect path skips).
+ queryClient.setQueryData(taskDetailQuery(task.id).queryKey, task);
+ rememberStartedTask(report.id, task.id);
+ // The task exists now, so the draft has served its purpose. Clearing only
+ // here (not on submit) keeps a failed creation's text for another try.
+ clearStarterDraft(report.id);
+ // The task_run artefact is written with the task, so a refetch picks up
+ // the durable association right away.
+ void queryClient.invalidateQueries({
+ queryKey: ["inbox", "report-tasks", report.id],
+ });
+ },
+ });
+
+ const submit = useCallback(() => {
+ const trimmed = starterDraft.trim();
+ if (!trimmed || isDiscussing) return;
+ // Only whether a question was asked — never the text. A quoted passage can
+ // be verbatim report content (customer data, code, identifiers), so it must
+ // not reach analytics.
+ fireAction("discuss", { has_question: true });
+ void discussReport(trimmed);
+ }, [starterDraft, isDiscussing, discussReport, fireAction]);
+
+ return (
+ <div className="flex h-full flex-col justify-between gap-3 p-3">
+ <div className="flex flex-col gap-1 pt-1">
+ <span className="font-medium text-[13px] text-gray-12">
+ Chat about this report
+ </span>
+ <span className="text-[12px] text-gray-11">
+ The agent joins with the full report and its evidence already in
+ context. Highlight any part of the report to quote it here.
+ </span>
+ </div>
+ <form
+ className="flex flex-col gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ >
+ <Textarea
+ aria-label="Question about this report"
+ autoFocus
+ placeholder="Ask about this report…"
+ rows={5}
+ value={starterDraft}
+ onChange={(event) => setStarterDraft(report.id, event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ submit();
+ }
+ }}
+ />
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-gray-10">
+ {isMac ? "⌘↵" : "Ctrl+↵"} to send
+ </span>
+ <Button
+ type="submit"
+ variant="primary"
+ size="sm"
+ disabled={!starterDraft.trim() || isDiscussing}
+ >
+ {isDiscussing && <Spinner />}
+ Start chat
+ </Button>
+ </div>
+ </form>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
index 97e67863a3e4..e96ac2f39bd3 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
@@ -1,10 +1,17 @@
import { FileTextIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";
import type { SignalReport } from "@posthog/shared/types";
+import {
+ AskAboutSelection,
+ quoteSelection,
+} from "@posthog/ui/features/inbox/components/AskAboutSelection";
import { ReportFeedbackFooter } from "@posthog/ui/features/inbox/components/detail/ReportFeedbackFooter";
import { InboxDetailFrame } from "@posthog/ui/features/inbox/components/InboxDetailFrame";
import { InboxReportDetailGate } from "@posthog/ui/features/inbox/components/InboxReportDetailGate";
+import { ReportChatSidebar } from "@posthog/ui/features/inbox/components/ReportChatSidebar";
import { ReportDetailActions } from "@posthog/ui/features/inbox/components/ReportDetailActions";
import { ReportVerdictBanner } from "@posthog/ui/features/inbox/components/ReportVerdictBanner";
+import { useReportChatPanelStore } from "@posthog/ui/features/inbox/stores/reportChatPanelStore";
+import { useCallback, useRef } from "react";
interface ReportDetailProps {
reportId: string;
@@ -48,6 +55,10 @@ export function ReportDetail({
* asks, with the action beside it), then the story (summary + charts), then
* the evidence. Pipeline machinery (runs, activity logs, reviewer reasoning)
* deliberately doesn't render.
+ *
+ * The report owns its own scroll so the chat dock can sit full-height beside
+ * it: reading and asking share one screen, and highlighting a passage quotes
+ * it into the chat.
*/
function ReportDetailContent({
report,
@@ -58,17 +69,36 @@ function ReportDetailContent({
backTo: string;
backLabel: string;
}) {
+ const chatOpen = useReportChatPanelStore((s) => s.open);
+ const setChatOpen = useReportChatPanelStore((s) => s.setOpen);
+ const setPendingQuote = useReportChatPanelStore((s) => s.setPendingQuote);
+ const contentRef = useRef<HTMLDivElement>(null);
+
+ const handleAsk = useCallback(
+ (text: string) => {
+ setPendingQuote(report.id, quoteSelection(text));
+ setChatOpen(true);
+ },
+ [report.id, setPendingQuote, setChatOpen],
+ );
+
return (
- <InboxDetailFrame
- report={report}
- backTo={backTo}
- backLabel={backLabel}
- fallbackTitle="Untitled report"
- primaryAction={<ReportDetailActions report={report} />}
- aboveSummary={<ReportVerdictBanner report={report} />}
- summarySection={{ Icon: FileTextIcon, title: "Summary" }}
- belowSummary={<ReportFeedbackFooter report={report} />}
- evidenceSection={{ Icon: MagnifyingGlassIcon, title: "Evidence" }}
- />
+ <div className="flex h-full min-h-0">
+ <div ref={contentRef} className="min-w-0 flex-1 overflow-y-auto">
+ <InboxDetailFrame
+ report={report}
+ backTo={backTo}
+ backLabel={backLabel}
+ fallbackTitle="Untitled report"
+ primaryAction={<ReportDetailActions report={report} />}
+ aboveSummary={<ReportVerdictBanner report={report} />}
+ summarySection={{ Icon: FileTextIcon, title: "Summary" }}
+ belowSummary={<ReportFeedbackFooter report={report} />}
+ evidenceSection={{ Icon: MagnifyingGlassIcon, title: "Evidence" }}
+ />
+ </div>
+ <AskAboutSelection containerRef={contentRef} onAsk={handleAsk} />
+ {chatOpen && <ReportChatSidebar report={report} />}
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx
index 771798c225c9..143097f94dae 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx
@@ -24,9 +24,9 @@ import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChanne
import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";
import { RefundReportDialog } from "@posthog/ui/features/inbox/components/RefundReportDialog";
import { useCreateCanvasReport } from "@posthog/ui/features/inbox/hooks/useCreateCanvasReport";
-import { useDiscussReport } from "@posthog/ui/features/inbox/hooks/useDiscussReport";
import { useRefundReport } from "@posthog/ui/features/inbox/hooks/useRefundReport";
import { useReportActionTracker } from "@posthog/ui/features/inbox/hooks/useReportActionTracker";
+import { useReportChatPanelStore } from "@posthog/ui/features/inbox/stores/reportChatPanelStore";
import { copyInboxReportLink } from "@posthog/ui/features/inbox/utils/copyInboxReportLink";
import { useCallback, useState } from "react";
@@ -42,8 +42,9 @@ const isMac =
/**
* The report header's action cluster: Discuss and Canvas stay visible, and
* everything occasional (GitHub, copy link, refund) folds into an overflow
- * menu. Starting or continuing implementation work lives in the verdict
- * banner above the summary (ReportVerdictBanner / PrDecisionBlock), not here.
+ * menu. Discuss opens the report's chat dock rather than navigating away;
+ * starting or continuing implementation work lives in the verdict banner
+ * above the summary (ReportVerdictBanner / PrDecisionBlock), not here.
*/
export function ReportDetailActions({
report,
@@ -54,18 +55,22 @@ export function ReportDetailActions({
const isResolved = report.status === "resolved";
const fireAction = useReportActionTracker(report);
- // Sessions and canvases started from a report file into the report's space,
- // or #general when the report has none — a task without a channel shows in
- // no space's sidebar at all.
+ const chatOpen = useReportChatPanelStore((s) => s.open);
+ const setChatOpen = useReportChatPanelStore((s) => s.setOpen);
+
+ const handleToggleChat = useCallback(() => {
+ if (!chatOpen) fireAction("discuss", { has_question: false });
+ setChatOpen(!chatOpen);
+ }, [chatOpen, setChatOpen, fireAction]);
+
+ // Canvases started from a report file into the report's space, or #general
+ // when the report has none — a task without a channel shows in no space's
+ // sidebar at all.
const { generalChannel, isLoading: channelsLoading } = useTaskChannels();
const taskChannelId = report.channel_id ?? generalChannel?.id ?? null;
// Until the channels query settles, an unassigned report has no fallback
// channel yet — creating a task then would file it into no space at all.
const awaitingChannel = taskChannelId === null && channelsLoading;
- const { discussReport, isDiscussing } = useDiscussReport({
- report,
- channelId: taskChannelId,
- });
const canvasActionEnabled = useChannelReportsEnabled();
const { createCanvasReport, isCreatingCanvas } = useCreateCanvasReport({
@@ -81,28 +86,16 @@ export function ReportDetailActions({
const refund = useRefundReport(report);
const [refundOpen, setRefundOpen] = useState(false);
- const handleCreateCanvas = useCallback(() => {
- fireAction("create_canvas");
- void createCanvasReport();
- }, [createCanvasReport, fireAction]);
-
- const [discussQuestion, setDiscussQuestion] = useState("");
- const [discussOpen, setDiscussOpen] = useState(false);
+ const [canvasOpen, setCanvasOpen] = useState(false);
+ const [canvasDirection, setCanvasDirection] = useState("");
- const submitDiscuss = useCallback(() => {
- const trimmed = discussQuestion.trim();
- if (!trimmed) return;
- fireAction("discuss", {
- has_question: true,
- question_text: trimmed.slice(0, 500),
- });
- setDiscussQuestion("");
- setDiscussOpen(false);
- void discussReport(trimmed);
- }, [discussQuestion, discussReport, fireAction]);
-
- const submitDisabled =
- discussQuestion.trim().length === 0 || isDiscussing || awaitingChannel;
+ const handleCreateCanvas = useCallback(() => {
+ const trimmed = canvasDirection.trim();
+ fireAction("create_canvas", { has_feedback: trimmed.length > 0 });
+ setCanvasDirection("");
+ setCanvasOpen(false);
+ void createCanvasReport(trimmed || undefined);
+ }, [canvasDirection, createCanvasReport, fireAction]);
// Read-only conveniences plus Refund. These are the only occasional actions,
// and the read-only ones stay even on a resolved report; Refund is a mutation,
@@ -154,95 +147,82 @@ export function ReportDetailActions({
return (
<>
- <Popover
- open={discussOpen}
- onOpenChange={(next) => {
- setDiscussOpen(next);
- if (!next) setDiscussQuestion("");
- }}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-pressed={chatOpen}
+ className="gap-1"
+ onClick={handleToggleChat}
+ title="Chat with the agent about this report"
>
- <PopoverTrigger
- render={
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={isDiscussing || awaitingChannel}
- className="gap-1"
- title="Discuss this report with your agent"
- >
- {isDiscussing ? <Spinner /> : <ChatCircleIcon size={12} />}
- Discuss
- </Button>
- }
- />
- <PopoverContent
- align="end"
- side="bottom"
- sideOffset={6}
- className="w-[420px] p-3"
+ <ChatCircleIcon size={12} />
+ Discuss
+ </Button>
+
+ {canvasActionEnabled && (
+ <Popover
+ open={canvasOpen}
+ onOpenChange={(next) => {
+ setCanvasOpen(next);
+ if (!next) setCanvasDirection("");
+ }}
>
- <form
- className="flex flex-col gap-2"
- onSubmit={(event) => {
- event.preventDefault();
- submitDiscuss();
- }}
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={isCreatingCanvas || awaitingChannel}
+ className="gap-1"
+ title="Have the agent build a canvas from this report"
+ >
+ {isCreatingCanvas ? <Spinner /> : <ShapesIcon size={12} />}
+ Canvas
+ </Button>
+ }
+ />
+ <PopoverContent
+ align="end"
+ side="bottom"
+ sideOffset={6}
+ className="flex w-[420px] flex-col gap-2 p-3"
>
+ <span className="text-[12px] text-gray-11">
+ What should the canvas focus on? The agent builds it from this
+ report's evidence and live data.
+ </span>
<Textarea
- aria-label="Question to discuss with the agent"
+ aria-label="What the canvas should focus on"
autoFocus
- placeholder="Ask about this report…"
- rows={5}
- value={discussQuestion}
- onChange={(event) => setDiscussQuestion(event.target.value)}
+ placeholder="Focus on… (optional)"
+ rows={3}
+ value={canvasDirection}
+ onChange={(event) => setCanvasDirection(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
- submitDiscuss();
+ handleCreateCanvas();
}
}}
/>
<div className="flex items-center justify-between gap-2">
<span className="text-[11px] text-gray-10">
- {isMac ? "⌘↵" : "Ctrl+↵"} to send
+ {isMac ? "⌘↵" : "Ctrl+↵"} to create
</span>
- <div className="flex gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setDiscussOpen(false)}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- variant="primary"
- size="sm"
- disabled={submitDisabled}
- >
- Discuss
- </Button>
- </div>
+ <Button
+ type="button"
+ variant="primary"
+ size="sm"
+ disabled={isCreatingCanvas || awaitingChannel}
+ onClick={handleCreateCanvas}
+ >
+ Create canvas
+ </Button>
</div>
- </form>
- </PopoverContent>
- </Popover>
-
- {canvasActionEnabled && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={isCreatingCanvas || awaitingChannel}
- className="gap-1"
- onClick={handleCreateCanvas}
- title="Have your agent build a canvas from this report"
- >
- {isCreatingCanvas ? <Spinner /> : <ShapesIcon size={12} />}
- Canvas
- </Button>
+ </PopoverContent>
+ </Popover>
)}
{overflowMenu}
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useDiscussReport.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useDiscussReport.ts
index 4d1ab8e33260..24bba448b1b5 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useDiscussReport.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useDiscussReport.ts
@@ -1,7 +1,7 @@
import { buildDiscussReportPrompt } from "@posthog/core/inbox/reportActions";
import { buildReportPromptContext } from "@posthog/core/inbox/reportPromptContext";
import type { TaskCreationInput } from "@posthog/core/task-detail/taskService";
-import type { SignalReport } from "@posthog/shared/types";
+import type { SignalReport, Task } from "@posthog/shared/types";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
import {
@@ -19,6 +19,10 @@ interface UseDiscussReportOptions {
report: SignalReport;
/** Space the created session belongs to (its feed home); null files it nowhere. */
channelId?: string | null;
+ /** Off for callers that show the conversation in place (the chat panel). */
+ redirectOnSuccess?: boolean;
+ /** Called with the created task, before any navigation. */
+ onTaskCreated?: (task: Task) => void;
}
interface UseDiscussReportReturn {
@@ -50,6 +54,8 @@ function buildDiscussDescription(
export function useDiscussReport({
report,
channelId,
+ redirectOnSuccess,
+ onTaskCreated,
}: UseDiscussReportOptions): UseDiscussReportReturn {
const queryClient = useQueryClient();
const client = useOptionalAuthenticatedClient();
@@ -118,6 +124,8 @@ export function useDiscussReport({
},
buildInput,
analyticsExtras: { has_branch: false },
+ redirectOnSuccess,
+ onTaskCreated,
});
const discussReport = useCallback(
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts
index 997996e78434..0a541ac7ce17 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts
@@ -2,6 +2,7 @@ import type { Task, TaskRun, TaskRunStatus } from "@posthog/shared/types";
import { describe, expect, it } from "vitest";
import {
findContinuableImplementationTask,
+ findLatestDiscussionTask,
getTaskPrUrl,
type ReportTaskData,
type ReportTaskPurpose,
@@ -106,6 +107,19 @@ describe("findContinuableImplementationTask", () => {
});
});
+describe("findLatestDiscussionTask", () => {
+ it("returns the newest discussion and ignores other purposes", () => {
+ const older = entry(makeTask("old-chat"), "discussion");
+ older.startedAt = "2026-06-20T10:00:00Z";
+ const newer = entry(makeTask("new-chat"), "discussion");
+ newer.startedAt = "2026-06-24T10:00:00Z";
+ const impl = entry(makeTask("impl", { prUrl: "https://gh/pr/1" }));
+ expect(findLatestDiscussionTask([impl, older, newer])).toBe(newer.task);
+ expect(findLatestDiscussionTask([impl])).toBeNull();
+ expect(findLatestDiscussionTask(undefined)).toBeNull();
+ });
+});
+
describe("getTaskPrUrl", () => {
it("returns the PR url when present", () => {
expect(
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts
index 76ba270a13ea..b3adf9e0189d 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts
@@ -10,7 +10,11 @@ import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
// Task↔report associations are unlabelled — a task's purpose is derived from the report's
// `task_run` artefacts (the signals pipeline writes product="signals" with one of these types;
// custom agents write their own (product, type) pair).
-export type ReportTaskPurpose = "research" | "implementation" | "other";
+export type ReportTaskPurpose =
+ | "research"
+ | "implementation"
+ | "discussion"
+ | "other";
export interface ReportTaskData {
task: Task;
@@ -31,6 +35,9 @@ function derivePurpose(taskRun: {
if (taskRun.type === "implementation") {
return { purpose: "implementation", purposeLabel: "Implementation" };
}
+ if (taskRun.type === "discussion") {
+ return { purpose: "discussion", purposeLabel: "Discussion" };
+ }
// repo_selection runs are plumbing, not report work — never displayed (matches the
// pre-derivation behavior of only showing research/implementation).
return null;
@@ -44,6 +51,7 @@ function derivePurpose(taskRun: {
const PURPOSE_ORDER: ReportTaskPurpose[] = [
"implementation",
"research",
+ "discussion",
"other",
];
@@ -144,3 +152,20 @@ export function findContinuableImplementationTask(
});
return running?.task ?? null;
}
+
+/**
+ * The report's conversation: the newest discussion task linked to it. A report
+ * has one ongoing chat rather than a pile of one-question sessions, so opening
+ * the chat panel resumes this task when it exists and only starts a fresh one
+ * when it doesn't.
+ */
+export function findLatestDiscussionTask(
+ reportTasks: ReportTaskData[] | undefined,
+): Task | null {
+ if (!reportTasks) return null;
+ const discussions = reportTasks.filter((t) => t.purpose === "discussion");
+ if (discussions.length === 0) return null;
+ return discussions.reduce((latest, t) =>
+ t.startedAt > latest.startedAt ? t : latest,
+ ).task;
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/stores/reportChatPanelStore.ts b/products/desktop/packages/ui/src/features/inbox/stores/reportChatPanelStore.ts
new file mode 100644
index 000000000000..dc9957357992
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/stores/reportChatPanelStore.ts
@@ -0,0 +1,75 @@
+import { create } from "zustand";
+
+interface ReportChatPanelState {
+ /** Whether the chat dock is showing beside the open report. */
+ open: boolean;
+ width: number;
+ /**
+ * Task ids of discussions started this session, per report. Bridges the gap
+ * between creating the discussion task and its task_run artefact appearing
+ * in the report's artefact list (the durable association).
+ */
+ startedTaskIdByReport: Record<string, string>;
+ /**
+ * A highlighted passage waiting to be quoted into the report's chat
+ * composer. Written by the selection affordance, consumed once by the panel.
+ */
+ pendingQuoteByReport: Record<string, string>;
+ /**
+ * The starter question typed before a discussion exists, per report. Held in
+ * the store rather than component state so closing the panel — which unmounts
+ * the starter — keeps the draft (and any quote folded into it). Cleared once a
+ * discussion task is created.
+ */
+ starterDraftByReport: Record<string, string>;
+ setOpen: (open: boolean) => void;
+ setWidth: (width: number) => void;
+ rememberStartedTask: (reportId: string, taskId: string) => void;
+ setPendingQuote: (reportId: string, quote: string) => void;
+ clearPendingQuote: (reportId: string) => void;
+ setStarterDraft: (reportId: string, text: string) => void;
+ clearStarterDraft: (reportId: string) => void;
+}
+
+export const useReportChatPanelStore = create<ReportChatPanelState>((set) => ({
+ open: false,
+ width: 420,
+ startedTaskIdByReport: {},
+ pendingQuoteByReport: {},
+ starterDraftByReport: {},
+ setOpen: (open) => set({ open }),
+ setWidth: (width) => set({ width }),
+ rememberStartedTask: (reportId, taskId) =>
+ set((state) => ({
+ startedTaskIdByReport: {
+ ...state.startedTaskIdByReport,
+ [reportId]: taskId,
+ },
+ })),
+ setPendingQuote: (reportId, quote) =>
+ set((state) => ({
+ pendingQuoteByReport: {
+ ...state.pendingQuoteByReport,
+ [reportId]: quote,
+ },
+ })),
+ clearPendingQuote: (reportId) =>
+ set((state) => {
+ if (!(reportId in state.pendingQuoteByReport)) return state;
+ const { [reportId]: _, ...rest } = state.pendingQuoteByReport;
+ return { pendingQuoteByReport: rest };
+ }),
+ setStarterDraft: (reportId, text) =>
+ set((state) => ({
+ starterDraftByReport: {
+ ...state.starterDraftByReport,
+ [reportId]: text,
+ },
+ })),
+ clearStarterDraft: (reportId) =>
+ set((state) => {
+ if (!(reportId in state.starterDraftByReport)) return state;
+ const { [reportId]: _, ...rest } = state.starterDraftByReport;
+ return { starterDraftByReport: rest };
+ }),
+}));
diff --git a/products/desktop/packages/ui/src/router/routes/website/$channelId/reports/$reportId.tsx b/products/desktop/packages/ui/src/router/routes/website/$channelId/reports/$reportId.tsx
index afa0d7fdea83..91a052da6b46 100644
--- a/products/desktop/packages/ui/src/router/routes/website/$channelId/reports/$reportId.tsx
+++ b/products/desktop/packages/ui/src/router/routes/website/$channelId/reports/$reportId.tsx
@@ -20,9 +20,9 @@ function ChannelReportDetailRoute() {
const { channels } = useChannels();
const channelName = channels.find((c) => c.id === channelId)?.name;
return (
- // WebsiteLayout's outlet is overflow-hidden, so the detail supplies its
- // own scroll container (the inbox shell used to provide this).
- <div className="h-full min-h-0 overflow-y-auto">
+ // ReportDetail owns its scroll (its chat dock sits beside the scrolling
+ // report); this wrapper only hands it WebsiteLayout's outlet height.
+ <div className="h-full min-h-0">
<ReportDetail
reportId={reportId}
cachedReport={cachedReport}