: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): split model switch and session summary (#96034)
Shy Alter9811d194f82e
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 08c3599023ca..bfe707d1b268 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -415,10 +415,22 @@ export interface ModelSwitchWarningShownProperties {export interface ModelSwitchWarningActionPropertiesextends ModelSwitchWarningShownProperties {- action: "cancel" | "copy_handoff_summary" | "switch_now";+ action: "cancel" | "switch_now";result?: "failed" | "succeeded";}+export interface SessionSummaryRequestedProperties {+ task_id: string;+ source: "retry" | "task_menu";+}++export interface SessionSummaryActionProperties {+ task_id: string;+ action: "copied" | "dismissed" | "stopped_waiting";+ /** How long the summary had been running when the action happened. */+ wait_ms: number;+}+// Tour eventstype TourAction = "started" | "step_advanced" | "dismissed" | "completed";@@ -1571,6 +1583,8 @@ export const ANALYTICS_EVENTS = {SESSION_CONFIG_CHANGED: "Session config changed",MODEL_SWITCH_WARNING_SHOWN: "Model switch warning shown",MODEL_SWITCH_WARNING_ACTION: "Model switch warning action",+ SESSION_SUMMARY_REQUESTED: "Session summary requested",+ SESSION_SUMMARY_ACTION: "Session summary action",// Settings eventsSETTING_CHANGED: "Setting changed",@@ -1779,6 +1793,8 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.SESSION_CONFIG_CHANGED]: SessionConfigChangedProperties;[ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_SHOWN]: ModelSwitchWarningShownProperties;[ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION]: ModelSwitchWarningActionProperties;+ [ANALYTICS_EVENTS.SESSION_SUMMARY_REQUESTED]: SessionSummaryRequestedProperties;+ [ANALYTICS_EVENTS.SESSION_SUMMARY_ACTION]: SessionSummaryActionProperties;// Settings events[ANALYTICS_EVENTS.SETTING_CHANGED]: SettingChangedProperties;diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsxindex 16824deb90d4..f51250597575 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx@@ -10,9 +10,7 @@ const meta: Meta<typeof ModelSwitchCacheDialog> = {toModelId: "claude-haiku-4-5",toModelLabel: "Claude Haiku 4.5",contextTokens: 84_000,- sessionCostUsd: 1.42,onConfirm: async () => {},- onCopyHandoffSummary: async () => {},onCancel: () => {},},};@@ -38,10 +36,8 @@ export const UnknownPricing: Story = {},};-export const SwitchOnly: Story = {+export const WithoutCostEstimate: Story = {args: {contextTokens: undefined,- sessionCostUsd: undefined,- onCopyHandoffSummary: undefined,},};diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsxindex b9593c81f734..1729b7362c5e 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsx@@ -3,46 +3,9 @@ import { fireEvent, render, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { ModelSwitchCacheDialog } from "./ModelSwitchCacheDialog";-const taskUsageState = vi.hoisted(() => ({- data: undefined as- | {- token_cost_usd: number;- compute_cost_usd: number;- total_cost_usd: number;- }- | undefined,-}));-vi.mock("@posthog/ui/features/sessions/hooks/useTaskUsage", () => ({- useTaskUsage: () => taskUsageState,-}));-describe("ModelSwitchCacheDialog", () => {beforeEach(() => {useSettingsStore.setState({ warnOnMidSessionModelSwitch: true });- taskUsageState.data = undefined;- });-- it("shows the same task cost used by the context indicator", () => {- taskUsageState.data = {- token_cost_usd: 12.5,- compute_cost_usd: 0.4,- total_cost_usd: 12.9,- };-- render(- <ModelSwitchCacheDialog- open- fromModelLabel="Claude Sonnet 5"- toModelId="claude-opus-5"- toModelLabel="Claude Opus 5"- taskId="task-1"- onConfirm={vi.fn().mockResolvedValue(true)}- onCancel={vi.fn()}- />,- );-- expect(screen.getByText("Estimated task cost so far")).toBeInTheDocument();- expect(screen.getByText("$12.90")).toBeInTheDocument();});it("keeps future warnings enabled when the user selects do not show again and cancels", () => {@@ -58,7 +21,7 @@ describe("ModelSwitchCacheDialog", () => {/>,);- fireEvent.click(screen.getByText("Do not show this ever again"));+ fireEvent.click(screen.getByText("Do not show this again"));fireEvent.click(screen.getByText("Cancel"));expect(onCancel).toHaveBeenCalledOnce();@@ -77,7 +40,7 @@ describe("ModelSwitchCacheDialog", () => {};const { rerender } = render(<ModelSwitchCacheDialog open {...props} />);- fireEvent.click(screen.getByText("Switch now"));+ fireEvent.click(screen.getByText("Switch model"));rerender(<ModelSwitchCacheDialog open={false} {...props} />);rerender(<ModelSwitchCacheDialog open {...props} />);diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsxindex fa2eccc831ad..0f0c97e8c047 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx@@ -9,11 +9,11 @@ import {AlertDialogTitle,Button,Checkbox,+ DialogBody,Label,Text,} from "@posthog/quill";import { formatCostUsd } from "@posthog/ui/features/sessions/contextColors";-import { useTaskUsage } from "@posthog/ui/features/sessions/hooks/useTaskUsage";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { type ReactElement, useEffect, useId, useRef, useState } from "react";@@ -22,15 +22,11 @@ interface ModelSwitchCacheDialogProps {fromModelLabel: string;toModelId: string;toModelLabel: string;- taskId?: string;contextTokens?: number;onConfirm: () => Promise<boolean>;- onCopyHandoffSummary?: () => Promise<void>;onCancel: () => void;}-type ActiveAction = "copy_summary" | "switch" | null;-export function ModelSwitchCacheDialog({open,...props@@ -45,18 +41,15 @@ function OpenModelSwitchCacheDialog({fromModelLabel,toModelId,toModelLabel,- taskId,contextTokens = 0,onConfirm,- onCopyHandoffSummary,onCancel,}: ModelSwitchCacheDialogProps): ReactElement {const setWarnOnModelSwitch = useSettingsStore((state) => state.setWarnOnMidSessionModelSwitch,);const [dontShowAgain, setDontShowAgain] = useState(false);- const [activeAction, setActiveAction] = useState<ActiveAction>(null);- const { data: taskUsage } = useTaskUsage(taskId, open);+ const [isSwitching, setIsSwitching] = useState(false);const checkboxId = useId();const cancelButtonRef = useRef<HTMLButtonElement>(null);const requestTokenRef = useRef(0);@@ -64,39 +57,24 @@ function OpenModelSwitchCacheDialog({toModelId,contextTokens,);- const hasCostInfo = estimatedInputCost !== null || taskUsage !== undefined;- const busy = activeAction !== null;useEffect(() => {if (open) {setDontShowAgain(false);- setActiveAction(null);+ setIsSwitching(false);requestTokenRef.current += 1;}}, [open]);- const rememberChoice = (): void => {- if (dontShowAgain) setWarnOnModelSwitch(false);- };-const handleConfirm = async (): Promise<void> => {const token = requestTokenRef.current;- setActiveAction("switch");+ setIsSwitching(true);try {- if (await onConfirm()) rememberChoice();+ if (await onConfirm()) {+ if (dontShowAgain) setWarnOnModelSwitch(false);+ }} finally {- if (requestTokenRef.current === token) setActiveAction(null);- }- };-- const handleCopyHandoffSummary = async (): Promise<void> => {- if (!onCopyHandoffSummary) return;- const token = requestTokenRef.current;- setActiveAction("copy_summary");- try {- await onCopyHandoffSummary();- } finally {- if (requestTokenRef.current === token) setActiveAction(null);+ if (requestTokenRef.current === token) setIsSwitching(false);}};@@ -104,7 +82,9 @@ function OpenModelSwitchCacheDialog({<AlertDialogopen={open}onOpenChange={(next) => {- if (!next && !busy) onCancel();+ // Only the switch request holds the dialog, and it resolves in about a+ // second. Nothing else here can lock a person in.+ if (!next && !isSwitching) onCancel();}}><AlertDialogContent initialFocus={cancelButtonRef}>@@ -115,73 +95,37 @@ function OpenModelSwitchCacheDialog({the full conversation to the new model.</AlertDialogDescription></AlertDialogHeader>- <div className="flex flex-col gap-4 px-4 pb-4">- {hasCostInfo && (- <div className="overflow-hidden rounded-(--radius-3) border border-(--gray-4) bg-(--gray-2)">- <div className="flex items-center justify-center gap-2.5 px-3 py-3">- <span className="truncate rounded-(--radius-2) bg-(--gray-4) px-2 py-1 text-[12px] text-muted-foreground">- {fromModelLabel}- </span>- <ArrowRight- size={13}- className="shrink-0 text-muted-foreground"- />- <span className="truncate rounded-(--radius-2) bg-(--gray-4) px-2 py-1 font-medium text-[12px] text-foreground">- {toModelLabel}- </span>- </div>- <div className="flex flex-col gap-2 border-(--gray-4) border-t px-3 py-3">- {estimatedInputCost !== null && (- <div className="flex items-center justify-between gap-4">- <Text className="text-[12px] text-muted-foreground">- Estimated cost to resend history- </Text>- <Text className="shrink-0 font-medium text-[12px] text-foreground tabular-nums">- {formatCostUsd(estimatedInputCost)}- </Text>- </div>- )}- {taskUsage !== undefined && (- <div className="flex items-center justify-between gap-4">- <Text className="text-[12px] text-muted-foreground">- Estimated task cost so far- </Text>- <Text className="shrink-0 font-medium text-[12px] text-foreground tabular-nums">- {formatCostUsd(taskUsage.total_cost_usd)}- </Text>- </div>- )}- </div>+ <DialogBody viewportClassName="flex flex-col gap-3.5 px-4 pb-4">+ <div className="flex flex-col gap-1.5">+ <div className="flex min-w-0 items-center gap-2 text-[13px]">+ <span className="truncate text-muted-foreground">+ {fromModelLabel}+ </span>+ <ArrowRight+ size={12}+ className="shrink-0 text-muted-foreground"+ />+ <span className="truncate font-medium text-foreground">+ {toModelLabel}+ </span></div>- )}- {onCopyHandoffSummary && (- <div className="flex items-center justify-between gap-4">- <div className="flex min-w-0 flex-col">- <Text className="font-medium text-[12px] text-foreground">- Continue with another agent+ {estimatedInputCost !== null && (+ <div className="flex items-baseline justify-between gap-4">+ <Text className="text-[13px] text-muted-foreground">+ Estimated cost to resend history</Text>- <Text className="text-[12px] text-muted-foreground">- Copy the important context from this conversation.+ <Text className="shrink-0 font-medium text-[13px] text-foreground tabular-nums">+ {formatCostUsd(estimatedInputCost)}</Text></div>- <Button- variant="outline"- size="sm"- loading={activeAction === "copy_summary"}- disabled={busy}- data-attr="model-switch-cache-dialog-copy-summary"- onClick={handleCopyHandoffSummary}- >- Copy summary- </Button>- </div>- )}- <div className="flex flex-col gap-1 border-(--gray-4) border-t pt-3">+ )}+ </div>+ <div className="flex flex-col gap-0.5 border-(--gray-4) border-t pt-3"><div className="flex items-center gap-2"><Checkboxid={checkboxId}checked={dontShowAgain}- disabled={busy}+ disabled={isSwitching}onCheckedChange={(checked) =>setDontShowAgain(checked === true)}@@ -191,31 +135,31 @@ function OpenModelSwitchCacheDialog({htmlFor={checkboxId}className="cursor-pointer text-[13px] text-muted-foreground">- Do not show this ever again+ Do not show this again</Label></div>- <Text className="text-[12px] text-muted-foreground">- You can always change your mind in Cost management settings.+ <Text className="pl-6 text-[11.5px] text-muted-foreground">+ Turn it back on in Cost management settings.</Text></div>- </div>+ </DialogBody><AlertDialogFooter className="flex-row justify-end"><Buttonref={cancelButtonRef}variant="outline"- disabled={busy}+ disabled={isSwitching}onClick={onCancel}>Cancel</Button><Buttonvariant="primary"- loading={activeAction === "switch"}- disabled={busy}+ loading={isSwitching}+ disabled={isSwitching}data-attr="model-switch-cache-dialog-confirm"onClick={handleConfirm}>- Switch now+ Switch model</Button></AlertDialogFooter></AlertDialogContent>diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanel.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanel.test.tsxnew file mode 100644index 000000000000..c2738d590aac--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanel.test.tsx@@ -0,0 +1,78 @@+import { Theme } from "@radix-ui/themes";+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useSideQuestionStore } from "../sideQuestionStore";+import { SessionSummaryPanel } from "./SessionSummaryPanel";++vi.mock("@posthog/di/react", () => ({+ useService: () => ({ askSideQuestion: vi.fn() }),+}));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));++describe("SessionSummaryPanel", () => {+ beforeEach(() => {+ useSideQuestionStore.setState({ byTaskId: {} });+ });++ const seed = (+ entry: Partial<{ status: string; answer: string; taskRunId: string }>,+ ): void => {+ useSideQuestionStore.setState({+ byTaskId: {+ "task-1": {+ id: "s-1",+ question: "write a handoff",+ taskRunId: "run-1",+ kind: "summary",+ label: "Session summary",+ status: "pending",+ ...entry,+ } as never,+ },+ });+ };++ it("says how long the summary takes and offers a way out while it runs", () => {+ seed({});++ render(+ <Theme>+ <SessionSummaryPanel taskId="task-1" taskRunId="run-1" />+ </Theme>,+ );++ expect(screen.getByText("Session summary")).toBeInTheDocument();+ expect(screen.getByText(/Writing the summary/)).toBeInTheDocument();+ fireEvent.click(screen.getByText("Stop waiting"));+ expect(useSideQuestionStore.getState().byTaskId["task-1"]).toBeUndefined();+ });++ it("offers copy and dismiss once the summary is written", () => {+ seed({ status: "done", answer: "The goal is to ship the parser." });++ render(+ <Theme>+ <SessionSummaryPanel taskId="task-1" taskRunId="run-1" />+ </Theme>,+ );++ expect(+ screen.getByText("The goal is to ship the parser."),+ ).toBeInTheDocument();+ expect(screen.getByText("Copy")).toBeInTheDocument();+ fireEvent.click(screen.getByText("Dismiss"));+ expect(useSideQuestionStore.getState().byTaskId["task-1"]).toBeUndefined();+ });++ it("hides a summary written for a prior run", () => {+ seed({ status: "done", answer: "The goal is to ship the parser." });++ const { container } = render(+ <Theme>+ <SessionSummaryPanel taskId="task-1" taskRunId="run-2" />+ </Theme>,+ );++ expect(container.firstElementChild).toBeEmptyDOMElement();+ });+});diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanel.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanel.tsxnew file mode 100644index 000000000000..ce3707a10b87--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanel.tsx@@ -0,0 +1,81 @@+import {+ SESSION_SERVICE,+ type SessionService,+} from "@posthog/core/sessions/sessionService";+import { useService } from "@posthog/di/react";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import {+ SessionSummaryPanelView,+ type SessionSummaryState,+} from "@posthog/ui/features/sessions/components/SessionSummaryPanelView";+import {+ SESSION_SUMMARY_LABEL,+ startSessionSummary,+} from "@posthog/ui/features/sessions/sessionSummary";+import { useSideQuestionStore } from "@posthog/ui/features/sessions/sideQuestionStore";+import { toast } from "@posthog/ui/primitives/toast";+import { track } from "@posthog/ui/shell/analytics";++interface SessionSummaryPanelProps {+ taskId: string;+ /** The task's current run. A summary written for a prior run is hidden. */+ taskRunId?: string;+}++/**+ * The carry-over summary, pinned above the composer that started it. The+ * summary lives only in view state, so this panel both shows it and removes+ * it. Nothing here blocks the conversation underneath.+ */+export function SessionSummaryPanel({+ taskId,+ taskRunId,+}: SessionSummaryPanelProps) {+ const entry = useSideQuestionStore((s) => s.byTaskId[taskId]);+ const dismiss = useSideQuestionStore((s) => s.dismiss);+ const sessionService = useService<SessionService>(SESSION_SERVICE);++ if (!entry || entry.kind !== "summary") return null;+ if (entry.taskRunId !== taskRunId) return null;++ const report = (action: "copied" | "dismissed" | "stopped_waiting"): void => {+ track(ANALYTICS_EVENTS.SESSION_SUMMARY_ACTION, {+ task_id: taskId,+ action,+ wait_ms: Date.now() - entry.askedAt,+ });+ };++ const state: SessionSummaryState =+ entry.status === "done"+ ? { status: "done", summary: entry.answer }+ : entry.status === "error"+ ? { status: "error", error: entry.error }+ : { status: "pending" };++ const copySummary = async (): Promise<void> => {+ if (entry.status !== "done") return;+ try {+ await navigator.clipboard.writeText(entry.answer);+ report("copied");+ toast.success("Summary copied");+ } catch {+ toast.error("Couldn't copy the summary");+ }+ };++ return (+ <SessionSummaryPanelView+ title={entry.label ?? SESSION_SUMMARY_LABEL}+ state={state}+ onCopy={() => void copySummary()}+ onRetry={() =>+ startSessionSummary(sessionService, taskId, entry.taskRunId, "retry")+ }+ onDismiss={() => {+ report(entry.status === "pending" ? "stopped_waiting" : "dismissed");+ dismiss(taskId);+ }}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanelView.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanelView.stories.tsxnew file mode 100644index 000000000000..9026ade7ca62--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanelView.stories.tsx@@ -0,0 +1,69 @@+import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { SessionSummaryPanelView } from "./SessionSummaryPanelView";++const SUMMARY = `**Goal.** Ship the JSONL parser behind the \`parser-v2\` flag.++**Progress.** The reader streams lines and the tests pass locally. The flag is off in production.++**Files.** \`src/parse/jsonl.ts\`, \`src/parse/jsonl.test.ts\`, \`src/flags.ts\`.++**Next.** Wire the flag into the ingest path, then measure the parse time on a large file.++**Blocker.** The staging bucket rejects uploads over 50 MB, so the large-file measurement is untested.`;++const LONG_SUMMARY = `**Goal.** Replace the hand-rolled JSONL reader with a streaming parser behind the \`parser-v2\` flag, without changing what the ingest path writes.++**Constraints.** The old reader stays the default until the flag rolls out. Output rows must match byte for byte, because the downstream table is append-only.++**Decisions.** The parser reads line by line instead of buffering the whole file, so a malformed line fails on its own rather than killing the run. Errors carry the line number. The flag is read once per run, not per line.++**Progress.** The parser and its tests are done. The suite covers empty files, a trailing newline, a line over the size cap, and invalid UTF-8. All of it passes locally.++**Files.** \`src/parse/jsonl.ts\` holds the parser. \`src/parse/jsonl.test.ts\` holds the cases. \`src/flags.ts\` declares the flag. \`src/ingest/run.ts\` still calls the old reader.++**Commands.** \`pnpm test src/parse\` runs the parser tests. \`pnpm typecheck\` is clean.++**Remaining work.** Wire the flag into \`src/ingest/run.ts\`, keep the old path as the fallback, then measure the parse time on a file over one gigabyte. After that, remove the old reader in a separate change.++**Blockers.** The staging bucket rejects uploads over 50 MB, so the large-file measurement has no input yet. Ask for a raised limit, or generate the file inside the sandbox instead.`;++const meta: Meta<typeof SessionSummaryPanelView> = {+ title: "Sessions/SessionSummaryPanelView",+ component: SessionSummaryPanelView,+ args: {+ title: "Session summary",+ onCopy: () => {},+ onRetry: () => {},+ onDismiss: () => {},+ },+ decorators: [+ (Story) => (+ <div className="mx-auto p-4" style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof SessionSummaryPanelView>;++export const Writing: Story = {+ args: { state: { status: "pending" } },+};++export const Written: Story = {+ args: { state: { status: "done", summary: SUMMARY } },+};++/** The scroll-heavy case: the text outgrows the panel and the edge fades. */+export const LongSummary: Story = {+ args: { state: { status: "done", summary: LONG_SUMMARY } },+};++export const Failed: Story = {+ args: {+ state: { status: "error", error: "The session is not connected." },+ },+};diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanelView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanelView.tsxnew file mode 100644index 000000000000..8465347c7902--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionSummaryPanelView.tsx@@ -0,0 +1,102 @@+import { TextAlignLeft } from "@phosphor-icons/react";+import { Button, Text } from "@posthog/quill";+import { Spinner } from "@posthog/ui/primitives/Spinner";+import { MarkdownRenderer } from "../../editor/components/MarkdownRenderer";++export type SessionSummaryState =+ | { status: "pending" }+ | { status: "done"; summary: string }+ | { status: "error"; error: string };++interface SessionSummaryPanelViewProps {+ title: string;+ state: SessionSummaryState;+ onCopy: () => void;+ onRetry: () => void;+ onDismiss: () => void;+}++/** Rough size of the text, so a person knows what they are about to paste. */+function wordCount(summary: string): number {+ return summary.trim().split(/\s+/).length;+}++/** Past this the text outgrows the panel, so the cut edge needs a signal. */+const SCROLLS_ABOVE_WORDS = 90;++/**+ * The summary dock, in the composer column. Presentation only: the container+ * owns the store, the clipboard, and the analytics.+ */+export function SessionSummaryPanelView({+ title,+ state,+ onCopy,+ onRetry,+ onDismiss,+}: SessionSummaryPanelViewProps) {+ return (+ <div className="mb-2 overflow-hidden rounded-(--radius-lg) border border-(--gray-4) bg-(--gray-2)">+ <div className="flex items-center gap-2 px-3 pt-2 pb-1">+ <TextAlignLeft size={14} className="shrink-0 text-muted-foreground" />+ <Text className="min-w-0 truncate font-medium text-[13px] text-foreground">+ {title}+ </Text>+ {state.status === "done" && (+ <Text className="shrink-0 text-[11.5px] text-muted-foreground tabular-nums">+ {wordCount(state.summary)} words+ </Text>+ )}+ <div className="ml-auto flex shrink-0 items-center gap-1">+ {state.status === "done" && (+ <Button type="button" variant="outline" size="xs" onClick={onCopy}>+ Copy+ </Button>+ )}+ {state.status === "error" && (+ <Button type="button" variant="outline" size="xs" onClick={onRetry}>+ Try again+ </Button>+ )}+ <Button+ type="button"+ variant="link-muted"+ size="xs"+ onClick={onDismiss}+ >+ {state.status === "pending" ? "Stop waiting" : "Dismiss"}+ </Button>+ </div>+ </div>+ <output className="block px-3 pb-2.5">+ {state.status === "pending" && (+ <div className="flex items-start gap-2">+ <Spinner+ size={13}+ className="mt-0.5 shrink-0 text-muted-foreground"+ />+ <Text className="text-[12.5px] text-muted-foreground">+ Writing the summary. About 30 seconds. You can keep working, and+ the agent finishes the turn either way.+ </Text>+ </div>+ )}+ {state.status === "done" && (+ <div className="relative">+ <div className="max-h-52 overflow-y-auto text-[13px] text-foreground">+ <MarkdownRenderer content={state.summary} />+ </div>+ {wordCount(state.summary) > SCROLLS_ABOVE_WORDS && (+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-7 bg-linear-to-t from-(--gray-2) to-transparent" />+ )}+ </div>+ )}+ {state.status === "error" && (+ <Text className="text-(--red-11) text-[12.5px]">+ Couldn't write the summary. {state.error}+ </Text>+ )}+ </output>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsxindex 76f03f5645cb..8160e7c54edf 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx@@ -11,12 +11,7 @@ import {FAST_MODE_OPTION_CATEGORY,} from "@posthog/core/task-detail/previewConfig";import { useService } from "@posthog/di/react";-import {- type AcpMessage,- FAST_MODE_FLAG,- sessionSupportsSideQuestion,-} from "@posthog/shared";-import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { type AcpMessage, FAST_MODE_FLAG } from "@posthog/shared";import type { Task, TaskRunStatus } from "@posthog/shared/domain-types";import {spendStopMessage,@@ -57,6 +52,7 @@ import {SessionInitializingView,sessionInitializingCopy,} from "@posthog/ui/features/sessions/components/SessionInitializingView";+import { SessionSummaryPanel } from "@posthog/ui/features/sessions/components/SessionSummaryPanel";import { SideQuestionCard } from "@posthog/ui/features/sessions/components/SideQuestionCard";import { SteerQueueToggle } from "@posthog/ui/features/sessions/components/SteerQueueToggle";import {@@ -85,14 +81,12 @@ import {useSessionViewActions,useShowRawLogs,} from "@posthog/ui/features/sessions/sessionViewStore";-import { useSideQuestionStore } from "@posthog/ui/features/sessions/sideQuestionStore";import type { Plan } from "@posthog/ui/features/sessions/types";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { useIsWorkspaceCloudRun } from "@posthog/ui/features/workspace/useWorkspace";import { useConnectivity } from "@posthog/ui/hooks/useConnectivity";import { Spinner } from "@posthog/ui/primitives/Spinner";import { toast } from "@posthog/ui/primitives/toast";-import { captureException, track } from "@posthog/ui/shell/analytics";import {pendingTaskPromptStoreApi,usePendingTaskPrompt,@@ -151,8 +145,6 @@ interface SessionViewProps {const DEFAULT_ERROR_MESSAGE ="Failed to resume this session. The working directory may have been deleted. Please start a new session.";-const HANDOFF_SUMMARY_PROMPT = `Create a concise handoff summary for another coding agent. Include the user's goal, constraints, decisions, current progress, relevant files, commands and tests, remaining work, and blockers. Do not continue the task. Return only the handoff summary.`;-export function SessionView({events,taskId,@@ -261,12 +253,6 @@ export function SessionView({);const contextUsage = useContextUsage(events);- const canCopyHandoffSummary = useSessionSelector(taskId, (session) =>- session ? sessionSupportsSideQuestion(session) : false,- );- const hasPendingSideQuestion = useSideQuestionStore((s) =>- taskId ? s.byTaskId[taskId]?.status === "pending" : false,- );const activeTaskRunId = useSessionSelector(taskId, (s) => s?.taskRunId);const applyConfigOption = useCallback(@@ -294,54 +280,6 @@ export function SessionView({onApply: applyConfigOption,});- const handleCopyHandoffSummary = useCallback(async (): Promise<void> => {- if (!taskId || !activeTaskRunId || !pendingModelSwitch) return;- const { ask, resolve, fail } = useSideQuestionStore.getState();- const questionId = ask(taskId, activeTaskRunId, HANDOFF_SUMMARY_PROMPT);- if (!questionId) return;- try {- const summary = await sessionService.askSideQuestion(- taskId,- HANDOFF_SUMMARY_PROMPT,- );- resolve(taskId, activeTaskRunId, questionId, summary);- await navigator.clipboard.writeText(summary);- track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION, {- task_id: taskId,- from_model: pendingModelSwitch.fromValue,- to_model: pendingModelSwitch.value,- context_tokens: contextUsage?.used,- action: "copy_handoff_summary",- result: "succeeded",- });- toast.success("Handoff summary copied");- } catch (error) {- const caughtError =- error instanceof Error ? error : new Error("Handoff summary failed");- fail(taskId, activeTaskRunId, questionId, caughtError.message);- captureException(caughtError, {- feature: "model_switch_handoff_summary",- });- track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION, {- task_id: taskId,- from_model: pendingModelSwitch.fromValue,- to_model: pendingModelSwitch.value,- context_tokens: contextUsage?.used,- action: "copy_handoff_summary",- result: "failed",- });- toast.error("Could not copy a handoff summary", {- description: "Try again, or continue without a summary.",- });- }- }, [- taskId,- activeTaskRunId,- pendingModelSwitch,- sessionService,- contextUsage?.used,- ]);-const handleConfigOptionChange = useCallback((configId: string, value: string) => {if (!taskId) return;@@ -879,6 +817,12 @@ export function SessionView({}`}><ComposerWidth compact={compact}>+ {taskId && (+ <SessionSummaryPanel+ taskId={taskId}+ taskRunId={activeTaskRunId}+ />+ )}{taskId && (<SideQuestionCardtaskId={taskId}@@ -972,14 +916,8 @@ export function SessionView({fromModelLabel={pendingModelSwitch?.fromLabel ?? ""}toModelId={pendingModelSwitch?.value ?? ""}toModelLabel={pendingModelSwitch?.label ?? ""}- taskId={taskId}contextTokens={contextUsage?.used}onConfirm={confirmModelSwitch}- onCopyHandoffSummary={- canCopyHandoffSummary && !hasPendingSideQuestion- ? handleCopyHandoffSummary- : undefined- }onCancel={cancelModelSwitch}/><ContextMenu.Content size="1">diff --git a/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.test.tsxindex 841f0deadb93..e10585c2f3c3 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.test.tsx@@ -25,6 +25,8 @@ describe("SideQuestionCard", () => {id: "q-1",question: "what changed?",taskRunId: "run-1",+ kind: "side_question",+ askedAt: 1_700_000_000_000,status: "pending",},},@@ -47,6 +49,8 @@ describe("SideQuestionCard", () => {id: "q-1",question: "what changed?",taskRunId: "run-1",+ kind: "side_question",+ askedAt: 1_700_000_000_000,status: "done",answer: "The function parses JSONL.",},@@ -69,6 +73,8 @@ describe("SideQuestionCard", () => {id: "q-1",question: "what changed?",taskRunId: "run-1",+ kind: "side_question",+ askedAt: 1_700_000_000_000,status: "error",error: "Side question timed out",},@@ -84,6 +90,31 @@ describe("SideQuestionCard", () => {expect(screen.getByText("Side question timed out")).toBeInTheDocument();});+ it("leaves a session summary to its own panel", () => {+ useSideQuestionStore.setState({+ byTaskId: {+ "task-1": {+ id: "q-1",+ question: "write a handoff",+ taskRunId: "run-1",+ kind: "summary",+ label: "Session summary",+ askedAt: 1_700_000_000_000,+ status: "done",+ answer: "The goal is to ship the parser.",+ },+ },+ });++ const { container } = render(+ <Theme>+ <SideQuestionCard taskId="task-1" taskRunId="run-1" />+ </Theme>,+ );++ expect(container.firstElementChild).toBeEmptyDOMElement();+ });+it("renders nothing when the entry belongs to a prior run", () => {useSideQuestionStore.setState({byTaskId: {@@ -91,6 +122,8 @@ describe("SideQuestionCard", () => {id: "q-1",question: "what changed?",taskRunId: "run-1",+ kind: "side_question",+ askedAt: 1_700_000_000_000,status: "done",answer: "The function parses JSONL.",},@@ -113,6 +146,8 @@ describe("SideQuestionCard", () => {id: "q-1",question: "what changed?",taskRunId: "run-1",+ kind: "side_question",+ askedAt: 1_700_000_000_000,status: "pending",},},diff --git a/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.tsx b/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.tsxindex abc689b841a9..dff13b298183 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SideQuestionCard.tsx@@ -1,7 +1,13 @@import { ChatCircleDots, X } from "@phosphor-icons/react";+import {+ Button,+ Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@posthog/quill";import { useSideQuestionStore } from "@posthog/ui/features/sessions/sideQuestionStore";import { Spinner } from "@posthog/ui/primitives/Spinner";-import { Box, Flex, IconButton, Text, Tooltip } from "@radix-ui/themes";import { MarkdownRenderer } from "../../editor/components/MarkdownRenderer";interface SideQuestionCardProps {@@ -13,52 +19,63 @@ interface SideQuestionCardProps {/*** Ephemeral "/btw" side-question card pinned above the composer. The exchange* lives only in view state — it is never part of the session transcript — so- * dismissing it leaves no trace.+ * dismissing it leaves no trace. Session summaries have their own panel.*/export function SideQuestionCard({ taskId, taskRunId }: SideQuestionCardProps) {const entry = useSideQuestionStore((s) => s.byTaskId[taskId]);const dismiss = useSideQuestionStore((s) => s.dismiss);if (!entry || entry.taskRunId !== taskRunId) return null;+ if (entry.kind === "summary") return null;++ const title = entry.label ?? entry.question;return (- <Box className="mb-2 rounded-lg border border-gray-5 bg-card px-3 py-2">- <Flex align="center" gap="2">- <ChatCircleDots size={14} className="shrink-0 text-gray-9" />+ <div className="mb-2 rounded-(--radius-lg) border border-(--gray-5) bg-(--gray-2) px-3 py-2">+ <div className="flex items-center gap-2">+ <ChatCircleDots size={14} className="shrink-0 text-muted-foreground" /><Text- title={entry.question}- className="min-w-0 flex-1 truncate font-medium text-[13px] text-gray-11"+ title={title}+ className="min-w-0 flex-1 truncate font-medium text-[13px] text-foreground">- {entry.question}+ {title}</Text>- <Tooltip content="Dismiss">- <IconButton- size="1"- variant="ghost"- color="gray"- aria-label="Dismiss side question"- onClick={() => dismiss(taskId)}- >- <X size={12} />- </IconButton>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="link-muted"+ size="icon-sm"+ aria-label="Dismiss side question"+ className="shrink-0"+ onClick={() => dismiss(taskId)}+ >+ <X size={12} />+ </Button>+ }+ />+ <TooltipContent side="top">Dismiss</TooltipContent></Tooltip>- </Flex>- <Box className="mt-1 pl-6" role="status" aria-live="polite">+ </div>+ <output className="mt-1 block pl-6">{entry.status === "pending" && (- <Flex align="center" gap="2">- <Spinner size={14} className="text-gray-9" />- <Text className="text-[13px] text-gray-9">Answering…</Text>- </Flex>+ <div className="flex items-center gap-2">+ <Spinner size={14} className="text-muted-foreground" />+ <Text className="text-[13px] text-muted-foreground">+ Answering…+ </Text>+ </div>)}{entry.status === "done" && (- <Box className="max-h-64 overflow-y-auto text-[13px] text-gray-12">+ <div className="max-h-64 overflow-y-auto text-[13px] text-foreground"><MarkdownRenderer content={entry.answer} />- </Box>+ </div>)}{entry.status === "error" && (- <Text className="text-[13px] text-red-11">{entry.error}</Text>+ <Text className="text-(--red-11) text-[13px]">{entry.error}</Text>)}- </Box>- </Box>+ </output>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/sessions/sessionSummary.ts b/products/desktop/packages/ui/src/features/sessions/sessionSummary.tsnew file mode 100644index 000000000000..c76157e0408b--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/sessionSummary.ts@@ -0,0 +1,32 @@+import type { SessionService } from "@posthog/core/sessions/sessionService";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { fireSideQuestion } from "@posthog/ui/features/sessions/sideQuestionStore";+import { track } from "@posthog/ui/shell/analytics";++export const SESSION_SUMMARY_LABEL = "Session summary";++const SESSION_SUMMARY_PROMPT = `Create a concise handoff summary for another coding agent. Include the user's goal, constraints, decisions, current progress, relevant files, commands and tests, remaining work, and blockers. Do not continue the task. Return only the handoff summary.`;++/**+ * Asks the running agent to write a carry-over summary for another agent. The+ * exchange runs beside the conversation and lands in the session summary+ * panel. False when one is already on its way.+ */+export function startSessionSummary(+ sessionService: Pick<SessionService, "askSideQuestion">,+ taskId: string,+ taskRunId: string,+ source: "retry" | "task_menu" = "task_menu",+): boolean {+ track(ANALYTICS_EVENTS.SESSION_SUMMARY_REQUESTED, {+ task_id: taskId,+ source,+ });+ return fireSideQuestion(+ sessionService,+ taskId,+ taskRunId,+ SESSION_SUMMARY_PROMPT,+ { kind: "summary", label: SESSION_SUMMARY_LABEL },+ );+}diff --git a/products/desktop/packages/ui/src/features/sessions/sideQuestionStore.ts b/products/desktop/packages/ui/src/features/sessions/sideQuestionStore.tsindex adc9c5a2a5ee..90e8826309b2 100644--- a/products/desktop/packages/ui/src/features/sessions/sideQuestionStore.ts+++ b/products/desktop/packages/ui/src/features/sessions/sideQuestionStore.ts@@ -5,11 +5,24 @@ import { create } from "zustand";const log = logger.scope("side-question");+/** Which surface owns the entry: the "/btw" card, or the session summary panel. */+export type SideQuestionKind = "side_question" | "summary";++export interface SideQuestionMeta {+ kind?: SideQuestionKind;+ /** What the surface calls this exchange. Without it a card shows the raw prompt. */+ label?: string;+}+type SideQuestionEntry = {id: string;question: string;/** The run this question was asked against — a card must not outlive it. */taskRunId: string;+ kind: SideQuestionKind;+ label?: string;+ /** When the question went out, so a surface can report how long it waited. */+ askedAt: number;} & (| { status: "pending" }| { status: "done"; answer: string }@@ -20,7 +33,12 @@ interface SideQuestionState {/** Latest side question per task. Ephemeral: never persisted, never part of session history. */byTaskId: Record<string, SideQuestionEntry>;/** Returns null when one is already pending — the card holds a single question. */- ask: (taskId: string, taskRunId: string, question: string) => string | null;+ ask: (+ taskId: string,+ taskRunId: string,+ question: string,+ meta?: SideQuestionMeta,+ ) => string | null;resolve: (taskId: string,taskRunId: string,@@ -54,6 +72,9 @@ function settle(id: entry.id,question: entry.question,taskRunId,+ kind: entry.kind,+ label: entry.label,+ askedAt: entry.askedAt,...outcome,},},@@ -62,7 +83,7 @@ function settle(export const useSideQuestionStore = create<SideQuestionState>()((set, get) => ({byTaskId: {},- ask: (taskId, taskRunId, question) => {+ ask: (taskId, taskRunId, question, meta) => {const pending = get().byTaskId[taskId];if (pending?.status === "pending" && pending.taskRunId === taskRunId) {return null;@@ -71,7 +92,15 @@ export const useSideQuestionStore = create<SideQuestionState>()((set, get) => ({set((state) => ({byTaskId: {...state.byTaskId,- [taskId]: { id, question, taskRunId, status: "pending" },+ [taskId]: {+ id,+ question,+ taskRunId,+ kind: meta?.kind ?? "side_question",+ label: meta?.label,+ askedAt: Date.now(),+ status: "pending",+ },},}));return id;@@ -105,9 +134,10 @@ export function fireSideQuestion(taskId: string,taskRunId: string,question: string,+ meta?: SideQuestionMeta,): boolean {const { ask, resolve, fail } = useSideQuestionStore.getState();- const id = ask(taskId, taskRunId, question);+ const id = ask(taskId, taskRunId, question, meta);if (!id) return false;sessionService.askSideQuestion(taskId, question)diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskOverflowMenu.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskOverflowMenu.tsxindex 2739dce31cdf..3431f649f6fc 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskOverflowMenu.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskOverflowMenu.tsx@@ -1,5 +1,10 @@import { DotsThree } from "@phosphor-icons/react";import { isTerminalStatus } from "@posthog/core/cloud-task/schemas";+import {+ SESSION_SERVICE,+ type SessionService,+} from "@posthog/core/sessions/sessionService";+import { useService } from "@posthog/di/react";import {DropdownMenu,DropdownMenuContent,@@ -8,6 +13,7 @@ import {DropdownMenuTrigger,Button as QuillButton,} from "@posthog/quill";+import { sessionSupportsSideQuestion } from "@posthog/shared";import type { Task } from "@posthog/shared/domain-types";import { useTaskArchive } from "@posthog/ui/features/archive/useTaskArchive";import {@@ -15,6 +21,8 @@ import {SHORTCUTS,} from "@posthog/ui/features/command/keyboard-shortcuts";import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/StopCloudRunDialog";+import { startSessionSummary } from "@posthog/ui/features/sessions/sessionSummary";+import { useSideQuestionStore } from "@posthog/ui/features/sessions/sideQuestionStore";import { useSessionSelector } from "@posthog/ui/features/sessions/useSession";import { useState } from "react";import { shallow } from "zustand/shallow";@@ -24,14 +32,23 @@ import { shallow } from "zustand/shallow";* rather than on its branch or its diff.*/export function TaskOverflowMenu({ task }: { task: Task }) {- const { isCloud, cloudStatus, stopRequested } = useSessionSelector(- task.id,- (session) => ({- isCloud: session?.isCloud ?? false,- cloudStatus: session?.cloudStatus ?? null,- stopRequested: session?.stopRequested ?? false,- }),- shallow,+ const { isCloud, cloudStatus, stopRequested, taskRunId, supportsSummary } =+ useSessionSelector(+ task.id,+ (session) => ({+ isCloud: session?.isCloud ?? false,+ cloudStatus: session?.cloudStatus ?? null,+ stopRequested: session?.stopRequested ?? false,+ taskRunId: session?.taskRunId ?? null,+ supportsSummary: session ? sessionSupportsSideQuestion(session) : false,+ }),+ shallow,+ );+ const sessionService = useService<SessionService>(SESSION_SERVICE);+ // The store holds one side question per task, so a pending "/btw" answer+ // blocks a summary too.+ const sideQuestionPending = useSideQuestionStore(+ (s) => s.byTaskId[task.id]?.status === "pending",);const [stopConfirmOpen, setStopConfirmOpen] = useState(false);const { requestArchive, dialog: archiveDialog } = useTaskArchive(task, {@@ -39,6 +56,7 @@ export function TaskOverflowMenu({ task }: { task: Task }) {});const canStop = isCloud && !isTerminalStatus(cloudStatus);+ const canSummarize = supportsSummary && taskRunId !== null;return (<>@@ -67,6 +85,17 @@ export function TaskOverflowMenu({ task }: { task: Task }) {{stopRequested ? "Stopping..." : "Stop run"}</DropdownMenuItem>)}+ {canSummarize && (+ <DropdownMenuItem+ disabled={sideQuestionPending}+ onClick={() => {+ if (!taskRunId) return;+ startSessionSummary(sessionService, task.id, taskRunId);+ }}+ >+ Summarize for another agent+ </DropdownMenuItem>+ )}<DropdownMenuItem onClick={requestArchive}>Archive<DropdownMenuShortcut>