:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(posthog-ai): keep context chips with their chat and link them (#125170)
Adam Leith2fd7576e0aa1
diff --git a/frontend/src/layout/ai/attachedContext.ts b/frontend/src/layout/ai/attachedContext.tsindex 48a60ba49242..eb71c7167484 100644--- a/frontend/src/layout/ai/attachedContext.ts+++ b/frontend/src/layout/ai/attachedContext.ts@@ -13,6 +13,11 @@ export interface AttachedContextItem {type: string/** Resource identifier — entity id, short_id, $ai_trace_id, … */key?: string | number+ /**+ * The id in the item's page URL, when it differs from `key` (a flag's context key is its name, and its page+ * takes the numeric id). Null means the item has no page. Undefined means `key` is the page id.+ */+ pageId?: string | number | null/** Optional human-readable label. */label?: string/**@@ -37,6 +42,9 @@ export interface AttachedContextItem {dismissGroup?: string}+/** A new chat's picks live under this key until its first send delivers them to the created task. */+export const NEW_CHAT_KEY = ''+/** Stable dedupe key for an attached context item: `${type}:${key ?? value}`. */export function attachedContextItemKey(item: AttachedContextItem): string {return `${item.type}:${item.key ?? item.value ?? ''}`diff --git a/frontend/src/layout/ai/attachedContextLogic.test.ts b/frontend/src/layout/ai/attachedContextLogic.test.tsindex 4c8bf710ed38..971f80d7e2b4 100644--- a/frontend/src/layout/ai/attachedContextLogic.test.ts+++ b/frontend/src/layout/ai/attachedContextLogic.test.ts@@ -8,6 +8,7 @@ describe('attachedContextLogic', () => {let logic: ReturnType<typeof attachedContextLogic.build>beforeEach(() => {+ window.localStorage.clear()initKeaTests()logic = attachedContextLogic()logic.mount()@@ -55,11 +56,12 @@ describe('attachedContextLogic', () => {// Sent-context keys are scoped per task: a global (unkeyed) store would prune context from the first// message of an unrelated task just because the same resource was sent from another one.- it('accumulates sent context keys per task without leaking across tasks', async () => {+ it('records delivered non-text keys per task without leaking across tasks', async () => {+ const insight = { type: 'insight', key: 'x' }await expectLogic(logic, () => {- logic.actions.markContextSent('task-a', ['insight:x'])- logic.actions.markContextSent('task-a', ['insight:x', 'dashboard:9'])- logic.actions.markContextSent('task-b', ['insight:x'])+ logic.actions.contextDelivered('task-a', [insight, { type: 'text', value: 'note' }])+ logic.actions.contextDelivered('task-a', [insight, { type: 'dashboard', key: 9 }])+ logic.actions.contextDelivered('task-b', [insight])}).toMatchValues({sentContextKeysByTask: {'task-a': ['insight:x', 'dashboard:9'],@@ -68,6 +70,50 @@ describe('attachedContextLogic', () => {})})+ it('saves references but no payload as chips, which outlive the provider and are removed per chat', async () => {+ const responses = 'private survey answer'+ const items = [+ { type: 'experiment', key: 17, label: 'Checkout' },+ { type: 'survey_open_ended_responses', value: responses, label: 'Open-ended responses' },+ { type: 'text', value: responses },+ { type: 'tool_context', value: responses, hidden: true },+ { type: 'email_template', key: 't1', label: 'Welcome', previewHtml: '<p>Hi</p>' },+ { type: 'text', key: 'note', value: responses },+ ]+ logic.actions.registerContext('scene', items)+ logic.actions.contextDelivered('task-a', items)+ logic.actions.contextDelivered('task-b', [items[0]])+ logic.actions.deregisterContext('scene')++ const chips = logic.values.chatChipsByTask['task-a']+ expect(chips.map((chip) => chip.label)).toEqual([+ 'Checkout',+ 'Open-ended responses',+ 'Text',+ 'Welcome',+ 'text note',+ ])+ expect(JSON.stringify(chips)).not.toContain(responses)+ expect(JSON.stringify(chips)).not.toContain('<p>Hi</p>')++ logic.actions.removeChatChip('task-a', 'experiment:17')++ expect(logic.values.chatChipsByTask['task-a']).toHaveLength(4)+ expect(logic.values.chatChipsByTask['task-b']).toHaveLength(1)+ })++ it('evicts the chat with the oldest delivery once the persisted store is full', async () => {+ for (let chat = 0; chat <= 49; chat++) {+ logic.actions.contextDelivered(`bounded-${chat}`, [{ type: 'insight', key: 'x' }])+ }+ logic.actions.contextDelivered('bounded-0', [{ type: 'dashboard', key: 'y' }])+ logic.actions.contextDelivered('bounded-50', [{ type: 'insight', key: 'x' }])++ expect(logic.values.chatChipsByTask['bounded-0']).toHaveLength(2)+ expect(logic.values.chatChipsByTask['bounded-1']).toBeUndefined()+ expect(Object.keys(logic.values.chatChipsByTask)).toHaveLength(50)+ })+it('dismissal hides an item, survives provider re-registration, and undismiss restores it', async () => {const item = { type: 'insight', key: 'x', label: 'X' }diff --git a/frontend/src/layout/ai/attachedContextLogic.ts b/frontend/src/layout/ai/attachedContextLogic.tsindex e90496fd2207..7527b2490d70 100644--- a/frontend/src/layout/ai/attachedContextLogic.ts+++ b/frontend/src/layout/ai/attachedContextLogic.ts@@ -1,20 +1,44 @@import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'-import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { type AttachedContextItem, NEW_CHAT_KEY, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { type ChatChipsByTask, addChatChips, removeChatChip, withRemovedGroup } from '~/layout/ai/chatContextChips'++function withoutPicks(+ pickedByChat: Record<string, AttachedContextItem[]>,+ chat: string,+ keys: Set<string>+): Record<string, AttachedContextItem[]> {+ const picks = pickedByChat[chat]+ return picks+ ? { ...pickedByChat, [chat]: picks.filter((item) => !keys.has(attachedContextItemKey(item))) }+ : pickedByChat+}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface attachedContextLogicValues {+ chatChipsByTask: ChatChipsByTaskcontextItems: AttachedContextItem[]dismissedGroups: Record<string, true>dismissedKeys: Record<string, true>hasContext: boolean+ pickedByChat: Record<string, AttachedContextItem[]>providers: Record<string, AttachedContextItem[]>+ removedGroupsByTask: Record<string, string[]>seenContextLinesByTask: Record<string, string[]>sentContextKeysByTask: Record<string, string[]>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface attachedContextLogicActions {+ contextDelivered: (+ taskId: string,+ items: AttachedContextItem[],+ fromNewChat?: boolean+ ) => {+ fromNewChat: boolean+ items: AttachedContextItem[]+ taskId: string+ }deregisterContext: (providerId: string) => {providerId: string}@@ -32,11 +56,11 @@ export interface attachedContextLogicActions {lines: string[]taskId: string}- markContextSent: (- taskId: string,- keys: string[]+ pickItem: (+ item: AttachedContextItem,+ taskId?: string) => {- keys: string[]+ item: AttachedContextItemtaskId: string}registerContext: (@@ -46,6 +70,22 @@ export interface attachedContextLogicActions {items: AttachedContextItem[]providerId: string}+ removeChatChip: (+ taskId: string,+ chipId: string,+ dismissGroup?: string+ ) => {+ chipId: string+ dismissGroup: string | undefined+ taskId: string+ }+ removePickedItem: (+ key: string,+ taskId?: string+ ) => {+ key: string+ taskId: string+ }undismissContext: (key: string,dismissGroup?: string@@ -81,8 +121,12 @@ export type attachedContextLogicType = MakeLogicType<* upserts its items; `contextItems` flattens and dedupes across providers.** A consumer reads `contextItems` at send time and wraps the outgoing message with the- * trusted/untrusted context blocks (`utils/posthogContextBlock`). Nothing here is keyed by conversation —- * the on-screen context is global to the app at any instant.+ * trusted/untrusted context blocks (`utils/posthogContextBlock`). The registry is not keyed by+ * conversation: the on-screen context is global to the app at any instant, and it only decides what a+ * new chat starts with.+ *+ * `chatChipsByTask` holds the chips of what each chat received, without the payloads, so a started chat+ * keeps its chips when the user navigates away. `chatContextLogic` owns how a chat combines these stores.** This store also keeps the sent-context bookkeeping, two layers keyed by task id (task-scoped, not* run-scoped, so the dedupe survives a terminal-run send re-pointing the consumer to a fresh run):@@ -104,8 +148,15 @@ export const attachedContextLogic = kea<attachedContextLogicType>([/** Idempotent upsert — re-register the same `providerId` to update its items. */registerContext: (providerId: string, items: AttachedContextItem[]) => ({ providerId, items }),deregisterContext: (providerId: string) => ({ providerId }),- /** Record context item keys already wrapped into a message sent for `taskId`. */- markContextSent: (taskId: string, keys: string[]) => ({ taskId, keys }),+ /**+ * A send delivered `items` to the chat: record them for dedupe, and save the visible ones as its chips.+ * `fromNewChat` says the new chat composer sent them, so its draft picks are the ones delivered.+ */+ contextDelivered: (taskId: string, items: AttachedContextItem[], fromNewChat: boolean = false) => ({+ taskId,+ items,+ fromNewChat,+ }),/** Record rendered context-block lines observed in `taskId`'s run log (see `seenContextLinesByTask`). */markContextLinesSeen: (taskId: string, lines: string[]) => ({ taskId, lines }),/**@@ -117,6 +168,9 @@ export const attachedContextLogic = kea<attachedContextLogicType>([*/dismissContext: (key: string, dismissGroup?: string) => ({ key, dismissGroup }),undismissContext: (key: string, dismissGroup?: string) => ({ key, dismissGroup }),+ removeChatChip: (taskId: string, chipId: string, dismissGroup?: string) => ({ taskId, chipId, dismissGroup }),+ pickItem: (item: AttachedContextItem, taskId: string = NEW_CHAT_KEY) => ({ item, taskId }),+ removePickedItem: (key: string, taskId: string = NEW_CHAT_KEY) => ({ key, taskId }),}),reducers({@@ -138,7 +192,8 @@ export const attachedContextLogic = kea<attachedContextLogicType>([sentContextKeysByTask: [{} as Record<string, string[]>,{- markContextSent: (state, { taskId, keys }) => {+ contextDelivered: (state, { taskId, items }) => {+ const keys = items.filter((item) => item.type !== 'text').map(attachedContextItemKey)if (keys.length === 0) {return state}@@ -151,6 +206,40 @@ export const attachedContextLogic = kea<attachedContextLogicType>([},},],+ pickedByChat: [+ {} as Record<string, AttachedContextItem[]>,+ {+ pickItem: (state, { item, taskId }) => {+ const key = attachedContextItemKey(item)+ const others = (state[taskId] ?? []).filter((existing) => attachedContextItemKey(existing) !== key)+ return { ...state, [taskId]: [...others, item] }+ },+ removePickedItem: (state, { key, taskId }) => withoutPicks(state, taskId, new Set([key])),+ contextDelivered: (state, { taskId, items, fromNewChat }) =>+ withoutPicks(+ state,+ fromNewChat ? NEW_CHAT_KEY : taskId,+ new Set(items.map(attachedContextItemKey))+ ),+ },+ ],+ chatChipsByTask: [+ {} as ChatChipsByTask,+ { persist: true },+ {+ contextDelivered: (state, { taskId, items }) => (taskId ? addChatChips(state, taskId, items) : state),+ removeChatChip: (state, { taskId, chipId, dismissGroup }) =>+ removeChatChip(state, taskId, chipId, dismissGroup),+ },+ ],+ // Persisted with the chips, because a reload must not resume sending a hidden payload the user removed.+ removedGroupsByTask: [+ {} as Record<string, string[]>,+ { persist: true },+ {+ removeChatChip: (state, { taskId, dismissGroup }) => withRemovedGroup(state, taskId, dismissGroup),+ },+ ],// Per-task set of rendered context-block lines observed in the task's run log (replay or live// echo). The durable dedupe layer: unlike `sentContextKeysByTask` it is reconstructed from the// persisted resume-chain history on every open, so it survives reloads and other sessions.diff --git a/frontend/src/layout/ai/chatContextChips.ts b/frontend/src/layout/ai/chatContextChips.tsnew file mode 100644index 000000000000..5abedcf57976--- /dev/null+++ b/frontend/src/layout/ai/chatContextChips.ts@@ -0,0 +1,102 @@+import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'++// Bounds the persisted store, because every chat a browser starts adds an entry to localStorage.+const MAX_PERSISTED_CHATS = 50++export interface ContextChip extends Pick<AttachedContextItem, 'type' | 'key' | 'pageId' | 'dismissible'> {+ id: string+ label: string+ dismissGroup?: string+}++export type ChatChipsByTask = Record<string, ContextChip[]>++function hasKey(item: AttachedContextItem): boolean {+ return item.key !== undefined && item.key !== null && item.key !== ''+}++function keyedLabel(item: AttachedContextItem): string {+ return `${item.type} ${item.key ?? ''}`.trim()+}++function chipReference({+ type,+ key,+ pageId,+ dismissible,+ dismissGroup,+}: AttachedContextItem): Pick<ContextChip, 'type' | 'key' | 'pageId' | 'dismissible' | 'dismissGroup'> {+ return { type, key, pageId, dismissible, dismissGroup }+}++/** The chip for an item on screen now. Its id matches `attachedContextItemKey`, so it can dismiss the item. */+export function contextChip(item: AttachedContextItem): ContextChip {+ return {+ ...chipReference(item),+ id: attachedContextItemKey(item),+ label: item.label || (item.type === 'text' && item.value) || keyedLabel(item) || 'Text',+ }+}++/**+ * The chip a chat stores. `value` can hold ingested data, such as survey responses, and the agent already has it, so+ * neither the id nor the label of a stored chip may derive from it.+ */+function storedChatChip(item: AttachedContextItem): ContextChip {+ if (hasKey(item)) {+ return { ...chipReference(item), id: attachedContextItemKey(item), label: item.label || keyedLabel(item) }+ }+ const label = item.label || (item.type === 'text' ? 'Text' : item.type)+ return { ...chipReference(item), id: `${item.type}:${label}`, label }+}++function withChatLast(chats: ChatChipsByTask, taskId: string, chips: ContextChip[]): ChatChipsByTask {+ const { [taskId]: _previous, ...others } = chats+ return { ...Object.fromEntries(Object.entries(others).slice(-(MAX_PERSISTED_CHATS - 1))), [taskId]: chips }+}++export function addChatChips(chats: ChatChipsByTask, taskId: string, items: AttachedContextItem[]): ChatChipsByTask {+ const existing = chats[taskId] ?? []+ const seenIds = new Set(existing.map((chip) => chip.id))+ const added: ContextChip[] = []+ for (const item of items) {+ const chip = storedChatChip(item)+ if (!item.hidden && !seenIds.has(chip.id)) {+ seenIds.add(chip.id)+ added.push(chip)+ }+ }+ return added.length > 0 ? withChatLast(chats, taskId, [...existing, ...added]) : chats+}++export function removeChatChip(+ chats: ChatChipsByTask,+ taskId: string,+ chipId: string,+ dismissGroup?: string+): ChatChipsByTask {+ const existing = chats[taskId]+ return existing+ ? {+ ...chats,+ [taskId]: existing.filter(+ (chip) => chip.id !== chipId && (!dismissGroup || chip.dismissGroup !== dismissGroup)+ ),+ }+ : chats+}++export function withRemovedGroup(+ removedGroups: Record<string, string[]>,+ taskId: string,+ dismissGroup: string | undefined+): Record<string, string[]> {+ if (!dismissGroup) {+ return removedGroups+ }+ const { [taskId]: existing = [], ...others } = removedGroups+ return {+ ...Object.fromEntries(Object.entries(others).slice(-(MAX_PERSISTED_CHATS - 1))),+ [taskId]: [...new Set([...existing, dismissGroup])],+ }+}diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.tsindex 43b27250910f..7f4c12d76f5d 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts@@ -10,6 +10,7 @@ import {PropertyOperator,} from '~/types'+import { contextItemPath } from 'products/posthog_ai/frontend/utils/contextItemLink'import { wrapWithPosthogContext } from 'products/posthog_ai/frontend/utils/posthogContextBlock'import {@@ -74,6 +75,13 @@ describe('featureFlagAiContext', () => {return item.value}+ test.each(['test-flag', '12'])('links flag %s by ID and keeps its context key', (key) => {+ const items = featureFlagContextItems({ ...baseFeatureFlag, key })++ expect(contextItemPath(items[0])).toBe('/feature-flags/1')+ expect(wrapWithPosthogContext('Review this flag', items)).toContain(`feature_flag ${key}`)+ })+it('renders the release conditions into the context block the agent reads', () => {const block = wrapWithPosthogContext('who matches this flag?',diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.tsindex 3428d744f99b..ad7e5295ecfc 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.ts@@ -23,7 +23,7 @@ const MAX_DESCRIPTION_LENGTH = 400export function featureFlagContextItems(featureFlag: FeatureFlagType): AttachedContextItem[] {return [// `name` on a flag is the description, so the key is the only display name available here.- { type: 'feature_flag', key: featureFlag.key, label: featureFlag.key },+ { type: 'feature_flag', key: featureFlag.key, pageId: featureFlag.id, label: featureFlag.key },{ type: 'feature_flag_targeting', label: 'Release conditions', value: targetingValue(featureFlag) },]}diff --git a/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx b/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsxindex 849f01f88986..afdb4c7c0e68 100644--- a/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx+++ b/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx@@ -31,7 +31,11 @@ import { SURVEY_CREATED_SOURCE } from '../constants'import { QuickSurveyType } from '../quick-create/types'import { QuickSurveyModal } from '../QuickSurveyModal'import { captureMaxAISurveyCreationException } from '../utils'-import { SurveyableFunnelInsight, extractFunnelContext } from '../utils/opportunityDetection'+import {+ SurveyableFunnelInsight,+ extractFunnelContext,+ surveyOpportunityContextItems,+} from '../utils/opportunityDetection'export interface SurveyOpportunityButtonProps {insight: SurveyableFunnelInsight@@ -106,21 +110,7 @@ export function SurveyOpportunityButton({},})- useAttachedContext(- funnelContext- ? [- { type: 'insight', key: insight.id, label: funnelContext.insightName },- {- type: 'survey_opportunity_funnel_context',- value: JSON.stringify({- conversionRate: funnelContext.conversionRate,- steps: funnelContext.steps,- }),- label: 'Funnel conversion context',- },- ]- : null- )+ useAttachedContext(surveyOpportunityContextItems(insight, funnelContext))const handleClick = (): void => {posthog.capture('survey opportunity clicked', {diff --git a/frontend/src/scenes/surveys/utils/opportunityDetection.test.ts b/frontend/src/scenes/surveys/utils/opportunityDetection.test.tsindex 019bee48bb2b..78ad4552ec9a 100644--- a/frontend/src/scenes/surveys/utils/opportunityDetection.test.ts+++ b/frontend/src/scenes/surveys/utils/opportunityDetection.test.ts@@ -1,9 +1,12 @@import { FunnelsQuery, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'import { FunnelVizType, InsightModel } from '~/types'-import { isSurveyableFunnelInsight } from './opportunityDetection'+import { contextItemPath } from 'products/posthog_ai/frontend/utils/contextItemLink'+import { wrapWithPosthogContext } from 'products/posthog_ai/frontend/utils/posthogContextBlock'-describe('isSurveyableFunnelInsight', () => {+import { isSurveyableFunnelInsight, surveyOpportunityContextItems } from './opportunityDetection'++describe('opportunityDetection', () => {const pageviews = { kind: NodeKind.EventsNode as const, event: '$pageview', name: '$pageview' }const signups = { kind: NodeKind.ActionsNode as const, id: 7, name: 'Signed up' }const steps = [@@ -53,4 +56,33 @@ describe('isSurveyableFunnelInsight', () => {])('checks %s', (_case, insight, expected) => {expect(isSurveyableFunnelInsight(insight)).toBe(expected)})++ describe('surveyOpportunityContextItems', () => {+ const funnelContext = { insightName: 'Signups', conversionRate: 0.2, steps: [] }++ const shortId = 'abc123' as InsightModel['short_id']++ test.each<[Partial<Pick<InsightModel, 'id' | 'short_id'>>, string | null]>([+ [{ id: 17, short_id: shortId }, '/insights/abc123'],+ [{ id: 17 }, null],+ [{}, null],+ ])('links %o by short ID and keeps the context key', (insight, expected) => {+ const items = surveyOpportunityContextItems(insight, funnelContext)++ expect(contextItemPath(items![0])).toBe(expected)+ expect(items![0].key).toBe(insight.id)+ expect(items![1]).toEqual({+ type: 'survey_opportunity_funnel_context',+ value: JSON.stringify({ conversionRate: 0.2, steps: [] }),+ label: 'Funnel conversion context',+ })+ if (insight.id) {+ expect(wrapWithPosthogContext('Review this funnel', items!)).toContain(`insight ${insight.id}`)+ }+ })++ it('attaches no context without a surveyable funnel', () => {+ expect(surveyOpportunityContextItems({ id: 17, short_id: shortId }, null)).toBeNull()+ })+ })})diff --git a/frontend/src/scenes/surveys/utils/opportunityDetection.ts b/frontend/src/scenes/surveys/utils/opportunityDetection.tsindex 50c0d3ce149f..ad0641108978 100644--- a/frontend/src/scenes/surveys/utils/opportunityDetection.ts+++ b/frontend/src/scenes/surveys/utils/opportunityDetection.ts@@ -1,3 +1,4 @@+import type { AttachedContextItem } from '~/layout/ai/attachedContext'import {AnyEntityNode,EventsNode,@@ -21,11 +22,36 @@ interface FunnelStepResult {export interface SurveyableFunnelInsight {id?: number+ short_id?: InsightModel['short_id']name?: stringquery: InsightVizNode<FunnelsQuery>result: FunnelStepResult[]}+export function surveyOpportunityContextItems(+ insight: Pick<SurveyableFunnelInsight, 'id' | 'short_id'>,+ funnelContext: FunnelContext | null+): AttachedContextItem[] | null {+ return funnelContext+ ? [+ {+ type: 'insight',+ key: insight.id,+ pageId: insight.short_id ?? null,+ label: funnelContext.insightName,+ },+ {+ type: 'survey_opportunity_funnel_context',+ value: JSON.stringify({+ conversionRate: funnelContext.conversionRate,+ steps: funnelContext.steps,+ }),+ label: 'Funnel conversion context',+ },+ ]+ : null+}+/*** Find the funnel with the best opportunity to create a survey, given a list* of dashboard tiles.diff --git a/packages/quill/packages/primitives/src/chip.tsx b/packages/quill/packages/primitives/src/chip.tsxindex 8e48fd875614..d860ca69e129 100644--- a/packages/quill/packages/primitives/src/chip.tsx+++ b/packages/quill/packages/primitives/src/chip.tsx@@ -43,10 +43,11 @@ const ChipClose = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeoreturn (<Buttonref={ref}- data-slot="chip-close"size="icon-xs"className={cn('quill-chip-close rounded-xs', className)}{...props}+ // After the spread because a wrapper such as TooltipTrigger passes its own data-slot through `render`, and the chip styles need this one.+ data-slot="chip-close">{children ?? <XIcon />}</Button>diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex 82fa946717cb..933774b70ddd 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -163,7 +163,7 @@ loosely typed — guard at the parse boundary with runtime checks; never assume(a mounted `useAttachedContext` hook / `AttachedContextProvider` component, or a kea logic registering via`cache.disposables` — setup dispatches `registerContext(providerId, items)`, cleanup `deregisterContext`,with `pauseOnPageHidden: false` since a hide-paused registration would drop context from sends that happen-while the tab is hidden; `contextPickerLogic` is the exemplar) contributes+while the tab is hidden) contributesabstract `AttachedContextItem`s — `type` is an **arbitrary string** (`'insight'`, `'dashboard'`, `'trace'`,`'text'`…; never an enumerated union), plus `key`/`label`/`value`. `contextItems` flattens and dedupes by`${type}:${key ?? value}`. At send time the send paths (`runInteractionLogic.sendNow`/`startNewRun`,@@ -184,15 +184,22 @@ message, and since the `logs/` snapshot replays the full resume chain this surviother users' sessions (matching the backend's `_collect_seen_entity_refs`/`prune_repeated_entity_refs`);`text` items are never deduped, repeated text is intentional.+**A chat's visible context is frozen when it starts. `logics/chatContextLogic.ts`, keyed by task, is the one definition of what is in a chat.**+A new chat shows and sends `contextItems` plus its picks.+A started chat shows its saved chips (`attachedContextLogic.chatChipsByTask`) plus its own picks, and sends those picks plus the `hidden` items, which follow the current page because tools act on that state.+Every send path takes its items from `chatSendItems`, and reports what it delivered with `contextDelivered(taskId, items, fromNewChat)`, which updates the dedupe keys, the chat's chips and the picks in one action.+`chatChipsByTask` persists in `localStorage`, so a stored chip keeps only references and labels, never `value` or `previewHtml`.+Removing a chip from a started chat also stops the hidden items in its `dismissGroup` for that chat (`removedGroupsByTask`).+**User-picked context (`logics/contextPickerLogic.ts` + `components/composer/AttachedContextBar.tsx`):** thecomposer's @-affordance. `AttachedContextBar` (Tier 2, drop into `Composer.Header`, the top-of-frame row above the textarea; already wired into`TaskComposer` and `TaskRunChat`) renders a `TaxonomicPopover` whose selections are projected to flat refs by`taxonomicItemToAttachedContext` — no entity loading, the agent fetches details — and stored in-`contextPickerLogic`, which is just another provider (`user-picker`) on `attachedContextLogic`. The bar's chips-render **all** of `contextItems`; closing a picked chip removes it from the picker, closing any other-provider's chip dispatches `attachedContextLogic.dismissContext(key)`. Dismissal filters the key out of+`attachedContextLogic.pickedByChat`. Picks are not a provider, so they never appear in `contextItems`. The+bar's chips render what `chatContextLogic` returns; closing a picked chip removes it from the picker, closing a+provider's chip in a new chat dispatches `attachedContextLogic.dismissContext(key)`. Dismissal filters the key out of`contextItems` and **survives provider re-registration** (the scene bridge upserts on every scene read — a-closed chip must not resurrect); re-picking the same item `undismissContext`s it.+closed chip must not resurrect); re-picking the same item adds it back as a pick.**Tool-stream events (`logics/toolStreamEventsLogic.ts`):** a global bus `runStreamLogic` publishestool-call lifecycle events to — `phase: started/updated/completed/failed`, with `toolName` **resolved** viadiff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex 52aa539a548b..5a538d1b2cae 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -286,11 +286,12 @@ import { AttachedContextBar } from 'products/posthog_ai/frontend/api/primitives'```The @-button opens a `TaxonomicPopover` over events/actions/insights/dashboards/notebooks/error-tracking-issues; a selection becomes a flat `{ type, key, label }` ref in `contextPickerLogic` (`api/logics`) — no-entity loading, the agent fetches details. The chips render **everything** in `contextItems`, whatever-provider contributed it. Closing a chip the picker owns removes the pick; closing any other provider's chip+issues; a selection becomes a flat `{ type, key, label }` ref through `contextPickerLogic` (`api/logics`) — no+entity loading, the agent fetches details. In a new chat the chips render your picks and **everything** in+`contextItems`, whatever provider contributed it. A started chat freezes its chips: pass `taskId` to `AttachedContextChips` or+`QuillAttachedContextChips` to show what `chatContextLogic` holds for that chat. Closing a chip the picker owns removes the pick; closing any other provider's chipdismisses that key (`attachedContextLogic.dismissContext`), which sticks even while the provider keeps-re-registering the item — re-picking it through the popover restores it.+re-registering the item — re-picking it through the popover adds it back as a pick.### React to the agent invoking a tooldiff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.tsindex aac0c3337b48..c524a67ea08d 100644--- a/products/posthog_ai/frontend/api/logics.ts+++ b/products/posthog_ai/frontend/api/logics.ts@@ -62,9 +62,10 @@ export type { UseComposerOverrideOptions } from '../hooks/useComposerOverride'export { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM, wrapWithPosthogContext } from '../utils/posthogContextBlock'// --- User-picked context (the composer's @-affordance, headless half) ----// `contextPickerLogic` owns explicit user picks and registers them as the `user-picker` provider;-// the `AttachedContextBar` component (Tier 2 `api/primitives`) is its prepackaged UI.-export { contextPickerLogic, taxonomicItemToAttachedContext, PICKER_PROVIDER_ID } from '../logics/contextPickerLogic'+// `contextPickerLogic` turns a selection into a pick, and `chatContextLogic` combines picks with the rest of a+// chat's context; the `AttachedContextBar` component (Tier 2 `api/primitives`) is the prepackaged UI.+export { chatContextLogic, chatSendItems } from '../logics/chatContextLogic'+export { contextPickerLogic, taxonomicItemToAttachedContext } from '../logics/contextPickerLogic'export type { PickableTaxonomicItem } from '../logics/contextPickerLogic'// --- Tool-stream event bus + subscription hook (headless) ---diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsxindex b2134ddb9070..c40eb18ceecb 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsx@@ -6,7 +6,9 @@ import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { ThreadSkinOverrideContext } from '../../hooks/useThreadSkin'import { AttachedContextBar } from './AttachedContextBar'+import { AttachedContextChips } from './AttachedContextChips'describe('AttachedContextBar', () => {beforeEach(() => {@@ -35,6 +37,33 @@ describe('AttachedContextBar', () => {expect(container.querySelectorAll('.LemonTag')).toHaveLength(1)})+ // The bar is the only chip row on surfaces with their own composer, so it must follow the skin to keep links.+ it('renders quill chips under the quill skin', () => {+ const { container } = render(+ <ThreadSkinOverrideContext.Provider value="quill">+ <AttachedContextBar />+ </ThreadSkinOverrideContext.Provider>+ )++ expect(container.querySelector('[data-attr="posthog-ai-context-chip"]')).toHaveTextContent('Weekly signups')+ expect(container.querySelectorAll('.LemonTag')).toHaveLength(0)+ })++ // Chips that follow the registry would drop the chat's context on navigation and show the new page instead.+ it('shows a started chat its saved context, not the context of the current page', () => {+ attachedContextLogic.actions.contextDelivered('task-a', [{ type: 'experiment', key: 17, label: 'Checkout' }])++ const { container } = render(<AttachedContextChips taskId="task-a" />)++ expect(container).toHaveTextContent('Checkout')+ expect(container).not.toHaveTextContent('Weekly signups')++ fireEvent.click(container.querySelector('.LemonTag') as Element)++ expect(attachedContextLogic.values.chatChipsByTask['task-a']).toEqual([])+ expect(attachedContextLogic.values.contextItems.map((item) => item.key)).toEqual(['d1', 't1'])+ })+it('removes the attachment from the context when its remove control is clicked', () => {render(<AttachedContextBar />)diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsxindex 0148e4d46310..b5f19cc22fac 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx@@ -1,6 +1,18 @@+import { useThreadSkin } from '../../hooks/useThreadSkin'+import { QuillAttachedContextChips } from '../quill/QuillAttachedContextChips'+import { QuillAttachedContextPicker } from '../quill/QuillAttachedContextPicker'import { AttachedContextChips } from './AttachedContextChips'import { AttachedContextPicker } from './AttachedContextPicker'export function AttachedContextBar(): JSX.Element | null {+ const skin = useThreadSkin()+ if (skin === 'quill') {+ return (+ <div className="flex min-w-0 flex-wrap items-center gap-1">+ <QuillAttachedContextPicker />+ <QuillAttachedContextChips />+ </div>+ )+ }return <AttachedContextChips leading={<AttachedContextPicker />} />}diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsxindex 70e167ed543c..d1a27d785d9f 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx@@ -7,10 +7,7 @@ import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'import { IconAction, IconEvent } from 'lib/lemon-ui/icons'-import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'-import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'--import { contextPickerLogic } from '../../logics/contextPickerLogic'+import { chatContextLogic } from '../../logics/chatContextLogic'function iconForType(type: string): JSX.Element {switch (type) {@@ -31,16 +28,6 @@ function iconForType(type: string): JSX.Element {}}-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: stringhtml: string@@ -74,34 +61,21 @@ function AttachmentPreview({ label, html, onRemove }: AttachmentPreviewProps): Jexport interface AttachedContextChipsProps {leading?: ReactNode+ taskId?: string}/**- * 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+ * Removable chips for what `chatContextLogic` says is in this chat. Closing one removes a pick, dismisses a provider's+ * item from a new chat, or takes the chip off a started chat. 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))- }+export function AttachedContextChips({ leading, taskId }: AttachedContextChipsProps): JSX.Element | null {+ const logic = chatContextLogic({ taskId })+ const { chips, attachments } = useValues(logic)+ const { removeChip } = useActions(logic)- if (visibleItems.length === 0 && !leading) {+ if (chips.length === 0 && attachments.length === 0 && !leading) {return null}@@ -109,12 +83,12 @@ export function AttachedContextChips({ leading }: AttachedContextChipsProps): JS<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) => (+ {attachments.map(({ chip, previewHtml }) => (<AttachmentPreview- key={attachedContextItemKey(item)}- label={labelForItem(item)}- html={item.previewHtml!}- onRemove={removeItem(item)}+ key={chip.id}+ label={chip.label}+ html={previewHtml}+ onRemove={chip.dismissible === false ? undefined : () => removeChip(chip)}/>))}</div>@@ -122,20 +96,18 @@ export function AttachedContextChips({ leading }: AttachedContextChipsProps): JS{(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)+ {chips.map((chip) => {+ const removable = chip.dismissible !== falsereturn (- <Tooltip key={key} title={label}>+ <Tooltip key={chip.id} title={chip.label}><LemonTag- icon={iconForType(item.type)}- onClose={onRemove}- closable={!!onRemove}- closeOnClick={!!onRemove}+ icon={iconForType(chip.type)}+ onClose={removable ? () => removeChip(chip) : undefined}+ closable={removable}+ closeOnClick={removable}className="flex items-center text-secondary max-w-48">- <span className="truncate min-w-0 flex-1">{label}</span>+ <span className="truncate min-w-0 flex-1">{chip.label}</span></LemonTag></Tooltip>)diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsxindex f8ffc078a7db..00280b528dfc 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx@@ -10,9 +10,13 @@ import { CONTEXT_PICKER_GROUP_TYPES, contextPickerLogic } from '../../logics/conexport interface AttachedContextPickerProps {className?: string+ taskId?: string}-export function AttachedContextPicker({ className = 'h-6 min-h-6 shrink-0' }: AttachedContextPickerProps): JSX.Element {+export function AttachedContextPicker({+ className = 'h-6 min-h-6 shrink-0',+ taskId,+}: AttachedContextPickerProps): JSX.Element {const { handleTaxonomicFilterChange } = useActions(contextPickerLogic)return (<Tooltip title="Add context to help PostHog AI answer your question">@@ -27,7 +31,11 @@ export function AttachedContextPicker({ className = 'h-6 min-h-6 shrink-0' }: AtclassName={className}groupType={TaxonomicFilterGroupType.Events}groupTypes={CONTEXT_PICKER_GROUP_TYPES}- onChange={handleTaxonomicFilterChange}+ onChange={(value, groupType, item) => {+ if (value !== null) {+ handleTaxonomicFilterChange(value, groupType, item, taskId)+ }+ }}icon={<IconAtSign className="text-secondary" />}placeholder="Add context"aria-label="Add context"diff --git a/products/posthog_ai/frontend/components/quill/QuillAttachedContextChip.stories.tsx b/products/posthog_ai/frontend/components/quill/QuillAttachedContextChip.stories.tsxnew file mode 100644index 000000000000..ca4464301d84--- /dev/null+++ b/products/posthog_ai/frontend/components/quill/QuillAttachedContextChip.stories.tsx@@ -0,0 +1,38 @@+import type { Meta, StoryObj } from '@storybook/react'++import { urls } from 'scenes/urls'++import { QuillAttachedContextChip } from './QuillAttachedContextChip'++const meta: Meta<typeof QuillAttachedContextChip> = {+ title: 'Products/PostHog AI/Quill context chip',+ component: QuillAttachedContextChip,+ parameters: {+ pageUrl: urls.experiment(17),+ testOptions: { snapshotBrowsers: [] },+ },+ render: () => (+ <div data-quill className="flex flex-wrap items-center gap-1 p-4">+ <QuillAttachedContextChip+ chip={{+ id: 'feature_flag:new-checkout-flow',+ type: 'feature_flag',+ key: 'new-checkout-flow',+ pageId: 12,+ label: 'new-checkout-flow',+ }}+ onRemove={() => {}}+ />+ <QuillAttachedContextChip+ chip={{ id: 'experiment:17', type: 'experiment', key: 17, label: 'Checkout button color' }}+ onRemove={() => {}}+ />+ <QuillAttachedContextChip chip={{ id: 'text:note', type: 'text', label: 'Only count paid plans' }} />+ </div>+ ),+}+export default meta++type Story = StoryObj<typeof QuillAttachedContextChip>++export const LinkCurrentPageAndPlain: Story = {}diff --git a/products/posthog_ai/frontend/components/quill/QuillAttachedContextChip.tsx b/products/posthog_ai/frontend/components/quill/QuillAttachedContextChip.tsxnew file mode 100644index 000000000000..2423d985e6d7--- /dev/null+++ b/products/posthog_ai/frontend/components/quill/QuillAttachedContextChip.tsx@@ -0,0 +1,71 @@+import { useValues } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { IconX } from '@posthog/icons'+import { Chip, ChipClose, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill-primitives'++import { LinkPrimitive } from 'lib/lemon-ui/Link'++import type { ContextChip } from '~/layout/ai/chatContextChips'++import { contextItemPath, isOnContextItemPage } from '../../utils/contextItemLink'++export interface QuillAttachedContextChipProps {+ chip: ContextChip+ onRemove?: () => void+}++export function QuillAttachedContextChip({ chip, onRemove }: QuillAttachedContextChipProps): JSX.Element {+ const { label } = chip+ const { location } = useValues(router)+ const path = contextItemPath(chip)+ const onPage = path !== null && isOnContextItemPage(path, location.pathname)++ return (+ <Chip className="max-w-48" data-attr="posthog-ai-context-chip">+ {onRemove && (+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <ChipClose+ aria-label={`Remove ${label}`}+ onClick={onRemove}+ data-attr="posthog-ai-context-chip-remove"+ />+ }+ >+ <IconX />+ </TooltipTrigger>+ <TooltipContent>Remove from chat</TooltipContent>+ </Tooltip>+ )}+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ path && !onPage ? (+ <LinkPrimitive+ to={path}+ className="min-w-0 truncate text-inherit hover:underline"+ onClick={() => {+ // pinned: analytics event name+ posthog.capture('posthog ai context chip opened', { type: chip.type })+ }}+ data-attr="posthog-ai-context-chip-link"+ />+ ) : (+ <span tabIndex={0} className="min-w-0 truncate" />+ )+ }+ >+ {label}+ </TooltipTrigger>+ <TooltipContent>+ {path === null ? label : onPage ? "You're on this page" : `Open ${label}`}+ </TooltipContent>+ </Tooltip>+ </Chip>+ )+}diff --git a/products/posthog_ai/frontend/components/quill/QuillAttachedContextChips.tsx b/products/posthog_ai/frontend/components/quill/QuillAttachedContextChips.tsxnew file mode 100644index 000000000000..e0d85cc2c82c--- /dev/null+++ b/products/posthog_ai/frontend/components/quill/QuillAttachedContextChips.tsx@@ -0,0 +1,66 @@+import { useActions, useValues } from 'kea'++import { IconX } from '@posthog/icons'+import { Button } from '@posthog/quill-primitives'++import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'++import { chatContextLogic } from '../../logics/chatContextLogic'+import { QuillAttachedContextChip } from './QuillAttachedContextChip'++export interface QuillAttachedContextChipsProps {+ taskId?: string+}++export function QuillAttachedContextChips({ taskId }: QuillAttachedContextChipsProps): JSX.Element | null {+ const logic = chatContextLogic({ taskId })+ const { chips, attachments } = useValues(logic)+ const { removeChip } = useActions(logic)++ if (chips.length === 0 && attachments.length === 0) {+ return null+ }++ return (+ <>+ {attachments.length > 0 && (+ <div className="flex w-full gap-2 overflow-x-auto" data-attr="posthog-ai-context-attachments">+ {attachments.map(({ chip, previewHtml }) => (+ <div+ key={chip.id}+ className="relative flex w-24 shrink-0 flex-col overflow-hidden rounded border bg-surface-primary"+ data-attr="posthog-ai-context-attachment"+ >+ <EmailPreviewThumbnail+ html={previewHtml}+ title={`${chip.label} preview`}+ size="attachment"+ className="border-b"+ />+ <span className="truncate px-1.5 py-1 text-xs" title={chip.label}>+ {chip.label}+ </span>+ {chip.dismissible !== false && (+ <Button+ size="icon-xs"+ aria-label={`Remove ${chip.label}`}+ onClick={() => removeChip(chip)}+ className="absolute top-0.5 right-0.5"+ >+ <IconX />+ </Button>+ )}+ </div>+ ))}+ </div>+ )}+ {chips.map((chip) => (+ <QuillAttachedContextChip+ key={chip.id}+ chip={chip}+ onRemove={chip.dismissible === false ? undefined : () => removeChip(chip)}+ />+ ))}+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx b/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsxindex f55df2146e20..5c319ef7ea65 100644--- a/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx+++ b/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx@@ -16,12 +16,12 @@ import {} from '@posthog/quill-primitives'import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { type TaxonomicFilterProps, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { cn } from 'lib/utils/css-classes'-import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { todayShellLogic } from '~/layout/today/todayShellLogic'+import { chatContextLogic } from '../../logics/chatContextLogic'import { CONTEXT_PICKER_GROUP_TYPES, contextPickerLogic } from '../../logics/contextPickerLogic'import { COMPOSER_MENU_CLASS } from './composerMenuClass'@@ -29,12 +29,14 @@ export interface QuillAttachedContextPickerProps {open?: booleanonOpenChange?: (open: boolean) => voidanchor?: RefObject<HTMLElement>+ taskId?: string}export function QuillAttachedContextPicker({open: controlledOpen,onOpenChange,anchor,+ taskId,}: QuillAttachedContextPickerProps = {}): JSX.Element {const [uncontrolledOpen, setUncontrolledOpen] = useState(false)const open = controlledOpen ?? uncontrolledOpen@@ -43,9 +45,22 @@ export function QuillAttachedContextPicker({onOpenChange?.(next)}const filterKey = `posthog-ai-context-picker-${useId()}`- const { hasContext } = useValues(attachedContextLogic)+ const { chips } = useValues(chatContextLogic({ taskId }))+ const hasContext = chips.length > 0const { handleTaxonomicFilterChange } = useActions(contextPickerLogic)const { todayRailEnabled, phoneLayout } = useValues(todayShellLogic)+ const filterProps: TaxonomicFilterProps = {+ taxonomicFilterLogicKey: filterKey,+ groupType: TaxonomicFilterGroupType.Events,+ taxonomicGroupTypes: CONTEXT_PICKER_GROUP_TYPES,+ onChange: ({ type }, value, item) => {+ if (value !== null) {+ handleTaxonomicFilterChange(value, type, item, taskId)+ }+ setOpen(false)+ },+ onClose: () => setOpen(false),+ }if (todayRailEnabled && phoneLayout) {return (<>@@ -79,20 +94,7 @@ export function QuillAttachedContextPicker({<DialogTitle>Add context</DialogTitle></div><div data-not-quill className="min-h-0 flex-1 overflow-hidden px-5 pt-3">- <TaxonomicFilter- taxonomicFilterLogicKey={filterKey}- groupType={TaxonomicFilterGroupType.Events}- taxonomicGroupTypes={CONTEXT_PICKER_GROUP_TYPES}- onChange={({ type }, value, item) => {- if (value !== null) {- handleTaxonomicFilterChange(value, type, item)- }- setOpen(false)- }}- onClose={() => setOpen(false)}- width="100%"- height={window.innerHeight - 72}- />+ <TaxonomicFilter {...filterProps} width="100%" height={window.innerHeight - 72} /></div></DialogContent></Dialog>@@ -142,16 +144,7 @@ export function QuillAttachedContextPicker({className="[&_.LemonInput]:rounded-none! [&_.LemonInput]:border-x-0! [&_.LemonInput]:border-t-0! [&_.LemonInput]:bg-transparent! [&_.LemonInput]:shadow-none! [&_.taxonomic-infinite-list]:min-h-0"><TaxonomicFilter- taxonomicFilterLogicKey={filterKey}- groupType={TaxonomicFilterGroupType.Events}- taxonomicGroupTypes={CONTEXT_PICKER_GROUP_TYPES}- onChange={({ type }, value, item) => {- if (value !== null) {- handleTaxonomicFilterChange(value, type, item)- }- setOpen(false)- }}- onClose={() => setOpen(false)}+ {...filterProps}width={anchor ? '100%' : 450}height={anchor ? 240 : undefined}popoverEnabled={!anchor}diff --git a/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx b/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsxindex ee1424600953..bc0e3326b005 100644--- a/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx+++ b/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx@@ -118,11 +118,11 @@ export function QuillComposerLayout({<InputGroupAddonref={chipsRowRef}align="block-start"- className="min-h-0 overflow-hidden data-[ready=true]:transition-[height] data-[ready=true]:duration-200 data-[ready=true]:ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none!"+ className="min-h-0 overflow-hidden px-1.5 data-[ready=true]:transition-[height] data-[ready=true]:duration-200 data-[ready=true]:ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none!"><divref={chipsContentRef}- className="flex w-full flex-wrap items-center gap-2 pt-2.5 pb-1.5 [&_.LemonTag]:h-6 [&_.LemonTag]:gap-1 [&_.LemonTag]:rounded-sm [&_.LemonTag]:px-2 [&_.LemonTag]:text-xs *:transition-[opacity,translate] *:duration-[180ms] *:ease-[cubic-bezier(0.19,1,0.22,1)] *:starting:-translate-y-1 *:starting:opacity-0 motion-reduce:*:transition-[opacity] motion-reduce:*:starting:translate-y-0"+ className="flex w-full flex-wrap items-center gap-2 py-1.5 [&_.LemonTag]:h-6 [&_.LemonTag]:gap-1 [&_.LemonTag]:rounded-sm [&_.LemonTag]:px-2 [&_.LemonTag]:text-xs *:transition-[opacity,translate] *:duration-[180ms] *:ease-[cubic-bezier(0.19,1,0.22,1)] *:starting:-translate-y-1 *:starting:opacity-0 motion-reduce:*:transition-[opacity] motion-reduce:*:starting:translate-y-0">{chips}</div>diff --git a/products/posthog_ai/frontend/logics/chatContextLogic.ts b/products/posthog_ai/frontend/logics/chatContextLogic.tsnew file mode 100644index 000000000000..a2ae05772efd--- /dev/null+++ b/products/posthog_ai/frontend/logics/chatContextLogic.ts@@ -0,0 +1,185 @@+import { MakeLogicType, LogicWrapper, actions, connect, kea, key, listeners, path, props, selectors } from 'kea'++import { type AttachedContextItem, NEW_CHAT_KEY, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { type ChatChipsByTask, type ContextChip, contextChip } from '~/layout/ai/chatContextChips'++export interface ContextAttachment {+ chip: ContextChip+ previewHtml: string+}++function uniqueBy<T>(items: T[], keyOf: (item: T) => string): T[] {+ const seen = new Set<string>()+ return items.filter((item) => {+ const itemKey = keyOf(item)+ const isNew = !seen.has(itemKey)+ seen.add(itemKey)+ return isNew+ })+}++/**+ * What a send carries before dedupe. A surface that pins its context replaces the page's items, and still sends picks.+ */+export function chatSendItems(+ pageItems: AttachedContextItem[],+ picks: AttachedContextItem[],+ pinnedItems?: AttachedContextItem[]+): AttachedContextItem[] {+ return uniqueBy([...(pinnedItems ?? pageItems), ...picks], attachedContextItemKey)+}++export interface ChatContextLogicProps {+ taskId?: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chatContextLogicValues {+ chatChipsByTask: ChatChipsByTask // attachedContextLogic+ contextItems: AttachedContextItem[] // attachedContextLogic+ pickedByChat: Record<string, AttachedContextItem[]> // attachedContextLogic+ removedGroupsByTask: Record<string, string[]> // attachedContextLogic+ attachments: ContextAttachment[]+ chips: ContextChip[]+ pageItems: AttachedContextItem[]+ picks: AttachedContextItem[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chatContextLogicActions {+ dismissContext: (+ key: string,+ dismissGroup?: string | undefined+ ) => {+ dismissGroup: string | undefined+ key: string+ } // attachedContextLogic+ removeChatChip: (+ taskId: string,+ chipId: string,+ dismissGroup?: string | undefined+ ) => {+ chipId: string+ dismissGroup: string | undefined+ taskId: string+ } // attachedContextLogic+ removePickedItem: (+ key: string,+ taskId?: string | undefined+ ) => {+ key: string+ taskId: string+ } // attachedContextLogic+ removeChip: (chip: ContextChip) => {+ chip: ContextChip+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chatContextLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ picks: (pickedByChat: Record<string, AttachedContextItem[]>, arg: string) => AttachedContextItem[]+ pageItems: (+ contextItems: AttachedContextItem[],+ removedGroupsByTask: Record<string, string[]>,+ arg: string | undefined+ ) => AttachedContextItem[]+ chips: (+ chatChipsByTask: ChatChipsByTask,+ pageItems: AttachedContextItem[],+ picks: AttachedContextItem[],+ arg: string+ ) => ContextChip[]+ attachments: (pageItems: AttachedContextItem[]) => ContextAttachment[]+ }+}++export type chatContextLogicType = MakeLogicType<+ chatContextLogicValues,+ chatContextLogicActions,+ ChatContextLogicProps,+ chatContextLogicMeta+>++const chatKey = (_: unknown, props: ChatContextLogicProps): string => props.taskId || NEW_CHAT_KEY++/**+ * The one definition of what is in a chat: its saved chips, the items it takes from the current page, and its picks.+ * A new chat has no saved chips and takes everything on the page. A started chat keeps the chips it saved and takes+ * only the hidden items, because a visible item reaches it only through a pick.+ */+export const chatContextLogic: LogicWrapper<chatContextLogicType> = kea<chatContextLogicType>([+ props({} as ChatContextLogicProps),+ key(({ taskId }) => taskId || NEW_CHAT_KEY),+ path((logicKey) => ['products', 'posthog_ai', 'frontend', 'logics', 'chatContextLogic', logicKey]),++ connect(() => ({+ values: [attachedContextLogic, ['contextItems', 'chatChipsByTask', 'pickedByChat', 'removedGroupsByTask']],+ actions: [attachedContextLogic, ['dismissContext', 'removeChatChip', 'removePickedItem']],+ })),++ actions({+ removeChip: (chip: ContextChip) => ({ chip }),+ }),++ selectors({+ picks: [+ (s) => [s.pickedByChat, chatKey],+ (pickedByChat: Record<string, AttachedContextItem[]>, chat: string): AttachedContextItem[] =>+ pickedByChat[chat] ?? [],+ ],+ pageItems: [+ (s) => [s.contextItems, s.removedGroupsByTask, (_, p: ChatContextLogicProps) => p.taskId],+ (+ contextItems: AttachedContextItem[],+ removedGroupsByTask: Record<string, string[]>,+ taskId?: string+ ): AttachedContextItem[] => {+ if (!taskId) {+ return contextItems+ }+ const removedGroups = removedGroupsByTask[taskId] ?? []+ return contextItems.filter(+ (item) => item.hidden && !(item.dismissGroup && removedGroups.includes(item.dismissGroup))+ )+ },+ ],+ chips: [+ (s) => [s.chatChipsByTask, s.pageItems, s.picks, chatKey],+ (+ chatChipsByTask: ChatChipsByTask,+ pageItems: AttachedContextItem[],+ picks: AttachedContextItem[],+ chat: string+ ): ContextChip[] =>+ uniqueBy(+ [+ ...(chatChipsByTask[chat] ?? []),+ ...pageItems.filter((item) => !item.hidden && !item.previewHtml).map(contextChip),+ ...picks.map(contextChip),+ ],+ (chip) => chip.id+ ),+ ],+ attachments: [+ (s) => [s.pageItems],+ (pageItems: AttachedContextItem[]): ContextAttachment[] =>+ pageItems.flatMap((item) =>+ !item.hidden && item.previewHtml ? [{ chip: contextChip(item), previewHtml: item.previewHtml }] : []+ ),+ ],+ }),++ listeners(({ actions, values, props }) => ({+ removeChip: ({ chip }) => {+ actions.removePickedItem(chip.id, props.taskId)+ if (props.taskId) {+ actions.removeChatChip(props.taskId, chip.id, chip.dismissGroup)+ } else if (values.pageItems.some((item: AttachedContextItem) => attachedContextItemKey(item) === chip.id)) {+ actions.dismissContext(chip.id, chip.dismissGroup)+ }+ },+ })),+])diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.test.tsindex 3a5e7dbbd6ab..b3c528492564 100644--- a/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts@@ -5,7 +5,8 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { initKeaTests } from '~/test/init'-import { PICKER_PROVIDER_ID, contextPickerLogic, taxonomicItemToAttachedContext } from './contextPickerLogic'+import { chatContextLogic, chatSendItems } from './chatContextLogic'+import { contextPickerLogic, taxonomicItemToAttachedContext } from './contextPickerLogic'describe('contextPickerLogic', () => {let store: ReturnType<typeof attachedContextLogic.build>@@ -48,42 +49,80 @@ describe('contextPickerLogic', () => {).toBeNull()})- it('picks flow into the store, removal and unmount take them back out', async () => {+ // A pick that missed the new chat's chips or its send would vanish without any error, and a dismissal must not block it.+ it('shows and sends a new chat pick, even of an item the user dismissed, until the chip is closed', async () => {+ store.actions.registerContext('bridge', [{ type: 'insight', key: 'abc123', label: 'DAU' }])+ store.actions.dismissContext('insight:abc123')+ const chat = chatContextLogic({})+ chat.mount()+await expectLogic(logic, () => {logic.actions.handleTaxonomicFilterChange('abc123', TaxonomicFilterGroupType.Insights, {short_id: 'abc123',name: 'DAU',})}).toFinishAllListeners()- expect(store.values.contextItems).toEqual([{ type: 'insight', key: 'abc123', label: 'DAU' }])- await expectLogic(logic, () => {- logic.actions.removePickedItem('insight:abc123')- }).toFinishAllListeners()- expect(store.values.contextItems).toEqual([])+ expect(chat.values.chips.map((chip) => chip.id)).toEqual(['insight:abc123'])+ expect(chatSendItems(chat.values.pageItems, chat.values.picks)).toEqual([+ { type: 'insight', key: 'abc123', label: 'DAU' },+ ])- await expectLogic(logic, () => {- logic.actions.handleTaxonomicFilterChange('7', TaxonomicFilterGroupType.Dashboards, {- id: 7,- name: 'Growth',- })- }).toFinishAllListeners()- logic.unmount()- expect(store.values.providers[PICKER_PROVIDER_ID]).toBeUndefined()- expect(store.values.contextItems).toEqual([])+ chat.actions.removeChip(chat.values.chips[0])++ expect(chat.values.chips).toEqual([])+ chat.unmount()})- it('re-picking a dismissed item restores it', async () => {- store.actions.registerContext('bridge', [{ type: 'insight', key: 'abc123', label: 'DAU' }])- store.actions.dismissContext('insight:abc123')- expect(store.values.contextItems).toEqual([])+ // Closing a chip that is both a pick and on the page must hide it, or it would stay in the composer.+ it('removes a chip that is both picked and on the current page', () => {+ const item = { type: 'dashboard', key: 7, label: 'Growth' }+ store.actions.registerContext('bridge', [item])+ store.actions.pickItem(item)+ const chat = chatContextLogic({})+ chat.mount()+ expect(chat.values.chips).toHaveLength(1)- await expectLogic(logic, () => {- logic.actions.handleTaxonomicFilterChange('abc123', TaxonomicFilterGroupType.Insights, {- short_id: 'abc123',- name: 'DAU',- })- }).toFinishAllListeners()- expect(store.values.contextItems).toEqual([{ type: 'insight', key: 'abc123', label: 'DAU' }])+ chat.actions.removeChip(chat.values.chips[0])++ expect(chat.values.chips).toEqual([])+ chat.unmount()+ })++ // Removing a chip must stop its hidden payload, or a closed worksheet keeps sending its draft on every follow-up.+ it('stops sending a removed chip group in that started chat only, and across a re-registration', () => {+ const dismissGroup = 'bi-worksheet:abc'+ const worksheet = { type: 'insight', key: 'abc', label: 'Saved worksheet', dismissGroup }+ const metric = { type: 'data_catalog_metric', key: 'mrr', label: 'mrr', dismissGroup }+ const draft = { type: 'text', hidden: true, dismissGroup, value: 'worksheet draft' }+ store.actions.registerContext('bi', [worksheet, metric, draft])+ store.actions.contextDelivered('task-a', [worksheet, metric, draft])+ store.actions.contextDelivered('task-b', [worksheet, metric, draft])+ const chatA = chatContextLogic({ taskId: 'task-a' })+ const chatB = chatContextLogic({ taskId: 'task-b' })+ chatA.mount()+ chatB.mount()+ expect(chatA.values.pageItems).toEqual([draft])++ chatA.actions.removeChip(chatA.values.chips[0])+ store.actions.registerContext('bi', [worksheet, metric, { ...draft, value: 'edited draft' }])++ expect(chatA.values.chips).toEqual([])+ expect(chatA.values.pageItems).toEqual([])+ expect(chatB.values.pageItems.map((item) => item.value)).toEqual(['edited draft'])+ expect(chatB.values.chips).toHaveLength(2)+ chatA.unmount()+ chatB.unmount()+ })++ it('clears a new chat draft only when the new chat delivers it, not when another chat does', () => {+ const pick = { type: 'dashboard', key: 7, label: 'Growth' }+ store.actions.pickItem(pick)++ store.actions.contextDelivered('another-task', [pick])+ expect(store.values.pickedByChat['']).toEqual([pick])++ store.actions.contextDelivered('created-task', [pick], true)+ expect(store.values.pickedByChat['']).toEqual([])})})diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.tsindex 6112dfc6482e..8bb523cf96fb 100644--- a/products/posthog_ai/frontend/logics/contextPickerLogic.ts+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.ts@@ -1,24 +1,10 @@-import {- MakeLogicType,- actions,- connect,- events,- kea,- listeners,- path,- reducers,- selectors,- sharedListeners,-} from 'kea'-import type { BreakPointFunction } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { type AttachedContextItem, NEW_CHAT_KEY } from '~/layout/ai/attachedContext'import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'-export const PICKER_PROVIDER_ID = 'user-picker'-/** The group types the composer's @-picker offers. Keep in sync with `taxonomicItemToAttachedContext`. */export const CONTEXT_PICKER_GROUP_TYPES: TaxonomicFilterGroupType[] = [TaxonomicFilterGroupType.Events,@@ -67,84 +53,35 @@ export function taxonomicItemToAttachedContext(}}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface contextPickerLogicValues {- pickedItems: AttachedContextItem[]- pickedKeys: Set<string>-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface contextPickerLogicActions {- deregisterContext: (providerId: string) => {- providerId: string- } // attachedContextLogic- registerContext: (- providerId: string,- items: AttachedContextItem[]- ) => {- items: AttachedContextItem[]- providerId: string- } // attachedContextLogic- undismissContext: (- key: string,- dismissGroup?: string | undefined+ pickItem: (+ item: AttachedContextItem,+ taskId?: string | undefined) => {- dismissGroup: string | undefined- key: string+ item: AttachedContextItem+ taskId: string} // attachedContextLogichandleTaxonomicFilterChange: (value: number | string,groupType: TaxonomicFilterGroupType,- item: PickableTaxonomicItem+ item: PickableTaxonomicItem,+ taskId?: string) => {groupType: TaxonomicFilterGroupTypeitem: PickableTaxonomicItem+ taskId: stringvalue: number | string}- pickItem: (item: AttachedContextItem) => {- item: AttachedContextItem- }- removePickedItem: (key: string) => {- key: string- }}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface contextPickerLogicMeta {- sharedListeners: {- syncProvider: (- payload: any,- breakpoint: BreakPointFunction,- action: {- type: string- payload: any- },- previousState: any- ) => void | Promise<void>- }- __keaTypeGenInternalSelectorTypes: {- pickedKeys: (pickedItems: AttachedContextItem[]) => Set<string>- }-}--export type contextPickerLogicType = MakeLogicType<- contextPickerLogicValues,- contextPickerLogicActions,- Record<string, any>,- contextPickerLogicMeta->+export type contextPickerLogicType = MakeLogicType<{}, contextPickerLogicActions>-/**- * Global store of context the user explicitly picked via the composer's @-affordance. Just another- * provider on `attachedContextLogic` (id `user-picker`): picks upsert into `pickedItems`, and every- * change re-registers the provider, so picked refs flow into `contextItems` and the send-time- * context-block wrap with zero extra plumbing.- */export const contextPickerLogic = kea<contextPickerLogicType>([path(['products', 'posthog_ai', 'frontend', 'logics', 'contextPickerLogic']),connect(() => ({- actions: [attachedContextLogic, ['registerContext', 'deregisterContext', 'undismissContext']],+ actions: [attachedContextLogic, ['pickItem']],})),actions({@@ -152,65 +89,17 @@ export const contextPickerLogic = kea<contextPickerLogicType>([handleTaxonomicFilterChange: (value: string | number,groupType: TaxonomicFilterGroupType,- item: PickableTaxonomicItem- ) => ({ value, groupType, item }),- pickItem: (item: AttachedContextItem) => ({ item }),- removePickedItem: (key: string) => ({ key }),- }),-- reducers({- pickedItems: [- [] as AttachedContextItem[],- {- pickItem: (state, { item }) => {- const key = attachedContextItemKey(item)- return state.filter((existing) => attachedContextItemKey(existing) !== key).concat(item)- },- removePickedItem: (state, { key }) =>- state.filter((existing) => attachedContextItemKey(existing) !== key),- },- ],- }),-- selectors({- pickedKeys: [- (s) => [s.pickedItems],- (pickedItems: AttachedContextItem[]): Set<string> => new Set(pickedItems.map(attachedContextItemKey)),- ],+ item: PickableTaxonomicItem,+ taskId: string = NEW_CHAT_KEY+ ) => ({ value, groupType, item, taskId }),}),- sharedListeners(({ actions, values }) => ({- syncProvider: () => {- actions.registerContext(PICKER_PROVIDER_ID, values.pickedItems)- },- })),-- listeners(({ actions, sharedListeners }) => ({- handleTaxonomicFilterChange: ({ value, groupType, item }) => {+ listeners(({ actions }) => ({+ handleTaxonomicFilterChange: ({ value, groupType, item, taskId }) => {const attached = taxonomicItemToAttachedContext(value, groupType, item)- if (!attached) {- return+ if (attached) {+ actions.pickItem(attached, taskId)}- // Re-picking something the user previously closed must bring it back.- actions.undismissContext(attachedContextItemKey(attached))- actions.pickItem(attached)- },- pickItem: sharedListeners.syncProvider,- removePickedItem: sharedListeners.syncProvider,- })),-- events(({ actions, cache, values }) => ({- afterMount: () => {- // `pauseOnPageHidden: false`: a hide-paused registration would drop picked context from a- // queued follow-up that flushes while the tab is hidden; the registration is idle-cost-free.- cache.disposables.add(- () => {- actions.registerContext(PICKER_PROVIDER_ID, values.pickedItems)- return () => actions.deregisterContext(PICKER_PROVIDER_ID)- },- 'contextPicker',- { pauseOnPageHidden: false }- )},})),])diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 7af438f45173..2853b6336f7d 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -215,6 +215,7 @@ describe('runInteractionLogic', () => {;(tasksRunCreate as jest.Mock).mockResolvedValue({ run: { id: 'run-2' }, latest_run: { id: 'run-2' } });(tasksRunsClearConversationCreate as jest.Mock).mockResolvedValue({});(tasksWarmResumeCreate as jest.Mock).mockResolvedValue({ task_id: TASK_ID, run_id: 'warm-run' })+ window.localStorage.clear()initKeaTests()project = projectLogic()project.mount()@@ -1027,7 +1028,9 @@ describe('runInteractionLogic', () => {it('does nothing on an empty queue and keeps unsent context after failed steering', async () => {setThinking(true)const context = attachedContextLogic()- context.actions.registerContext('test', [{ type: 'insight', key: 'fake', value: 'example insight' }])+ context.actions.registerContext('test', [+ { type: 'insight', key: 'fake', value: 'example insight', hidden: true },+ ])logic.actions.setComposerFormValues({ draft: 'unsent' })logic.actions.steerQueue()expect(tasksRunsCommandCreate).not.toHaveBeenCalled()@@ -1527,7 +1530,9 @@ describe('runInteractionLogic', () => {rejectSend = reject}))- attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'sig', label: 'Signups' }])+ attachedContextLogic().actions.registerContext('scene', [+ { type: 'insight', key: 'sig', label: 'Signups', hidden: true },+ ])setStatus('completed')logic.actions.setComposerFormValues({ draft: 'continue from here' })logic.actions.submitComposerForm()@@ -1544,7 +1549,9 @@ describe('runInteractionLogic', () => {expect(onRunStarted).not.toHaveBeenCalled()expect(logic.values.startingRun).toBe(false)expect(logic.values.composerForm.draft).toBe('continue from here')- expect(logic.values.pendingContextItems).toEqual([{ type: 'insight', key: 'sig', label: 'Signups' }])+ expect(logic.values.pendingContextItems).toEqual([+ { type: 'insight', key: 'sig', label: 'Signups', hidden: true },+ ])expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()@@ -1582,7 +1589,7 @@ describe('runInteractionLogic', () => {)try {attachedContextLogic().actions.registerContext('scene', [- { type: 'insight', key: 'sig', label: 'Signups' },+ { type: 'insight', key: 'sig', label: 'Signups', hidden: true },])setStatus('completed')logic.actions.setComposerFormValues({ draft: 'continue from here' })@@ -1634,7 +1641,7 @@ describe('runInteractionLogic', () => {expect(onRunStarted).not.toHaveBeenCalled()expect(logic.values.composerForm.draft).toBe('continue from here')expect(logic.values.pendingContextItems).toEqual([- { type: 'insight', key: 'sig', label: 'Signups' },+ { type: 'insight', key: 'sig', label: 'Signups', hidden: true },])expect(lemonToast.error).toHaveBeenCalledWith("Couldn't start this run yet. Please try again.")resolveRetry({ latest_run: { id: 'late-run' } })@@ -1649,12 +1656,12 @@ describe('runInteractionLogic', () => {it.each(['global', 'runner'])('wraps and deduplicates %s context while echoing raw text', async (scope) => {const contextItems = [- { type: 'insight', key: 'sig', label: 'Signups' },- { type: 'text', value: 'always resend me' },+ { type: 'insight', key: 'sig', label: 'Signups', hidden: true },+ { type: 'text', value: 'always resend me', hidden: true },]attachedContextLogic().actions.registerContext('scene',- scope === 'global' ? contextItems : [{ type: 'text', value: 'unrelated scene context' }]+ scope === 'global' ? contextItems : [{ type: 'text', value: 'unrelated scene context', hidden: true }])if (scope === 'runner') {logic.unmount()@@ -1697,11 +1704,52 @@ describe('runInteractionLogic', () => {expect(secondSend.params.content.endsWith('follow up')).toBe(true)})+ it('sends a pick but not the visible context of the current page, and keeps the pick on a failed send', async () => {+ const pick = { type: 'dashboard', key: 7, label: 'Weekly' }+ attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'nav', label: 'Other page' }])+ attachedContextLogic().actions.pickItem(pick, TASK_ID)+ setThinking(false)+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))++ logic.actions.setComposerFormValues({ draft: 'follow up' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ expect(attachedContextLogic().values.pickedByChat[TASK_ID]).toEqual([pick])+ expect(attachedContextLogic().values.chatChipsByTask[TASK_ID]).toBeUndefined()+ ;(tasksRunsCommandCreate as jest.Mock).mockClear()++ logic.actions.setComposerFormValues({ draft: 'follow up' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ const send = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }+ expect(send.params.content).toContain('- dashboard 7 ("Weekly")')+ expect(send.params.content).not.toContain('- insight nav')+ expect(attachedContextLogic().values.chatChipsByTask[TASK_ID].map((chip) => chip.id)).toEqual(['dashboard:7'])+ expect(attachedContextLogic().values.pickedByChat[TASK_ID]).toEqual([])+ })++ it('leaves a pick made in another chat out of this chat', async () => {+ attachedContextLogic().actions.pickItem({ type: 'dashboard', key: 7, label: 'Weekly' }, 'another-task')+ setThinking(false)++ logic.actions.setComposerFormValues({ draft: 'follow up' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ const send = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }+ expect(send.params.content).not.toContain('- dashboard 7')+ })+it('prunes context whose rendered line the run log already carries, even with no sent-key bookkeeping', async () => {// The reload scenario: `sentContextKeysByTask` is empty (fresh session), but `runStreamLogic`// recorded the block lines it found replaying the resume-chain history — the same ref must not// be re-wrapped into the next send.- const seenItem = { type: 'insight', key: 'sig', label: 'Signups' }+ const seenItem = { type: 'insight', key: 'sig', label: 'Signups', hidden: true }attachedContextLogic().actions.registerContext('scene', [seenItem])attachedContextLogic().actions.markContextLinesSeen(TASK_ID, [contextItemLine(seenItem)])setThinking(false)@@ -1717,7 +1765,7 @@ describe('runInteractionLogic', () => {})it('sends /clear unwrapped so the agent still sees the command at the front, and keeps the context pending', async () => {- const item = { type: 'insight', key: 'sig', label: 'Signups' }+ const item = { type: 'insight', key: 'sig', label: 'Signups', hidden: true }attachedContextLogic().actions.registerContext('scene', [item])setThinking(false)@@ -1742,7 +1790,9 @@ describe('runInteractionLogic', () => {})it('keeps pruning context sent by a terminal-run send after re-pointing to the fresh run', async () => {- attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'sig', label: 'Signups' }])+ attachedContextLogic().actions.registerContext('scene', [+ { type: 'insight', key: 'sig', label: 'Signups', hidden: true },+ ])// A send on a finished run starts a fresh run, wrapping the pending context into its seed message.setStatus('completed')diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 8a5c4ab5c84b..8b9af64334df 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -58,6 +58,7 @@ import type { PendingAttachment } from '../utils/attachments'import { extractCommentContexts, withCommentContexts } from '../utils/commentContext'import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'import { submitWithWarmRunRetry } from '../utils/warmRunSubmission'+import { chatContextLogic, chatSendItems } from './chatContextLogic'import { codexBillingLogic, pickedCodexModelAccess, usesChatGptPlan } from './codexBillingLogic'import { composerAttachmentsLogic } from './composerAttachmentsLogic'import { modelCatalogueLogic } from './modelCatalogueLogic'@@ -180,9 +181,10 @@ function runStartFailureMessage(error: unknown): string {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface runInteractionLogicValues {dataProcessingAccepted: boolean // aiConsentLogic- contextItems: AttachedContextItem[] // attachedContextLogicseenContextLinesByTask: Record<string, string[]> // attachedContextLogicsentContextKeysByTask: Record<string, string[]> // attachedContextLogic+ pageItems: AttachedContextItem[] // chatContextLogic+ picks: AttachedContextItem[] // chatContextLogicqueuedAttachments: PendingAttachment[] // composerAttachmentsLogicstagedAttachments: PendingAttachment[] // composerAttachmentsLogiccatalogue: ModelChoiceApi[] // modelCatalogueLogic@@ -228,6 +230,7 @@ export interface runInteractionLogicValues {>consentBlocked: booleanconsentBlockedSource: 'draft' | 'queue' | 'steer'+ contextCandidates: AttachedContextItem[]deferredSteerRequestId: string | nulldraftRecovery: DraftRecoveryeffortOverride: string | null@@ -260,11 +263,13 @@ export interface runInteractionLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface runInteractionLogicActions {- markContextSent: (+ contextDelivered: (taskId: string,- keys: string[]+ items: AttachedContextItem[],+ fromNewChat?: boolean | undefined) => {- keys: string[]+ fromNewChat: boolean+ items: AttachedContextItem[]taskId: string} // attachedContextLogicclaimAttachmentsForQueue: () => {@@ -611,11 +616,16 @@ export interface runInteractionLogicMeta {) => booleanqueueHeld: (queuedMessages: QueuedMessage[], queueHold: QueueHold) => booleanisSubmitting: (sending: boolean, startingRun: boolean, clearing: boolean) => boolean+ contextCandidates: (+ pageItems: AttachedContextItem[],+ picks: AttachedContextItem[],+ arg: AttachedContextItem[] | undefined+ ) => AttachedContextItem[]pendingContextItems: (- arg: AttachedContextItem[],+ contextCandidates: AttachedContextItem[],sentContextKeysByTask: Record<string, string[]>,seenContextLinesByTask: Record<string, string[]>,- arg2: string+ arg: string) => AttachedContextItem[]}}@@ -691,7 +701,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>(['bootstrappedTaskId',],attachedContextLogic,- ['contextItems', 'sentContextKeysByTask', 'seenContextLinesByTask'],+ ['sentContextKeysByTask', 'seenContextLinesByTask'],+ chatContextLogic({ taskId: props.taskId }),+ ['pageItems', 'picks'],aiConsentLogic,['dataProcessingAccepted'],modelCatalogueLogic,@@ -725,7 +737,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>(['reset as resetStream',],attachedContextLogic,- ['markContextSent'],+ ['contextDelivered'],toolStreamEventsLogic,['claimApplyBackTargets', 'releaseApplyBackTargets'],runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),@@ -1166,6 +1178,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([(s) => [s.sending, s.startingRun, s.clearing],(sending: boolean, startingRun: boolean, clearing: boolean): boolean => sending || startingRun || clearing,],+ contextCandidates: [+ (s) => [s.pageItems, s.picks, (_, p: RunInteractionLogicProps) => p.contextItems],+ (+ pageItems: AttachedContextItem[],+ picks: AttachedContextItem[],+ pinnedItems: AttachedContextItem[] | undefined+ ): AttachedContextItem[] => chatSendItems(pageItems, picks, pinnedItems),+ ],// Attached context not yet wrapped into a message for this task, the snapshot the next send wraps.// Two dedupe layers, both task-scoped (not run-scoped, so the dedupe survives a terminal-run send// re-pointing to a fresh run instance): the in-memory sent keys marked by this session's sends, and@@ -1175,20 +1195,20 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// text is intentional, e.g. consecutive error snippets).pendingContextItems: [(s) => [- (state, p: RunInteractionLogicProps) => p.contextItems ?? s.contextItems(state, p),+ s.contextCandidates,s.sentContextKeysByTask,s.seenContextLinesByTask,(_, p: RunInteractionLogicProps) => p.taskId,],(- contextItems: AttachedContextItem[],+ contextCandidates: AttachedContextItem[],sentContextKeysByTask: Record<string, string[]>,seenContextLinesByTask: Record<string, string[]>,taskId: string): AttachedContextItem[] => {const sentKeys = new Set(sentContextKeysByTask[taskId] ?? [])const seenLines = new Set(seenContextLinesByTask[taskId] ?? [])- return contextItems.filter(+ return contextCandidates.filter((item) =>item.type === 'text' ||(!sentKeys.has(attachedContextItemKey(item)) && !seenLines.has(contextItemLine(item)))@@ -1256,17 +1276,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([return contexts.length > 0 ? text : content}- const restoreQueuedRows = (rows: QueuedMessage[], content: string): void => {- actions.prependQueuedMessages(rows.length > 0 ? rows : [{ id: nextQueuedMessageId(), content }])+ // Dedupe can prune an item from the wire, such as a re-pick, but the chat still holds it. Recording the whole+ // set stops every later send in the resume chain from re-inflating it.+ const recordDelivery = (items: AttachedContextItem[]): void => {+ actions.contextDelivered(props.taskId, items)}- // Record the non-text refs just wrapped into a send under the task, so no later send anywhere in- // the task's resume chain (including the next run after a terminal-run send) re-inflates them.- const markPendingContextSent = (pendingContext: AttachedContextItem[]): void => {- const sentKeys = pendingContext.filter((item) => item.type !== 'text').map(attachedContextItemKey)- if (sentKeys.length > 0) {- actions.markContextSent(props.taskId, sentKeys)- }+ const restoreQueuedRows = (rows: QueuedMessage[], content: string): void => {+ actions.prependQueuedMessages(rows.length > 0 ? rows : [{ id: nextQueuedMessageId(), content }])}return {@@ -1429,6 +1446,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// `/clear` goes unwrapped: a context block would hide the command behind it (the// agent reads the command off the front) and mark refs sent that nothing ever read.const pendingContext = isClearCommand(content) ? [] : values.pendingContextItems+ const deliveredContext = isClearCommand(content) ? [] : values.contextCandidatesactions.claimApplyBackTargets(streamKey)// Clear the draft synchronously before the await so text the user types while the send is in// flight isn't clobbered when the request resolves; a failed send restores it ahead of anything@@ -1539,7 +1557,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// The SSE echo (`pushHumanMessage`) reopens the turn — always the raw text the user typed.// The names ride along so the chips show on send, not when the turn echoes back.actions.pushHumanMessage(content, stageAttachmentPreviews(sending))- markPendingContextSent(pendingContext)+ recordDelivery(deliveredContext)// One attached while this send was in flight belongs to the next message.actions.removeAttachments(sending.map((attachment) => attachment.id))actions.finishTaskDraftDelivery()@@ -1624,6 +1642,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([actions.setStartingRun(true)const streamKey = props.streamKey ?? props.runIdconst pendingContext = values.pendingContextItems+ const deliveredContext = values.contextCandidatesconst disposables = cache.disposablesconst projectId = String(values.currentProjectId)const taskId = props.taskId@@ -1719,7 +1738,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([}accepted = trueactions.finishTaskDraftDelivery()- markPendingContextSent(pendingContext)+ recordDelivery(deliveredContext)// A failure leaves them staged for the retry.actions.removeAttachments(sending.map((attachment) => attachment.id))props.flushDraft?.()diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsxindex 57c9e2208dca..3bc07ac95b04 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx@@ -45,6 +45,7 @@ import { ComposerModePicker } from '../../../components/composer/ComposerModePicimport { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'import { OnboardingReplayButton } from '../../../components/onboarding/OnboardingReplayButton'+import { QuillAttachedContextChips } from '../../../components/quill/QuillAttachedContextChips'import { QuillAttachedContextPicker } from '../../../components/quill/QuillAttachedContextPicker'import { QuillComposerLayout } from '../../../components/quill/QuillComposerLayout'import { QuillComposerSendButton } from '../../../components/quill/QuillComposerSendButton'@@ -297,7 +298,7 @@ export function TaskComposer({onToggleDefault={toggleDefaultRepository}/>)}- <AttachedContextChips />+ <QuillAttachedContextChips /><ComposerAttachmentChips attachmentsKey={attachmentsKey} /></>}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsxindex 40021f2c2dd3..b7501fbe06d3 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx@@ -44,6 +44,7 @@ import { ComposerModePicker } from '../../../components/composer/ComposerModePicimport { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'import { ContextUsageChip } from '../../../components/ContextUsageChip'+import { QuillAttachedContextChips } from '../../../components/quill/QuillAttachedContextChips'import { QuillAttachedContextPicker } from '../../../components/quill/QuillAttachedContextPicker'import { QuillComposerLayout } from '../../../components/quill/QuillComposerLayout'import { QuillComposerSendButton } from '../../../components/quill/QuillComposerSendButton'@@ -282,7 +283,7 @@ export function TaskRunComposer({<>{repository && <QuillRunRepositoryChip repository={repository} branch={branch} />}{logicProps.taskId && <CommentContextChips logicProps={logicProps} />}- <AttachedContextChips />+ <QuillAttachedContextChips taskId={logicProps.taskId} /><ComposerAttachmentChips attachmentsKey={attachmentsKey} /></>}@@ -296,6 +297,7 @@ export function TaskRunComposer({onAddContext={() => setContextPickerOpen(true)}/><QuillAttachedContextPicker+ taskId={logicProps.taskId}open={contextPickerOpen}onOpenChange={setContextPickerOpen}anchor={groupRef}@@ -318,13 +320,13 @@ export function TaskRunComposer({<Composer.Frame ref={labelRef}><Composer.Header className="flex flex-wrap items-center gap-2 empty:hidden">{logicProps.taskId && <CommentContextChips logicProps={logicProps} />}- <AttachedContextChips />+ <AttachedContextChips taskId={logicProps.taskId} /><ComposerAttachmentChips attachmentsKey={attachmentsKey} /></Composer.Header>{field}<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2"><ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={labelRef} />- <AttachedContextPicker />+ <AttachedContextPicker taskId={logicProps.taskId} />{pickers(modelPicker, modePicker)}<div className="ml-auto"><ContextUsageChip />diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 7c55906302de..e7bca4a5a682 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -799,6 +799,9 @@ describe('taskTrackerSceneLogic', () => {expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({'new-task': source === 'both' ? ['insight:scene-sig', 'insight:sig'] : ['insight:sig'],})+ expect(attachedContextLogic().values.chatChipsByTask['new-task'].map((chip) => chip.id)).toEqual(+ source === 'both' ? ['insight:scene-sig', 'insight:sig', 'text:Text'] : ['insight:sig', 'text:Text']+ )expect(logic.values.newTaskData.seedContextItems).toBeUndefined()expect(attachedContextLogic().values.contextItems).toHaveLength(source === 'seed' ? 0 : source === 'both' ? 1 : 2@@ -806,6 +809,27 @@ describe('taskTrackerSceneLogic', () => {})+ // A pinned surface replaces the page's context, but the user's own pick must still reach the first message.+ it('sends a new chat pick alongside pinned context and clears the draft', async () => {+ const pinned = taskTrackerSceneLogic({+ panelId: 'pinned-context',+ contextItems: [{ type: 'insight', key: 'pinned', label: 'Pinned' }],+ })+ pinned.mount()+ attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'page', label: 'Page' }])+ attachedContextLogic().actions.pickItem({ type: 'dashboard', key: 7, label: 'Weekly' })++ pinned.actions.setNewTaskData({ description: 'why the drop?' })+ pinned.actions.submitNewTask()+ await expectLogic(pinned).toFinishAllListeners()++ expect(runBody?.pending_user_message).toContain('- insight pinned ("Pinned")')+ expect(runBody?.pending_user_message).toContain('- dashboard 7 ("Weekly")')+ expect(runBody?.pending_user_message).not.toContain('- insight page')+ expect(attachedContextLogic().values.pickedByChat['']).toEqual([])+ pinned.unmount()+ })+// The tasks backend has no server-side consent check (unlike the conversations coordinator), so a// send must be blocked client-side before it ever reaches `api.tasks.create` — otherwise a sandbox// run starts with zero consent enforcement. Warming is held to the same rule: it boots a clouddiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex de72d659010a..e6e1d746facc 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -15,7 +15,6 @@ import { projectLogic } from 'scenes/projectLogic'import { urls } from 'scenes/urls'import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'-import { attachedContextItemKey } from '~/layout/ai/attachedContext'import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'@@ -45,6 +44,7 @@ import type { IntegrationType } from '../../../../../frontend/src/types'import { runStreamLogic } from '../../api/logics'import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'+import { chatContextLogic, chatSendItems } from '../../logics/chatContextLogic'import {CodexBillingUnresolvedError,codexBillingLogic,@@ -202,7 +202,8 @@ const EMPTY_TASK_FORM: TaskCreateForm = {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskTrackerSceneLogicValues {dataProcessingAccepted: boolean // aiConsentLogic- contextItems: AttachedContextItem[] // attachedContextLogic+ pageItems: AttachedContextItem[] // chatContextLogic+ picks: AttachedContextItem[] // chatContextLogicstagedAttachments: PendingAttachment[] // composerAttachmentsLogiccomposerOverride: ComposerOverride | null // composerOverrideLogicseed: ComposerSeed | null // composerSeedLogic@@ -256,11 +257,13 @@ export interface taskTrackerSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskTrackerSceneLogicActions {- markContextSent: (+ contextDelivered: (taskId: string,- keys: string[]+ items: AttachedContextItem[],+ fromNewChat?: boolean | undefined) => {- keys: string[]+ fromNewChat: boolean+ items: AttachedContextItem[]taskId: string} // attachedContextLogicaddFiles: (files: File[]) => {@@ -526,8 +529,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['tasks', 'repositories', 'taskListParams'],integrationsLogic,['integrations', 'githubIntegrations'],- attachedContextLogic,- ['contextItems'],+ chatContextLogic({}),+ ['pageItems', 'picks'],aiConsentLogic,['dataProcessingAccepted'],projectLogic,@@ -566,7 +569,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([integrationsLogic,['loadIntegrationsSuccess'],attachedContextLogic,- ['markContextSent'],+ ['contextDelivered'],toolStreamEventsLogic,['claimApplyBackTargets', 'releaseApplyBackTargets'],composerSeedLogic(props),@@ -1017,7 +1020,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// instance by binding this `streamKey`). Released by `clearActiveCreation` (failure / leaving the run).const streamKey = `draft-${uuid()}`const seededContext = [- ...(props.contextItems ?? values.contextItems),+ ...chatSendItems(values.pageItems, values.picks, props.contextItems),...(values.newTaskData.seedContextItems ?? []),]actions.claimApplyBackTargets(streamKey)@@ -1211,12 +1214,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([throw new Error('Run creation did not return a run ID')}- // Mark the seeded non-text refs sent under the created task, so the run's first follow-up- // (sent via `runInteractionLogic`) doesn't re-wrap them. Text items always resend.- const seededKeys = seededContext.filter((item) => item.type !== 'text').map(attachedContextItemKey)- if (seededKeys.length > 0) {- actions.markContextSent(newTask.id, seededKeys)- }+ // Recording the seed under the created task stops the run's first follow-up (sent via+ // `runInteractionLogic`) from re-wrapping it, and freezes it as the chat's chips.+ actions.contextDelivered(newTask.id, seededContext, true)const creationIsActive = values.activeCreation?.streamKey === streamKeyif (creationIsActive) {diff --git a/products/posthog_ai/frontend/utils/contextItemLink.test.ts b/products/posthog_ai/frontend/utils/contextItemLink.test.tsnew file mode 100644index 000000000000..9a8496e43384--- /dev/null+++ b/products/posthog_ai/frontend/utils/contextItemLink.test.ts@@ -0,0 +1,35 @@+import { contextItemPath, isOnContextItemPage } from './contextItemLink'++describe('contextItemLink', () => {+ test.each([+ [{ type: 'experiment', key: 17 }, '/experiments/17'],+ [{ type: 'feature_flag', key: 'new-checkout', pageId: 12 }, '/feature-flags/12'],+ [{ type: 'feature_flag', key: '99', pageId: 12 }, '/feature-flags/12'],+ [{ type: 'feature_flag', key: 'new-checkout', pageId: null }, null],+ [{ type: 'error_tracking_issue', key: 'issue-id' }, '/error_tracking/issue-id'],+ [{ type: 'signal_report', key: 'report-id' }, '/inbox/report-id'],+ [{ type: 'insight', key: 'aBc123' }, '/insights/aBc123'],+ [{ type: 'insight', key: 17, pageId: 'aBc123' }, '/insights/aBc123'],+ [{ type: 'notebook', key: 'note123' }, '/notebooks/note123'],+ // An event item's key is the event name, and the event page needs a definition id.+ [{ type: 'event', key: '$pageview' }, null],+ [{ type: 'text', value: 'Some note' }, null],+ [{ type: 'experiment' }, null],+ ])('links %o to %s', (item, expected) => {+ expect(contextItemPath(item)).toEqual(expected)+ })++ test.each([+ ['/project/1/experiments/17', '/experiments/17', true],+ ['/project/1/experiments/17/', '/experiments/17', true],+ ['/project/1/notebooks/note123/', '/notebooks/note123', true],+ ['/project/1/insights/aBc123/edit', '/insights/aBc123', true],+ ['/project/1/insights/aBc123/alerts/7', '/insights/aBc123', true],+ ['/project/1/insights/aBc124/edit', '/insights/aBc123', false],+ ['/project/1/experiments/17/edit', '/experiments/17', true],+ ['/project/1/experiments/170', '/experiments/17', false],+ ['/project/1/feature-flags/12', '/experiments/17', false],+ ])('on %s, the page %s is current: %s', (pathname, path, expected) => {+ expect(isOnContextItemPage(path, pathname)).toBe(expected)+ })+})diff --git a/products/posthog_ai/frontend/utils/contextItemLink.ts b/products/posthog_ai/frontend/utils/contextItemLink.tsnew file mode 100644index 000000000000..ff4f69c83d84--- /dev/null+++ b/products/posthog_ai/frontend/utils/contextItemLink.ts@@ -0,0 +1,35 @@+import { objectKindLink } from 'lib/components/AgentObjectTags/rewriteAgentObjectTags'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { urls } from 'scenes/urls'++import type { AttachedContextItem } from '~/layout/ai/attachedContext'++const OBJECT_KIND_BY_CONTEXT_TYPE: Record<string, string> = {+ error_tracking_issue: 'error',+ signal_report: 'report',+}++function pathOnly(url: string): string {+ return url.split(/[?#]/)[0].replace(/\/+$/, '')+}++export function contextItemPath(item: Pick<AttachedContextItem, 'type' | 'key' | 'pageId'>): string | null {+ const pageId = item.pageId === undefined ? item.key : item.pageId+ if (pageId === undefined || pageId === null || pageId === '') {+ return null+ }+ if (item.type === 'notebook') {+ return urls.notebook(String(pageId))+ }+ return objectKindLink(OBJECT_KIND_BY_CONTEXT_TYPE[item.type] ?? item.type, String(pageId), '').url+}++/**+ * Whether the browser already shows that page, so a click on the chip must not navigate. A sub-route such as+ * `/insights/:id/edit` shows the same resource, and a click would leave the mode the user is in.+ */+export function isOnContextItemPage(path: string, pathname: string): boolean {+ const current = pathOnly(removeProjectIdIfPresent(pathname))+ const target = pathOnly(path)+ return current === target || current.startsWith(`${target}/`)+}diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex fb0e05cb7b87..6f9716d85016 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -14,7 +14,6 @@ import { urls } from 'scenes/urls'import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'import { REPORT_AI_PANEL } from '~/layout/ai/aiPanelIds'-import { attachedContextItemKey } from '~/layout/ai/attachedContext'import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'@@ -22,7 +21,13 @@ import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import { runStreamLogic, taskRunDefaultsLogic, wrapWithPosthogContext } from 'products/posthog_ai/frontend/api/logics'+import {+ chatContextLogic,+ chatSendItems,+ runStreamLogic,+ taskRunDefaultsLogic,+ wrapWithPosthogContext,+} from 'products/posthog_ai/frontend/api/logics'import { submitWithWarmRunRetry } from 'products/posthog_ai/frontend/utils/warmRunSubmission'import {tasksCreate,@@ -431,7 +436,8 @@ function panelStillOnReport(context: ReportChatContext | null, reportId: string)export interface inboxTaskKickoffLogicValues {dataProcessingAccepted: boolean // aiConsentLogicdataProcessingApprovalDisabledReason: string | null // aiConsentLogic- contextItems: AttachedContextItem[] // attachedContextLogic+ pageItems: AttachedContextItem[] // chatContextLogic+ picks: AttachedContextItem[] // chatContextLogicfeatureFlags: FeatureFlagsSet // featureFlagLogiccurrentProjectId: number | null // projectLogicactiveCreation: ActiveCreation | null // runnerPanelLogic@@ -456,11 +462,13 @@ export interface inboxTaskKickoffLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxTaskKickoffLogicActions {- markContextSent: (+ contextDelivered: (taskId: string,- keys: string[]+ items: AttachedContextItem[],+ fromNewChat?: boolean | undefined) => {- keys: string[]+ fromNewChat: boolean+ items: AttachedContextItem[]taskId: string} // attachedContextLogicclearActiveCreation: () => {@@ -611,7 +619,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([connect(() => ({actions: [attachedContextLogic,- ['markContextSent'],+ ['contextDelivered'],runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }),['setActiveCreation', 'clearActiveCreation', 'setHistoryExpanded'],sidePanelStateLogic,@@ -620,8 +628,8 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([values: [projectLogic,['currentProjectId'],- attachedContextLogic,- ['contextItems'],+ chatContextLogic({}),+ ['pageItems', 'picks'],runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }),['activeCreation'],taskRunDefaultsLogic,@@ -928,7 +936,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([return}// The sidebar context can belong to another report, and the quick ask shows no attachments.- const contextItems = background ? [] : values.contextItems+ const contextItems = background ? [] : chatSendItems(values.pageItems, values.picks)// The composer renders from a snapshot that can go stale between load and submit (the// report resolves, fails, or gets suppressed meanwhile), so the action-vs-answer framing// is derived from the report's current server-side state. A failed refetch fails closed:@@ -1000,10 +1008,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([warmLease,!background)- const sentContextKeys = contextItems.filter((item) => item.type !== 'text').map(attachedContextItemKey)- if (sentContextKeys.length > 0) {- actions.markContextSent(taskId, sentContextKeys)- }+ actions.contextDelivered(taskId, contextItems, true)if (background) {lemonToast.success('Asked AI about this report', {toastId: `report-quick-ask-${runId}`,