: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): session right panel for timeline, artifacts and changes (#82584)
Adam Leith44fcb06e48a0
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 0c49a9577cc8..11e55dd4b6a8 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -1601,7 +1601,7 @@ export class SessionService {private static readonly TASK_CREATION_IN_FLIGHT_TTL_MS = 10 * 60 * 1000;private activityHeartbeats = new Map<string,- ReturnType<typeof setInterval>+ { timer: ReturnType<typeof setInterval>; holders: number }>();private localRepoPaths = new Map<string, string>();private localRecoveryAttempts = new Map<string, Promise<boolean>>();@@ -7008,6 +7008,14 @@ export class SessionService {this.d.store.updateSession(session.taskRunId, { taskTitle });}+ /**+ * One heartbeat per run, held by however many surfaces are watching it. The+ * count is what makes that safe: several components mount the same run at+ * once (the transcript, the logs, the session panel), and an unheld beat+ * would let whichever unmounts first stop the run's activity signal for the+ * others, leaving the server free to idle-reclaim an agent someone is+ * watching.+ */public startActivityHeartbeat(taskRunId: string): () => void {const record = () => {this.d.trpc.agent.recordActivity.mutate({ taskRunId }).catch(() => {});@@ -7016,13 +7024,23 @@ export class SessionService {record();const existing = this.activityHeartbeats.get(taskRunId);if (existing) {- clearInterval(existing);+ existing.holders += 1;+ } else {+ this.activityHeartbeats.set(taskRunId, {+ timer: setInterval(record, ACTIVITY_HEARTBEAT_INTERVAL_MS),+ holders: 1,+ });}- const heartbeat = setInterval(record, ACTIVITY_HEARTBEAT_INTERVAL_MS);- this.activityHeartbeats.set(taskRunId, heartbeat);+ let released = false;return () => {- clearInterval(heartbeat);+ if (released) return;+ released = true;+ const entry = this.activityHeartbeats.get(taskRunId);+ if (!entry) return;+ entry.holders -= 1;+ if (entry.holders > 0) return;+ clearInterval(entry.timer);this.activityHeartbeats.delete(taskRunId);};}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsxindex abeeaf33dfd8..53ef7c7eb08f 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx@@ -147,41 +147,24 @@ describe("ActivityPanel", () => {expect(screen.getByText("timeline body")).toBeTruthy();});- // A focus left over from an earlier visit must not hijack the panel, and the- // panel is reused across tasks without remounting.- it("does not open comments for a focus that predates the task", () => {- useCommentNavigationStore- .getState()- .requestCommentFocus(- "task-2",- { scope: "task_artifact", itemId: "artifact-1" },- "comment-1",- );- const { rerender } = renderPanel("task-1");-- rerender(- <ActivityPanel- taskId="task-2"- channelId="channel-1"- task={{ ...task, id: "task-2" }}- showTaskSummary={false}- />,- );-- expect(screen.getByText("timeline body")).toBeTruthy();- });-- it("keeps a fresh focus request when the panel switches tasks", () => {- const { rerender } = renderPanel("task-1");- act(() =>+ // A request nobody has shown yet is outstanding whenever it was written, and+ // the click that picks a thread often precedes the surface that can show it.+ it.each([+ { name: "before the panel rendered the task", beforeMount: true },+ { name: "while the panel was on another task", beforeMount: false },+ ])("opens comments for a request made $name", ({ beforeMount }) => {+ const request = () =>useCommentNavigationStore.getState().requestCommentFocus("task-2",{ scope: "task_artifact", itemId: "artifact-1" },"comment-1",- ),- );+ );++ if (beforeMount) request();+ const { rerender } = renderPanel("task-1");+ if (!beforeMount) act(request);rerender(<ActivityPanel@@ -193,6 +176,12 @@ describe("ActivityPanel", () => {);expect(screen.getByText("comments body")).toBeTruthy();+ // Acknowledged on the way, so the request is spent rather than reopening+ // comments over every later surface that reads it.+ expect(+ useCommentNavigationStore.getState().focusByTask["task-2"]+ ?.openCommentsTab,+ ).toBe(false);});// Only the timeline reads bottom-up; the thread lists put what matters on top.diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsxindex d944c9ed69e8..56ff6d26d5b6 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx@@ -1,5 +1,4 @@import {- ArrowDownIcon,ArrowSquareOutIcon,CaretRightIcon,XIcon,@@ -7,30 +6,18 @@ import {import { Button, Tabs, TabsList, TabsTrigger } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { Task } from "@posthog/shared/domain-types";-import { ActivityTimeline } from "@posthog/ui/features/canvas/components/ActivityTimeline";-import { ActivityLoadingState } from "@posthog/ui/features/canvas/components/activityRows";-import { TaskCard } from "@posthog/ui/features/canvas/components/ChannelFeedView";-import { TaskArtifactsList } from "@posthog/ui/features/canvas/components/TaskArtifactsList";-import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";import {- AgentStatusLine,- ThreadLoadingState,-} from "@posthog/ui/features/canvas/components/ThreadPanel";+ ActivityPanelBody,+ type ActivityTab,+} from "@posthog/ui/features/canvas/components/ActivityPanelBody";+import { TaskCard } from "@posthog/ui/features/canvas/components/ChannelFeedView";+import { ThreadLoadingState } from "@posthog/ui/features/canvas/components/ThreadPanel";import { useTaskThread } from "@posthog/ui/features/canvas/hooks/useTaskThread";-import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";-import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";-import { buildConversationItems } from "@posthog/ui/features/sessions/components/buildConversationItems";-import { mergeConversationItems } from "@posthog/ui/features/sessions/components/mergeConversationItems";-import {- useOptimisticItemsForTask,- useSessionIsCloud,-} from "@posthog/ui/features/sessions/sessionStore";+import { useCommentFocusRequest } from "@posthog/ui/features/sessions/useCommentFocusRequest";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";import { track } from "@posthog/ui/shell/analytics";import { useQuery } from "@tanstack/react-query";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";--type ActivityTab = "timeline" | "artifacts" | "comments";+import { useCallback, useState } from "react";const ACTIVITY_TABS: readonly { key: ActivityTab; label: string }[] = [{ key: "timeline", label: "Timeline" },@@ -135,16 +122,6 @@ function ActivityConversation({canOpenInPlace?: boolean;}) {const taskId = task.id;- const {- timeline,- messages,- agentStatus,- events,- isPromptPending,- hasLoadedThread,- currentUser,- } = useThreadConversation(task, { surface: "activity_panel" });-const [tab, setTab] = useState<ActivityTab>("timeline");const handleTabChange = useCallback((next: ActivityTab) => {@@ -159,131 +136,8 @@ function ActivityConversation({[taskId],);- // Draw once the thread has answered, and never take the timeline away again.- // Gating on the live session (`isReady`) blinks a loader over drawn rows while it- // connects. The latch is set on commit, because Strict Mode and concurrent- // rendering abandon renders that would otherwise set it.- const hasDrawnTimeline = useRef(false);- const timelineReady = hasDrawnTimeline.current || hasLoadedThread;- useEffect(() => {- if (hasLoadedThread) hasDrawnTimeline.current = true;- }, [hasLoadedThread]);-- // Merged exactly as the transcript merges it, because "Show in chat" hands the transcript- // one of these item ids. A prompt still waiting on its echo is an optimistic item there and- // the server copy is dropped, so raw events alone would name a row it does not render.- const optimisticItems = useOptimisticItemsForTask(taskId);- const isCloudSession = useSessionIsCloud(taskId);- const conversationItems = useMemo(- () =>- tab === "timeline"- ? mergeConversationItems({- conversationItems: buildConversationItems(events, isPromptPending)- .items,- optimisticItems,- isCloud: isCloudSession,- })- : [],- [tab, events, isPromptPending, optimisticItems, isCloudSession],- );-- // A thread picked on the artifact itself lives in the Comments tab, so the- // pick has to bring the tab with it. Only a fresh request switches tabs: a- // focus left over from an earlier visit must not hijack the panel on mount.- const focusByTask = useCommentNavigationStore((state) => state.focusByTask);- const commentFocus = focusByTask[taskId];- const acknowledgeCommentsTabOpen = useCommentNavigationStore(- (state) => state.acknowledgeCommentsTabOpen,- );- // Seed requests that predate this panel, but leave later requests for other tasks pending- // until the reused panel switches to that task.- const seenFocus = useRef(- new Map(- Object.entries(focusByTask).map(([focusTaskId, focus]) => [- focusTaskId,- focus?.nonce ?? null,- ]),- ),- );- useEffect(() => {- if (- commentFocus?.openCommentsTab &&- commentFocus.nonce !== seenFocus.current.get(taskId)- ) {- seenFocus.current.set(taskId, commentFocus.nonce);- // Not handleTabChange: a programmatic switch isn't a user tab change.- setTab("comments");- }- }, [commentFocus, taskId]);- useEffect(() => {- if (tab === "comments" && commentFocus?.openCommentsTab) {- acknowledgeCommentsTabOpen(taskId, commentFocus.nonce);- }- }, [acknowledgeCommentsTabOpen, commentFocus, tab, taskId]);-- const scrollRef = useRef<HTMLDivElement>(null);- // Within this much of the bottom still counts as watching the end, so a row arriving- // mid-poll keeps following. Wide enough to survive a partially scrolled last row.- const AT_BOTTOM_SLACK_PX = 48;- const [hasNewerBelow, setHasNewerBelow] = useState(false);- const scrollToLatest = useCallback(() => {- const node = scrollRef.current;- if (!node) return;- node.scrollTo({ top: node.scrollHeight });- setHasNewerBelow(false);- }, []);- const onScroll = useCallback(() => {- const node = scrollRef.current;- if (!node) return;- const atBottom =- node.scrollHeight - node.scrollTop - node.clientHeight <=- AT_BOTTOM_SLACK_PX;- if (atBottom) setHasNewerBelow(false);- }, []);- // biome-ignore lint/correctness/useExhaustiveDependencies: follow the end when rendered content changes- useEffect(() => {- // Only the timeline reads bottom-up; the other tabs put what matters on top.- if (tab !== "timeline") return;- const node = scrollRef.current;- if (!node) return;- // Following unconditionally yanks the panel to the bottom on every refetch while someone- // is reading further up, so follow only for a reader already at the end.- const atBottom =- node.scrollHeight - node.scrollTop - node.clientHeight <=- AT_BOTTOM_SLACK_PX;- if (atBottom) {- node.scrollTo({ top: node.scrollHeight });- setHasNewerBelow(false);- return;- }- setHasNewerBelow(true);- }, [timeline, events.length, agentStatus?.phase, tab]);-- const body = () => {- if (tab === "comments") {- return <TaskCommentsList task={task} timeline={timeline} />;- }- if (tab === "artifacts") {- return (- <TaskArtifactsList- task={task}- timeline={timeline}- canOpenInPlace={canOpenInPlace}- />- );- }- if (!timelineReady) return <ActivityLoadingState />;- return (- <ActivityTimeline- task={task}- timeline={timeline}- messages={messages}- conversationItems={conversationItems}- currentUserId={currentUser?.id}- canOpenInPlace={canOpenInPlace}- />- );- };+ // Not handleTabChange: a programmatic switch isn't a user tab change.+ useCommentFocusRequest(taskId, () => setTab("comments"));return (<div className="flex h-full min-w-0 flex-col bg-gray-1">@@ -300,31 +154,15 @@ function ActivityConversation({<TaskCard task={task} channelId={channelId} inThread /></div>)}- <div className="relative flex min-h-0 flex-1 flex-col">- <div- ref={scrollRef}- onScroll={onScroll}- aria-busy={!timelineReady}- className="flex-1 overflow-y-auto"- >- {body()}- </div>- {tab === "timeline" && hasNewerBelow && (- <Button- variant="default"- size="sm"- className="-translate-x-1/2 absolute bottom-2 left-1/2 z-20 shadow-md"- onClick={scrollToLatest}- >- <ArrowDownIcon size={12} />- New activity- </Button>- )}- </div>-- {tab === "timeline" && agentStatus && (- <AgentStatusLine status={agentStatus} />- )}+ {/* Keyed by session: the body latches "the timeline has drawn" so it+ never blinks back to a loader, and the dock reuses one body across+ tasks, which would carry that latch onto a session still loading. */}+ <ActivityPanelBody+ key={taskId}+ task={task}+ tab={tab}+ canOpenInPlace={canOpenInPlace}+ /></div>);}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsxnew file mode 100644index 000000000000..6f49f9f19d5d--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsx@@ -0,0 +1,170 @@+import { ArrowDownIcon } from "@phosphor-icons/react";+import { Button } from "@posthog/quill";+import type { Task } from "@posthog/shared/domain-types";+import { ActivityTimeline } from "@posthog/ui/features/canvas/components/ActivityTimeline";+import { ActivityLoadingState } from "@posthog/ui/features/canvas/components/activityRows";+import { TaskArtifactsList } from "@posthog/ui/features/canvas/components/TaskArtifactsList";+import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";+import { AgentStatusLine } from "@posthog/ui/features/canvas/components/ThreadPanel";+import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";+import { buildConversationItems } from "@posthog/ui/features/sessions/components/buildConversationItems";+import { mergeConversationItems } from "@posthog/ui/features/sessions/components/mergeConversationItems";+import {+ useOptimisticItemsForTask,+ useSessionIsCloud,+} from "@posthog/ui/features/sessions/sessionStore";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";++export type ActivityTab = "timeline" | "artifacts" | "comments";++// Within this much of the bottom still counts as watching the end, so a row arriving+// mid-poll keeps following. Wide enough to survive a partially scrolled last row.+const AT_BOTTOM_SLACK_PX = 48;++/**+ * A session's activity: its timeline, artifacts, or comments. Which one is+ * picked by the panel above it, either the tabbed dock (ActivityPanel) or the+ * chrome's right panel (RightPanel), so the three lists behave the same+ * wherever they are drawn.+ */+export function ActivityPanelBody({+ task,+ tab,+ canOpenInPlace,+}: {+ task: Task;+ tab: ActivityTab;+ /** Set where the task's own view (transcript, review pane) is mounted beside+ * this body, so activity rows can drive it instead of going nowhere. */+ canOpenInPlace?: boolean;+}) {+ const taskId = task.id;+ const {+ timeline,+ messages,+ agentStatus,+ events,+ isPromptPending,+ hasLoadedThread,+ currentUser,+ } = useThreadConversation(task, { surface: "activity_panel" });++ // Draw once the thread has answered, and never take the timeline away again.+ // Gating on the live session (`isReady`) blinks a loader over drawn rows while it+ // connects. The latch is set on commit, because Strict Mode and concurrent+ // rendering abandon renders that would otherwise set it.+ const hasDrawnTimeline = useRef(false);+ const timelineReady = hasDrawnTimeline.current || hasLoadedThread;+ useEffect(() => {+ if (hasLoadedThread) hasDrawnTimeline.current = true;+ }, [hasLoadedThread]);++ // Merged exactly as the transcript merges it, because "Show in chat" hands the transcript+ // one of these item ids. A prompt still waiting on its echo is an optimistic item there and+ // the server copy is dropped, so raw events alone would name a row it does not render.+ const optimisticItems = useOptimisticItemsForTask(taskId);+ const isCloudSession = useSessionIsCloud(taskId);+ const conversationItems = useMemo(+ () =>+ tab === "timeline"+ ? mergeConversationItems({+ conversationItems: buildConversationItems(events, isPromptPending)+ .items,+ optimisticItems,+ isCloud: isCloudSession,+ })+ : [],+ [tab, events, isPromptPending, optimisticItems, isCloudSession],+ );++ const scrollRef = useRef<HTMLDivElement>(null);+ const [hasNewerBelow, setHasNewerBelow] = useState(false);+ const scrollToLatest = useCallback(() => {+ const node = scrollRef.current;+ if (!node) return;+ node.scrollTo({ top: node.scrollHeight });+ setHasNewerBelow(false);+ }, []);+ const onScroll = useCallback(() => {+ const node = scrollRef.current;+ if (!node) return;+ const atBottom =+ node.scrollHeight - node.scrollTop - node.clientHeight <=+ AT_BOTTOM_SLACK_PX;+ if (atBottom) setHasNewerBelow(false);+ }, []);+ // biome-ignore lint/correctness/useExhaustiveDependencies: follow the end when rendered content changes+ useEffect(() => {+ // Only the timeline reads bottom-up; the other tabs put what matters on top.+ if (tab !== "timeline") return;+ const node = scrollRef.current;+ if (!node) return;+ // Following unconditionally yanks the panel to the bottom on every refetch while someone+ // is reading further up, so follow only for a reader already at the end.+ const atBottom =+ node.scrollHeight - node.scrollTop - node.clientHeight <=+ AT_BOTTOM_SLACK_PX;+ if (atBottom) {+ node.scrollTo({ top: node.scrollHeight });+ setHasNewerBelow(false);+ return;+ }+ setHasNewerBelow(true);+ }, [timeline, events.length, agentStatus?.phase, tab]);++ const body = () => {+ if (tab === "comments") {+ return <TaskCommentsList task={task} timeline={timeline} />;+ }+ if (tab === "artifacts") {+ return (+ <TaskArtifactsList+ task={task}+ timeline={timeline}+ canOpenInPlace={canOpenInPlace}+ />+ );+ }+ if (!timelineReady) return <ActivityLoadingState />;+ return (+ <ActivityTimeline+ task={task}+ timeline={timeline}+ messages={messages}+ conversationItems={conversationItems}+ currentUserId={currentUser?.id}+ canOpenInPlace={canOpenInPlace}+ />+ );+ };++ return (+ <>+ <div className="relative flex min-h-0 flex-1 flex-col">+ <div+ ref={scrollRef}+ onScroll={onScroll}+ aria-busy={!timelineReady}+ className="flex-1 overflow-y-auto"+ >+ {body()}+ </div>+ {tab === "timeline" && hasNewerBelow && (+ <Button+ variant="default"+ size="sm"+ className="-translate-x-1/2 absolute bottom-2 left-1/2 z-20 shadow-md"+ onClick={scrollToLatest}+ >+ <ArrowDownIcon size={12} />+ New activity+ </Button>+ )}+ </div>++ {tab === "timeline" && agentStatus && (+ <AgentStatusLine status={agentStatus} />+ )}+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsxindex c34c76bed08e..9941cab26aff 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsx@@ -53,6 +53,12 @@ interface ChannelBreadcrumbProps {onRename?: (next: string) => void;/** Right-aligned slot pushed to the far end of the bar (e.g. an opener). */trailing?: ReactNode;+ /**+ * Slot that rides directly after the leaf segment instead of the far end —+ * for controls that act on the leaf itself (copy its link), which read as+ * unrelated once the bar's width separates them from the name.+ */+ leafTrailing?: ReactNode;}// "# channel / leaf" header breadcrumb shared across channel scenes (CONTEXT.md,@@ -69,6 +75,7 @@ export function ChannelBreadcrumb({editScopeKey,onRename,trailing,+ leafTrailing,}: ChannelBreadcrumbProps) {const spacesLayout = useChannelsLayout();// Only a leaf is renamable, so the scope key falls back to its label.@@ -162,6 +169,9 @@ export function ChannelBreadcrumb({) : (<BreadcrumbSegment icon={leafIcon} label={leafLabel} muted />)}+ {leafTrailing && (+ <span className="flex shrink-0 items-center">{leafTrailing}</span>+ )}</>)}</Flex>diff --git a/products/desktop/packages/ui/src/features/canvas/components/CopyThreadLinkButton.tsx b/products/desktop/packages/ui/src/features/canvas/components/CopyThreadLinkButton.tsxindex 625875432486..7fa5bd33c261 100644--- a/products/desktop/packages/ui/src/features/canvas/components/CopyThreadLinkButton.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/CopyThreadLinkButton.tsx@@ -21,7 +21,6 @@ export function CopyThreadLinkButton({<TooltipTriggerrender={<Button- variant="outline"size="icon-sm"aria-label="Copy link to thread"className="no-drag"diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.test.tsxindex b5d1165546cb..e81e41b8cbfe 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.test.tsx@@ -23,8 +23,10 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({isLoading: false,}),}));+// The dock only exists off the chrome, so the layout is per-test state.+const layout = vi.hoisted(() => ({ channels: false }));vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({- useChannelsLayout: () => true,+ useChannelsLayout: () => layout.channels,}));vi.mock("@posthog/ui/features/canvas/hooks/useTaskChannels", () => ({PERSONAL_CHANNEL_NAME: "me",@@ -83,6 +85,7 @@ import { WebsiteChannelHome } from "./WebsiteChannelHome";describe("WebsiteChannelHome", () => {beforeEach(() => {+ layout.channels = false;useThreadPanelStore.setState({openByChannel: {},collapsed: false,@@ -103,18 +106,25 @@ describe("WebsiteChannelHome", () => {expect(useThreadPanelStore.getState().openByChannel["chan-1"]).toBeNull();});- it("shows the task sidebar for a thread opened from this feed", () => {- render(- <Theme>- <WebsiteChannelHome channelId="chan-1" />- </Theme>,- );+ it.each([+ { channels: false, docked: true },+ { channels: true, docked: false },+ ])(+ "thread opened from this feed docks=$docked when channels layout is $channels",+ ({ channels, docked }) => {+ layout.channels = channels;+ render(+ <Theme>+ <WebsiteChannelHome channelId="chan-1" />+ </Theme>,+ );- act(() => {- useThreadPanelStore.getState().openThread("chan-1", "task-1");- });+ act(() => {+ useThreadPanelStore.getState().openThread("chan-1", "task-1");+ });- expect(screen.getByTestId("task-sidebar")).toBeTruthy();- expect(screen.queryByTestId("feed")).toBeTruthy();- });+ expect(Boolean(screen.queryByTestId("task-sidebar"))).toBe(docked);+ expect(screen.queryByTestId("feed")).toBeTruthy();+ },+ );});diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsxindex f52c8e478368..e31edb2f58a9 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx@@ -202,9 +202,12 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {[handleOpenFull],);+ // Under the spaces chrome there is no thread dock to peek into, so the feed+ // opens the session itself and the right panel carries what the dock used to.const handleOpenThread = useCallback(- (task: Task) => openThread(channelId, task.id),- [channelId, openThread],+ (task: Task) =>+ spacesLayout ? handleOpenFull(task.id) : openThread(channelId, task.id),+ [channelId, openThread, spacesLayout, handleOpenFull],);const threadTask = threadTaskId@@ -306,15 +309,17 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {</div></div>- {threadTaskId && threadTaskId !== inheritedThreadTaskId && (- <ThreadSidebar- taskId={threadTaskId}- channelId={channelId}- task={threadTask}- onClose={() => closeThread(channelId)}- onOpenFull={() => handleOpenFull(threadTaskId)}- />- )}+ {!spacesLayout &&+ threadTaskId &&+ threadTaskId !== inheritedThreadTaskId && (+ <ThreadSidebar+ taskId={threadTaskId}+ channelId={channelId}+ task={threadTask}+ onClose={() => closeThread(channelId)}+ onOpenFull={() => handleOpenFull(threadTaskId)}+ />+ )}{channelName && (<CreateChannelModaldiff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsxindex e88b16f0ee2a..e34c366e8425 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx@@ -46,6 +46,14 @@ import {useIsDashboardEditing,} from "@posthog/ui/features/canvas/stores/dashboardEditStore";import { copyCanvasLink } from "@posthog/ui/features/canvas/utils/copyCanvasLink";+import {+ RightPanel,+ SWITCHER_WIDTH_PX,+} from "@posthog/ui/features/navigation/components/RightPanel";+import {+ CONTENT_CHROME_RIGHT_VAR,+ useRightPanelOpen,+} from "@posthog/ui/features/navigation/rightPanelSide";import { buildCommentThreads } from "@posthog/ui/features/sessions/components/commentViewTypes";import { useCommentsQuery } from "@posthog/ui/features/sessions/components/useComments";import {@@ -57,7 +65,7 @@ import { useTasks } from "@posthog/ui/features/tasks/useTasks";import { toast } from "@posthog/ui/primitives/toast";import { track } from "@posthog/ui/shell/analytics";import { useHeaderStore } from "@posthog/ui/shell/headerStore";-import { Box, Flex } from "@radix-ui/themes";+import { Flex } from "@radix-ui/themes";import { useIsMutating, useQueryClient } from "@tanstack/react-query";import {Outlet,@@ -65,7 +73,7 @@ import {useParams,useRouterState,} from "@tanstack/react-router";-import { type ReactNode, useState } from "react";+import { type CSSProperties, type ReactNode, useState } from "react";// Edit toggle + autosave status for a canvas. Source is server-versioned now —// version browsing and revert live in the canvas view's own toolbar — so the@@ -359,6 +367,7 @@ export function WebsiteLayout() {const channelId = params.channelId;const dashboardId = params.dashboardId;const taskId = params.taskId;+ const rightPanelOpen = useRightPanelOpen(taskId);const base = channelId ? `/website/${channelId}` : "/website";const { data: tasks } = useTasks();@@ -396,32 +405,26 @@ export function WebsiteLayout() {{/* Title bar for non-canvas views: every channel scene (task detail,new task, CONTEXT.md) pushes its "# channel / leaf" breadcrumb intothe header store, as do channel-less mirrored pages (Home, Skills, …).- Hidden when the canvas toolbar is showing (grid / a single canvas). */}- {!showToolbar && headerContent && (- <Flex- align="center"- gap="2"- className="h-10 shrink-0 border-gray-6 border-b px-3"- >- <Flex- align="center"- justify="between"- className="h-full min-w-0 flex-1 overflow-hidden"- >+ Hidden when the canvas toolbar is showing (grid / a single canvas),+ and skipped entirely when there is neither a title nor a session's+ actions to carry. */}+ {!showToolbar && (headerContent || channelTask) && (+ <div className="flex h-10 shrink-0 items-center gap-2 border-gray-6 border-b px-3">+ <div className="flex h-full min-w-0 flex-1 items-center justify-between overflow-hidden">{headerContent}- </Flex>+ </div>+ {/* Rendered without a wrapper: the actions cap themselves at half the+ bar, and a wrapper that hugs their content resolves that+ percentage against itself, which clips them. */}{channelTask && <TaskHeaderActions task={channelTask} />}- </Flex>+ </div>)}{/* Single canvas toolbar: the "# channel / canvas" breadcrumb (left) andcanvas actions (Edit / New canvas) on the right.Freeform canvases own their own date control in-app (DateTimePicker). */}{showToolbar && channelId && (- <Flex- align="center"- className="h-10 shrink-0 border-border border-b px-3"- >+ <div className="flex h-10 shrink-0 items-center border-border border-b px-3">{isDashboardDetail && dashboardId ? (<CanvasBreadcrumbchannelName={channelName}@@ -442,13 +445,34 @@ export function WebsiteLayout() {trailing={<NewCanvasMenu channelId={channelId} />}/>)}- </Flex>+ </div>)}- <Box flexGrow="1" overflow="hidden">- <MentionAvailabilityProvider disabledReason={mentionsDisabledReason}>- <Outlet />- </MentionAvailabilityProvider>- </Box>+ {/* The right panel's switcher pins itself to this row's top right, so the+ row is its positioning context. `isolate` keeps the switcher's stacking+ rank inside the row, where it only has to beat the panel's own layer,+ rather than reaching the app's dialogs and popovers. While the panel is+ closed the switcher floats over the content pane, so the row publishes+ how much of its right edge is spoken for and the pane's own chrome+ stops short of it. */}+ <div+ className="relative isolate flex min-h-0 flex-1 overflow-hidden"+ style={+ {+ [CONTENT_CHROME_RIGHT_VAR]: rightPanelOpen+ ? "0px"+ : `${SWITCHER_WIDTH_PX}px`,+ } as CSSProperties+ }+ >+ <div className="min-w-0 flex-1 overflow-hidden">+ <MentionAvailabilityProvider disabledReason={mentionsDisabledReason}>+ <Outlet />+ </MentionAvailabilityProvider>+ </div>+ {/* One panel at a time beside the content: the session's timeline,+ artifacts, comments, or changes, as a push column. */}+ {spacesLayout && <RightPanel />}+ </div>{/* Warm-iframe pool for canvases. Mounted once here so it persists acrossevery in-space navigation; overlays itself onto the active canvas'splaceholder and stays warm-but-hidden otherwise. */}diff --git a/products/desktop/packages/ui/src/features/code-review/components/ReviewToolbar.tsx b/products/desktop/packages/ui/src/features/code-review/components/ReviewToolbar.tsxindex de37aac1b9dd..f6a9a8023b71 100644--- a/products/desktop/packages/ui/src/features/code-review/components/ReviewToolbar.tsx+++ b/products/desktop/packages/ui/src/features/code-review/components/ReviewToolbar.tsx@@ -12,6 +12,7 @@ import {type ReviewMode,useReviewNavigationStore,} from "@posthog/ui/features/code-review/reviewNavigationStore";+import { useReviewInRightPanel } from "@posthog/ui/features/navigation/useReviewInRightPanel";import { Tooltip } from "@posthog/ui/primitives/Tooltip";import { Flex, Separator, Text } from "@radix-ui/themes";import { FoldVertical, Maximize, Minimize, UnfoldVertical } from "lucide-react";@@ -114,6 +115,11 @@ export const ReviewToolbar = memo(function ReviewToolbar({setReviewMode(taskId, "closed");};+ // The panel's own switcher opens and closes the review there, and its column+ // has one width, which the expanded mode has no way to take. Both controls+ // would sit dead in the panel, so they stay with the Code scene.+ const inRightPanel = useReviewInRightPanel();+const visibleFileSummary = getVisibleFileSummary(commentFilter,fileCount,@@ -136,7 +142,7 @@ export const ReviewToolbar = memo(function ReviewToolbar({style={{zIndex: 2,}}- className="sticky top-0 h-[32px] shrink-0 border-b border-b-(--gray-6) bg-(--color-background)"+ className="sticky top-0 h-[32px] shrink-0 border-b border-b-(--gray-6) bg-(--color-background) ps-3"><Flex align="center" gap="2"><Text className="font-medium text-[13px]">{fileCountLabel}</Text>@@ -201,24 +207,26 @@ export const ReviewToolbar = memo(function ReviewToolbar({</Button></Tooltip>- <Tooltip- content={- reviewMode === "expanded" ? "Collapse review" : "Expand review"- }- >- <Button- size="icon-sm"- onClick={handleToggleExpand}- aria-selected={reviewMode === "expanded"}- className="rounded-xs"+ {!inRightPanel && (+ <Tooltip+ content={+ reviewMode === "expanded" ? "Collapse review" : "Expand review"+ }>- {reviewMode === "expanded" ? (- <Minimize size={12} />- ) : (- <Maximize size={12} />- )}- </Button>- </Tooltip>+ <Button+ size="icon-sm"+ onClick={handleToggleExpand}+ aria-selected={reviewMode === "expanded"}+ className="rounded-xs"+ >+ {reviewMode === "expanded" ? (+ <Minimize size={12} />+ ) : (+ <Maximize size={12} />+ )}+ </Button>+ </Tooltip>+ )}<Separator orientation="vertical" size="1" />@@ -231,11 +239,13 @@ export const ReviewToolbar = memo(function ReviewToolbar({onHideViewedFilesChange={onHideViewedFilesChange}/>- <Tooltip content="Close review">- <Button size="icon-sm" onClick={handleClose} className="rounded-xs">- <X size={14} />- </Button>- </Tooltip>+ {!inRightPanel && (+ <Tooltip content="Close review">+ <Button size="icon-sm" onClick={handleClose} className="rounded-xs">+ <X size={14} />+ </Button>+ </Tooltip>+ )}</Flex></Flex>);diff --git a/products/desktop/packages/ui/src/features/navigation/components/RightPanel.tsx b/products/desktop/packages/ui/src/features/navigation/components/RightPanel.tsxnew file mode 100644index 000000000000..2f9276aef097--- /dev/null+++ b/products/desktop/packages/ui/src/features/navigation/components/RightPanel.tsx@@ -0,0 +1,273 @@+import {+ ChatCircleIcon,+ GitDiffIcon,+ type Icon,+ PackageIcon,+ PulseIcon,+} from "@phosphor-icons/react";+import {+ Button,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@posthog/quill";+import type { Task } from "@posthog/shared/domain-types";+import { ActivityPanelBody } from "@posthog/ui/features/canvas/components/ActivityPanelBody";+import {+ LazyCloudReviewPage as CloudReviewPage,+ LazyReviewPage as ReviewPage,+} from "@posthog/ui/features/code-review/components/LazyReviewPages";+import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";+import { openRightPanelSide } from "@posthog/ui/features/navigation/rightPanelSide";+import { useCommentFocusRequest } from "@posthog/ui/features/sessions/useCommentFocusRequest";+import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";+import { useTasks } from "@posthog/ui/features/tasks/useTasks";+import { useIsCloudTask } from "@posthog/ui/features/workspace/useWorkspace";+import {+ ResizableSidebar,+ SLIDE_MS,+} from "@posthog/ui/primitives/ResizableSidebar";+import { useQuery } from "@tanstack/react-query";+import { useParams } from "@tanstack/react-router";+import { useCallback, useEffect, useState } from "react";+import {+ DEFAULT_RIGHT_PANEL_SIDE,+ RIGHT_PANEL_MIN_WIDTH,+ type RightPanelSide,+ resolveRightPanelSide,+ useRightPanelStore,+} from "../rightPanelStore";++const SIDES: Record<RightPanelSide, { label: string; Icon: Icon }> = {+ timeline: { label: "Timeline", Icon: PulseIcon },+ artifacts: { label: "Artifacts", Icon: PackageIcon },+ comments: { label: "Comments", Icon: ChatCircleIcon },+ changes: { label: "Changes", Icon: GitDiffIcon },+};++const SIDE_ORDER: readonly RightPanelSide[] = [+ "timeline",+ "artifacts",+ "comments",+ "changes",+];++/**+ * The room the switcher takes at the right of the row, covering SIDE_ORDER at+ * icon-sm. The panel's header row leaves it free for the title, and while the+ * panel is closed the content pane's own chrome (the tab strip and its split+ * and close controls) keeps out of it through CONTENT_CHROME_RIGHT_VAR.+ */+export const SWITCHER_WIDTH_PX = 112;++/** The task the right panel talks about: the one on the current route. */+function useRightPanelTask(taskId: string): Task | null {+ const { data: tasks } = useTasks();+ const fromList = tasks?.find((t) => t.id === taskId);+ // A session reached by deep link can be open before the list carries it.+ const { data: fetched } = useQuery({+ ...taskDetailQuery(taskId),+ enabled: !fromList,+ });+ return fromList ?? fetched ?? null;+}++/** Which panel this session has open. */+function useActiveSide(taskId: string): RightPanelSide | null {+ const stored = useRightPanelStore((s) => s.sideByKey[taskId]);+ const reviewMode = useReviewNavigationStore(+ (s) => s.reviewModes[taskId] ?? "closed",+ );+ return resolveRightPanelSide({+ stored,+ isReviewOpen: reviewMode !== "closed",+ });+}++/**+ * The panel's own switcher: one button per side, the active one toggling the+ * panel closed. It sits a row below the header band, pinned to the right edge,+ * and stays there whether the panel is open or closed, because the panel slides+ * out from under it.+ */+function RightPanelButtons({+ active,+ taskId,+}: {+ active: RightPanelSide | null;+ taskId: string;+}) {+ return (+ <TooltipProvider delay={400}>+ <div className="pointer-events-auto flex shrink-0 items-center gap-0.5">+ {SIDE_ORDER.map((side) => {+ const { label, Icon } = SIDES[side];+ return (+ <Tooltip key={side}>+ <TooltipTrigger+ render={+ <Button+ variant="default"+ size="icon-sm"+ aria-label={label}+ data-selected={active === side || undefined}+ onClick={() =>+ openRightPanelSide(active === side ? null : side, taskId)+ }+ className="text-muted-foreground data-selected:bg-fill-selected data-selected:text-foreground"+ >+ <Icon size={16} />+ </Button>+ }+ />+ <TooltipContent side="bottom">{label}</TooltipContent>+ </Tooltip>+ );+ })}+ </div>+ </TooltipProvider>+ );+}++function ChangesPanelContent({ task }: { task: Task }) {+ return useIsCloudTask(task) ? (+ <CloudReviewPage task={task} />+ ) : (+ <ReviewPage task={task} />+ );+}++/**+ * The panel's title and contents fade with its slide, so the two read as one+ * movement: in over the slide's own duration, out quicker, so the panel is+ * already gone as the column finishes closing.+ */+const PANEL_FADE_OUT_MS = 120;++/**+ * The side to draw, which outlasts the one that is open: a closing panel has to+ * keep its title and contents on screen to fade them out, then drop them. A+ * drag that is still held keeps them, since dragging back out brings the same+ * panel in and rebuilding it mid-drag would stutter.+ */+function useFadingSide(+ active: RightPanelSide | null,+ held: boolean,+): RightPanelSide | null {+ const [drawn, setDrawn] = useState(active);+ useEffect(() => {+ if (active != null) {+ setDrawn(active);+ return;+ }+ if (held) return;+ const timer = setTimeout(() => setDrawn(null), PANEL_FADE_OUT_MS);+ return () => clearTimeout(timer);+ }, [active, held]);+ return drawn;+}++/**+ * Every side the panel shows belongs to a session, so the column keeps to a+ * session's own page and nothing below this runs anywhere else.+ */+export function RightPanel() {+ const taskId = useParams({ strict: false }).taskId;+ // Keyed by session: the panel holds per-session state (which side is drawn,+ // which comment request it has taken), and carrying that across a navigation+ // draws the previous session's panel over the new one for a frame.+ return taskId ? <SessionRightPanel key={taskId} taskId={taskId} /> : null;+}++/**+ * The right panel column: a push column beside the content, one panel at a+ * time, shared resizable width. Its switcher is pinned to the top right of the+ * column and outlives any one panel, so the panel opens and closes beneath a+ * row of buttons that never move.+ */+function SessionRightPanel({ taskId }: { taskId: string }) {+ const task = useRightPanelTask(taskId);+ const active = useActiveSide(taskId);+ useCommentFocusRequest(taskId, () => openRightPanelSide("comments", taskId));++ const width = useRightPanelStore((s) => s.width);+ const setWidth = useRightPanelStore((s) => s.setWidth);+ const isResizing = useRightPanelStore((s) => s.isResizing);+ const setIsResizing = useRightPanelStore((s) => s.setIsResizing);++ const open = active != null;+ const drawn = useFadingSide(active, isResizing);++ // Dragging the handle past the panel's floor closes it, and dragging back out+ // while still holding brings it in again. The drag holds the closing panel's+ // contents, so `drawn` is the side to put back; the fallback only stands in+ // for a reopen that starts from no panel at all.+ const setOpen = useCallback(+ (next: boolean) =>+ openRightPanelSide(+ next ? (drawn ?? DEFAULT_RIGHT_PANEL_SIDE) : null,+ taskId,+ ),+ [drawn, taskId],+ );++ return (+ <>+ <ResizableSidebar+ open={open}+ width={width}+ setWidth={setWidth}+ isResizing={isResizing}+ setIsResizing={setIsResizing}+ side="right"+ minWidth={RIGHT_PANEL_MIN_WIDTH}+ setOpen={setOpen}+ >+ <div+ className="flex h-full min-h-0 flex-col bg-background transition-opacity ease-out motion-reduce:transition-none"+ style={{+ opacity: open ? 1 : 0,+ transitionDuration: open+ ? `${SLIDE_MS}ms`+ : `${PANEL_FADE_OUT_MS}ms`,+ }}+ >+ {drawn && (+ <>+ <div+ className="flex h-[32px] shrink-0 items-center border-border border-b pl-3"+ style={{ paddingRight: SWITCHER_WIDTH_PX }}+ >+ <span className="min-w-0 truncate font-medium text-[13px]">+ {SIDES[drawn].label}+ </span>+ </div>+ {/* Nothing under the title until the session resolves, because+ the route says there is a session and an empty state would+ contradict it. */}+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden">+ {task &&+ (drawn === "changes" ? (+ <ChangesPanelContent task={task} />+ ) : (+ <ActivityPanelBody task={task} tab={drawn} canOpenInPlace />+ ))}+ </div>+ </>+ )}+ </div>+ </ResizableSidebar>+ {/* Outside the sliding column, so the buttons hold their place while the+ panel comes and goes under them. It has to outrank the panel's closed+ layer, which sweeps across this corner at z-50 on the way out; the+ row's own `isolate` keeps that rank from reaching the app's overlays. */}+ <div+ className="pointer-events-none absolute top-0 right-0 z-60 flex h-[32px] items-center justify-end pr-2"+ style={{ width: SWITCHER_WIDTH_PX }}+ >+ <RightPanelButtons active={active} taskId={taskId} />+ </div>+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/navigation/rightPanelSide.ts b/products/desktop/packages/ui/src/features/navigation/rightPanelSide.tsnew file mode 100644index 000000000000..41b5da1f061f--- /dev/null+++ b/products/desktop/packages/ui/src/features/navigation/rightPanelSide.ts@@ -0,0 +1,63 @@+import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";+import {+ DEFAULT_RIGHT_PANEL_SIDE,+ type RightPanelSide,+ resolveRightPanelSide,+ useRightPanelStore,+} from "@posthog/ui/features/navigation/rightPanelStore";++/**+ * Put a session's right panel on a side, or close it with `null`. Changes rides+ * the review store so the command menu, PR links, and diff toggles that already+ * open review all land on the same panel, and so that picking another panel+ * closes what they opened.+ */+export function openRightPanelSide(+ side: RightPanelSide | null,+ taskId: string,+): void {+ useRightPanelStore.getState().setSideForKey(taskId, side);+ useReviewNavigationStore+ .getState()+ .setReviewMode(taskId, side === "changes" ? "split" : "closed");+}++/** The side a session's panel is showing, outside a React render. */+export function currentRightPanelSide(taskId: string): RightPanelSide | null {+ const reviewMode =+ useReviewNavigationStore.getState().reviewModes[taskId] ?? "closed";+ return resolveRightPanelSide({+ stored: useRightPanelStore.getState().sideByKey[taskId],+ isReviewOpen: reviewMode !== "closed",+ });+}++/** What the keyboard does to the panel: open it, or put it away. */+export function toggleRightPanel(taskId: string): void {+ const open = currentRightPanelSide(taskId) != null;+ openRightPanelSide(open ? null : DEFAULT_RIGHT_PANEL_SIDE, taskId);+}++/**+ * How much of the content row's right edge the panel's switcher is sitting on.+ * Chrome that pins itself to that edge (the panel tree's tab strip and its+ * split and close controls) reads this and stops short, so the switcher can+ * float over the content pane without taking a column of its own or swallowing+ * the clicks meant for what is under it.+ */+export const CONTENT_CHROME_RIGHT_VAR = "--content-chrome-right";++/** Whether this session's panel is open, for chrome that has to make room. */+export function useRightPanelOpen(taskId: string | undefined): boolean {+ const stored = useRightPanelStore((s) =>+ taskId ? s.sideByKey[taskId] : undefined,+ );+ const reviewMode = useReviewNavigationStore((s) =>+ taskId ? (s.reviewModes[taskId] ?? "closed") : "closed",+ );+ if (!taskId) return false;+ return (+ resolveRightPanelSide({ stored, isReviewOpen: reviewMode !== "closed" }) !=+ null+ );+}diff --git a/products/desktop/packages/ui/src/features/navigation/rightPanelStore.test.ts b/products/desktop/packages/ui/src/features/navigation/rightPanelStore.test.tsnew file mode 100644index 000000000000..3a8289cfdffa--- /dev/null+++ b/products/desktop/packages/ui/src/features/navigation/rightPanelStore.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";+import { type RightPanelSide, resolveRightPanelSide } from "./rightPanelStore";++describe("resolveRightPanelSide", () => {+ it.each<{+ name: string;+ stored: RightPanelSide | null | undefined;+ isReviewOpen: boolean;+ expected: RightPanelSide | null;+ }>([+ {+ name: "an untouched session opens on the timeline",+ stored: undefined,+ isReviewOpen: false,+ expected: "timeline",+ },+ {+ name: "a session someone closed the panel on stays closed",+ stored: null,+ isReviewOpen: false,+ expected: null,+ },+ {+ name: "a session keeps the panel it was left on",+ stored: "artifacts",+ isReviewOpen: false,+ expected: "artifacts",+ },+ {+ name: "a review opened from elsewhere shows the changes",+ stored: "comments",+ isReviewOpen: true,+ expected: "changes",+ },+ {+ name: "a review opened on a session someone closed the panel on still shows",+ stored: null,+ isReviewOpen: true,+ expected: "changes",+ },+ {+ name: "a review closed from elsewhere closes the panel it was showing in",+ stored: "changes",+ isReviewOpen: false,+ expected: null,+ },+ ])("$name", ({ stored, isReviewOpen, expected }) => {+ expect(resolveRightPanelSide({ stored, isReviewOpen })).toBe(expected);+ });+});diff --git a/products/desktop/packages/ui/src/features/navigation/rightPanelStore.ts b/products/desktop/packages/ui/src/features/navigation/rightPanelStore.tsnew file mode 100644index 000000000000..e2b028f7a556--- /dev/null+++ b/products/desktop/packages/ui/src/features/navigation/rightPanelStore.ts@@ -0,0 +1,78 @@+import { electronStorage } from "@posthog/ui/shell/rendererStorage";+import { create } from "zustand";+import { persist } from "zustand/middleware";++/**+ * Which panel the right column shows. `changes` is also opened from elsewhere,+ * through reviewNavigationStore.+ */+export type RightPanelSide = "timeline" | "artifacts" | "comments" | "changes";++/** What a session opens on before anyone touches its panel. */+export const DEFAULT_RIGHT_PANEL_SIDE: RightPanelSide = "timeline";++export const RIGHT_PANEL_MIN_WIDTH = 280;+const RIGHT_PANEL_DEFAULT_WIDTH = 340;++interface RightPanelStore {+ width: number;+ isResizing: boolean;+ /**+ * The panel each session (or the sessionless fallback key) has open, so+ * coming back to a session finds it as it was left. `null` is a panel someone+ * closed; a missing entry is a session nobody has touched, which opens on the+ * default. Not persisted, because this is within-run memory.+ */+ sideByKey: Record<string, RightPanelSide | null | undefined>;+ setWidth: (width: number) => void;+ setIsResizing: (isResizing: boolean) => void;+ setSideForKey: (key: string, side: RightPanelSide | null) => void;+}++/**+ * Which panel a session shows, given what it was left on. An open review mode+ * wins, because every existing "open review" entry point (the command menu, PR+ * links, diff toggles) sets it and expects the changes to appear; then an+ * explicit choice, including the `null` of a panel someone closed; then the+ * default, so opening a session lands on its timeline rather than on nothing.+ */+export function resolveRightPanelSide({+ stored,+ isReviewOpen,+}: {+ stored: RightPanelSide | null | undefined;+ isReviewOpen: boolean;+}): RightPanelSide | null {+ if (isReviewOpen) return "changes";+ // The review mode has the last word on Changes in both directions. Whoever+ // closes a review closes it from wherever they are (the footer's diff chip,+ // the review shortcut) without touching the panel's own memory, and a panel+ // that kept showing Changes there would draw its title over a review that+ // has dropped its queries.+ if (stored === "changes") return null;+ if (stored !== undefined) return stored;+ return DEFAULT_RIGHT_PANEL_SIDE;+}++export const useRightPanelStore = create<RightPanelStore>()(+ persist(+ (set) => ({+ width: RIGHT_PANEL_DEFAULT_WIDTH,+ isResizing: false,+ sideByKey: {},+ setWidth: (width) =>+ set({ width: Math.max(RIGHT_PANEL_MIN_WIDTH, width) }),+ setIsResizing: (isResizing) => set({ isResizing }),+ setSideForKey: (key, side) =>+ set((state) => ({ sideByKey: { ...state.sideByKey, [key]: side } })),+ }),+ {+ name: "right-panel",+ // A resize drag calls setWidth per pointer event, and this backend+ // coalesces the burst behind its debounce instead of writing+ // synchronously on each one, the way every other panel store does.+ storage: electronStorage,+ partialize: (state) => ({ width: state.width }),+ },+ ),+);diff --git a/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.ts b/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.tsnew file mode 100644index 000000000000..22770a2258f8--- /dev/null+++ b/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.ts@@ -0,0 +1,13 @@+import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";+import { useParams } from "@tanstack/react-router";++/**+ * Whether a session's review belongs to the shared right panel rather than to+ * the surface asking. Three places turn on this: the panel draws the review,+ * the session's own review pane stands down, and the controls that opened the+ * review from elsewhere come off, because the panel's switcher owns it now.+ */+export function useReviewInRightPanel(): boolean {+ const channelId = useParams({ strict: false }).channelId;+ return useChannelsLayout() && channelId != null;+}diff --git a/products/desktop/packages/ui/src/features/panels/components/TabbedPanel.tsx b/products/desktop/packages/ui/src/features/panels/components/TabbedPanel.tsxindex 3c096ccb88a1..c14595e424a0 100644--- a/products/desktop/packages/ui/src/features/panels/components/TabbedPanel.tsx+++ b/products/desktop/packages/ui/src/features/panels/components/TabbedPanel.tsx@@ -1,6 +1,7 @@import { useDroppable } from "@dnd-kit/react";import { Plus, SquareSplitHorizontalIcon, X } from "@phosphor-icons/react";import { useHostTRPCClient } from "@posthog/host-router/react";+import { CONTENT_CHROME_RIGHT_VAR } from "@posthog/ui/features/navigation/rightPanelSide";import { PanelDropZones } from "@posthog/ui/features/panels/components/PanelDropZones";import type { SplitDirection } from "@posthog/ui/features/panels/panelLayoutStore";import type { PanelContent } from "@posthog/ui/features/panels/panelTypes";@@ -191,6 +192,7 @@ export const TabbedPanel: React.FC<TabbedPanelProps> = ({<Flexref={tabBarRef}className="scrollbar-overlay absolute top-0 right-0 left-0 h-[36px] items-start"+ style={{ right: `var(${CONTENT_CHROME_RIGHT_VAR}, 0px)` }}>{content.tabs.map((tab, index) => (<PanelTab@@ -240,6 +242,7 @@ export const TabbedPanel: React.FC<TabbedPanelProps> = ({<Flexalign="center"className="absolute top-0 right-0 h-[32px] border-b border-b-(--gray-6) border-l border-l-(--gray-6) bg-(--color-background)"+ style={{ right: `var(${CONTENT_CHROME_RIGHT_VAR}, 0px)` }}>{rightContent}{onClosePanel && (diff --git a/products/desktop/packages/ui/src/features/sessions/useCommentFocusRequest.ts b/products/desktop/packages/ui/src/features/sessions/useCommentFocusRequest.tsnew file mode 100644index 000000000000..23b8c8a041f4--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/useCommentFocusRequest.ts@@ -0,0 +1,36 @@+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";+import { useEffect, useRef } from "react";++/**+ * A thread picked on the artifact itself is read in the comments surface, so+ * the pick has to bring that surface with it. The one protocol behind that:+ * whoever can show the comments takes the request, opens, and acknowledges,+ * which is what clears the flag. A request is taken once, by nonce, so a+ * surface that stays mounted across several picks reacts to each of them and+ * to none of them twice.+ *+ * Requests arrive both while the surface is mounted and just before it mounts,+ * because the click that asks for a thread is often the click that navigates+ * into the session. Both are honored: a request that nobody acknowledged is+ * still outstanding, whenever it was written.+ */+export function useCommentFocusRequest(+ taskId: string,+ openComments: () => void,+): void {+ const focus = useCommentNavigationStore((state) => state.focusByTask[taskId]);+ const acknowledge = useCommentNavigationStore(+ (state) => state.acknowledgeCommentsTabOpen,+ );+ const takenNonce = useRef<number | null>(null);+ const openRef = useRef(openComments);+ openRef.current = openComments;++ useEffect(() => {+ if (!focus?.openCommentsTab) return;+ if (focus.nonce === takenNonce.current) return;+ takenNonce.current = focus.nonce;+ openRef.current();+ acknowledge(taskId, focus.nonce);+ }, [acknowledge, focus, taskId]);+}diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsxindex e0bd2cf4c43e..169a2eca7df5 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsx@@ -24,6 +24,8 @@ import { useFileSearchStore } from "../../command/fileSearchStore";import { SHORTCUTS } from "../../command/keyboard-shortcuts";import { useRepoFileWatcher } from "../../file-watcher/useRepoFileWatcher";import { clearGitReviewQueries } from "../../git-interaction/gitCacheKeys";+import { useRightPanelStore } from "../../navigation/rightPanelStore";+import { useReviewInRightPanel } from "../../navigation/useReviewInRightPanel";import { PanelLayout } from "../../panels/components/PanelLayout";import { MIN_CHAT_WIDTH } from "../../sessions/constants";import { useArchivingTasksStore } from "../../sidebar/archivingTasksStore";@@ -212,7 +214,7 @@ export function TaskDetail({leafLabel={task.title}editScopeKey={taskId}onRename={handleTitleEditSubmit}- trailing={trailing}+ leafTrailing={trailing}/>) : (<Flex align="center" justify="between" gap="2" width="100%">@@ -265,13 +267,22 @@ export function TaskDetail({const isCloud =workspace?.mode === "cloud" || task.latest_run?.environment === "cloud";- const isReviewOpen = reviewMode !== "closed";- const isExpanded = reviewMode === "expanded";-+ // Where the shared right panel draws the review, the in-task pane stands+ // down rather than drawing it a second time.+ const inRightPanel = useReviewInRightPanel();+ const isReviewOpen = !inRightPanel && reviewMode !== "closed";+ const isExpanded = !inRightPanel && reviewMode === "expanded";++ // Keyed off the review mode rather than this pane, so a review open in the+ // right panel keeps the diff queries it is drawing from. A drag on that+ // panel's handle passes through "closed" and back within one gesture, so the+ // clear waits for the drag to end rather than emptying the cache under a+ // review that is still on screen.+ const isDraggingRightPanel = useRightPanelStore((s) => s.isResizing);useEffect(() => {- if (isReviewOpen) return;+ if (reviewMode !== "closed" || isDraggingRightPanel) return;clearGitReviewQueries();- }, [isReviewOpen]);+ }, [reviewMode, isDraggingRightPanel]);const containerRef = useRef<HTMLDivElement>(null);const [reviewWidth, setReviewWidth] = useState<number | null>(null);diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsxindex eedaf2b15ca2..2dcb37ea4cfb 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx@@ -81,6 +81,11 @@ vi.mock("@posthog/ui/features/sessions/components/StopCloudRunButton", () => ({vi.mock("@posthog/ui/features/diff-stats/DiffStatsBadge", () => ({DiffStatsBadge: () => null,}));+// Reads the route, which these renders don't provide. The Code scene's answer+// is false, and that is the row this test covers.+vi.mock("@posthog/ui/features/navigation/useReviewInRightPanel", () => ({+ useReviewInRightPanel: () => false,+}));vi.mock("@posthog/ui/primitives/Tooltip", () => ({Tooltip: ({ children }: { children: ReactNode }) => children,}));diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsxindex b34463369d34..88e8a5919f6f 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx@@ -13,6 +13,7 @@ import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlaimport { BranchSelector } from "@posthog/ui/features/git-interaction/components/BranchSelector";import { CloudGitInteractionHeader } from "@posthog/ui/features/git-interaction/components/CloudGitInteractionHeader";import { TaskActionsMenu } from "@posthog/ui/features/git-interaction/components/TaskActionsMenu";+import { useReviewInRightPanel } from "@posthog/ui/features/navigation/useReviewInRightPanel";import { HandoffConfirmDialog } from "@posthog/ui/features/sessions/components/HandoffConfirmDialog";import { StopCloudRunButton } from "@posthog/ui/features/sessions/components/StopCloudRunButton";import { useHandoffDialogStore } from "@posthog/ui/features/sessions/handoffDialogStore";@@ -132,6 +133,9 @@ export function TaskHeaderActions({ task }: { task: Task }) {const workspace = useWorkspace(task.id);const workspaceLoaded = useWorkspaceLoaded();const isCloudTask = useIsCloudTask(task);+ // The badge is this row's way into the review, so it comes off where the+ // right panel's switcher already offers one.+ const showDiffBadge = !useReviewInRightPanel();return (<Flex@@ -154,7 +158,7 @@ export function TaskHeaderActions({ task }: { task: Task }) {/></div>)}- <TaskDiffStatsBadge task={task} />+ {showDiffBadge && <TaskDiffStatsBadge task={task} />}{workspaceLoaded && (<>diff --git a/products/desktop/packages/ui/src/primitives/ResizableSidebar.tsx b/products/desktop/packages/ui/src/primitives/ResizableSidebar.tsxindex 88d257a92f6f..145b08157173 100644--- a/products/desktop/packages/ui/src/primitives/ResizableSidebar.tsx+++ b/products/desktop/packages/ui/src/primitives/ResizableSidebar.tsx@@ -13,9 +13,11 @@ const DRAG_REOPEN_AT = DRAG_COLLAPSE_AT + 16;// Every moving part of the open/close choreography — the box width, the// panel's translateX, and the title bar in __root — must share this exact// curve (Tailwind's ease-out) and duration, or the panel's edge drifts ahead-// of the content edge mid-animation and the layers visibly overlap.+// of the content edge mid-animation and the layers visibly overlap. Anything+// a caller animates alongside the slide takes SLIDE_MS.+export const SLIDE_MS = 200;const SLIDE_EASING = "cubic-bezier(0, 0, 0.2, 1)";-const SLIDE_WIDTH_TRANSITION = `width 0.2s ${SLIDE_EASING}, min-width 0.2s ${SLIDE_EASING}, max-width 0.2s ${SLIDE_EASING}`;+const SLIDE_WIDTH_TRANSITION = `width ${SLIDE_MS}ms ${SLIDE_EASING}, min-width ${SLIDE_MS}ms ${SLIDE_EASING}, max-width ${SLIDE_MS}ms ${SLIDE_EASING}`;interface ResizableSidebarProps {children: React.ReactNode;@@ -28,6 +30,10 @@ interface ResizableSidebarProps {// Floor for drag-resize. Defaults to SIDEBAR_MIN_WIDTH; callers whose chrome// needs more room can raise it.minWidth?: number;+ // What the column keeps while closed. Zero collapses it away, which is what+ // a sidebar wants; a caller that pins chrome over this column gives that+ // chrome's width, so the content pane never reaches under it.+ collapsedWidth?: number;// Enables drag-to-close/reopen. Without it, dragging just clamps at min.setOpen?: (open: boolean) => void;// While closed, the panel can "peek" — slide out over the content as a@@ -49,6 +55,7 @@ export const ResizableSidebar: React.FC<ResizableSidebarProps> = ({setIsResizing,side,minWidth = SIDEBAR_MIN_WIDTH,+ collapsedWidth = 0,setOpen,peek = false,onPeekEnter,@@ -67,12 +74,26 @@ export const ResizableSidebar: React.FC<ResizableSidebarProps> = ({// re-registers the listeners with the post-close open/peek values, so the// closure state can't be trusted for the width restore.const dragEndedClosedRef = React.useRef(false);+ // The panel's anchored edge in window coordinates — its left for a left-hand+ // panel, its right for a right-hand one. Width is the pointer's distance from+ // it, so a panel that doesn't start at the window edge still tracks the+ // cursor. Captured on mousedown: resizing moves the far edge, never this one.+ const boxRef = React.useRef<HTMLDivElement | null>(null);+ const anchorRef = React.useRef(0);const handleMouseDown = (e: React.MouseEvent) => {e.preventDefault();dragOriginRef.current = open ? "docked" : "overlay";dragStartWidthRef.current = width;dragEndedClosedRef.current = false;+ const rect = boxRef.current?.getBoundingClientRect();+ anchorRef.current = rect+ ? side === "left"+ ? rect.left+ : rect.right+ : side === "left"+ ? 0+ : window.innerWidth;setIsResizing(true);document.body.style.cursor = "col-resize";document.body.style.userSelect = "none";@@ -101,9 +122,12 @@ export const ResizableSidebar: React.FC<ResizableSidebarProps> = ({const handleMouseMove = (e: MouseEvent) => {if (!isResizing) return;- // Distance from the sidebar's window edge, regardless of side.+ // Distance from the panel's own anchored edge, regardless of side, which+ // is the width the pointer is asking for.const pointer =- side === "left" ? e.clientX : window.innerWidth - e.clientX;+ side === "left"+ ? e.clientX - anchorRef.current+ : anchorRef.current - e.clientX;const maxWidth = window.innerWidth * 0.5;const clamped = Math.max(minWidth, Math.min(maxWidth, pointer));@@ -153,7 +177,9 @@ export const ResizableSidebar: React.FC<ResizableSidebarProps> = ({}if (!open && peek) {const pointer =- side === "left" ? e.clientX : window.innerWidth - e.clientX;+ side === "left"+ ? e.clientX - anchorRef.current+ : anchorRef.current - e.clientX;if (pointer > width + PEEK_CLOSE_MARGIN) onPeekLeave?.();}};@@ -183,7 +209,9 @@ export const ResizableSidebar: React.FC<ResizableSidebarProps> = ({const isLeft = side === "left";// Closed = overlay mode: the box collapses to 0 width but the panel stays// mounted as an absolutely positioned layer that peek slides in and out.- const isOverlay = !open;+ // A column that keeps a width while closed stays docked: there is no edge to+ // peek out from, and its caller draws in the space it holds.+ const isOverlay = !open && collapsedWidth === 0;const overlayVisible = isOverlay && peek;// While the panel slides, the resize handle sweeps under a stationary@@ -213,10 +241,11 @@ export const ResizableSidebar: React.FC<ResizableSidebarProps> = ({return (<Box+ ref={boxRef}style={{- width: open ? `${width}px` : "0",- minWidth: open ? `${width}px` : "0",- maxWidth: open ? `${width}px` : "0",+ width: open ? `${width}px` : `${collapsedWidth}px`,+ minWidth: open ? `${width}px` : `${collapsedWidth}px`,+ maxWidth: open ? `${width}px` : `${collapsedWidth}px`,// Suppress only while dragging the docked sidebar so it tracks the// pointer frame-for-frame; a drag-to-close (open flips false mid-drag)// re-enables it so the collapse animates instead of jump-cutting.diff --git a/products/desktop/packages/ui/src/router/routes/website/$channelId/tasks/$taskId.tsx b/products/desktop/packages/ui/src/router/routes/website/$channelId/tasks/$taskId.tsxindex b3c8bfb1740c..80a102b4c5eb 100644--- a/products/desktop/packages/ui/src/router/routes/website/$channelId/tasks/$taskId.tsx+++ b/products/desktop/packages/ui/src/router/routes/website/$channelId/tasks/$taskId.tsx@@ -114,13 +114,17 @@ function ChannelTaskDetailRoute() {channelId={channelId}/></div>- <ThreadSidebar- taskId={taskId}- channelId={channelId}- task={task}- showTaskSummary={false}- canOpenInPlace- />+ {/* The chrome's right panel carries the timeline, artifacts and comments+ now, so the session's own dock only serves the legacy Code layout. */}+ {!spacesLayout && (+ <ThreadSidebar+ taskId={taskId}+ channelId={channelId}+ task={task}+ showTaskSummary={false}+ canOpenInPlace+ />+ )}</div>);}diff --git a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsxindex f7f25b81d582..5d8cb5dffe0e 100644--- a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx+++ b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx@@ -15,6 +15,7 @@ import { useReviewNavigationStore } from "@posthog/ui/features/code-review/revieimport { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useFolders } from "@posthog/ui/features/folders/useFolders";+import { toggleRightPanel } from "@posthog/ui/features/navigation/rightPanelSide";import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";@@ -204,7 +205,18 @@ export function GlobalEventHandlers({);useHotkeys(SHORTCUTS.TOGGLE_LEFT_SIDEBAR, toggleLeftSidebar, globalOptions);useHotkeys(SHORTCUTS.TOGGLE_REVIEW_PANEL, handleToggleReview, globalOptions);- useHotkeys(SHORTCUTS.TOGGLE_ACTIVITY_PANEL, toggleActivityPanel, {+ // Under the spaces chrome a session's activity is the right panel, and the+ // dock this shortcut used to collapse is not rendered, so it goes to the+ // panel instead. Off that chrome, only the dock exists.+ const handleToggleActivityPanel = useCallback(() => {+ if (channelsLayout && currentTaskId) {+ toggleRightPanel(currentTaskId);+ return;+ }+ toggleActivityPanel();+ }, [channelsLayout, currentTaskId]);++ useHotkeys(SHORTCUTS.TOGGLE_ACTIVITY_PANEL, handleToggleActivityPanel, {...globalOptions,enabled: channelsLayout,});