Skip to content

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

chore(desktop): remove legacy conversation thread (#99581)

Adam Leith624404f8a9ad
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/components/McpToolView.tsx b/products/desktop/packages/ui/src/features/mcp-apps/components/McpToolView.tsx
index c44a4c60e5f1..a1e13b811f48 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/components/McpToolView.tsx
+++ b/products/desktop/packages/ui/src/features/mcp-apps/components/McpToolView.tsx
@@ -4,16 +4,12 @@ import {
isPostHogExecTool,
} from "@posthog/core/sessions/posthogExecDisplay";
import { readMcpToolDescriptor } from "@posthog/shared";
-import { useChatThreadChrome } from "../../sessions/components/chat-thread/chatThreadChrome";
import { ToolRow } from "../../sessions/components/session-update/ToolRow";
import {
- ContentPre,
compactInput,
- formatInput,
- getContentText,
- stripCodeFences,
ToolTitle,
type ToolViewProps,
+ toolCallDetails,
truncateText,
useToolCallStatus,
} from "../../sessions/components/session-update/toolCallUtils";
@@ -38,10 +34,6 @@ export function McpToolView({
turnCancelled,
turnComplete,
);
- // New thread restyles the MCP header/output; the legacy thread keeps its original colours + the
- // input/output divider so ConversationView is unchanged when the chat thread is toggled off.
- const chatChrome = useChatThreadChrome();
-
const { serverName: defaultServerName, toolName: defaultToolName } =
parseMcpToolKey(mcpToolName);
const descriptor = readMcpToolDescriptor(toolCall._meta);
@@ -59,32 +51,6 @@ export function McpToolView({
)
: undefined
: compactInput(rawInput);
- const fullInput = formatInput(rawInput);
-
- const output = stripCodeFences(getContentText(content) ?? "");
- const hasOutput = output.trim().length > 0;
- // Surface output for failures too, otherwise a failed call shows "(Failed)"
- // with no reason — the error text lives in `content`.
- const showOutput = (isComplete || isFailed) && hasOutput;
-
- const body =
- fullInput || showOutput ? (
- <>
- {fullInput && <ContentPre>{fullInput}</ContentPre>}
- {showOutput &&
- (chatChrome ? (
- <ContentPre>{output}</ContentPre>
- ) : (
- <div className={fullInput ? "border-gray-6 border-t" : undefined}>
- <ContentPre>{output}</ContentPre>
- </div>
- ))}
- </>
- ) : undefined;
-
- const previewClass = chatChrome
- ? "text-muted-foreground/50"
- : "text-accent-11";
return (
<ToolRow
@@ -93,12 +59,12 @@ export function McpToolView({
isFailed={isFailed}
wasCancelled={wasCancelled}
defaultOpen={expanded}
- content={body}
+ content={toolCallDetails({ rawInput, content, isComplete, isFailed })}
>
<ToolTitle>{displayName}</ToolTitle>
{inputPreview && (
<ToolTitle>
- <span className={previewClass}>{inputPreview}</span>
+ <span className="text-muted-foreground/50">{inputPreview}</span>
</ToolTitle>
)}
</ToolRow>
diff --git a/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx b/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx
index e508f543190b..8311ef00007f 100644
--- a/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx
+++ b/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx
@@ -8,10 +8,10 @@ vi.mock("@posthog/di/react", () => ({
useService: () => ({ maybeRevertBypassMode: vi.fn() }),
}));
-vi.mock("../sessions/components/ThreadView", async () => {
+vi.mock("../sessions/components/chat-thread/ChatThread", async () => {
const { PlanContent } = await import("./PlanContent");
return {
- ThreadView: () => (
+ AcpChatThread: () => (
<PlanContent id="test-plan" plan="# Test plan\n\nShip the fix." />
),
};
@@ -62,7 +62,7 @@ vi.mock("../message-editor/useAutoFocusOnTyping", () => ({
}));
vi.mock("../settings/settingsStore", () => ({
useSettingsStore: (selector?: (state: unknown) => unknown) => {
- const state = { allowBypassPermissions: false, useNewChatThread: false };
+ const state = { allowBypassPermissions: false };
return selector ? selector(state) : state;
},
}));
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationSearchBar.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationSearchBar.tsx
deleted file mode 100644
index 2e3a7d3404b5..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationSearchBar.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { ArrowDown, ArrowUp, X } from "@phosphor-icons/react";
-import { IconButton } from "@radix-ui/themes";
-import {
- forwardRef,
- type KeyboardEvent as ReactKeyboardEvent,
- useCallback,
- useImperativeHandle,
- useLayoutEffect,
- useRef,
-} from "react";
-
-export interface ConversationSearchBarHandle {
- focusAndSelect: () => void;
-}
-
-interface ConversationSearchBarProps {
- query: string;
- currentMatch: number;
- totalMatches: number;
- onQueryChange: (query: string) => void;
- onNext: () => void;
- onPrev: () => void;
- onClose: () => void;
-}
-
-export const ConversationSearchBar = forwardRef<
- ConversationSearchBarHandle,
- ConversationSearchBarProps
->(function ConversationSearchBar(
- { query, currentMatch, totalMatches, onQueryChange, onNext, onPrev, onClose },
- ref,
-) {
- const inputRef = useRef<HTMLInputElement>(null);
-
- useLayoutEffect(() => {
- inputRef.current?.focus();
- }, []);
-
- useImperativeHandle(
- ref,
- () => ({
- focusAndSelect: () => {
- const input = inputRef.current;
- if (!input) return;
- input.focus();
- input.select();
- },
- }),
- [],
- );
-
- const handleKeyDown = useCallback(
- (e: ReactKeyboardEvent<HTMLInputElement>) => {
- if (e.key === "Escape") {
- e.preventDefault();
- onClose();
- } else if (e.key === "Enter" || e.key === "ArrowDown") {
- e.preventDefault();
- if (e.shiftKey) {
- onPrev();
- } else {
- onNext();
- }
- } else if (e.key === "ArrowUp") {
- e.preventDefault();
- onPrev();
- }
- },
- [onClose, onNext, onPrev],
- );
-
- return (
- <div
- data-overlay
- className="absolute top-2 right-6 z-30 flex items-center gap-1 rounded-lg border border-(--gray-6) bg-(--color-background) px-2 py-1 shadow-md"
- >
- <input
- ref={inputRef}
- type="text"
- value={query}
- onChange={(e) => onQueryChange(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder="Find in conversation..."
- className="w-48 border-none bg-transparent text-(--gray-12) text-[13px] outline-none placeholder:text-(--gray-9)"
- />
- {query && (
- <span className="shrink-0 text-(--gray-10) text-[12px]">
- {totalMatches > 0
- ? `${currentMatch + 1} of ${totalMatches}`
- : "No results"}
- </span>
- )}
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- onClick={onPrev}
- disabled={totalMatches === 0}
- aria-label="Previous match"
- >
- <ArrowUp size={14} />
- </IconButton>
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- onClick={onNext}
- disabled={totalMatches === 0}
- aria-label="Next match"
- >
- <ArrowDown size={14} />
- </IconButton>
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- onClick={onClose}
- aria-label="Close search"
- >
- <X size={14} />
- </IconButton>
- </div>
- );
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.stories.tsx
deleted file mode 100644
index 1c9ede42fe72..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.stories.tsx
+++ /dev/null
@@ -1,944 +0,0 @@
-import type { SessionUpdate } from "@agentclientprotocol/sdk";
-import {
- toolInfoFromToolUse,
- toolUpdateFromToolResult,
-} from "@posthog/agent/adapters/claude/conversion/tool-use-to-acp";
-import type { AcpMessage } from "@posthog/shared";
-import { ConversationView } from "@posthog/ui/features/sessions/components/ConversationView";
-import type { Meta, StoryObj } from "@storybook/react-vite";
-
-let timestamp = Date.now();
-let messageId = 1;
-let toolCallCounter = 1;
-
-function resetCounters() {
- timestamp = Date.now();
- messageId = 1;
- toolCallCounter = 1;
-}
-
-function ts(): number {
- timestamp += 100;
- return timestamp;
-}
-
-function promptRequest(content: string): AcpMessage {
- const id = messageId++;
- return {
- type: "acp_message",
- ts: ts(),
- message: {
- jsonrpc: "2.0",
- id,
- method: "session/prompt",
- params: { prompt: [{ type: "text", text: content }] },
- },
- };
-}
-
-function promptResponse(id: number): AcpMessage {
- return {
- type: "acp_message",
- ts: ts(),
- message: {
- jsonrpc: "2.0",
- id,
- result: { stopReason: "end_turn" },
- },
- };
-}
-
-function sessionUpdate(update: SessionUpdate): AcpMessage {
- return {
- type: "acp_message",
- ts: ts(),
- message: {
- method: "session/update",
- params: { update },
- },
- };
-}
-
-function agentMessage(text: string): AcpMessage {
- return sessionUpdate({
- sessionUpdate: "agent_message_chunk",
- content: { type: "text", text },
- });
-}
-
-interface ToolCallOptions {
- status?: "pending" | "in_progress" | "completed" | "failed";
- result?: { content: unknown; is_error?: boolean };
- cachedFileContent?: Record<string, string>;
-}
-
-function toolCall(
- toolName: string,
- toolInput: Record<string, unknown>,
- options: ToolCallOptions = {},
-): AcpMessage {
- const { status = "completed", result, cachedFileContent = {} } = options;
- const toolCallId = `tool-${toolCallCounter++}`;
-
- const info = toolInfoFromToolUse(
- { name: toolName, input: toolInput },
- cachedFileContent,
- );
-
- let content = info.content;
- if (result && status === "completed") {
- const update = toolUpdateFromToolResult(
- { tool_use_id: toolCallId, ...result } as Parameters<
- typeof toolUpdateFromToolResult
- >[0],
- { name: toolName, input: toolInput },
- );
- if (update.content) {
- content = [...(content || []), ...update.content];
- }
- }
-
- return sessionUpdate({
- sessionUpdate: "tool_call",
- toolCallId,
- title: info.title,
- kind: info.kind,
- status,
- content,
- locations: info.locations,
- rawInput: toolInput,
- } as SessionUpdate);
-}
-
-function buildAllToolCallsConversation(): AcpMessage[] {
- resetCounters();
- const events: AcpMessage[] = [];
-
- events.push(promptRequest("Help me understand this codebase"));
- events.push(
- agentMessage(
- "I'll explore the codebase to understand its structure. Let me start by reading some key files.\n\n",
- ),
- );
-
- events.push(
- toolCall(
- "Read",
- { file_path: "/Users/jonathan/dev/posthog-code/package.json" },
- {
- result: {
- content: [
- {
- type: "text",
- text: `{
- "name": "posthog-code",
- "version": "1.0.0",
- "private": true,
- "workspaces": ["apps/*", "packages/*"],
- "scripts": {
- "dev": "turbo dev",
- "build": "turbo build",
- "test": "turbo test",
- "lint": "biome check --write"
- }
-}`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(
- toolCall(
- "Grep",
- { pattern: "export function", path: "src/" },
- {
- result: {
- content: [
- {
- type: "text",
- text: `src/utils/helpers.ts:5: export function formatDate(date: Date): string {
-src/utils/helpers.ts:9: export function capitalize(str: string): string {
-src/utils/helpers.ts:13: export function debounce<T>(fn: T, delay: number): T {
-src/components/Button.tsx:8: export function Button({ children, onClick }: ButtonProps) {
-src/hooks/useAuth.ts:12: export function useAuth() {`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(
- agentMessage(
- "Found some utility functions. Let me make an edit to improve the implementation.\n\n",
- ),
- );
-
- const oldFileContent = `export function formatDate(date: Date): string {
- return date.toISOString().split("T")[0];
-}
-
-export function capitalize(str: string): string {
- return str.charAt(0).toUpperCase() + str.slice(1);
-}`;
-
- events.push(
- toolCall(
- "Edit",
- {
- file_path: "src/utils/helpers.ts",
- old_string: `export function formatDate(date: Date): string {
- return date.toISOString().split("T")[0];
-}`,
- new_string: `export function formatDate(date: Date): string {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, "0");
- const day = String(date.getDate()).padStart(2, "0");
- return \`\${year}-\${month}-\${day}\`;
-}`,
- },
- {
- cachedFileContent: { "src/utils/helpers.ts": oldFileContent },
- },
- ),
- );
-
- events.push(
- agentMessage("Now let me run the tests to make sure everything works.\n\n"),
- );
-
- events.push(
- toolCall(
- "Bash",
- { command: "pnpm test", description: "Run tests" },
- {
- result: {
- content: [
- {
- type: "text",
- text: `> [email protected] test
-> vitest run
-
- ✓ src/utils/helpers.test.ts (3 tests) 12ms
- ✓ src/components/Button.test.ts (5 tests) 45ms
- ✓ src/hooks/useAuth.test.ts (4 tests) 23ms
-
- Test Files 3 passed (3)
- Tests 12 passed (12)
- Start at 14:23:45
- Duration 892ms`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(
- agentMessage("Tests pass! Let me also check the API documentation.\n\n"),
- );
-
- events.push(
- toolCall(
- "WebFetch",
- {
- url: "https://api.example.com/docs",
- prompt: "Get API documentation for reference",
- },
- {
- result: {
- content: [
- {
- type: "text",
- text: `# API Documentation
-
-## Authentication
-All endpoints require Bearer token authentication.
-
-## Endpoints
-- GET /users - List all users
-- POST /users - Create a new user
-- GET /users/:id - Get user by ID`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(
- agentMessage(
- "Let me think about the best approach to implement the new feature...\n\n",
- ),
- );
-
- events.push(
- toolCall(
- "Task",
- {
- description: "Analyze codebase architecture",
- prompt:
- "Explore the codebase structure and identify patterns for adding new features",
- },
- {
- result: {
- content: [
- {
- type: "text",
- text: `Based on my analysis:
-
-1. The codebase follows a monorepo structure
-2. Uses TypeScript with strict mode
-3. Has good test coverage
-4. Follows feature-based folder organization
-
-Recommendation: Add the new feature in a dedicated feature folder with its own components, hooks, and tests.`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(agentMessage("Now creating a new file for the feature.\n\n"));
-
- events.push(
- toolCall("Write", {
- file_path: "src/features/analytics/index.ts",
- content: `export interface AnalyticsEvent {
- name: string;
- properties?: Record<string, unknown>;
- timestamp: Date;
-}
-
-export function trackEvent(event: AnalyticsEvent): void {
- console.log("[Analytics]", event.name, event.properties);
-}
-
-export function useAnalytics() {
- return {
- track: (name: string, properties?: Record<string, unknown>) => {
- trackEvent({ name, properties, timestamp: new Date() });
- },
- };
-}
-`,
- }),
- );
-
- events.push(
- agentMessage(
- "I've created the analytics module. The codebase is well-structured with:\n\n- **Monorepo setup** using pnpm workspaces\n- **TypeScript** with strict type checking\n- **Feature-based architecture** for scalability\n- **Good test coverage** across all packages\n\nLet me know if you'd like me to explain any specific part in more detail!",
- ),
- );
-
- events.push(promptResponse(1));
-
- events.push(promptRequest("Search the web for React best practices"));
-
- events.push(
- agentMessage("I'll search for the latest React best practices.\n\n"),
- );
-
- events.push(
- toolCall(
- "WebSearch",
- { query: "React hooks best practices 2024" },
- {
- result: {
- content: [
- {
- type: "text",
- text: `Found 5 results:
-
-1. React Hooks Best Practices - React Blog
- https://react.dev/learn/hooks-best-practices
-
-2. Top 10 React Hook Patterns - Dev.to
- https://dev.to/hooks-patterns
-
-3. Custom Hooks Guide - Kent C. Dodds
- https://kentcdodds.com/custom-hooks`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(
- agentMessage(
- "Here are some great resources on React best practices. The key points are:\n\n1. Keep hooks at the top level\n2. Use custom hooks for reusable logic\n3. Memoize expensive computations",
- ),
- );
-
- events.push(promptResponse(2));
-
- events.push(promptRequest("Find all TypeScript files in the project"));
-
- events.push(agentMessage("I'll search for all TypeScript files.\n\n"));
-
- events.push(
- toolCall(
- "Glob",
- { pattern: "**/*.ts", path: "src/" },
- {
- result: {
- content: [
- {
- type: "text",
- text: `src/index.ts
-src/utils/helpers.ts
-src/utils/logger.ts
-src/components/Button.ts
-src/hooks/useAuth.ts
-src/features/analytics/index.ts`,
- },
- ],
- },
- },
- ),
- );
-
- events.push(agentMessage("Found 6 TypeScript files in the src directory."));
-
- events.push(promptResponse(3));
-
- return events;
-}
-
-const meta: Meta<typeof ConversationView> = {
- title: "Features/Sessions/ConversationView",
- component: ConversationView,
- parameters: {
- layout: "fullscreen",
- },
- decorators: [
- (Story) => (
- <div className="flex h-[90vh] flex-col">
- <Story />
- </div>
- ),
- ],
-};
-
-export default meta;
-type Story = StoryObj<typeof ConversationView>;
-
-export const AllToolCalls: Story = {
- args: {
- events: buildAllToolCallsConversation(),
- isPromptPending: false,
- repoPath: "/Users/jonathan/dev/posthog-code",
- },
-};
-
-export const WithPendingPrompt: Story = {
- args: {
- events: (() => {
- const events = buildAllToolCallsConversation();
- events.push(promptRequest("What else can you help me with?"));
- events.push(
- agentMessage(
- "I can help you with many things! Let me search for...\n\n",
- ),
- );
- events.push(
- toolCall("Grep", { pattern: "TODO" }, { status: "in_progress" }),
- );
- return events;
- })(),
- isPromptPending: true,
- promptStartedAt: Date.now() - 5000,
- repoPath: "/Users/jonathan/dev/posthog-code",
- },
-};
-
-export const Empty: Story = {
- args: {
- events: [],
- isPromptPending: false,
- },
-};
-
-export const SingleTurn: Story = {
- args: {
- events: (() => {
- resetCounters();
- const events: AcpMessage[] = [];
-
- events.push(promptRequest("Hello!"));
- events.push(
- agentMessage(
- "Hello! I'm ready to help you with your codebase. What would you like to do?",
- ),
- );
- events.push(promptResponse(1));
-
- return events;
- })(),
- isPromptPending: false,
- },
-};
-
-export const LongConversation: Story = {
- args: {
- events: (() => {
- resetCounters();
- const events: AcpMessage[] = [];
-
- for (let i = 0; i < 10; i++) {
- events.push(
- promptRequest(`Question ${i + 1}: How does feature ${i + 1} work?`),
- );
- events.push(
- agentMessage(
- `Feature ${i + 1} works by using a combination of React hooks and context providers. Here's a brief overview:\n\n`,
- ),
- );
- events.push(
- toolCall(
- "Read",
- { file_path: `src/features/feature${i + 1}/index.ts` },
- {
- result: {
- content: [
- {
- type: "text",
- text: `export function useFeature${i + 1}() {
- const [state, setState] = useState(null);
-
- useEffect(() => {
- loadFeature${i + 1}Data().then(setState);
- }, []);
-
- return { state, refresh: () => loadFeature${i + 1}Data().then(setState) };
-}`,
- },
- ],
- },
- },
- ),
- );
- events.push(
- agentMessage(
- `The feature uses a custom hook pattern with useState and useEffect for data loading. Would you like me to explain more?\n\n`,
- ),
- );
- events.push(promptResponse(i + 1));
- }
-
- return events;
- })(),
- isPromptPending: false,
- repoPath: "/Users/jonathan/dev/posthog-code",
- },
-};
-
-function buildMarkdownShowcaseConversation(): AcpMessage[] {
- resetCounters();
- const events: AcpMessage[] = [];
-
- events.push(promptRequest("Show me all markdown rendering capabilities"));
-
- events.push(
- agentMessage(`# API Reference: Authentication Service v2.4.1
-
-## Quick Start
-
-Import and initialize the client:
-
-\`\`\`typescript
-import { AuthClient } from '@acme/auth-sdk';
-
-const client = new AuthClient({
- apiKey: process.env.AUTH_API_KEY,
- timeout: 30000,
- retries: 3
-});
-
-const session = await client.authenticate({
- email: '[email protected]',
- password: '••••••••'
-});
-\`\`\`
-
-## Rate Limits
-
-| Tier | Requests/min | Burst | Price |
-|------|-------------|-------|-------|
-| Free | 60 | 100 | $0 |
-| Pro | 1,000 | 2,500 | $29/mo |
-| Enterprise | 10,000 | 50k | Custom |
-
-## Error Handling
-
-When authentication fails, you'll receive an error response:
-
-\`\`\`json
-{
- "error": {
- "code": "AUTH_INVALID_CREDENTIALS",
- "message": "The provided credentials are invalid.",
- "requestId": "req_7xKo2nhV03",
- "timestamp": "2024-01-15T09:23:41.892Z"
- }
-}
-\`\`\`
-
-Common error codes:
-
-- \`AUTH_INVALID_CREDENTIALS\` — Wrong email or password
-- \`AUTH_RATE_LIMITED\` — Too many requests (wait 60s)
-- \`AUTH_TOKEN_EXPIRED\` — Refresh token or re-authenticate
-- \`AUTH_MFA_REQUIRED\` — 2FA verification needed
-
-## Terminal Output
-
-\`\`\`bash
-$ npm run build
-> @acme/[email protected] build
-> next build
-
-▲ Next.js 14.1.0
-
-Creating an optimized production build...
-✓ Compiled successfully in 12.4s
-✓ Linting and checking validity
-✓ Collecting page data
-✓ Generating static pages (24/24)
-✓ Finalizing page optimization
-
-Route (app) Size First Load JS
-┌ ○ / 5.2 kB 89.1 kB
-├ ○ /dashboard 12.8 kB 96.7 kB
-├ ● /settings/[...slug] 3.1 kB 87.0 kB
-└ ○ /api/health 0 B 0 B
-
-○ (Static) prerendered as static content
-● (SSG) prerendered as static HTML
-\`\`\`
-
-## Configuration
-
-Create a \`config.yaml\` in your project root:
-
-\`\`\`yaml
-auth:
- provider: oauth2
- issuer: https://auth.acme.dev
- client_id: \${CLIENT_ID}
- scopes:
- - openid
- - profile
- - email
-
-database:
- host: localhost
- port: 5432
- pool_size: 20
- ssl: true
-
-logging:
- level: info # debug | info | warn | error
- format: json
-\`\`\`
-
-## Metrics & Observability
-
-Average response times (p50 / p95 / p99):
-
-- **POST /auth/token** — 45ms / 120ms / 340ms
-- **GET /auth/userinfo** — 12ms / 28ms / 65ms
-- **POST /auth/refresh** — 38ms / 95ms / 210ms
-
-Memory usage: ~128MB baseline, scales to 512MB under load.
-
----
-
-## Text Formatting
-
-This section demonstrates various **text formatting** options available:
-
-- **Bold text** for emphasis
-- *Italic text* for subtle emphasis
-- ~~Strikethrough~~ for deleted content
-- \`inline code\` for technical terms
-- Combined ***bold and italic*** together
-
-> **Note:** This is a blockquote with important information. Use blockquotes to highlight key points or warnings in your documentation.
-
-### Task Lists
-
-- [x] Implement authentication flow
-- [x] Add rate limiting
-- [ ] Write integration tests
-- [ ] Update API documentation
-
-### Nested Lists
-
-1. First level item
- - Second level bullet
- - Another bullet
- 1. Third level numbered
- 2. Another numbered
-2. Back to first level
- - With a bullet point
-
-### Links and References
-
-Check out the [official documentation](https://docs.example.com) for more details.
-
-For keyboard shortcuts, use <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> to open the command palette.
-
----
-
-## Changelog
-
-**v2.4.1** (2024-01-12)
-- Fixed race condition in token refresh logic (#1847)
-- Improved error messages for SAML configurations
-
-**v2.4.0** (2024-01-08)
-- Added support for passkeys/WebAuthn
-- New \`onSessionExpired\` callback hook
-- **Breaking:** Removed deprecated \`legacyMode\` option
-
-*Last updated: January 15, 2024 • Found an issue? [Open a PR](https://github.com/acme/auth-sdk)*`),
- );
-
- events.push(promptResponse(1));
-
- return events;
-}
-
-export const MarkdownShowcase: Story = {
- args: {
- events: buildMarkdownShowcaseConversation(),
- isPromptPending: false,
- repoPath: "/Users/jonathan/dev/posthog-code",
- },
-};
-
-function buildMarkdownDebugConversation(): AcpMessage[] {
- resetCounters();
- const events: AcpMessage[] = [];
-
- events.push(promptRequest("Show me all markdown features"));
-
- events.push(
- agentMessage(`# Heading 1
-## Heading 2
-### Heading 3
-#### Heading 4
-##### Heading 5
-###### Heading 6
-
----
-
-## Text Formatting
-
-Regular paragraph text.
-
-**Bold text**
-
-*Italic text*
-
-***Bold and italic***
-
-~~Strikethrough~~
-
----
-
-## Inline Code
-
-Use \`const x = 1\` for inline code.
-
-Error codes: \`AUTH_INVALID\`, \`RATE_LIMITED\`, \`NOT_FOUND\`
-
----
-
-## Code Blocks
-
-\`\`\`typescript
-interface User {
- id: string;
- name: string;
- email: string;
-}
-
-function getUser(id: string): User {
- return { id, name: "John", email: "[email protected]" };
-}
-\`\`\`
-
-\`\`\`json
-{
- "name": "example",
- "version": "1.0.0",
- "dependencies": {
- "react": "^18.0.0"
- }
-}
-\`\`\`
-
-\`\`\`bash
-$ npm install
-$ npm run build
-$ npm test
-\`\`\`
-
-\`\`\`yaml
-config:
- enabled: true
- options:
- - first
- - second
-\`\`\`
-
----
-
-## Blockquotes
-
-> This is a blockquote.
-
-> **Note:** Important information here.
-
-> Multi-line blockquote
-> continues on next line.
-
----
-
-## Unordered Lists
-
-- Item one
-- Item two
-- Item three
-
-* Also works with asterisks
-* Another item
-
----
-
-## Ordered Lists
-
-1. First item
-2. Second item
-3. Third item
-
----
-
-## Nested Lists
-
-- Parent item
- - Child item
- - Another child
- - Grandchild
-- Back to parent
- 1. Numbered child
- 2. Another numbered
-
-1. Numbered parent
- - Bullet child
- - Another bullet
-2. Second numbered parent
-
----
-
-## Task Lists
-
-- [x] Completed task
-- [x] Another completed
-- [ ] Incomplete task
-- [ ] Another incomplete
-
----
-
-## Links
-
-[Simple link](https://example.com)
-
-[Link with title](https://example.com "Example Site")
-
-Check the [documentation](https://docs.example.com) for more info.
-
----
-
-## Tables
-
-| Header 1 | Header 2 | Header 3 |
-|----------|----------|----------|
-| Cell 1 | Cell 2 | Cell 3 |
-| Cell 4 | Cell 5 | Cell 6 |
-
-| Left | Center | Right |
-|:-----|:------:|------:|
-| L | C | R |
-| L | C | R |
-
----
-
-## Horizontal Rules
-
-Above the rule
-
----
-
-Below the rule
-
-***
-
-Another separator
-
-___
-
-Final separator
-
----
-
-## Mixed Content
-
-Here's a paragraph with **bold**, *italic*, \`code\`, and a [link](https://example.com).
-
-1. List with **bold item**
-2. List with *italic item*
-3. List with \`code item\`
-4. List with [link item](https://example.com)
-
-> Blockquote with **bold**, *italic*, and \`code\`.
-
----
-
-## Edge Cases
-
-**Bold at start** of paragraph.
-
-Paragraph ending with **bold**
-
-*Italic at start* of paragraph.
-
-Paragraph ending with *italic*
-
-\`Code at start\` of paragraph.
-
-Paragraph ending with \`code\`
-
-Empty paragraph below:
-
-Next paragraph after empty.`),
- );
-
- events.push(promptResponse(1));
-
- return events;
-}
-
-export const MarkdownDebug: Story = {
- args: {
- events: buildMarkdownDebugConversation(),
- isPromptPending: false,
- repoPath: "/Users/jonathan/dev/posthog-code",
- },
-};
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx
deleted file mode 100644
index 175408b70dde..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx
+++ /dev/null
@@ -1,592 +0,0 @@
-import { ArrowDown, XCircle } from "@phosphor-icons/react";
-import {
- Button,
- cn,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@posthog/quill";
-import type { AcpMessage } from "@posthog/shared";
-import type { Task } from "@posthog/shared/domain-types";
-import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
-import type {
- ConversationItem,
- TurnContext,
-} from "@posthog/ui/features/sessions/components/buildConversationItems";
-import { ConversationSearchBar } from "@posthog/ui/features/sessions/components/ConversationSearchBar";
-import type { PromptRecallHandler } from "@posthog/ui/features/sessions/components/chat-thread/composerPromptRecall";
-import { MessageJumpPicker } from "@posthog/ui/features/sessions/components/chat-thread/MessageJumpPicker";
-import { THREAD_HOTKEY_OPTIONS } from "@posthog/ui/features/sessions/components/chat-thread/threadHotkeys";
-import { usePromptRecallSource } from "@posthog/ui/features/sessions/components/chat-thread/usePromptRecallSource";
-import { GitActionMessage } from "@posthog/ui/features/sessions/components/GitActionMessage";
-import { GitActionResult } from "@posthog/ui/features/sessions/components/GitActionResult";
-import {
- type ConversationTurn,
- groupRowsIntoTurns,
-} from "@posthog/ui/features/sessions/components/groupConversationTurns";
-import { mergeConversationItems } from "@posthog/ui/features/sessions/components/mergeConversationItems";
-import type {
- ThreadGrouping,
- ThreadRow,
-} from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
-import { createIncrementalThreadGrouper } from "@posthog/ui/features/sessions/components/new-thread/incrementalThreadGrouping";
-import { ToolCallGroupChip } from "@posthog/ui/features/sessions/components/new-thread/ToolCallGroupChip";
-import { SessionFooter } from "@posthog/ui/features/sessions/components/SessionFooter";
-import {
- type RenderItem,
- SessionUpdateView,
-} from "@posthog/ui/features/sessions/components/session-update/SessionUpdateView";
-import { UserMessage } from "@posthog/ui/features/sessions/components/session-update/UserMessage";
-import { UserShellExecuteView } from "@posthog/ui/features/sessions/components/session-update/UserShellExecuteView";
-import {
- VirtualizedList,
- type VirtualizedListHandle,
-} from "@posthog/ui/features/sessions/components/VirtualizedList";
-import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";
-import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useConversationItems";
-import { useConversationSearch } from "@posthog/ui/features/sessions/hooks/useConversationSearch";
-import {
- useOptimisticItemsForTask,
- usePendingPermissionsForTask,
- useQueuedMessagesForTask,
- useSessionForTask,
-} from "@posthog/ui/features/sessions/sessionStore";
-import {
- useGroupOverrides,
- useSessionViewActions,
-} from "@posthog/ui/features/sessions/sessionViewStore";
-import { useThreadScrollRequest } from "@posthog/ui/features/sessions/threadNavigationStore";
-import { SessionTaskIdProvider } from "@posthog/ui/features/sessions/useSessionTaskId";
-import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
-import { TIP_KEYS } from "@posthog/ui/features/settings/tipKeys";
-import { SkillButtonActionMessage } from "@posthog/ui/features/skill-buttons/components/SkillButtonActionMessage";
-import { Box, Flex, Text } from "@radix-ui/themes";
-import {
- memo,
- type RefObject,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { useHotkeys } from "react-hotkeys-hook";
-
-export interface ConversationViewProps {
- events: AcpMessage[];
- isPromptPending: boolean | null;
- promptStartedAt?: number | null;
- repoPath?: string | null;
- taskId?: string;
- task?: Task;
- slackThreadUrl?: string;
- compact?: boolean;
- /**
- * Allow horizontal scrolling of the transcript viewport. Defaults to true.
- * Narrow surfaces (the Agent Builder dock) pass false to avoid a horizontal
- * scrollbar from off-edge content; nested code blocks keep their own scroll.
- */
- scrollX?: boolean;
- /**
- * Filled with the view's prompt recall handler so the composer can forward
- * plain Up/Down presses (caret at the input boundary) to it.
- */
- promptRecallRef?: RefObject<PromptRecallHandler | null>;
- /** See `SharedChatThreadProps.olderHistoryCursor`. */
- olderHistoryCursor?: number;
- isLoadingOlderHistory?: boolean;
- onLoadOlderHistory?: () => void;
-}
-
-export function ConversationView({
- events,
- isPromptPending,
- promptStartedAt,
- repoPath,
- taskId,
- task,
- slackThreadUrl,
- compact = false,
- scrollX = true,
- promptRecallRef,
-}: ConversationViewProps) {
- const listRef = useRef<VirtualizedListHandle>(null);
- const isAtBottomRef = useRef(true);
- const [showScrollButton, setShowScrollButton] = useState(false);
- const debugLogsCloudRuns = useSettingsStore((s) => s.debugLogsCloudRuns);
- const showDebugLogs = debugLogsCloudRuns;
-
- const groupOverrides = useGroupOverrides();
- const sessionViewActions = useSessionViewActions();
-
- // Streaming appends one event per token. The parse is incremental — each
- // event is handled once and completed turns are reused by reference — so per
- // token the work tracks the active turn, not the whole thread. We feed
- // `events` directly (no frame-throttle) so a sent message's optimistic->real
- // swap is never delayed past the frame the store commits it.
- const {
- items: conversationItems,
- lastTurnInfo,
- isCompacting,
- isClearing,
- isBackgroundTurnActive,
- completedToolCallCount,
- lastActivityAt,
- } = useConversationItems(events, isPromptPending, {
- showDebugLogs,
- });
-
- const firstUserMessageIdRef = useRef<string | undefined>(undefined);
- if (firstUserMessageIdRef.current === undefined) {
- firstUserMessageIdRef.current = conversationItems.find(
- (i) => i.type === "user_message",
- )?.id;
- }
- const firstUserMessageId = firstUserMessageIdRef.current;
-
- const [initialItemIds] = useState(
- () =>
- new Set(
- conversationItems
- .filter((i) => i.type === "user_message")
- .map((i) => i.id),
- ),
- );
-
- const pendingPermissions = usePendingPermissionsForTask(taskId ?? "");
- const pendingPermissionsCount = pendingPermissions.size;
- const queuedCount = useQueuedMessagesForTask(taskId).length;
- const optimisticItems = useOptimisticItemsForTask(taskId);
- const session = useSessionForTask(taskId);
- const pausedDurationMs = session?.pausedDurationMs ?? 0;
-
- const isCloud = session?.isCloud ?? false;
-
- const items = useMemo<ConversationItem[]>(
- () =>
- mergeConversationItems({
- conversationItems,
- optimisticItems,
- isCloud,
- }),
- [conversationItems, optimisticItems, isCloud],
- );
-
- // Fold each completed turn's tool-call work into a collapsible chip, and emit
- // the keepMounted indices (standalone MCP-app rows, whose iframes must survive
- // scrolling) + the item→row map in the same pass.
- const threadGrouperRef = useRef<ReturnType<
- typeof createIncrementalThreadGrouper
- > | null>(null);
- threadGrouperRef.current ??= createIncrementalThreadGrouper();
- const threadGrouper = threadGrouperRef.current;
- const grouping = useMemo<ThreadGrouping>(
- () => threadGrouper.update(items, groupOverrides),
- [items, groupOverrides, threadGrouper],
- );
- const threadRows = grouping.rows;
- const rowKeepMounted = grouping.keepMounted;
- const { turns, rowToTurnIndex } = useMemo(
- () => groupRowsIntoTurns(threadRows),
- [threadRows],
- );
- const turnKeepMounted = useMemo(
- () => [...new Set(rowKeepMounted.map((index) => rowToTurnIndex[index]))],
- [rowKeepMounted, rowToTurnIndex],
- );
- const itemIdToTurnIndex = useMemo(() => {
- const result = new Map<string, number>();
- for (const [id, rowIndex] of grouping.idToRowIndex) {
- const turnIndex = rowToTurnIndex[rowIndex];
- if (turnIndex === undefined) {
- throw new Error(`Missing turn for conversation row ${rowIndex}`);
- }
- result.set(id, turnIndex);
- }
- return result;
- }, [grouping.idToRowIndex, rowToTurnIndex]);
-
- const containerRef = useRef<HTMLDivElement>(null);
-
- // Adapter so search (which scrolls by item index) lands on the right row,
- // since grouped rows != items.
- const itemsRef = useRef(items);
- itemsRef.current = items;
- const itemIdToTurnIndexRef = useRef(itemIdToTurnIndex);
- itemIdToTurnIndexRef.current = itemIdToTurnIndex;
- const searchListRef = useRef<VirtualizedListHandle>({
- scrollToBottom: () => listRef.current?.scrollToBottom(),
- scrollToIndex: (index: number) => {
- const id = itemsRef.current[index]?.id;
- const turnIndex =
- id != null ? itemIdToTurnIndexRef.current.get(id) : undefined;
- listRef.current?.scrollToIndex(turnIndex ?? index);
- },
- });
-
- const search = useConversationSearch({
- items,
- containerRef,
- listRef: searchListRef,
- });
-
- const [jumpPickerOpen, setJumpPickerOpen] = useState(false);
- const [keyboardFocusedMessageId, setKeyboardFocusedMessageId] = useState<
- string | null
- >(null);
-
- const userMessages = useMemo(() => {
- const result: Array<{ id: string; index: number; content: string }> = [];
- for (let i = 0; i < items.length; i++) {
- const item = items[i];
- if (item.type === "user_message") {
- result.push({ id: item.id, index: i, content: item.content });
- }
- }
- return result;
- }, [items]);
-
- usePromptRecallSource(userMessages, promptRecallRef);
-
- // Grouped rows != items, so scroll by the row the message landed in (same
- // mapping search uses), falling back to the raw item index.
- const scrollToUserMessage = useCallback((id: string, itemIndex: number) => {
- const turnIndex = itemIdToTurnIndexRef.current.get(id) ?? itemIndex;
- listRef.current?.scrollToIndex(turnIndex);
- }, []);
-
- const handleNavigateMessage = useCallback(
- (direction: -1 | 1) => {
- if (userMessages.length === 0) return;
-
- const currentIndex = keyboardFocusedMessageId
- ? userMessages.findIndex(
- (message) => message.id === keyboardFocusedMessageId,
- )
- : -1;
-
- const nextIndex =
- currentIndex === -1
- ? direction > 0
- ? 0
- : userMessages.length - 1
- : Math.max(
- 0,
- Math.min(userMessages.length - 1, currentIndex + direction),
- );
-
- const nextMessage = userMessages[nextIndex];
- if (!nextMessage) return;
-
- useSettingsStore.getState().markHintLearned(TIP_KEYS.recallMessageNav);
- setKeyboardFocusedMessageId(nextMessage.id);
- scrollToUserMessage(nextMessage.id, nextMessage.index);
- },
- [keyboardFocusedMessageId, userMessages, scrollToUserMessage],
- );
-
- useHotkeys(
- SHORTCUTS.MESSAGE_JUMP,
- () => setJumpPickerOpen((prev) => !prev),
- THREAD_HOTKEY_OPTIONS,
- );
-
- useHotkeys(
- SHORTCUTS.MESSAGE_PREV,
- () => handleNavigateMessage(-1),
- THREAD_HOTKEY_OPTIONS,
- );
-
- useHotkeys(
- SHORTCUTS.MESSAGE_NEXT,
- () => handleNavigateMessage(1),
- THREAD_HOTKEY_OPTIONS,
- );
-
- const clearKeyboardFocus = useCallback(() => {
- setKeyboardFocusedMessageId(null);
- }, []);
-
- const handleJumpToMessage = useCallback(
- (id: string) => {
- const message = userMessages.find((entry) => entry.id === id);
- // Reported, not swallowed: a request for a message this list has not built yet is
- // retried by the caller rather than dropped.
- if (!message) return false;
- setKeyboardFocusedMessageId(id);
- scrollToUserMessage(id, message.index);
- return true;
- },
- [userMessages, scrollToUserMessage],
- );
-
- // The Activity timeline lives in a sibling pane, so it asks for the jump
- // through the store rather than reaching in here.
- useThreadScrollRequest(taskId, handleJumpToMessage);
-
- const handleScrollStateChange = useCallback((isAtBottom: boolean) => {
- isAtBottomRef.current = isAtBottom;
- setShowScrollButton(!isAtBottom);
- }, []);
-
- const scrollToBottom = useCallback(() => {
- listRef.current?.scrollToBottom();
- setShowScrollButton(false);
- }, []);
-
- useEffect(() => {
- const handleVisibilityChange = () => {
- if (!document.hidden && isAtBottomRef.current) {
- listRef.current?.scrollToBottom();
- setShowScrollButton(false);
- }
- };
-
- document.addEventListener("visibilitychange", handleVisibilityChange);
- return () =>
- document.removeEventListener("visibilitychange", handleVisibilityChange);
- }, []);
-
- const renderItem = useCallback(
- (item: ConversationItem) => {
- switch (item.type) {
- case "user_message":
- return (
- <UserMessage
- content={item.content}
- attachments={item.attachments}
- timestamp={item.timestamp}
- animate={!initialItemIds.has(item.id)}
- taskId={taskId}
- keyboardFocused={item.id === keyboardFocusedMessageId}
- sourceUrl={
- slackThreadUrl && item.id === firstUserMessageId
- ? slackThreadUrl
- : undefined
- }
- />
- );
- case "git_action":
- return <GitActionMessage actionType={item.actionType} />;
- case "skill_button_action":
- return <SkillButtonActionMessage buttonId={item.buttonId} />;
- case "session_update":
- return (
- <SessionUpdateRow
- update={item.update}
- turnContext={item.turnContext}
- thoughtComplete={item.thoughtComplete}
- />
- );
- case "git_action_result":
- return repoPath ? (
- <GitActionResult
- actionType={item.actionType}
- repoPath={repoPath}
- turnId={item.turnId}
- />
- ) : null;
- case "turn_cancelled":
- return <TurnCancelledView interruptReason={item.interruptReason} />;
- case "user_shell_execute":
- return <UserShellExecuteView item={item} />;
- }
- },
- [
- repoPath,
- taskId,
- slackThreadUrl,
- firstUserMessageId,
- initialItemIds,
- keyboardFocusedMessageId,
- ],
- );
-
- const getTurnKey = useCallback((turn: ConversationTurn) => turn.id, []);
-
- const renderRow = useCallback(
- (row: ThreadRow) => {
- if (row.kind === "item") return renderItem(row.item);
- return (
- <ToolCallGroupChip
- summary={row.summary}
- expanded={row.expanded}
- turnComplete={row.turnComplete}
- onToggle={() =>
- sessionViewActions.setGroupOverride(row.id, !row.expanded)
- }
- >
- {row.expanded
- ? row.items.map((it) => {
- // Plain assistant text inside the group has no leading icon, so
- // pad it to line up with the tool titles (the text-next-to-icon
- // column = ToolCallBlock's pl-3 + the icon/gap width). Tool and
- // thought rows already carry their own icon indent.
- const isPlainMessage =
- it.type === "session_update" &&
- it.update.sessionUpdate === "agent_message_chunk";
- return (
- <div
- key={it.id}
- className={cn(
- isPlainMessage ? "pl-5" : undefined,
- "empty:hidden",
- )}
- >
- {renderItem(it)}
- </div>
- );
- })
- : null}
- </ToolCallGroupChip>
- );
- },
- [renderItem, sessionViewActions],
- );
-
- const renderTurn = useCallback(
- (turn: ConversationTurn) => (
- <div>
- {turn.rows.map((row) => (
- <div
- key={row.id}
- className="py-1.5"
- data-conversation-item-id={row.id}
- >
- {renderRow(row)}
- </div>
- ))}
- </div>
- ),
- [renderRow],
- );
-
- const footer = (
- <div className={compact ? "pb-1" : "pb-16"}>
- <SessionFooter
- task={task}
- isPromptPending={isPromptPending}
- promptStartedAt={promptStartedAt}
- lastGenerationDuration={
- lastTurnInfo?.isComplete
- ? Math.max(0, lastTurnInfo.durationMs - pausedDurationMs)
- : null
- }
- lastStopReason={lastTurnInfo?.stopReason}
- queuedCount={queuedCount}
- hasPendingPermission={pendingPermissionsCount > 0}
- pausedDurationMs={pausedDurationMs}
- isCompacting={isCompacting}
- isClearing={isClearing}
- isBackgroundTurnActive={isBackgroundTurnActive}
- completedToolCallCount={completedToolCallCount}
- lastActivityAt={lastActivityAt}
- />
- </div>
- );
-
- return (
- <div
- ref={containerRef}
- className="group/thread relative flex-1"
- onPointerDownCapture={clearKeyboardFocus}
- >
- {search.open && (
- <ConversationSearchBar
- ref={search.searchBarRef}
- query={search.query}
- currentMatch={search.currentIndex}
- totalMatches={search.totalMatches}
- onQueryChange={search.setQuery}
- onNext={search.next}
- onPrev={search.prev}
- onClose={search.close}
- />
- )}
-
- <MessageJumpPicker
- open={jumpPickerOpen}
- onOpenChange={setJumpPickerOpen}
- items={items}
- onJumpToMessage={handleJumpToMessage}
- />
-
- <SessionTaskIdProvider taskId={taskId}>
- <VirtualizedList<ConversationTurn>
- ref={listRef}
- items={turns}
- getItemKey={getTurnKey}
- renderItem={renderTurn}
- onScrollStateChange={handleScrollStateChange}
- keepMounted={turnKeepMounted}
- className="absolute inset-0 bg-background"
- itemClassName="mx-auto px-2"
- itemStyle={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}
- footer={footer}
- scrollX={scrollX}
- />
- </SessionTaskIdProvider>
- {showScrollButton && (
- <Box className="absolute right-6 bottom-4 z-10">
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="icon-lg"
- variant="outline"
- onClick={scrollToBottom}
- >
- <ArrowDown size={14} weight="bold" />
- </Button>
- }
- />
- <TooltipContent>Scroll to bottom</TooltipContent>
- </Tooltip>
- </Box>
- )}
- </div>
- );
-}
-
-const SessionUpdateRow = memo(function SessionUpdateRow({
- update,
- turnContext,
- thoughtComplete,
-}: {
- update: RenderItem;
- turnContext: TurnContext;
- thoughtComplete?: boolean;
-}) {
- return (
- <SessionUpdateView
- item={update}
- toolCalls={turnContext.toolCalls}
- childItems={turnContext.childItems}
- turnCancelled={turnContext.turnCancelled}
- turnComplete={turnContext.turnComplete}
- thoughtComplete={thoughtComplete}
- />
- );
-});
-
-const TurnCancelledView = memo(function TurnCancelledView({
- interruptReason,
-}: {
- interruptReason?: string;
-}) {
- const message =
- interruptReason === "moving_to_worktree"
- ? "Paused while worktree is focused"
- : "Interrupted by user";
-
- return (
- <Box className="border-gray-4 border-l-2 py-0.5 pl-3">
- <Flex align="center" gap="2" className="text-gray-9">
- <XCircle size={14} />
- <Text color="gray" className="text-[13px]">
- {message}
- </Text>
- </Flex>
- </Box>
- );
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
index c1907dd8d86f..44ba7526aea1 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -37,6 +37,7 @@ import { PermissionSelector } from "@posthog/ui/features/permissions/PermissionS
import { CloudStreamDisconnectedBanner } from "@posthog/ui/features/sessions/components/CloudSessionLifecycle";
import { ComposerWidth } from "@posthog/ui/features/sessions/components/ComposerWidth";
import { ContextUsageIndicator } from "@posthog/ui/features/sessions/components/ContextUsageIndicator";
+import { AcpChatThread } from "@posthog/ui/features/sessions/components/chat-thread/ChatThread";
import type { PromptRecallHandler } from "@posthog/ui/features/sessions/components/chat-thread/composerPromptRecall";
import {
copyFromContextMenu,
@@ -57,7 +58,6 @@ import {
shouldSubmitComposerOptimistically,
submitComposerPrompt,
} from "@posthog/ui/features/sessions/components/submitComposerPrompt";
-import { ThreadView } from "@posthog/ui/features/sessions/components/ThreadView";
import { usePendingModelSwitch } from "@posthog/ui/features/sessions/components/usePendingModelSwitch";
import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";
import { useAutoCompact } from "@posthog/ui/features/sessions/hooks/useAutoCompact";
@@ -126,7 +126,6 @@ interface SessionViewProps {
onNewSession?: () => void;
isInitializing?: boolean;
isCloud?: boolean;
- slackThreadUrl?: string;
compact?: boolean;
isActiveSession?: boolean;
/** Hide the message input and permission UI — log-only view. */
@@ -163,7 +162,6 @@ export function SessionView({
onNewSession,
isInitializing = false,
isCloud = false,
- slackThreadUrl,
compact = false,
isActiveSession = true,
hideInput = false,
@@ -636,15 +634,13 @@ export function SessionView({
/>
{isSuspended ? (
<>
- <ThreadView
+ <AcpChatThread
events={events}
isPromptPending={isPromptPending}
promptStartedAt={promptStartedAt}
repoPath={repoPath}
taskId={taskId}
task={task}
- slackThreadUrl={slackThreadUrl}
- scrollX={false}
/>
<Box className="border-gray-4 border-t">
<Box
@@ -704,16 +700,13 @@ export function SessionView({
retryLabel={retryLabel}
/>
)}
- <ThreadView
+ <AcpChatThread
events={events}
isPromptPending={isPromptPending}
promptStartedAt={promptStartedAt}
repoPath={repoPath}
taskId={taskId}
task={task}
- slackThreadUrl={slackThreadUrl}
- compact={compact}
- scrollX={false}
promptRecallRef={promptRecallRef}
olderHistoryCursor={olderHistoryCursor}
isLoadingOlderHistory={isLoadingOlderHistory}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ThreadView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ThreadView.tsx
deleted file mode 100644
index b365701d91b2..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/ThreadView.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import type { ConversationViewProps } from "@posthog/ui/features/sessions/components/ConversationView";
-import { AcpChatThread } from "@posthog/ui/features/sessions/components/chat-thread/ChatThread";
-
-/** Props still take `ConversationView`'s shape until that component is deleted. */
-type ThreadViewProps = ConversationViewProps & {
- /** See `SharedChatThreadProps.groupToolCalls`. */
- groupToolCalls?: boolean;
-};
-
-export function ThreadView(props: ThreadViewProps) {
- return <AcpChatThread {...props} />;
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index abfc7e5cb494..b95f84060e85 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -45,20 +45,18 @@ import { ANALYTICS_EVENTS } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import { useSmoothedText } from "@posthog/ui/features/editor/components/useSmoothedText";
-import { hasUiAppResult } from "@posthog/ui/features/mcp-apps/hasUiAppResult";
import {
type BuildResult,
type ConversationItem,
hasSetupProgressForRun,
- type TurnContext,
} from "@posthog/ui/features/sessions/components/buildConversationItems";
import {
ChatMarkdown,
ChatStreamingMarkdown,
} from "@posthog/ui/features/sessions/components/chat-thread/ChatMarkdown";
import { ChatThreadFooter } from "@posthog/ui/features/sessions/components/chat-thread/ChatThreadFooter";
-import { ChatThreadChromeProvider } from "@posthog/ui/features/sessions/components/chat-thread/chatThreadChrome";
import type { PromptRecallHandler } from "@posthog/ui/features/sessions/components/chat-thread/composerPromptRecall";
+import { groupToolRuns } from "@posthog/ui/features/sessions/components/chat-thread/groupToolRuns";
import { MessageJumpPicker } from "@posthog/ui/features/sessions/components/chat-thread/MessageJumpPicker";
import { MessageMinimap } from "@posthog/ui/features/sessions/components/chat-thread/MessageMinimap";
import { ToolGroup } from "@posthog/ui/features/sessions/components/chat-thread/ToolGroup";
@@ -94,11 +92,9 @@ import { GitActionMessage } from "@posthog/ui/features/sessions/components/GitAc
import { GitActionResult } from "@posthog/ui/features/sessions/components/GitActionResult";
import { isUserInitiatedConversationItem } from "@posthog/ui/features/sessions/components/isUserInitiatedConversationItem";
import { mergeConversationItems } from "@posthog/ui/features/sessions/components/mergeConversationItems";
-import { isPlanItem } from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
import { InjectedBlockChips } from "@posthog/ui/features/sessions/components/session-update/InjectedBlockChips";
import { MentionChip } from "@posthog/ui/features/sessions/components/session-update/parseFileMentions";
import { SessionUpdateView } from "@posthog/ui/features/sessions/components/session-update/SessionUpdateView";
-import { isShowActionsItem } from "@posthog/ui/features/sessions/components/session-update/showActionsItem";
import { UserShellExecuteView } from "@posthog/ui/features/sessions/components/session-update/UserShellExecuteView";
import { splitUserMessage } from "@posthog/ui/features/sessions/components/session-update/userMessageDisplay";
import { useVisibleInjectedBlocks } from "@posthog/ui/features/sessions/components/session-update/useVisibleInjectedBlocks";
@@ -152,235 +148,6 @@ import {
} from "react";
import { useHotkeys } from "react-hotkeys-hook";
-type SessionUpdateItem = Extract<ConversationItem, { type: "session_update" }>;
-
-function isToolCallItem(item: ConversationItem): item is SessionUpdateItem {
- return (
- item.type === "session_update" && item.update.sessionUpdate === "tool_call"
- );
-}
-
-function isSessionUpdateItem(
- item: ConversationItem,
-): item is SessionUpdateItem {
- return item.type === "session_update";
-}
-
-/**
- * Session-updates that `SessionUpdateView` always renders as `null`. They produce no row, so they
- * must not break a contiguous tool run.
- */
-const INVISIBLE_UPDATES = new Set([
- "user_message_chunk",
- "tool_call_update",
- "plan",
- "available_commands_update",
- "config_option_update",
-]);
-
-/**
- * True when an item renders nothing, so it should be transparent to tool grouping. Besides the
- * always-null updates, this covers text chunks the stream emits with empty/whitespace or non-text
- * content (a stray empty `agent_message_chunk` between two tool calls is hidden via `empty:hidden`
- * but would otherwise split the run into two ungrouped markers).
- */
-function isInvisibleItem(item: ConversationItem): boolean {
- if (item.type !== "session_update") return false;
- const update = item.update;
- if (INVISIBLE_UPDATES.has(update.sessionUpdate)) return true;
- if (
- update.sessionUpdate === "agent_message_chunk" ||
- update.sessionUpdate === "agent_thought_chunk"
- ) {
- return update.content.type !== "text" || update.content.text.trim() === "";
- }
- return false;
-}
-
-/**
- * A thought joins a tool run instead of breaking it, because between two calls it narrates the
- * stretch of work the run already stands for. The group's body still lists it in order. Prose to
- * the user (`agent_message_chunk`) does break a run, since that is addressed to the reader rather
- * than describing the work.
- */
-function isThoughtItem(item: ConversationItem): boolean {
- return (
- item.type === "session_update" &&
- item.update.sessionUpdate === "agent_thought_chunk"
- );
-}
-
-function isTurnDecided(
- turnContext: TurnContext,
- erroredTurns: Set<TurnContext>,
- supersededTurns: Set<TurnContext>,
- isSessionIdle: boolean,
-): boolean {
- // A cloud turn that errors out never gets a `turn_completed` event.
- if (erroredTurns.has(turnContext)) return true;
- if (!turnContext.turnComplete) return false;
- // `turnComplete` flips true the instant an implicit turn opens, so trust it only once
- // superseded or the session goes idle.
- return turnContext.isImplicit
- ? supersededTurns.has(turnContext) || isSessionIdle
- : true;
-}
-
-function lastRenderableIdsByTurn(
- items: ConversationItem[],
- isSessionIdle: boolean,
-): Map<TurnContext, string> {
- const erroredTurns = new Set<TurnContext>();
- const lastIndexByTurn = new Map<TurnContext, number>();
- let lastSessionUpdateIndex = -1;
- items.forEach((item, index) => {
- if (!isSessionUpdateItem(item)) return;
- lastIndexByTurn.set(item.turnContext, index);
- lastSessionUpdateIndex = index;
- if (item.update.sessionUpdate === "error") {
- erroredTurns.add(item.turnContext);
- }
- });
- const supersededTurns = new Set<TurnContext>();
- for (const [turnContext, lastIndex] of lastIndexByTurn) {
- if (lastIndex < lastSessionUpdateIndex) supersededTurns.add(turnContext);
- }
-
- const out = new Map<TurnContext, string>();
- for (const item of items) {
- if (!isToolCallItem(item)) continue;
- if (
- !isTurnDecided(
- item.turnContext,
- erroredTurns,
- supersededTurns,
- isSessionIdle,
- )
- ) {
- continue;
- }
- if (!hasUiAppResult(item)) continue;
- out.set(item.turnContext, item.id);
- }
- return out;
-}
-
-/**
- * An item that must render as its own row, never folded into a `ToolGroupItem`:
- * a plan awaiting approval, a show-actions handoff, or a call whose result
- * carries a UI app. The next standalone item type joins this predicate instead
- * of widening the condition at the call site.
- *
- * A UI-app call cannot ride in a group, and `keepMounted` on the group body is
- * not the fix. It would keep every collapsed run's body mounted thread-wide,
- * and a chart inside a group still stays invisible until the user expands it:
- * while the run is live the group reads "Thinking…", so a rendered chart would
- * hide behind a collapsed panel. Keeping the chart outside the group is the
- * rule that fixes both.
- */
-function rendersStandalone(
- item: ConversationItem,
- lastRenderableIds: Map<TurnContext, string>,
-): boolean {
- return (
- isPlanItem(item) ||
- isShowActionsItem(item) ||
- (isToolCallItem(item) &&
- lastRenderableIds.get(item.turnContext) === item.id)
- );
-}
-
-/**
- * Collapse each contiguous run of ≥2 tool-call updates into a single `ToolGroupItem`. A run is
- * broken by any *visible* non-tool, non-thought item (prose, status) so groups follow reading
- * order; invisible updates (see {@link INVISIBLE_UPDATES}) are transparent and don't split a run.
- * A lone tool call passes through untouched as a single marker, and so do the thoughts around it:
- * thoughts ride along a run, they never make one. A standalone item (see
- * {@link rendersStandalone}) flushes the run and passes through alone.
- */
-/**
- * Item arrays for settled runs, keyed on the run's (stable) first item.
- *
- * Grouping re-runs over the whole thread on every streamed chunk, so a completed run produces a
- * fresh array with identical contents each time. New identity defeats `ToolGroup`'s `memo`, which
- * makes every settled group above the live one re-render per chunk. Handing back the previous
- * array lets them skip the render.
- *
- * Only safe once the run's turn is complete, because a live tool's status is mutated in place on
- * its resolved `ToolCall`: reusing an array mid-turn would leave a spinner on a tool that has
- * since finished. `len` covers a run that gains items before it settles.
- */
-const settledRunItems = new WeakMap<
- ConversationItem,
- { len: number; items: SessionUpdateItem[] }
->();
-
-function stableRunItems(run: SessionUpdateItem[]): SessionUpdateItem[] {
- if (!run.at(-1)?.turnContext.turnComplete) return run;
- const key = run[0];
- const cached = settledRunItems.get(key);
- if (cached && cached.len === run.length) return cached.items;
- settledRunItems.set(key, { len: run.length, items: run });
- return run;
-}
-
-export function groupToolRuns(
- items: ConversationItem[],
- isPromptPending: boolean | null = true,
-): ThreadItem[] {
- // `=== false` matches `incrementalConversationItems`'s own idle check.
- const lastRenderableIds = lastRenderableIdsByTurn(
- items,
- isPromptPending === false,
- );
- const out: ThreadItem[] = [];
- // The buffer holds the active run in order: tools, the thoughts between them, and any invisible
- // items interleaved with either.
- let buffer: ConversationItem[] = [];
- let toolCount = 0;
-
- const flush = () => {
- const hasEarlierRenderableCall = buffer.some(
- (item) =>
- isToolCallItem(item) &&
- hasUiAppResult(item) &&
- lastRenderableIds.get(item.turnContext) !== item.id,
- );
- if (toolCount >= 2 || hasEarlierRenderableCall) {
- out.push({
- type: "tool_group",
- // Keyed on the first tool call so the id survives thoughts appending around it.
- id: buffer.filter(isToolCallItem)[0].id,
- items: stableRunItems(buffer.filter(isSessionUpdateItem)),
- });
- } else {
- out.push(...buffer);
- }
- buffer = [];
- toolCount = 0;
- };
-
- for (const item of items) {
- if (isToolCallItem(item)) {
- if (rendersStandalone(item, lastRenderableIds)) {
- flush();
- out.push(item);
- continue;
- }
- buffer.push(item);
- toolCount++;
- } else if (isInvisibleItem(item) || isThoughtItem(item)) {
- // Don't break the run; carry it along in order.
- buffer.push(item);
- } else {
- flush();
- out.push(item);
- }
- }
- flush();
- return out;
-}
-
/**
* Collapse each contiguous run of non-user rows into one {@link AgentTurn}, broken only by a
* user-initiated row (which stays standalone so it remains the scroll anchor for the sticky header
@@ -402,7 +169,7 @@ function groupIntoTurns(rows: ThreadItem[]): TurnRow[] {
// git_action and skill_button_action stand in for the user's message when the prompt was a
// git operation or a skill button click (see handlePromptRequest) — they open a turn just
// like a user message, so they break the agent card too rather than render inside it as if
- // they were agent output. Same boundary set as the legacy view's buildThreadGroups.
+ // they were agent output.
if (isUserInitiatedConversationItem(row)) {
flush();
out.push(row);
@@ -1187,10 +954,8 @@ function ThreadScrollBody({
}) {
const keyedRows = useMemo(() => keyTurnRows(rows), [rows]);
- // `group/thread` so the footer's hover-reveal (opacity-50 → 100 on group-hover) tracks the thread,
- // mirroring the legacy ConversationView container. `@container/thread` makes the thread's own
- // width the query basis for everything inside it — the panel is resizable and splittable, so the
- // viewport says nothing useful about how much room a row actually has.
+ // `group/thread` lets the footer's hover reveal track the thread. `@container/thread` makes the
+ // thread's own width the query basis because the panel is resizable and splittable.
return (
<ChatMessageScroller
className="@container/thread group/thread"
@@ -1307,8 +1072,8 @@ const FlatRowView = memo(
* Reuses the existing parse pipeline (`useConversationItems`) and the non-virtualized
* `ChatMessageScroller` (`content-visibility: auto`). User + assistant turns render through
* `ChatMessage`/`ChatBubble` (end-aligned filled / start-aligned ghost) with our own `ChatMarkdown`.
- * Tool calls render as `ChatMarker` — `ChatThreadChromeProvider` flips the shared `ToolRow` chrome
- * to the ChatX primitive, so every tool view is mapped without forking. User messages carry their
+ * Tool calls render as `ChatMarker` through the shared `ToolRow`, so every tool view is mapped
+ * without forking. User messages carry their
* context chips (`ChatMessageHeader`), file/attachment mentions, and a hover timestamp
* (`ChatMessageFooter`) — see `UserBubble`.
*/
@@ -1625,50 +1390,48 @@ function ChatThreadRenderer({
return (
<SessionTaskIdProvider taskId={taskId}>
- <ChatThreadChromeProvider value={true}>
- <ChatMessageScrollerProvider
- // The windowed body owns following itself (anchorTo end + followOnAppend) — the
- // engine's own follow would fight it, so it only auto-scrolls when non-virtualized.
- autoScroll={!virtualized}
- defaultScrollPosition="end"
- // `scrollEdgeThreshold` is left at the engine's tight default on purpose. The engine
- // re-enters "following-bottom" on *every* scroll event taken within the band, which
- // overrides the free-scrolling its own wheel handler just set — so a wide band traps a
- // reader scrolling up out of the bottom, and streamed content yanks them back each
- // frame. `ThreadAutoFollow` is what keeps the thread pinned across the band's width;
- // unlike the engine it only lets go on a real gesture.
- scrollPreviousItemPeek={SCROLL_PREVIOUS_ITEM_PEEK}
- >
- {virtualized ? (
- <VirtualThreadScrollBody
+ <ChatMessageScrollerProvider
+ // The windowed body owns following itself (anchorTo end + followOnAppend) — the
+ // engine's own follow would fight it, so it only auto-scrolls when non-virtualized.
+ autoScroll={!virtualized}
+ defaultScrollPosition="end"
+ // `scrollEdgeThreshold` is left at the engine's tight default on purpose. The engine
+ // re-enters "following-bottom" on *every* scroll event taken within the band, which
+ // overrides the free-scrolling its own wheel handler just set — so a wide band traps a
+ // reader scrolling up out of the bottom, and streamed content yanks them back each
+ // frame. `ThreadAutoFollow` is what keeps the thread pinned across the band's width;
+ // unlike the engine it only lets go on a real gesture.
+ scrollPreviousItemPeek={SCROLL_PREVIOUS_ITEM_PEEK}
+ >
+ {virtualized ? (
+ <VirtualThreadScrollBody
+ items={items}
+ flatRows={flatRows}
+ renderRow={renderWindowedRow}
+ onUserInteract={clearKeyboardFocus}
+ footer={footer}
+ renderNav={renderNav}
+ resumeRef={threadResumeRef}
+ olderHistoryCursor={olderHistoryCursor}
+ isLoadingOlderHistory={isLoadingOlderHistory}
+ onLoadOlderHistory={onLoadOlderHistory}
+ />
+ ) : (
+ <>
+ <ThreadScrollBody
+ autoFollowRef={autoFollowRef}
items={items}
- flatRows={flatRows}
- renderRow={renderWindowedRow}
+ rows={rows}
+ renderItem={renderItem}
+ keyboardFocusedMessageId={keyboardFocusedMessageId}
onUserInteract={clearKeyboardFocus}
footer={footer}
- renderNav={renderNav}
- resumeRef={threadResumeRef}
- olderHistoryCursor={olderHistoryCursor}
- isLoadingOlderHistory={isLoadingOlderHistory}
- onLoadOlderHistory={onLoadOlderHistory}
+ resumeStateRef={threadResumeRef}
/>
- ) : (
- <>
- <ThreadScrollBody
- autoFollowRef={autoFollowRef}
- items={items}
- rows={rows}
- renderItem={renderItem}
- keyboardFocusedMessageId={keyboardFocusedMessageId}
- onUserInteract={clearKeyboardFocus}
- footer={footer}
- resumeStateRef={threadResumeRef}
- />
- {renderNav()}
- </>
- )}
- </ChatMessageScrollerProvider>
- </ChatThreadChromeProvider>
+ {renderNav()}
+ </>
+ )}
+ </ChatMessageScrollerProvider>
</SessionTaskIdProvider>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
index 97d5025cd449..f3a926f6bfee 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
@@ -21,9 +21,7 @@ interface ChatThreadFooterProps {
}
/**
- * The session status footer (duration / queued / diff stats) for the new chat thread, rendered as
- * the last item in the thread. The legacy `ConversationView` renders the same `SessionFooter` the
- * same way. Context usage is not here — it sits in the composer's own toolbar.
+ * The session status footer appears as the last thread item. Context usage stays in the composer toolbar.
*/
export function ChatThreadFooter({
isPromptPending,
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.test.tsx
index a6d7427c175b..045a0818220a 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.test.tsx
@@ -52,6 +52,8 @@ function toolItem(
title: string;
details?: unknown;
toolMeta?: ReturnType<typeof posthogToolMeta>;
+ kind?: "read" | "other";
+ settled?: boolean;
},
): SessionUpdateItem {
return {
@@ -61,8 +63,8 @@ function toolItem(
sessionUpdate: "tool_call",
toolCallId: id,
title: options.title,
- kind: "other",
- status: "in_progress",
+ kind: options.kind ?? "other",
+ status: options.settled ? "completed" : "in_progress",
details: options.details,
_meta: options.toolMeta,
},
@@ -70,7 +72,7 @@ function toolItem(
toolCalls: new Map(),
childItems: new Map(),
turnCancelled: false,
- turnComplete: false,
+ turnComplete: options.settled ?? false,
},
} as SessionUpdateItem;
}
@@ -143,6 +145,14 @@ describe("ToolGroup", () => {
items: [subagentItem("spawn-1"), subagentItem("spawn-2")],
expected: "Ran 2 subagents",
},
+ {
+ name: "summarizes workflows separately from other tool calls",
+ items: [
+ toolItem("read-1", { title: "read-1", kind: "read", settled: true }),
+ toolItem("workflow-1", { title: "workflow", settled: true }),
+ ],
+ expected: "Read a file, ran a workflow",
+ },
{
name: "names the current tool while the run is active",
items: [
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.tsx
index 148df48475a0..c0daf390ace7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ToolGroup.tsx
@@ -16,11 +16,11 @@ import {
} from "framer-motion";
import { memo, useMemo } from "react";
import type { ConversationItem } from "../buildConversationItems";
-import { summarizeMemo } from "../new-thread/buildThreadGroups";
import { isSubagentSpawnTool } from "../session-update/collaborationTools";
import { mcpToolDisplayName } from "../session-update/mcpToolDisplay";
import { SessionUpdateView } from "../session-update/SessionUpdateView";
import { iconForToolCall } from "../session-update/toolCallUtils";
+import { summarizeToolGroupMemo } from "./toolGroupSummary";
type SessionUpdateItem = Extract<ConversationItem, { type: "session_update" }>;
@@ -164,10 +164,14 @@ export const ToolGroup = memo(function ToolGroup({
: null;
// A run with no countable work (a lone streaming thought) keeps the live shape rather than
- // falling back to summarize's "Worked". Cached once the turn completes because the walk is
- // O(run) and the live turn re-renders every group on every streamed chunk.
+ // falling back to the "Worked" summary. The summary is cached once the turn completes because
+ // the live turn re-renders every group on every streamed chunk.
const summary = useMemo(
- () => summarizeMemo(items, items.at(-1)?.turnContext.turnComplete ?? false),
+ () =>
+ summarizeToolGroupMemo(
+ items,
+ items.at(-1)?.turnContext.turnComplete ?? false,
+ ),
[items],
);
const showSummary = !isActive && summary.hasCountableWork;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/chatThreadChrome.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/chatThreadChrome.tsx
deleted file mode 100644
index 914983a260f8..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/chatThreadChrome.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { createContext, useContext } from "react";
-
-/**
- * When true, shared session-update components (notably `ToolRow`) render their chrome with the new
- * ChatX primitives (`ChatMarker`) instead of the legacy Radix chrome. The experimental `ChatThread`
- * turns this on; the production `ConversationView` never provides it, so its rendering is unchanged.
- *
- * This lets one shared `ToolRow` serve both threads — the new thread swaps chrome via context
- * rather than forking every per-tool view.
- */
-const ChatThreadChromeContext = createContext(false);
-
-export const ChatThreadChromeProvider = ChatThreadChromeContext.Provider;
-
-export function useChatThreadChrome(): boolean {
- return useContext(ChatThreadChromeContext);
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
index 1e6fc29b4556..7e8c03d25bd8 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
@@ -1,7 +1,7 @@
import { posthogToolMeta } from "@posthog/shared";
import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
import { describe, expect, it } from "vitest";
-import { groupToolRuns } from "./ChatThread";
+import { groupToolRuns } from "./groupToolRuns";
type SessionUpdateItem = Extract<ConversationItem, { type: "session_update" }>;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.ts
new file mode 100644
index 000000000000..4a8d5969293e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.ts
@@ -0,0 +1,243 @@
+import { readAgentToolName } from "@posthog/shared";
+import { hasUiAppResult } from "@posthog/ui/features/mcp-apps/hasUiAppResult";
+import type {
+ ConversationItem,
+ TurnContext,
+} from "@posthog/ui/features/sessions/components/buildConversationItems";
+import type { ThreadItem } from "@posthog/ui/features/sessions/components/chat-thread/threadVirtualization";
+import { isPlanApprovalTool } from "@posthog/ui/features/sessions/components/session-update/collaborationTools";
+import { isShowActionsItem } from "@posthog/ui/features/sessions/components/session-update/showActionsItem";
+
+type SessionUpdateItem = Extract<ConversationItem, { type: "session_update" }>;
+
+function isToolCallItem(item: ConversationItem): item is SessionUpdateItem {
+ return (
+ item.type === "session_update" && item.update.sessionUpdate === "tool_call"
+ );
+}
+
+function isSessionUpdateItem(
+ item: ConversationItem,
+): item is SessionUpdateItem {
+ return item.type === "session_update";
+}
+
+/**
+ * Session-updates that `SessionUpdateView` always renders as `null`. They produce no row, so they
+ * must not break a contiguous tool run.
+ */
+const INVISIBLE_UPDATES = new Set([
+ "user_message_chunk",
+ "tool_call_update",
+ "plan",
+ "available_commands_update",
+ "config_option_update",
+]);
+
+/**
+ * True when an item renders nothing, so it should be transparent to tool grouping. Besides the
+ * always-null updates, this covers text chunks the stream emits with empty/whitespace or non-text
+ * content (a stray empty `agent_message_chunk` between two tool calls is hidden via `empty:hidden`
+ * but would otherwise split the run into two ungrouped markers).
+ */
+function isInvisibleItem(item: ConversationItem): boolean {
+ if (item.type !== "session_update") return false;
+ const update = item.update;
+ if (INVISIBLE_UPDATES.has(update.sessionUpdate)) return true;
+ if (
+ update.sessionUpdate === "agent_message_chunk" ||
+ update.sessionUpdate === "agent_thought_chunk"
+ ) {
+ return update.content.type !== "text" || update.content.text.trim() === "";
+ }
+ return false;
+}
+
+/**
+ * A thought joins a tool run instead of breaking it, because between two calls it narrates the
+ * stretch of work the run already stands for. The group's body still lists it in order. Prose to
+ * the user (`agent_message_chunk`) does break a run, since that is addressed to the reader rather
+ * than describing the work.
+ */
+function isThoughtItem(item: ConversationItem): boolean {
+ return (
+ item.type === "session_update" &&
+ item.update.sessionUpdate === "agent_thought_chunk"
+ );
+}
+
+function isTurnDecided(
+ turnContext: TurnContext,
+ erroredTurns: Set<TurnContext>,
+ supersededTurns: Set<TurnContext>,
+ isSessionIdle: boolean,
+): boolean {
+ // A cloud turn that errors out never gets a `turn_completed` event.
+ if (erroredTurns.has(turnContext)) return true;
+ if (!turnContext.turnComplete) return false;
+ // `turnComplete` flips true the instant an implicit turn opens, so trust it only once
+ // superseded or the session goes idle.
+ return turnContext.isImplicit
+ ? supersededTurns.has(turnContext) || isSessionIdle
+ : true;
+}
+
+function lastRenderableIdsByTurn(
+ items: ConversationItem[],
+ isSessionIdle: boolean,
+): Map<TurnContext, string> {
+ const erroredTurns = new Set<TurnContext>();
+ const lastIndexByTurn = new Map<TurnContext, number>();
+ let lastSessionUpdateIndex = -1;
+ items.forEach((item, index) => {
+ if (!isSessionUpdateItem(item)) return;
+ lastIndexByTurn.set(item.turnContext, index);
+ lastSessionUpdateIndex = index;
+ if (item.update.sessionUpdate === "error") {
+ erroredTurns.add(item.turnContext);
+ }
+ });
+ const supersededTurns = new Set<TurnContext>();
+ for (const [turnContext, lastIndex] of lastIndexByTurn) {
+ if (lastIndex < lastSessionUpdateIndex) supersededTurns.add(turnContext);
+ }
+
+ const out = new Map<TurnContext, string>();
+ for (const item of items) {
+ if (!isToolCallItem(item)) continue;
+ if (
+ !isTurnDecided(
+ item.turnContext,
+ erroredTurns,
+ supersededTurns,
+ isSessionIdle,
+ )
+ ) {
+ continue;
+ }
+ if (!hasUiAppResult(item)) continue;
+ out.set(item.turnContext, item.id);
+ }
+ return out;
+}
+
+/**
+ * An item that must render as its own row, never folded into a `ToolGroupItem`:
+ * a plan awaiting approval, a show-actions handoff, or a call whose result
+ * carries a UI app. The next standalone item type joins this predicate instead
+ * of widening the condition at the call site.
+ *
+ * A UI-app call cannot ride in a group, and `keepMounted` on the group body is
+ * not the fix. It would keep every collapsed run's body mounted thread-wide,
+ * and a chart inside a group still stays invisible until the user expands it:
+ * while the run is live the group reads "Thinking…", so a rendered chart would
+ * hide behind a collapsed panel. Keeping the chart outside the group is the
+ * rule that fixes both.
+ */
+function rendersStandalone(
+ item: ConversationItem,
+ lastRenderableIds: Map<TurnContext, string>,
+): boolean {
+ const isPlanItem =
+ item.type === "session_update" &&
+ item.update.sessionUpdate === "tool_call" &&
+ (item.update.kind === "switch_mode" ||
+ isPlanApprovalTool(readAgentToolName(item.update._meta)));
+ return (
+ isPlanItem ||
+ isShowActionsItem(item) ||
+ (isToolCallItem(item) &&
+ lastRenderableIds.get(item.turnContext) === item.id)
+ );
+}
+
+/**
+ * Collapse each contiguous run of ≥2 tool-call updates into a single `ToolGroupItem`. A run is
+ * broken by any *visible* non-tool, non-thought item (prose, status) so groups follow reading
+ * order; invisible updates (see {@link INVISIBLE_UPDATES}) are transparent and don't split a run.
+ * A lone tool call passes through untouched as a single marker, and so do the thoughts around it:
+ * thoughts ride along a run, they never make one. A standalone item (see
+ * {@link rendersStandalone}) flushes the run and passes through alone.
+ */
+/**
+ * Item arrays for settled runs, keyed on the run's (stable) first item.
+ *
+ * Grouping re-runs over the whole thread on every streamed chunk, so a completed run produces a
+ * fresh array with identical contents each time. New identity defeats `ToolGroup`'s `memo`, which
+ * makes every settled group above the live one re-render per chunk. Handing back the previous
+ * array lets them skip the render.
+ *
+ * Only safe once the run's turn is complete, because a live tool's status is mutated in place on
+ * its resolved `ToolCall`: reusing an array mid-turn would leave a spinner on a tool that has
+ * since finished. `len` covers a run that gains items before it settles.
+ */
+const settledRunItems = new WeakMap<
+ ConversationItem,
+ { len: number; items: SessionUpdateItem[] }
+>();
+
+function stableRunItems(run: SessionUpdateItem[]): SessionUpdateItem[] {
+ if (!run.at(-1)?.turnContext.turnComplete) return run;
+ const key = run[0];
+ const cached = settledRunItems.get(key);
+ if (cached && cached.len === run.length) return cached.items;
+ settledRunItems.set(key, { len: run.length, items: run });
+ return run;
+}
+
+export function groupToolRuns(
+ items: ConversationItem[],
+ isPromptPending: boolean | null = true,
+): ThreadItem[] {
+ // `=== false` matches `incrementalConversationItems`'s own idle check.
+ const lastRenderableIds = lastRenderableIdsByTurn(
+ items,
+ isPromptPending === false,
+ );
+ const out: ThreadItem[] = [];
+ // The buffer holds the active run in order: tools, the thoughts between them, and any invisible
+ // items interleaved with either.
+ let buffer: ConversationItem[] = [];
+ let toolCount = 0;
+
+ const flush = () => {
+ const hasEarlierRenderableCall = buffer.some(
+ (item) =>
+ isToolCallItem(item) &&
+ hasUiAppResult(item) &&
+ lastRenderableIds.get(item.turnContext) !== item.id,
+ );
+ if (toolCount >= 2 || hasEarlierRenderableCall) {
+ out.push({
+ type: "tool_group",
+ // Keyed on the first tool call so the id survives thoughts appending around it.
+ id: buffer.filter(isToolCallItem)[0].id,
+ items: stableRunItems(buffer.filter(isSessionUpdateItem)),
+ });
+ } else {
+ out.push(...buffer);
+ }
+ buffer = [];
+ toolCount = 0;
+ };
+
+ for (const item of items) {
+ if (isToolCallItem(item)) {
+ if (rendersStandalone(item, lastRenderableIds)) {
+ flush();
+ out.push(item);
+ continue;
+ }
+ buffer.push(item);
+ toolCount++;
+ } else if (isInvisibleItem(item) || isThoughtItem(item)) {
+ // Don't break the run; carry it along in order.
+ buffer.push(item);
+ } else {
+ flush();
+ out.push(item);
+ }
+ }
+ flush();
+ return out;
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/toolGroupSummary.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/toolGroupSummary.ts
new file mode 100644
index 000000000000..ae358383f88f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/toolGroupSummary.ts
@@ -0,0 +1,213 @@
+import {
+ piSubagentToolDetailsSchema,
+ readAgentToolName,
+} from "@posthog/shared";
+import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
+import {
+ isSubagentSpawnTool,
+ isWorkflowTool,
+} from "@posthog/ui/features/sessions/components/session-update/collaborationTools";
+
+type GroupCounts = {
+ execute: number;
+ read: number;
+ list: number;
+ edit: number;
+ delete: number;
+ move: number;
+ search: number;
+ fetch: number;
+ subagents: number;
+ workflows: number;
+ other: number;
+};
+
+type ToolGroupSummary = {
+ doneLabel: string;
+ hasCountableWork: boolean;
+};
+
+function getToolName(update: {
+ _meta?: unknown;
+ title?: string | null;
+}): string | undefined {
+ const toolName = readAgentToolName(update._meta);
+ if (toolName) {
+ return toolName;
+ }
+ return isSubagentSpawnTool(update.title) ? "subagent" : undefined;
+}
+
+function subagentCount(item: ConversationItem): number {
+ if (item.type !== "session_update") {
+ return 0;
+ }
+
+ const update = item.update;
+ if (update.sessionUpdate !== "tool_call") {
+ return 0;
+ }
+
+ const resolved = update.toolCallId
+ ? item.turnContext.toolCalls.get(update.toolCallId)
+ : undefined;
+ const details = resolved?.details ?? update.details;
+ const parsed = piSubagentToolDetailsSchema.safeParse(details);
+ return parsed.success && parsed.data.results.length > 0
+ ? parsed.data.results.length
+ : 1;
+}
+
+function plural(n: number, singular: string, pluralForm: string): string {
+ return `${n} ${n === 1 ? singular : pluralForm}`;
+}
+
+function files(n: number): string {
+ return n === 1 ? "a file" : `${n} files`;
+}
+
+function buildDoneLabel(counts: GroupCounts): string {
+ const segments: string[] = [];
+ if (counts.execute > 0) {
+ segments.push(`ran ${plural(counts.execute, "command", "commands")}`);
+ }
+ if (counts.read > 0) {
+ segments.push(`read ${files(counts.read)}`);
+ }
+ if (counts.list > 0) {
+ segments.push(`listed ${plural(counts.list, "directory", "directories")}`);
+ }
+ if (counts.edit > 0) {
+ segments.push(`edited ${files(counts.edit)}`);
+ }
+ if (counts.delete > 0) {
+ segments.push(`deleted ${files(counts.delete)}`);
+ }
+ if (counts.move > 0) {
+ segments.push(`moved ${files(counts.move)}`);
+ }
+ if (counts.search > 0) {
+ segments.push(`ran ${plural(counts.search, "search", "searches")}`);
+ }
+ if (counts.fetch > 0) {
+ segments.push(`fetched ${plural(counts.fetch, "page", "pages")}`);
+ }
+ if (counts.subagents > 0) {
+ segments.push(`ran ${plural(counts.subagents, "subagent", "subagents")}`);
+ }
+ if (counts.workflows === 1) {
+ segments.push("ran a workflow");
+ }
+ if (counts.workflows > 1) {
+ segments.push(`ran ${counts.workflows} workflows`);
+ }
+ if (counts.other > 0) {
+ segments.push(plural(counts.other, "tool call", "tool calls"));
+ }
+ if (segments.length === 0) {
+ return "Worked";
+ }
+ const joined = segments.join(", ");
+ return joined.charAt(0).toUpperCase() + joined.slice(1);
+}
+
+function summarizeToolGroup(items: ConversationItem[]): ToolGroupSummary {
+ const counts: GroupCounts = {
+ execute: 0,
+ read: 0,
+ list: 0,
+ edit: 0,
+ delete: 0,
+ move: 0,
+ search: 0,
+ fetch: 0,
+ subagents: 0,
+ workflows: 0,
+ other: 0,
+ };
+
+ for (const item of items) {
+ if (item.type !== "session_update") {
+ continue;
+ }
+ const update = item.update;
+ if (update.sessionUpdate !== "tool_call") {
+ continue;
+ }
+
+ const name = getToolName(update);
+ if (isWorkflowTool(name ?? update.title)) {
+ counts.workflows++;
+ } else if (isSubagentSpawnTool(name)) {
+ counts.subagents += subagentCount(item);
+ } else {
+ switch (update.kind ?? null) {
+ case "execute":
+ counts.execute++;
+ break;
+ case "read":
+ counts.read++;
+ break;
+ case "list":
+ counts.list++;
+ break;
+ case "edit":
+ counts.edit++;
+ break;
+ case "delete":
+ counts.delete++;
+ break;
+ case "move":
+ counts.move++;
+ break;
+ case "search":
+ counts.search++;
+ break;
+ case "fetch":
+ counts.fetch++;
+ break;
+ default:
+ counts.other++;
+ break;
+ }
+ }
+ }
+
+ const hasCountableWork =
+ counts.execute +
+ counts.read +
+ counts.list +
+ counts.edit +
+ counts.delete +
+ counts.move +
+ counts.search +
+ counts.fetch +
+ counts.subagents +
+ counts.workflows +
+ counts.other >
+ 0;
+ return { doneLabel: buildDoneLabel(counts), hasCountableWork };
+}
+
+const summaryCache = new WeakMap<
+ ConversationItem,
+ { len: number; summary: ToolGroupSummary }
+>();
+
+export function summarizeToolGroupMemo(
+ items: ConversationItem[],
+ turnComplete: boolean,
+): ToolGroupSummary {
+ const key = items[0];
+ if (turnComplete) {
+ const cached = summaryCache.get(key);
+ if (cached && cached.len === items.length) {
+ return cached.summary;
+ }
+ }
+ const summary = summarizeToolGroup(items);
+ if (turnComplete) {
+ summaryCache.set(key, { len: items.length, summary });
+ }
+ return summary;
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/groupConversationTurns.test.ts b/products/desktop/packages/ui/src/features/sessions/components/groupConversationTurns.test.ts
deleted file mode 100644
index 2ffba9189137..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/groupConversationTurns.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import type { ThreadRow } from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
-import { describe, expect, it } from "vitest";
-import { groupRowsIntoTurns } from "./groupConversationTurns";
-
-function row(item: ConversationItem): ThreadRow {
- return { kind: "item", id: item.id, item };
-}
-
-function userMessage(id: string): ConversationItem {
- return { type: "user_message", id, content: id, timestamp: 0 };
-}
-
-function cancelled(id: string): ConversationItem {
- return { type: "turn_cancelled", id } as ConversationItem;
-}
-
-function userAction(
- id: string,
- type: "git_action" | "skill_button_action",
-): ConversationItem {
- return { type, id } as ConversationItem;
-}
-
-describe("groupRowsIntoTurns", () => {
- it("keeps each prompt and its response in one virtual row", () => {
- const result = groupRowsIntoTurns([
- row(userMessage("user-1")),
- row(cancelled("reply-1")),
- row(userMessage("user-2")),
- row(cancelled("reply-2")),
- ]);
-
- expect(
- result.turns.map((turn) => turn.rows.map((item) => item.id)),
- ).toEqual([
- ["user-1", "reply-1"],
- ["user-2", "reply-2"],
- ]);
- });
-
- it("maps source rows to their virtual turn", () => {
- const result = groupRowsIntoTurns([
- row(userMessage("user-1")),
- row(cancelled("reply-1")),
- row(userMessage("user-2")),
- ]);
-
- expect(result.rowToTurnIndex).toEqual([0, 0, 1]);
- });
-
- it.each(["git_action", "skill_button_action"] as const)(
- "starts a turn for %s",
- (type) => {
- const result = groupRowsIntoTurns([
- row(userMessage("user-1")),
- row(cancelled("reply-1")),
- row(userAction("action-1", type)),
- row(cancelled("reply-2")),
- ]);
-
- expect(
- result.turns.map((turn) => turn.rows.map((item) => item.id)),
- ).toEqual([
- ["user-1", "reply-1"],
- ["action-1", "reply-2"],
- ]);
- },
- );
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/groupConversationTurns.ts b/products/desktop/packages/ui/src/features/sessions/components/groupConversationTurns.ts
deleted file mode 100644
index f8875e8b32ea..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/groupConversationTurns.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { isUserInitiatedConversationItem } from "@posthog/ui/features/sessions/components/isUserInitiatedConversationItem";
-import type { ThreadRow } from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
-
-export interface ConversationTurn {
- id: string;
- rows: ThreadRow[];
-}
-
-function startsConversationTurn(row: ThreadRow): boolean {
- return row.kind === "item" && isUserInitiatedConversationItem(row.item);
-}
-
-export function groupRowsIntoTurns(rows: ThreadRow[]): {
- turns: ConversationTurn[];
- rowToTurnIndex: number[];
-} {
- const turns: ConversationTurn[] = [];
- const rowToTurnIndex: number[] = [];
-
- for (const row of rows) {
- if (turns.length === 0 || startsConversationTurn(row)) {
- turns.push({ id: `turn:${row.id}`, rows: [] });
- }
- const turnIndex = turns.length - 1;
- turns[turnIndex].rows.push(row);
- rowToTurnIndex.push(turnIndex);
- }
-
- return { turns, rowToTurnIndex };
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/ToolCallGroupChip.tsx b/products/desktop/packages/ui/src/features/sessions/components/new-thread/ToolCallGroupChip.tsx
deleted file mode 100644
index 94e8a1cd4ea2..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/ToolCallGroupChip.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { CaretDownIcon, CaretRightIcon } from "@phosphor-icons/react";
-import type { GroupSummary } from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
-import {
- labelForIconKey,
- motion as motionConfig,
-} from "@posthog/ui/features/sessions/components/new-thread/conversationThreadConfig";
-import { ToolRow } from "@posthog/ui/features/sessions/components/session-update/ToolRow";
-import { DotsCircleSpinner } from "@posthog/ui/primitives/DotsCircleSpinner";
-import { Tooltip } from "@posthog/ui/primitives/Tooltip";
-import { motion, useReducedMotion } from "framer-motion";
-import type { ReactNode } from "react";
-
-interface ToolCallGroupChipProps {
- summary: GroupSummary;
- expanded: boolean;
- turnComplete: boolean;
- onToggle: () => void;
- /** Rendered group items, shown inside the ToolRow's box when expanded. */
- children?: ReactNode;
-}
-
-/**
- * A tool-call group is just a ToolRow whose body is the turn's tool work: a
- * collapsible trigger (caret + summary + icon strip) and the same bordered
- * content box. While the turn runs it shows the live action; once complete it
- * shows a verb-led summary.
- */
-export function ToolCallGroupChip({
- summary,
- expanded,
- turnComplete,
- onToggle,
- children,
-}: ToolCallGroupChipProps) {
- const reduceMotion = useReducedMotion();
- const animate = motionConfig.enabled && !reduceMotion;
- const Caret = expanded ? CaretDownIcon : CaretRightIcon;
- // Spin on THIS group's own in-flight tool, not the turn — a turn split across
- // several chips (by messages/plans) must not keep finished chips spinning.
- const running = !turnComplete && summary.active && summary.liveLabel != null;
- // While running, show both what's happened so far (doneLabel reflects the
- // running tallies) and what's happening now (the live tool title), so a
- // collapsed turn reads as actively-working rather than stalled.
- const hasDone = summary.hasCountableWork;
- const label = running
- ? hasDone
- ? `${summary.doneLabel} · ${summary.liveLabel}`
- : (summary.liveLabel as string)
- : summary.doneLabel;
-
- return (
- <motion.div
- initial={animate ? motionConfig.chip.initial : false}
- animate={animate ? motionConfig.chip.animate : undefined}
- transition={animate ? motionConfig.chip.transition : undefined}
- className="pl-3"
- >
- <ToolRow
- collapsible
- open={expanded}
- onOpenChange={onToggle}
- content={children}
- leading={
- <span className="shrink-0 pt-1">
- <Caret
- size={12}
- weight="bold"
- className="text-gray-10 transition-colors group-hover:text-gray-12"
- />
- </span>
- }
- trailing={
- !expanded && summary.icons.length > 0 ? (
- <span className="ml-1 flex shrink-0 items-center gap-1.5 text-gray-9">
- {summary.icons.map(({ Icon, key }) => (
- <Tooltip key={key} content={labelForIconKey(key)}>
- <span className="flex items-center">
- <Icon size={13} />
- </span>
- </Tooltip>
- ))}
- </span>
- ) : null
- }
- >
- <span className="flex min-w-0 items-center gap-1.5 font-medium text-[13px] text-gray-11 transition-colors group-hover:text-gray-12">
- {running ? (
- <DotsCircleSpinner size={12} className="shrink-0 text-gray-10" />
- ) : null}
- <span className="truncate">{label}</span>
- </span>
- </ToolRow>
- </motion.div>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.ts
deleted file mode 100644
index 7773619fc474..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.ts
+++ /dev/null
@@ -1,241 +0,0 @@
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import { describe, expect, it } from "vitest";
-import { buildThreadGroups, isGroupableItem } from "./buildThreadGroups";
-
-function turnContext() {
- return {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- };
-}
-
-function toolCallItem(
- id: string,
- meta: unknown,
- overrides?: Record<string, unknown>,
-): ConversationItem {
- return {
- type: "session_update",
- id,
- update: {
- sessionUpdate: "tool_call",
- toolCallId: id,
- title: `tool ${id}`,
- kind: "other",
- status: "completed",
- _meta: meta,
- ...overrides,
- },
- turnContext: turnContext(),
- } as unknown as ConversationItem;
-}
-
-/** Put the settled call (the one carrying output) in the turn's map, as a
- * tool_call_update does. */
-function resolveToolCall(item: ConversationItem, resolved: unknown): void {
- if (item.type !== "session_update") return;
- item.turnContext.toolCalls.set(
- (resolved as { toolCallId: string }).toolCallId,
- resolved as never,
- );
-}
-
-describe("buildThreadGroups MCP detection", () => {
- it("keeps a tool call with only the posthog meta channel standalone (codex adapters)", () => {
- const mcpItem = toolCallItem("t1", {
- posthog: {
- toolName: "mcp__posthog__exec",
- mcp: { server: "posthog", tool: "exec" },
- },
- });
-
- expect(isGroupableItem(mcpItem)).toBe(false);
-
- const grouping = buildThreadGroups([mcpItem], {});
- expect(grouping.rows).toHaveLength(1);
- expect(grouping.rows[0].kind).toBe("item");
- expect(grouping.keepMounted).toEqual([0]);
- });
-
- it("keeps a tool call with the legacy claudeCode mcp__ name standalone", () => {
- const legacyItem = toolCallItem("t1", {
- claudeCode: { toolName: "mcp__github__search" },
- });
-
- expect(isGroupableItem(legacyItem)).toBe(false);
- const grouping = buildThreadGroups([legacyItem], {});
- expect(grouping.keepMounted).toEqual([0]);
- });
-
- it("keeps an MCP tool standalone when only its result supplies metadata", () => {
- const action = toolCallItem("action", undefined, {
- title: "show_actions",
- rawInput: {
- actions: [
- { kind: "open_space", label: "Open space", channel_id: "space-1" },
- ],
- },
- });
- resolveToolCall(action, {
- toolCallId: "action",
- status: "completed",
- _meta: {
- posthog: {
- toolName: "mcp__posthog-code-tools__show_actions",
- mcp: { server: "posthog-code-tools", tool: "show_actions" },
- },
- },
- });
-
- expect(isGroupableItem(action)).toBe(false);
- const grouping = buildThreadGroups([action], {});
- expect(grouping.rows[0].kind).toBe("item");
- expect(grouping.keepMounted).toEqual([0]);
- });
-
- it("uses the nested PostHog action in a live group label", () => {
- const item = toolCallItem("mcp-exec", undefined, {
- title: "Execute PostHog command",
- status: "in_progress",
- details: {
- kind: "tool",
- name: "mcp_posthog_exec",
- args: '{"command":"call feature-flag-get-all"}',
- },
- });
- if (item.type === "session_update") {
- item.turnContext.turnComplete = false;
- }
-
- const grouping = buildThreadGroups([item], {});
- const row = grouping.rows[0];
- expect(row.kind).toBe("tool_group");
- if (row.kind !== "tool_group") return;
- expect(row.summary.liveLabel).toBe("posthog - Get feature flags");
- });
-
- it("folds non-MCP tool calls into a collapsed group", () => {
- const plain = toolCallItem("t1", {
- posthog: { toolName: "Bash" },
- });
- const alsoPlain = toolCallItem("t2", undefined, { kind: "read" });
-
- const grouping = buildThreadGroups([plain, alsoPlain], {});
- expect(grouping.rows).toHaveLength(1);
- expect(grouping.rows[0].kind).toBe("tool_group");
- expect(grouping.keepMounted).toEqual([]);
- // Both folded items still map to the group's row for find-in-thread.
- expect(grouping.idToRowIndex.get("t1")).toBe(0);
- expect(grouping.idToRowIndex.get("t2")).toBe(0);
- });
-
- it("summarizes a workflow as a workflow, not a generic tool call", () => {
- const items = [
- toolCallItem("read-1", undefined, { kind: "read" }),
- toolCallItem("workflow-1", undefined, { title: "workflow" }),
- ];
-
- const grouping = buildThreadGroups(items, {});
- const row = grouping.rows[0];
- expect(row.kind).toBe("tool_group");
- if (row.kind !== "tool_group") {
- return;
- }
- expect(row.summary.doneLabel).toBe("Read a file, ran a workflow");
- });
-
- it("counts only spawned agents as subagents", () => {
- const items = [
- toolCallItem("spawn-1", {
- posthog: { toolName: "spawn_agent" },
- }),
- toolCallItem("wait-1", {
- posthog: { toolName: "wait_agent" },
- }),
- toolCallItem("close-1", {
- posthog: { toolName: "close_agent" },
- }),
- ];
-
- const grouping = buildThreadGroups(items, {});
- const row = grouping.rows[0];
- expect(row.kind).toBe("tool_group");
- if (row.kind !== "tool_group") return;
- expect(row.summary.counts.subagents).toBe(1);
- expect(row.summary.counts.other).toBe(2);
- expect(row.summary.doneLabel).toBe("Ran 1 subagent, 2 tool calls");
- });
-});
-
-describe("buildThreadGroups artifact detection", () => {
- // A PR's url arrives on the tool_call_update, which lands in the turn's tool
- // call map rather than on the item grouping walks. Reading only the item folds
- // the call into a collapsed group and hides the card the run just earned.
- it("keeps a pull request the run opened as its own row", () => {
- const bash = toolCallItem(
- "bash",
- { posthog: { toolName: "Bash" } },
- { kind: "execute" },
- );
- const create = toolCallItem(
- "create-pr",
- { posthog: { toolName: "Bash" } },
- { kind: "execute", rawInput: { command: "gh pr create --fill" } },
- );
- resolveToolCall(create, {
- toolCallId: "create-pr",
- kind: "execute",
- status: "completed",
- rawInput: { command: "gh pr create --fill" },
- content: [
- {
- type: "content",
- content: {
- type: "text",
- text: "https://github.com/PostHog/posthog/pull/82584",
- },
- },
- ],
- });
-
- expect(isGroupableItem(create)).toBe(false);
-
- const grouping = buildThreadGroups([bash, create], {});
- expect(grouping.rows.map((r) => r.kind)).toEqual(["tool_group", "item"]);
- expect(grouping.idToRowIndex.get("create-pr")).toBe(1);
- });
-});
-
-describe("buildThreadGroups plan detection", () => {
- // The plan tool call is emitted from the model's raw input, and its plan text
- // and switch_mode kind are backfilled by the permission handler. Grouping by
- // kind alone folds an ExitPlanMode call into the collapsed tool group before
- // its kind resolves — burying the plan the user is meant to read. Matching by
- // tool name keeps it as its own row regardless of when the kind arrives.
- it.each([
- ["switch_mode kind", { kind: "switch_mode" }, undefined],
- [
- "ExitPlanMode name, kind not yet resolved",
- { kind: "other" },
- { claudeCode: { toolName: "ExitPlanMode" } },
- ],
- ])(
- "keeps a plan tool call (%s) as its own row, not folded into a group",
- (_label, overrides, meta) => {
- const write = toolCallItem(
- "write",
- { claudeCode: { toolName: "Write" } },
- { kind: "edit" },
- );
- const plan = toolCallItem("plan", meta, overrides);
-
- expect(isGroupableItem(plan)).toBe(false);
-
- const grouping = buildThreadGroups([write, plan], {});
- expect(grouping.rows.map((r) => r.kind)).toEqual(["tool_group", "item"]);
- expect(grouping.idToRowIndex.get("plan")).toBe(1);
- },
- );
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.ts
deleted file mode 100644
index b7547575b8f9..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.ts
+++ /dev/null
@@ -1,434 +0,0 @@
-import type { Icon } from "@phosphor-icons/react";
-import {
- piSubagentToolDetailsSchema,
- readAgentToolName,
- readMcpToolDescriptor,
-} from "@posthog/shared";
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import { isUserInitiatedConversationItem } from "@posthog/ui/features/sessions/components/isUserInitiatedConversationItem";
-import {
- buildDoneLabel,
- type GroupCounts,
- type GroupIconKey,
- grouping,
- MCP_ICON,
- SUBAGENT_ICON,
-} from "@posthog/ui/features/sessions/components/new-thread/conversationThreadConfig";
-import {
- isPlanApprovalTool,
- isSubagentSpawnTool,
- isWorkflowTool,
-} from "@posthog/ui/features/sessions/components/session-update/collaborationTools";
-import { hasInlineArtifact } from "@posthog/ui/features/sessions/components/session-update/inlineArtifacts";
-import { mcpToolDisplayName } from "@posthog/ui/features/sessions/components/session-update/mcpToolDisplay";
-import { iconForToolKind } from "@posthog/ui/features/sessions/components/session-update/toolIcons";
-import type { ToolCall } from "@posthog/ui/features/sessions/types";
-
-export interface GroupIconEntry {
- Icon: Icon;
- key: GroupIconKey;
-}
-
-export interface GroupSummary {
- counts: GroupCounts;
- icons: GroupIconEntry[];
- /** Title of the most recent tool — "what's happening now" while running. */
- liveLabel: string | null;
- /** Verb-led summary shown once the turn completes. */
- doneLabel: string;
- /**
- * This group's last tool call is still pending/in_progress. A turn can span
- * several groups (messages/plans split it), so spin on the group's own work,
- * not the turn — otherwise finished earlier groups keep spinning until the
- * whole turn ends.
- */
- active: boolean;
- /**
- * The group did some countable tool work (i.e. doneLabel is a real summary,
- * not the "Worked" fallback). Lets the chip decide whether to show the
- * summary without depending on the fallback string.
- */
- hasCountableWork: boolean;
-}
-
-/**
- * One rendered row of the new thread. Either a passthrough conversation item or
- * a collapsed tool-call group standing in for a run of work items.
- */
-export type ThreadRow =
- | {
- kind: "item";
- id: string;
- item: ConversationItem;
- }
- | {
- kind: "tool_group";
- id: string;
- items: ConversationItem[];
- summary: GroupSummary;
- turnComplete: boolean;
- expanded: boolean;
- };
-
-export interface ThreadGrouping {
- rows: ThreadRow[];
- /** Row indices of standalone MCP-app items, for the list's keepMounted. */
- keepMounted: number[];
- /** Every item id (incl. those folded into a group) → its row index. */
- idToRowIndex: Map<string, number>;
-}
-
-function getToolName(update: {
- _meta?: unknown;
- title?: string | null;
-}): string | undefined {
- const toolName = readAgentToolName(update._meta);
- if (toolName) {
- return toolName;
- }
- return isSubagentSpawnTool(update.title) ? "subagent" : undefined;
-}
-
-function subagentCount(item: ConversationItem): number {
- if (item.type !== "session_update") {
- return 0;
- }
-
- const update = item.update;
- if (update.sessionUpdate !== "tool_call") {
- return 0;
- }
-
- const resolved = update.toolCallId
- ? item.turnContext.toolCalls.get(update.toolCallId)
- : undefined;
- const details = resolved?.details ?? update.details;
- const parsed = piSubagentToolDetailsSchema.safeParse(details);
- return parsed.success && parsed.data.results.length > 0
- ? parsed.data.results.length
- : 1;
-}
-
-function isMcpToolItem(item: ConversationItem): boolean {
- if (item.type !== "session_update") return false;
- if (item.update.sessionUpdate !== "tool_call") return false;
- const resolved = item.update.toolCallId
- ? item.turnContext.toolCalls.get(item.update.toolCallId)
- : undefined;
- return (
- readMcpToolDescriptor(resolved?._meta ?? item.update._meta) !== undefined
- );
-}
-
-function isAlwaysVisibleItem(item: ConversationItem): boolean {
- return (
- item.type === "session_update" &&
- grouping.alwaysVisibleUpdates.has(item.update.sessionUpdate)
- );
-}
-
-/**
- * The agent's direct text to the user. Never folded — it surfaces as its own
- * chat row so a collapsed turn never swallows something said to the user.
- */
-function isDirectMessageItem(item: ConversationItem): boolean {
- return (
- item.type === "session_update" &&
- item.update.sessionUpdate === "agent_message_chunk"
- );
-}
-
-/**
- * A plan presented for approval (the ExitPlanMode / switch_mode tool call,
- * rendered by PlanApprovalView). Keep it visible so the user can read it.
- */
-export function isPlanItem(item: ConversationItem): boolean {
- return (
- item.type === "session_update" &&
- item.update.sessionUpdate === "tool_call" &&
- (item.update.kind === "switch_mode" ||
- isPlanApprovalTool(readAgentToolName(item.update._meta)))
- );
-}
-
-/**
- * A tool call that hands the user a deliverable (an uploaded file, a pull
- * request it just opened). The card belongs in the thread, so the run that
- * produced it must not fold away behind a "ran 12 commands" summary.
- */
-function isArtifactItem(item: ConversationItem): boolean {
- if (item.type !== "session_update") return false;
- if (item.update.sessionUpdate !== "tool_call") return false;
- const { toolCallId } = item.update;
- // The output a PR is read from arrives on the tool_call_update, which lands
- // in the turn's map rather than on the item this grouping walks.
- const resolved = toolCallId
- ? item.turnContext.toolCalls.get(toolCallId)
- : undefined;
- return hasInlineArtifact(resolved ?? (item.update as unknown as ToolCall));
-}
-
-/**
- * Whether an item folds into a tool-call group rather than getting its own row.
- * A group is a maximal run of these; anything else flushes the run. Grouping is
- * keyed on item type alone, never on turn boundaries — a run can straddle the
- * end of one turn and the start of the next.
- */
-export function isGroupableItem(item: ConversationItem): boolean {
- if (item.type !== "session_update") return false;
- if (grouping.excludeMcpApps && isMcpToolItem(item)) return false;
- if (
- isAlwaysVisibleItem(item) ||
- isDirectMessageItem(item) ||
- isPlanItem(item) ||
- isArtifactItem(item)
- )
- return false;
- return true;
-}
-
-/**
- * Tallies, icons, and live/done labels for a run of grouped items. Exported so the thread's
- * `ToolGroup` reads the same counts, keeping one definition of what "ran 3 commands" means.
- */
-function summarize(items: ConversationItem[]): GroupSummary {
- const counts: GroupCounts = {
- execute: 0,
- read: 0,
- list: 0,
- edit: 0,
- delete: 0,
- move: 0,
- search: 0,
- fetch: 0,
- subagents: 0,
- workflows: 0,
- other: 0,
- };
- let liveLabel: string | null = null;
- let lastToolStatus: string | undefined;
- let trailingThoughtStreaming = false;
- const icons: GroupIconEntry[] = [];
- const seenIcons = new Set<string>();
-
- const addIcon = (Icon: Icon, key: GroupIconKey) => {
- if (seenIcons.has(key) || icons.length >= grouping.maxIconsInChip) return;
- seenIcons.add(key);
- icons.push({ Icon, key });
- };
-
- for (const item of items) {
- if (item.type !== "session_update") continue;
- const update = item.update;
- if (update.sessionUpdate === "tool_call") {
- const resolved = update.toolCallId
- ? item.turnContext.toolCalls.get(update.toolCallId)
- : undefined;
- const displayName = mcpToolDisplayName(
- resolved ?? (update as unknown as ToolCall),
- );
- if (displayName ?? update.title) {
- liveLabel = displayName ?? update.title ?? null;
- }
- lastToolStatus = update.status ?? undefined;
- const name = getToolName(update);
- if (isWorkflowTool(name ?? update.title)) {
- counts.workflows++;
- } else if (isSubagentSpawnTool(name)) {
- counts.subagents += subagentCount(item);
- addIcon(SUBAGENT_ICON, "subagent");
- } else if (readMcpToolDescriptor(update._meta)) {
- counts.other++;
- addIcon(MCP_ICON, "mcp");
- } else {
- const kind = update.kind ?? null;
- switch (kind) {
- case "execute":
- counts.execute++;
- break;
- case "read":
- counts.read++;
- break;
- case "list":
- counts.list++;
- break;
- case "edit":
- counts.edit++;
- break;
- case "delete":
- counts.delete++;
- break;
- case "move":
- counts.move++;
- break;
- case "search":
- counts.search++;
- break;
- case "fetch":
- counts.fetch++;
- break;
- default:
- counts.other++;
- break;
- }
- addIcon(iconForToolKind(kind), `kind:${kind ?? "other"}`);
- }
- }
- // A thought still streaming at the end of the group means the agent is
- // actively thinking — the chip must not read as finished ("Worked").
- if (update.sessionUpdate === "agent_thought_chunk") {
- trailingThoughtStreaming = item.thoughtComplete === false;
- } else if (update.sessionUpdate === "tool_call") {
- trailingThoughtStreaming = false;
- }
- }
-
- if (trailingThoughtStreaming) liveLabel = "Thinking…";
- const active =
- trailingThoughtStreaming ||
- lastToolStatus === "pending" ||
- lastToolStatus === "in_progress";
- const hasCountableWork =
- counts.execute +
- counts.read +
- counts.list +
- counts.edit +
- counts.delete +
- counts.move +
- counts.search +
- counts.fetch +
- counts.subagents +
- counts.workflows +
- counts.other >
- 0;
- return {
- counts,
- icons,
- liveLabel,
- active,
- hasCountableWork,
- doneLabel: buildDoneLabel(counts),
- };
-}
-
-// Completed turns are frozen by reference in the conversation builder, so their
-// group summary never changes — cache it keyed on the group's (stable) first
-// item to avoid re-walking every frozen group on every streamed token. The
-// active (incomplete) turn is never cached, so its live label stays correct.
-const summaryCache = new WeakMap<
- ConversationItem,
- { len: number; summary: GroupSummary }
->();
-
-/**
- * `summarize`, skipping the walk for a run whose turn has completed. Exported so callers rendering
- * many groups per streamed chunk don't re-walk the settled ones.
- */
-export function summarizeMemo(
- leading: ConversationItem[],
- turnComplete: boolean,
-): GroupSummary {
- const key = leading[0];
- if (turnComplete) {
- const cached = summaryCache.get(key);
- if (cached && cached.len === leading.length) return cached.summary;
- }
- const summary = summarize(leading);
- if (turnComplete) summaryCache.set(key, { len: leading.length, summary });
- return summary;
-}
-
-/**
- * Transform the flat conversation items into rows for the new thread, folding
- * each turn's tool-call work into a collapsible group according to the global
- * per-group overrides. Emits the keepMounted indices and
- * item→row map in the same pass so callers don't re-walk the list.
- *
- * Safe to run on every render under useMemo; frozen-turn summaries are cached.
- */
-export function buildThreadGroups(
- items: ConversationItem[],
- overrides: Record<string, boolean>,
-): ThreadGrouping {
- const rows: ThreadRow[] = [];
- const keepMounted: number[] = [];
- const idToRowIndex = new Map<string, number>();
- let buffer: ConversationItem[] = [];
-
- const pushItemRow = (item: ConversationItem): number => {
- const idx = rows.length;
- rows.push({ kind: "item", id: item.id, item });
- idToRowIndex.set(item.id, idx);
- return idx;
- };
-
- const flush = () => {
- if (buffer.length === 0) return;
- const leading = buffer;
- const first = leading[0];
- const turnComplete =
- first.type === "session_update" && first.turnContext.turnComplete;
- const groupId = `group:${first.id}`;
-
- // Groups collapse by default; a per-group override (true=expanded) wins. No chip for a group
- // with no countable tool work (e.g. a lone streaming thought): folding it would hide the only
- // thing happening behind a meaningless "Worked" chip.
- const summary = summarizeMemo(leading, turnComplete);
- const expanded = overrides[groupId] ?? false;
- const chipPresent = summary.hasCountableWork;
-
- if (chipPresent) {
- // The chip owns its children (rendered inside one bordered box when
- // expanded), so they are NOT emitted as separate rows here. Their ids
- // still map to the group's row so find-in-thread can scroll to them.
- const idx = rows.length;
- rows.push({
- kind: "tool_group",
- id: groupId,
- items: leading,
- summary,
- turnComplete,
- expanded,
- });
- for (const item of leading) idToRowIndex.set(item.id, idx);
- } else {
- for (const item of leading) pushItemRow(item);
- }
- buffer = [];
- };
-
- for (const item of items) {
- if (isUserInitiatedConversationItem(item)) {
- flush();
- pushItemRow(item);
- continue;
- }
- switch (item.type) {
- case "session_update": {
- if (isGroupableItem(item)) {
- buffer.push(item);
- } else if (grouping.excludeMcpApps && isMcpToolItem(item)) {
- // Keep MCP-app tool calls standalone so their iframes stay mounted.
- flush();
- keepMounted.push(pushItemRow(item));
- } else {
- // Setup/clone progress, the agent's direct messages, and plans never
- // collapse into a group — they surface as their own chat rows.
- flush();
- pushItemRow(item);
- }
- break;
- }
- default: {
- // git_action_result, turn_cancelled, user_shell_execute, queued —
- // standalone rows that belong to the current turn's epilogue.
- flush();
- pushItemRow(item);
- break;
- }
- }
- }
- flush();
-
- return { rows, keepMounted, idToRowIndex };
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/conversationThreadConfig.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/conversationThreadConfig.ts
deleted file mode 100644
index 9613e2879ac8..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/conversationThreadConfig.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { type Icon, PuzzlePiece, Robot } from "@phosphor-icons/react";
-import type { CodeToolKind } from "@posthog/ui/features/sessions/types";
-
-/**
- * Single source of truth for the modernized conversation thread's tuneable
- * behavior. Everything here is meant to be edited freely — no magic numbers
- * live in the components or the grouping selector.
- */
-
-// ---------- Grouping ----------
-
-export const grouping = {
- /**
- * MCP-app tool calls are excluded from collapsing so their iframes stay
- * mounted (the `keepMounted` contract). Flip to false to fold them in.
- */
- excludeMcpApps: true,
- /**
- * session_update kinds that never fold into a group — always rendered as
- * their own row regardless of collapse mode (e.g. the cloud setup / clone
- * progress card).
- */
- alwaysVisibleUpdates: new Set<string>(["progress_group"]),
- /** Max distinct tool icons shown in a collapsed chip's icon strip. */
- maxIconsInChip: 10,
-} as const;
-
-/** Per-action tallies for a collapsed group. */
-export interface GroupCounts {
- execute: number;
- read: number;
- list: number;
- edit: number;
- delete: number;
- move: number;
- search: number;
- fetch: number;
- subagents: number;
- workflows: number;
- other: number;
-}
-
-function plural(n: number, singular: string, pluralForm: string): string {
- return `${n} ${n === 1 ? singular : pluralForm}`;
-}
-
-function files(n: number): string {
- return n === 1 ? "a file" : `${n} files`;
-}
-
-/**
- * The "done" summary shown once a turn completes — verb-led and action-shaped,
- * e.g. "Ran 25 commands, read a file, edited a file". Tuneable: reorder or
- * reword segments freely.
- */
-export function buildDoneLabel(counts: GroupCounts): string {
- const seg: string[] = [];
- if (counts.execute > 0)
- seg.push(`ran ${plural(counts.execute, "command", "commands")}`);
- if (counts.read > 0) seg.push(`read ${files(counts.read)}`);
- if (counts.list > 0)
- seg.push(`listed ${plural(counts.list, "directory", "directories")}`);
- if (counts.edit > 0) seg.push(`edited ${files(counts.edit)}`);
- if (counts.delete > 0) seg.push(`deleted ${files(counts.delete)}`);
- if (counts.move > 0) seg.push(`moved ${files(counts.move)}`);
- if (counts.search > 0)
- seg.push(`ran ${plural(counts.search, "search", "searches")}`);
- if (counts.fetch > 0)
- seg.push(`fetched ${plural(counts.fetch, "page", "pages")}`);
- if (counts.subagents > 0)
- seg.push(`ran ${plural(counts.subagents, "subagent", "subagents")}`);
- if (counts.workflows === 1) seg.push("ran a workflow");
- if (counts.workflows > 1) seg.push(`ran ${counts.workflows} workflows`);
- if (counts.other > 0)
- seg.push(plural(counts.other, "tool call", "tool calls"));
- if (seg.length === 0) return "Worked";
- const joined = seg.join(", ");
- return joined.charAt(0).toUpperCase() + joined.slice(1);
-}
-
-export const SUBAGENT_ICON: Icon = Robot;
-export const MCP_ICON: Icon = PuzzlePiece;
-
-/** The closed set of `GroupIconEntry.key` values a chip icon can carry. */
-export type GroupIconKey =
- | "subagent"
- | "mcp"
- | `kind:${CodeToolKind}`
- | "kind:other";
-
-/** Human-readable label for a chip icon, keyed by its `GroupIconEntry.key`. */
-const ICON_KEY_LABELS: Partial<Record<GroupIconKey, string>> = {
- subagent: "Spawned a subagent",
- mcp: "Called an MCP tool",
- "kind:read": "Read files",
- "kind:edit": "Edited files",
- "kind:delete": "Deleted files",
- "kind:move": "Moved files",
- "kind:search": "Searched the codebase",
- "kind:execute": "Ran terminal commands",
- "kind:think": "Thought through the problem",
- "kind:fetch": "Fetched a web page",
- "kind:question": "Asked a question",
-};
-
-export function labelForIconKey(key: GroupIconKey): string {
- return ICON_KEY_LABELS[key] ?? "Ran other tools";
-}
-
-// ---------- Motion ----------
-
-/**
- * Motion is scoped to the content layer only — never the virtualizer's row
- * `translateY`, which it owns. All of this collapses to instant when the user
- * prefers reduced motion (handled in the components).
- */
-export const motion = {
- enabled: true,
- /** Group chip mount + the expanded↔chip swap. */
- chip: {
- initial: { opacity: 0 },
- animate: { opacity: 1 },
- transition: { duration: 0.18, ease: "easeOut" as const },
- },
-} as const;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping.test.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping.test.ts
deleted file mode 100644
index 395d77a1a1e1..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import type {
- ConversationItem,
- TurnContext,
-} from "@posthog/ui/features/sessions/components/buildConversationItems";
-import {
- buildThreadGroups,
- type ThreadGrouping,
-} from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
-import { createIncrementalThreadGrouper } from "@posthog/ui/features/sessions/components/new-thread/incrementalThreadGrouping";
-import { describe, expect, it } from "vitest";
-
-const completeContext: TurnContext = {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
-};
-
-const activeContext: TurnContext = {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: false,
-};
-
-function userMessage(id: string): ConversationItem {
- return {
- type: "user_message",
- id,
- content: id,
- timestamp: 1,
- };
-}
-
-function toolItem(
- id: string,
- turnContext: TurnContext = activeContext,
-): ConversationItem {
- return {
- type: "session_update",
- id,
- turnContext,
- update: {
- sessionUpdate: "tool_call",
- toolCallId: id,
- kind: "read",
- title: "Read",
- status: turnContext.turnComplete ? "completed" : "in_progress",
- },
- };
-}
-
-function agentMessage(id: string): ConversationItem {
- return {
- type: "session_update",
- id,
- turnContext: activeContext,
- update: {
- sessionUpdate: "agent_message_chunk",
- content: { type: "text", text: "hello" },
- },
- };
-}
-
-function expectGroupingEquivalent(
- actual: ThreadGrouping,
- expected: ThreadGrouping,
-) {
- expect(actual.rows).toEqual(expected.rows);
- expect(actual.keepMounted).toEqual(expected.keepMounted);
- expect([...actual.idToRowIndex.entries()]).toEqual([
- ...expected.idToRowIndex.entries(),
- ]);
-}
-
-describe("createIncrementalThreadGrouper", () => {
- it("matches a full regroup when appending to the active tool group", () => {
- const grouper = createIncrementalThreadGrouper();
- const overrides = {};
- const items = [
- userMessage("u1"),
- toolItem("t1", completeContext),
- userMessage("u2"),
- toolItem("t2"),
- ];
-
- grouper.update(items, overrides);
-
- const next = [...items, toolItem("t3")];
- expectGroupingEquivalent(
- grouper.update(next, overrides),
- buildThreadGroups(next, overrides),
- );
- });
-
- it("reuses the grouped prefix when appending a standalone row", () => {
- const grouper = createIncrementalThreadGrouper();
- const overrides = {};
- const items = [userMessage("u1"), toolItem("t1", completeContext)];
- const first = grouper.update(items, overrides);
-
- const next = [...items, agentMessage("m1")];
- const second = grouper.update(next, overrides);
-
- expectGroupingEquivalent(second, buildThreadGroups(next, overrides));
- expect(second.rows[0]).toBe(first.rows[0]);
- });
-
- it("matches a full regroup when a streamed tool extends a completed group", () => {
- const grouper = createIncrementalThreadGrouper();
- const overrides = {};
- // A completed turn ending on a tool call, then a new turn's tool call with
- // no message between them: buildThreadGroups folds all three into one group
- // (groups break on item type, not turn completion), so the cut must not
- // split them.
- const items = [
- toolItem("c1", completeContext),
- toolItem("c2", completeContext),
- ];
- grouper.update(items, overrides);
-
- const next = [...items, toolItem("a1", activeContext)];
- expectGroupingEquivalent(
- grouper.update(next, overrides),
- buildThreadGroups(next, overrides),
- );
- });
-
- it("matches a full regroup after a reset-triggering replacement", () => {
- const grouper = createIncrementalThreadGrouper();
- const overrides = {};
- grouper.update(
- [userMessage("u1"), toolItem("t1", completeContext)],
- overrides,
- );
-
- // Same length, entirely new items — breaks the append invariant and forces
- // a full rebuild.
- const replaced = [userMessage("x1"), toolItem("y1", completeContext)];
- expectGroupingEquivalent(
- grouper.update(replaced, overrides),
- buildThreadGroups(replaced, overrides),
- );
- });
-
- it("does not mutate a previously returned grouping", () => {
- const grouper = createIncrementalThreadGrouper();
- const overrides = {};
- const items = [userMessage("u1"), toolItem("t1", completeContext)];
- const first = grouper.update(items, overrides);
- const firstEntries = [...first.idToRowIndex.entries()];
-
- grouper.update([...items, agentMessage("m1")], overrides);
-
- expect([...first.idToRowIndex.entries()]).toEqual(firstEntries);
- });
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping.ts
deleted file mode 100644
index c8b6189752f2..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import {
- buildThreadGroups,
- isGroupableItem,
- type ThreadGrouping,
-} from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
-
-interface Cache {
- items: ConversationItem[];
- overrides: Record<string, boolean>;
- grouping: ThreadGrouping;
- stablePrefixItemCount: number;
-}
-
-/**
- * Caches the grouped prefix of completed turns and only regroups the streamed
- * suffix on each append, instead of re-running buildThreadGroups over the whole
- * transcript every render. Falls back to a full rebuild whenever the input
- * isn't an append of the cached items.
- */
-export function createIncrementalThreadGrouper() {
- let cache: Cache | null = null;
-
- const rebuildAll = (
- items: ConversationItem[],
- overrides: Record<string, boolean>,
- ): ThreadGrouping => {
- const grouping = buildThreadGroups(items, overrides);
- cache = {
- items,
- overrides,
- grouping,
- stablePrefixItemCount: findStablePrefixItemCount(items),
- };
- return grouping;
- };
-
- const update = (
- items: ConversationItem[],
- overrides: Record<string, boolean>,
- ): ThreadGrouping => {
- if (!cache || cache.overrides !== overrides) {
- return rebuildAll(items, overrides);
- }
-
- if (cache.items === items) {
- return cache.grouping;
- }
-
- const stablePrefixItemCount = findStablePrefixItemCount(items);
- const rebuildStart = groupBoundaryAtOrBefore(
- items,
- Math.min(cache.stablePrefixItemCount, stablePrefixItemCount),
- );
-
- // The cut is only safe if the prefix [0, rebuildStart) is unchanged. The
- // boundary item is enough to verify: stable-prefix items are completed turns
- // frozen by reference in the conversation builder, so a matching boundary
- // means the whole prefix matches.
- if (
- rebuildStart > 0 &&
- cache.items[rebuildStart - 1] !== items[rebuildStart - 1]
- ) {
- return rebuildAll(items, overrides);
- }
-
- const prefixRowCount = getPrefixRowCount(
- cache.grouping,
- items,
- rebuildStart,
- );
- const suffixGrouping = buildThreadGroups(
- items.slice(rebuildStart),
- overrides,
- );
-
- const rows = [
- ...cache.grouping.rows.slice(0, prefixRowCount),
- ...suffixGrouping.rows,
- ];
- const keepMounted = [
- ...cache.grouping.keepMounted.filter((idx) => idx < prefixRowCount),
- ...suffixGrouping.keepMounted.map((idx) => idx + prefixRowCount),
- ];
-
- // Build a fresh map rather than mutate cache.grouping's: the previously
- // returned grouping still references that map, and must keep its own row
- // indices. Prefix entries are exactly the ids whose row is below the cut.
- const idToRowIndex = new Map<string, number>();
- for (const [id, idx] of cache.grouping.idToRowIndex) {
- if (idx < prefixRowCount) idToRowIndex.set(id, idx);
- }
- for (const [id, idx] of suffixGrouping.idToRowIndex) {
- idToRowIndex.set(id, idx + prefixRowCount);
- }
-
- const grouping = { rows, keepMounted, idToRowIndex };
- cache = { items, overrides, grouping, stablePrefixItemCount };
- return grouping;
- };
-
- return { update };
-}
-
-/**
- * Index of the first item belonging to the still-streaming tail: walk back over
- * the trailing run of active (not turn-complete) session updates.
- */
-function findStablePrefixItemCount(items: ConversationItem[]): number {
- let count = items.length;
- while (count > 0) {
- const item = items[count - 1];
- if (item.type !== "session_update" || item.turnContext.turnComplete) {
- break;
- }
- count--;
- }
- return count;
-}
-
-/**
- * A foldable group is a run of groupable items broken only by item type, never
- * by turn completion, so a single group can straddle the completed/active
- * boundary. Cutting inside it would split one group into two rows that diverge
- * from a full regroup, so back the cut up to the run's start.
- */
-function groupBoundaryAtOrBefore(
- items: ConversationItem[],
- index: number,
-): number {
- if (
- index === 0 ||
- index >= items.length ||
- !isGroupableItem(items[index - 1]) ||
- !isGroupableItem(items[index])
- ) {
- return index;
- }
- let start = index;
- while (start > 0 && isGroupableItem(items[start - 1])) start--;
- return start;
-}
-
-function getPrefixRowCount(
- grouping: ThreadGrouping,
- items: ConversationItem[],
- rebuildStart: number,
-): number {
- if (rebuildStart === 0) return 0;
-
- // The cut lands on a group boundary, so the boundary item starts its own row;
- // its cached row index is the prefix row count. When that item is newly
- // appended (not in the cache), fall back to the last prefix item's row + 1 —
- // a group-boundary cut guarantees it's the last item of its row.
- const boundaryItem = items[rebuildStart];
- const boundaryRowIndex = boundaryItem
- ? grouping.idToRowIndex.get(boundaryItem.id)
- : undefined;
- if (boundaryRowIndex !== undefined) return boundaryRowIndex;
-
- const lastPrefixItem = items[rebuildStart - 1];
- const lastPrefixRowIndex = lastPrefixItem
- ? grouping.idToRowIndex.get(lastPrefixItem.id)
- : undefined;
- return lastPrefixRowIndex === undefined ? 0 : lastPrefixRowIndex + 1;
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.test.ts b/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.test.ts
index 70fbbbaf6a7c..52311396fff4 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.test.ts
@@ -1,8 +1,5 @@
import { describe, expect, it } from "vitest";
-import {
- formatCompactBoundaryLabel,
- formatLegacyCompactBoundaryDetails,
-} from "./CompactBoundaryView";
+import { formatCompactBoundaryLabel } from "./CompactBoundaryView";
describe("formatCompactBoundaryLabel", () => {
it.each([
@@ -29,25 +26,3 @@ describe("formatCompactBoundaryLabel", () => {
expect(formatCompactBoundaryLabel(props)).toBe(expected);
});
});
-
-describe("formatLegacyCompactBoundaryDetails", () => {
- it.each([
- {
- name: "missing metadata",
- props: {},
- expected: null,
- },
- {
- name: "token count without context size",
- props: { preTokens: 12_400 },
- expected: "~12K tokens summarized",
- },
- {
- name: "percentage and token count",
- props: { preTokens: 75_000, contextSize: 100_000 },
- expected: "75% of context · ~75K tokens summarized",
- },
- ])("formats $name", ({ props, expected }) => {
- expect(formatLegacyCompactBoundaryDetails(props)).toBe(expected);
- });
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.tsx
index 4481d64caedd..fd719cb2d75e 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/CompactBoundaryView.tsx
@@ -1,8 +1,5 @@
-import { Lightning } from "@phosphor-icons/react";
import { ChatMarker, ChatMarkerContent } from "@posthog/quill";
import type { CompactBoundaryMetadata } from "@posthog/ui/features/sessions/types";
-import { Badge, Box, Flex, Text } from "@radix-ui/themes";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
interface CompactBoundaryDisplayMetadata {
trigger?: "manual" | "auto";
@@ -15,18 +12,13 @@ function getCompactBoundaryMetadata({
preTokens,
contextSize,
}: CompactBoundaryMetadata): CompactBoundaryDisplayMetadata {
- const metadata: CompactBoundaryDisplayMetadata = {
- trigger,
- };
+ const metadata: CompactBoundaryDisplayMetadata = { trigger };
- if (preTokens === undefined) {
- return metadata;
- }
+ if (preTokens === undefined) return metadata;
metadata.tokensK = Math.round(preTokens / 1000);
- if (contextSize) {
+ if (contextSize)
metadata.percent = Math.round((preTokens / contextSize) * 100);
- }
return metadata;
}
@@ -36,9 +28,7 @@ export function formatCompactBoundaryLabel(
): string {
const metadata = getCompactBoundaryMetadata(props);
const details: string[] = [];
- if (metadata.trigger) {
- details.push(metadata.trigger);
- }
+ if (metadata.trigger) details.push(metadata.trigger);
if (metadata.percent !== undefined) {
details.push(`${metadata.percent}% of context`);
} else if (metadata.tokensK !== undefined) {
@@ -47,64 +37,16 @@ export function formatCompactBoundaryLabel(
return ["Conversation compacted", ...details].join(" · ");
}
-export function formatLegacyCompactBoundaryDetails(
- props: CompactBoundaryMetadata,
-): string | null {
- const metadata = getCompactBoundaryMetadata(props);
- if (metadata.tokensK === undefined) return null;
- if (metadata.percent !== undefined) {
- return `${metadata.percent}% of context · ~${metadata.tokensK}K tokens summarized`;
- }
- return `~${metadata.tokensK}K tokens summarized`;
-}
-
export function CompactBoundaryView({
trigger,
preTokens,
contextSize,
}: CompactBoundaryMetadata) {
- const metadata = getCompactBoundaryMetadata({
- trigger,
- preTokens,
- contextSize,
- });
- const legacyDetails = formatLegacyCompactBoundaryDetails({
- trigger,
- preTokens,
- contextSize,
- });
- // New thread renders the boundary as a centered separator marker; the legacy thread keeps its
- // bordered badge row so ConversationView is unchanged when the chat thread is off.
- const chatChrome = useChatThreadChrome();
-
- if (chatChrome) {
- return (
- <ChatMarker variant="separator">
- <ChatMarkerContent>
- {formatCompactBoundaryLabel({ trigger, preTokens, contextSize })}
- </ChatMarkerContent>
- </ChatMarker>
- );
- }
-
return (
- <Box className="my-1 border-blue-6 border-l-2 py-1 pl-3 dark:border-blue-8">
- <Flex align="center" gap="2">
- <Lightning size={14} weight="fill" className="text-blue-9" />
- <Text className="text-[13px] text-gray-11">Conversation compacted</Text>
- {metadata.trigger && (
- <Badge
- size="1"
- color={metadata.trigger === "auto" ? "orange" : "blue"}
- variant="soft"
- >
- {metadata.trigger}
- </Badge>
- )}
- {legacyDetails && (
- <Text className="text-[13px] text-gray-9">({legacyDetails})</Text>
- )}
- </Flex>
- </Box>
+ <ChatMarker variant="separator">
+ <ChatMarkerContent>
+ {formatCompactBoundaryLabel({ trigger, preTokens, contextSize })}
+ </ChatMarkerContent>
+ </ChatMarker>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ConversationClearedView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ConversationClearedView.tsx
index 95667fcd18a1..408249b0d893 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ConversationClearedView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ConversationClearedView.tsx
@@ -1,28 +1,9 @@
-import { Eraser } from "@phosphor-icons/react";
-import { ChatMarker, ChatMarkerContent, Text } from "@posthog/quill";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
+import { ChatMarker, ChatMarkerContent } from "@posthog/quill";
-// New thread renders the boundary as a centered separator marker; the legacy
-// thread keeps a bordered row so ConversationView is unchanged when the chat
-// thread is off (mirrors CompactBoundaryView).
export function ConversationClearedView() {
- const chatChrome = useChatThreadChrome();
-
- if (chatChrome) {
- return (
- <ChatMarker variant="separator">
- <ChatMarkerContent>Conversation cleared</ChatMarkerContent>
- </ChatMarker>
- );
- }
-
return (
- <div className="my-1 flex items-center gap-2 border-gray-6 border-l-2 py-1 pl-3 dark:border-gray-8">
- <Eraser size={14} weight="fill" className="text-gray-9" aria-hidden />
- <Text className="text-[13px] text-gray-11">Conversation cleared</Text>
- <Text className="text-[13px] text-gray-9">
- (earlier messages are no longer in the agent's context)
- </Text>
- </div>
+ <ChatMarker variant="separator">
+ <ChatMarkerContent>Conversation cleared</ChatMarkerContent>
+ </ChatMarker>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/EditToolView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/EditToolView.tsx
index 78dd87553dc3..8ce1f0f09367 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/EditToolView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/EditToolView.tsx
@@ -1,6 +1,4 @@
import { PencilSimple } from "@phosphor-icons/react";
-import { Text } from "@radix-ui/themes";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { CodePreview } from "./CodePreview";
import { FileMentionChip } from "./FileMentionChip";
import { ToolRow } from "./ToolRow";
@@ -67,18 +65,12 @@ export function EditToolView({
const hasDiff = diff && (oldText || newText);
const diffStats = diff ? getDiffStats(oldText, newText) : null;
- const isPlanFile = filePath.includes("claude/plans/");
- const chatChrome = useChatThreadChrome();
-
return (
<ToolRow
icon={PencilSimple}
isLoading={isLoading}
isFailed={isFailed}
wasCancelled={wasCancelled}
- // Keep the legacy thread's inline diff behavior, but make tool details
- // opt-in in the experimental thread like every other tool result.
- defaultOpen={chatChrome ? false : !isPlanFile}
content={
hasDiff ? (
<CodePreview
@@ -93,10 +85,10 @@ export function EditToolView({
>
{filePath && <FileMentionChip filePath={filePath} />}
{diffStats && (
- <Text className="font-mono text-[13px]">
+ <span className="font-mono text-[13px]">
<span className="text-green-11">+{diffStats.added}</span>{" "}
<span className="text-red-11">-{diffStats.removed}</span>
- </Text>
+ </span>
)}
</ToolRow>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ExecuteToolView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ExecuteToolView.tsx
index 9959b6d52f1a..20649c63a491 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ExecuteToolView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ExecuteToolView.tsx
@@ -1,7 +1,6 @@
import { Terminal } from "@phosphor-icons/react";
import { compactHomePath } from "@posthog/shared";
import { Tooltip } from "@posthog/ui/primitives/Tooltip";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { ToolRow } from "./ToolRow";
import {
ContentPre,
@@ -41,11 +40,6 @@ export function ExecuteToolView({
// tools whose rawInput carries no `command`.
const headerText = executeInput?.description ?? (command ? undefined : title);
- // The command renders in both chromes but styled differently: the new thread shows it as plain
- // mono text carried by the ChatMarker title; the legacy thread keeps the bordered inline chip so
- // ConversationView is unchanged when the chat thread is toggled off.
- const chatChrome = useChatThreadChrome();
-
const output = stripCodeFences(getContentText(content) ?? "").replace(
ANSI_REGEX,
"",
@@ -68,24 +62,15 @@ export function ExecuteToolView({
content={hasOutput ? <ContentPre>{output}</ContentPre> : undefined}
>
{headerText && <ToolTitle>{headerText}</ToolTitle>}
- {command &&
- (chatChrome ? (
- <ToolTitle className="min-w-0 shrink truncate font-mono">
- <Tooltip content={commandTooltip}>
- <span className="block truncate">
- {truncateText(compactHomePath(command), MAX_COMMAND_LENGTH)}
- </span>
- </Tooltip>
- </ToolTitle>
- ) : (
- <ToolTitle className="min-w-0 shrink truncate">
- <Tooltip content={commandTooltip}>
- <span className="block truncate border border-border bg-gray-5 font-mono">
- {truncateText(compactHomePath(command), MAX_COMMAND_LENGTH)}
- </span>
- </Tooltip>
- </ToolTitle>
- ))}
+ {command && (
+ <ToolTitle className="min-w-0 shrink truncate font-mono">
+ <Tooltip content={commandTooltip}>
+ <span className="block truncate">
+ {truncateText(compactHomePath(command), MAX_COMMAND_LENGTH)}
+ </span>
+ </Tooltip>
+ </ToolTitle>
+ )}
</ToolRow>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ProgressGroupView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ProgressGroupView.tsx
index e5b3efcd76ce..f0075785c622 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ProgressGroupView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ProgressGroupView.tsx
@@ -1,25 +1,17 @@
-import { CaretDown, CaretRight, ListChecks } from "@phosphor-icons/react";
+import { ListChecks } from "@phosphor-icons/react";
import { type Step, StepList } from "@posthog/ui/primitives/StepList";
-import * as Collapsible from "@radix-ui/react-collapsible";
-import { Box, Text } from "@radix-ui/themes";
import { useEffect, useState } from "react";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { ToolRow } from "./ToolRow";
interface ProgressGroupViewProps {
steps: Step[];
- /** True while at least one step in this group is `in_progress`. */
isActive: boolean;
- /** True once the enclosing turn has finished. Drives the auto-collapse. */
turnComplete?: boolean;
}
-// Header label follows the stream: the currently in-flight step's label if
-// any, otherwise the last step seen. No hardcoded fallbacks — the backend
-// controls all wording, including present-tense during `in_progress`.
function resolveHeaderLabel(steps: Step[]): string | null {
if (steps.length === 0) return null;
- const active = steps.find((s) => s.status === "in_progress");
+ const active = steps.find((step) => step.status === "in_progress");
if (active) return active.label;
return steps[steps.length - 1].label;
}
@@ -30,81 +22,24 @@ export function ProgressGroupView({
turnComplete,
}: ProgressGroupViewProps) {
const [userToggledOpen, setUserToggledOpen] = useState<boolean | null>(null);
- // New thread renders the group through the shared `ToolRow` (ChatMarker chrome); the legacy thread
- // keeps its bespoke Radix collapsible so ConversationView is unchanged when the chat thread is off.
- const chatChrome = useChatThreadChrome();
useEffect(() => {
- // Any reactivation clears the sticky user choice so a new round of work
- // starts expanded again.
if (isActive) setUserToggledOpen(null);
}, [isActive]);
if (steps.length === 0) return null;
const hasHeader = steps.length > 1;
-
- // Legacy thread: bespoke collapsible header (caret + summary). While the turn is still running the
- // trigger is disabled and forced open, so the user sees progress stream in without a flicker between
- // consecutive step transitions. Once the turn completes, the header auto-collapses (default: open)
- // and becomes interactive. Single-step groups have no header — the one step row IS the whole view.
const isSettled = turnComplete && !isActive;
- if (!chatChrome) {
- const isOpen = !hasHeader
- ? true
- : !isSettled
- ? true
- : (userToggledOpen ?? true);
- const summaryLabel = resolveHeaderLabel(steps) ?? "";
-
- return (
- <Box className="my-1">
- <Collapsible.Root
- open={isOpen}
- onOpenChange={(next) => {
- if (hasHeader && isSettled) setUserToggledOpen(next);
- }}
- >
- {hasHeader && (
- <Collapsible.Trigger asChild disabled={!isSettled}>
- <button
- type="button"
- className="flex w-full items-center gap-2 rounded-sm px-1 py-0.5 text-left enabled:hover:bg-gray-3 disabled:cursor-default"
- >
- {isOpen ? (
- <CaretDown size={12} className="text-gray-10" />
- ) : (
- <CaretRight size={12} className="text-gray-10" />
- )}
- <Text className="font-medium text-gray-12 text-sm">
- {summaryLabel}
- </Text>
- </button>
- </Collapsible.Trigger>
- )}
- <Collapsible.Content>
- <Box pl={hasHeader ? "4" : "0"} py="1">
- <StepList steps={steps} />
- </Box>
- </Collapsible.Content>
- </Collapsible.Root>
- </Box>
- );
- }
-
- // New thread: single-step groups have no header, so their body must stay expanded — collapsing with
- // no header would leave nothing on screen.
if (!hasHeader) {
return (
- <Box className="my-1">
+ <div className="my-1">
<StepList steps={steps} />
- </Box>
+ </div>
);
}
- // Multi-step groups stay open while the turn is running, then honour the user
- // toggle once the turn completes (default: collapsed).
const isOpen = !isSettled ? true : (userToggledOpen ?? false);
const summaryLabel = resolveHeaderLabel(steps) ?? "";
@@ -114,8 +49,6 @@ export function ProgressGroupView({
isLoading={isActive}
open={isOpen}
onOpenChange={(next) => {
- // Only the user's choice (after the turn finishes) sticks; while running
- // the row is controlled open, so a stray toggle is ignored.
if (isSettled) setUserToggledOpen(next);
}}
content={<StepList steps={steps} />}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx
index e8dd9c5562f3..51e765d40127 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx
@@ -1,14 +1,8 @@
-import {
- ArrowsClockwise,
- ShieldWarning,
- Warning,
- XCircle,
-} from "@phosphor-icons/react";
+import { ArrowsClockwise, ShieldWarning } from "@phosphor-icons/react";
import { ChatMarker, ChatMarkerContent } from "@posthog/quill";
import { Spin, Spinner } from "@posthog/ui/primitives/Spinner";
import { Box, Callout, Flex, Text } from "@radix-ui/themes";
import { useEffect, useState } from "react";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { formatDuration } from "../GeneratingIndicator";
interface StatusNotificationViewProps {
@@ -73,12 +67,7 @@ export function StatusNotificationView({
maxAttempts,
delayMs,
}: StatusNotificationViewProps) {
- // New thread renders status notes as centered separator markers; the legacy thread keeps its
- // bordered rows so ConversationView is unchanged when the chat thread is off.
- const chatChrome = useChatThreadChrome();
-
- // Terminal refusal: the safety classifier declined the request and no
- // fallback model rescued it. Rendered as a callout in both chromes.
+ // Terminal refusal: the safety classifier declined the request and no fallback model rescued it.
if (status === "refusal") {
return (
<Box className="my-2">
@@ -105,20 +94,10 @@ export function StatusNotificationView({
}
if (status === "process_killed" && message) {
- if (chatChrome) {
- return (
- <ChatMarker variant="separator">
- <ChatMarkerContent>{message}</ChatMarkerContent>
- </ChatMarker>
- );
- }
return (
- <div className="my-1 border-orange-6 border-l-2 py-1 pl-3 dark:border-orange-8">
- <div className="flex items-center gap-2">
- <Warning size={14} weight="fill" className="text-orange-9" />
- <span className="text-[13px] text-muted-foreground">{message}</span>
- </div>
- </div>
+ <ChatMarker variant="separator">
+ <ChatMarkerContent>{message}</ChatMarkerContent>
+ </ChatMarker>
);
}
@@ -127,20 +106,10 @@ export function StatusNotificationView({
fromModel && toModel
? `${fromModel} declined this request, retried with ${toModel}`
: "Request declined, retried with the fallback model";
- if (chatChrome) {
- return (
- <ChatMarker variant="separator">
- <ChatMarkerContent>{message}</ChatMarkerContent>
- </ChatMarker>
- );
- }
return (
- <Box className="my-1 border-orange-6 border-l-2 py-1 pl-3 dark:border-orange-8">
- <Flex align="center" gap="2">
- <ArrowsClockwise size={14} className="text-orange-9" />
- <Text className="text-[13px] text-gray-11">{message}</Text>
- </Flex>
- </Box>
+ <ChatMarker variant="separator">
+ <ChatMarkerContent>{message}</ChatMarkerContent>
+ </ChatMarker>
);
}
@@ -148,20 +117,10 @@ export function StatusNotificationView({
// is cleared separately; this row reports the outcome.
if (status === "compacting_failed") {
const failureMessage = formatCompactionFailure(error);
- if (chatChrome) {
- return (
- <ChatMarker variant="separator">
- <ChatMarkerContent>{failureMessage}</ChatMarkerContent>
- </ChatMarker>
- );
- }
return (
- <Box className="my-1 border-gray-6 border-l-2 py-1 pl-3 dark:border-gray-8">
- <Flex align="center" gap="2">
- <XCircle size={14} className="text-gray-9" />
- <Text className="text-[13px] text-gray-11">{failureMessage}</Text>
- </Flex>
- </Box>
+ <ChatMarker variant="separator">
+ <ChatMarkerContent>{failureMessage}</ChatMarkerContent>
+ </ChatMarker>
);
}
@@ -192,20 +151,10 @@ export function StatusNotificationView({
// reports the outcome.
if (status === "clearing_failed") {
const message = error ? `Clear failed: ${error}` : "Clear failed";
- if (chatChrome) {
- return (
- <ChatMarker variant="separator">
- <ChatMarkerContent>{message}</ChatMarkerContent>
- </ChatMarker>
- );
- }
return (
- <Box className="my-1 border-gray-6 border-l-2 py-1 pl-3 dark:border-gray-8">
- <Flex align="center" gap="2">
- <XCircle size={14} className="text-gray-9" aria-hidden />
- <Text className="text-[13px] text-gray-11">{message}</Text>
- </Flex>
- </Box>
+ <ChatMarker variant="separator">
+ <ChatMarkerContent>{message}</ChatMarkerContent>
+ </ChatMarker>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.test.tsx
index 7a88f3ac6b96..188b5717b33c 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.test.tsx
@@ -3,7 +3,6 @@ import type {
ConversationItem,
TurnContext,
} from "@posthog/ui/features/sessions/components/buildConversationItems";
-import { ChatThreadChromeProvider } from "@posthog/ui/features/sessions/components/chat-thread/chatThreadChrome";
import type { ToolCall } from "@posthog/ui/features/sessions/types";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
@@ -78,19 +77,17 @@ describe("SubagentToolView", () => {
render(
<QueryClientProvider client={new QueryClient()}>
<ServiceProvider container={new Container()}>
- <ChatThreadChromeProvider value>
- <SubagentToolView
- toolCall={{
- toolCallId: "agent",
- title: "Test nested actions",
- kind: "think",
- status: "completed",
- }}
- childItems={childItems}
- turnContext={turnContext}
- turnComplete
- />
- </ChatThreadChromeProvider>
+ <SubagentToolView
+ toolCall={{
+ toolCallId: "agent",
+ title: "Test nested actions",
+ kind: "think",
+ status: "completed",
+ }}
+ childItems={childItems}
+ turnContext={turnContext}
+ turnComplete
+ />
</ServiceProvider>
</QueryClientProvider>,
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.tsx
index 2f1038fcc968..303ad61889e1 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/SubagentToolView.tsx
@@ -1,19 +1,11 @@
-import {
- ArrowsInSimple as ArrowsInSimpleIcon,
- ArrowsOutSimple as ArrowsOutSimpleIcon,
- Robot,
-} from "@phosphor-icons/react";
+import { Robot } from "@phosphor-icons/react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@posthog/quill";
import {
LoadingIcon,
- StatusIndicators,
type ToolViewProps,
useToolCallStatus,
} from "@posthog/ui/features/sessions/components/session-update/toolCallUtils";
-import { Box, Flex, IconButton, Text } from "@radix-ui/themes";
-import { useState } from "react";
import type { ConversationItem, TurnContext } from "../buildConversationItems";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { SessionUpdateView } from "./SessionUpdateView";
import { isShowActionsItem } from "./showActionsItem";
import { ToolRow } from "./ToolRow";
@@ -23,11 +15,6 @@ interface SubagentToolViewProps extends ToolViewProps {
turnContext: TurnContext;
}
-/**
- * A subagent (Task/Agent) call. The new thread renders it as a single `ToolRow` (ChatMarker chrome)
- * whose collapsible body holds the subagent's own child tool calls. The legacy thread keeps its
- * bespoke bordered box + expand button so ConversationView is unchanged when the chat thread is off.
- */
export function SubagentToolView({
toolCall,
turnCancelled,
@@ -41,8 +28,6 @@ export function SubagentToolView({
turnCancelled,
turnComplete,
);
- const chatChrome = useChatThreadChrome();
- const [isExpanded, setIsExpanded] = useState(false);
const renderItems = (items: ConversationItem[]) =>
items.map((child) =>
@@ -57,63 +42,6 @@ export function SubagentToolView({
/>
) : null,
);
- const hasChildren = childItems.length > 0;
- const childContent = hasChildren ? renderItems(childItems) : undefined;
-
- // Legacy thread: bespoke bordered box with an expand toggle.
- if (!chatChrome) {
- return (
- <Box className="max-w-4xl overflow-hidden rounded-sm border border-gray-6 bg-gray-1">
- <button
- type="button"
- onClick={() => setIsExpanded(!isExpanded)}
- className="flex w-full cursor-pointer items-center justify-between border-none bg-transparent px-3 py-2"
- >
- <Flex align="center" gap="2">
- <Tooltip>
- <TooltipTrigger
- render={
- <span className="flex items-center">
- <LoadingIcon
- icon={Robot}
- isLoading={isLoading}
- className="text-gray-10"
- />
- </span>
- }
- />
- <TooltipContent side="top">
- Delegated to a subagent
- </TooltipContent>
- </Tooltip>
- <Text className="text-[13px] text-gray-10">
- <span className="font-medium text-gray-12">Subagent</span>
- {title && title !== "Subagent" ? ` · ${title}` : ""}
- </Text>
- <StatusIndicators isFailed={isFailed} wasCancelled={wasCancelled} />
- </Flex>
- {hasChildren && (
- <IconButton asChild size="1" variant="ghost" color="gray">
- <span>
- {isExpanded ? (
- <ArrowsInSimpleIcon size={12} />
- ) : (
- <ArrowsOutSimpleIcon size={12} />
- )}
- </span>
- </IconButton>
- )}
- </button>
-
- {isExpanded && hasChildren && (
- // [&_.tool-row-collapsible]:pl-1 so that inner ToolRow triggers have some more spacing on left
- <Box className="space-y-1 border-gray-6 border-t px-2 py-2 [&_.tool-row-collapsible]:pl-1">
- {childContent}
- </Box>
- )}
- </Box>
- );
- }
const nestedItems: ConversationItem[] = [];
const actionItems: ConversationItem[] = [];
@@ -127,8 +55,6 @@ export function SubagentToolView({
nestedItems.length > 0 ? renderItems(nestedItems) : undefined;
const actionContent = renderItems(actionItems);
- // New thread: same minimal shape as ThoughtView — a single ToolRow whose collapsible body holds the
- // subagent's child tool calls. ToolRow supplies the ChatMarker chrome, so no bespoke box here.
return (
<div>
<ToolRow
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ThoughtView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ThoughtView.tsx
index 9b3d917bfa04..1b19fdb472b6 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ThoughtView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ThoughtView.tsx
@@ -1,6 +1,5 @@
import { Brain } from "@phosphor-icons/react";
import { memo } from "react";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { ToolRow } from "./ToolRow";
import { ContentPre } from "./toolCallUtils";
@@ -14,10 +13,6 @@ export const ThoughtView = memo(function ThoughtView({
isLoading,
}: ThoughtViewProps) {
const hasContent = content.trim().length > 0;
- // New thread reads back in past tense once the thought is done; the legacy thread keeps "Thinking"
- // so ConversationView is unchanged when the chat thread is toggled off.
- const chatChrome = useChatThreadChrome();
-
// An empty thought that's done streaming is pure noise — a bare "Thinking"
// header with nothing under it. Only show it while content is still arriving.
if (!hasContent && !isLoading) return null;
@@ -29,7 +24,7 @@ export const ThoughtView = memo(function ThoughtView({
isLoading={isLoading}
content={hasContent ? <ContentPre>{content}</ContentPre> : undefined}
>
- {chatChrome && !isLoading ? "Thought" : "Thinking"}
+ {!isLoading ? "Thought" : "Thinking"}
</ToolRow>
</div>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.stories.tsx
index 980d89254120..17b716b45b67 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.stories.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.stories.tsx
@@ -529,7 +529,7 @@ export const ExecuteCommandLongInput: Story = {
type: "text",
text: `apps/code/src/renderer/components/permissions/types.ts
apps/code/src/renderer/features/sessions/types.ts
-apps/code/src/renderer/features/sessions/components/ConversationView.tsx
+packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
packages/agent/src/adapters/claude/conversion/tool-use-to-acp.ts`,
},
},
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx
index 77aea996d436..408aa1672ad0 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx
@@ -20,9 +20,7 @@ import {
useToolCallStatus,
} from "@posthog/ui/features/sessions/components/session-update/toolCallUtils";
import type { ToolCall } from "@posthog/ui/features/sessions/types";
-import { Box } from "@radix-ui/themes";
import type { ConversationItem, TurnContext } from "../buildConversationItems";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { isPlanApprovalTool, isSubagentSpawnTool } from "./collaborationTools";
import { CreatedPrCard, UploadedArtifactCard } from "./InlineArtifactCard";
import {
@@ -50,7 +48,6 @@ export function ToolCallBlock({
);
const toolName = readAgentToolName(toolCall._meta);
const mcpToolName = readMcpToolName(toolCall._meta);
- const chatChrome = useChatThreadChrome();
const { isComplete } = useToolCallStatus(
toolCall.status,
turnCancelled,
@@ -73,11 +70,7 @@ export function ToolCallBlock({
// An artifact is a deliverable, not a step: it takes the row rather than the
// tool's own header, from the moment the agent starts handing it over.
if (isUploadArtifactCall(toolCall._meta)) {
- return (
- <Box className={chatChrome ? "" : "pl-3"}>
- <UploadedArtifactCard {...props} />
- </Box>
- );
+ return <UploadedArtifactCard {...props} />;
}
// The buttons are the point of the call, not a step it took, so a completed
@@ -86,7 +79,7 @@ export function ToolCallBlock({
// which shows why it failed rather than live buttons the block never stopped.
if (isShowActionsCall(toolCall._meta) && isComplete) {
return (
- <div className={chatChrome ? "my-1" : "my-1 pl-3"}>
+ <div className="my-1">
<ShowActionsRow {...props} />
</div>
);
@@ -103,35 +96,29 @@ export function ToolCallBlock({
turnComplete: turnComplete ?? false,
};
return (
- <Box>
- <SubagentToolView
- {...props}
- childItems={subagentChildItems}
- turnContext={turnContext}
- />
- </Box>
+ <SubagentToolView
+ {...props}
+ childItems={subagentChildItems}
+ turnContext={turnContext}
+ />
);
}
if (mcpToolName) {
return (
- <Box className={chatChrome ? "" : "pl-3"}>
+ <>
{McpToolBlock ? (
<McpToolBlock {...props} mcpToolName={mcpToolName} />
) : (
<ToolCallView {...props} agentToolName={mcpToolName} />
)}
{createdPrUrl && <CreatedPrCard url={createdPrUrl} />}
- </Box>
+ </>
);
}
if (isPlanApprovalTool(toolName)) {
- return (
- <Box>
- <PlanApprovalView {...props} />
- </Box>
- );
+ return <PlanApprovalView {...props} />;
}
const content = (() => {
@@ -164,10 +151,10 @@ export function ToolCallBlock({
})();
return (
- <Box>
+ <>
{content}
{createdPrUrl && <CreatedPrCard url={createdPrUrl} />}
- </Box>
+ </>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallView.tsx
index 2c761a013f5c..7b17c153dad9 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallView.tsx
@@ -7,18 +7,14 @@ import {
readPiMcpCallDetails,
} from "@posthog/shared";
import type { ToolCall } from "@posthog/ui/features/sessions/types";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { ToolRow } from "./ToolRow";
import {
- ContentPre,
compactInput,
- formatInput,
- getContentText,
getFilename,
iconForToolCall,
- stripCodeFences,
ToolTitle,
type ToolViewProps,
+ toolCallDetails,
useToolCallStatus,
} from "./toolCallUtils";
@@ -100,10 +96,6 @@ export function ToolCallView({
turnComplete,
);
const KindIcon = iconForToolCall(toolCall, agentToolName);
- // New thread drops the input/output divider (ContentPre carries its own border); the legacy thread
- // keeps it so ConversationView is unchanged when the chat thread is toggled off.
- const chatChrome = useChatThreadChrome();
-
const filePath = kind === "read" && locations?.[0]?.path;
const toolDisplay = agentToolName
? toolNameDisplays[agentToolName]
@@ -118,14 +110,12 @@ export function ToolCallView({
: undefined;
const mcpDisplay = mcpProxyDisplay(toolCall);
- // New thread reads back in past tense once the tool has finished ("Reading" → "Read"); the legacy
- // thread keeps the original present-tense prefix so ConversationView is unchanged when toggled off.
const displayText =
mcpDisplay?.title ??
(specialDisplay
- ? chatChrome && !isLoading
- ? specialDisplay.pastPrefix
- : specialDisplay.prefix
+ ? isLoading
+ ? specialDisplay.prefix
+ : specialDisplay.pastPrefix
: filePath
? `Read ${getFilename(filePath)}`
: title
@@ -135,28 +125,6 @@ export function ToolCallView({
const inputPreview = mcpDisplay
? mcpDisplay.input
: (specialDisplay?.value ?? compactInput(rawInput));
- const fullInput = formatInput(rawInput);
-
- const output = stripCodeFences(getContentText(content) ?? "");
- const hasOutput = output.trim().length > 0;
- // Surface output for failures too, otherwise a failed call shows "(Failed)"
- // with no reason — the error text lives in `content`.
- const showOutput = (isComplete || isFailed) && hasOutput;
-
- const body =
- fullInput || showOutput ? (
- <>
- {fullInput && <ContentPre>{fullInput}</ContentPre>}
- {showOutput &&
- (chatChrome ? (
- <ContentPre>{output}</ContentPre>
- ) : (
- <div className={fullInput ? "border-gray-6 border-t" : undefined}>
- <ContentPre>{output}</ContentPre>
- </div>
- ))}
- </>
- ) : undefined;
return (
<ToolRow
@@ -165,22 +133,12 @@ export function ToolCallView({
isFailed={isFailed}
wasCancelled={wasCancelled}
defaultOpen={expanded}
- content={body}
+ content={toolCallDetails({ rawInput, content, isComplete, isFailed })}
>
{displayText && <ToolTitle>{displayText}</ToolTitle>}
{inputPreview && (
- // `min-w-0 shrink` overrides the title's default `shrink-0`: the input preview is the
- // flexible piece of the header, so it gives way (and truncates) instead of overflowing.
- <ToolTitle className="min-w-0 shrink">
- <span
- className={
- chatChrome
- ? "font-mono text-primary text-sm"
- : "font-mono text-accent-11"
- }
- >
- {inputPreview}
- </span>
+ <ToolTitle>
+ <span className="font-mono text-primary text-sm">{inputPreview}</span>
</ToolTitle>
)}
{specialDisplay && <ToolTitle>{specialDisplay.suffix}</ToolTitle>}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolRow.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolRow.tsx
index 2b14a2701f48..f71ec101b2a7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolRow.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolRow.tsx
@@ -1,4 +1,3 @@
-import { Collapsible } from "@base-ui/react/collapsible";
import { type Icon, WrenchIcon } from "@phosphor-icons/react";
import {
ChatMarker,
@@ -7,52 +6,22 @@ import {
cn,
} from "@posthog/quill";
import { Spinner } from "@posthog/ui/primitives/Spinner";
-import { type ReactNode, useState } from "react";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
-import {
- ExpandableIcon,
- LoadingIcon,
- StatusIndicators,
- ToolTitle,
-} from "./toolCallUtils";
+import type { ReactNode } from "react";
+import { StatusIndicators, ToolTitle } from "./toolCallUtils";
interface ToolRowProps {
- /** Leading tool icon. Ignored when `leading` is provided. */
icon?: Icon;
isLoading?: boolean;
isFailed?: boolean;
wasCancelled?: boolean;
- /**
- * Header content beside the icon. A plain string is wrapped in a ToolTitle;
- * pass nodes directly for richer headers (chips, mono spans, stats).
- */
children: ReactNode;
- /** Collapsible body. When present the row becomes a collapsible trigger. */
content?: ReactNode;
- /** Start expanded (uncontrolled). */
defaultOpen?: boolean;
- /** Controlled open state. Provide together with `onOpenChange`. */
open?: boolean;
onOpenChange?: (open: boolean) => void;
- /**
- * Force the collapsible trigger even when `content` is lazily omitted while
- * closed (used by the tool-call group, which only renders children open).
- */
- collapsible?: boolean;
- /** Wrap the content in the standard bordered box. Default true. */
- boxed?: boolean;
- /** Override the leading icon slot entirely (e.g. a caret for a group). */
leading?: ReactNode;
- /** Extra header content after the title (e.g. a summary icon strip). */
- trailing?: ReactNode;
}
-/**
- * The single wrapping element for every tool call: a header (icon + text), and
- * — when there's a body — a base-ui Collapsible whose content sits in a
- * left-padded box. Every tool view and the tool-call group render through this
- * so MCP, execute, read, edit, etc. are structurally identical.
- */
export function ToolRow({
icon,
isLoading = false,
@@ -63,138 +32,38 @@ export function ToolRow({
defaultOpen = false,
open,
onOpenChange,
- collapsible,
- boxed = true,
leading,
- trailing,
}: ToolRowProps) {
- const [internalOpen, setInternalOpen] = useState(defaultOpen);
- const isControlled = open !== undefined;
- const isOpen = isControlled ? open : internalOpen;
- const setOpen = (next: boolean) => {
- if (!isControlled) setInternalOpen(next);
- onOpenChange?.(next);
- };
-
- const chatChrome = useChatThreadChrome();
-
- const isCollapsible = collapsible || content != null;
-
- // New thread: render the tool as a ChatMarker (icon + title row, collapsible detail body).
- // Old thread (no provider) skips this and uses the Radix chrome below.
- if (chatChrome) {
- const IconComp = icon ?? WrenchIcon;
- const iconNode = leading ?? (isLoading ? <Spinner /> : <IconComp />);
- return (
- <ChatMarker
- body={content ? <div className="pt-1.5">{content}</div> : undefined}
- defaultOpen={defaultOpen}
- open={open}
- onOpenChange={onOpenChange}
- // Overrides quill's interactive row, which bleeds its hit area 4px past
- // the text column, fills on hover, and draws an outset focus ring. All
- // three land outside the chat column here, where a transcript is mostly
- // these rows.
- className={cn(
- "mx-0 px-0 opacity-50 hover:bg-transparent focus-visible:bg-transparent",
- // Breathing room between the header row and the nested content below:
- // quill's marker panel has no top padding of its own, so expanded
- // bodies sit flush against the trigger.
- "[&_[data-slot=marker-panel]]:pt-2 [&_[data-slot=marker-panel]]:pb-1",
- // quill 0.3.0-beta.24 parks the chevron at the row's far end with
- // `margin-inline-start: auto`, which strands it from the text it opens.
- "[&>svg:last-child]:ms-0",
- "focus-visible:shadow-none focus-visible:ring-(--ring)/50 focus-visible:ring-2 focus-visible:ring-inset",
- // Only rows that expand on click get the open state: a flat marker
- // ("Thinking" before any content arrives) can't honor it.
- isCollapsible &&
- "hover:opacity-100 data-panel-open:bg-transparent data-panel-open:opacity-100",
- // The descendant selector is load-bearing: the title, the argument,
- // and the status text each set their own muted color, so a color on
- // the row alone loses to all three. Scoped to the trigger so a nested
- // marker in the panel keeps its own outcome.
- isFailed &&
- "text-destructive-foreground opacity-100 [&_*]:text-destructive-foreground",
- )}
- >
- <ChatMarkerIcon>{iconNode}</ChatMarkerIcon>
- {/* No `w-full`: the content sizes to its text, so the chevron sits
- against the end of it. `overflow-hidden` keeps a long argument from
- spilling past the trigger. */}
- <ChatMarkerContent className="flex min-w-0 flex-nowrap items-center gap-1 overflow-hidden">
- {/* Example: posthog - insight-create(... */}
- {typeof children === "string" ? (
- <ToolTitle>{children}</ToolTitle>
- ) : (
- children
- )}
- <StatusIndicators isFailed={isFailed} wasCancelled={wasCancelled} />
- {trailing}
- </ChatMarkerContent>
- </ChatMarker>
- );
- }
-
- const leadingNode = leading ?? (
- <span className="flex shrink-0 items-center justify-center pt-1">
- {isCollapsible ? (
- <ExpandableIcon
- icon={icon ?? WrenchIcon}
- isLoading={isLoading}
- isExpandable
- isExpanded={isOpen}
- />
- ) : (
- <LoadingIcon icon={icon ?? WrenchIcon} isLoading={isLoading} />
- )}
- </span>
- );
-
- const header = (
- <span className="flex min-w-0 flex-wrap items-center gap-1">
- {typeof children === "string" ? (
- <ToolTitle>{children}</ToolTitle>
- ) : (
- children
- )}
- <StatusIndicators isFailed={isFailed} wasCancelled={wasCancelled} />
- {trailing}
- </span>
- );
-
- if (!isCollapsible) {
- return (
- <div className="group flex min-w-0 items-start gap-2 py-0.5">
- {leadingNode}
- {header}
- </div>
- );
- }
+ const isCollapsible = content != null;
+ const IconComp = icon ?? WrenchIcon;
+ const iconNode = leading ?? (isLoading ? <Spinner /> : <IconComp />);
return (
- <Collapsible.Root
- open={isOpen}
- onOpenChange={setOpen}
- className="tool-row-collapsible"
+ <ChatMarker
+ body={content ? <div className="pt-1.5">{content}</div> : undefined}
+ defaultOpen={defaultOpen}
+ open={open}
+ onOpenChange={onOpenChange}
+ className={cn(
+ "mx-0 px-0 opacity-50 hover:bg-transparent focus-visible:bg-transparent",
+ "[&_[data-slot=marker-panel]]:pt-2 [&_[data-slot=marker-panel]]:pb-1",
+ "[&>svg:last-child]:ms-0",
+ "focus-visible:shadow-none focus-visible:ring-(--ring)/50 focus-visible:ring-2 focus-visible:ring-inset",
+ isCollapsible &&
+ "hover:opacity-100 data-panel-open:bg-transparent data-panel-open:opacity-100",
+ isFailed &&
+ "text-destructive-foreground opacity-100 [&_*]:text-destructive-foreground",
+ )}
>
- <Collapsible.Trigger className="group mb-0 flex w-full min-w-0 cursor-pointer items-start gap-2 rounded-sm py-0.5 pl-1 text-left hover:bg-fill-hover data-panel-open:bg-fill-selected">
- {leadingNode}
- {header}
- </Collapsible.Trigger>
- <Collapsible.Panel>
- {content != null && (
- <div
- className={cn(
- "flex flex-col gap-2 p-2 [&_p]:mb-0",
- boxed
- ? "mt-1 mb-3 ml-5 max-w-4xl overflow-hidden rounded-lg border border-gray-6"
- : "mt-1 ml-5",
- )}
- >
- {content}
- </div>
+ <ChatMarkerIcon>{iconNode}</ChatMarkerIcon>
+ <ChatMarkerContent className="flex min-w-0 flex-nowrap items-center gap-1 overflow-hidden">
+ {typeof children === "string" ? (
+ <ToolTitle>{children}</ToolTitle>
+ ) : (
+ children
)}
- </Collapsible.Panel>
- </Collapsible.Root>
+ <StatusIndicators isFailed={isFailed} wasCancelled={wasCancelled} />
+ </ChatMarkerContent>
+ </ChatMarker>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/inlineArtifacts.ts b/products/desktop/packages/ui/src/features/sessions/components/session-update/inlineArtifacts.ts
index 09ab952de7cc..07ef5e1efa1b 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/inlineArtifacts.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/inlineArtifacts.ts
@@ -23,10 +23,3 @@ export function readCreatedPrUrl(toolCall: ToolCall): string | null {
outputText: toolCallOutputText(toolCall),
});
}
-
-/** Whether a tool call draws an artifact card, which never folds into a tool group. */
-export function hasInlineArtifact(toolCall: ToolCall): boolean {
- return (
- isUploadArtifactCall(toolCall._meta) || readCreatedPrUrl(toolCall) !== null
- );
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/toolCallUtils.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/toolCallUtils.tsx
index 5b3b1d4339f7..d2065122b53d 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/toolCallUtils.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/toolCallUtils.tsx
@@ -1,15 +1,6 @@
-import {
- Command,
- type Icon,
- MagnifyingGlass,
- Minus,
- Plus,
-} from "@phosphor-icons/react";
-import { cn } from "@posthog/quill";
+import { Command, type Icon, MagnifyingGlass } from "@phosphor-icons/react";
import { DotsCircleSpinner } from "@posthog/ui/primitives/DotsCircleSpinner";
-import { Box, Text } from "@radix-ui/themes";
import type { ToolCall, ToolCallContent } from "../../types";
-import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";
import { iconForToolKind } from "./toolIcons";
/** Tool icon by agent tool name, for tools without a generic `kind`. */
@@ -36,13 +27,13 @@ export function ToolTitle({
children: React.ReactNode;
className?: string;
}) {
- // New thread (ChatX marker chrome) uses the muted, truncating title; the legacy thread keeps its
- // original styling so toggling the chat thread off leaves ConversationView pixel-identical.
- const chatChrome = useChatThreadChrome();
- const base = chatChrome
- ? "text-sm text-muted-foreground truncate min-w-0"
- : "text-[13px] text-gray-11";
- return <Text className={cn(base, className)}>{children}</Text>;
+ return (
+ <span
+ className={`min-w-0 truncate text-muted-foreground text-sm ${className ?? ""}`}
+ >
+ {children}
+ </span>
+ );
}
export function StatusIndicators({
@@ -55,14 +46,14 @@ export function StatusIndicators({
return (
<>
{isFailed && (
- <Text className="shrink-0 whitespace-nowrap text-[13px] text-gray-10">
+ <span className="shrink-0 whitespace-nowrap text-[13px] text-gray-10">
(Failed)
- </Text>
+ </span>
)}
{wasCancelled && (
- <Text className="shrink-0 whitespace-nowrap text-[13px] text-gray-10">
+ <span className="shrink-0 whitespace-nowrap text-[13px] text-gray-10">
(Cancelled)
- </Text>
+ </span>
)}
</>
);
@@ -234,64 +225,39 @@ export function LoadingIcon({
return <IconComponent size={ICON_SIZE} className={className} />;
}
-export function ExpandableIcon({
- icon: IconComponent,
- isLoading,
- isExpandable,
- isExpanded,
+/** Expandable body for a generic tool call: its formatted input, then its text output. */
+export function toolCallDetails({
+ rawInput,
+ content,
+ isComplete,
+ isFailed,
}: {
- icon: Icon;
- isLoading: boolean;
- isExpandable: boolean;
- isExpanded: boolean;
-}) {
- if (isLoading) return <Spinner />;
- if (!isExpandable) {
- return <IconComponent size={ICON_SIZE} className={ICON_CLASS} />;
- }
+ rawInput: unknown;
+ content: ToolCall["content"];
+ isComplete: boolean;
+ isFailed: boolean;
+}): React.ReactNode | undefined {
+ const fullInput = formatInput(rawInput);
+ const output = stripCodeFences(getContentText(content) ?? "");
+ // A failed call keeps its output because the error text lives in `content`.
+ const showOutput = (isComplete || isFailed) && output.trim().length > 0;
+ if (!fullInput && !showOutput) return undefined;
return (
<>
- <IconComponent
- size={ICON_SIZE}
- className={`${ICON_CLASS} group-hover:hidden`}
- />
- {isExpanded ? (
- <Minus
- size={ICON_SIZE}
- className={`hidden ${ICON_CLASS} group-hover:block`}
- />
- ) : (
- <Plus
- size={ICON_SIZE}
- className={`hidden ${ICON_CLASS} group-hover:block`}
- />
- )}
+ {fullInput && <ContentPre>{fullInput}</ContentPre>}
+ {showOutput && <ContentPre>{output}</ContentPre>}
</>
);
}
export function ContentPre({ children }: { children: React.ReactNode }) {
- // New thread wraps output in a bordered, muted box (it sits inside a ChatMarker panel); the legacy
- // thread keeps the original borderless scroll box so ConversationView is unchanged when toggled off.
- const chatChrome = useChatThreadChrome();
- if (chatChrome) {
- return (
- <Box className="max-h-64 rounded-sm border border-border">
- <Box className="scroll-mask-2 max-h-64 overflow-auto bg-muted/50 p-3">
- <pre className="m-0 whitespace-pre-wrap break-all font-mono text-xs">
- {children}
- </pre>
- </Box>
- </Box>
- );
- }
return (
- <Box className="scroll-mask-2 max-h-64 overflow-auto px-3 py-2">
- <Text asChild className="text-[13px] text-gray-11">
- <pre className="m-0 whitespace-pre-wrap break-all font-mono">
+ <div className="max-h-64 rounded-sm border border-border">
+ <div className="scroll-mask-2 max-h-64 overflow-auto bg-muted/50 p-3">
+ <pre className="m-0 whitespace-pre-wrap break-all font-mono text-xs">
{children}
</pre>
- </Text>
- </Box>
+ </div>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useConversationSearch.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useConversationSearch.ts
deleted file mode 100644
index 5584aeb89082..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/hooks/useConversationSearch.ts
+++ /dev/null
@@ -1,213 +0,0 @@
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import type { ConversationSearchBarHandle } from "@posthog/ui/features/sessions/components/ConversationSearchBar";
-import type { VirtualizedListHandle } from "@posthog/ui/features/sessions/components/VirtualizedList";
-import { extractSearchableText } from "@posthog/ui/features/sessions/utils/extractSearchableText";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-
-const HIGHLIGHT_MATCH = "search-match";
-const HIGHLIGHT_ACTIVE = "search-match-active";
-
-interface SearchMatch {
- itemIndex: number;
- itemId: string;
- occurrenceInItem: number;
-}
-
-function escapeRegExp(s: string): string {
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-
-function clearHighlights() {
- if (typeof CSS === "undefined" || !CSS.highlights) return;
- CSS.highlights.delete(HIGHLIGHT_MATCH);
- CSS.highlights.delete(HIGHLIGHT_ACTIVE);
-}
-
-function findItemElement(
- container: HTMLElement,
- itemId: string,
-): HTMLElement | null {
- return container.querySelector(
- `[data-conversation-item-id="${CSS.escape(itemId)}"]`,
- );
-}
-
-function findRangesInItem(itemEl: HTMLElement, query: string): Range[] {
- const ranges: Range[] = [];
- const re = new RegExp(escapeRegExp(query), "gi");
- const walker = document.createTreeWalker(itemEl, NodeFilter.SHOW_TEXT);
- while (walker.nextNode()) {
- const node = walker.currentNode;
- const text = node.textContent ?? "";
- if (!text) continue;
- re.lastIndex = 0;
- let m: RegExpExecArray | null = re.exec(text);
- while (m !== null) {
- const range = new Range();
- range.setStart(node, m.index);
- range.setEnd(node, m.index + m[0].length);
- ranges.push(range);
- if (m.index === re.lastIndex) re.lastIndex++;
- m = re.exec(text);
- }
- }
- return ranges;
-}
-
-interface UseConversationSearchArgs {
- items: ConversationItem[];
- containerRef: React.RefObject<HTMLDivElement | null>;
- listRef: React.RefObject<VirtualizedListHandle | null>;
-}
-
-export function useConversationSearch({
- items,
- containerRef,
- listRef,
-}: UseConversationSearchArgs) {
- const [open, setOpen] = useState(false);
- const [query, setQuery] = useState("");
- const [currentIndex, setCurrentIndex] = useState(0);
- const searchBarRef = useRef<ConversationSearchBarHandle>(null);
-
- const matches = useMemo<SearchMatch[]>(() => {
- if (!query) return [];
- const re = new RegExp(escapeRegExp(query), "gi");
- const out: SearchMatch[] = [];
- for (let i = 0; i < items.length; i++) {
- const item = items[i];
- const text = extractSearchableText(item);
- if (!text) continue;
- re.lastIndex = 0;
- let occurrence = 0;
- let m: RegExpExecArray | null = re.exec(text);
- while (m !== null) {
- out.push({
- itemIndex: i,
- itemId: item.id,
- occurrenceInItem: occurrence++,
- });
- if (m.index === re.lastIndex) re.lastIndex++;
- m = re.exec(text);
- }
- }
- return out;
- }, [items, query]);
-
- const setQueryAndReset = useCallback((q: string) => {
- setQuery(q);
- setCurrentIndex(0);
- }, []);
-
- const next = useCallback(() => {
- if (matches.length === 0) return;
- const i = (currentIndex + 1) % matches.length;
- setCurrentIndex(i);
- listRef.current?.scrollToIndex(matches[i].itemIndex);
- }, [matches, currentIndex, listRef]);
-
- const prev = useCallback(() => {
- if (matches.length === 0) return;
- const i = (currentIndex - 1 + matches.length) % matches.length;
- setCurrentIndex(i);
- listRef.current?.scrollToIndex(matches[i].itemIndex);
- }, [matches, currentIndex, listRef]);
-
- const close = useCallback(() => {
- setOpen(false);
- setQuery("");
- setCurrentIndex(0);
- clearHighlights();
- }, []);
-
- useEffect(() => {
- if (!query || matches.length === 0) return;
- listRef.current?.scrollToIndex(matches[0].itemIndex);
- }, [query, matches, listRef]);
-
- // Apply CSS Custom Highlights. Reapplies whenever the virtualized list
- // mutates the DOM (items entering/leaving the viewport), so no scroll
- // listener or timeout retries are needed.
- useEffect(() => {
- if (typeof CSS === "undefined" || !CSS.highlights) return;
- const container = containerRef.current;
- if (!container || !query || matches.length === 0) {
- clearHighlights();
- return;
- }
-
- const matchesByItemId = new Map<string, SearchMatch[]>();
- for (const m of matches) {
- const list = matchesByItemId.get(m.itemId);
- if (list) list.push(m);
- else matchesByItemId.set(m.itemId, [m]);
- }
-
- const active = matches[currentIndex] ?? null;
-
- function apply() {
- clearHighlights();
- const allRanges: Range[] = [];
- let activeRange: Range | null = null;
-
- for (const [itemId] of matchesByItemId) {
- const itemEl = findItemElement(container as HTMLElement, itemId);
- if (!itemEl) continue;
- const domRanges = findRangesInItem(itemEl, query);
- for (const r of domRanges) allRanges.push(r);
- if (active && active.itemId === itemId && domRanges.length > 0) {
- // Pick the DOM occurrence matching the data-model occurrence
- // within this item. If the DOM has fewer occurrences (e.g.
- // markdown collapsed whitespace), fall back to the last one.
- const idx = Math.min(active.occurrenceInItem, domRanges.length - 1);
- activeRange = domRanges[idx];
- }
- }
-
- if (allRanges.length > 0) {
- CSS.highlights.set(HIGHLIGHT_MATCH, new Highlight(...allRanges));
- }
- if (activeRange) {
- CSS.highlights.set(HIGHLIGHT_ACTIVE, new Highlight(activeRange));
- }
- }
-
- apply();
-
- const observer = new MutationObserver(apply);
- observer.observe(container, {
- childList: true,
- subtree: true,
- characterData: true,
- });
-
- return () => {
- observer.disconnect();
- };
- }, [containerRef, query, matches, currentIndex]);
-
- // Global Cmd+F: open the search bar, or refocus + select-all if open.
- useEffect(() => {
- const onKeyDown = (e: KeyboardEvent) => {
- if (!(e.metaKey || e.ctrlKey) || e.key !== "f") return;
- e.preventDefault();
- setOpen(true);
- searchBarRef.current?.focusAndSelect();
- };
- document.addEventListener("keydown", onKeyDown, { capture: true });
- return () =>
- document.removeEventListener("keydown", onKeyDown, { capture: true });
- }, []);
-
- return {
- open,
- query,
- currentIndex,
- totalMatches: matches.length,
- searchBarRef,
- setQuery: setQueryAndReset,
- next,
- prev,
- close,
- };
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts b/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts
index f18683cb982b..a9811895572d 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionViewStore.ts
@@ -5,12 +5,6 @@ interface SessionViewState {
showRawLogs: boolean;
searchQuery: string;
showSearch: boolean;
- /**
- * Ephemeral per-tool-group expand overrides for the new thread, keyed by
- * group id. `true` = expanded, `false` = collapsed, absent = follow the
- * global collapse mode. Not persisted; wiped when the global mode changes.
- */
- groupOverrides: Record<string, boolean>;
/**
* Ephemeral per-task collapse of the queued-messages dock, keyed by taskId.
* `true` = collapsed; absent/`false` = expanded (the default). Not persisted;
@@ -37,8 +31,6 @@ interface SessionViewActions {
setShowRawLogs: (show: boolean) => void;
setSearchQuery: (query: string) => void;
toggleSearch: () => void;
- setGroupOverride: (id: string, expanded: boolean) => void;
- clearGroupOverrides: () => void;
setQueueCollapsed: (taskId: string, collapsed: boolean) => void;
setTurnFeedback: (
turnId: string,
@@ -53,7 +45,6 @@ const useStore = create<SessionViewStore>((set) => ({
showRawLogs: false,
searchQuery: "",
showSearch: false,
- groupOverrides: {},
queueCollapsedByTaskId: {},
turnFeedbackByTurnId: {},
permissionDockHeight: null,
@@ -65,16 +56,6 @@ const useStore = create<SessionViewStore>((set) => ({
showSearch: !state.showSearch,
searchQuery: state.showSearch ? "" : state.searchQuery,
})),
- setGroupOverride: (id, expanded) =>
- set((state) => ({
- groupOverrides: { ...state.groupOverrides, [id]: expanded },
- })),
- clearGroupOverrides: () =>
- set((state) =>
- Object.keys(state.groupOverrides).length === 0
- ? state
- : { groupOverrides: {} },
- ),
setQueueCollapsed: (taskId, collapsed) =>
set((state) => ({
queueCollapsedByTaskId: {
@@ -96,7 +77,6 @@ const useStore = create<SessionViewStore>((set) => ({
export const useShowRawLogs = () => useStore((s) => s.showRawLogs);
export const useSearchQuery = () => useStore((s) => s.searchQuery);
export const useShowSearch = () => useStore((s) => s.showSearch);
-export const useGroupOverrides = () => useStore((s) => s.groupOverrides);
export const useQueueCollapsed = (taskId: string) =>
useStore((s) => s.queueCollapsedByTaskId[taskId] ?? false);
export const usePermissionDockHeight = () =>
diff --git a/products/desktop/packages/ui/src/features/sessions/utils/extractSearchableText.test.ts b/products/desktop/packages/ui/src/features/sessions/utils/extractSearchableText.test.ts
deleted file mode 100644
index 18d7a5a71cda..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/utils/extractSearchableText.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import { extractSearchableText } from "@posthog/ui/features/sessions/utils/extractSearchableText";
-import { describe, expect, it } from "vitest";
-
-describe("extractSearchableText", () => {
- it("extracts user message content", () => {
- const item: ConversationItem = {
- type: "user_message",
- id: "1",
- content: "hello world",
- timestamp: 0,
- };
- expect(extractSearchableText(item)).toBe("hello world");
- });
-
- it("extracts agent message text chunk", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "2",
- update: {
- sessionUpdate: "agent_message_chunk",
- content: { type: "text", text: "agent reply" },
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("agent reply");
- });
-
- it("extracts agent thought text chunk", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "3",
- update: {
- sessionUpdate: "agent_thought_chunk",
- content: { type: "text", text: "thinking..." },
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("thinking...");
- });
-
- it("returns empty string for non-text agent chunks", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "4",
- update: {
- sessionUpdate: "agent_message_chunk",
- content: {
- type: "image",
- data: "base64data",
- mimeType: "image/png",
- },
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("");
- });
-
- it("returns empty string for tool calls", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "5",
- update: {
- sessionUpdate: "tool_call",
- toolCallId: "tc-1",
- title: "Read file",
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("");
- });
-
- it("extracts console message", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "6",
- update: {
- sessionUpdate: "console",
- level: "info",
- message: "console output",
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("console output");
- });
-
- it("extracts error message", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "7",
- update: {
- sessionUpdate: "error",
- errorType: "FatalError",
- message: "something broke",
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("something broke");
- });
-
- it("extracts status text", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "8",
- update: {
- sessionUpdate: "status",
- status: "running",
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("running");
- });
-
- it("extracts task notification summary", () => {
- const item: ConversationItem = {
- type: "session_update",
- id: "9",
- update: {
- sessionUpdate: "task_notification",
- taskId: "t1",
- status: "completed",
- summary: "task done",
- outputFile: "/tmp/out",
- },
- turnContext: {
- toolCalls: new Map(),
- childItems: new Map(),
- turnCancelled: false,
- turnComplete: true,
- },
- };
- expect(extractSearchableText(item)).toBe("task done");
- });
-
- it("joins shell command with stdout and stderr", () => {
- const item: ConversationItem = {
- type: "user_shell_execute",
- id: "10",
- command: "ls -la",
- cwd: "/tmp",
- result: { stdout: "file.txt", stderr: "warning", exitCode: 0 },
- };
- expect(extractSearchableText(item)).toBe("ls -la file.txt warning");
- });
-
- it("returns just the command when shell execute has no result", () => {
- const item: ConversationItem = {
- type: "user_shell_execute",
- id: "11",
- command: "echo hi",
- cwd: "/tmp",
- };
- expect(extractSearchableText(item)).toBe("echo hi ");
- });
-
- it("falls back to default text for turn_cancelled without reason", () => {
- const item: ConversationItem = {
- type: "turn_cancelled",
- id: "12",
- };
- expect(extractSearchableText(item)).toBe("Interrupted by user");
- });
-
- it("uses provided interruptReason on turn_cancelled", () => {
- const item: ConversationItem = {
- type: "turn_cancelled",
- id: "13",
- interruptReason: "moving_to_worktree",
- };
- expect(extractSearchableText(item)).toBe("moving_to_worktree");
- });
-
- it.each(["git_action", "skill_button_action", "git_action_result"] as const)(
- "returns empty string for %s items",
- (type) => {
- const item = {
- type,
- id: "x",
- actionType: "commit",
- buttonId: "btn",
- turnId: "t",
- } as unknown as ConversationItem;
- expect(extractSearchableText(item)).toBe("");
- },
- );
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/utils/extractSearchableText.ts b/products/desktop/packages/ui/src/features/sessions/utils/extractSearchableText.ts
deleted file mode 100644
index 78ba59cadb9e..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/utils/extractSearchableText.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
-import type { RenderItem } from "@posthog/ui/features/sessions/components/session-update/SessionUpdateView";
-
-function extractRenderItemText(update: RenderItem): string {
- switch (update.sessionUpdate) {
- case "agent_message_chunk":
- case "agent_thought_chunk":
- return "content" in update && update.content.type === "text"
- ? update.content.text
- : "";
- case "tool_call":
- // Tool calls are excluded from search. Each tool type renders its
- // collapsed state differently so extracted text wouldn't match the
- // DOM, causing count mismatches with visible highlights.
- return "";
- case "console":
- return update.message;
- case "error":
- return update.message;
- case "status":
- return update.status;
- case "task_notification":
- return update.summary;
- default:
- return "";
- }
-}
-
-export function extractSearchableText(item: ConversationItem): string {
- switch (item.type) {
- case "user_message":
- return item.content;
- case "session_update":
- return extractRenderItemText(item.update);
- case "user_shell_execute":
- return [
- item.command,
- item.result?.stdout ?? "",
- item.result?.stderr ?? "",
- ].join(" ");
- case "turn_cancelled":
- return item.interruptReason ?? "Interrupted by user";
- case "git_action":
- case "skill_button_action":
- case "git_action_result":
- return "";
- }
-}
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
index 0dc14ecec768..1585389cb72d 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -337,8 +337,6 @@ export interface SettingsStore {
setTerminalCustomFontFamily: (value: string) => void;
setTerminalGpuRendering: (enabled: boolean) => void;
- // Conversation thread (new-thread)
-
// Sidebar
// Shows a per-repo "Worktrees" dropdown of task-less worktrees a click can
// start a task in. Opt-in: off by default to keep the sidebar uncluttered.
@@ -650,8 +648,6 @@ export const useSettingsStore = create<SettingsStore>()(
setTerminalGpuRendering: (enabled) =>
set({ terminalGpuRendering: enabled }),
- // Conversation thread (new-thread)
-
// Sidebar
showSidebarWorktrees: false,
setShowSidebarWorktrees: (enabled) =>
@@ -803,8 +799,6 @@ export const useSettingsStore = create<SettingsStore>()(
terminalCustomFontFamily: state.terminalCustomFontFamily,
terminalGpuRendering: state.terminalGpuRendering,
- // Conversation thread (new-thread)
-
// Sidebar
showSidebarWorktrees: state.showSidebarWorktrees,
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx
index 12d302b0b479..fc5c75278124 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx
@@ -94,10 +94,6 @@ export function TaskLogsPanel({ taskId, task, hideInput }: TaskLogsPanelProps) {
onSendPrompt: handleSendPrompt,
});
- const slackThreadUrl =
- typeof task.latest_run?.state?.slack_thread_url === "string"
- ? task.latest_run.state.slack_thread_url
- : undefined;
const canRecoverGithubTask = canControlTask(task, session?.isTaskAuthor);
const githubRecoveryAvailable =
githubConnectionRequired && canRecoverGithubTask;
@@ -218,7 +214,6 @@ export function TaskLogsPanel({ taskId, task, hideInput }: TaskLogsPanelProps) {
onNewSession={isCloud ? undefined : handleNewSession}
isInitializing={isInitializing}
isCloud={isCloud}
- slackThreadUrl={slackThreadUrl}
/>
</ErrorBoundary>
</Box>
diff --git a/products/desktop/scripts/measure-session-hotpaths.ts b/products/desktop/scripts/measure-session-hotpaths.ts
index 45952e8405d8..2b956b5d44a6 100644
--- a/products/desktop/scripts/measure-session-hotpaths.ts
+++ b/products/desktop/scripts/measure-session-hotpaths.ts
@@ -17,8 +17,6 @@ import type {
TurnContext,
} from "../packages/ui/src/features/sessions/components/buildConversationItems";
import { mergeConversationItems } from "../packages/ui/src/features/sessions/components/mergeConversationItems";
-import { buildThreadGroups } from "../packages/ui/src/features/sessions/components/new-thread/buildThreadGroups";
-import { createIncrementalThreadGrouper } from "../packages/ui/src/features/sessions/components/new-thread/incrementalThreadGrouping";
const COMPLETED_TURNS = readPositiveInt("SESSION_COMPLETED_TURNS", 2_000);
const STREAM_EVENTS = readPositiveInt("SESSION_STREAM_EVENTS", 500);
@@ -303,24 +301,6 @@ function runConversationMergeBenchmark(): Measurement[] {
];
}
-function runThreadGroupingBenchmark(): Measurement[] {
- const sequences = buildThreadSequences();
- const overrides = {};
- return [
- measure("thread grouping full rebuild", () => {
- for (const items of sequences) {
- buildThreadGroups(items, "partial", overrides);
- }
- }),
- measure("thread grouping append tracker", () => {
- const grouper = createIncrementalThreadGrouper();
- for (const items of sequences) {
- grouper.update(items, "partial", overrides);
- }
- }),
- ];
-}
-
function format(ms: number): string {
return `${ms.toFixed(2)}ms`;
}
@@ -342,4 +322,3 @@ printPair(runContextUsageBenchmark());
printPair(runSessionResourcesBenchmark());
printPair(runLatestPlanBenchmark());
printPair(runConversationMergeBenchmark());
-printPair(runThreadGroupingBenchmark());