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(posthog-ai): render the chat thread in quill behind phai-quill (#109084)

Adam Leith06966fa4ee68
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 06fed3b38b92..61a5fa654f05 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7010,6 +7010,18 @@ snapshots:
hash: v1.k794b7964.ff266ce4b007479bd8156db3c4b65a91a8b987d226bfd7622b20085df50d5d1c.2IsZbL1hVZEqsqWd22bNC0XJvJSqSlXHKCc0LGtJzJc
products-posthog-ai-threadview--saved-insight-query--light:
hash: v1.k794b7964.405cb15303a44d4f837d5569ab4110e07b62ffa71fc418e0aaeb29ddafe8cf8e.mnRWTc0Tao1ttGBbi8vm9n77TQn-RXrRtmeeaDk-yM8
+ products-posthog-ai-threadview-quill--compared-with-lemon--dark:
+ hash: v1.k794b7964.0eef4b8bb8e847af86a96de1b100ccef151cc567197bee0200ca75a0e715c286.a5rC4BaHZaP6PhJ0-i0xMfj1DhJiQLcQtM_xXJkvMj4
+ products-posthog-ai-threadview-quill--compared-with-lemon--light:
+ hash: v1.k794b7964.c7a5ffd2925080a181b740d34b2c27b38ad09f50892b11d14ceceba7e336a968.6xFkSM46Y-L3sx2EzN4vegRwjUqUwaxMc4usQN_1Bcw
+ products-posthog-ai-threadview-quill--completed-turn--dark:
+ hash: v1.k794b7964.bd9bb2903f370c2f1030c1b31e69f004007f3aeb9c1be958381f91ecfc1aeca0.RxgqjdEnZ5RANGV5fD3rSvbYHYRo-6M7N2L-KS4oGNk
+ products-posthog-ai-threadview-quill--completed-turn--light:
+ hash: v1.k794b7964.7814b44a7cdb67fe04b11c0b67cd29da9df560fdd443a6a049127785b87eaddb.Ms_Zza_5d6X6oEsJVYbLuYXaZDqrN80vHn7E9nSP_bw
+ products-posthog-ai-threadview-quill--streaming-turn--dark:
+ hash: v1.k794b7964.dc0c5375f7622aa8755a424c981f16489ca45e0b178a147a1ef45f1bf85d4c4a.PmyP1cKLntqhPrftuHkvd3HvPYcS7iE9spSH9NXVbho
+ products-posthog-ai-threadview-quill--streaming-turn--light:
+ hash: v1.k794b7964.ab821f2b11da4c0a45f57411e64e6a420e09d024c3580da2b24f465810606212.-muSpXCIxCIulLSskbyWyNXWTqn16CR6ZXl03tuiwLo
products-posthog-ai-virtualizedthread--anchored-open--dark:
hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OE
products-posthog-ai-virtualizedthread--anchored-open--light:
@@ -7047,9 +7059,9 @@ snapshots:
products-posthog-ai-virtualizedthread--remembered-position--light:
hash: v1.k794b7964.fcd3d3ae2a58e891ec3fb4b224d8674f1591e349a990e0211aee29c9bf6f8d01.ThH9PVDZc4Ziy5_MNxrvijx6pRk5muGoa3ul6PgEEZw
products-posthog-ai-virtualizedthread--streaming--dark:
- hash: v1.k794b7964.c4ebc83f695831769cc95475925e983a71d5909636818ff2153e2dc7df5450a1.9VcSQPoSe9fMttmpga5INPhkJySlhF35v8dHEs52L90
+ hash: v1.k794b7964.b82eb1f4dc8701cf771e98d9214e6b72878727e5f68feac99a7a2a97d120c8a7.yrNrQvDVMHhEcXBq_FC0zykgDZ33RIRP6hHC95RFdEc
products-posthog-ai-virtualizedthread--streaming--light:
- hash: v1.k794b7964.e731151aea72bc9d5f4248dd2548e03fe07336fb29b2110d1e348020985ef9d1.NMSw9HS1VJuLZsmgp29MVPo708vTot8RLCqFv8IC7RQ
+ hash: v1.k794b7964.abd616bcda408ecf3fd0dfcaa1595491e88913000ad61893414d3536612ee3b5.94VJLVoiR9MVKJHF7FbnLu64DXBRbUpQLLoXu1Z74As
products-signals-self-driving-intro-modal--default--dark:
hash: v1.k794b7964.e72031a3a874ed6a1825089edff6147a3ea0d74c20c74951f8b5d38d92f54464.WQmsYZby7Raw1OaQn_oKtu1eASs_te6AgRALWXM6xLE
products-signals-self-driving-intro-modal--default--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 82871ee9dfa7..4ebf45c6a141 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -444,6 +444,7 @@ export const FEATURE_FLAGS = {
PAGE_REPORTS_RANKED_URL_SEARCH: 'page-reports-ranked-url-search', // owner: @jordanm-posthog #team-web-analytics
PASSWORD_PROTECTED_SHARES: 'password-protected-shares', // owner: @aspicer
PHAI_PLAN_MODE: 'phai-plan-mode', // owner: #team-posthog-ai
+ PHAI_QUILL: 'phai-quill', // owner: #team-posthog-ai, renders the PostHog AI chat thread in quill like PostHog Desktop; on with today-rail-nav too
PHAI_SANDBOX_MODE: 'phai-sandbox-mode', // owner: #team-posthog-ai
PHAI_SCENE_AUTO_OPEN: 'phai-scene-auto-open', // owner: #team-posthog-ai
PHAI_TASKS: 'phai-tasks', // owner: #team-array
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 501087bb5826..888eaa34bf2f 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -83,6 +83,7 @@ import {
ThreadView,
TurnFeedbackActions,
type TurnTrailer,
+ useThreadSkin,
} from 'products/posthog_ai/frontend/api/primitives'
import { LogEntry } from 'products/posthog_ai/frontend/lib/parse-logs'
import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'
@@ -129,6 +130,7 @@ function isErrorMessage(message: ThreadMessage): boolean {
export function Thread({ className }: { className?: string }): JSX.Element | null {
const { conversation, sandboxConversationKey, isConvertedConversation } = useValues(maxThreadLogic)
const { panelId } = useValues(maxLogic)
+ const threadSkin = useThreadSkin()
const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'
const isPiTask = isPiTaskRuntime(conversation?.task?.runtime)
@@ -184,7 +186,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
{/* The live Max column owns scroll via ThreadAutoScroller — render rows in flow, not virtualized. */}
- <ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} />
+ <ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} skin={threadSkin} />
</BindLogic>
</div>
)
@@ -204,7 +206,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
logic={runStreamLogic}
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
- <ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} />
+ <ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} skin={threadSkin} />
</BindLogic>
</div>
)
diff --git a/packages/quill/packages/primitives/AGENTS.md b/packages/quill/packages/primitives/AGENTS.md
index b2d1e075f918..efdc51357faa 100644
--- a/packages/quill/packages/primitives/AGENTS.md
+++ b/packages/quill/packages/primitives/AGENTS.md
@@ -942,6 +942,7 @@ Skipped items don't appear at all.
- **`QuestionnaireChoice` assembles its own row** — the overlaid native radio/checkbox, the indicator, the label, and the shortcut key. Write only the answer's text; add `QuestionnaireChoiceDescription` for a muted second line. `multiple` on the item swaps radios for checkboxes and the indicator's dot for a check.
- **`QuestionnaireInput` always needs an accessible name.** A placeholder is not a label — pass `aria-label` or point `aria-labelledby` at a visible one. It shares the item's `name`, so typing in it replaces whatever choice was picked. It renders as an `InputGroup` wearing a choice's indicator, filled once there's text and tinted like a picked row — the indicator takes its shape from the choices beside it, round for radios and square for checkboxes. Pass `render` to replace the whole row.
+- **Next and Submit stay disabled until the active question has an answer.** The engine refuses an unanswered question on submit, optional ones included, so the buttons match it; Skip is the way past an optional one. A keyboard submit still runs validation and shows `QuestionnaireError`.
- **`QuestionnaireActions` is layout only** — a three-column row that pins Previous to the start and hugs Skip and Next/Submit to the end, so buttons don't move as they appear and disappear. It holds no state.
- **Branching is the app's.** A question that no longer applies gets `disabled`, which drops it out of the order, the progress count, and the validation pass. Same for controlled navigation: pass `item`/`onItemChange` to send the user back to a question that failed the app's own checks, and `invalid` plus `QuestionnaireError` children to say why.
- Only the active item is visible — the engine hides and inerts the rest, so every question stays mounted and keeps its answer. Don't unmount them yourself.
@@ -1166,7 +1167,8 @@ Quill spacing uses a 4px base (`gap-1` = 4px, `gap-2` = 8px, `gap-4` = 16px). Th
### Text sizes
-- `--text-ui` (13px) is the primary UI text: controls, list rows, chat, and the body text of cards, dialogs, drawers, popovers and tooltips.
+- `--text-ui` (13px) is the primary UI text: controls, list rows, chat rows, and the body text of cards, dialogs, drawers, popovers and tooltips.
+- `--text-sm` (14px) is chat message text: `ChatMessage` and `ChatBubble` content, so a conversation reads at body size beside its 13px rows.
- `--text-xs` (12px) is secondary text: descriptions, labels, field errors, tables, and `sm` controls. Chat is the exception, and uses `--text-ui` for its help, error and meta text too.
- In component CSS, write `var(--text-ui, 0.8125rem)`. Set `--text-ui` on an ancestor to rescale the primary text together.
diff --git a/packages/quill/packages/primitives/src/chat/chat-bubble.css b/packages/quill/packages/primitives/src/chat/chat-bubble.css
index 73c2368ee79e..a25508819bfb 100644
--- a/packages/quill/packages/primitives/src/chat/chat-bubble.css
+++ b/packages/quill/packages/primitives/src/chat/chat-bubble.css
@@ -39,7 +39,7 @@
padding-block: 0.375rem;
padding-inline: 0.625rem;
overflow: hidden;
- font-size: var(--text-ui, 0.8125rem);
+ font-size: var(--text-sm, 0.875rem);
line-height: 1.625;
overflow-wrap: break-word;
border: 1px solid transparent;
diff --git a/packages/quill/packages/primitives/src/chat/chat-message.css b/packages/quill/packages/primitives/src/chat/chat-message.css
index 4d52e9cb35e1..01c2781b7f0d 100644
--- a/packages/quill/packages/primitives/src/chat/chat-message.css
+++ b/packages/quill/packages/primitives/src/chat/chat-message.css
@@ -13,7 +13,7 @@
gap: 0.375rem;
width: 100%;
min-width: 0;
- font-size: var(--text-ui, 0.8125rem);
+ font-size: var(--text-sm, 0.875rem);
line-height: 1.625;
}
diff --git a/packages/quill/packages/primitives/src/chat/questionnaire.css b/packages/quill/packages/primitives/src/chat/questionnaire.css
index 7c36b5064c42..d15c5df6f517 100644
--- a/packages/quill/packages/primitives/src/chat/questionnaire.css
+++ b/packages/quill/packages/primitives/src/chat/questionnaire.css
@@ -149,6 +149,9 @@
justify-content: center;
width: 0.875rem;
height: 0.875rem;
+
+ /* Centers the box on the label's first line, whose height is the row's 1.375 line height. */
+ margin-block-start: calc((1.375em - 0.875rem) / 2);
pointer-events: none;
border: 1px solid var(--input);
border-radius: 3px;
diff --git a/packages/quill/packages/primitives/src/chat/questionnaire.tsx b/packages/quill/packages/primitives/src/chat/questionnaire.tsx
index 5daa0244ee78..e8c8221d7bc2 100644
--- a/packages/quill/packages/primitives/src/chat/questionnaire.tsx
+++ b/packages/quill/packages/primitives/src/chat/questionnaire.tsx
@@ -8,6 +8,7 @@ import {
type QuestionnaireItemStatus,
type QuestionnaireShortcutMode,
} from '@shadcn/react/questionnaire'
+import { mergeProps } from '@base-ui/react/merge-props'
import { CheckIcon } from 'lucide-react'
import * as React from 'react'
@@ -287,6 +288,24 @@ function QuestionnaireSkip({
)
}
+type AdvanceRender = React.ComponentProps<typeof QuestionnairePrimitive.Submit>['render']
+
+/**
+ * Next and Submit stay disabled while the active question is unanswered. The engine refuses an unanswered
+ * question on submit anyway, optional ones included (Skip is their way past), so a live button there only
+ * invites a click that fails. A keyboard submit still runs the engine's validation and shows the error.
+ */
+function disabledUntilAnswered(render: AdvanceRender): NonNullable<AdvanceRender> {
+ return (props, state) => {
+ const gated = { ...props, disabled: props.disabled || state.status === 'unanswered' }
+ if (typeof render === 'function') {
+ return render(gated, state)
+ }
+ const element = render ?? <Button variant="primary" />
+ return React.cloneElement(element, mergeProps(element.props as React.ComponentProps<'button'>, gated))
+ }
+}
+
function QuestionnaireNext({
children,
className,
@@ -297,7 +316,7 @@ function QuestionnaireNext({
<QuestionnairePrimitive.Next
data-slot="questionnaire-next"
className={cn('quill-questionnaire__next', className)}
- render={render ?? <Button variant="primary" />}
+ render={disabledUntilAnswered(render)}
{...props}
>
{children ?? 'Next'}
@@ -315,7 +334,7 @@ function QuestionnaireSubmit({
<QuestionnairePrimitive.Submit
data-slot="questionnaire-submit"
className={cn('quill-questionnaire__submit', className)}
- render={render ?? <Button variant="primary" />}
+ render={disabledUntilAnswered(render)}
{...props}
>
{children ?? 'Submit'}
diff --git a/packages/quill/packages/primitives/src/styles/layers.css b/packages/quill/packages/primitives/src/styles/layers.css
index f0a7371fa739..10bed23b4dc5 100644
--- a/packages/quill/packages/primitives/src/styles/layers.css
+++ b/packages/quill/packages/primitives/src/styles/layers.css
@@ -23,7 +23,7 @@
--text-xxs: 0.625rem;
--text-xxs--line-height: 0.75rem;
- /* Primary UI text: controls, list rows, chat, and container body text. Secondary text stays at --text-xs.
+ /* Primary UI text: controls, list rows, chat rows, and container body text. Secondary text stays at --text-xs.
Set it on an ancestor to rescale the primary text together. */
--text-ui: 0.8125rem;
--text-ui--line-height: 1.25rem;
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 222987af7a00..65580465f907 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -213,6 +213,12 @@ ingestion).
`useMemo`, wrap child callbacks in `useCallback`, and subscribe narrowly (select only what you render).
- **Keep the projection pure.** `foldLogToThread` is pure and deterministic; item ids stay stable across
re-folds. Listeners fire only side effects, each with a fire-once guard, suppressed on `source: 'replay'`.
+- **A shared presenter renders in both thread skins.** `ThreadView`'s `skin` prop (`'lemon' | 'quill'`) sets
+ `ThreadSkinContext`; `quill` is the PostHog Desktop chat layout, on behind the `phai-quill` flag (and `today-rail-nav`).
+ `Activity`, `ThreadRow` message rows, `ThreadActivityGroup`, `RunAlertActivity`, `PullRequestCard` and
+ `TurnFeedbackActions` read `useQuillThread()` and dispatch to their `components/quill/` skin at the top of the
+ component. Behavior both skins need (open state, group windowing, ratings) lives in a shared hook
+ (`useActivityDisclosure`, `useActivityGroup`, `useTurnRating`), never in one skin. Tool renderers never branch on skin.
- **A tool card is two header lines plus an accordion — overflow goes in the accordion.** Every tool
renderer wraps its content in `ToolActivity`, which exposes exactly two always-visible header lines:
the `title` and the `subtitle` (the one salient input — a command, path, repo, branch). **Any other
@@ -241,6 +247,7 @@ components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); Rea
# RunLogSkeleton (shared loader), Thread, Composer, perm/question surfaces, activity, tool/;
# AttachedContextProvider (render-null context injection wrapper)
composer/ # the Composer compound; AttachedContextBar (@-picker + context chips)
+ quill/ # the quill thread skin (ThreadSkinContext, ThreadMarker, message/group/alert/feedback skins)
tool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)
widgets/ # PostHog product data-tool widgets (insight/dashboard/recordings/notebook/query)
hooks/ # useAttachedContext, useToolStream — mount-scoped registration wrappers over the logics
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index fb7641e3a62d..fb15d2033356 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -51,6 +51,8 @@ export { DEFAULT_SUGGESTIONS_DATA } from '../components/suggestions/suggestionsD
// atoms); `ThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).
export { Thread } from '../components/Thread'
export { ThreadView } from '../components/ThreadView'
+export type { ThreadSkin } from '../components/quill/quillThreadContext'
+export { useThreadSkin } from '../hooks/useThreadSkin'
export type { TurnTrailer } from '../utils/turnTrailers'
export { TurnFeedbackActions } from '../components/TurnFeedbackActions'
export { MessageTemplate } from '../messages/MessageTemplate'
@@ -67,11 +69,11 @@ export {
ActivityDetails,
ActivityHeader,
ActivityStatusIcon,
- ActivitySubsteps,
ActivityToggleSection,
ShimmeringContent,
} from '../components/ActivityPrimitives'
-export type { ActivityStatus } from '../components/ActivityPrimitives'
+export { ActivitySubsteps } from '../components/ActivitySubsteps'
+export type { ActivityStatus } from '../components/activityTypes'
export { RunActivity } from '../components/RunActivity'
export { RunAlertActivity } from '../components/RunAlertActivity'
diff --git a/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx b/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx
index 051347b65e4d..955b28658a2e 100644
--- a/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx
+++ b/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
+import { useQuillThread } from './quill/quillThreadContext'
+
export function ActivityElapsedTime({
startedAt,
endedAt,
@@ -11,6 +13,7 @@ export function ActivityElapsedTime({
endedAt?: number
active: boolean
}): JSX.Element | null {
+ const quill = useQuillThread()
const [now, setNow] = useState(Date.now)
const { isVisible } = usePageVisibility()
useEffect(() => {
@@ -28,7 +31,7 @@ export function ActivityElapsedTime({
const seconds = Math.floor((end - startedAt) / 1000)
return (
<span
- className="tabular-nums text-muted"
+ className={quill ? 'tabular-nums' : 'tabular-nums text-muted'}
title="Elapsed time for this activity group, including tools and waiting, not the whole response."
>
· {seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`}
diff --git a/products/posthog_ai/frontend/components/ActivityGroupRows.tsx b/products/posthog_ai/frontend/components/ActivityGroupRows.tsx
new file mode 100644
index 000000000000..bfc0ffb94553
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ActivityGroupRows.tsx
@@ -0,0 +1,76 @@
+import { Fragment, type ReactNode } from 'react'
+
+import { MarkdownMessage } from '../messages/MarkdownMessage'
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+import { ACTIVITY_CHAIN_MIN, groupConsecutiveTools } from '../utils/groupThreadActivity'
+import { resolveToolCall } from '../utils/toolResolver'
+import { Activity } from './ActivityPrimitives'
+import { lookupToolRenderer } from './tool/toolRegistry'
+
+/**
+ * The rows an open activity group lists. With `fold`, a run of identical consecutive calls collapses into
+ * one row; the first and last rows of a group never fold, so a reader never opens two accordions to reach
+ * one call. Flat rows keep their own item keys, so a row's expanded state survives when the window shifts.
+ */
+export function ActivityGroupRows({
+ items,
+ fold,
+ thoughtsOnly,
+ toolInvocations,
+ active,
+ renderItem,
+}: {
+ items: ThreadItem[]
+ fold: boolean
+ thoughtsOnly: boolean
+ toolInvocations: Map<string, ToolInvocation>
+ active: boolean
+ renderItem: (item: ThreadItem) => ReactNode
+}): JSX.Element {
+ const individualRows = (rows: ThreadItem[]): ReactNode[] =>
+ rows.map((item) => (
+ <Fragment key={item.id}>
+ {thoughtsOnly ? (
+ <div className="text-muted">
+ <MarkdownMessage id={item.id} content={item.text ?? ''} />
+ </div>
+ ) : (
+ renderItem(item)
+ )}
+ </Fragment>
+ ))
+ return (
+ <>
+ {groupConsecutiveTools(items, toolInvocations).flatMap((chain) => {
+ if (!fold || chain.length < ACTIVITY_CHAIN_MIN) {
+ return individualRows(chain)
+ }
+ const chainCalls = chain.map((item) => toolInvocations.get(item.toolCallId!)!)
+ const resolved = resolveToolCall(chainCalls[0])
+ const entry = lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName)
+ const failed = chainCalls.filter((call) => call.status === 'failed').length
+ const running =
+ active && chainCalls.some((call) => call.status === 'pending' || call.status === 'in_progress')
+ return (
+ <div key={chain[0].id} data-attr="thread-tool-chain">
+ <Activity
+ id={`chain-${chain[0].id}`}
+ title={
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="truncate">{entry.displayName}</span>
+ <span className="text-muted shrink-0">· {chain.length} calls</span>
+ {failed > 0 && <span className="text-danger shrink-0">· {failed} failed</span>}
+ </span>
+ }
+ icon={entry.icon}
+ status={running ? 'in_progress' : 'completed'}
+ animate={false}
+ autoExpand={false}
+ details={<div className="flex flex-col gap-1 min-w-0">{individualRows(chain)}</div>}
+ />
+ </div>
+ )
+ })}
+ </>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
index ddce921e2e35..8fff8ae975f5 100644
--- a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
@@ -1,13 +1,15 @@
import clsx from 'clsx'
-import React, { useLayoutEffect, useState } from 'react'
+import React, { useState } from 'react'
import { IconChevronDown, IconChevronRight } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { MarkdownMessage } from '../messages/MarkdownMessage'
import { ActivityDisclosure } from './ActivityDisclosure'
-
-export type ActivityStatus = 'pending' | 'in_progress' | 'completed' | 'failed'
+import { ActivitySubsteps } from './ActivitySubsteps'
+import type { ActivityProps, ActivityStatus } from './activityTypes'
+import { QuillActivity } from './quill/QuillActivity'
+import { useQuillThread } from './quill/quillThreadContext'
+import { useActivityDisclosure } from './useActivityDisclosure'
export function ShimmeringContent({ children }: { children: React.ReactNode }): JSX.Element {
const isTextContent = typeof children === 'string'
@@ -40,19 +42,6 @@ export function ShimmeringContent({ children }: { children: React.ReactNode }):
)
}
-function activitySubstepText(content: string, isInProgress: boolean): string {
- if (content.at(0) === '[' && content.at(-1) === ')') {
- // Skip ... for web search `updates`, where each is a Markdown-formatted link to a search result.
- return content
- }
- if (!content.endsWith('...') && !content.endsWith('\u2026') && !content.endsWith('.') && isInProgress) {
- return content + '...'
- } else if ((content.endsWith('...') || content.endsWith('\u2026')) && !isInProgress) {
- return content.replace(/\u2026/g, '').replace(/[.]/g, '')
- }
- return content
-}
-
export function ActivityStatusIcon(_props: {
status: ActivityStatus
showCompletionIcon?: boolean
@@ -184,43 +173,6 @@ export function ActivityHeader({
)
}
-export function ActivitySubsteps({
- id,
- substeps,
- status,
-}: {
- id: string
- substeps: string[]
- status: ActivityStatus
-}): JSX.Element {
- const isCompleted = status === 'completed'
- const isFailed = status === 'failed'
-
- return (
- <>
- {substeps.map((substep, substepIndex) => {
- const isCurrentSubstep = substepIndex === substeps.length - 1
- const isCompletedSubstep = substepIndex < substeps.length - 1 || isCompleted
-
- return (
- <div key={substepIndex} className="animate-fade-in">
- <MarkdownMessage
- id={id}
- className={clsx(
- 'leading-relaxed',
- isFailed && 'text-danger',
- !isFailed && isCompletedSubstep && 'text-muted',
- !isFailed && isCurrentSubstep && !isCompleted && 'text-secondary'
- )}
- content={activitySubstepText(substep ?? '', status === 'in_progress')}
- />
- </div>
- )
- })}
- </>
- )
-}
-
export function ActivityDetails({ children, hasIcon }: { children: React.ReactNode; hasIcon: boolean }): JSX.Element {
return (
<div className={clsx('space-y-1 border-l-2 border-border-secondary', hasIcon && 'pl-3.5 ml-[calc(0.775rem)]')}>
@@ -268,7 +220,11 @@ export function ActivityToggleSection({
)
}
-export function Activity({
+export function Activity(props: ActivityProps): JSX.Element {
+ return useQuillThread() ? <QuillActivity {...props} /> : <LemonActivity {...props} />
+}
+
+function LemonActivity({
id,
title,
subtitle,
@@ -283,29 +239,14 @@ export function Activity({
children = null,
autoExpand = true,
onToggleDetails,
-}: {
- id: string
- title: React.ReactNode
- subtitle?: React.ReactNode
- status: ActivityStatus
- icon?: React.ReactNode
- animate?: boolean
- showCompletionIcon?: boolean
- showProgressIcon?: boolean
- failedIcon?: React.ReactNode
- substeps?: string[]
- details?: React.ReactNode
- children?: React.ReactNode
- autoExpand?: boolean
- onToggleDetails?: (expanded: boolean) => void
-}): JSX.Element {
+}: ActivityProps): JSX.Element {
const hasDetails = substeps.length > 0 || !!details
- const shouldExpandDetails = autoExpand && hasDetails && status !== 'completed' && status !== 'failed'
- const [isDetailsExpanded, setIsDetailsExpanded] = useState(shouldExpandDetails)
-
- useLayoutEffect(() => {
- setIsDetailsExpanded(shouldExpandDetails)
- }, [shouldExpandDetails])
+ const { open: isDetailsExpanded, setOpen: setIsDetailsExpanded } = useActivityDisclosure({
+ autoExpand,
+ hasDetails,
+ status,
+ onToggleDetails,
+ })
return (
<div className="flex flex-col rounded w-full min-w-0 text-[13px] leading-5 font-normal">
@@ -316,10 +257,7 @@ export function Activity({
animate={animate}
hasDetails={hasDetails}
isDetailsExpanded={isDetailsExpanded}
- onToggleDetails={() => {
- onToggleDetails?.(!isDetailsExpanded)
- setIsDetailsExpanded(!isDetailsExpanded)
- }}
+ onToggleDetails={() => setIsDetailsExpanded(!isDetailsExpanded)}
showCompletionIcon={showCompletionIcon}
showProgressIcon={showProgressIcon}
failedIcon={failedIcon}
diff --git a/products/posthog_ai/frontend/components/ActivitySubsteps.tsx b/products/posthog_ai/frontend/components/ActivitySubsteps.tsx
new file mode 100644
index 000000000000..374e2f56787c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ActivitySubsteps.tsx
@@ -0,0 +1,56 @@
+import clsx from 'clsx'
+
+import { MarkdownMessage } from '../messages/MarkdownMessage'
+import type { ActivityStatus } from './activityTypes'
+import { useQuillThread } from './quill/quillThreadContext'
+
+function activitySubstepText(content: string, isInProgress: boolean): string {
+ if (content.at(0) === '[' && content.at(-1) === ')') {
+ // Skip ... for web search `updates`, where each is a Markdown-formatted link to a search result.
+ return content
+ }
+ if (!content.endsWith('...') && !content.endsWith('\u2026') && !content.endsWith('.') && isInProgress) {
+ return content + '...'
+ } else if ((content.endsWith('...') || content.endsWith('\u2026')) && !isInProgress) {
+ return content.replace(/\u2026/g, '').replace(/[.]/g, '')
+ }
+ return content
+}
+
+export function ActivitySubsteps({
+ id,
+ substeps,
+ status,
+}: {
+ id: string
+ substeps: string[]
+ status: ActivityStatus
+}): JSX.Element {
+ const quill = useQuillThread()
+ const isCompleted = status === 'completed'
+ const isFailed = status === 'failed'
+
+ return (
+ <>
+ {substeps.map((substep, substepIndex) => {
+ const isCurrentSubstep = substepIndex === substeps.length - 1
+ const isCompletedSubstep = substepIndex < substeps.length - 1 || isCompleted
+
+ return (
+ <div key={substepIndex} className="animate-fade-in">
+ <MarkdownMessage
+ id={id}
+ className={clsx(
+ 'leading-relaxed',
+ isFailed && 'text-danger',
+ !quill && !isFailed && isCompletedSubstep && 'text-muted',
+ !quill && !isFailed && isCurrentSubstep && !isCompleted && 'text-secondary'
+ )}
+ content={activitySubstepText(substep ?? '', status === 'in_progress')}
+ />
+ </div>
+ )
+ })}
+ </>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsx
index c48a9f826648..0a2f96b6f85a 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx
@@ -8,13 +8,16 @@ import { PostHogErrorBoundary } from '@posthog/react'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { cn } from 'lib/utils/css-classes'
+import { useThreadSkin } from '../hooks/useThreadSkin'
import { runStreamLogic } from '../logics/runStreamLogic'
import { MarkdownMessage } from '../messages/MarkdownMessage'
import { getPermissionDisplay } from '../policy/permissionDisplayUtils'
+import { FEEDBACK_PLACEHOLDER, isFeedbackOption, optionRowLabel, optionSublabel } from '../policy/permissionOptionCopy'
import { isPlanPermissionRequest, mapPermissionOptions, type ApprovalCardOption } from '../policy/permissionUtils'
import type { PermissionRequestRecord } from '../types/streamTypes'
import { resolveToolCall } from '../utils/toolResolver'
import { isPlanApprovalModeOptionId, InlineEditableText, PlanApprovalSelector } from './PlanApprovalActions'
+import { QuillPermissionQuestionnaire } from './quill/QuillPermissionQuestionnaire'
import { DiffStats } from './tool/DiffStats'
import { FilePath } from './tool/FilePath'
import { LazyDiffEditor } from './tool/LazyDiffEditor'
@@ -30,8 +33,6 @@ interface PermissionInputProps {
/** Collapsed height of the payload preview, in lines — enough to scan, never enough to bury the choices. */
const PAYLOAD_COLLAPSED_LINES = 12
-const FEEDBACK_PLACEHOLDER = 'Tell the agent what to do differently'
-
interface PermissionEvidenceProps {
request: PermissionRequestRecord
/** Tool identity for the evidence header; omitted when the headline sentence already carries it. */
@@ -113,33 +114,6 @@ function PermissionEvidence({ request, label, payload }: PermissionEvidenceProps
return <PayloadPermissionEvidence label={label} payload={payload} />
}
-/** A decline that relays feedback is answered through its inline textarea, not a plain click. */
-function isFeedbackOption(option: ApprovalCardOption): boolean {
- return option.requiresFeedback || option.supportsFeedback
-}
-
-function optionRowLabel(option: ApprovalCardOption): string {
- // The wire's feedback option describes the interaction ("Type here to tell the agent…") instead of
- // naming the choice; the textarea placeholder carries that instruction, the row just needs a name.
- if (isFeedbackOption(option) && /^type here\b/i.test(option.label)) {
- return 'Do it differently…'
- }
- return option.label
-}
-
-function optionSublabel(option: ApprovalCardOption): string | null {
- if (option.requiresFeedback) {
- return 'The agent adjusts and continues instead of stopping this turn.'
- }
- if (option.supportsFeedback) {
- return 'With a note the agent adjusts and continues. Without one, declining stops this turn.'
- }
- if (option.decision === 'declined') {
- return 'Stops this turn. Send a follow-up to redirect the agent.'
- }
- return null
-}
-
interface PermissionOptionRowsProps {
options: ApprovalCardOption[]
responding: boolean
@@ -460,6 +434,7 @@ function GenericPermissionInput({
responding,
onRespond,
}: GenericPermissionInputProps): JSX.Element {
+ const skin = useThreadSkin()
const display = getPermissionDisplay(request)
// Only a genuine wire-level description that says more than the tool title becomes the
// headline; a title-only request keeps the derived tool title as its headline (and the
@@ -476,31 +451,46 @@ function GenericPermissionInput({
/>
)
+ const preview = PermissionPreview ? (
+ <PostHogErrorBoundary
+ key={`${streamKey}:${request.requestId}`}
+ additionalProperties={{ feature: 'posthog_ai_permission_preview' }}
+ fallback={evidence}
+ >
+ <Suspense fallback={evidence}>
+ <PermissionPreview request={request} fallback={evidence} />
+ </Suspense>
+ </PostHogErrorBoundary>
+ ) : (
+ evidence
+ )
+ const headline = headlineBody ? (
+ <div className="max-h-60 overflow-y-auto min-w-0 flex-1">
+ <MarkdownMessage content={headlineBody} id={`permission-${request.requestId}`} />
+ </div>
+ ) : (
+ <span>{display.title ?? 'Approval required'}</span>
+ )
+
+ if (skin === 'quill') {
+ return (
+ <QuillPermissionQuestionnaire
+ headline={headline}
+ evidence={preview}
+ options={options}
+ responding={responding}
+ onRespond={onRespond}
+ />
+ )
+ }
+
return (
<div className="flex flex-col gap-2.5 p-3">
<div className="flex items-start gap-2 text-sm font-medium">
<IconWarning className="text-warning size-4 mt-0.5 shrink-0" />
- {headlineBody ? (
- <div className="max-h-60 overflow-y-auto min-w-0 flex-1">
- <MarkdownMessage content={headlineBody} id={`permission-${request.requestId}`} />
- </div>
- ) : (
- <span>{display.title ?? 'Approval required'}</span>
- )}
+ {headline}
</div>
- {PermissionPreview ? (
- <PostHogErrorBoundary
- key={`${streamKey}:${request.requestId}`}
- additionalProperties={{ feature: 'posthog_ai_permission_preview' }}
- fallback={evidence}
- >
- <Suspense fallback={evidence}>
- <PermissionPreview request={request} fallback={evidence} />
- </Suspense>
- </PostHogErrorBoundary>
- ) : (
- evidence
- )}
+ {preview}
<PermissionOptionRows options={options} responding={responding} onRespond={onRespond} />
</div>
)
diff --git a/products/posthog_ai/frontend/components/PullRequestCard.tsx b/products/posthog_ai/frontend/components/PullRequestCard.tsx
index 6e2903f5d5c5..ab77371caba3 100644
--- a/products/posthog_ai/frontend/components/PullRequestCard.tsx
+++ b/products/posthog_ai/frontend/components/PullRequestCard.tsx
@@ -3,6 +3,9 @@ import { memo } from 'react'
import { IconCheckCircle, IconExternal, IconPullRequest } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
+import { QuillPullRequestRow } from './quill/QuillPullRequestRow'
+import { useQuillThread } from './quill/quillThreadContext'
+
/**
* Post-turn "Pull request opened" card for a sandbox coding run — the web port of PostHog Desktop's
* `GitActionResult`, adapted to LemonUI. Plain props, `React.memo`'d — `prUrl` is required, so the
@@ -17,6 +20,9 @@ export const PullRequestCard = memo(function PullRequestCard({
prUrl: string
branch?: string
}): JSX.Element {
+ if (useQuillThread()) {
+ return <QuillPullRequestRow prUrl={prUrl} branch={branch} />
+ }
return (
<div
className="flex flex-col gap-2 rounded-lg border border-success bg-success-highlight p-3"
diff --git a/products/posthog_ai/frontend/components/RunActivity.tsx b/products/posthog_ai/frontend/components/RunActivity.tsx
index d3229a167c13..d10104605e97 100644
--- a/products/posthog_ai/frontend/components/RunActivity.tsx
+++ b/products/posthog_ai/frontend/components/RunActivity.tsx
@@ -1,7 +1,7 @@
import { type ReactNode } from 'react'
import { Activity } from './ActivityPrimitives'
-import type { ActivityStatus } from './ActivityPrimitives'
+import type { ActivityStatus } from './activityTypes'
/**
* Progress / status card for the sandbox runtime — a thin adapter over the shared `Activity` used by
diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.tsx
index ba5198edd379..a7b2d824c516 100644
--- a/products/posthog_ai/frontend/components/RunAlertActivity.tsx
+++ b/products/posthog_ai/frontend/components/RunAlertActivity.tsx
@@ -4,8 +4,11 @@ import { LemonButton, Spinner } from '@posthog/lemon-ui'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { MarkdownMessage } from '../messages/MarkdownMessage'
-import type { RunAlertKind, RunConnectionState } from '../types/streamTypes'
+import type { RunConnectionState } from '../types/streamTypes'
import { Activity } from './ActivityPrimitives'
+import { QuillRunAlertCard } from './quill/QuillRunAlertCard'
+import { useQuillThread } from './quill/quillThreadContext'
+import { RUN_ALERT_TITLES } from './runAlertTitles'
interface RunAlertActivityProps extends RunConnectionState {
/** Stable id for the markdown message. Defaults per kind. */
@@ -17,15 +20,6 @@ interface RunAlertActivityProps extends RunConnectionState {
copyDetails?: string
}
-const TITLES: Record<RunAlertKind, string> = {
- reconnecting: 'Restoring conversation',
- connection_failed: 'Connection lost',
- agent_error: 'Run stopped',
- agent_error_continued: 'Agent error',
- agent_crash: 'Agent stopped unexpectedly',
- message_undelivered: 'Message not delivered',
-}
-
/**
* The card for every run stream/connection alert, used in two places:
* - the thread footer (selector-driven, `runStreamLogic.runConnectionState`) for the live `reconnecting`
@@ -47,13 +41,14 @@ export function RunAlertActivity({
copyDetails,
}: RunAlertActivityProps): JSX.Element {
const activityId = id ?? `run-alert-${kind}`
+ const quill = useQuillThread()
if (kind === 'reconnecting') {
const subtitle = attempt && maxAttempts ? `Attempt ${attempt} of ${maxAttempts}` : 'Loading…'
return (
<Activity
id={activityId}
- title={TITLES.reconnecting}
+ title={RUN_ALERT_TITLES.reconnecting}
subtitle={subtitle}
status="in_progress"
icon={<Spinner className="size-3" />}
@@ -61,6 +56,20 @@ export function RunAlertActivity({
)
}
+ if (quill) {
+ return (
+ <QuillRunAlertCard
+ kind={kind}
+ id={activityId}
+ message={message}
+ retryable={retryable}
+ onRetry={onRetry}
+ undeliveredMessage={undeliveredMessage}
+ copyDetails={copyDetails}
+ />
+ )
+ }
+
// A stopped run gets a bordered card, not a tinted banner: red only on the icon, and the reason and
// the actions share the title's left edge.
return (
@@ -70,7 +79,7 @@ export function RunAlertActivity({
>
<div className="flex items-center gap-2 font-semibold">
<IconWarning className="size-4 shrink-0 text-danger" />
- <span className="grow">{TITLES[kind]}</span>
+ <span className="grow">{RUN_ALERT_TITLES[kind]}</span>
{copyDetails && (
<LemonButton
type="tertiary"
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index 5302d8272026..dc75a638129d 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -1,8 +1,9 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo } from 'react'
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'
+import { useThreadSkin } from '../hooks/useThreadSkin'
import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'
import { taskLogic } from '../logics/taskLogic'
import { isPiTaskRuntime, OriginProduct } from '../types/taskTypes'
@@ -11,6 +12,7 @@ import { ContextUsageChip } from './ContextUsageChip'
import { FeedbackPromptTrailer } from './FeedbackPromptTrailer'
import { PermissionInput } from './PermissionInput'
import { QuestionInput } from './QuestionInput'
+import { QuillRunSurfaceInputs } from './quill/QuillRunSurfaceInputs'
import { RunLogSkeleton } from './RunLogSkeleton'
import { ThreadView } from './ThreadView'
import { TurnFeedbackActions } from './TurnFeedbackActions'
@@ -56,8 +58,12 @@ interface RunSurfaceContextValue {
interaction: 'live' | 'read-only'
/** Run created by a Signals scout — the context-usage line is suppressed for these. */
isScout: boolean
+ floatingInputsHeight: number
+ setFloatingInputsHeight: (height: number) => void
}
+const FLOATING_INPUTS_GAP = 16
+
const RunSurfaceContext = createContext<RunSurfaceContextValue | null>(null)
function useRunSurfaceContext(): RunSurfaceContextValue {
@@ -91,6 +97,7 @@ function RunSurfaceRoot({
// A pending surface (no run id) must supply `streamKey` to key on; `runId` is the key otherwise.
const logicKey = streamKey ?? runId ?? ''
const hasOptimisticClientStream = !!streamKey && streamKey !== runId
+ const [floatingInputsHeight, setFloatingInputsHeight] = useState(0)
const { hasThreadItems } = useValues(runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }))
// The runtime and scout flag live on the task (not the run), so the surface owns loading it once and
@@ -136,6 +143,8 @@ function RunSurfaceRoot({
conversationId,
interaction,
isScout,
+ floatingInputsHeight,
+ setFloatingInputsHeight,
}}
>
<RunSurfaceBootstrap taskId={taskId} />
@@ -201,7 +210,8 @@ function RunSurfaceThread({
/** Composer-less live embeds keep the usage line in the thread footer; the runner shows it in its composer. */
showContextUsage?: boolean
} = {}): JSX.Element {
- const { interaction, isScout, taskId, streamKey, runId } = useRunSurfaceContext()
+ const { interaction, isScout, taskId, streamKey, runId, floatingInputsHeight } = useRunSurfaceContext()
+ const skin = useThreadSkin()
const { bootstrapLoading, hasThreadItems } = useValues(runStreamLogic)
// Feedback identity: always the task, matching `$ai_session_id` on other surfaces.
const feedbackSessionId = taskId
@@ -243,10 +253,12 @@ function RunSurfaceThread({
scrollRestorationKey={restoreReadPosition ? taskId : undefined}
className={className}
listClassName={listClassName}
+ endInset={floatingInputsHeight > 0 ? floatingInputsHeight + FLOATING_INPUTS_GAP : undefined}
rowClassName={rowClassName}
showContextUsage={showContextUsage && interaction === 'live' && !isScout}
renderTurnTrailer={collectsFeedback ? renderTurnTrailer : undefined}
footerExtra={feedbackPrompt}
+ skin={skin}
/>
)
}
@@ -265,36 +277,60 @@ function RunSurfaceComposer({
children?: ReactNode
isStopping?: boolean
}): JSX.Element | null {
- const { interaction, streamKey } = useRunSurfaceContext()
+ const { interaction, streamKey, floatingInputsHeight, setFloatingInputsHeight } = useRunSurfaceContext()
const { pendingPermissionRequest, respondingToPermission, currentRunStatus, runOpening } = useValues(runStreamLogic)
+ const skin = useThreadSkin()
if (interaction !== 'live') {
return null
}
const request = !isTerminalRunStatus(currentRunStatus) ? pendingPermissionRequest : null
const showApproval = !!request && !respondingToPermission && !isStopping
+ const approval =
+ request &&
+ (request.questions?.length ? (
+ <QuestionInput
+ key={`${request.sourceRunId}:${request.requestId}`}
+ streamKey={streamKey}
+ request={request}
+ disabled={isStopping}
+ />
+ ) : (
+ <PermissionInput
+ key={`${request.sourceRunId}:${request.requestId}`}
+ streamKey={streamKey}
+ request={request}
+ disabled={isStopping}
+ />
+ ))
+ const composer = children && (currentRunStatus !== null || runOpening) ? children : null
// Both inputs keep their local state through delivery and restoration, including uncommitted draft keystrokes.
+ if (skin === 'quill') {
+ return (
+ <QuillRunSurfaceInputs
+ approval={approval}
+ showApproval={showApproval}
+ composer={composer}
+ height={floatingInputsHeight}
+ onHeightChange={setFloatingInputsHeight}
+ />
+ )
+ }
return (
<>
- {request && (
+ {approval && (
<div hidden={!showApproval} className="border-t px-4 py-3" data-attr="run-approval">
- <div key={`${request.sourceRunId}:${request.requestId}`} className="mx-auto w-full max-w-180">
- {request.questions?.length ? (
- <QuestionInput streamKey={streamKey} request={request} disabled={isStopping} />
- ) : (
- <PermissionInput streamKey={streamKey} request={request} disabled={isStopping} />
- )}
- </div>
+ <div className="mx-auto w-full max-w-180">{approval}</div>
</div>
)}
- {children && (currentRunStatus !== null || runOpening) && (
+ {composer && (
<div
hidden={showApproval}
data-attr="composer"
className="px-4 pb-[calc(1rem_+_env(safe-area-inset-bottom))]"
>
<LemonDivider className="mt-0 mb-4" />
- <div className="mx-auto w-full max-w-180">{children}</div>
+ <div className="mx-auto w-full max-w-180">{composer}</div>
</div>
)}
</>
diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
index 7f5e1d7c0519..8f14c1e877d0 100644
--- a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
@@ -1,124 +1,34 @@
-import { Fragment, type ReactNode, useEffect, useState } from 'react'
-
import { IconChevronRight, IconSpinner } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { MarkdownMessage } from '../messages/MarkdownMessage'
-import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
-import {
- ACTIVITY_CHAIN_MIN,
- activityWindow,
- groupConsecutiveTools,
- type ThreadActivityGroup as ActivityGroup,
-} from '../utils/groupThreadActivity'
-import { resolveToolCall } from '../utils/toolResolver'
import { ActivityDisclosure } from './ActivityDisclosure'
import { ActivityElapsedTime } from './ActivityElapsedTime'
-import { Activity } from './ActivityPrimitives'
-import { lookupToolRenderer } from './tool/toolRegistry'
-import { VirtualizedThread } from './VirtualizedThread'
+import { ActivityGroupRows } from './ActivityGroupRows'
+import { QuillActivityGroup } from './quill/QuillActivityGroup'
+import { useQuillThread } from './quill/quillThreadContext'
+import { type ActivityGroupProps, useActivityGroup } from './useActivityGroup'
-export function ThreadActivityGroup({
- group,
- toolInvocations,
- active,
- cancelled,
- waitingForInput = false,
- renderItem,
-}: {
- group: ActivityGroup
- toolInvocations: Map<string, ToolInvocation>
- active: boolean
- cancelled: boolean
- waitingForInput?: boolean
- renderItem: (item: ThreadItem) => ReactNode
-}): JSX.Element {
- const pauseFollowing = VirtualizedThread.usePauseFollowing()
- const isFollowing = VirtualizedThread.useIsFollowing()
- const [expanded, setExpanded] = useState(false)
- const [visibleIds, setVisibleIds] = useState<string[]>([])
- const [showMiddle, setShowMiddle] = useState(false)
- useEffect(() => {
- if (expanded && isFollowing) {
- setVisibleIds((previous) =>
- previous.length === group.items.length && previous.every((id, index) => id === group.items[index].id)
- ? previous
- : group.items.map((item) => item.id)
- )
- }
- }, [expanded, isFollowing, group.items])
- const calls = group.items.flatMap((item) => {
- const call = item.toolCallId ? toolInvocations.get(item.toolCallId) : undefined
- return call ? [call] : []
- })
- const thoughtsOnly = group.items.every((item) => item.type === 'assistant_thought')
- const activeLabel = thoughtsOnly ? 'Thinking' : 'Working'
- const finishedLabel = thoughtsOnly ? 'Thought' : 'Worked'
- const label = waitingForInput ? 'Waiting for you' : active ? activeLabel : cancelled ? 'Stopped' : finishedLabel
- const current = active
- ? calls.findLast((call) => call.status === 'in_progress' || call.status === 'pending')
- : undefined
- const resolved = current ? resolveToolCall(current) : undefined
- const currentLabel =
- current && resolved
- ? current.title || lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName).displayName
- : 'Thinking…'
- const visible = new Set(visibleIds)
- const snapshot = isFollowing ? group.items : group.items.filter((item) => visible.has(item.id))
- const visibleThoughtsOnly = snapshot.every((item) => item.type === 'assistant_thought')
- const window = activityWindow(snapshot, showMiddle)
- const newCount = isFollowing ? 0 : group.items.filter((item) => !visible.has(item.id)).length
- const toggle = (): void => {
- if (!expanded) {
- setVisibleIds(group.items.map((item) => item.id))
- }
- setExpanded(!expanded)
- }
- const individualRows = (items: ThreadItem[]): ReactNode[] =>
- items.map((item) => (
- <Fragment key={item.id}>
- {visibleThoughtsOnly ? (
- <div className="text-muted">
- <MarkdownMessage id={item.id} content={item.text ?? ''} />
- </div>
- ) : (
- renderItem(item)
- )}
- </Fragment>
- ))
- // The first and last rows stay flat so a reader never opens two accordions to reach one call.
- // Flat rows keep their own item keys, so a row's expanded state survives when the window shifts.
- const rows = (items: ThreadItem[], fold: boolean): ReactNode =>
- groupConsecutiveTools(items, toolInvocations).flatMap((chain) => {
- if (!fold || chain.length < ACTIVITY_CHAIN_MIN) {
- return individualRows(chain)
- }
- const chainCalls = chain.map((item) => toolInvocations.get(item.toolCallId!)!)
- const resolved = resolveToolCall(chainCalls[0])
- const entry = lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName)
- const failed = chainCalls.filter((call) => call.status === 'failed').length
- const running =
- active && chainCalls.some((call) => call.status === 'pending' || call.status === 'in_progress')
- return (
- <div key={chain[0].id} data-attr="thread-tool-chain">
- <Activity
- id={`chain-${chain[0].id}`}
- title={
- <span className="flex items-center gap-2 min-w-0">
- <span className="truncate">{entry.displayName}</span>
- <span className="text-muted shrink-0">· {chain.length} calls</span>
- {failed > 0 && <span className="text-danger shrink-0">· {failed} failed</span>}
- </span>
- }
- icon={entry.icon}
- status={running ? 'in_progress' : 'completed'}
- animate={false}
- autoExpand={false}
- details={<div className="flex flex-col gap-1 min-w-0">{individualRows(chain)}</div>}
- />
- </div>
- )
- })
+export function ThreadActivityGroup(props: ActivityGroupProps): JSX.Element {
+ return useQuillThread() ? <QuillActivityGroup {...props} /> : <LemonThreadActivityGroup {...props} />
+}
+
+function LemonThreadActivityGroup(props: ActivityGroupProps): JSX.Element {
+ const { group, toolInvocations, active, waitingForInput = false, renderItem } = props
+ const {
+ label,
+ currentLabel,
+ calls,
+ thoughtsOnly,
+ expanded,
+ setExpanded,
+ window,
+ showMiddle,
+ toggleMiddle,
+ visibleThoughtsOnly,
+ newCount,
+ showNew,
+ } = useActivityGroup(props)
+ const rowProps = { thoughtsOnly: visibleThoughtsOnly, toolInvocations, active, renderItem }
return (
<div
@@ -129,7 +39,7 @@ export function ThreadActivityGroup({
type="tertiary"
size="small"
fullWidth
- onClick={toggle}
+ onClick={() => setExpanded(!expanded)}
aria-expanded={expanded}
aria-controls={`activity-details-${group.id}`}
data-attr="thread-activity-toggle"
@@ -171,7 +81,7 @@ export function ThreadActivityGroup({
)}
<ActivityDisclosure open={expanded} id={`activity-details-${group.id}`}>
<div className="ml-3 pl-3 border-l border-border-secondary flex flex-col gap-1 min-w-0">
- {rows(window.first, false)}
+ <ActivityGroupRows items={window.first} fold={false} {...rowProps} />
{window.hiddenCount > 0 && (
<>
<LemonButton
@@ -180,25 +90,24 @@ export function ThreadActivityGroup({
data-attr="thread-activity-more"
aria-expanded={showMiddle}
aria-controls={`activity-middle-${group.id}`}
- onClick={() => {
- pauseFollowing()
- setShowMiddle(!showMiddle)
- }}
+ onClick={toggleMiddle}
>
{showMiddle ? 'Show less' : `Show ${window.hiddenCount} more`}
</LemonButton>
<ActivityDisclosure open={showMiddle} id={`activity-middle-${group.id}`}>
- <div className="flex flex-col gap-1 min-w-0">{rows(window.middle, true)}</div>
+ <div className="flex flex-col gap-1 min-w-0">
+ <ActivityGroupRows items={window.middle} fold {...rowProps} />
+ </div>
</ActivityDisclosure>
</>
)}
- {rows(window.last, false)}
+ <ActivityGroupRows items={window.last} fold={false} {...rowProps} />
{newCount > 0 && (
<LemonButton
type="tertiary"
size="xsmall"
data-attr="thread-activity-refresh"
- onClick={() => setVisibleIds(group.items.map((item) => item.id))}
+ onClick={showNew}
>
Show {newCount} new {newCount === 1 ? 'activity' : 'activities'}
</LemonButton>
diff --git a/products/posthog_ai/frontend/components/ThreadItems.tsx b/products/posthog_ai/frontend/components/ThreadItems.tsx
index 9b4b93d2f6f6..222a677008b0 100644
--- a/products/posthog_ai/frontend/components/ThreadItems.tsx
+++ b/products/posthog_ai/frontend/components/ThreadItems.tsx
@@ -5,7 +5,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import type { ThreadItem } from '../types/streamTypes'
import { Activity } from './ActivityPrimitives'
-import type { ActivityStatus } from './ActivityPrimitives'
+import type { ActivityStatus } from './activityTypes'
/** Statuses that run for a while and get a spinner with their own label, keyed by wire status. */
const IN_PROGRESS_STATUS_LABELS: Record<string, string> = {
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index 85c5745f1daf..37a5f6611d36 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -18,6 +18,8 @@ import { ReasoningAnswer } from '../messages/ReasoningAnswer'
import type { ProgressStep, ThreadItem } from '../types/streamTypes'
import { resolveToolCall } from '../utils/toolResolver'
import { Activity } from './ActivityPrimitives'
+import { QuillAssistantMessage, QuillHumanMessage } from './quill/QuillMessages'
+import { useQuillThread } from './quill/quillThreadContext'
import { RunErrorRow } from './RunErrorRow'
import { ThreadAttachments } from './ThreadAttachments'
import { CompactBoundaryItem, ConversationClearedItem, StatusItem, TaskNotificationItem } from './ThreadItems'
@@ -145,7 +147,11 @@ export const ThreadRow = memo(function ThreadRow({
turnCancelled,
runEnded = true,
}: ThreadRowProps): JSX.Element | null {
+ const quill = useQuillThread()
if (item.type === 'human_message') {
+ if (quill) {
+ return <QuillHumanMessage item={item} />
+ }
return (
<MessageTemplate
type="human"
@@ -158,6 +164,9 @@ export const ThreadRow = memo(function ThreadRow({
)
}
if (item.type === 'assistant_message') {
+ if (quill) {
+ return <QuillAssistantMessage item={item} />
+ }
return (
<MessageTemplate type="ai" wrapperClassName="max-w-4/5">
<MarkdownMessage content={item.text ?? ''} id={item.id} />
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index ce56794db99f..02a0d471545a 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from 'react'
+import { cn } from 'lib/utils/css-classes'
import { inStorybookTestRunner } from 'lib/utils/dom'
import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'
@@ -13,6 +14,7 @@ import { TurnHoverStore } from '../utils/turnHoverStore'
import { type TurnTrailer, computeTurnTrailers, mapRowsToTurnSeparator } from '../utils/turnTrailers'
import { ContextUsageChip } from './ContextUsageChip'
import { PullRequestCard } from './PullRequestCard'
+import { type ThreadSkin, ThreadSkinContext } from './quill/quillThreadContext'
import { RunAlertActivity } from './RunAlertActivity'
import { RunContext } from './RunContext'
import { ThreadActivityGroup } from './ThreadActivityGroup'
@@ -73,9 +75,18 @@ interface ThreadViewProps {
footerExtra?: ReactNode
className?: string
listClassName?: string
+ endInset?: number
rowClassName?: string
+ /**
+ * `quill` lays the thread out like PostHog Desktop's chat: user bubbles, ghost assistant prose, and
+ * each step as a quill chat marker. Every presenter below picks its skin from `ThreadSkinContext`,
+ * so tool renderers need no changes.
+ */
+ skin?: ThreadSkin
}
+const QUILL_ROW_GAP = 16
+
/**
* Sandbox-runtime thread presenter. Reads `runStreamLogic.values.threadItems` (assistant text,
* tool-invocation references, run separators, inline errors) from whatever `runStreamLogic`
@@ -96,6 +107,8 @@ export function ThreadView({
className,
listClassName,
rowClassName,
+ endInset,
+ skin = 'lemon',
}: ThreadViewProps): JSX.Element {
const {
threadItems,
@@ -269,7 +282,7 @@ export function ThreadView({
]
)
- return (
+ const thread = (
<VirtualizedThread.Root
key={scrollRestorationKey}
scrollRestorationKey={scrollRestorationKey}
@@ -287,12 +300,29 @@ export function ThreadView({
// thread is already pinned when the first streamed rows land.
turnActive={streamPhase !== 'idle'}
virtualized={virtualized}
+ endInset={endInset}
+ gap={skin === 'quill' ? QUILL_ROW_GAP : undefined}
className={className}
listClassName={listClassName}
>
{renderItem}
</VirtualizedThread.Root>
)
+ if (skin === 'lemon') {
+ return thread
+ }
+ return (
+ <ThreadSkinContext.Provider value={skin}>
+ {/* Virtualized, the root lays out rows itself; in document flow, this wrapper sets the rhythm. */}
+ {/* Quill's text color, set once here: a ghost bubble sets none, so its prose would inherit the page's. */}
+ <div
+ data-quill
+ className={cn('text-[var(--foreground)]', virtualized ? 'contents' : 'flex flex-col gap-4')}
+ >
+ {thread}
+ </div>
+ </ThreadSkinContext.Provider>
+ )
}
/** Leading run-context row. Memoized so it only re-renders when the run's branch/repo refs change. */
diff --git a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
index ded93892870b..71f7aa0f29b1 100644
--- a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
+++ b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
@@ -1,6 +1,5 @@
import clsx from 'clsx'
-import { useActions, useValues } from 'kea'
-import { useContext, useState, memo } from 'react'
+import { useContext, memo } from 'react'
import { IconCopy, IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'
import { LemonButton, LemonInput } from '@posthog/lemon-ui'
@@ -9,30 +8,23 @@ import { TZLabel } from 'lib/components/TZLabel'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { stripMarkdown } from 'lib/utils/markdown'
-import { messageRatingsLogic } from '../logics/messageRatingsLogic'
import { MessageTemplate } from '../messages/MessageTemplate'
-import { RunRef, captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'
+import { useQuillThread } from './quill/quillThreadContext'
+import { QuillTurnFeedbackActions } from './quill/QuillTurnFeedbackActions'
+import type { TurnFeedbackActionsProps } from './turnFeedbackTypes'
import { TurnRevealContext } from './TurnRevealContext'
-
-export interface TurnFeedbackActionsProps {
- /** Task id backing the sandbox conversation. Lands in `$ai_session_id`. */
- sessionId: string
- /** Ordinal of the completed turn — the rating's identity, stable across reloads. */
- turnIndex: number
- run: RunRef
- /** The turn's gateway trace id, when the run reported one. Lands in `$ai_trace_id`. */
- traceId?: string
- turnText: string
- /** When the turn completed, in milliseconds. */
- timestamp?: number
-}
+import { useTurnRating } from './useTurnRating'
/**
* Feedback actions under a completed turn: copy, thumbs up/down, the completion time, and a
* free-text form on thumbs-down. Counterpart of the legacy thread's `SuccessActions` — same events
* (`$ai_metric` quality / `$ai_feedback`), plus runtime/task/run properties.
*/
-export const TurnFeedbackActions = memo(function TurnFeedbackActions({
+export const TurnFeedbackActions = memo(function TurnFeedbackActions(props: TurnFeedbackActionsProps): JSX.Element {
+ return useQuillThread() ? <QuillTurnFeedbackActions {...props} /> : <LemonTurnFeedbackActions {...props} />
+})
+
+function LemonTurnFeedbackActions({
sessionId,
turnIndex,
run,
@@ -40,33 +32,9 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
turnText,
timestamp,
}: TurnFeedbackActionsProps): JSX.Element {
- const { ratingForKey } = useValues(messageRatingsLogic)
- const { setRating } = useActions(messageRatingsLogic)
const turnHovered = useContext(TurnRevealContext)
-
- const ratingKey = `${sessionId}:turn-${turnIndex}`
- const rating = ratingForKey(ratingKey)
- const [feedback, setFeedback] = useState<string>('')
- const [feedbackInputStatus, setFeedbackInputStatus] = useState<'hidden' | 'pending' | 'submitted'>('hidden')
-
- function submitRating(newRating: 'good' | 'bad'): void {
- if (rating) {
- return // Already rated
- }
- setRating({ key: ratingKey, rating: newRating })
- captureTurnRating(sessionId, traceId ?? null, newRating, turnIndex, run)
- if (newRating === 'bad') {
- setFeedbackInputStatus('pending')
- }
- }
-
- function submitFeedback(): void {
- if (!feedback) {
- return // Input is empty
- }
- captureTurnFeedbackText(sessionId, traceId ?? null, feedback, turnIndex, run)
- setFeedbackInputStatus('submitted')
- }
+ const { rating, submitRating, feedback, setFeedback, feedbackInputStatus, closeFeedback, submitFeedback } =
+ useTurnRating({ sessionId, turnIndex, run, traceId })
return (
<>
@@ -119,12 +87,7 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
? 'What disappointed you about the answer?'
: 'Thank you for your feedback!'}
</h4>
- <LemonButton
- icon={<IconX />}
- type="tertiary"
- size="xsmall"
- onClick={() => setFeedbackInputStatus('hidden')}
- />
+ <LemonButton icon={<IconX />} type="tertiary" size="xsmall" onClick={closeFeedback} />
</div>
{feedbackInputStatus === 'pending' && (
<div className="flex w-full gap-1.5 items-center mt-1.5">
@@ -150,4 +113,4 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
)}
</>
)
-})
+}
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index 5d6f901b9355..f827f0369557 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -103,6 +103,8 @@ interface RootContextValue {
measureElement: (node: Element | null) => void
/** Inter-row spacing (px), applied as bottom padding on the measured row so heights include it. */
gap: number
+ /** The last row takes no gap: nothing follows it, and an empty footer would otherwise leave a blank strip. */
+ lastIndex: number
maxWidthClassName: string
/** When false, rows render in document flow (no virtualization) and an ancestor owns scroll. */
virtualized: boolean
@@ -190,6 +192,7 @@ export interface VirtualizedThreadRootProps<T> {
*/
virtualized?: boolean
listClassName?: string
+ endInset?: number
children: (item: T, index: number) => ReactNode
}
@@ -216,6 +219,7 @@ function Root<T>({
maxWidthClassName = 'max-w-180',
className,
listClassName,
+ endInset = 0,
virtualized = true,
children,
}: VirtualizedThreadRootProps<T>): JSX.Element {
@@ -350,6 +354,7 @@ function Root<T>({
estimateSize: estimateVirtualRow,
overscan: overscanCount,
getItemKey: getVirtualItemKey,
+ paddingEnd: endInset,
// The virtualizer writes container height + row offsets to the DOM itself, in the same tick as each
// measurement — no stale-offset overlap while rows measure, and React re-renders only on range change.
directDomUpdates: true,
@@ -895,12 +900,13 @@ function Root<T>({
() => ({
measureElement: virtualizer.measureElement,
gap,
+ lastIndex: rowCount - 1,
maxWidthClassName,
virtualized,
isFollowing: stickToBottom && (!virtualized || pinned),
pauseFollowing: () => setPinned(false),
}),
- [virtualizer, gap, maxWidthClassName, virtualized, stickToBottom, pinned, setPinned]
+ [virtualizer, gap, rowCount, maxWidthClassName, virtualized, stickToBottom, pinned, setPinned]
)
// Flow mode: render rows directly so an ancestor scroll container (and its auto-scroller) keeps working.
@@ -968,7 +974,7 @@ function Row({ children, className }: { children: ReactNode; className?: string
if (!root || !row) {
throw new Error('VirtualizedThread.Row must be rendered inside VirtualizedThread.Root')
}
- const { measureElement, gap, maxWidthClassName, virtualized } = root
+ const { measureElement, gap, lastIndex, maxWidthClassName, virtualized } = root
const { index } = row
// Re-registers the node whenever `index` changes: the virtualizer's element cache (which both direct
@@ -1000,7 +1006,7 @@ function Row({ children, className }: { children: ReactNode; className?: string
<div ref={measureRef} style={ROW_BASE_STYLE}>
<div
className={cn('w-full mx-auto @container/thread', maxWidthClassName, className)}
- style={{ paddingBottom: gap }}
+ style={{ paddingBottom: index === lastIndex ? 0 : gap }}
>
{children}
</div>
diff --git a/products/posthog_ai/frontend/components/activityTypes.ts b/products/posthog_ai/frontend/components/activityTypes.ts
new file mode 100644
index 000000000000..b1c0933a9f0c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/activityTypes.ts
@@ -0,0 +1,20 @@
+import type { ReactNode } from 'react'
+
+export type ActivityStatus = 'pending' | 'in_progress' | 'completed' | 'failed'
+
+export interface ActivityProps {
+ id: string
+ title: ReactNode
+ subtitle?: ReactNode
+ status: ActivityStatus
+ icon?: ReactNode
+ animate?: boolean
+ showCompletionIcon?: boolean
+ showProgressIcon?: boolean
+ failedIcon?: ReactNode
+ substeps?: string[]
+ details?: ReactNode
+ children?: ReactNode
+ autoExpand?: boolean
+ onToggleDetails?: (expanded: boolean) => void
+}
diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx
index 0195ea3a21af..0148e4d46310 100644
--- a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx
+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx
@@ -1,168 +1,6 @@
-import { useActions, useValues } from 'kea'
+import { AttachedContextChips } from './AttachedContextChips'
+import { AttachedContextPicker } from './AttachedContextPicker'
-import { IconAtSign, IconBug, IconDashboard, IconGraph, IconNotebook, IconX } from '@posthog/icons'
-import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
-
-import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
-import { IconAction, IconEvent } from 'lib/lemon-ui/icons'
-
-import { attachedContextLogic } from '../../logics/attachedContextLogic'
-import { contextPickerLogic } from '../../logics/contextPickerLogic'
-import { type AttachedContextItem, attachedContextItemKey } from '../../types/contextTypes'
-
-const PICKER_GROUP_TYPES: TaxonomicFilterGroupType[] = [
- TaxonomicFilterGroupType.Events,
- TaxonomicFilterGroupType.Actions,
- TaxonomicFilterGroupType.Insights,
- TaxonomicFilterGroupType.Dashboards,
- TaxonomicFilterGroupType.Notebooks,
- TaxonomicFilterGroupType.ErrorTrackingIssues,
-]
-
-function iconForType(type: string): JSX.Element {
- switch (type) {
- case 'dashboard':
- return <IconDashboard />
- case 'insight':
- return <IconGraph />
- case 'event':
- return <IconEvent />
- case 'action':
- return <IconAction />
- case 'notebook':
- return <IconNotebook />
- case 'error_tracking_issue':
- return <IconBug />
- default:
- return <IconAtSign />
- }
-}
-
-function labelForItem(item: AttachedContextItem): string {
- if (item.label) {
- return item.label
- }
- if (item.type === 'text') {
- return item.value ?? 'Text'
- }
- return `${item.type} ${item.key ?? ''}`.trim()
-}
-
-interface AttachmentPreviewProps {
- label: string
- html: string
- onRemove?: () => void
-}
-
-/** An attached item with a preview, shown as a thumbnail with its name, like an image attachment in a chat composer. */
-function AttachmentPreview({ label, html, onRemove }: AttachmentPreviewProps): JSX.Element {
- return (
- <div
- className="relative flex flex-col w-24 shrink-0 rounded border bg-surface-primary overflow-hidden"
- data-attr="posthog-ai-context-attachment"
- >
- <EmailPreviewThumbnail html={html} title={`${label} preview`} size="attachment" className="border-b" />
- <span className="px-1.5 py-1 text-xs truncate" title={label}>
- {label}
- </span>
- {onRemove && (
- <LemonButton
- size="xxsmall"
- type="secondary"
- icon={<IconX className="h-3 w-3" />}
- onClick={onRemove}
- tooltip="Remove"
- aria-label={`Remove ${label}`}
- className="absolute top-0.5 right-0.5 bg-surface-primary"
- />
- )}
- </div>
- )
-}
-
-/**
- * The composer's context affordance: an @-button (TaxonomicPopover) that attaches entity refs to
- * `contextPickerLogic`, plus removable chips for everything currently in
- * `attachedContextLogic.contextItems` — picked items and auto-registered providers (e.g. the scene
- * bridge) alike. Closing a dismissible picked chip removes it from the picker; closing any other
- * dismissible provider's chip dismisses its key, which sticks even when the provider re-registers
- * the item. Providers can keep mandatory context visible with `dismissible: false`.
- * An item with `previewHtml` shows as a thumbnail in a row above the chips instead of as a chip.
- */
-export function AttachedContextBar(): JSX.Element {
- const { contextItems, hasContext } = useValues(attachedContextLogic)
- const { dismissContext } = useActions(attachedContextLogic)
- const { pickedKeys } = useValues(contextPickerLogic)
- const { handleTaxonomicFilterChange, removePickedItem } = useActions(contextPickerLogic)
-
- const visibleItems = contextItems.filter((item) => !item.hidden)
- const attachments = visibleItems.filter((item) => item.previewHtml)
- const chips = visibleItems.filter((item) => !item.previewHtml)
- const removeItem = (item: AttachedContextItem): (() => void) | undefined => {
- if (item.dismissible === false) {
- return undefined
- }
- const key = attachedContextItemKey(item)
- return () => (pickedKeys.has(key) ? removePickedItem(key) : dismissContext(key, item.dismissGroup))
- }
-
- return (
- <div className="flex flex-col gap-2 min-w-0">
- {attachments.length > 0 && (
- <div className="flex gap-2 overflow-x-auto" data-attr="posthog-ai-context-attachments">
- {attachments.map((item) => (
- <AttachmentPreview
- key={attachedContextItemKey(item)}
- label={labelForItem(item)}
- html={item.previewHtml!}
- onRemove={removeItem(item)}
- />
- ))}
- </div>
- )}
- <div className="flex flex-wrap items-center gap-1 min-w-0">
- <Tooltip title="Add context to help PostHog AI answer your question">
- {/* Wrapper span prevents Base UI's Tooltip.Trigger from merging
- props into TaxonomicPopover. Without it, mergeProps treats
- onChange as a DOM event handler and wraps it in a single-arg
- callback, dropping the groupType and item arguments. */}
- <span>
- <TaxonomicPopover
- size="xxsmall"
- type="tertiary"
- className="flex-shrink-0 border"
- groupType={TaxonomicFilterGroupType.Events}
- groupTypes={PICKER_GROUP_TYPES}
- onChange={handleTaxonomicFilterChange}
- icon={<IconAtSign className="text-secondary" />}
- placeholder={hasContext ? null : 'Add context'}
- placeholderClass="text-secondary"
- width={450}
- data-attr="posthog-ai-context-picker"
- />
- </span>
- </Tooltip>
- {chips.map((item) => {
- const key = attachedContextItemKey(item)
- const label = labelForItem(item)
- const onRemove = removeItem(item)
- return (
- <Tooltip key={key} title={label}>
- <LemonTag
- icon={iconForType(item.type)}
- onClose={onRemove}
- closable={!!onRemove}
- closeOnClick={!!onRemove}
- className="flex items-center text-secondary max-w-48"
- >
- <span className="truncate min-w-0 flex-1">{label}</span>
- </LemonTag>
- </Tooltip>
- )
- })}
- </div>
- </div>
- )
+export function AttachedContextBar(): JSX.Element | null {
+ return <AttachedContextChips leading={<AttachedContextPicker />} />
}
diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx
new file mode 100644
index 000000000000..552209ebdafc
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx
@@ -0,0 +1,146 @@
+import { useActions, useValues } from 'kea'
+import type { ReactNode } from 'react'
+
+import { IconAtSign, IconBug, IconDashboard, IconGraph, IconNotebook, IconX } from '@posthog/icons'
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'
+import { IconAction, IconEvent } from 'lib/lemon-ui/icons'
+
+import { attachedContextLogic } from '../../logics/attachedContextLogic'
+import { contextPickerLogic } from '../../logics/contextPickerLogic'
+import { type AttachedContextItem, attachedContextItemKey } from '../../types/contextTypes'
+
+function iconForType(type: string): JSX.Element {
+ switch (type) {
+ case 'dashboard':
+ return <IconDashboard />
+ case 'insight':
+ return <IconGraph />
+ case 'event':
+ return <IconEvent />
+ case 'action':
+ return <IconAction />
+ case 'notebook':
+ return <IconNotebook />
+ case 'error_tracking_issue':
+ return <IconBug />
+ default:
+ return <IconAtSign />
+ }
+}
+
+function labelForItem(item: AttachedContextItem): string {
+ if (item.label) {
+ return item.label
+ }
+ if (item.type === 'text') {
+ return item.value ?? 'Text'
+ }
+ return `${item.type} ${item.key ?? ''}`.trim()
+}
+
+interface AttachmentPreviewProps {
+ label: string
+ html: string
+ onRemove?: () => void
+}
+
+function AttachmentPreview({ label, html, onRemove }: AttachmentPreviewProps): JSX.Element {
+ return (
+ <div
+ className="relative flex flex-col w-24 shrink-0 rounded border bg-surface-primary overflow-hidden"
+ data-attr="posthog-ai-context-attachment"
+ >
+ <EmailPreviewThumbnail html={html} title={`${label} preview`} size="attachment" className="border-b" />
+ <span className="px-1.5 py-1 text-xs truncate" title={label}>
+ {label}
+ </span>
+ {onRemove && (
+ <LemonButton
+ size="xxsmall"
+ type="secondary"
+ icon={<IconX className="h-3 w-3" />}
+ onClick={onRemove}
+ tooltip="Remove"
+ aria-label={`Remove ${label}`}
+ className="absolute top-0.5 right-0.5 bg-surface-primary"
+ />
+ )}
+ </div>
+ )
+}
+
+export interface AttachedContextChipsProps {
+ leading?: ReactNode
+}
+
+/**
+ * Removable chips for everything in `attachedContextLogic.contextItems`: picked items and
+ * auto-registered providers (e.g. the scene bridge) alike. Closing a dismissible picked chip removes it
+ * from the picker; closing any other dismissible provider's chip dismisses its key, which sticks even
+ * when the provider re-registers the item. Providers can keep mandatory context visible with
+ * `dismissible: false`. An item with `previewHtml` shows as a thumbnail in a row above the chips.
+ * Renders nothing when there is neither context nor a `leading` slot.
+ */
+export function AttachedContextChips({ leading }: AttachedContextChipsProps): JSX.Element | null {
+ const { contextItems } = useValues(attachedContextLogic)
+ const { dismissContext } = useActions(attachedContextLogic)
+ const { pickedKeys } = useValues(contextPickerLogic)
+ const { removePickedItem } = useActions(contextPickerLogic)
+
+ const visibleItems = contextItems.filter((item) => !item.hidden)
+ const attachments = visibleItems.filter((item) => item.previewHtml)
+ const chips = visibleItems.filter((item) => !item.previewHtml)
+ const removeItem = (item: AttachedContextItem): (() => void) | undefined => {
+ if (item.dismissible === false) {
+ return undefined
+ }
+ const key = attachedContextItemKey(item)
+ return () => (pickedKeys.has(key) ? removePickedItem(key) : dismissContext(key, item.dismissGroup))
+ }
+
+ if (visibleItems.length === 0 && !leading) {
+ return null
+ }
+
+ return (
+ <div className="flex flex-col gap-2 min-w-0">
+ {attachments.length > 0 && (
+ <div className="flex gap-2 overflow-x-auto" data-attr="posthog-ai-context-attachments">
+ {attachments.map((item) => (
+ <AttachmentPreview
+ key={attachedContextItemKey(item)}
+ label={labelForItem(item)}
+ html={item.previewHtml!}
+ onRemove={removeItem(item)}
+ />
+ ))}
+ </div>
+ )}
+ {(leading || chips.length > 0) && (
+ <div className="flex flex-wrap items-center gap-1 min-w-0">
+ {leading}
+ {chips.map((item) => {
+ const key = attachedContextItemKey(item)
+ const label = labelForItem(item)
+ const onRemove = removeItem(item)
+ return (
+ <Tooltip key={key} title={label}>
+ <LemonTag
+ icon={iconForType(item.type)}
+ onClose={onRemove}
+ closable={!!onRemove}
+ closeOnClick={!!onRemove}
+ className="flex items-center text-secondary max-w-48"
+ >
+ <span className="truncate min-w-0 flex-1">{label}</span>
+ </LemonTag>
+ </Tooltip>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx
new file mode 100644
index 000000000000..d45c8b008269
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx
@@ -0,0 +1,51 @@
+import { useActions, useValues } from 'kea'
+
+import { IconAtSign } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+
+import { attachedContextLogic } from '../../logics/attachedContextLogic'
+import { contextPickerLogic } from '../../logics/contextPickerLogic'
+
+const PICKER_GROUP_TYPES: TaxonomicFilterGroupType[] = [
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.Insights,
+ TaxonomicFilterGroupType.Dashboards,
+ TaxonomicFilterGroupType.Notebooks,
+ TaxonomicFilterGroupType.ErrorTrackingIssues,
+]
+
+export interface AttachedContextPickerProps {
+ className?: string
+}
+
+export function AttachedContextPicker({ className = 'flex-shrink-0 border' }: AttachedContextPickerProps): JSX.Element {
+ const { hasContext } = useValues(attachedContextLogic)
+ const { handleTaxonomicFilterChange } = useActions(contextPickerLogic)
+ return (
+ <Tooltip title="Add context to help PostHog AI answer your question">
+ {/* Wrapper span prevents Base UI's Tooltip.Trigger from merging
+ props into TaxonomicPopover. Without it, mergeProps treats
+ onChange as a DOM event handler and wraps it in a single-arg
+ callback, dropping the groupType and item arguments. */}
+ <span>
+ <TaxonomicPopover
+ size="xxsmall"
+ type="tertiary"
+ className={className}
+ groupType={TaxonomicFilterGroupType.Events}
+ groupTypes={PICKER_GROUP_TYPES}
+ onChange={handleTaxonomicFilterChange}
+ icon={<IconAtSign className="text-secondary" />}
+ placeholder={hasContext ? null : 'Add context'}
+ placeholderClass="text-secondary"
+ width={450}
+ data-attr="posthog-ai-context-picker"
+ />
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/composer/ComposerAttachmentChips.tsx b/products/posthog_ai/frontend/components/composer/ComposerAttachmentChips.tsx
new file mode 100644
index 000000000000..672d47f994b9
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/ComposerAttachmentChips.tsx
@@ -0,0 +1,58 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { IconDocument, IconImage } from '@posthog/icons'
+import { LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
+import { formatFileSize, isImageAttachment } from '../../utils/attachments'
+
+/** The bytes are already in the browser, so this preview costs an object URL and no request. */
+function AttachmentThumbnail({ file }: { file: File }): JSX.Element {
+ const [src, setSrc] = useState<string | null>(null)
+ useEffect(() => {
+ const objectUrl = URL.createObjectURL(file)
+ setSrc(objectUrl)
+ return () => URL.revokeObjectURL(objectUrl)
+ }, [file])
+
+ if (!src) {
+ return <IconImage />
+ }
+ return <img src={src} alt="" className="size-4 rounded-sm object-cover" />
+}
+
+export function ComposerAttachmentChips({ attachmentsKey }: { attachmentsKey: string }): JSX.Element | null {
+ const logic = composerAttachmentsLogic({ attachmentsKey })
+ const { stagedAttachments, uploading } = useValues(logic)
+ const { removeAttachment } = useActions(logic)
+ if (stagedAttachments.length === 0) {
+ return null
+ }
+ return (
+ <>
+ {stagedAttachments.map(({ id, file }) => (
+ <Tooltip key={id} title={`${file.name} (${formatFileSize(file.size)})`}>
+ <LemonTag
+ icon={
+ uploading ? (
+ <Spinner />
+ ) : isImageAttachment(file.name) ? (
+ <AttachmentThumbnail file={file} />
+ ) : (
+ <IconDocument />
+ )
+ }
+ onClose={() => removeAttachment(id)}
+ closable={!uploading}
+ closeOnClick={!uploading}
+ className="flex items-center text-secondary max-w-48"
+ data-attr="posthog-ai-attachment-chip"
+ >
+ <span className="truncate min-w-0 flex-1">{file.name}</span>
+ </LemonTag>
+ </Tooltip>
+ ))}
+ </>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx b/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx
index 7eb200fac6e5..3918299f8954 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx
@@ -1,92 +1,12 @@
-import { useActions, useValues } from 'kea'
-import { type ChangeEvent, type ClipboardEvent, type RefObject, useCallback, useEffect, useRef, useState } from 'react'
+import { useActions } from 'kea'
+import { type ClipboardEvent, type RefObject, useCallback } from 'react'
-import { IconDocument, IconImage, IconUpload } from '@posthog/icons'
-import { LemonButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { IconUpload } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
-import { MAX_ATTACHMENTS_PER_MESSAGE, formatFileSize, isImageAttachment } from '../../utils/attachments'
-
-/**
- * Not `LemonFileInput`'s `alternativeDropTargetRef`: it keeps its own copy of the file list and re-syncs it
- * only when the `value` prop changes identity, so a composer whose logic owns the list grows that copy and
- * re-reports every earlier file on each drop.
- */
-function useFileDrop(target: RefObject<HTMLElement> | undefined, onFiles: (files: File[]) => void): boolean {
- const [isOver, setIsOver] = useState(false)
- // Dragging over a child fires dragleave on the parent, so count nesting rather than flicker off.
- const depth = useRef(0)
- const onFilesRef = useRef(onFiles)
- onFilesRef.current = onFiles
-
- useEffect(() => {
- const node = target?.current
- if (!node) {
- return
- }
- const carriesFiles = (event: DragEvent): boolean =>
- Array.from(event.dataTransfer?.types ?? []).includes('Files')
- const onDragEnter = (event: DragEvent): void => {
- if (!carriesFiles(event)) {
- return
- }
- depth.current += 1
- setIsOver(true)
- }
- const onDragOver = (event: DragEvent): void => {
- if (carriesFiles(event)) {
- // Or the browser takes the drop itself and navigates to the file.
- event.preventDefault()
- }
- }
- const onDragLeave = (): void => {
- depth.current = Math.max(0, depth.current - 1)
- if (depth.current === 0) {
- setIsOver(false)
- }
- }
- const onDrop = (event: DragEvent): void => {
- if (!carriesFiles(event)) {
- return
- }
- event.preventDefault()
- depth.current = 0
- setIsOver(false)
- const files = Array.from(event.dataTransfer?.files ?? [])
- if (files.length > 0) {
- onFilesRef.current(files)
- }
- }
-
- node.addEventListener('dragenter', onDragEnter)
- node.addEventListener('dragover', onDragOver)
- node.addEventListener('dragleave', onDragLeave)
- node.addEventListener('drop', onDrop)
- return () => {
- node.removeEventListener('dragenter', onDragEnter)
- node.removeEventListener('dragover', onDragOver)
- node.removeEventListener('dragleave', onDragLeave)
- node.removeEventListener('drop', onDrop)
- }
- }, [target])
-
- return isOver
-}
-
-/** The bytes are already in the browser, so this preview costs an object URL and no request. */
-function AttachmentThumbnail({ file }: { file: File }): JSX.Element {
- const [src, setSrc] = useState<string | null>(null)
- useEffect(() => {
- const objectUrl = URL.createObjectURL(file)
- setSrc(objectUrl)
- return () => URL.revokeObjectURL(objectUrl)
- }, [file])
-
- if (!src) {
- return <IconImage />
- }
- return <img src={src} alt="" className="size-4 rounded-sm object-cover" />
-}
+import { ComposerAttachmentChips } from './ComposerAttachmentChips'
+import { useComposerFilePicker } from './useComposerFilePicker'
export interface ComposerAttachmentsProps {
attachmentsKey: string
@@ -99,46 +19,15 @@ export function ComposerAttachments({
dropTargetRef,
disabledReason,
}: ComposerAttachmentsProps): JSX.Element {
- const logic = composerAttachmentsLogic({ attachmentsKey })
- const { stagedAttachments, uploading, isAtAttachmentLimit } = useValues(logic)
- const { addFiles, removeAttachment } = useActions(logic)
- const inputRef = useRef<HTMLInputElement>(null)
-
- const addDisabledReason =
- disabledReason ?? (isAtAttachmentLimit ? `Up to ${MAX_ATTACHMENTS_PER_MESSAGE} files per message` : undefined)
-
- const acceptDropped = useCallback(
- (files: File[]) => {
- if (!addDisabledReason) {
- addFiles(files)
- }
- },
- [addFiles, addDisabledReason]
+ const { fileInput, openPicker, isOver, addDisabledReason, hasStagedFiles } = useComposerFilePicker(
+ attachmentsKey,
+ dropTargetRef,
+ disabledReason
)
- const isOver = useFileDrop(dropTargetRef, acceptDropped)
-
- const onPicked = (event: ChangeEvent<HTMLInputElement>): void => {
- const files = Array.from(event.target.files ?? [])
- if (files.length > 0) {
- addFiles(files)
- }
- // Or picking the same file twice in a row is not a change and never fires.
- event.target.value = ''
- }
return (
<div className="flex flex-wrap items-center gap-1 min-w-0">
- <input
- ref={inputRef}
- type="file"
- multiple
- // The harness reads the artifact off disk with its own file tools, so narrowing here would
- // only refuse files that work.
- accept="*/*"
- className="hidden"
- onChange={onPicked}
- data-attr="posthog-ai-attach-input"
- />
+ {fileInput}
<LemonButton
size="xxsmall"
type="tertiary"
@@ -146,35 +35,12 @@ export function ComposerAttachments({
icon={<IconUpload className="text-secondary" />}
disabledReason={addDisabledReason}
tooltip="Attach files for PostHog AI to read"
- onClick={() => inputRef.current?.click()}
+ onClick={openPicker}
data-attr="posthog-ai-attach-file"
>
- {stagedAttachments.length > 0 ? null : (
- <span className="text-secondary">{isOver ? 'Drop to attach' : 'Attach'}</span>
- )}
+ {hasStagedFiles ? null : <span className="text-secondary">{isOver ? 'Drop to attach' : 'Attach'}</span>}
</LemonButton>
- {stagedAttachments.map(({ id, file }) => (
- <Tooltip key={id} title={`${file.name} (${formatFileSize(file.size)})`}>
- <LemonTag
- icon={
- uploading ? (
- <Spinner />
- ) : isImageAttachment(file.name) ? (
- <AttachmentThumbnail file={file} />
- ) : (
- <IconDocument />
- )
- }
- onClose={() => removeAttachment(id)}
- closable={!uploading}
- closeOnClick={!uploading}
- className="flex items-center text-secondary max-w-48"
- data-attr="posthog-ai-attachment-chip"
- >
- <span className="truncate min-w-0 flex-1">{file.name}</span>
- </LemonTag>
- </Tooltip>
- ))}
+ <ComposerAttachmentChips attachmentsKey={attachmentsKey} />
</div>
)
}
diff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx
index c486fe2e439b..6e3326c41742 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx
@@ -15,6 +15,9 @@ import {
RuntimeAdapterEnumApi,
} from 'products/tasks/frontend/generated/api.schemas'
+import { useThreadSkin } from '../../hooks/useThreadSkin'
+import { QuillModePicker } from '../quill/QuillModePicker'
+
interface ModeStyle {
icon: JSX.Element
className: string
@@ -83,6 +86,22 @@ export interface ComposerModePickerProps {
export function ComposerModePicker({ selectedMode, onModeChange, modes }: ComposerModePickerProps): JSX.Element {
// Ordered by `modes`, not by MODE_OPTIONS: each runtime lists its modes in its own order.
const offered = modes ?? getModesForRuntimeAdapter(RuntimeAdapterEnumApi.Claude)
+ const skin = useThreadSkin()
+ if (skin === 'quill') {
+ return <QuillModePicker selectedMode={selectedMode} onModeChange={onModeChange} modes={offered} />
+ }
+ return <SelectModePicker selectedMode={selectedMode} onModeChange={onModeChange} offered={offered} />
+}
+
+function SelectModePicker({
+ selectedMode,
+ onModeChange,
+ offered,
+}: {
+ selectedMode: PermissionMode
+ onModeChange: (mode: PermissionMode) => void
+ offered: PermissionMode[]
+}): JSX.Element {
const options = offered.flatMap((mode) => MODE_OPTIONS.filter((option) => option.value === mode))
const selectedOption = getModeOption(selectedMode)
// The mode the description strip shows. Base UI highlights the selected item on open, which
diff --git a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
index 70d2986856bd..224c6c516822 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
@@ -33,8 +33,10 @@ import {
RuntimeAdapterEnumApi,
} from 'products/tasks/frontend/generated/api.schemas'
+import { useThreadSkin } from '../../hooks/useThreadSkin'
import { ModelCostChip } from '../ModelCostChip'
import { ModelCostFooter } from '../ModelCostFooter'
+import type { ThreadSkin } from '../quill/quillThreadContext'
import { ComposerReasoningSlider } from './ComposerReasoningSlider'
// Separates model and effort in a slider stop key; never appears in a model id or an effort.
@@ -79,6 +81,11 @@ interface PickerSectionProps {
}
/** One `label … current ›` row of the cascade, opening a radio list. */
+const PICKER_CHROME: Record<ThreadSkin, { triggerVariant: 'outline' | 'default'; icons: boolean }> = {
+ lemon: { triggerVariant: 'outline', icons: true },
+ quill: { triggerVariant: 'default', icons: false },
+}
+
function PickerSection({ title, current, value, onValueChange, children, footer }: PickerSectionProps): JSX.Element {
return (
<DropdownMenuSub>
@@ -119,6 +126,7 @@ export function ComposerModelEffortPickers({
onResetToDefault,
onOpenDefaultSettings,
}: ComposerModelEffortPickersProps): JSX.Element {
+ const chrome = PICKER_CHROME[useThreadSkin()]
const [open, setOpen] = useState(false)
const [advanced, setAdvanced] = useState(false)
// Frozen when the Advanced view is entered rather than derived from the ladder: a model pick that steps off a
@@ -212,12 +220,12 @@ export function ComposerModelEffortPickers({
>
<DropdownMenuTrigger
render={
- <Button variant="outline" size="sm">
+ <Button variant={chrome.triggerVariant} size="sm">
{isDefaultSelection ? `Default · ${modelLabel}` : modelLabel}
{effortOptions.length > 0 && (
<span className="text-muted">{getEffortLabel(selectedEffort)}</span>
)}
- <IconChevronDown />
+ {chrome.icons && <IconChevronDown />}
</Button>
}
/>
@@ -321,7 +329,7 @@ export function ComposerModelEffortPickers({
)
}
>
- <IconRevert />
+ {chrome.icons && <IconRevert />}
Reset to default
</DropdownMenuItem>
)}
@@ -330,7 +338,7 @@ export function ComposerModelEffortPickers({
you disagree with is the moment you want to change it. */}
{onOpenDefaultSettings && (
<DropdownMenuItem onClick={() => selectAndClose(onOpenDefaultSettings)}>
- <IconGear />
+ {chrome.icons && <IconGear />}
Change default
</DropdownMenuItem>
)}
diff --git a/products/posthog_ai/frontend/components/composer/useComposerFilePicker.tsx b/products/posthog_ai/frontend/components/composer/useComposerFilePicker.tsx
new file mode 100644
index 000000000000..33fa19ae63e9
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/useComposerFilePicker.tsx
@@ -0,0 +1,69 @@
+import { useActions, useValues } from 'kea'
+import { type ChangeEvent, type RefObject, useCallback, useRef } from 'react'
+
+import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
+import { MAX_ATTACHMENTS_PER_MESSAGE } from '../../utils/attachments'
+import { useFileDrop } from './useFileDrop'
+
+export interface ComposerFilePicker {
+ fileInput: JSX.Element
+ openPicker: () => void
+ isOver: boolean
+ addDisabledReason: string | undefined
+ hasStagedFiles: boolean
+}
+
+export function useComposerFilePicker(
+ attachmentsKey: string,
+ dropTargetRef?: RefObject<HTMLElement>,
+ disabledReason?: string
+): ComposerFilePicker {
+ const logic = composerAttachmentsLogic({ attachmentsKey })
+ const { stagedAttachments, isAtAttachmentLimit } = useValues(logic)
+ const { addFiles } = useActions(logic)
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ const addDisabledReason =
+ disabledReason ?? (isAtAttachmentLimit ? `Up to ${MAX_ATTACHMENTS_PER_MESSAGE} files per message` : undefined)
+
+ const acceptDropped = useCallback(
+ (files: File[]) => {
+ if (!addDisabledReason) {
+ addFiles(files)
+ }
+ },
+ [addFiles, addDisabledReason]
+ )
+ const isOver = useFileDrop(dropTargetRef, acceptDropped)
+
+ const onPicked = (event: ChangeEvent<HTMLInputElement>): void => {
+ const files = Array.from(event.target.files ?? [])
+ if (files.length > 0) {
+ addFiles(files)
+ }
+ // Or picking the same file twice in a row is not a change and never fires.
+ event.target.value = ''
+ }
+
+ const fileInput = (
+ <input
+ ref={inputRef}
+ type="file"
+ multiple
+ // The harness reads the artifact off disk with its own file tools, so narrowing here would
+ // only refuse files that work.
+ accept="*/*"
+ className="hidden"
+ onChange={onPicked}
+ data-attr="posthog-ai-attach-input"
+ />
+ )
+
+ return {
+ fileInput,
+ openPicker: () => inputRef.current?.click(),
+ isOver,
+ addDisabledReason,
+ hasStagedFiles: stagedAttachments.length > 0,
+ }
+}
diff --git a/products/posthog_ai/frontend/components/composer/useFileDrop.ts b/products/posthog_ai/frontend/components/composer/useFileDrop.ts
new file mode 100644
index 000000000000..8d6059ab72a0
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/useFileDrop.ts
@@ -0,0 +1,67 @@
+import { type RefObject, useEffect, useRef, useState } from 'react'
+
+/**
+ * Not `LemonFileInput`'s `alternativeDropTargetRef`: it keeps its own copy of the file list and re-syncs it
+ * only when the `value` prop changes identity, so a composer whose logic owns the list grows that copy and
+ * re-reports every earlier file on each drop.
+ */
+export function useFileDrop(target: RefObject<HTMLElement> | undefined, onFiles: (files: File[]) => void): boolean {
+ const [isOver, setIsOver] = useState(false)
+ // Dragging over a child fires dragleave on the parent, so count nesting rather than flicker off.
+ const depth = useRef(0)
+ const onFilesRef = useRef(onFiles)
+ onFilesRef.current = onFiles
+
+ useEffect(() => {
+ const node = target?.current
+ if (!node) {
+ return
+ }
+ const carriesFiles = (event: DragEvent): boolean =>
+ Array.from(event.dataTransfer?.types ?? []).includes('Files')
+ const onDragEnter = (event: DragEvent): void => {
+ if (!carriesFiles(event)) {
+ return
+ }
+ depth.current += 1
+ setIsOver(true)
+ }
+ const onDragOver = (event: DragEvent): void => {
+ if (carriesFiles(event)) {
+ // Or the browser takes the drop itself and navigates to the file.
+ event.preventDefault()
+ }
+ }
+ const onDragLeave = (): void => {
+ depth.current = Math.max(0, depth.current - 1)
+ if (depth.current === 0) {
+ setIsOver(false)
+ }
+ }
+ const onDrop = (event: DragEvent): void => {
+ if (!carriesFiles(event)) {
+ return
+ }
+ event.preventDefault()
+ depth.current = 0
+ setIsOver(false)
+ const files = Array.from(event.dataTransfer?.files ?? [])
+ if (files.length > 0) {
+ onFilesRef.current(files)
+ }
+ }
+
+ node.addEventListener('dragenter', onDragEnter)
+ node.addEventListener('dragover', onDragOver)
+ node.addEventListener('dragleave', onDragLeave)
+ node.addEventListener('drop', onDrop)
+ return () => {
+ node.removeEventListener('dragenter', onDragEnter)
+ node.removeEventListener('dragover', onDragOver)
+ node.removeEventListener('dragleave', onDragLeave)
+ node.removeEventListener('drop', onDrop)
+ }
+ }, [target])
+
+ return isOver
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillActivity.tsx b/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
new file mode 100644
index 000000000000..d2e347d15e20
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
@@ -0,0 +1,60 @@
+import { cn } from '@posthog/quill-primitives'
+
+import { ActivitySubsteps } from '../ActivitySubsteps'
+import type { ActivityProps } from '../activityTypes'
+import { useActivityDisclosure } from '../useActivityDisclosure'
+import { ThreadMarker } from './ThreadMarker'
+
+export function QuillActivity({
+ id,
+ title,
+ subtitle,
+ status,
+ icon,
+ animate = true,
+ showProgressIcon = false,
+ failedIcon,
+ substeps = [],
+ details = null,
+ children = null,
+ autoExpand = true,
+ onToggleDetails,
+}: ActivityProps): JSX.Element {
+ const hasDetails = substeps.length > 0 || !!details
+ const { open, setOpen } = useActivityDisclosure({ autoExpand, hasDetails, status, onToggleDetails })
+
+ const isRunning = status === 'in_progress'
+ const body = hasDetails ? (
+ <div
+ className="flex min-w-0 flex-col gap-1 text-[length:var(--text-ui,0.8125rem)] leading-[1.625] text-foreground [&_.LemonMarkdown_p]:mb-0"
+ data-not-quill
+ >
+ {substeps.length > 0 && <ActivitySubsteps id={id} substeps={substeps} status={status} />}
+ {details}
+ </div>
+ ) : undefined
+
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <ThreadMarker
+ icon={status === 'failed' && failedIcon ? failedIcon : icon}
+ running={isRunning && animate}
+ spinner={showProgressIcon}
+ failed={status === 'failed'}
+ body={body}
+ open={open}
+ onOpenChange={setOpen}
+ className={cn(status === 'pending' && 'opacity-40')}
+ >
+ <span className="min-w-0 truncate font-medium">{title}</span>
+ {subtitle && <span className="min-w-0 truncate">{subtitle}</span>}
+ </ThreadMarker>
+ {/* Product widgets (charts, tables, diffs) keep PostHog's own colours inside the quill thread. */}
+ {children && (
+ <div className="min-w-0 ps-5" data-not-quill>
+ {children}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx b/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx
new file mode 100644
index 000000000000..ce9ee50c7ab7
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx
@@ -0,0 +1,80 @@
+import { IconWrench } from '@posthog/icons'
+import { Button } from '@posthog/quill-primitives'
+
+import { ActivityElapsedTime } from '../ActivityElapsedTime'
+import { ActivityGroupRows } from '../ActivityGroupRows'
+import { type ActivityGroupProps, useActivityGroup } from '../useActivityGroup'
+import { ThreadMarker } from './ThreadMarker'
+
+export function QuillActivityGroup(props: ActivityGroupProps): JSX.Element {
+ const { group, toolInvocations, active, waitingForInput = false, renderItem } = props
+ const {
+ label,
+ currentLabel,
+ calls,
+ thoughtsOnly,
+ expanded,
+ setExpanded,
+ window,
+ showMiddle,
+ toggleMiddle,
+ visibleThoughtsOnly,
+ newCount,
+ showNew,
+ } = useActivityGroup(props)
+ const rowProps = { thoughtsOnly: visibleThoughtsOnly, toolInvocations, active, renderItem }
+ const running = active && !waitingForInput
+
+ return (
+ <ThreadMarker
+ icon={<IconWrench />}
+ running={running}
+ spinner
+ open={expanded}
+ onOpenChange={setExpanded}
+ body={
+ <div className="flex min-w-0 flex-col gap-1" data-attr="thread-activity-group">
+ <ActivityGroupRows items={window.first} fold={false} {...rowProps} />
+ {window.hiddenCount > 0 && (
+ <Button
+ variant="link-muted"
+ size="xs"
+ className="self-start"
+ data-attr="thread-activity-more"
+ aria-expanded={showMiddle}
+ onClick={toggleMiddle}
+ >
+ {showMiddle ? 'Show less' : `Show ${window.hiddenCount} more`}
+ </Button>
+ )}
+ <ActivityGroupRows items={window.middle} fold {...rowProps} />
+ <ActivityGroupRows items={window.last} fold={false} {...rowProps} />
+ {newCount > 0 && (
+ <Button
+ variant="link-muted"
+ size="xs"
+ className="self-start"
+ data-attr="thread-activity-refresh"
+ onClick={showNew}
+ >
+ Show {newCount} new {newCount === 1 ? 'activity' : 'activities'}
+ </Button>
+ )}
+ </div>
+ }
+ >
+ <span className="shrink-0 font-medium" data-attr="thread-activity-toggle">
+ {running && !thoughtsOnly ? currentLabel : label}
+ </span>
+ {waitingForInput && <span className="truncate">Review the request below</span>}
+ {!waitingForInput && (
+ <ActivityElapsedTime startedAt={group.startedAt} endedAt={group.endedAt} active={active} />
+ )}
+ {calls.length > 0 && (
+ <span className="shrink-0 tabular-nums">
+ · {calls.length} tool {calls.length === 1 ? 'call' : 'calls'}
+ </span>
+ )}
+ </ThreadMarker>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillComposerAttachButton.tsx b/products/posthog_ai/frontend/components/quill/QuillComposerAttachButton.tsx
new file mode 100644
index 000000000000..b0f568567dab
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillComposerAttachButton.tsx
@@ -0,0 +1,49 @@
+import type { RefObject } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill-primitives'
+
+import { useComposerFilePicker } from '../composer/useComposerFilePicker'
+
+export interface QuillComposerAttachButtonProps {
+ attachmentsKey: string
+ dropTargetRef?: RefObject<HTMLElement>
+ disabledReason?: string
+}
+
+export function QuillComposerAttachButton({
+ attachmentsKey,
+ dropTargetRef,
+ disabledReason,
+}: QuillComposerAttachButtonProps): JSX.Element {
+ const { fileInput, openPicker, isOver, addDisabledReason } = useComposerFilePicker(
+ attachmentsKey,
+ dropTargetRef,
+ disabledReason
+ )
+ return (
+ <>
+ {fileInput}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label="Attach files"
+ disabled={!!addDisabledReason}
+ onClick={openPicker}
+ className={isOver ? 'ring-1 ring-ring' : undefined}
+ data-attr="posthog-ai-attach-file"
+ >
+ <IconPlus />
+ </Button>
+ }
+ />
+ <TooltipContent>
+ {addDisabledReason ?? (isOver ? 'Drop to attach' : 'Attach files for PostHog AI to read')}
+ </TooltipContent>
+ </Tooltip>
+ </>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx b/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx
new file mode 100644
index 000000000000..88f297f15dcd
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx
@@ -0,0 +1,56 @@
+import type { ReactNode, RefObject } from 'react'
+
+import { InputGroup, InputGroupAddon } from '@posthog/quill-primitives'
+
+export interface QuillComposerLayoutProps {
+ groupRef: RefObject<HTMLDivElement>
+ textAreaRef: RefObject<HTMLTextAreaElement>
+ chips: ReactNode
+ field: ReactNode
+ send: ReactNode
+ controls: ReactNode
+ meta: ReactNode
+}
+
+export function QuillComposerLayout({
+ groupRef,
+ textAreaRef,
+ chips,
+ field,
+ send,
+ controls,
+ meta,
+}: QuillComposerLayoutProps): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1">
+ <InputGroup
+ ref={groupRef}
+ onClick={(event) => {
+ if (!(event.target as HTMLElement).closest('button, a, input, textarea, [role="menu"]')) {
+ textAreaRef.current?.focus()
+ }
+ }}
+ className={
+ // The textarea is Lemon's, so quill's own focus rule, keyed to its input slot, never fires here.
+ 'h-auto cursor-text bg-[var(--card)] focus-within:border-[color-mix(in_oklab,var(--ring)_50%,transparent)] focus-within:shadow-[0_0_0_3px_color-mix(in_oklab,var(--ring)_30%,transparent)] ' +
+ '[&_[data-slot=composer-placeholder]]:top-2.5 [&_[data-slot=composer-placeholder]]:left-3.5 [&_textarea]:min-h-[37px]'
+ }
+ >
+ <InputGroupAddon align="block-start" className="flex-wrap">
+ {chips}
+ </InputGroupAddon>
+ <div className="relative w-full">
+ {field}
+ <span className="absolute right-1 bottom-1 flex items-center">{send}</span>
+ </div>
+ </InputGroup>
+ <div
+ data-quill
+ className="@container/composer flex flex-wrap items-center gap-1 px-1 text-[var(--foreground)]"
+ >
+ {controls}
+ <div className="ml-auto">{meta}</div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillComposerSendButton.tsx b/products/posthog_ai/frontend/components/quill/QuillComposerSendButton.tsx
new file mode 100644
index 000000000000..be6c1fa7372e
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillComposerSendButton.tsx
@@ -0,0 +1,48 @@
+import { forwardRef } from 'react'
+
+import { IconArrowRight, IconStopFilled } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill-primitives'
+
+import { useComposerContext } from '../composer/Composer'
+
+export const QuillComposerSendButton = forwardRef<HTMLSpanElement, { 'data-attr'?: string }>(
+ function QuillComposerSendButton({ 'data-attr': dataAttr }, ref): JSX.Element {
+ const { sendDisabledReason, loading, stopLoading, showStop, onStop } = useComposerContext()
+ const button = showStop ? (
+ <Button
+ type="button"
+ variant="destructive"
+ size="icon"
+ aria-label="Stop"
+ loading={stopLoading}
+ onClick={() => onStop?.()}
+ data-attr={dataAttr}
+ >
+ <IconStopFilled />
+ </Button>
+ ) : (
+ <Button
+ type="submit"
+ variant="primary"
+ size="icon"
+ aria-label="Send message"
+ loading={loading}
+ disabled={!!sendDisabledReason}
+ className="rounded-xs"
+ data-attr={dataAttr}
+ >
+ <IconArrowRight className="-rotate-90" />
+ </Button>
+ )
+ return (
+ <span ref={ref} className="flex">
+ <Tooltip>
+ <TooltipTrigger render={button} />
+ <TooltipContent>
+ {showStop ? (stopLoading ? 'Stopping…' : 'Stop') : (sendDisabledReason ?? 'Send message')}
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ )
+ }
+)
diff --git a/products/posthog_ai/frontend/components/quill/QuillFooterButton.tsx b/products/posthog_ai/frontend/components/quill/QuillFooterButton.tsx
new file mode 100644
index 000000000000..57e269125a72
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillFooterButton.tsx
@@ -0,0 +1,76 @@
+import { type ReactNode, useEffect, useRef, useState } from 'react'
+
+import { IconCheck, IconCopy } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill-primitives'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+/**
+ * Icon affordance for message and turn footers. Stays muted whether idle or active: the icon carries
+ * the state, so the row never lights up in a colour the thread doesn't use elsewhere.
+ */
+export function QuillFooterButton({
+ label,
+ tooltip,
+ onClick,
+ dataAttr,
+ children,
+}: {
+ label: string
+ tooltip?: string
+ onClick: () => void
+ dataAttr?: string
+ children: ReactNode
+}): JSX.Element {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <Button
+ variant="default"
+ size="icon-xs"
+ aria-label={label}
+ onClick={onClick}
+ data-attr={dataAttr}
+ className="text-muted-foreground hover:text-foreground"
+ >
+ {children}
+ </Button>
+ }
+ />
+ <TooltipContent>{tooltip ?? label}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+const COPIED_MS = 2000
+
+export function QuillCopyButton({
+ value,
+ label,
+ dataAttr,
+}: {
+ value: string
+ label: string
+ dataAttr?: string
+}): JSX.Element {
+ const [copied, setCopied] = useState(false)
+ const timer = useRef<ReturnType<typeof setTimeout>>()
+ useEffect(() => () => clearTimeout(timer.current), [])
+ return (
+ <QuillFooterButton
+ label={label}
+ tooltip={copied ? 'Copied' : label}
+ dataAttr={dataAttr}
+ onClick={() => {
+ void copyToClipboard(value, 'text', { silent: true })
+ setCopied(true)
+ clearTimeout(timer.current)
+ timer.current = setTimeout(() => setCopied(false), COPIED_MS)
+ }}
+ >
+ {copied ? <IconCheck /> : <IconCopy />}
+ </QuillFooterButton>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillMessages.tsx b/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
new file mode 100644
index 000000000000..37f233fbe126
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
@@ -0,0 +1,109 @@
+import { memo, type ReactNode, useEffect, useRef, useState } from 'react'
+
+import { IconChevronDown } from '@posthog/icons'
+import {
+ ChatBubble,
+ ChatBubbleContent,
+ ChatMessage,
+ ChatMessageContent,
+ ChatMessageFooter,
+ cn,
+} from '@posthog/quill-primitives'
+
+import { TZLabel } from 'lib/components/TZLabel'
+
+import { MarkdownMessage } from '../../messages/MarkdownMessage'
+import type { ThreadItem } from '../../types/streamTypes'
+import { ThreadAttachments } from '../ThreadAttachments'
+import { QuillCopyButton } from './QuillFooterButton'
+
+/**
+ * Clamps a user bubble to five lines with a Show more toggle. Overflow depends on wrapping width, so it
+ * is measured against the clamped height and re-measured on resize, and the toggle only appears when the
+ * content actually exceeds the clamp.
+ */
+function ClampedContent({ children }: { children: ReactNode }): JSX.Element {
+ const [expanded, setExpanded] = useState(false)
+ const [overflowing, setOverflowing] = useState(false)
+ const ref = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ const el = ref.current
+ if (expanded || !el) {
+ return
+ }
+ const observer = new ResizeObserver(() => setOverflowing(el.scrollHeight - el.clientHeight > 1))
+ observer.observe(el)
+ return () => observer.disconnect()
+ }, [expanded])
+
+ return (
+ <>
+ <div
+ ref={ref}
+ className={cn(
+ '[&_p]:my-0',
+ !expanded && 'max-h-[5lh] overflow-hidden',
+ !expanded && overflowing && '[mask-image:linear-gradient(to_bottom,black_45%,transparent)]'
+ )}
+ >
+ {children}
+ </div>
+ {overflowing && (
+ <button
+ type="button"
+ onClick={() => setExpanded(!expanded)}
+ className="mt-1 flex items-center gap-0.5 text-sm text-foreground"
+ >
+ Show {expanded ? 'less' : 'more'}
+ <IconChevronDown className={cn('size-3', expanded && 'rotate-180')} />
+ </button>
+ )}
+ </>
+ )
+}
+
+export const QuillHumanMessage = memo(function QuillHumanMessage({ item }: { item: ThreadItem }): JSX.Element {
+ const text = item.text ?? ''
+ return (
+ <ChatMessage align="end" className="group" data-attr="posthog-ai-human-message">
+ <ChatMessageContent className="gap-1">
+ {item.attachments && (
+ <div className="self-end">
+ <ThreadAttachments attachments={item.attachments} />
+ </div>
+ )}
+ <ChatBubble align="end" className="rounded-lg">
+ <ChatBubbleContent>
+ <ClampedContent>
+ <MarkdownMessage content={text || '*No text.*'} id={item.id} />
+ </ClampedContent>
+ </ChatBubbleContent>
+ </ChatBubble>
+ <ChatMessageFooter className="min-h-5 items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
+ {item.startedAt !== undefined && (
+ // A fresh dayjs object every render would defeat TZLabel's memo; a string compares by value.
+ <TZLabel time={new Date(item.startedAt).toISOString()} className="text-xs text-foreground" />
+ )}
+ {text && (
+ <QuillCopyButton value={text} label="Copy message" dataAttr="posthog-ai-human-message-copy" />
+ )}
+ </ChatMessageFooter>
+ </ChatMessageContent>
+ </ChatMessage>
+ )
+})
+
+export const QuillAssistantMessage = memo(function QuillAssistantMessage({ item }: { item: ThreadItem }): JSX.Element {
+ return (
+ <ChatMessage align="start">
+ <ChatMessageContent className="gap-1">
+ <ChatBubble variant="ghost">
+ <ChatBubbleContent>
+ <MarkdownMessage content={item.text ?? ''} id={item.id} />
+ </ChatBubbleContent>
+ </ChatBubble>
+ </ChatMessageContent>
+ </ChatMessage>
+ )
+})
diff --git a/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx b/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx
new file mode 100644
index 000000000000..122c226e5b35
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx
@@ -0,0 +1,80 @@
+import { useRef, useState } from 'react'
+
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ MenuLabel,
+} from '@posthog/quill-primitives'
+
+import { getModeOption, MODE_OPTIONS, type PermissionMode } from 'products/posthog_ai/frontend/utils/composerModes'
+import {
+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi,
+ InitialPermissionModeEnumApi,
+} from 'products/tasks/frontend/generated/api.schemas'
+
+const UNSUPERVISED_MODES: PermissionMode[] = [
+ InitialPermissionModeEnumApi.BypassPermissions,
+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess,
+]
+
+export interface QuillModePickerProps {
+ selectedMode: PermissionMode
+ onModeChange: (mode: PermissionMode) => void
+ modes: PermissionMode[]
+}
+
+export function QuillModePicker({ selectedMode, onModeChange, modes }: QuillModePickerProps): JSX.Element {
+ const [open, setOpen] = useState(false)
+ // Applied once the menu has closed, so the toolbar doesn't relayout under the closing menu.
+ const pendingModeRef = useRef<PermissionMode | null>(null)
+ const options = modes.flatMap((mode) => MODE_OPTIONS.filter((option) => option.value === mode))
+ const selectedLabel = getModeOption(selectedMode)?.label ?? 'Mode'
+ const unsupervised = UNSUPERVISED_MODES.includes(selectedMode)
+
+ return (
+ <DropdownMenu
+ open={open}
+ onOpenChange={setOpen}
+ onOpenChangeComplete={(isOpen) => {
+ if (!isOpen && pendingModeRef.current !== null) {
+ onModeChange(pendingModeRef.current)
+ pendingModeRef.current = null
+ }
+ }}
+ >
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ variant={unsupervised ? 'destructive' : 'default'}
+ size="sm"
+ aria-label="Mode"
+ title={selectedLabel}
+ >
+ <span className="@max-[400px]/composer:max-w-20 truncate">{selectedLabel}</span>
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="start" side="top" sideOffset={6} className="min-w-[200px]">
+ <MenuLabel>Mode</MenuLabel>
+ <DropdownMenuRadioGroup
+ value={selectedMode}
+ onValueChange={(value) => {
+ pendingModeRef.current = value as PermissionMode
+ setOpen(false)
+ }}
+ >
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ <span className="whitespace-nowrap">{option.label}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx
new file mode 100644
index 000000000000..c49211d2f607
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx
@@ -0,0 +1,63 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import type { ApprovalCardOption } from '../../policy/permissionUtils'
+import { QuillPermissionQuestionnaire } from './QuillPermissionQuestionnaire'
+
+const OPTIONS: ApprovalCardOption[] = [
+ {
+ optionId: 'allow',
+ label: 'Yes',
+ decision: 'approved',
+ primary: true,
+ remembered: false,
+ requiresFeedback: false,
+ supportsFeedback: false,
+ },
+ {
+ optionId: 'reject',
+ label: 'No, and tell the agent what to do differently',
+ decision: 'declined',
+ primary: false,
+ remembered: false,
+ requiresFeedback: false,
+ supportsFeedback: true,
+ },
+]
+
+describe('QuillPermissionQuestionnaire', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ test.each([
+ { answer: 'the approve choice', pick: () => fireEvent.click(screen.getByText('Yes')), expected: ['allow'] },
+ { answer: 'the plain decline', pick: () => fireEvent.click(screen.getByText('No')), expected: ['reject'] },
+ {
+ answer: 'a typed note',
+ pick: () =>
+ fireEvent.change(screen.getByLabelText('Tell the agent what to do differently'), {
+ target: { value: 'use the staging project' },
+ }),
+ expected: ['reject', 'use the staging project'],
+ },
+ ])('sends $answer on submit', ({ pick, expected }) => {
+ const onRespond = jest.fn()
+ render(
+ <QuillPermissionQuestionnaire
+ headline="Update the task summary"
+ evidence={null}
+ options={OPTIONS}
+ responding={false}
+ onRespond={onRespond}
+ />
+ )
+
+ expect(screen.getByText('Send').closest('button')).toHaveAttribute('aria-disabled', 'true')
+ pick()
+ fireEvent.click(screen.getByText('Send'))
+
+ expect(onRespond).toHaveBeenCalledWith(...expected)
+ })
+})
diff --git a/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx
new file mode 100644
index 000000000000..83d6564d52a7
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx
@@ -0,0 +1,132 @@
+import { type ReactNode, useState } from 'react'
+
+import {
+ Button,
+ Card,
+ CardContent,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ Questionnaire,
+ QuestionnaireActions,
+ QuestionnaireChoice,
+ QuestionnaireChoiceDescription,
+ QuestionnaireChoices,
+ QuestionnaireError,
+ QuestionnaireInput,
+ QuestionnaireItem,
+ QuestionnaireSubmit,
+ QuestionnaireTitle,
+} from '@posthog/quill-primitives'
+
+import { FEEDBACK_PLACEHOLDER, optionRowLabel, optionSublabel } from '../../policy/permissionOptionCopy'
+import type { ApprovalCardOption } from '../../policy/permissionUtils'
+
+const ANSWER_NAME = 'permission'
+
+type PermissionAnswer = { kind: 'choice'; optionId: string } | { kind: 'note'; text: string }
+
+export interface QuillPermissionQuestionnaireProps {
+ headline: ReactNode
+ evidence: ReactNode
+ options: ApprovalCardOption[]
+ responding: boolean
+ onRespond: (optionId: string, customInput?: string) => void
+}
+
+/**
+ * The note row answers a decline that relays feedback, so that decline's own choice only has to say "No".
+ * Without that split the choice and the note row both read as "tell the agent what to do differently".
+ */
+function choiceCopy(option: ApprovalCardOption): { label: string; description: string | null } {
+ if (option.supportsFeedback) {
+ return { label: 'No', description: 'Stops this turn.' }
+ }
+ return { label: optionRowLabel(option), description: optionSublabel(option) }
+}
+
+export function QuillPermissionQuestionnaire({
+ headline,
+ evidence,
+ options,
+ responding,
+ onRespond,
+}: QuillPermissionQuestionnaireProps): JSX.Element {
+ const [answer, setAnswer] = useState<PermissionAnswer | null>(null)
+ const feedbackOption = options.find((option) => option.requiresFeedback || option.supportsFeedback)
+ const choiceOptions = options.filter((option) => !option.requiresFeedback)
+
+ return (
+ <Card size="sm">
+ <CardHeader>
+ <CardTitle>{headline}</CardTitle>
+ </CardHeader>
+ {/* `contents` keeps the card's content and footer in the card's own layout while the form still wraps the submit. */}
+ <Questionnaire
+ className="contents"
+ items={[{ name: ANSWER_NAME, required: true }]}
+ shortcuts="numbers"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (responding || !answer) {
+ return
+ }
+ if (answer.kind === 'choice') {
+ onRespond(answer.optionId)
+ } else if (feedbackOption) {
+ onRespond(feedbackOption.optionId, answer.text)
+ }
+ }}
+ >
+ <CardContent className="flex flex-col gap-3">
+ {evidence}
+ <QuestionnaireItem name={ANSWER_NAME} required>
+ <QuestionnaireTitle className="sr-only">Allow this?</QuestionnaireTitle>
+ <QuestionnaireChoices>
+ {choiceOptions.map((option) => {
+ const { label, description } = choiceCopy(option)
+ return (
+ <QuestionnaireChoice
+ key={option.optionId}
+ value={option.optionId}
+ onChange={(event) =>
+ event.target.checked &&
+ setAnswer({ kind: 'choice', optionId: option.optionId })
+ }
+ >
+ {label}
+ {description && (
+ <QuestionnaireChoiceDescription>
+ {description}
+ </QuestionnaireChoiceDescription>
+ )}
+ </QuestionnaireChoice>
+ )
+ })}
+ {feedbackOption && (
+ <QuestionnaireInput
+ aria-label={FEEDBACK_PLACEHOLDER}
+ placeholder={FEEDBACK_PLACEHOLDER}
+ onChange={(event) => {
+ const text = event.target.value.trim()
+ setAnswer((current) =>
+ text ? { kind: 'note', text } : current?.kind === 'note' ? null : current
+ )
+ }}
+ />
+ )}
+ </QuestionnaireChoices>
+ <QuestionnaireError />
+ </QuestionnaireItem>
+ </CardContent>
+ <CardFooter>
+ <QuestionnaireActions className="w-full">
+ <QuestionnaireSubmit render={<Button variant="primary" loading={responding} />}>
+ Send
+ </QuestionnaireSubmit>
+ </QuestionnaireActions>
+ </CardFooter>
+ </Questionnaire>
+ </Card>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx b/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx
new file mode 100644
index 000000000000..ef4e1fe1ad5c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx
@@ -0,0 +1,21 @@
+import { IconExternal, IconPullRequest } from '@posthog/icons'
+import { Button, ChatMarkerValue } from '@posthog/quill-primitives'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import { ThreadMarker } from './ThreadMarker'
+
+export function QuillPullRequestRow({ prUrl, branch }: { prUrl: string; branch?: string }): JSX.Element {
+ return (
+ <div className="flex items-center gap-2" data-attr="max-sandbox-pr-card">
+ <ThreadMarker icon={<IconPullRequest />} className="opacity-100">
+ <span className="font-medium">Pull request opened</span>
+ {branch && <ChatMarkerValue className="font-mono">{branch}</ChatMarkerValue>}
+ </ThreadMarker>
+ <Button variant="outline" size="xs" render={<LinkPrimitive to={prUrl} target="_blank" />}>
+ Open on GitHub
+ <IconExternal />
+ </Button>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillRunAlertCard.tsx b/products/posthog_ai/frontend/components/quill/QuillRunAlertCard.tsx
new file mode 100644
index 000000000000..510a9c7ef08c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillRunAlertCard.tsx
@@ -0,0 +1,63 @@
+import { IconCopy, IconWarning } from '@posthog/icons'
+import { Button, Card, CardContent, CardFooter, CardHeader, CardTitle } from '@posthog/quill-primitives'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import { MarkdownMessage } from '../../messages/MarkdownMessage'
+import type { RunAlertKind } from '../../types/streamTypes'
+import { RUN_ALERT_TITLES } from '../runAlertTitles'
+import { QuillFooterButton } from './QuillFooterButton'
+
+export interface QuillRunAlertCardProps {
+ kind: RunAlertKind
+ id: string
+ message?: string
+ retryable?: boolean
+ onRetry?: () => void
+ undeliveredMessage?: boolean
+ copyDetails?: string
+}
+
+export function QuillRunAlertCard({
+ kind,
+ id,
+ message,
+ retryable,
+ onRetry,
+ undeliveredMessage,
+ copyDetails,
+}: QuillRunAlertCardProps): JSX.Element {
+ const canRetry = kind === 'connection_failed' && retryable && onRetry
+ return (
+ <Card size="sm" className="max-w-4/5" data-attr="run-alert-card">
+ <CardHeader className="flex-row items-center gap-2">
+ <IconWarning className="size-4 shrink-0 text-destructive-foreground" />
+ <CardTitle className="grow">{RUN_ALERT_TITLES[kind]}</CardTitle>
+ {copyDetails && (
+ <QuillFooterButton
+ label="Copy run details for support"
+ dataAttr="run-error-copy-details"
+ onClick={() => void copyToClipboard(copyDetails, 'run details')}
+ >
+ <IconCopy />
+ </QuillFooterButton>
+ )}
+ </CardHeader>
+ {(message || undeliveredMessage) && (
+ <CardContent className="flex min-w-0 flex-col gap-1 break-words text-foreground">
+ {message && <MarkdownMessage content={message} id={`${id}-message`} />}
+ {undeliveredMessage && kind !== 'message_undelivered' && (
+ <div>Your last message was not delivered.</div>
+ )}
+ </CardContent>
+ )}
+ {canRetry && (
+ <CardFooter>
+ <Button variant="outline" size="sm" onClick={onRetry} data-attr="agent-stream-retry">
+ Retry
+ </Button>
+ </CardFooter>
+ )}
+ </Card>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillRunSurfaceInputs.tsx b/products/posthog_ai/frontend/components/quill/QuillRunSurfaceInputs.tsx
new file mode 100644
index 000000000000..7971dcbee960
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillRunSurfaceInputs.tsx
@@ -0,0 +1,53 @@
+import { type ReactNode, useState } from 'react'
+
+import { useElementHeight } from '../../hooks/useElementHeight'
+
+const COLUMN_CLASS = 'pointer-events-auto mx-auto w-full max-w-180 px-4'
+
+export interface QuillRunSurfaceInputsProps {
+ approval: ReactNode
+ showApproval: boolean
+ composer: ReactNode
+ height: number
+ onHeightChange: (height: number) => void
+}
+
+/**
+ * The quill skin of the run surface's input region. It floats over the thread's bottom edge: messages fade
+ * out in the strip above the inputs and stay hidden behind them. The fade lets clicks through to the
+ * thread; only the inputs take them.
+ */
+export function QuillRunSurfaceInputs({
+ approval,
+ showApproval,
+ composer,
+ height,
+ onHeightChange,
+}: QuillRunSurfaceInputsProps): JSX.Element {
+ const [node, setNode] = useState<HTMLDivElement | null>(null)
+ useElementHeight(node, onHeightChange)
+ return (
+ // `data-not-quill` keeps `--color-bg-primary` the page background, which a quill ancestor rebinds to its brand color.
+ <div
+ ref={setNode}
+ data-not-quill
+ className="pointer-events-none relative z-10 pt-6 bg-[linear-gradient(to_bottom,transparent,var(--color-bg-primary)_1.5rem)]"
+ style={{ marginTop: -height }}
+ >
+ {approval && (
+ <div hidden={!showApproval} className="pb-4" data-attr="run-approval">
+ <div className={COLUMN_CLASS}>{approval}</div>
+ </div>
+ )}
+ {composer && (
+ <div
+ hidden={showApproval}
+ data-attr="composer"
+ className="pb-[calc(1rem_+_env(safe-area-inset-bottom))]"
+ >
+ <div className={COLUMN_CLASS}>{composer}</div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx b/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx
new file mode 100644
index 000000000000..4de0b0d4e6ee
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx
@@ -0,0 +1,147 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+import { useEffect } from 'react'
+
+import { runStreamLogic } from '../../logics/runStreamLogic'
+import type { StoredLogEntry } from '../../types/wireTypes'
+import type { TurnTrailer } from '../../utils/turnTrailers'
+import { ThreadView } from '../ThreadView'
+import { TurnFeedbackActions } from '../TurnFeedbackActions'
+
+function notification(timestamp: string, method: string, params: Record<string, unknown>): StoredLogEntry {
+ return { type: 'notification', timestamp, notification: { method, params } }
+}
+
+function update(timestamp: string, sessionUpdate: Record<string, unknown>): StoredLogEntry {
+ return notification(timestamp, 'session/update', { update: sessionUpdate })
+}
+
+function toolCall(
+ timestamp: string,
+ id: string,
+ toolName: string,
+ title: string,
+ rawInput: Record<string, unknown>
+): StoredLogEntry {
+ return update(timestamp, {
+ sessionUpdate: 'tool_call',
+ toolCallId: id,
+ title,
+ status: 'in_progress',
+ rawInput,
+ _meta: { claudeCode: { toolName } },
+ })
+}
+
+function toolResult(timestamp: string, id: string, status: string, text: string): StoredLogEntry {
+ return update(timestamp, {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: id,
+ status,
+ content: [{ type: 'content', content: { type: 'text', text } }],
+ })
+}
+
+const COMPLETED_TURN: StoredLogEntry[] = [
+ update('2024-03-11T14:02:10Z', {
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Why did signups drop last week? Check the funnel and the recent deploys.' },
+ }),
+ update('2024-03-11T14:02:12Z', {
+ sessionUpdate: 'agent_thought_chunk',
+ content: { type: 'text', text: 'Start with the signup funnel, then compare it with the deploy log.' },
+ }),
+ toolCall('2024-03-11T14:02:13Z', 'read-funnel', 'Read', 'Read signup_funnel.sql', {
+ file_path: 'queries/signup_funnel.sql',
+ }),
+ toolResult('2024-03-11T14:02:14Z', 'read-funnel', 'completed', 'SELECT step, count() FROM funnel GROUP BY step'),
+ toolCall('2024-03-11T14:02:15Z', 'grep-deploys', 'Grep', 'Search deploy log', { pattern: 'signup' }),
+ toolResult('2024-03-11T14:02:16Z', 'grep-deploys', 'completed', 'deploys.log:42: signup form validation changed'),
+ toolCall('2024-03-11T14:02:17Z', 'run-tests', 'Bash', 'Run signup tests', { command: 'pnpm test signup' }),
+ toolResult('2024-03-11T14:02:19Z', 'run-tests', 'failed', '1 test failed: email validation rejects plus signs'),
+ update('2024-03-11T14:02:21Z', {
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'answer',
+ content: {
+ type: 'text',
+ text: 'Signups dropped **18%** after the deploy on Tuesday.\n\nThe new email validation rejects addresses with a `+`, so those users never reach the second funnel step.',
+ },
+ }),
+ notification('2024-03-11T14:02:22Z', '_posthog/turn_complete', {}),
+]
+
+const STREAMING_TURN: StoredLogEntry[] = [
+ ...COMPLETED_TURN,
+ update('2024-03-11T14:03:00Z', {
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Can you fix the validation?' },
+ }),
+ toolCall('2024-03-11T14:03:02Z', 'read-validator', 'Read', 'Read emailValidator.ts', {
+ file_path: 'src/emailValidator.ts',
+ }),
+]
+
+function renderTrailer(trailer: TurnTrailer): JSX.Element {
+ return (
+ <TurnFeedbackActions
+ sessionId="example-task"
+ turnIndex={trailer.turnIndex}
+ run={{ taskId: 'example-task' }}
+ turnText={trailer.turnText}
+ timestamp={trailer.timestamp}
+ />
+ )
+}
+
+interface FixtureProps {
+ streamKey: string
+ entries: StoredLogEntry[]
+ skin: 'quill' | 'lemon' | 'both'
+}
+
+function Fixture({ streamKey, entries, skin }: FixtureProps): JSX.Element {
+ useEffect(() => {
+ const logic = runStreamLogic({ streamKey })
+ const unmount = logic.mount()
+ // Strict mode reruns this effect; ingest once.
+ if (logic.values.threadItems.length === 0) {
+ for (const entry of entries) {
+ logic.actions.ingestAcpFrame(entry, 'replay')
+ }
+ }
+ return unmount
+ }, [streamKey, entries])
+ return (
+ <BindLogic logic={runStreamLogic} props={{ streamKey }}>
+ <div className="flex gap-4">
+ {skin !== 'lemon' && (
+ <div className="h-160 w-180 max-w-full rounded border p-4">
+ <ThreadView skin="quill" renderTurnTrailer={renderTrailer} />
+ </div>
+ )}
+ {skin !== 'quill' && (
+ <div className="h-160 w-180 max-w-full rounded border p-4">
+ <ThreadView renderTurnTrailer={renderTrailer} />
+ </div>
+ )}
+ </div>
+ </BindLogic>
+ )
+}
+
+const meta: Meta<FixtureProps> = {
+ title: 'Products/PostHog AI/ThreadView/Quill',
+ parameters: { mockDate: '2024-03-11T14:05:00Z' },
+ args: { streamKey: 'example-quill-completed', entries: COMPLETED_TURN, skin: 'quill' },
+ render: (props) => <Fixture {...props} />,
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const CompletedTurn: Story = {}
+export const StreamingTurn: Story = { args: { streamKey: 'example-quill-streaming', entries: STREAMING_TURN } }
+export const ComparedWithLemon: Story = {
+ args: { streamKey: 'example-quill-compare', skin: 'both' },
+ parameters: { testOptions: { skip: true } },
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
new file mode 100644
index 000000000000..c0d2e5ecb353
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
@@ -0,0 +1,103 @@
+import { useContext } from 'react'
+
+import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'
+import { Button, ChatMessageFooter, Input, Text, cn } from '@posthog/quill-primitives'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { stripMarkdown } from 'lib/utils/markdown'
+
+import type { TurnFeedbackActionsProps } from '../turnFeedbackTypes'
+import { TurnRevealContext } from '../TurnRevealContext'
+import { useTurnRating } from '../useTurnRating'
+import { QuillCopyButton, QuillFooterButton } from './QuillFooterButton'
+
+export function QuillTurnFeedbackActions({
+ sessionId,
+ turnIndex,
+ run,
+ traceId,
+ turnText,
+ timestamp,
+}: TurnFeedbackActionsProps): JSX.Element {
+ const turnHovered = useContext(TurnRevealContext)
+ const { rating, submitRating, feedback, setFeedback, feedbackInputStatus, closeFeedback, submitFeedback } =
+ useTurnRating({ sessionId, turnIndex, run, traceId })
+
+ return (
+ <div className="flex flex-col gap-2">
+ <ChatMessageFooter
+ className={cn(
+ 'min-h-5 items-center gap-1 ps-0 transition-opacity focus-within:opacity-100',
+ rating || turnHovered ? 'opacity-100' : 'opacity-0'
+ )}
+ >
+ {timestamp !== undefined && (
+ <TZLabel time={new Date(timestamp).toISOString()} className="text-xs text-foreground" />
+ )}
+ {turnText && (
+ <QuillCopyButton
+ value={stripMarkdown(turnText)}
+ label="Copy answer"
+ dataAttr="posthog-ai-turn-copy"
+ />
+ )}
+ {rating !== 'bad' && (
+ <QuillFooterButton
+ label="Good answer"
+ dataAttr="posthog-ai-turn-rating-good"
+ onClick={() => submitRating('good')}
+ >
+ {rating === 'good' ? <IconThumbsUpFilled /> : <IconThumbsUp />}
+ </QuillFooterButton>
+ )}
+ {rating !== 'good' && (
+ <QuillFooterButton
+ label="Bad answer"
+ dataAttr="posthog-ai-turn-rating-bad"
+ onClick={() => submitRating('bad')}
+ >
+ {rating === 'bad' ? <IconThumbsDownFilled /> : <IconThumbsDown />}
+ </QuillFooterButton>
+ )}
+ </ChatMessageFooter>
+ {feedbackInputStatus !== 'hidden' && (
+ <div className="flex max-w-4/5 flex-col gap-2 rounded-lg border border-border p-3">
+ <div className="flex items-center gap-1">
+ <Text size="sm" weight="medium" className="grow">
+ {feedbackInputStatus === 'pending'
+ ? 'What disappointed you about the answer?'
+ : 'Thank you for your feedback!'}
+ </Text>
+ <QuillFooterButton label="Close" onClick={closeFeedback}>
+ <IconX />
+ </QuillFooterButton>
+ </div>
+ {feedbackInputStatus === 'pending' && (
+ <form
+ className="flex items-center gap-1.5"
+ onSubmit={(event) => {
+ event.preventDefault()
+ submitFeedback()
+ }}
+ >
+ <Input
+ placeholder="Help us improve PostHog AI…"
+ value={feedback}
+ onChange={(event) => setFeedback(event.target.value)}
+ autoFocus
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ data-attr="posthog-ai-turn-feedback-submit"
+ disabled={!feedback}
+ >
+ Submit
+ </Button>
+ </form>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx b/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx
new file mode 100644
index 000000000000..8755d8225a24
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx
@@ -0,0 +1,65 @@
+import type { ReactNode } from 'react'
+
+import { ChatMarker, ChatMarkerContent, ChatMarkerIcon, Spinner, cn } from '@posthog/quill-primitives'
+
+/**
+ * The row chrome every quill thread row shares. Quill's interactive row bleeds its hit area past the
+ * text column, fills on hover and draws an outset focus ring; a transcript is mostly these rows, so they
+ * stay flush with the column. Rows read in the thread's text color, not quill's muted row color.
+ */
+const QUILL_THREAD_ROW_CLASS = cn(
+ 'mx-0 px-0 text-foreground hover:bg-transparent focus-visible:bg-transparent',
+ 'data-panel-open:bg-transparent',
+ '[&_[data-slot=marker-panel]]:pt-2 [&_[data-slot=marker-panel]]:pb-1',
+ // Quill parks the chevron at the row's far end, which strands it from the text it opens.
+ '[&>svg:last-child]:ms-0',
+ 'focus-visible:shadow-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring'
+)
+
+export interface ThreadMarkerProps {
+ icon?: ReactNode
+ running?: boolean
+ spinner?: boolean
+ failed?: boolean
+ body?: ReactNode
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
+ className?: string
+ children: ReactNode
+}
+
+export function ThreadMarker({
+ icon,
+ running = false,
+ spinner = false,
+ failed = false,
+ body,
+ open,
+ onOpenChange,
+ className,
+ children,
+}: ThreadMarkerProps): JSX.Element {
+ return (
+ <ChatMarker
+ status={failed ? 'error' : running ? 'running' : undefined}
+ body={body}
+ open={open}
+ onOpenChange={onOpenChange}
+ className={cn(
+ QUILL_THREAD_ROW_CLASS,
+ // A fainter base under the full-foreground sweep, so a live row reads as moving at a glance.
+ running && '[--quill-shimmer-base:color-mix(in_oklab,var(--muted-foreground)_70%,transparent)]',
+ className
+ )}
+ >
+ {(icon || (running && spinner)) && (
+ <ChatMarkerIcon className="flex items-center justify-center">
+ {running && spinner ? <Spinner /> : icon}
+ </ChatMarkerIcon>
+ )}
+ <ChatMarkerContent className="flex min-w-0 flex-nowrap items-center gap-1.5 overflow-hidden">
+ {children}
+ </ChatMarkerContent>
+ </ChatMarker>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/quillThreadContext.ts b/products/posthog_ai/frontend/components/quill/quillThreadContext.ts
new file mode 100644
index 000000000000..a07fc7804b7e
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/quillThreadContext.ts
@@ -0,0 +1,15 @@
+import { createContext, useContext } from 'react'
+
+export type ThreadSkin = 'lemon' | 'quill'
+
+/**
+ * The skin of the thread a presenter renders in, set by `ThreadView`'s `skin` prop. Shared presenters
+ * (`Activity`, `ThreadRow`, `ThreadActivityGroup`, `RunAlertActivity`, `PullRequestCard`,
+ * `TurnFeedbackActions`) read it to pick their quill skin, so the tool registry's renderers and a
+ * consumer's turn trailers never need to know which thread hosts them.
+ */
+export const ThreadSkinContext = createContext<ThreadSkin>('lemon')
+
+export function useQuillThread(): boolean {
+ return useContext(ThreadSkinContext) === 'quill'
+}
diff --git a/products/posthog_ai/frontend/components/runAlertTitles.ts b/products/posthog_ai/frontend/components/runAlertTitles.ts
new file mode 100644
index 000000000000..f7534a133fec
--- /dev/null
+++ b/products/posthog_ai/frontend/components/runAlertTitles.ts
@@ -0,0 +1,10 @@
+import type { RunAlertKind } from '../types/streamTypes'
+
+export const RUN_ALERT_TITLES: Record<RunAlertKind, string> = {
+ reconnecting: 'Restoring conversation',
+ connection_failed: 'Connection lost',
+ agent_error: 'Run stopped',
+ agent_error_continued: 'Agent error',
+ agent_crash: 'Agent stopped unexpectedly',
+ message_undelivered: 'Message not delivered',
+}
diff --git a/products/posthog_ai/frontend/components/tool/ToolActivity.tsx b/products/posthog_ai/frontend/components/tool/ToolActivity.tsx
index f90a1bf070d6..2bf790b3491b 100644
--- a/products/posthog_ai/frontend/components/tool/ToolActivity.tsx
+++ b/products/posthog_ai/frontend/components/tool/ToolActivity.tsx
@@ -5,7 +5,7 @@ import { IconWarning, IconWrench } from '@posthog/icons'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
import { Activity } from '../ActivityPrimitives'
-import type { ActivityStatus } from '../ActivityPrimitives'
+import type { ActivityStatus } from '../activityTypes'
import { VirtualizedThread } from '../VirtualizedThread'
import { resolveToolCallStatus } from './toolContentUtils'
diff --git a/products/posthog_ai/frontend/components/turnFeedbackTypes.ts b/products/posthog_ai/frontend/components/turnFeedbackTypes.ts
new file mode 100644
index 000000000000..80131e143bca
--- /dev/null
+++ b/products/posthog_ai/frontend/components/turnFeedbackTypes.ts
@@ -0,0 +1,17 @@
+import type { RunRef } from '../utils/feedbackEvents'
+
+export interface TurnRatingTarget {
+ /** Task id backing the sandbox conversation. Lands in `$ai_session_id`. */
+ sessionId: string
+ /** Ordinal of the completed turn — the rating's identity, stable across reloads. */
+ turnIndex: number
+ run: RunRef
+ /** The turn's gateway trace id, when the run reported one. Lands in `$ai_trace_id`. */
+ traceId?: string
+}
+
+export interface TurnFeedbackActionsProps extends TurnRatingTarget {
+ turnText: string
+ /** When the turn completed, in milliseconds. */
+ timestamp?: number
+}
diff --git a/products/posthog_ai/frontend/components/useActivityDisclosure.ts b/products/posthog_ai/frontend/components/useActivityDisclosure.ts
new file mode 100644
index 000000000000..8d1936c122e4
--- /dev/null
+++ b/products/posthog_ai/frontend/components/useActivityDisclosure.ts
@@ -0,0 +1,32 @@
+import { useLayoutEffect, useState } from 'react'
+
+import type { ActivityStatus } from './activityTypes'
+
+/**
+ * Open state for an activity's details, shared by every skin. With `autoExpand`, details open while the
+ * step runs and close once it settles; a reader's toggle holds until the status changes that rule.
+ */
+export function useActivityDisclosure({
+ autoExpand,
+ hasDetails,
+ status,
+ onToggleDetails,
+}: {
+ autoExpand: boolean
+ hasDetails: boolean
+ status: ActivityStatus
+ onToggleDetails?: (expanded: boolean) => void
+}): { open: boolean; setOpen: (open: boolean) => void } {
+ const shouldExpand = autoExpand && hasDetails && status !== 'completed' && status !== 'failed'
+ const [open, setOpenState] = useState(shouldExpand)
+ useLayoutEffect(() => {
+ setOpenState(shouldExpand)
+ }, [shouldExpand])
+ return {
+ open,
+ setOpen: (next) => {
+ onToggleDetails?.(next)
+ setOpenState(next)
+ },
+ }
+}
diff --git a/products/posthog_ai/frontend/components/useActivityGroup.ts b/products/posthog_ai/frontend/components/useActivityGroup.ts
new file mode 100644
index 000000000000..fd20dc670fd4
--- /dev/null
+++ b/products/posthog_ai/frontend/components/useActivityGroup.ts
@@ -0,0 +1,122 @@
+import { type ReactNode, useEffect, useState } from 'react'
+
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+import { type ThreadActivityGroup, activityWindow } from '../utils/groupThreadActivity'
+import { resolveToolCall } from '../utils/toolResolver'
+import { lookupToolRenderer } from './tool/toolRegistry'
+import { VirtualizedThread } from './VirtualizedThread'
+
+function groupLabel({
+ active,
+ cancelled,
+ waitingForInput,
+ thoughtsOnly,
+}: {
+ active: boolean
+ cancelled: boolean
+ waitingForInput: boolean
+ thoughtsOnly: boolean
+}): string {
+ if (waitingForInput) {
+ return 'Waiting for you'
+ }
+ if (active) {
+ return thoughtsOnly ? 'Thinking' : 'Working'
+ }
+ if (cancelled) {
+ return 'Stopped'
+ }
+ return thoughtsOnly ? 'Thought' : 'Worked'
+}
+
+export interface ActivityGroupProps {
+ group: ThreadActivityGroup
+ toolInvocations: Map<string, ToolInvocation>
+ active: boolean
+ cancelled: boolean
+ waitingForInput?: boolean
+ renderItem: (item: ThreadItem) => ReactNode
+}
+
+/**
+ * Everything an activity group shows, for every skin: its label, the tool calls, and the rows to list
+ * when open. An open group freezes its rows while the reader is scrolled away from the bottom, so rows
+ * never insert above what they are reading; `newCount` counts what arrived since, and `showNew` lets it in.
+ */
+export function useActivityGroup({
+ group,
+ toolInvocations,
+ active,
+ cancelled,
+ waitingForInput = false,
+}: ActivityGroupProps): {
+ label: string
+ currentLabel: string
+ calls: ToolInvocation[]
+ thoughtsOnly: boolean
+ expanded: boolean
+ setExpanded: (expanded: boolean) => void
+ window: ReturnType<typeof activityWindow<ThreadItem>>
+ showMiddle: boolean
+ toggleMiddle: () => void
+ visibleThoughtsOnly: boolean
+ newCount: number
+ showNew: () => void
+} {
+ const pauseFollowing = VirtualizedThread.usePauseFollowing()
+ const isFollowing = VirtualizedThread.useIsFollowing()
+ const [expanded, setExpandedState] = useState(false)
+ const [visibleIds, setVisibleIds] = useState<string[]>([])
+ const [showMiddle, setShowMiddle] = useState(false)
+ useEffect(() => {
+ if (expanded && isFollowing) {
+ setVisibleIds((previous) =>
+ previous.length === group.items.length && previous.every((id, index) => id === group.items[index].id)
+ ? previous
+ : group.items.map((item) => item.id)
+ )
+ }
+ }, [expanded, isFollowing, group.items])
+
+ const calls = group.items.flatMap((item) => {
+ const call = item.toolCallId ? toolInvocations.get(item.toolCallId) : undefined
+ return call ? [call] : []
+ })
+ const thoughtsOnly = group.items.every((item) => item.type === 'assistant_thought')
+ const label = groupLabel({ active, cancelled, waitingForInput, thoughtsOnly })
+ const current = active
+ ? calls.findLast((call) => call.status === 'in_progress' || call.status === 'pending')
+ : undefined
+ const resolved = current ? resolveToolCall(current) : undefined
+ const currentLabel =
+ current && resolved
+ ? current.title || lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName).displayName
+ : 'Thinking…'
+
+ const visible = new Set(visibleIds)
+ const snapshot = isFollowing ? group.items : group.items.filter((item) => visible.has(item.id))
+ const allIds = (): string[] => group.items.map((item) => item.id)
+
+ return {
+ label,
+ currentLabel,
+ calls,
+ thoughtsOnly,
+ expanded,
+ setExpanded: (next) => {
+ if (next && !expanded) {
+ setVisibleIds(allIds())
+ }
+ setExpandedState(next)
+ },
+ window: activityWindow(snapshot, showMiddle),
+ showMiddle,
+ toggleMiddle: () => {
+ pauseFollowing()
+ setShowMiddle(!showMiddle)
+ },
+ visibleThoughtsOnly: snapshot.every((item) => item.type === 'assistant_thought'),
+ newCount: isFollowing ? 0 : group.items.filter((item) => !visible.has(item.id)).length,
+ showNew: () => setVisibleIds(allIds()),
+ }
+}
diff --git a/products/posthog_ai/frontend/components/useTurnRating.ts b/products/posthog_ai/frontend/components/useTurnRating.ts
new file mode 100644
index 000000000000..a0af5b3a655a
--- /dev/null
+++ b/products/posthog_ai/frontend/components/useTurnRating.ts
@@ -0,0 +1,50 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { type MessageRatingOrNull, messageRatingsLogic } from '../logics/messageRatingsLogic'
+import { captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'
+import type { TurnRatingTarget } from './turnFeedbackTypes'
+
+export type TurnFeedbackInputStatus = 'hidden' | 'pending' | 'submitted'
+
+export function useTurnRating({ sessionId, turnIndex, run, traceId }: TurnRatingTarget): {
+ rating: MessageRatingOrNull
+ submitRating: (rating: 'good' | 'bad') => void
+ feedback: string
+ setFeedback: (feedback: string) => void
+ feedbackInputStatus: TurnFeedbackInputStatus
+ closeFeedback: () => void
+ submitFeedback: () => void
+} {
+ const { ratingForKey } = useValues(messageRatingsLogic)
+ const { setRating } = useActions(messageRatingsLogic)
+ const ratingKey = `${sessionId}:turn-${turnIndex}`
+ const rating = ratingForKey(ratingKey)
+ const [feedback, setFeedback] = useState<string>('')
+ const [feedbackInputStatus, setFeedbackInputStatus] = useState<TurnFeedbackInputStatus>('hidden')
+
+ return {
+ rating,
+ submitRating: (newRating) => {
+ if (rating) {
+ return // Already rated
+ }
+ setRating({ key: ratingKey, rating: newRating })
+ captureTurnRating(sessionId, traceId ?? null, newRating, turnIndex, run)
+ if (newRating === 'bad') {
+ setFeedbackInputStatus('pending')
+ }
+ },
+ feedback,
+ setFeedback,
+ feedbackInputStatus,
+ closeFeedback: () => setFeedbackInputStatus('hidden'),
+ submitFeedback: () => {
+ if (!feedback) {
+ return // Input is empty
+ }
+ captureTurnFeedbackText(sessionId, traceId ?? null, feedback, turnIndex, run)
+ setFeedbackInputStatus('submitted')
+ },
+ }
+}
diff --git a/products/posthog_ai/frontend/hooks/useElementHeight.ts b/products/posthog_ai/frontend/hooks/useElementHeight.ts
new file mode 100644
index 000000000000..c85e9f6a203c
--- /dev/null
+++ b/products/posthog_ai/frontend/hooks/useElementHeight.ts
@@ -0,0 +1,15 @@
+import { useEffect } from 'react'
+
+export function useElementHeight(node: HTMLElement | null, onHeight: (height: number) => void): void {
+ useEffect(() => {
+ if (!node) {
+ return
+ }
+ const observer = new ResizeObserver(() => onHeight(node.offsetHeight))
+ observer.observe(node)
+ return () => {
+ observer.disconnect()
+ onHeight(0)
+ }
+ }, [node, onHeight])
+}
diff --git a/products/posthog_ai/frontend/hooks/useThreadSkin.ts b/products/posthog_ai/frontend/hooks/useThreadSkin.ts
new file mode 100644
index 000000000000..862c9b43d8a0
--- /dev/null
+++ b/products/posthog_ai/frontend/hooks/useThreadSkin.ts
@@ -0,0 +1,13 @@
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import type { ThreadSkin } from '../components/quill/quillThreadContext'
+
+/**
+ * The skin for every PostHog AI chat surface: the thread, the run composer and its pickers. The quill chat
+ * is part of the quill web redesign, so `today-rail-nav` turns it on as well.
+ */
+export function useThreadSkin(): ThreadSkin {
+ const phaiQuill = useFeatureFlag('PHAI_QUILL')
+ const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+ return phaiQuill || todayRailNav ? 'quill' : 'lemon'
+}
diff --git a/products/posthog_ai/frontend/policy/permissionOptionCopy.ts b/products/posthog_ai/frontend/policy/permissionOptionCopy.ts
new file mode 100644
index 000000000000..430431f44915
--- /dev/null
+++ b/products/posthog_ai/frontend/policy/permissionOptionCopy.ts
@@ -0,0 +1,30 @@
+import type { ApprovalCardOption } from './permissionUtils'
+
+export const FEEDBACK_PLACEHOLDER = 'Tell the agent what to do differently'
+
+/** A decline that relays feedback is answered through its inline textarea, not a plain click. */
+export function isFeedbackOption(option: ApprovalCardOption): boolean {
+ return option.requiresFeedback || option.supportsFeedback
+}
+
+export function optionRowLabel(option: ApprovalCardOption): string {
+ // The wire's feedback option describes the interaction ("Type here to tell the agent…") instead of
+ // naming the choice; the textarea placeholder carries that instruction, the row just needs a name.
+ if (isFeedbackOption(option) && /^type here\b/i.test(option.label)) {
+ return 'Do it differently…'
+ }
+ return option.label
+}
+
+export function optionSublabel(option: ApprovalCardOption): string | null {
+ if (option.requiresFeedback) {
+ return 'The agent adjusts and continues instead of stopping this turn.'
+ }
+ if (option.supportsFeedback) {
+ return 'With a note the agent adjusts and continues. Without one, declining stops this turn.'
+ }
+ if (option.decision === 'declined') {
+ return 'Stops this turn. Send a follow-up to redirect the agent.'
+ }
+ return null
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
index 178b19a5cb4f..f13b827a1ea6 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -8,7 +8,7 @@ import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'
-import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'
+import { Composer, QueuedMessageList, useThreadSkin } from 'products/posthog_ai/frontend/api/primitives'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
import { runSlashCommandsLogic } from 'products/posthog_ai/frontend/logics/runSlashCommandsLogic'
import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
@@ -16,7 +16,10 @@ import { getRuntimeAdapterForModel, pickerModels } from 'products/posthog_ai/fro
import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/frontend/utils/composerModes'
import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
+import { AttachedContextChips } from '../../../components/composer/AttachedContextChips'
+import { AttachedContextPicker } from '../../../components/composer/AttachedContextPicker'
import { CommandResultCard } from '../../../components/composer/CommandResultCard'
+import { ComposerAttachmentChips } from '../../../components/composer/ComposerAttachmentChips'
import { ComposerAttachments, useComposerAttachmentPaste } from '../../../components/composer/ComposerAttachments'
import { ComposerCommandMenu } from '../../../components/composer/ComposerCommandMenu'
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
@@ -24,6 +27,9 @@ import { ComposerModePicker } from '../../../components/composer/ComposerModePic
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { ContextUsageChip } from '../../../components/ContextUsageChip'
+import { QuillComposerAttachButton } from '../../../components/quill/QuillComposerAttachButton'
+import { QuillComposerLayout } from '../../../components/quill/QuillComposerLayout'
+import { QuillComposerSendButton } from '../../../components/quill/QuillComposerSendButton'
export function TaskRunComposer({
logicProps,
@@ -97,7 +103,74 @@ export function TaskRunComposer({
const attachmentsKey = logicProps.interactionKey ?? logicProps.runId
const onPaste = useComposerAttachmentPaste(attachmentsKey)
// The whole input frame is the drop target, so a file dropped anywhere on it attaches.
- const frameRef = useRef<HTMLLabelElement>(null)
+ const labelRef = useRef<HTMLLabelElement>(null)
+ const groupRef = useRef<HTMLDivElement>(null)
+ const skin = useThreadSkin()
+
+ const placeholder = isTerminal
+ ? 'Send a message to start a new run, or type / for commands…'
+ : 'Send a follow-up message, or type / for commands…'
+ // Selection lives in the bound runInteractionLogic and is applied when the message is sent — synced to the
+ // running agent on a follow-up, or used to seed the next run once terminal.
+ const modePicker = (
+ <ComposerModePicker
+ selectedMode={selectedMode}
+ onModeChange={setMode}
+ modes={getModesForRuntimeAdapter(composerAdapter)}
+ />
+ )
+ const modelPicker = (
+ <ComposerModelEffortPickers
+ models={offeredModels}
+ selectedModel={selectedModel}
+ defaultModel={defaultModel}
+ isDefaultModelLoading={myConfigLoading}
+ selectedEffort={selectedEffort}
+ onModelChange={setModel}
+ onEffortChange={setEffort}
+ // While the run is live its harness is fixed to whatever the sandbox booted; once
+ // terminal the next send starts a fresh run, which may pick any harness.
+ lockedRuntimeAdapter={isTerminal ? null : logicProps.currentRuntimeAdapter}
+ onOpenDefaultSettings={() =>
+ router.actions.push(urls.settings('environment-task-agents', 'task-agent-my-preference'))
+ }
+ />
+ )
+ const field = (
+ <ComposerCommandMenu commands={slashCommands}>
+ <Composer.Field>
+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} onPaste={onPaste} />
+ </Composer.Field>
+ </ComposerCommandMenu>
+ )
+ const pickers = (first: JSX.Element, second: JSX.Element): JSX.Element => (
+ <fieldset disabled={!controlsReady} className="flex flex-wrap items-center gap-1 border-0 p-0 m-0 min-w-0">
+ {first}
+ {second}
+ </fieldset>
+ )
+ const withConsent = (sendButton: JSX.Element): JSX.Element => (
+ <AIConsentPopoverWrapper
+ placement="top-end"
+ showArrow
+ ignoreDismissal
+ hidden={!consentBlocked}
+ // A draft may be a slash command, so it resubmits through the command path rather than
+ // straight to the agent. Queue and steer have no command form and go back as they were.
+ onApprove={() => {
+ if (consentBlockedSource === 'draft') {
+ clearConsentBlock()
+ submitComposer()
+ } else {
+ submitAfterConsent()
+ }
+ }}
+ onDismiss={() => clearConsentBlock()}
+ >
+ {sendButton}
+ </AIConsentPopoverWrapper>
+ )
return (
<div onFocusCapture={() => setComposerFocused(true)} onBlurCapture={() => setComposerFocused(false)}>
@@ -158,80 +231,48 @@ export function TaskRunComposer({
/>
</Composer.Banner>
)}
- <Composer.Frame ref={frameRef}>
- <Composer.Header className="flex flex-wrap items-center gap-1">
- <AttachedContextBar />
- <ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={frameRef} />
- </Composer.Header>
- <ComposerCommandMenu commands={slashCommands}>
- <Composer.Field>
- <Composer.Placeholder>
- {isTerminal
- ? 'Send a message to start a new run, or type / for commands…'
- : 'Send a follow-up message, or type / for commands…'}
- </Composer.Placeholder>
- <Composer.Textarea
- data-attr="sandbox-composer-input"
- autoFocus={autoFocus}
- onPaste={onPaste}
- />
- </Composer.Field>
- </ComposerCommandMenu>
- <Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
- <fieldset
- disabled={!controlsReady}
- className="flex flex-wrap items-center gap-1 border-0 p-0 m-0 min-w-0"
- >
- {/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and is
- applied when the message is sent — synced to the running agent on a follow-up,
- or used to seed the next run once terminal. */}
- <ComposerModePicker
- selectedMode={selectedMode}
- onModeChange={setMode}
- modes={getModesForRuntimeAdapter(composerAdapter)}
- />
- <ComposerModelEffortPickers
- models={offeredModels}
- selectedModel={selectedModel}
- defaultModel={defaultModel}
- isDefaultModelLoading={myConfigLoading}
- selectedEffort={selectedEffort}
- onModelChange={setModel}
- onEffortChange={setEffort}
- // While the run is live its harness is fixed to whatever the sandbox booted; once
- // terminal the next send starts a fresh run, which may pick any harness.
- lockedRuntimeAdapter={isTerminal ? null : logicProps.currentRuntimeAdapter}
- onOpenDefaultSettings={() =>
- router.actions.push(
- urls.settings('environment-task-agents', 'task-agent-my-preference')
- )
- }
- />
- </fieldset>
- <div className="ml-auto">
- <ContextUsageChip />
- </div>
- </Composer.Footer>
- </Composer.Frame>
- <AIConsentPopoverWrapper
- placement="top-end"
- showArrow
- ignoreDismissal
- hidden={!consentBlocked}
- // A draft may be a slash command, so it resubmits through the command path rather than
- // straight to the agent. Queue and steer have no command form and go back as they were.
- onApprove={() => {
- if (consentBlockedSource === 'draft') {
- clearConsentBlock()
- submitComposer()
- } else {
- submitAfterConsent()
+ {skin === 'quill' ? (
+ <QuillComposerLayout
+ groupRef={groupRef}
+ textAreaRef={textAreaRef}
+ chips={
+ <>
+ <AttachedContextChips />
+ <ComposerAttachmentChips attachmentsKey={attachmentsKey} />
+ </>
}
- }}
- onDismiss={() => clearConsentBlock()}
- >
- <Composer.Submit data-attr="sandbox-composer-send" />
- </AIConsentPopoverWrapper>
+ field={field}
+ send={withConsent(<QuillComposerSendButton data-attr="sandbox-composer-send" />)}
+ controls={
+ <>
+ <QuillComposerAttachButton attachmentsKey={attachmentsKey} dropTargetRef={groupRef} />
+ {/* The picker is Lemon, so it keeps Lemon's colors inside the quill row. */}
+ <div data-not-quill className="flex">
+ <AttachedContextPicker className="flex-shrink-0" />
+ </div>
+ {pickers(modelPicker, modePicker)}
+ </>
+ }
+ meta={<ContextUsageChip />}
+ />
+ ) : (
+ <>
+ <Composer.Frame ref={labelRef}>
+ <Composer.Header className="flex flex-wrap items-center gap-1">
+ <AttachedContextBar />
+ <ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={labelRef} />
+ </Composer.Header>
+ {field}
+ <Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
+ {pickers(modePicker, modelPicker)}
+ <div className="ml-auto">
+ <ContextUsageChip />
+ </div>
+ </Composer.Footer>
+ </Composer.Frame>
+ {withConsent(<Composer.Submit data-attr="sandbox-composer-send" />)}
+ </>
+ )}
</Composer.Root>
</div>
)