Skip to content

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

feat(desktop/composer): rework attachments, toolbar and chat column (#76454)

Adam Leithb929e92214fb
diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx
index e34e11a7d255..6430da447bb2 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx
@@ -316,7 +316,7 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {
onOpenTask={handleOpenTask}
onOpenThread={handleOpenThread}
/>
- <div className="mx-auto w-full px-4 pt-2 pb-4">
+ <div className="mx-auto w-full px-4 pt-2 pb-2">
<ChannelHomeComposer
ref={composerRef}
channelId={channelId}
diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx
index 76542c4cb858..7722fb06b32f 100644
--- a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx
+++ b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx
@@ -39,8 +39,8 @@ interface LoopModelFieldsProps {
/**
* Static model configuration for a loop: model, adapter, and reasoning effort.
* Loops have no live agent session, so the interactive
- * `UnifiedModelSelector`/`ReasoningLevelSelector` (which read a session's
- * `SessionConfigOption`) don't apply here; instead this presents the same
+ * `ReasoningLevelSelector` (which reads a session's `SessionConfigOption`)
+ * doesn't apply here; instead this presents the same
* per-adapter choices as the main create-task picker (see `loopModels.ts`),
* so every selectable combo passes the server's validation in
* `process_task/utils.py`. Adapter and model switches clamp a now-unsupported
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/Attachment.tsx b/products/desktop/packages/ui/src/features/message-editor/components/Attachment.tsx
new file mode 100644
index 000000000000..88c9ba0bec6c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/components/Attachment.tsx
@@ -0,0 +1,132 @@
+import { FileIcon, WarningCircle, X } from "@phosphor-icons/react";
+import {
+ Button,
+ cn,
+ Spinner,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@posthog/quill";
+import { fileExtensionLabel } from "@posthog/ui/features/message-editor/fileKind";
+import type { ReactNode } from "react";
+
+export type AttachmentUploadStatus = "uploading" | "error";
+
+/**
+ * Extensions that read better as their own mark than as text. ".JSON" is five
+ * characters crammed into a 32px square; "{}" is the same idea at a glance.
+ */
+const EXTENSION_GLYPHS: Record<string, string> = {
+ ".json": "{}",
+};
+
+/**
+ * One attachment on a prompt: a square the size of the composer's other icon
+ * buttons, showing the file's own picture when it has one and a document glyph
+ * when it doesn't. The filename lives in the tooltip rather than beside the
+ * square — across a row of these, names cost more room than they buy.
+ */
+export function Attachment({
+ label,
+ preview,
+ hint,
+ onOpen,
+ onRemove,
+ status,
+}: {
+ label: string;
+ /**
+ * The file's own thumbnail. Without one the square shows the extension, which
+ * says more at this size than a generic document glyph does.
+ */
+ preview?: ReactNode;
+ /** Second tooltip line: what clicking the square does. Omit when nothing does. */
+ hint?: string;
+ onOpen?: () => void;
+ onRemove?: () => void;
+ status?: AttachmentUploadStatus;
+}) {
+ const extension = fileExtensionLabel(label);
+ const glyph = extension ? EXTENSION_GLYPHS[extension] : undefined;
+ const face =
+ preview ??
+ (glyph ? (
+ <span className="font-medium font-mono text-[13px]">{glyph}</span>
+ ) : extension ? (
+ <span className="font-medium text-[10px] uppercase">{extension}</span>
+ ) : (
+ <FileIcon size={16} weight="duotone" />
+ ));
+
+ return (
+ // The remove control is a badge over the corner rather than a slot inside,
+ // so it costs the square no room. Keyboard focus reveals it too — hover
+ // alone would strand it.
+ // Hovering lifts the whole attachment above its neighbours so the remove
+ // badge, which overhangs the corner, isn't clipped under the next square.
+ <div className="group/attachment relative shrink-0 focus-within:z-10 hover:z-10">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-lg"
+ aria-label={label}
+ onClick={onOpen}
+ // Explicit square: `icon-lg` sizes the box, but a thumbnail is
+ // free to stretch a flex button, so the face is absolutely
+ // positioned inside a fixed one instead.
+ className={cn(
+ "relative size-8 shrink-0 overflow-hidden p-0",
+ !onOpen && "cursor-default",
+ )}
+ >
+ <span className="absolute inset-0 flex items-center justify-center">
+ {face}
+ </span>
+ {status && (
+ <span className="absolute inset-0 flex items-center justify-center bg-[var(--gray-a5)]">
+ {status === "uploading" ? (
+ <Spinner
+ className="size-3.5"
+ aria-label="Uploading attachment"
+ />
+ ) : (
+ <WarningCircle
+ size={14}
+ className="text-red-9"
+ aria-label="Attachment upload failed"
+ />
+ )}
+ </span>
+ )}
+ </Button>
+ }
+ />
+ <TooltipContent side="top">
+ {label}
+ {hint && (
+ <>
+ <br />
+ {hint}
+ </>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ {onRemove && (
+ <button
+ type="button"
+ aria-label={`Remove ${label}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemove();
+ }}
+ className="-top-1.5 -right-1.5 absolute z-10 flex size-4 items-center justify-center rounded-full bg-gray-9 text-gray-1 opacity-0 shadow-sm transition-opacity hover:bg-gray-10 focus-visible:opacity-100 group-focus-within/attachment:opacity-100 group-hover/attachment:opacity-100 motion-reduce:transition-none"
+ >
+ <X size={9} weight="bold" />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx b/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx
index abdc6395249f..d7d291a0d8d5 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx
@@ -1,9 +1,4 @@
-import {
- File,
- FolderSimple,
- GithubLogo,
- Paperclip,
-} from "@phosphor-icons/react";
+import { File, FolderSimple, GithubLogo, Plus } from "@phosphor-icons/react";
import {
deriveFileLabel,
type FileAttachment,
@@ -67,7 +62,7 @@ export function AttachmentMenu({
const [menuOpen, setMenuOpen] = useState(false);
const [issuePickerOpen, setIssuePickerOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
- const paperclipRef = useRef<HTMLButtonElement>(null);
+ const attachButtonRef = useRef<HTMLButtonElement>(null);
const showAddDirectoryDialog = useAddDirectoryDialogStore((s) => s.show);
const { data: ghStatus } = useQuery({
@@ -185,7 +180,7 @@ export function AttachmentMenu({
<DropdownMenuTrigger
render={
<Button
- ref={paperclipRef}
+ ref={attachButtonRef}
type="button"
variant="default"
size="icon-sm"
@@ -193,7 +188,7 @@ export function AttachmentMenu({
aria-label={attachTooltip}
title={attachTooltip}
>
- <Paperclip size={iconSize} weight="bold" />
+ <Plus size={iconSize} weight="bold" />
</Button>
}
/>
@@ -235,7 +230,7 @@ export function AttachmentMenu({
open={issuePickerOpen}
onOpenChange={setIssuePickerOpen}
onSelect={handleIssueSelect}
- anchor={paperclipRef}
+ anchor={attachButtonRef}
/>
</>
);
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/AttachmentsBar.tsx b/products/desktop/packages/ui/src/features/message-editor/components/AttachmentsBar.tsx
index 537f6ad0dd43..a296f0b3004c 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/AttachmentsBar.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/AttachmentsBar.tsx
@@ -1,43 +1,40 @@
-import { File, WarningCircle, X } from "@phosphor-icons/react";
import type { FileAttachment } from "@posthog/core/message-editor/content";
import {
isGifFile,
isRasterImageFile,
parseImageDataUrl,
} from "@posthog/shared";
+import {
+ Attachment,
+ type AttachmentUploadStatus,
+} from "@posthog/ui/features/message-editor/components/Attachment";
import { SafeImagePreview } from "@posthog/ui/primitives/SafeImagePreview";
-import { Dialog, Flex, IconButton, Spinner, Text } from "@radix-ui/themes";
+import { Dialog, Flex, Text } from "@radix-ui/themes";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import { readFileAsDataUrl } from "../hostApi";
-export type AttachmentUploadStatus = "uploading" | "error";
-
-function AttachmentStatusIcon({ status }: { status?: AttachmentUploadStatus }) {
- if (status === "uploading") {
- return <Spinner size="1" aria-label="Uploading attachment" />;
- }
- if (status === "error") {
- return (
- <WarningCircle
- size={14}
- className="text-red-9"
- aria-label="Attachment upload failed"
- />
- );
- }
- return null;
-}
+export type { AttachmentUploadStatus };
-function FrozenGifThumbnail({ src, alt }: { src: string; alt: string }) {
+/**
+ * A GIF's first frame, drawn once to a canvas. An animating thumbnail in the
+ * composer pulls the eye off what you are writing.
+ */
+function useFrozenGif(src: string | null | undefined, enabled: boolean) {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
+ if (!enabled || !src) return;
const img = new Image();
+ let cancelled = false;
img.onload = () => {
+ // A decode that lands after the src changed would paint the previous
+ // GIF's frame onto the canvas the new one is about to use, and the
+ // handler holds the decoded image alive until it fires.
+ if (cancelled) return;
const canvas = canvasRef.current;
if (!canvas) return;
- const size = 56;
+ const size = 64;
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
@@ -48,14 +45,16 @@ function FrozenGifThumbnail({ src, alt }: { src: string; alt: string }) {
ctx.drawImage(img, sx, sy, min, min, 0, 0, size, size);
};
img.src = src;
- }, [src]);
+ return () => {
+ cancelled = true;
+ img.onload = null;
+ };
+ }, [src, enabled]);
- return (
- <canvas ref={canvasRef} aria-label={alt} className="size-3.5 rounded-sm" />
- );
+ return canvasRef;
}
-function ImageThumbnail({
+function ImageAttachment({
attachment,
onRemove,
uploadStatus,
@@ -71,46 +70,31 @@ function ImageThumbnail({
});
const isGif = isGifFile(attachment.label);
+ const canvasRef = useFrozenGif(dataUrl, isGif);
const parsedImage = dataUrl ? parseImageDataUrl(dataUrl) : null;
+ const preview = isGif ? (
+ <canvas ref={canvasRef} aria-hidden className="size-full object-cover" />
+ ) : dataUrl ? (
+ <img src={dataUrl} alt="" className="size-full object-cover" />
+ ) : (
+ // Holds the square's shape until the data URL resolves.
+ <span className="size-full bg-[var(--gray-a5)]" />
+ );
+
return (
<Dialog.Root>
- <div className="group relative flex-shrink-0">
- <Dialog.Trigger>
- <button
- type="button"
- className="inline-flex items-center gap-1 rounded-[var(--radius-1)] bg-[var(--gray-a3)] p-1 font-medium text-[11px] text-[var(--gray-11)] hover:bg-[var(--gray-a4)]"
- >
- {dataUrl ? (
- isGif ? (
- <FrozenGifThumbnail src={dataUrl} alt={attachment.label} />
- ) : (
- <img
- src={dataUrl}
- alt={attachment.label}
- className="size-3.5 rounded-sm object-cover"
- />
- )
- ) : (
- <span className="size-3.5 rounded-sm bg-[var(--gray-a5)]" />
- )}
- <span className="max-w-[80px] truncate">{attachment.label}</span>
- <AttachmentStatusIcon status={uploadStatus} />
- </button>
- </Dialog.Trigger>
- <IconButton
- size="1"
- variant="solid"
- color="gray"
- className="!absolute -top-1 -right-1 !size-3.5 opacity-0 transition-opacity group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onRemove();
- }}
- >
- <X size={8} weight="bold" />
- </IconButton>
- </div>
+ <Dialog.Trigger>
+ <div>
+ <Attachment
+ label={attachment.label}
+ preview={preview}
+ hint="Click to preview"
+ onRemove={onRemove}
+ status={uploadStatus}
+ />
+ </div>
+ </Dialog.Trigger>
<Dialog.Content maxWidth="85vw" className="w-fit p-[16px]">
<Dialog.Title mb="2" className="text-sm">
{attachment.label}
@@ -132,40 +116,6 @@ function ImageThumbnail({
);
}
-function FileChip({
- attachment,
- onRemove,
- uploadStatus,
-}: {
- attachment: FileAttachment;
- onRemove: () => void;
- uploadStatus?: AttachmentUploadStatus;
-}) {
- return (
- <span className="group/chip inline-flex flex-shrink-0 items-center gap-1 rounded-[var(--radius-1)] bg-[var(--gray-a3)] p-1 font-medium text-[11px] text-[var(--gray-11)]">
- <button
- type="button"
- tabIndex={-1}
- aria-label="Remove attachment"
- className="relative inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center border-none bg-transparent p-0"
- onClick={(e) => {
- e.stopPropagation();
- onRemove();
- }}
- >
- <span className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-100 transition-opacity duration-150 group-hover/chip:opacity-0 motion-reduce:transition-none">
- <File size={14} weight="duotone" />
- </span>
- <span className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-150 group-hover/chip:opacity-100 motion-reduce:transition-none">
- <X size={12} weight="bold" />
- </span>
- </button>
- <span className="max-w-[120px] truncate">{attachment.label}</span>
- <AttachmentStatusIcon status={uploadStatus} />
- </span>
- );
-}
-
interface AttachmentsBarProps {
attachments: FileAttachment[];
onRemove: (id: string) => void;
@@ -180,21 +130,21 @@ export function AttachmentsBar({
if (attachments.length === 0) return null;
return (
- <Flex gap="1" align="center" className="flex-wrap pb-1.5">
+ <Flex gap="1" align="center" className="flex-wrap">
{attachments.map((att) =>
isRasterImageFile(att.label) ? (
- <ImageThumbnail
+ <ImageAttachment
key={att.id}
attachment={att}
onRemove={() => onRemove(att.id)}
uploadStatus={uploadStatuses?.[att.id]}
/>
) : (
- <FileChip
+ <Attachment
key={att.id}
- attachment={att}
+ label={att.label}
onRemove={() => onRemove(att.id)}
- uploadStatus={uploadStatuses?.[att.id]}
+ status={uploadStatuses?.[att.id]}
/>
),
)}
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx b/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx
index 39f37db2e499..ad75a31501c6 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx
@@ -1,5 +1,4 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
-import { CaretDown, ChartLineUp, Shapes } from "@phosphor-icons/react";
import {
Button,
DropdownMenu,
@@ -11,7 +10,6 @@ import {
DropdownMenuTrigger,
MenuLabel,
} from "@posthog/quill";
-import { getModeStyle } from "@posthog/ui/features/sessions/modeStyles";
import { flattenSelectOptions } from "@posthog/ui/features/sessions/sessionStore";
import { useRetainedConfigOption } from "@posthog/ui/features/sessions/useRetainedConfigOption";
import { useRef, useState } from "react";
@@ -77,36 +75,28 @@ export function ModeSelector({
const currentValue = displayOption.currentValue;
const canvasActive = !!canvas?.active;
- const currentStyle = canvasActive
- ? { icon: <Shapes size={12} weight="fill" />, className: "text-teal-11" }
- : getModeStyle(currentValue);
const currentLabel = canvasActive
? "Canvas"
: (allOptions.find((opt) => opt.value === currentValue)?.name ??
currentValue);
+ // Running unsupervised is the only mode the trigger colours at all, and it
+ // does so as a whole destructive button rather than a tinted label — a mode
+ // tint per mode turns the toolbar into a palette and stops reading as a
+ // warning where it matters.
+ const bypassActive =
+ !canvasActive &&
+ (currentValue === "bypassPermissions" || currentValue === "full-access");
const toggles: Array<{
label: string;
active: boolean;
onToggle: () => void;
- icon: React.ReactNode;
- className: string;
}> = [];
if (canvas) {
- toggles.push({
- label: "Canvas",
- ...canvas,
- icon: <Shapes size={12} weight="fill" />,
- className: "text-teal-11",
- });
+ toggles.push({ label: "Canvas", ...canvas });
}
if (autoresearch) {
- toggles.push({
- label: "Autoresearch",
- ...autoresearch,
- icon: <ChartLineUp size={12} />,
- className: "text-muted-foreground",
- });
+ toggles.push({ label: "Autoresearch", ...autoresearch });
}
return (
@@ -130,18 +120,12 @@ export function ModeSelector({
render={
<Button
type="button"
- variant="default"
+ variant={bypassActive ? "destructive" : "default"}
size="sm"
disabled={isDisabled}
aria-label="Mode"
>
- <span className={currentStyle.className}>{currentStyle.icon}</span>
- <span className={currentStyle.className}>{currentLabel}</span>
- <CaretDown
- size={10}
- weight="bold"
- className="text-muted-foreground"
- />
+ <span>{currentLabel}</span>
</Button>
}
/>
@@ -161,15 +145,11 @@ export function ModeSelector({
setOpen(false);
}}
>
- {options.map((option) => {
- const style = getModeStyle(option.value);
- return (
- <DropdownMenuRadioItem key={option.value} value={option.value}>
- <span className={`${style.className}`}>{style.icon}</span>
- <span className="whitespace-nowrap">{option.name}</span>
- </DropdownMenuRadioItem>
- );
- })}
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ <span className="whitespace-nowrap">{option.name}</span>
+ </DropdownMenuRadioItem>
+ ))}
</DropdownMenuRadioGroup>
{toggles.length > 0 && <DropdownMenuSeparator />}
{toggles.map((toggle) => (
@@ -181,7 +161,6 @@ export function ModeSelector({
setOpen(false);
}}
>
- <span className={toggle.className}>{toggle.icon}</span>
<span className="whitespace-nowrap">{toggle.label}</span>
</DropdownMenuCheckboxItem>
))}
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/PromptHistoryDialog.tsx b/products/desktop/packages/ui/src/features/message-editor/components/PromptHistoryDialog.tsx
index c083184455b7..74e2319cd3f4 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/PromptHistoryDialog.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/PromptHistoryDialog.tsx
@@ -1,11 +1,11 @@
import { ClockCounterClockwise, MagnifyingGlass } from "@phosphor-icons/react";
import {
+ Button,
Dialog,
DialogContent,
DialogTitle,
DialogTrigger,
Input,
- InputGroupButton,
Tooltip,
TooltipContent,
TooltipProvider,
@@ -123,14 +123,15 @@ export function PromptHistoryDialog({
render={
<TooltipTrigger
render={
- <InputGroupButton
+ <Button
+ type="button"
variant="default"
size="icon-sm"
aria-label="Prompt history"
disabled={disabled || !hasHistory}
>
<ClockCounterClockwise size={14} />
- </InputGroupButton>
+ </Button>
}
/>
}
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.stories.tsx b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.stories.tsx
index c408dde3096a..672f0a7e0ddd 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.stories.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.stories.tsx
@@ -1,15 +1,21 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
+import type { FileAttachment } from "@posthog/core/message-editor/content";
+import type { ContextUsage } from "@posthog/core/sessions/contextUsage";
+import { PromptHistoryDialog } from "@posthog/ui/features/message-editor/components/PromptHistoryDialog";
import { PromptInput } from "@posthog/ui/features/message-editor/components/PromptInput";
import type { MentionChip } from "@posthog/ui/features/message-editor/content";
import type { EditorHandle } from "@posthog/ui/features/message-editor/types";
+import { ContextUsageIndicator } from "@posthog/ui/features/sessions/components/ContextUsageIndicator";
import { ReasoningLevelSelector } from "@posthog/ui/features/sessions/components/ReasoningLevelSelector";
-import { UnifiedModelSelector } from "@posthog/ui/features/sessions/components/UnifiedModelSelector";
-import type { AgentAdapter } from "@posthog/ui/features/settings/settingsStore";
+import { SteerQueueToggle } from "@posthog/ui/features/sessions/components/SteerQueueToggle";
+import { ChannelContextChip } from "@posthog/ui/features/task-detail/components/ChannelContextChip";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { useEffect, useRef, useState } from "react";
// The host tRPC, DI, and query providers are supplied globally by the
-// `withAppProviders` decorator in `.storybook/preview.tsx`.
+// `withAppProviders` decorator in `.storybook/preview.tsx`. Image attachments
+// read their thumbnail through the host, which never answers here, so they
+// render the extension face rather than a picture.
// --- Mock data matching SessionConfigOption shape ---
@@ -53,86 +59,168 @@ const mockReasoningOption = {
],
} satisfies SessionConfigOption;
-// --- Wrapper to inject chips after mount ---
+const mockModeOption = {
+ id: "mode",
+ name: "Mode",
+ type: "select" as const,
+ currentValue: "auto",
+ options: [
+ { value: "read-only", name: "Read-only" },
+ { value: "auto", name: "Auto" },
+ { value: "full-access", name: "Full access" },
+ ],
+} satisfies SessionConfigOption;
-function PromptInputWithChips({
- chips,
- ...props
-}: React.ComponentProps<typeof PromptInput> & { chips?: MentionChip[] }) {
- const ref = useRef<EditorHandle>(null);
- const insertedRef = useRef(false);
+const mockUsage: ContextUsage = {
+ used: 24_000,
+ size: 353_000,
+ percentage: 7,
+ cost: { amount: 0.42, currency: "USD" },
+ breakdown: {
+ systemPrompt: 14_000,
+ tools: 0,
+ rules: 0,
+ skills: 0,
+ mcp: 0,
+ subagents: 0,
+ conversation: 11_000,
+ },
+};
- useEffect(() => {
- if (!chips?.length || insertedRef.current) return;
- insertedRef.current = true;
- const timer = setTimeout(() => {
- for (const chip of chips) {
- ref.current?.insertChip(chip);
- }
- }, 200);
- return () => clearTimeout(timer);
- }, [chips]);
+const nearFullUsage: ContextUsage = {
+ ...mockUsage,
+ used: 320_000,
+ percentage: 91,
+ breakdown: {
+ systemPrompt: 14_000,
+ tools: 22_000,
+ rules: 8000,
+ skills: 6000,
+ mcp: 12_000,
+ subagents: 18_000,
+ conversation: 240_000,
+ },
+};
- return <PromptInput ref={ref} {...props} />;
+function attachment(label: string, id = `/tmp/${label}`): FileAttachment {
+ return { id, label };
}
-// --- Wrapper with stateful selectors ---
+const SAMPLE_TEXT = "Rework the composer toolbar so it sits under the input";
+const LONG_TEXT = Array.from(
+ { length: 12 },
+ (_, i) => `Line ${i + 1}: keep the composer scrolling past its max height.`,
+).join("\n");
+
+// --- Harness: fills the editor and mounts the optional toolbar slots ---
-function PromptInputWithSelectors({
+interface HarnessProps
+ extends Omit<React.ComponentProps<typeof PromptInput>, "sessionId"> {
+ sessionId?: string;
+ /** Seeded into the editor after mount, so `!` reaches bash mode. */
+ text?: string;
+ chips?: MentionChip[];
+ attachments?: FileAttachment[];
+ /** The merged model + effort pill a live session renders. */
+ showSelectors?: boolean;
+ showMode?: boolean;
+ showHistory?: boolean;
+ showSteerQueue?: boolean;
+ contextUsage?: ContextUsage | null;
+ channelContext?: boolean;
+}
+
+function PromptInputHarness({
+ sessionId = "storybook-session",
+ text,
chips,
+ attachments,
showSelectors = true,
+ showMode = true,
+ showHistory = true,
+ showSteerQueue = true,
+ contextUsage = mockUsage,
+ channelContext = false,
...props
-}: React.ComponentProps<typeof PromptInput> & {
- chips?: MentionChip[];
- showSelectors?: boolean;
-}) {
- const [adapter, setAdapter] = useState<AgentAdapter>("claude");
- const [modelOption, setModelOption] =
- useState<SessionConfigOption>(mockModelOption);
+}: HarnessProps) {
+ const ref = useRef<EditorHandle>(null);
+ const seededRef = useRef(false);
const [reasoningOption, setReasoningOption] =
useState<SessionConfigOption>(mockReasoningOption);
+ const [modeOption, setModeOption] =
+ useState<SessionConfigOption>(mockModeOption);
- const handleModelChange = (value: string) => {
- setModelOption({ ...mockModelOption, currentValue: value });
- };
-
- const handleReasoningChange = (value: string) => {
- setReasoningOption({ ...mockReasoningOption, currentValue: value });
- };
+ // One pass after mount: the editor is ready a tick late, and re-seeding on
+ // every render would fight whatever is typed into it.
+ useEffect(() => {
+ if (seededRef.current) return;
+ seededRef.current = true;
+ const timer = setTimeout(() => {
+ if (text) ref.current?.setContent(text);
+ for (const chip of chips ?? []) ref.current?.insertChip(chip);
+ for (const file of attachments ?? []) ref.current?.addAttachment(file);
+ }, 200);
+ return () => clearTimeout(timer);
+ }, [text, chips, attachments]);
return (
- <PromptInputWithChips
- chips={chips}
- modelSelector={
- showSelectors ? (
- <UnifiedModelSelector
- modelOption={modelOption}
- adapter={adapter}
- onAdapterChange={setAdapter}
- onModelChange={handleModelChange}
- />
- ) : (
- false
- )
+ <PromptInput
+ ref={ref}
+ sessionId={sessionId}
+ modeOption={showMode ? modeOption : undefined}
+ onModeChange={
+ showMode
+ ? (value) => setModeOption({ ...mockModeOption, currentValue: value })
+ : undefined
}
+ allowBypassPermissions
+ modelSelector={null}
reasoningSelector={
showSelectors ? (
<ReasoningLevelSelector
thoughtOption={reasoningOption}
- onChange={handleReasoningChange}
+ modelOption={mockModelOption}
+ adapter="claude"
+ onChange={(value) =>
+ setReasoningOption({
+ ...mockReasoningOption,
+ currentValue: value,
+ })
+ }
+ />
+ ) : null
+ }
+ historyButton={
+ showHistory ? (
+ <PromptHistoryDialog
+ onSelect={() => {}}
+ hasPendingDraft={() => false}
/>
- ) : (
- false
- )
+ ) : undefined
+ }
+ messagingModeToggle={
+ showSteerQueue ? (
+ <SteerQueueToggle taskId="storybook-task" />
+ ) : undefined
+ }
+ toolbarEndSlot={
+ contextUsage ? (
+ <ContextUsageIndicator usage={contextUsage} />
+ ) : undefined
+ }
+ attachmentsPrefix={
+ channelContext ? (
+ <ChannelContextChip channelName="engineering" onRemove={() => {}} />
+ ) : undefined
}
{...props}
/>
);
}
-const meta: Meta<typeof PromptInputWithSelectors> = {
+const meta: Meta<typeof PromptInputHarness> = {
title: "Features/MessageEditor/PromptInput",
- component: PromptInputWithSelectors,
+ component: PromptInputHarness,
parameters: {
layout: "padded",
},
@@ -144,15 +232,17 @@ const meta: Meta<typeof PromptInputWithSelectors> = {
),
],
args: {
- sessionId: "storybook-session",
placeholder: "Type a message...",
disabled: false,
isLoading: false,
- autoFocus: true,
+ autoFocus: false,
isActiveSession: true,
enableBashMode: true,
enableCommands: true,
showSelectors: true,
+ showMode: true,
+ showHistory: true,
+ showSteerQueue: true,
onSubmit: () => {},
onCancel: () => {},
},
@@ -162,18 +252,45 @@ const meta: Meta<typeof PromptInputWithSelectors> = {
enableBashMode: { control: "boolean" },
enableCommands: { control: "boolean" },
showSelectors: { control: "boolean" },
+ showMode: { control: "boolean" },
+ showHistory: { control: "boolean" },
+ showSteerQueue: { control: "boolean" },
+ channelContext: { control: "boolean" },
+ hideDefaultToolbar: { control: "boolean" },
+ editorHeight: { control: "radio", options: ["default", "large"] },
placeholder: { control: "text" },
},
};
export default meta;
-type Story = StoryObj<typeof PromptInputWithSelectors>;
+type Story = StoryObj<typeof PromptInputHarness>;
+
+// --- Content states ---
-export const Default: Story = {};
+export const Empty: Story = {
+ args: { sessionId: "sb-empty" },
+};
+
+export const Filled: Story = {
+ args: { sessionId: "sb-filled", text: SAMPLE_TEXT },
+};
+
+export const Overflowing: Story = {
+ name: "Filled (scrolls past max height)",
+ args: { sessionId: "sb-overflow", text: LONG_TEXT },
+};
+
+export const LargeEditor: Story = {
+ name: "Filled (editorHeight large)",
+ args: { sessionId: "sb-large", text: LONG_TEXT, editorHeight: "large" },
+};
+
+// --- Chips ---
export const WithFileChip: Story = {
- name: "With File Chip",
+ name: "Chip: file",
args: {
+ sessionId: "sb-chip-file",
chips: [
{
type: "file",
@@ -185,15 +302,17 @@ export const WithFileChip: Story = {
};
export const WithCommandChip: Story = {
- name: "With Command Chip",
+ name: "Chip: command",
args: {
+ sessionId: "sb-chip-command",
chips: [{ type: "command", id: "good", label: "good" }],
},
};
export const WithMultipleChips: Story = {
- name: "With Multiple Chips",
+ name: "Chips: several",
args: {
+ sessionId: "sb-chip-multi",
chips: [
{
type: "file",
@@ -211,8 +330,9 @@ export const WithMultipleChips: Story = {
};
export const AllChipTypes: Story = {
- name: "All Chip Types",
+ name: "Chips: every type",
args: {
+ sessionId: "sb-chip-all",
chips: [
{ type: "file", id: "/src/index.ts", label: "src/index.ts" },
{ type: "command", id: "review", label: "review" },
@@ -234,30 +354,10 @@ export const AllChipTypes: Story = {
},
};
-export const BashMode: Story = {
- name: "Bash Mode (type ! to activate)",
- args: {
- enableBashMode: true,
- placeholder: "Type ! to enter bash mode...",
- },
-};
-
-export const Loading: Story = {
- name: "Loading (With Cancel)",
- args: {
- isLoading: true,
- },
-};
-
-export const Disabled: Story = {
- args: {
- disabled: true,
- },
-};
-
export const LongChipLabels: Story = {
- name: "Long Chip Labels",
+ name: "Chips: long labels",
args: {
+ sessionId: "sb-chip-long",
chips: [
{
type: "file",
@@ -275,9 +375,267 @@ export const LongChipLabels: Story = {
},
};
-export const NoToolbar: Story = {
- name: "No Toolbar (Minimal)",
+// --- Attachments ---
+
+export const OneAttachment: Story = {
+ name: "Attachments: one",
+ args: {
+ sessionId: "sb-attach-one",
+ attachments: [attachment("diagram.png")],
+ },
+};
+
+export const ManyAttachments: Story = {
+ name: "Attachments: many kinds",
+ args: {
+ sessionId: "sb-attach-many",
+ attachments: [
+ attachment("screenshot.png"),
+ attachment("recording.gif"),
+ attachment("notes.md"),
+ attachment("trace.json"),
+ attachment("query.sql"),
+ attachment("archive.tar.gz"),
+ attachment("no-extension"),
+ ],
+ },
+};
+
+export const AttachmentsUploading: Story = {
+ name: "Attachments: uploading and failed",
+ args: {
+ sessionId: "sb-attach-status",
+ attachments: [
+ attachment("uploading.png"),
+ attachment("failed.png"),
+ attachment("done.png"),
+ ],
+ attachmentUploadStatuses: {
+ "/tmp/uploading.png": "uploading",
+ "/tmp/failed.png": "error",
+ },
+ },
+};
+
+export const AttachmentsWithChannelContext: Story = {
+ name: "Attachments: with channel CONTEXT.md",
args: {
+ sessionId: "sb-attach-context",
+ channelContext: true,
+ attachments: [attachment("screenshot.png"), attachment("notes.md")],
+ },
+};
+
+export const ChannelContextOnly: Story = {
+ name: "Attachments: channel CONTEXT.md only",
+ args: { sessionId: "sb-context-only", channelContext: true },
+};
+
+export const AttachmentsAndChipsAndText: Story = {
+ name: "Attachments + chips + text",
+ args: {
+ sessionId: "sb-everything",
+ text: SAMPLE_TEXT,
+ channelContext: true,
+ attachments: [attachment("screenshot.png"), attachment("trace.json")],
+ chips: [
+ { type: "file", id: "/src/index.ts", label: "src/index.ts" },
+ { type: "command", id: "review", label: "review" },
+ ],
+ },
+};
+
+// --- Bash mode ---
+
+export const BashModeEmpty: Story = {
+ name: "Bash mode: just the bang",
+ args: { sessionId: "sb-bash-empty", text: "!" },
+};
+
+export const BashModeFilled: Story = {
+ name: "Bash mode: with a command",
+ args: { sessionId: "sb-bash-filled", text: "!git status --short" },
+};
+
+export const BashModeDisabled: Story = {
+ name: "Bash mode: disabled (bang is plain text)",
+ args: {
+ sessionId: "sb-bash-off",
+ enableBashMode: false,
+ text: "!git status --short",
+ },
+};
+
+// --- Run state ---
+
+export const Loading: Story = {
+ name: "Running (stop button)",
+ args: { sessionId: "sb-loading", isLoading: true, text: SAMPLE_TEXT },
+};
+
+export const Disabled: Story = {
+ args: { sessionId: "sb-disabled", disabled: true, text: SAMPLE_TEXT },
+};
+
+export const EditingQueued: Story = {
+ name: "Editing a queued message",
+ args: {
+ sessionId: "sb-editing",
+ text: SAMPLE_TEXT,
+ isEditingQueued: true,
+ onCancelEdit: () => {},
+ submitTooltipOverride: "Save edit",
+ },
+};
+
+export const SubmitBlocked: Story = {
+ name: "Submit blocked externally",
+ args: {
+ sessionId: "sb-blocked",
+ text: SAMPLE_TEXT,
+ submitDisabledExternal: true,
+ },
+};
+
+// --- Toolbar composition ---
+
+export const NoSelectors: Story = {
+ name: "Toolbar: no model or reasoning",
+ args: { sessionId: "sb-no-selectors", showSelectors: false },
+};
+
+export const NoMode: Story = {
+ name: "Toolbar: no mode",
+ args: { sessionId: "sb-no-mode", showMode: false },
+};
+
+export const NoContextUsage: Story = {
+ name: "Toolbar: no context ring",
+ args: { sessionId: "sb-no-usage", contextUsage: null },
+};
+
+export const ContextNearlyFull: Story = {
+ name: "Toolbar: context nearly full",
+ args: { sessionId: "sb-usage-full", contextUsage: nearFullUsage },
+};
+
+export const ToolbarBare: Story = {
+ name: "Toolbar: nothing but attach",
+ args: {
+ sessionId: "sb-bare",
showSelectors: false,
+ showMode: false,
+ showHistory: false,
+ showSteerQueue: false,
+ contextUsage: null,
+ },
+};
+
+export const NoToolbar: Story = {
+ name: "Toolbar: hidden entirely",
+ args: {
+ sessionId: "sb-no-toolbar",
+ hideDefaultToolbar: true,
+ showHistory: false,
+ showSteerQueue: false,
+ contextUsage: null,
+ text: SAMPLE_TEXT,
+ },
+};
+
+export const WithHeaderAddon: Story = {
+ name: "Header addon above the editor",
+ args: {
+ sessionId: "sb-header",
+ text: SAMPLE_TEXT,
+ headerAddon: (
+ <span className="text-[12px] text-muted-foreground">
+ Autoresearch armed — the next send iterates on its own
+ </span>
+ ),
},
};
+
+// --- The whole grid at once ---
+
+const MATRIX: Array<{ label: string; args: Partial<HarnessProps> }> = [
+ { label: "Empty", args: {} },
+ { label: "Filled", args: { text: SAMPLE_TEXT } },
+ { label: "Bash mode", args: { text: "!git status" } },
+ {
+ label: "Chips",
+ args: { chips: [{ type: "file", id: "/a.ts", label: "a.ts" }] },
+ },
+ { label: "Attachment", args: { attachments: [attachment("shot.png")] } },
+ {
+ label: "Attachment + channel context",
+ args: { channelContext: true, attachments: [attachment("shot.png")] },
+ },
+ {
+ label: "Everything",
+ args: {
+ text: SAMPLE_TEXT,
+ channelContext: true,
+ attachments: [attachment("shot.png"), attachment("trace.json")],
+ chips: [{ type: "command", id: "review", label: "review" }],
+ },
+ },
+ { label: "Running", args: { isLoading: true, text: SAMPLE_TEXT } },
+ { label: "Disabled", args: { disabled: true, text: SAMPLE_TEXT } },
+ {
+ label: "No selectors",
+ args: { showSelectors: false, text: SAMPLE_TEXT },
+ },
+ {
+ label: "Attach only",
+ args: {
+ showSelectors: false,
+ showMode: false,
+ showHistory: false,
+ showSteerQueue: false,
+ contextUsage: null,
+ },
+ },
+ {
+ label: "Toolbar hidden",
+ args: {
+ hideDefaultToolbar: true,
+ showHistory: false,
+ showSteerQueue: false,
+ contextUsage: null,
+ text: SAMPLE_TEXT,
+ },
+ },
+ { label: "Context nearly full", args: { contextUsage: nearFullUsage } },
+];
+
+export const Matrix: Story = {
+ name: "Matrix (every state on one page)",
+ parameters: { layout: "fullscreen" },
+ decorators: [
+ (Story) => (
+ <div className="p-4">
+ <Story />
+ </div>
+ ),
+ ],
+ render: (args) => (
+ <div className="flex flex-col gap-6">
+ {MATRIX.map((variant, index) => (
+ <div key={variant.label} className="flex flex-col gap-1">
+ <span className="font-medium text-[12px] text-muted-foreground">
+ {variant.label}
+ </span>
+ <div className="max-w-[800px]">
+ <PromptInputHarness
+ {...args}
+ {...variant.args}
+ autoFocus={false}
+ sessionId={`sb-matrix-${index}`}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ ),
+};
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.test.tsx b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.test.tsx
index e56f646a672b..9f39fa5f493b 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.test.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.test.tsx
@@ -70,13 +70,7 @@ vi.mock("./SlotMachineSubmit", () => ({
}));
vi.mock("@posthog/quill", () => ({
- InputGroup: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- InputGroupAddon: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- InputGroupButton: ({
+ Button: ({
children,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
@@ -84,6 +78,12 @@ vi.mock("@posthog/quill", () => ({
{children}
</button>
),
+ InputGroup: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ InputGroupAddon: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
}));
import { PromptInput } from "./PromptInput";
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
index 45bc9aad1c00..46a08b2286a2 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
@@ -2,7 +2,12 @@ import "./message-editor.css";
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
import { ArrowUp, StopCircle } from "@phosphor-icons/react";
import type { FileAttachment } from "@posthog/core/message-editor/content";
-import { InputGroup, InputGroupAddon, InputGroupButton } from "@posthog/quill";
+import {
+ Button,
+ InputGroup,
+ InputGroupAddon,
+ TooltipProvider,
+} from "@posthog/quill";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import type { PromptRecallHandler } from "@posthog/ui/features/sessions/components/chat-thread/composerPromptRecall";
import { cycleModeOption } from "@posthog/ui/features/sessions/sessionStore";
@@ -66,15 +71,28 @@ export interface PromptInputProps {
reasoningSelector?: React.ReactElement | null | false;
messagingModeToggle?: React.ReactNode;
historyButton?: React.ReactNode;
+ /**
+ * Rendered in the attachments row at the top of the composer, ahead of the
+ * attachments themselves — for context the prompt carries that the user did
+ * not attach by hand (e.g. a channel's CONTEXT.md).
+ */
+ attachmentsPrefix?: React.ReactNode;
+ /**
+ * Pushed to the far end of the composer's toolbar row — for read-only status
+ * about the session the prompt goes to (e.g. context usage), as opposed to
+ * the controls on the left that change what sending does.
+ */
+ toolbarEndSlot?: React.ReactNode;
/**
* Rendered inside the composer box, above the editor — for mode chrome
* that must read as part of the input itself (e.g. autoresearch controls)
* rather than a separate widget attached outside it.
*/
headerAddon?: React.ReactNode;
- // Render an empty toolbar (no attach/mode/model/reasoning/history/submit).
- // Submission falls back to the Enter key. Used by surfaces that want the
- // editor chrome without any controls yet (e.g. the canvas composer).
+ // Drop the toolbar row's own controls (attach/mode/model/reasoning/history).
+ // The row itself is omitted unless a caller slot still needs it, and send
+ // stays put — it lives in the box, not the row. Used by surfaces that want
+ // the editor chrome without any controls yet (e.g. the canvas composer).
hideDefaultToolbar?: boolean;
// prompt history provider
getPromptHistory?: () => string[];
@@ -131,6 +149,8 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
reasoningSelector,
messagingModeToggle,
historyButton,
+ attachmentsPrefix,
+ toolbarEndSlot,
headerAddon,
hideDefaultToolbar = false,
getPromptHistory,
@@ -355,7 +375,11 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
doSubmit();
};
- const submitBlocked = submitDisabledExternal || isEmpty;
+ // `disabled` counts: every caller sets it for a state where sending is
+ // impossible or would repeat itself (task creation in flight, a session
+ // that is not running, a compacting Pi session), and the editor cannot be
+ // typed into, so a live send button only invites a click that misfires.
+ const submitBlocked = disabled || submitDisabledExternal || isEmpty;
const submitTooltip =
submitTooltipOverride ??
(submitBlocked ? "Enter a message" : "Send message");
@@ -363,115 +387,150 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
// Stop takes priority over everything: you cancel a run, you don't gamble
// on it. With slot machine mode on, the send affordance moves out to the
// pull-lever mounted beside the composer, so the toolbar slot is empty.
+ // A real quill Button, not InputGroupButton: this is the composer's primary
+ // action and should carry the design system's raised primary treatment
+ // rather than the flat in-field styling. Stop shares the slot, so it uses
+ // the same component — otherwise the button would change shape mid-run.
const inStopMode = isLoading && !!onCancel;
const submitButton = inStopMode ? (
<Tooltip content="Stop">
- <InputGroupButton
+ <Button
variant="destructive"
- size="icon-sm"
+ size="icon"
onClick={onCancel}
aria-label="Stop"
>
<StopCircle size={14} weight="fill" />
- </InputGroupButton>
+ </Button>
</Tooltip>
) : slotMachineMode ? null : (
<Tooltip content={submitTooltip}>
- <InputGroupButton
+ <Button
variant="primary"
- size="icon-sm"
+ size="icon"
onClick={handleSubmitClick}
disabled={submitBlocked}
aria-label="Send message"
{...(tourTarget && { "data-tour": `${tourTarget}-submit` })}
>
<ArrowUp size={14} weight="bold" />
- </InputGroupButton>
+ </Button>
</Tooltip>
);
- return (
- <Flex direction="column" gap="1">
- <Flex gap="2" align="stretch">
- <InputGroup
- onClick={handleContainerClick}
- onContextMenu={handleContextMenu}
- className={`h-auto flex-1 cursor-text bg-card ${isBashMode ? "ring-1 ring-blue-9" : "focus-within:border-ring/50 focus-within:ring-3 focus-within:ring-ring/30"}`}
- {...(tourTarget && {
- "data-tour": `${tourTarget}-editor`,
- "data-tour-ready": !isEmpty ? "true" : undefined,
- })}
- >
- {headerAddon && (
- <InputGroupAddon align="block-start">
- {headerAddon}
- </InputGroupAddon>
+ // The controls sit under the box rather than inside it, so the box holds
+ // only what you are writing plus the send button. Mirrors the addons' own
+ // flex/gap/padding so the row keeps their spacing and left inset, and
+ // carries the muted colour the addons would have supplied.
+ const toolbar = (!hideDefaultToolbar ||
+ toolbarEndSlot ||
+ messagingModeToggle) && (
+ <div className="flex select-none items-center gap-1 whitespace-nowrap px-1 text-muted-foreground">
+ {!hideDefaultToolbar && (
+ <>
+ <AttachmentMenu
+ disabled={disabled}
+ repoPath={repoPath}
+ taskId={taskId}
+ onAddAttachment={addAttachment}
+ onAttachFiles={onAttachFiles}
+ onInsertChip={insertChip}
+ onRemoveChip={removeChipById}
+ />
+ {onModeChange && (
+ <ModeSelector
+ modeOption={modeOption}
+ onChange={onModeChange}
+ allowBypassPermissions={allowBypassPermissions}
+ disabled={disabled}
+ autoresearch={autoresearch}
+ canvas={canvas}
+ />
)}
- {attachments.length > 0 && (
- <InputGroupAddon align="block-start">
+ {modelSelector && <span>{modelSelector}</span>}
+ {reasoningSelector && <span>{reasoningSelector}</span>}
+ {isBashMode && (
+ <Text className="font-mono text-(--blue-9) text-[13px]">
+ ! bash
+ </Text>
+ )}
+ </>
+ )}
+ <span className="ml-auto flex items-center gap-1">
+ {toolbarEndSlot}
+ {!hideDefaultToolbar && historyButton}
+ {messagingModeToggle}
+ </span>
+ </div>
+ );
+
+ const composerRow = (
+ <Flex gap="2" align="stretch">
+ <InputGroup
+ onClick={handleContainerClick}
+ onContextMenu={handleContextMenu}
+ className={`h-auto flex-1 cursor-text bg-card ${isBashMode ? "ring-1 ring-blue-9" : "focus-within:border-ring/50 focus-within:ring-3 focus-within:ring-ring/30"}`}
+ {...(tourTarget && {
+ "data-tour": `${tourTarget}-editor`,
+ "data-tour-ready": !isEmpty ? "true" : undefined,
+ })}
+ >
+ {headerAddon && (
+ <InputGroupAddon align="block-start">{headerAddon}</InputGroupAddon>
+ )}
+ {(attachmentsPrefix || attachments.length > 0) && (
+ <InputGroupAddon align="block-start">
+ {/* One provider for the row: moving between squares reuses the
+ open delay instead of re-waiting it per attachment. */}
+ <TooltipProvider>
+ {attachmentsPrefix}
<AttachmentsBar
attachments={attachments}
onRemove={removeAttachment}
uploadStatuses={attachmentUploadStatuses}
/>
- </InputGroupAddon>
- )}
+ </TooltipProvider>
+ </InputGroupAddon>
+ )}
+ {/* Send floats over the text's bottom-right rather than sitting in a
+ column beside it. Laid out beside the text, it would push the
+ scroll container inwards and strand the scrollbar mid-box; over
+ it, the container runs to the edge and the bar hugs it. The text
+ reserves the button's width so a long line never runs underneath. */}
+ <div className="relative w-full">
<div
className={clsx(
- "cli-editor-scroll relative min-h-[50px] w-full flex-1 overflow-y-auto px-2 py-2 text-[14px]",
+ "cli-editor-scroll relative min-h-[37px] w-full overflow-y-auto py-2 pr-10 pl-2 text-[14px]",
editorHeight === "large" ? "max-h-[45vh]" : "max-h-[200px]",
+ // A disabled editor still looks editable: the caret is the only
+ // tell, and it is absent precisely because you cannot focus it.
+ disabled && "text-muted-foreground",
+ // What you are typing in bash mode is a shell command, so it
+ // should look like one.
+ isBashMode && "font-mono",
)}
>
<EditorContent editor={editor} />
</div>
- <InputGroupAddon align="block-end" className="p-1">
- {!hideDefaultToolbar && (
- <>
- <AttachmentMenu
- disabled={disabled}
- repoPath={repoPath}
- taskId={taskId}
- onAddAttachment={addAttachment}
- onAttachFiles={onAttachFiles}
- onInsertChip={insertChip}
- onRemoveChip={removeChipById}
- />
- {onModeChange && (
- <ModeSelector
- modeOption={modeOption}
- onChange={onModeChange}
- allowBypassPermissions={allowBypassPermissions}
- disabled={disabled}
- autoresearch={autoresearch}
- canvas={canvas}
- />
- )}
- {modelSelector && <span>{modelSelector}</span>}
- {reasoningSelector && <span>{reasoningSelector}</span>}
- {messagingModeToggle && <span>{messagingModeToggle}</span>}
- {isBashMode && (
- <Text className="font-mono text-(--blue-9) text-[13px]">
- ! bash
- </Text>
- )}
- </>
- )}
- {/* Submit stays even with a blank toolbar; only the left-side
- addons are suppressed. */}
- <span className="ml-auto flex items-center gap-1">
- {!hideDefaultToolbar && historyButton}
- {submitButton}
- </span>
- </InputGroupAddon>
- </InputGroup>
- {slotMachineMode && !inStopMode && (
- <SlotMachineSubmit
- disabled={submitBlocked}
- onSubmit={doSubmit}
- tourTarget={tourTarget}
- />
- )}
- </Flex>
+ {submitButton && (
+ <span className="absolute right-2 bottom-1">{submitButton}</span>
+ )}
+ </div>
+ </InputGroup>
+ {slotMachineMode && !inStopMode && (
+ <SlotMachineSubmit
+ disabled={submitBlocked}
+ onSubmit={doSubmit}
+ tourTarget={tourTarget}
+ />
+ )}
+ </Flex>
+ );
+
+ return (
+ <Flex direction="column" gap="1">
+ {composerRow}
+ {toolbar}
</Flex>
);
},
diff --git a/products/desktop/packages/ui/src/features/message-editor/fileKind.test.ts b/products/desktop/packages/ui/src/features/message-editor/fileKind.test.ts
new file mode 100644
index 000000000000..bc971f7ec97c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/fileKind.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { fileExtensionLabel } from "./fileKind";
+
+describe("fileExtensionLabel", () => {
+ it.each([
+ ["notes.md", ".md"],
+ ["NOTES.MD", ".md"],
+ ["a.test.ts", ".ts"],
+ ["clipboard.png", ".png"],
+ [".env", null],
+ ["Makefile", null],
+ ["trailing.", null],
+ ])("labels %s as %s", (filename, expected) => {
+ expect(fileExtensionLabel(filename)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/fileKind.ts b/products/desktop/packages/ui/src/features/message-editor/fileKind.ts
new file mode 100644
index 000000000000..560eeb8d3913
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/fileKind.ts
@@ -0,0 +1,12 @@
+/**
+ * A file's extension, dotted and lowercased, for the face of an attachment
+ * square (`.md`, `.json`). Null when there is nothing useful to show — a
+ * dotfile or an extensionless name — so callers can fall back to a glyph.
+ */
+export function fileExtensionLabel(filename: string): string | null {
+ // `lastIndexOf` over split: a dotfile (`.env`) has no extension, and a
+ // multi-dot name (`a.test.ts`) is typed by its last segment.
+ const dot = filename.lastIndexOf(".");
+ if (dot <= 0 || dot === filename.length - 1) return null;
+ return `.${filename.slice(dot + 1).toLowerCase()}`;
+}
diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
index 64a87562f51c..abc8608cea5e 100644
--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
@@ -27,6 +27,7 @@ import {
CloudConnectionBanner,
CloudStreamDisconnectedBanner,
} from "@posthog/ui/features/sessions/components/CloudSessionLifecycle";
+import { ContextUsageIndicator } from "@posthog/ui/features/sessions/components/ContextUsageIndicator";
import { ChatThread } from "@posthog/ui/features/sessions/components/chat-thread/ChatThread";
import type { PromptRecallHandler } from "@posthog/ui/features/sessions/components/chat-thread/composerPromptRecall";
import { focusComposerOnPaneClick } from "@posthog/ui/features/sessions/components/focusComposerOnPaneClick";
@@ -393,7 +394,6 @@ export function PiSessionView({
isPromptPending={isStreaming}
taskId={taskId}
repoPath={repoPath}
- usage={contextUsage}
promptRecallRef={promptRecallRef}
/>
</Box>
@@ -408,6 +408,7 @@ export function PiSessionView({
/>
<PromptInput
sessionId={taskId}
+ toolbarEndSlot={<ContextUsageIndicator usage={contextUsage} />}
taskId={taskId}
repoPath={repoPath}
placeholder="Type a message..."
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx
index 2379254317a4..adb73299c6c6 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx
@@ -5,7 +5,6 @@ import {
getOverallUsageColor,
} from "@posthog/ui/features/sessions/contextColors";
import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
-import { Flex, Text } from "@radix-ui/themes";
interface ContextBreakdownPopoverProps {
usage: ContextUsage;
@@ -23,22 +22,20 @@ export function ContextBreakdownPopover({
const hasSize = size > 0;
return (
- <Flex direction="column" gap="3" className="min-w-[280px]">
- <Flex align="center" justify="between">
- <Text className="font-medium text-(--gray-12) text-[13px]">
- Context
- </Text>
- <Text className="text-(--gray-10) text-[12px] tabular-nums">
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-6">
+ <span className="font-medium text-[13px] text-foreground">Context</span>
+ <span className="text-[12px] text-muted-foreground tabular-nums">
{hasSize
? `~${formatTokensCompact(used)} / ${formatTokensCompact(size)} tokens`
: `~${formatTokensCompact(used)} tokens`}
- </Text>
- </Flex>
+ </span>
+ </div>
{hasSize && (
- <Text className="font-semibold text-(--gray-12) text-[15px]">
+ <span className="font-semibold text-[15px] text-foreground">
{percentage}% full
- </Text>
+ </span>
)}
{breakdown ? (
@@ -48,48 +45,42 @@ export function ContextBreakdownPopover({
)}
{breakdown && (
- <Flex direction="column" gap="2">
+ <div className="flex flex-col gap-2">
{CONTEXT_CATEGORIES.filter((c) => breakdown[c.key] > 0).map((cat) => (
- <Flex
+ <div
key={cat.key}
- align="center"
- justify="between"
- className="text-[13px]"
+ className="flex items-center justify-between gap-6 text-[13px]"
>
- <Flex align="center" gap="2">
+ <span className="flex items-center gap-2">
<span
className="inline-block size-2.5 rounded-sm"
style={{ backgroundColor: cat.color }}
/>
- <Text className="text-(--gray-12)">{cat.label}</Text>
- </Flex>
- <Text className="text-(--gray-11) tabular-nums">
+ <span className="text-foreground">{cat.label}</span>
+ </span>
+ <span className="text-muted-foreground tabular-nums">
{formatTokensCompact(breakdown[cat.key])}
- </Text>
- </Flex>
+ </span>
+ </div>
))}
- </Flex>
+ </div>
)}
{!breakdown && usage.breakdownAvailable !== false && (
- <Text className="text-(--gray-10) text-[12px]">
+ <span className="text-[12px] text-muted-foreground">
Detailed breakdown available after the first response.
- </Text>
+ </span>
)}
{showCost && cost && (
- <Flex
- align="center"
- justify="between"
- className="border-(--gray-4) border-t pt-2 text-[13px]"
- >
- <Text className="text-(--gray-11)">Estimated cost</Text>
- <Text className="font-medium text-(--gray-12) tabular-nums">
+ <div className="flex items-center justify-between border-border border-t pt-2 text-[13px]">
+ <span className="text-muted-foreground">Estimated cost</span>
+ <span className="font-medium text-foreground tabular-nums">
{formatCostUsd(cost.amount)}
- </Text>
- </Flex>
+ </span>
+ </div>
)}
- </Flex>
+ </div>
);
}
@@ -103,13 +94,13 @@ function SegmentedBar({
fallback: string;
}) {
if (size <= 0) {
- return <div className="h-1.5 w-full rounded-full bg-(--gray-4)" />;
+ return <div className="h-1.5 w-full rounded-full bg-muted" />;
}
// Scale each segment to the full context window so the filled portion
// matches the "% full" figure and the empty track reads as remaining context.
return (
- <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-(--gray-4)">
+ <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-muted">
{CONTEXT_CATEGORIES.map((cat) => {
const value = breakdown[cat.key];
if (value <= 0) return null;
@@ -135,7 +126,7 @@ function SinglePercentBar({
color: string;
}) {
return (
- <div className="h-1.5 w-full overflow-hidden rounded-full bg-(--gray-4)">
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className="h-full rounded-full"
style={{ width: `${percentage}%`, backgroundColor: color }}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx
index 08013c518136..cf048a7590ad 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx
@@ -1,6 +1,6 @@
import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { Theme } from "@radix-ui/themes";
-import { render, screen } from "@testing-library/react";
+import { render } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContextUsageIndicator } from "./ContextUsageIndicator";
@@ -34,44 +34,35 @@ describe("ContextUsageIndicator", () => {
expect(container.querySelector("button")).toBeNull();
});
- it("renders the compact used/size label, percentage, and aria-label", () => {
- render(
- <Theme>
- <ContextUsageIndicator usage={usage()} />
- </Theme>,
- );
- expect(screen.getByText(/50K\/200K · 25%/)).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "Context usage: 25%" }),
- ).toBeInTheDocument();
- });
-
- it("shows only the token count when the context window is unknown (size 0)", () => {
- render(
+ // The ring carries no text, so the accessible name is the only way the
+ // numbers reach a reader — including the "/0 · 0%" an unknown window must
+ // never claim, and the cost the flag is supposed to surface.
+ it.each([
+ ["a known window", {}, false, "Context usage: 25%"],
+ [
+ "an unknown window (size 0)",
+ { used: 50_000, size: 0, percentage: 0 },
+ false,
+ "Context usage: 50K tokens",
+ ],
+ [
+ "cost enabled",
+ { cost: { amount: 0.42, currency: "USD" } },
+ true,
+ "Context usage: 25% · $0.42",
+ ],
+ ])("names itself for %s", (_case, overrides, costEnabled, expected) => {
+ flagState.enabled = costEnabled;
+ const { container } = render(
<Theme>
<ContextUsageIndicator
- usage={usage({ used: 50_000, size: 0, percentage: 0 })}
+ usage={usage(overrides as Partial<ContextUsage>)}
/>
</Theme>,
);
- // No misleading "/0 · 0%" — just the used tokens.
- expect(screen.getByText("50K")).toBeInTheDocument();
- expect(screen.queryByText(/\/0/)).not.toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "Context usage: 50K tokens" }),
- ).toBeInTheDocument();
- });
-
- it("appends the estimated cost to the label when the flag is enabled", () => {
- flagState.enabled = true;
- render(
- <Theme>
- <ContextUsageIndicator
- usage={usage({ cost: { amount: 0.42, currency: "USD" } })}
- />
- </Theme>,
+ expect(container.querySelector("button")?.getAttribute("aria-label")).toBe(
+ expected,
);
- expect(screen.getByText(/50K\/200K · 25% · \$0\.42/)).toBeInTheDocument();
});
it("renders a finite stroke offset at 0% (no NaN/Infinity)", () => {
@@ -85,6 +76,5 @@ describe("ContextUsageIndicator", () => {
const progress = container.querySelectorAll("circle")[1];
const offset = Number(progress?.getAttribute("stroke-dashoffset"));
expect(Number.isFinite(offset)).toBe(true);
- expect(screen.getByText(/0\/200K · 0%/)).toBeInTheDocument();
});
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx
index c088a620beec..46f002f3dde0 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx
@@ -1,3 +1,9 @@
+import {
+ Button,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@posthog/quill";
import { TASK_COST_FLAG } from "@posthog/shared";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import {
@@ -6,7 +12,6 @@ import {
getOverallUsageColor,
} from "@posthog/ui/features/sessions/contextColors";
import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
-import { Flex, Popover, Text } from "@radix-ui/themes";
import { ContextBreakdownPopover } from "./ContextBreakdownPopover";
const CIRCLE_SIZE = 20;
@@ -30,30 +35,27 @@ export function ContextUsageIndicator({ usage }: ContextUsageIndicatorProps) {
const strokeDashoffset = CIRCUMFERENCE - (percentage / 100) * CIRCUMFERENCE;
const color = getOverallUsageColor(percentage);
const showCost = costEnabled && cost !== null;
- const tokenLabel = hasSize
- ? `${formatTokensCompact(used)}/${formatTokensCompact(size)} · ${percentage}%`
- : formatTokensCompact(used);
- const label = showCost
- ? `${tokenLabel} · ${formatCostUsd(cost.amount)}`
- : tokenLabel;
-
return (
- <Popover.Root>
- <Popover.Trigger>
- <button
- type="button"
- className="flex cursor-pointer select-none items-center gap-1 bg-transparent"
- aria-label={
- hasSize
- ? `Context usage: ${percentage}%`
- : `Context usage: ${formatTokensCompact(used)} tokens`
- }
- >
- <Flex align="center" gap="1">
+ <Popover>
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ variant="default"
+ size="icon-sm"
+ aria-label={
+ hasSize
+ ? `Context usage: ${percentage}%` +
+ (showCost ? ` · ${formatCostUsd(cost.amount)}` : "")
+ : `Context usage: ${formatTokensCompact(used)} tokens` +
+ (showCost ? ` · ${formatCostUsd(cost.amount)}` : "")
+ }
+ >
+ {/* viewBox, not width/height: quill sizes a button's svg down to
+ its icon slot, which would crop an unscaled drawing. */}
<svg
- width={CIRCLE_SIZE}
- height={CIRCLE_SIZE}
- className="-rotate-90 shrink-0"
+ viewBox={`0 0 ${CIRCLE_SIZE} ${CIRCLE_SIZE}`}
+ className="-rotate-90 size-4 shrink-0"
role="img"
aria-hidden="true"
>
@@ -62,7 +64,7 @@ export function ContextUsageIndicator({ usage }: ContextUsageIndicatorProps) {
cy={CIRCLE_SIZE / 2}
r={RADIUS}
fill="none"
- stroke="var(--gray-5)"
+ stroke="var(--border)"
strokeWidth={STROKE_WIDTH}
/>
<circle
@@ -77,15 +79,19 @@ export function ContextUsageIndicator({ usage }: ContextUsageIndicatorProps) {
strokeLinecap="round"
/>
</svg>
- <Text className="text-[13px] text-muted-foreground tabular-nums">
- {label}
- </Text>
- </Flex>
- </button>
- </Popover.Trigger>
- <Popover.Content size="2" side="top" align="end" sideOffset={6}>
+ </Button>
+ }
+ />
+ {/* quill's popup is a fixed 18rem; the token figures sit on their own
+ line and would spill out of it. */}
+ <PopoverContent
+ side="top"
+ align="end"
+ sideOffset={6}
+ className="w-auto min-w-[280px] gap-3"
+ >
<ContextBreakdownPopover usage={usage} showCost={showCost} />
- </Popover.Content>
- </Popover.Root>
+ </PopoverContent>
+ </Popover>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx
index 6adcfcf52226..23609b838772 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx
@@ -51,7 +51,6 @@ import {
} from "@posthog/ui/features/sessions/components/VirtualizedList";
import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";
import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";
-import { useContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useConversationItems";
import { useConversationSearch } from "@posthog/ui/features/sessions/hooks/useConversationSearch";
import {
@@ -151,8 +150,6 @@ export function ConversationView({
const groupOverrides = useGroupOverrides();
const sessionViewActions = useSessionViewActions();
- const contextUsage = useContextUsage(events);
-
// 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
@@ -512,7 +509,6 @@ export function ConversationView({
hasPendingPermission={pendingPermissionsCount > 0}
pausedDurationMs={pausedDurationMs}
isCompacting={isCompacting}
- usage={contextUsage}
completedToolCallCount={completedToolCallCount}
/>
</div>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/PendingInputPlaceholder.tsx b/products/desktop/packages/ui/src/features/sessions/components/PendingInputPlaceholder.tsx
index 571fb1cdfd03..d33372a273bf 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/PendingInputPlaceholder.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/PendingInputPlaceholder.tsx
@@ -6,23 +6,21 @@ import { Box, Flex } from "@radix-ui/themes";
*/
export function PendingInputPlaceholder() {
return (
- <Box
- aria-hidden
- className="w-full rounded-(--radius-2) border border-(--gray-5) bg-card opacity-70"
- >
- <Box className="min-h-[50px] px-2 py-2">
- <Box className="h-3 w-2/5 animate-pulse rounded bg-gray-4" />
- </Box>
+ <Flex direction="column" gap="1" aria-hidden className="w-full opacity-70">
<Flex
- align="center"
- gap="2"
- className="border-(--gray-4) border-t px-2 py-1.5"
+ align="end"
+ className="rounded-(--radius-2) border border-(--gray-5) bg-card"
>
- <Box className="h-5 w-5 animate-pulse rounded bg-gray-4" />
- <Box className="h-5 w-16 animate-pulse rounded bg-gray-4" />
- <Box className="h-5 w-20 animate-pulse rounded bg-gray-4" />
- <Box className="ml-auto h-6 w-6 animate-pulse rounded bg-gray-5" />
+ <Box className="min-h-[37px] flex-1 px-2 py-2">
+ <Box className="h-3 w-2/5 animate-pulse rounded bg-gray-4" />
+ </Box>
+ <Box className="m-1 h-7 w-7 shrink-0 animate-pulse rounded bg-gray-5" />
</Flex>
- </Box>
+ <Flex align="center" gap="1" className="px-1">
+ <Box className="h-6 w-6 animate-pulse rounded bg-gray-4" />
+ <Box className="h-6 w-16 animate-pulse rounded bg-gray-4" />
+ <Box className="h-6 w-28 animate-pulse rounded bg-gray-4" />
+ </Flex>
+ </Flex>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
index 03179f28ce2f..2866bd8f424a 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
@@ -4,10 +4,7 @@ import type {
} from "@agentclientprotocol/sdk";
import {
ArrowCounterClockwise,
- CaretDown,
- Cpu,
Lightning,
- Robot,
Spinner,
} from "@phosphor-icons/react";
import {
@@ -58,11 +55,6 @@ const ADAPTER_LABELS: Record<AgentAdapter, string> = {
codex: "Codex",
};
-const ADAPTER_ICONS: Record<AgentAdapter, React.ReactNode> = {
- claude: <Robot size={14} weight="regular" />,
- codex: <Cpu size={14} weight="regular" />,
-};
-
// Separates model and effort in a slider stop key; never appears in ids.
const STOP_SEPARATOR = "|";
@@ -319,12 +311,17 @@ export function ReasoningLevelSelector({
});
};
+ // Both labels can be blank while a config reloads. The trigger has no icon
+ // to fall back on, so it would render as an empty pill announced as
+ // "Reasoning: undefined".
const triggerAriaLabel =
modelLabel && effortLabel
? `Model and reasoning: ${modelLabel} ${effortLabel}`
: modelLabel
? `Model: ${modelLabel}`
- : `Reasoning: ${effortLabel}`;
+ : effortLabel
+ ? `Reasoning: ${effortLabel}`
+ : "Model and reasoning";
return (
<DropdownMenu
@@ -357,16 +354,10 @@ export function ReasoningLevelSelector({
fastActive ? "ring-1 ring-amber-9 ring-inset" : undefined
}
>
- {fastActive ? (
+ {fastActive && (
<span className="text-amber-11">
<Lightning size={14} weight="fill" />
</span>
- ) : (
- adapter && (
- <span className="text-muted-foreground">
- {ADAPTER_ICONS[adapter]}
- </span>
- )
)}
{modelLabel && (
<span className="font-medium text-foreground">{modelLabel}</span>
@@ -382,11 +373,9 @@ export function ReasoningLevelSelector({
{effortLabel}
</span>
)}
- <CaretDown
- size={10}
- weight="bold"
- className="text-muted-foreground"
- />
+ {!modelLabel && !effortLabel && (
+ <span className="font-medium text-foreground">Model</span>
+ )}
</Button>
}
/>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionFooter.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionFooter.tsx
index 82548518d783..788da9abe0f4 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionFooter.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionFooter.tsx
@@ -1,11 +1,9 @@
import { Brain, Pause } from "@phosphor-icons/react";
import type { Task } from "@posthog/shared/domain-types";
-import { ContextUsageIndicator } from "@posthog/ui/features/sessions/components/ContextUsageIndicator";
import {
formatDuration,
GeneratingIndicator,
} from "@posthog/ui/features/sessions/components/GeneratingIndicator";
-import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { Box, Flex, Text } from "@radix-ui/themes";
import { DiffStatsChip } from "./DiffStatsChip";
import { ImageBuilderBuildButton } from "./ImageBuilderBuildButton";
@@ -21,7 +19,6 @@ interface SessionFooterProps {
hasPendingPermission?: boolean;
pausedDurationMs?: number;
isCompacting?: boolean;
- usage?: ContextUsage | null;
/** Number of tool calls finished so far; the generating indicator advances
* its status word each time this changes. */
completedToolCallCount?: number;
@@ -37,7 +34,6 @@ export function SessionFooter({
hasPendingPermission = false,
pausedDurationMs,
isCompacting = false,
- usage,
completedToolCallCount,
}: SessionFooterProps) {
const rightSide = (
@@ -46,7 +42,6 @@ export function SessionFooter({
<ImageBuilderBuildButton taskId={task.id} />
)}
{task && <DiffStatsChip task={task} />}
- <ContextUsageIndicator usage={usage ?? null} />
</Flex>
);
if (isPromptPending && !isCompacting) {
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 5ed90a943a98..64e8075cf199 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -27,6 +27,7 @@ import {
CloudStreamDisconnectedBanner,
ConnectingToAgent,
} from "@posthog/ui/features/sessions/components/CloudSessionLifecycle";
+import { ContextUsageIndicator } from "@posthog/ui/features/sessions/components/ContextUsageIndicator";
import type { PromptRecallHandler } from "@posthog/ui/features/sessions/components/chat-thread/composerPromptRecall";
import {
copyFromContextMenu,
@@ -48,7 +49,11 @@ import {
submitComposerPrompt,
} from "@posthog/ui/features/sessions/components/submitComposerPrompt";
import { ThreadView } from "@posthog/ui/features/sessions/components/ThreadView";
-import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";
+import {
+ CHAT_CONTENT_MAX_WIDTH,
+ CHAT_CONTENT_PADDING_INLINE,
+} from "@posthog/ui/features/sessions/constants";
+import { useContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { useCancelQueuedMessageEdit } from "@posthog/ui/features/sessions/hooks/useEditQueuedMessage";
import { useSessionEventsResidency } from "@posthog/ui/features/sessions/hooks/useSessionEventsResidency";
import { useToggleMessagingMode } from "@posthog/ui/features/sessions/hooks/useToggleMessagingMode";
@@ -120,7 +125,15 @@ interface SessionViewProps {
const DEFAULT_ERROR_MESSAGE =
"Failed to resume this session. The working directory may have been deleted. Please start a new session.";
-/** Centers composer-slot content at the chat width (or compact padding). */
+/**
+ * Centers composer-slot content at the chat width (or compact padding).
+ *
+ * The composer reserves the same horizontal room as the thread's scroll
+ * content and caps at the same width, so the two columns are identical at
+ * every panel width rather than only once the panel is wide enough for the
+ * full column. Padding on the capped box instead of around it would eat into
+ * `CHAT_CONTENT_MAX_WIDTH` and leave the composer narrower than the messages.
+ */
function ComposerWidth({
compact,
children,
@@ -128,12 +141,18 @@ function ComposerWidth({
compact: boolean;
children: React.ReactNode;
}) {
+ if (compact) {
+ return <Box className="p-1">{children}</Box>;
+ }
+
return (
- <Box
- className={compact ? "p-1" : "mx-auto pb-2"}
- style={compact ? undefined : { maxWidth: CHAT_CONTENT_MAX_WIDTH }}
- >
- {children}
+ <Box style={{ paddingInline: CHAT_CONTENT_PADDING_INLINE }}>
+ <Box
+ className="mx-auto pb-2"
+ style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}
+ >
+ {children}
+ </Box>
</Box>
);
}
@@ -291,6 +310,7 @@ export function SessionView({
const isCloudRun = useIsWorkspaceCloudRun(taskId);
const editorRef = useRef<PromptInputHandle>(null);
+ const contextUsage = useContextUsage(events);
const sendInFlightRef = useRef(false);
const composerSubmissionRef = useRef(0);
const attachmentIdsRef = useRef<Set<string>>(new Set());
@@ -815,6 +835,9 @@ export function SessionView({
<SteerQueueToggle taskId={taskId} />
) : undefined
}
+ toolbarEndSlot={
+ <ContextUsageIndicator usage={contextUsage} />
+ }
onToggleMessagingMode={toggleMessagingMode}
onAttachmentsChange={handleAttachmentsChange}
attachmentUploadStatuses={attachmentUploadStatuses}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SteerQueueToggle.tsx b/products/desktop/packages/ui/src/features/sessions/components/SteerQueueToggle.tsx
index 5b51da75bdd2..73588263d473 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SteerQueueToggle.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SteerQueueToggle.tsx
@@ -1,5 +1,5 @@
import { Lightning, Stack } from "@phosphor-icons/react";
-import { Button } from "@posthog/quill";
+import { Button, cn } from "@posthog/quill";
import {
formatHotkey,
SHORTCUTS,
@@ -63,7 +63,20 @@ export function SteerQueueToggle({ taskId }: SteerQueueToggleProps) {
<Stack size={12} />
)}
</span>
- <span className={colorClass}>{label}</span>
+ {/* Both labels stack in one grid cell, so the button is always as wide
+ as the longer of them. Sized by the label alone, toggling modes
+ would shove the rest of the toolbar sideways. */}
+ <span className="grid">
+ <span aria-hidden className="invisible col-start-1 row-start-1">
+ Steer
+ </span>
+ <span aria-hidden className="invisible col-start-1 row-start-1">
+ Queue
+ </span>
+ <span className={cn("col-start-1 row-start-1", colorClass)}>
+ {label}
+ </span>
+ </span>
</Button>
</Tooltip>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/UnifiedModelSelector.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/UnifiedModelSelector.test.tsx
deleted file mode 100644
index 129e4fa04d5a..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/UnifiedModelSelector.test.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import type {
- SessionConfigOption,
- SessionConfigSelectGroup,
-} from "@agentclientprotocol/sdk";
-import { Theme } from "@radix-ui/themes";
-import { render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { describe, expect, it, vi } from "vitest";
-import { UnifiedModelSelector } from "./UnifiedModelSelector";
-
-const groupedCodexModel: SessionConfigOption = {
- type: "select",
- id: "model",
- name: "Model",
- category: "model",
- currentValue: "gpt-5.5",
- options: [
- {
- group: "openai",
- name: "OpenAI",
- options: [
- { value: "gpt-5.5", name: "GPT-5.5" },
- { value: "gpt-5.5-codex", name: "GPT-5.5 Codex" },
- ],
- },
- {
- group: "fable",
- name: "Fable",
- options: [{ value: "fable", name: "Fable" }],
- },
- ] satisfies SessionConfigSelectGroup[],
-};
-
-const flatCodexModel: SessionConfigOption = {
- type: "select",
- id: "model",
- name: "Model",
- category: "model",
- currentValue: "gpt-5.5",
- options: [
- { value: "gpt-5.5", name: "GPT-5.5" },
- { value: "fable", name: "Fable" },
- ],
-};
-
-function renderSelector(
- props: Partial<React.ComponentProps<typeof UnifiedModelSelector>> = {},
-) {
- return render(
- <Theme>
- <UnifiedModelSelector
- modelOption={groupedCodexModel}
- adapter="codex"
- onAdapterChange={vi.fn()}
- onModelChange={vi.fn()}
- {...props}
- />
- </Theme>,
- );
-}
-
-describe("UnifiedModelSelector", () => {
- it("renders the codex adapter label, group labels, and grouped model items", async () => {
- const user = userEvent.setup();
- renderSelector();
-
- await user.click(screen.getByRole("button", { name: "Model" }));
-
- // Every model in every group renders as a radio item.
- expect(
- await screen.findByRole("menuitemradio", { name: "GPT-5.5" }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("menuitemradio", { name: "GPT-5.5 Codex" }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("menuitemradio", { name: "Fable" }),
- ).toBeInTheDocument();
- // Adapter MenuLabel + group MenuLabels render.
- expect(screen.getByText("Codex")).toBeInTheDocument();
- expect(screen.getByText("OpenAI")).toBeInTheDocument();
- });
-
- it("renders flat (ungrouped) model items", async () => {
- const user = userEvent.setup();
- renderSelector({ modelOption: flatCodexModel });
-
- await user.click(screen.getByRole("button", { name: "Model" }));
-
- expect(
- await screen.findByRole("menuitemradio", { name: "GPT-5.5" }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("menuitemradio", { name: "Fable" }),
- ).toBeInTheDocument();
- });
-
- it("fires onModelChange exactly once with the picked value after the menu closes", async () => {
- const user = userEvent.setup();
- const onModelChange = vi.fn();
- renderSelector({ onModelChange });
-
- await user.click(screen.getByRole("button", { name: "Model" }));
- await user.click(
- await screen.findByRole("menuitemradio", { name: "GPT-5.5 Codex" }),
- );
-
- // onModelChange is deferred until the menu-close animation completes, so
- // wait for it rather than asserting synchronously after the click.
- await waitFor(() =>
- expect(onModelChange).toHaveBeenCalledExactlyOnceWith("gpt-5.5-codex"),
- );
- });
-
- it("switches adapter via the 'Switch to Claude' item", async () => {
- const user = userEvent.setup();
- const onAdapterChange = vi.fn();
- renderSelector({ onAdapterChange });
-
- await user.click(screen.getByRole("button", { name: "Model" }));
- await user.click(
- await screen.findByRole("menuitem", { name: /switch to claude/i }),
- );
-
- expect(onAdapterChange).toHaveBeenCalledExactlyOnceWith("claude");
- });
-
- it("renders a disabled loading button with no menu while connecting", () => {
- renderSelector({ isConnecting: true });
-
- const button = screen.getByRole("button", { name: /loading/i });
- expect(button).toHaveAttribute("aria-disabled", "true");
- expect(
- screen.queryByRole("button", { name: "Model" }),
- ).not.toBeInTheDocument();
- });
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/UnifiedModelSelector.tsx b/products/desktop/packages/ui/src/features/sessions/components/UnifiedModelSelector.tsx
deleted file mode 100644
index 34f979a2b0dc..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/UnifiedModelSelector.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-import type {
- SessionConfigOption,
- SessionConfigSelectGroup,
-} from "@agentclientprotocol/sdk";
-import {
- ArrowsClockwise,
- CaretDown,
- Cpu,
- Robot,
- Spinner,
-} from "@phosphor-icons/react";
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuRadioGroup,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
- MenuLabel,
-} from "@posthog/quill";
-import { gateRestrictedModelPick } from "@posthog/ui/features/billing/modelGate";
-import { ModelRadioItem } from "@posthog/ui/features/sessions/components/ModelRadioItem";
-import { flattenSelectOptions } from "@posthog/ui/features/sessions/sessionStore";
-import { useRetainedConfigOption } from "@posthog/ui/features/sessions/useRetainedConfigOption";
-import type { AgentAdapter } from "@posthog/ui/features/settings/settingsStore";
-import { Fragment, useMemo, useRef, useState } from "react";
-
-const ADAPTER_ICONS: Record<AgentAdapter, React.ReactNode> = {
- claude: <Robot size={14} weight="regular" />,
- codex: <Cpu size={14} weight="regular" />,
-};
-
-const ADAPTER_LABELS: Record<AgentAdapter, string> = {
- claude: "Claude Code",
- codex: "Codex",
-};
-
-function getOtherAdapter(adapter: AgentAdapter): AgentAdapter {
- return adapter === "claude" ? "codex" : "claude";
-}
-
-interface UnifiedModelSelectorProps {
- modelOption?: SessionConfigOption;
- adapter: AgentAdapter;
- onAdapterChange: (adapter: AgentAdapter) => void;
- onModelChange?: (model: string) => void;
- disabled?: boolean;
- isConnecting?: boolean;
-}
-
-export function UnifiedModelSelector({
- modelOption,
- adapter,
- onAdapterChange,
- onModelChange,
- disabled,
- isConnecting,
-}: UnifiedModelSelectorProps) {
- const [open, setOpen] = useState(false);
- const pendingValueRef = useRef<string | null>(null);
- // Keep the last model on the trigger while the new harness's config loads, so
- // the trigger doesn't shrink to the "Model" fallback and jostle the toolbar
- // mid-switch. The radio group below still renders from the live option once
- // loading finishes.
- const displayOption = useRetainedConfigOption(modelOption);
- const selectOption =
- displayOption?.type === "select" ? displayOption : undefined;
- const options = selectOption
- ? flattenSelectOptions(selectOption.options)
- : [];
- const groupedOptions = useMemo(() => {
- if (!selectOption || selectOption.options.length === 0) return [];
- if ("group" in selectOption.options[0]) {
- return selectOption.options as SessionConfigSelectGroup[];
- }
- return [];
- }, [selectOption]);
-
- const currentValue = selectOption?.currentValue;
- const currentLabel =
- options.find((option) => option.value === currentValue)?.name ??
- currentValue;
-
- const otherAdapter = getOtherAdapter(adapter);
-
- // Collapse to a bare loading button only while the menu is closed (initial
- // load). When the menu is open we keep it mounted and surface the loading
- // state inside the content instead — switching harness refetches the new
- // adapter's config, and unmounting here would dismiss the picker mid-switch
- // and force the user to reopen it just to choose a model.
- if (isConnecting && !open) {
- return (
- <Button type="button" variant="default" size="sm" disabled>
- <Spinner size={12} className="animate-spin" />
- Loading...
- </Button>
- );
- }
-
- return (
- <DropdownMenu
- open={open}
- onOpenChange={setOpen}
- onOpenChangeComplete={(isOpen) => {
- if (!isOpen && pendingValueRef.current !== null) {
- onModelChange?.(pendingValueRef.current);
- pendingValueRef.current = null;
- }
- }}
- >
- <DropdownMenuTrigger
- render={
- <Button
- type="button"
- variant="default"
- size="sm"
- disabled={disabled}
- aria-label="Model"
- >
- <span className="text-muted-foreground">
- {ADAPTER_ICONS[adapter]}
- </span>
- {currentLabel ?? "Model"}
- <CaretDown
- size={10}
- weight="bold"
- className="text-muted-foreground"
- />
- </Button>
- }
- />
- <DropdownMenuContent
- align="start"
- side="top"
- sideOffset={6}
- className="min-w-[220px]"
- >
- <MenuLabel>{ADAPTER_LABELS[adapter]}</MenuLabel>
- {isConnecting ? (
- <div className="flex items-center gap-2 px-2 py-1.5 text-muted-foreground">
- <Spinner size={12} className="animate-spin" />
- Loading...
- </div>
- ) : (
- <DropdownMenuRadioGroup
- value={currentValue ?? ""}
- onValueChange={(value) => {
- // A plan-restricted model opens the upgrade gate instead of
- // becoming the selection.
- if (gateRestrictedModelPick(options, value)) {
- pendingValueRef.current = null;
- setOpen(false);
- return;
- }
- pendingValueRef.current = value;
- setOpen(false);
- }}
- >
- {groupedOptions.length > 0
- ? groupedOptions.map((group, index) => (
- <Fragment key={group.group}>
- {index > 0 && <DropdownMenuSeparator />}
- <MenuLabel>{group.name}</MenuLabel>
- {group.options.map((model) => (
- <ModelRadioItem key={model.value} model={model} />
- ))}
- </Fragment>
- ))
- : options.map((model) => (
- <ModelRadioItem key={model.value} model={model} />
- ))}
- </DropdownMenuRadioGroup>
- )}
-
- <DropdownMenuSeparator />
-
- <DropdownMenuItem
- closeOnClick={false}
- onClick={() => onAdapterChange(otherAdapter)}
- >
- <ArrowsClockwise size={12} weight="bold" />
- Switch to {ADAPTER_LABELS[otherAdapter]}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
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 e96ed83084aa..8cf3210c9e58 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
@@ -6,7 +6,6 @@ import {
Scroll,
} from "@phosphor-icons/react";
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
-import type { ContextUsage } from "@posthog/core/sessions/contextUsage";
import { useService } from "@posthog/di/react";
import {
Button,
@@ -96,8 +95,8 @@ import { SessionUpdateView } from "@posthog/ui/features/sessions/components/sess
import { UserShellExecuteView } from "@posthog/ui/features/sessions/components/session-update/UserShellExecuteView";
import { UserMessageAttachments } from "@posthog/ui/features/sessions/components/UserMessageAttachments";
import {
- CHAT_CONTENT_GUTTER,
CHAT_CONTENT_MAX_WIDTH,
+ CHAT_CONTENT_PADDING_INLINE,
} from "@posthog/ui/features/sessions/constants";
import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";
import { useAgentConversationItems } from "@posthog/ui/features/sessions/hooks/useAgentConversationItems";
@@ -907,7 +906,7 @@ function ThreadScrollBody({
items: ConversationItem[];
rows: TurnRow[];
renderItem: (item: ConversationItem) => ReactNode;
- /** Status row (duration / context usage) pinned as the last item in the thread. */
+ /** Status row (duration / diff stats) pinned as the last item in the thread. */
footer?: ReactNode;
keyboardFocusedMessageId?: string | null;
/** Clears keyboard-focused message state on any pointer interaction with the thread. */
@@ -924,10 +923,12 @@ function ThreadScrollBody({
}, [rows]);
// `group/thread` so the footer's hover-reveal (opacity-50 → 100 on group-hover) tracks the thread,
- // mirroring the legacy ConversationView container.
+ // 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.
return (
<ChatMessageScroller
- className="group/thread"
+ className="@container/thread group/thread"
onPointerDownCapture={onUserInteract}
>
<MessageMinimap items={items} />
@@ -937,7 +938,7 @@ function ThreadScrollBody({
<ChatMessageScrollerContent
className="gap-4 py-4 pb-8"
density="default"
- style={{ paddingInline: CHAT_CONTENT_GUTTER }}
+ style={{ paddingInline: CHAT_CONTENT_PADDING_INLINE }}
>
{keyedRows.map(({ item, key }) => (
<ThreadRow
@@ -1041,7 +1042,6 @@ interface SharedChatThreadProps {
repoPath?: string | null;
task?: Task;
taskId?: string;
- usage?: ContextUsage | null;
footerState?: Omit<BuildResult, "items">;
}
@@ -1114,7 +1114,6 @@ function ChatThreadRenderer({
repoPath,
task,
taskId,
- usage,
footerState,
promptRecallRef,
}: ChatThreadRendererProps) {
@@ -1241,7 +1240,6 @@ function ChatThreadRenderer({
promptStartedAt={promptStartedAt}
task={task}
taskId={taskId}
- usage={usage}
footerState={footerState}
/>
</>
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 80af68e99154..cdd5d8185641 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
@@ -1,9 +1,7 @@
-import type { ContextUsage } from "@posthog/core/sessions/contextUsage";
import type { AcpMessage } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import type { BuildResult } from "@posthog/ui/features/sessions/components/buildConversationItems";
import { SessionFooter } from "@posthog/ui/features/sessions/components/SessionFooter";
-import { useContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useConversationItems";
import {
usePendingPermissionsForTask,
@@ -18,14 +16,13 @@ interface ChatThreadFooterProps {
promptStartedAt?: number | null;
task?: Task;
taskId?: string;
- usage?: ContextUsage | null;
footerState?: Omit<BuildResult, "items">;
}
/**
- * The session status footer (duration / queued / context usage / diff stats) for the new chat
- * thread, rendered UNDER the composer. The legacy `ConversationView` renders the same
- * `SessionFooter` at the bottom of the thread instead; here it lives under the input.
+ * 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.
*
* Re-derives the turn / usage / queue state from `events` with the same hooks `ConversationView`
* uses — `ChatThread` runs its own `useConversationItems`, so this is a second (incremental,
@@ -38,12 +35,9 @@ export function ChatThreadFooter({
promptStartedAt,
task,
taskId,
- usage,
footerState,
}: ChatThreadFooterProps) {
const showDebugLogs = useSettingsStore((s) => s.debugLogsCloudRuns);
- const eventContextUsage = useContextUsage(events);
- const contextUsage = usage === undefined ? eventContextUsage : usage;
const eventFooterState = useConversationItems(events, isPromptPending, {
showDebugLogs,
});
@@ -75,7 +69,6 @@ export function ChatThreadFooter({
hasPendingPermission={pendingPermissions.size > 0}
pausedDurationMs={pausedDurationMs}
isCompacting={isCompacting}
- usage={contextUsage}
completedToolCallCount={completedToolCallCount}
/>
</div>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx
index 001e1ae1028a..700c39269ba6 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx
@@ -151,8 +151,10 @@ export function MessageMinimap({
if (entries.length < 2) return null;
return (
- // Hugs the scroll container's top-right corner (clear of the scrollbar). The thread column
- // reserves CHAT_CONTENT_GUTTER on this side, so rows never run underneath the rail.
+ // Hugs the scroll container's top-right corner (clear of the scrollbar). It floats over the
+ // column rather than displacing it: translucent and blurred, and pointer-transparent except on
+ // the trigger itself. Rows only pass underneath once the thread is too narrow for the column's
+ // own slack to clear the rail's 44px.
<div className="pointer-events-none absolute top-2 right-3 z-10">
<DropdownMenu open={open} onOpenChange={handleOpenChange}>
<DropdownMenuTrigger
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx
index 4902e357b91c..c1e77a5f383f 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx
@@ -15,8 +15,8 @@ import {
type ThreadScrollResume,
} from "@posthog/ui/features/sessions/components/chat-thread/threadVirtualization";
import {
- CHAT_CONTENT_GUTTER,
CHAT_CONTENT_MAX_WIDTH,
+ CHAT_CONTENT_PADDING_INLINE,
} from "@posthog/ui/features/sessions/constants";
import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";
import {
@@ -416,7 +416,7 @@ export function VirtualThreadScrollBody({
return (
<>
<ChatMessageScroller
- className="group/thread"
+ className="@container/thread group/thread"
onPointerDownCapture={onUserInteract}
>
<MessageMinimap
@@ -430,7 +430,7 @@ export function VirtualThreadScrollBody({
<ChatMessageScrollerContent
className="block"
density="default"
- style={{ paddingInline: CHAT_CONTENT_GUTTER }}
+ style={{ paddingInline: CHAT_CONTENT_PADDING_INLINE }}
>
<div className="relative w-full" style={{ height: totalSize }}>
{virtualItems.map((virtualItem) => {
diff --git a/products/desktop/packages/ui/src/features/sessions/constants.ts b/products/desktop/packages/ui/src/features/sessions/constants.ts
index fae447a584cb..9918a571c71f 100644
--- a/products/desktop/packages/ui/src/features/sessions/constants.ts
+++ b/products/desktop/packages/ui/src/features/sessions/constants.ts
@@ -1,9 +1,26 @@
export const CHAT_CONTENT_MAX_WIDTH = 750;
/**
- * Horizontal room reserved on both sides of the thread's scroll content. The minimap rail hugs the
- * scroll container rather than the column, so this keeps rows off it once the panel is too narrow
- * for the column's own slack; the left side mirrors it to keep the column centred.
+ * Horizontal room reserved on both sides of the thread's scroll content, and by the composer, so
+ * the two columns narrow in step instead of one running wider than the other (and into the panel
+ * edges). Wide enough to clear the minimap rail (44px from the right edge) while the pane can
+ * afford it; once the gutter collapses toward the floor below, rows do pass under the rail.
*/
-export const CHAT_CONTENT_GUTTER = 32;
-export const CHAT_CONTENT_PADDING = 8;
-export const MIN_CHAT_WIDTH = CHAT_CONTENT_MAX_WIDTH + CHAT_CONTENT_PADDING * 2;
+export const CHAT_CONTENT_GUTTER = 48;
+/**
+ * Floor the gutter collapses to once the pane is too narrow to hold the full one. Below this the
+ * column would spend more of a cramped pane on empty margin than on the messages.
+ */
+export const CHAT_CONTENT_GUTTER_MIN = 24;
+/**
+ * `paddingInline` for anything that shares the chat column — thread rows, composer. Percentages
+ * resolve against the pane, so the gutter tracks the pane's own width rather than the viewport's:
+ * full while the pane can hold the column plus both gutters, sliding down to the floor as it
+ * narrows.
+ */
+export const CHAT_CONTENT_PADDING_INLINE = `clamp(${CHAT_CONTENT_GUTTER_MIN}px, calc((100% - ${CHAT_CONTENT_MAX_WIDTH}px) / 2), ${CHAT_CONTENT_GUTTER}px)`;
+/**
+ * Narrowest the review-pane splitter may squeeze the chat pane to. Deliberately short of
+ * CHAT_CONTENT_MAX_WIDTH + the gutters: the column shrinks gracefully below that, and holding the
+ * full gutter here would cost the review pane room for no benefit.
+ */
+export const MIN_CHAT_WIDTH = CHAT_CONTENT_MAX_WIDTH + 16;
diff --git a/products/desktop/packages/ui/src/features/sessions/contextColors.ts b/products/desktop/packages/ui/src/features/sessions/contextColors.ts
index a3e5896cfd3a..0de5a6bf7c17 100644
--- a/products/desktop/packages/ui/src/features/sessions/contextColors.ts
+++ b/products/desktop/packages/ui/src/features/sessions/contextColors.ts
@@ -6,21 +6,28 @@ export interface CategoryStyle {
color: string;
}
+// Quill tokens, not Radix scale vars: the breakdown renders inside a quill
+// popover portal, which sits outside the Radix Themes scope those vars are
+// declared on and would draw the swatches as transparent.
export const CONTEXT_CATEGORIES: readonly CategoryStyle[] = [
- { key: "systemPrompt", label: "System prompt", color: "var(--gray-9)" },
- { key: "tools", label: "Tools", color: "var(--violet-9)" },
- { key: "rules", label: "Rules", color: "var(--green-9)" },
- { key: "skills", label: "Skills", color: "var(--amber-9)" },
- { key: "mcp", label: "MCP", color: "var(--pink-9)" },
- { key: "subagents", label: "Subagents", color: "var(--blue-9)" },
- { key: "conversation", label: "Conversation", color: "var(--orange-9)" },
+ {
+ key: "systemPrompt",
+ label: "System prompt",
+ color: "var(--muted-foreground)",
+ },
+ { key: "tools", label: "Tools", color: "var(--data-color-14)" },
+ { key: "rules", label: "Rules", color: "var(--data-color-7)" },
+ { key: "skills", label: "Skills", color: "var(--data-color-13)" },
+ { key: "mcp", label: "MCP", color: "var(--data-color-9)" },
+ { key: "subagents", label: "Subagents", color: "var(--data-color-8)" },
+ { key: "conversation", label: "Conversation", color: "var(--primary)" },
] as const;
export function getOverallUsageColor(percentage: number): string {
- if (percentage >= 90) return "var(--red-9)";
- if (percentage >= 75) return "var(--orange-9)";
- if (percentage >= 50) return "var(--amber-9)";
- return "var(--green-9)";
+ if (percentage >= 90) return "var(--destructive-foreground)";
+ if (percentage >= 75) return "var(--data-color-12)";
+ if (percentage >= 50) return "var(--warning-foreground)";
+ return "var(--success-foreground)";
}
export function formatTokensCompact(tokens: number): string {
diff --git a/products/desktop/packages/ui/src/features/sessions/modeStyles.ts b/products/desktop/packages/ui/src/features/sessions/modeStyles.ts
new file mode 100644
index 000000000000..3285c5cef01f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/modeStyles.ts
@@ -0,0 +1,13 @@
+// Short, human labels keyed by mode id. The raw permission-option names are long
+// "Yes, and ..." strings; these read cleanly on the Approve button and in the
+// "Approve and…" dropdown. Callers fall back to the raw option name when a mode
+// isn't listed here.
+export const MODE_LABELS: Record<string, string> = {
+ plan: "Plan",
+ default: "Manually approve edits",
+ acceptEdits: "Accept edits",
+ auto: "Auto",
+ bypassPermissions: "Bypass permissions",
+ "read-only": "Read-only",
+ "full-access": "Full access",
+};
diff --git a/products/desktop/packages/ui/src/features/sessions/modeStyles.tsx b/products/desktop/packages/ui/src/features/sessions/modeStyles.tsx
deleted file mode 100644
index 065fd2da45d8..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/modeStyles.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import {
- Circle,
- Eye,
- LockOpen,
- Pause,
- Pencil,
- Robot,
- ShieldCheck,
-} from "@phosphor-icons/react";
-
-export interface ModeStyle {
- icon: React.ReactNode;
- className: string;
-}
-
-export const MODE_STYLES: Record<string, ModeStyle> = {
- plan: {
- icon: <Pause size={12} weight="bold" />,
- className: "text-amber-11",
- },
- default: {
- icon: <Pencil size={12} />,
- className: "text-gray-11",
- },
- acceptEdits: {
- icon: <ShieldCheck size={12} weight="fill" />,
- className: "text-green-11",
- },
- bypassPermissions: {
- icon: <LockOpen size={12} weight="bold" />,
- className: "text-red-11",
- },
- auto: {
- icon: <Robot size={12} weight="fill" />,
- className: "text-blue-11",
- },
- "read-only": {
- icon: <Eye size={12} />,
- className: "text-amber-11",
- },
- "full-access": {
- icon: <LockOpen size={12} weight="bold" />,
- className: "text-red-11",
- },
-};
-
-export const DEFAULT_MODE_STYLE: ModeStyle = {
- icon: <Circle size={12} />,
- className: "text-gray-11",
-};
-
-export function getModeStyle(value: string): ModeStyle {
- return MODE_STYLES[value] ?? DEFAULT_MODE_STYLE;
-}
-
-// Short, human labels keyed by mode id. The raw permission-option names are long
-// "Yes, and ..." strings; these read cleanly on the Approve button and in the
-// "Approve and…" dropdown. Callers fall back to the raw option name when a mode
-// isn't listed here.
-export const MODE_LABELS: Record<string, string> = {
- plan: "Plan",
- default: "Manually approve edits",
- acceptEdits: "Accept edits",
- auto: "Auto",
- bypassPermissions: "Bypass permissions",
- "read-only": "Read-only",
- "full-access": "Full access",
-};
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/ChannelContextChip.tsx b/products/desktop/packages/ui/src/features/task-detail/components/ChannelContextChip.tsx
new file mode 100644
index 000000000000..3c37b3ae2e0c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/components/ChannelContextChip.tsx
@@ -0,0 +1,26 @@
+import { Attachment } from "@posthog/ui/features/message-editor/components/Attachment";
+
+/**
+ * The channel CONTEXT.md riding along with the prompt, shown in the composer's
+ * attachments row. Deliberately the same component the user's own attachments
+ * use, because that is what it is from the writer's point of view: something
+ * extra travelling with the message, which they can inspect or drop.
+ */
+export function ChannelContextChip({
+ channelName,
+ onView,
+ onRemove,
+}: {
+ channelName?: string;
+ onView?: () => void;
+ onRemove: () => void;
+}) {
+ return (
+ <Attachment
+ label={`${channelName ? `#${channelName} ` : ""}CONTEXT.md`}
+ hint={onView ? "Click to view" : undefined}
+ onOpen={onView}
+ onRemove={onRemove}
+ />
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index 2c0a9a8dc8c1..9a18a8cdb59d 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -1,4 +1,4 @@
-import { FileText, X } from "@phosphor-icons/react";
+import { X } from "@phosphor-icons/react";
import type { AutoresearchService } from "@posthog/core/autoresearch/autoresearch";
import { AUTORESEARCH_SERVICE } from "@posthog/core/autoresearch/identifiers";
import { buildKickoffPreamble } from "@posthog/core/autoresearch/prompts";
@@ -97,6 +97,7 @@ import { useTaskCreation } from "../hooks/useTaskCreation";
import { useWarmTask } from "../hooks/useWarmTask";
import { resolveWorkspaceModePreference } from "../hooks/workspaceModePreference";
import { AgentRuntimeSelect } from "./AgentRuntimeSelect";
+import { ChannelContextChip } from "./ChannelContextChip";
import { CloudGithubMissingNotice } from "./CloudGithubMissingNotice";
import { NewTaskSuggestions } from "./ContinueCliSessions";
import {
@@ -1385,6 +1386,15 @@ export function TaskInput({
(runtime === "pi" && !currentPiModel)
}
tourTarget="task-input"
+ attachmentsPrefix={
+ includeChannelContext ? (
+ <ChannelContextChip
+ channelName={channelName}
+ onView={onContextChipClick}
+ onRemove={() => setChannelContextDismissed(true)}
+ />
+ ) : undefined
+ }
repoPath={selectedDirectory}
modeOption={runtime === "pi" ? undefined : modeOption}
onModeChange={runtime === "pi" ? undefined : handleModeChange}
@@ -1477,44 +1487,6 @@ export function TaskInput({
</Tooltip>
</div>
)}
- {includeChannelContext && (
- <div className="-mt-px mx-2 flex select-none flex-wrap items-center gap-1.5 rounded-b-md border border-gray-6 border-t-0 bg-gray-2 px-2 py-1 text-[12px] text-gray-11">
- <span className="shrink-0 text-gray-10">Using:</span>
- <span className="inline-flex items-center gap-1 rounded-[var(--radius-1)] bg-[var(--gray-a3)] px-1.5 py-px font-medium text-[var(--gray-11)]">
- {onContextChipClick ? (
- <Tooltip content="View this CONTEXT.md">
- <button
- type="button"
- onClick={onContextChipClick}
- className="inline-flex min-w-0 items-center gap-1 rounded text-[var(--gray-11)] hover:text-gray-12"
- >
- <FileText size={12} />
- <span className="truncate">
- {channelName ? `#${channelName} ` : ""}CONTEXT.md
- </span>
- </button>
- </Tooltip>
- ) : (
- <>
- <FileText size={12} />
- <span className="truncate">
- {channelName ? `#${channelName} ` : ""}CONTEXT.md
- </span>
- </>
- )}
- <Tooltip content="Don't include this CONTEXT.md">
- <button
- type="button"
- onClick={() => setChannelContextDismissed(true)}
- aria-label="Remove CONTEXT.md from prompt"
- className="ml-0.5 inline-flex size-3.5 items-center justify-center rounded text-gray-10 hover:bg-gray-5 hover:text-gray-12"
- >
- <X size={12} />
- </button>
- </Tooltip>
- </span>
- </div>
- )}
{effectiveWorkspaceMode === "cloud" &&
!isLoadingRepos &&
!hasGithubIntegration && (