Skip to content

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

feat(desktop): send agent feedback as $ai_metric and $ai_feedback (#90261)

Jake Ruth561f179ad45e
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 4d9b934b5aa1..bc6d5ac311dc 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -150,17 +150,22 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
className
)
+ // Feedback identity: always the task, matching `$ai_session_id` on other surfaces.
+ const feedbackTaskId = conversation?.task?.id
+ // Stable identity so the memoized trailer rows don't re-render on every streamed frame.
+ const feedbackRun = useMemo(() => ({ taskId: feedbackTaskId }), [feedbackTaskId])
const renderTurnTrailer = useCallback(
(trailer: TurnTrailer): JSX.Element | null =>
- sandboxConversationKey ? (
+ feedbackTaskId ? (
<TurnFeedbackActions
- sessionId={sandboxConversationKey}
+ sessionId={feedbackTaskId}
turnIndex={trailer.turnIndex}
+ run={feedbackRun}
isLastTurn={trailer.isLastTurn}
turnText={trailer.turnText}
/>
) : null,
- [sandboxConversationKey]
+ [feedbackTaskId, feedbackRun]
)
if (isPiTask) {
diff --git a/products/desktop/docs/LOCAL-DEVELOPMENT.md b/products/desktop/docs/LOCAL-DEVELOPMENT.md
index 092a718c669f..7f7b9551d173 100644
--- a/products/desktop/docs/LOCAL-DEVELOPMENT.md
+++ b/products/desktop/docs/LOCAL-DEVELOPMENT.md
@@ -179,33 +179,33 @@ posthog.isFeatureEnabled("mcp-gateway"); // undefined ⇒ flags never loaded
The OAuth application in your local PostHog must have the client ID `DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ`. Verify at http://localhost:8010/admin/posthog/oauthapplication/.
-### "OAuth error: invalid_scope"
-
-PostHog Desktop requests the wildcard scope `*` (see `OAUTH_SCOPES` in
-`packages/shared/src/oauth.ts`). PostHog's OAuth server only grants `*` at
-`/authorize` when the OAuth application's **scope ceiling is empty** — this is
-the grandfathering path for the PostHog Desktop client. If the application has any
-explicit `scopes` or `optional_scopes` configured, the wildcard is rejected with
-`invalid_scope`.
-
-Fix: clear the scope ceiling on your local OAuth application so it matches the
-production app. Either edit it at
-http://localhost:8010/admin/posthog/oauthapplication/ (empty the **Scopes** and
-**Optional scopes** fields), or run in your PostHog repo:
+### "OAuth error: invalid_scope" or "Couldn't check Desktop access"
+
+PostHog Desktop requests an explicit scope list (`OAUTH_SCOPES` in `packages/shared/src/oauth.ts`),
+which includes the privileged scope `llm_gateway:read`.
+`/authorize` never rejects a request over scopes: it clamps the request to the application's
+scope ceiling (`OAuthApplication.scopes`) and grants whatever falls inside
+(`validate_scopes` in `posthog/api/oauth/views.py`).
+An empty ceiling falls back to the default unprivileged scopes, which exclude `llm_gateway:read`.
+So an app created manually (option B above) or by an older demo data generator signs in fine
+but issues a token without that scope.
+`GET /api/projects/:id/desktop/access/` requires it (`required_scopes` on the desktop access endpoint),
+so the request returns 403 and the app shows "Couldn't check Desktop access".
+On older PostHog checkouts the same misconfiguration failed sign-in with `invalid_scope` instead.
+(A current `generate_demo_data` seeds a ceiling that already covers the scope.)
+
+Fix: seed the ceiling with the defaults plus that one privileged scope,
+which matches how the production Desktop app is configured. In your PostHog repo:
```bash
-python manage.py shell -c "
-from posthog.models.oauth import OAuthApplication
-app = OAuthApplication.objects.get(client_id='DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ')
-app.scopes = []
-app.optional_scopes = []
-app.save()
-print('cleared scope ceiling for', app.client_id)
-"
+python manage.py seed_oauth_app_scopes \
+ --client-id DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ \
+ --scopes '@default,llm_gateway:read'
```
-Then retry login. (Do not add `*` to the ceiling — an explicit ceiling never
-grants the wildcard, even if `*` is listed.)
+Add `--clear-optional-scopes` if the command reports optional scopes. Then log
+out of the app and sign in again: an existing token keeps the scopes it was
+issued with. (Do not add `*` to the ceiling. It is not a valid ceiling entry.)
### "Redirect URI mismatch"
diff --git a/products/desktop/packages/core/src/analytics/aiFeedback.test.ts b/products/desktop/packages/core/src/analytics/aiFeedback.test.ts
new file mode 100644
index 000000000000..6473686e9f2a
--- /dev/null
+++ b/products/desktop/packages/core/src/analytics/aiFeedback.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildSlashFeedbackEvents,
+ buildTurnRatingMetric,
+ type SlashFeedbackInput,
+} from "./aiFeedback";
+
+const run = { taskId: "task-1", taskRunId: "run-1" };
+
+const context = {
+ $ai_session_id: "task-1",
+ $ai_trace_id: null,
+ ai_product: "posthog_code",
+ task_id: "task-1",
+ task_run_id: "run-1",
+};
+
+describe("aiFeedback", () => {
+ it.each([
+ ["positive", "good"],
+ ["negative", "bad"],
+ ] as const)(
+ "maps a %s thumb to a quality=%s metric on the turn",
+ (sentiment, rating) => {
+ expect(
+ buildTurnRatingMetric({ run, turnId: "turn-9", sentiment }),
+ ).toEqual({
+ ...context,
+ turn_id: "turn-9",
+ $ai_metric_name: "quality",
+ $ai_metric_value: rating,
+ });
+ },
+ );
+
+ it("still rates a turn when the thread has no task", () => {
+ expect(
+ buildTurnRatingMetric({
+ run: { taskId: null },
+ turnId: "turn-1",
+ sentiment: "positive",
+ }),
+ ).toMatchObject({
+ $ai_session_id: null,
+ task_id: null,
+ task_run_id: undefined,
+ $ai_metric_value: "good",
+ });
+ });
+
+ it.each<
+ [
+ string,
+ Pick<SlashFeedbackInput, "feedbackType" | "comment">,
+ { rating: "good" | "bad" | null; text: string | null },
+ ]
+ >([
+ ["/good", { feedbackType: "good" }, { rating: "good", text: null }],
+ [
+ "/bad with a comment",
+ { feedbackType: "bad", comment: " wrong file " },
+ { rating: "bad", text: "wrong file" },
+ ],
+ [
+ "/feedback with a comment",
+ { feedbackType: "general", comment: "add a diff view" },
+ { rating: null, text: "add a diff view" },
+ ],
+ [
+ "/feedback with no comment",
+ { feedbackType: "general" },
+ { rating: null, text: null },
+ ],
+ [
+ "/good with a blank comment",
+ { feedbackType: "good", comment: " " },
+ { rating: "good", text: null },
+ ],
+ ])("%s", (_label, input, expected) => {
+ const { metric, feedback } = buildSlashFeedbackEvents({
+ run,
+ eventCount: 12,
+ ...input,
+ });
+ const slashContext = {
+ ...context,
+ feedback_type: input.feedbackType,
+ event_count: 12,
+ };
+ expect(metric).toEqual(
+ expected.rating === null
+ ? null
+ : {
+ ...slashContext,
+ $ai_metric_name: "quality",
+ $ai_metric_value: expected.rating,
+ },
+ );
+ expect(feedback).toEqual(
+ expected.text === null
+ ? null
+ : { ...slashContext, $ai_feedback_text: expected.text },
+ );
+ });
+});
diff --git a/products/desktop/packages/core/src/analytics/aiFeedback.ts b/products/desktop/packages/core/src/analytics/aiFeedback.ts
new file mode 100644
index 000000000000..eace3382d617
--- /dev/null
+++ b/products/desktop/packages/core/src/analytics/aiFeedback.ts
@@ -0,0 +1,85 @@
+import type {
+ AgentTurnFeedbackSentiment,
+ AiFeedbackContextProperties,
+ AiFeedbackProperties,
+ AiMetricProperties,
+ AiQualityRating,
+ FeedbackType,
+} from "@posthog/shared/analytics-events";
+
+/** Sanity cap shared with the inbox note's FEEDBACK_NOTE_MAX_LENGTH. Capture only
+ * rejects megabyte-scale events (and drops them whole, not truncated), so the cap
+ * is a product bound, not a technical one. The editor enforces it before capture;
+ * the slice here is the last-resort guard for other callers. */
+export const AI_FEEDBACK_TEXT_MAX_LENGTH = 4000;
+
+export interface AiFeedbackRunRef {
+ taskId: string | null;
+ taskRunId?: string;
+}
+
+function buildContext(
+ run: AiFeedbackRunRef,
+ extra: Partial<AiFeedbackContextProperties> = {},
+): AiFeedbackContextProperties {
+ return {
+ $ai_session_id: run.taskId,
+ $ai_trace_id: null,
+ ai_product: "posthog_code",
+ task_id: run.taskId,
+ task_run_id: run.taskRunId,
+ ...extra,
+ };
+}
+
+export function sentimentToRating(
+ sentiment: AgentTurnFeedbackSentiment,
+): AiQualityRating {
+ return sentiment === "positive" ? "good" : "bad";
+}
+
+export function buildTurnRatingMetric(input: {
+ run: AiFeedbackRunRef;
+ turnId: string;
+ sentiment: AgentTurnFeedbackSentiment;
+}): AiMetricProperties {
+ return {
+ ...buildContext(input.run, { turn_id: input.turnId }),
+ $ai_metric_name: "quality",
+ $ai_metric_value: sentimentToRating(input.sentiment),
+ };
+}
+
+export interface SlashFeedbackInput {
+ run: AiFeedbackRunRef;
+ feedbackType: FeedbackType;
+ comment?: string;
+ eventCount: number;
+}
+
+export interface SlashFeedbackEvents {
+ metric: AiMetricProperties | null;
+ feedback: AiFeedbackProperties | null;
+}
+
+export function buildSlashFeedbackEvents(
+ input: SlashFeedbackInput,
+): SlashFeedbackEvents {
+ const context = buildContext(input.run, {
+ feedback_type: input.feedbackType,
+ event_count: input.eventCount,
+ });
+ const comment = input.comment?.trim().slice(0, AI_FEEDBACK_TEXT_MAX_LENGTH);
+ const metric: AiMetricProperties | null =
+ input.feedbackType === "general"
+ ? null
+ : {
+ ...context,
+ $ai_metric_name: "quality",
+ $ai_metric_value: input.feedbackType,
+ };
+ const feedback: AiFeedbackProperties | null = comment
+ ? { ...context, $ai_feedback_text: comment }
+ : null;
+ return { metric, feedback };
+}
diff --git a/products/desktop/packages/core/src/message-editor/commands.ts b/products/desktop/packages/core/src/message-editor/commands.ts
index a16caaca6a53..7ad333aaa45b 100644
--- a/products/desktop/packages/core/src/message-editor/commands.ts
+++ b/products/desktop/packages/core/src/message-editor/commands.ts
@@ -1,5 +1,3 @@
-import type { FeedbackType } from "@posthog/shared/analytics-events";
-
export function basename(path: string): string {
const trimmed = path.replace(/[\\/]+$/, "");
const idx = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
@@ -18,34 +16,3 @@ export function parseCommandLine(text: string): ParsedCommandLine | null {
if (!match) return null;
return { name: match[1], args: match[2] };
}
-
-export interface FeedbackEventInput {
- taskId: string;
- taskRunId?: string;
- logUrl?: string;
- eventCount: number;
- feedbackType: FeedbackType;
- comment?: string;
-}
-
-export interface FeedbackEventPayload {
- task_id: string;
- task_run_id: string | undefined;
- log_url: string | undefined;
- event_count: number;
- feedback_type: FeedbackType;
- feedback_comment: string | undefined;
-}
-
-export function buildFeedbackEventPayload(
- input: FeedbackEventInput,
-): FeedbackEventPayload {
- return {
- task_id: input.taskId,
- task_run_id: input.taskRunId,
- log_url: input.logUrl,
- event_count: input.eventCount,
- feedback_type: input.feedbackType,
- feedback_comment: input.comment?.trim() || undefined,
- };
-}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 975c8bd349c0..e625d5fa9989 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -482,14 +482,32 @@ export interface DeepLinkChannelProperties {
task_id?: string;
}
-// Feedback events
-export interface TaskFeedbackProperties {
- task_id: string;
+// PostHog's reserved LLM analytics feedback events, same shape as the PostHog AI
+// web client (products/posthog_ai/frontend/utils/feedbackEvents.ts).
+// `$ai_session_id` is the task id because every `$ai_generation` of a run
+// carries it as `task_id`; `$ai_trace_id` is null until the sandbox exposes
+// per-turn trace ids.
+export type AiFeedbackProduct = "posthog_code";
+export type AiQualityRating = "good" | "bad";
+
+export interface AiFeedbackContextProperties {
+ $ai_session_id: string | null;
+ $ai_trace_id: null;
+ ai_product: AiFeedbackProduct;
+ task_id: string | null;
task_run_id?: string;
- log_url?: string;
- event_count: number;
- feedback_type: FeedbackType;
- feedback_comment?: string;
+ turn_id?: string;
+ feedback_type?: FeedbackType;
+ event_count?: number;
+}
+
+export interface AiMetricProperties extends AiFeedbackContextProperties {
+ $ai_metric_name: "quality";
+ $ai_metric_value: AiQualityRating;
+}
+
+export interface AiFeedbackProperties extends AiFeedbackContextProperties {
+ $ai_feedback_text: string;
}
// Onboarding events
@@ -1479,7 +1497,8 @@ export const ANALYTICS_EVENTS = {
CODEX_SUBSCRIPTION_SIGNED_OUT: "Codex subscription signed out",
// Feedback events
- TASK_FEEDBACK: "Task feedback",
+ AI_METRIC: "$ai_metric",
+ AI_FEEDBACK: "$ai_feedback",
// Branch mismatch events
BRANCH_MISMATCH_WARNING_SHOWN: "Branch mismatch warning shown",
@@ -1679,7 +1698,8 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_SIGNED_OUT]: never;
// Feedback events
- [ANALYTICS_EVENTS.TASK_FEEDBACK]: TaskFeedbackProperties;
+ [ANALYTICS_EVENTS.AI_METRIC]: AiMetricProperties;
+ [ANALYTICS_EVENTS.AI_FEEDBACK]: AiFeedbackProperties;
// Branch mismatch events
[ANALYTICS_EVENTS.BRANCH_MISMATCH_WARNING_SHOWN]: BranchMismatchWarningShownProperties;
diff --git a/products/desktop/packages/ui/src/features/message-editor/commands.test.ts b/products/desktop/packages/ui/src/features/message-editor/commands.test.ts
index c1cccb24e30c..7e76bbec621a 100644
--- a/products/desktop/packages/ui/src/features/message-editor/commands.test.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/commands.test.ts
@@ -1,5 +1,7 @@
+import { AI_FEEDBACK_TEXT_MAX_LENGTH } from "@posthog/core/analytics/aiFeedback";
import { describe, expect, it, vi } from "vitest";
import {
+ getCodeCommandInputError,
rewriteLocalSkillCommandPrompt,
tryExecuteCodeCommand,
} from "./commands";
@@ -10,6 +12,9 @@ vi.mock("@posthog/ui/primitives/toast", () => ({
toast: { error: toastError, success: vi.fn() },
}));
+const track = vi.hoisted(() => vi.fn());
+vi.mock("../../shell/analytics", () => ({ track }));
+
const commands: EditorAvailableCommand[] = [
{
name: "local-test-skill",
@@ -47,6 +52,79 @@ describe("message editor commands", () => {
});
});
+describe("feedback commands", () => {
+ const context = {
+ taskId: "task-1",
+ repoPath: null,
+ session: {
+ taskRunId: "run-1",
+ events: [{}, {}],
+ },
+ taskRun: null,
+ };
+ const expectedContext = {
+ $ai_session_id: "task-1",
+ $ai_trace_id: null,
+ ai_product: "posthog_code",
+ task_id: "task-1",
+ task_run_id: "run-1",
+ };
+
+ it("captures /bad with a comment as a quality metric plus feedback text", async () => {
+ track.mockClear();
+ expect(await tryExecuteCodeCommand("/bad wrong file", context)).toBe(true);
+ expect(track).toHaveBeenCalledWith(
+ "$ai_metric",
+ expect.objectContaining({
+ ...expectedContext,
+ $ai_metric_name: "quality",
+ $ai_metric_value: "bad",
+ }),
+ );
+ expect(track).toHaveBeenCalledWith(
+ "$ai_feedback",
+ expect.objectContaining({
+ ...expectedContext,
+ $ai_feedback_text: "wrong file",
+ event_count: 2,
+ }),
+ );
+ expect(track).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects /feedback without a comment and captures nothing", async () => {
+ track.mockClear();
+ toastError.mockClear();
+ expect(await tryExecuteCodeCommand("/feedback", context)).toBe(true);
+ expect(track).not.toHaveBeenCalled();
+ expect(toastError).toHaveBeenCalledWith(
+ expect.stringContaining("Add a comment after /feedback"),
+ );
+ });
+
+ it("rejects an over-limit comment pre-submit and reports the counts", () => {
+ const oversized = "x".repeat(AI_FEEDBACK_TEXT_MAX_LENGTH + 234);
+ const error = getCodeCommandInputError(`/feedback ${oversized}`);
+ expect(error).toContain("4,234 characters");
+ expect(error).toContain("the limit is 4,000");
+ });
+
+ it.each([
+ ["/feedback", true],
+ ["/feedback ", true],
+ ["/btw", true],
+ ["/feedback add a diff view", false],
+ [`/good ${"x".repeat(AI_FEEDBACK_TEXT_MAX_LENGTH + 1)}`, true],
+ [`/feedback ${"x".repeat(AI_FEEDBACK_TEXT_MAX_LENGTH)}`, false],
+ ["/good", false],
+ ["/bad no comment needed", false],
+ ["plain message", false],
+ ])("pre-submit input check for %j blocks=%s", (text, blocks) => {
+ const error = getCodeCommandInputError(text);
+ expect(error !== null).toBe(blocks);
+ });
+});
+
describe("/btw command", () => {
const baseContext = {
taskId: "task-1",
diff --git a/products/desktop/packages/ui/src/features/message-editor/commands.ts b/products/desktop/packages/ui/src/features/message-editor/commands.ts
index c665cfab45e8..e52fe6a0552d 100644
--- a/products/desktop/packages/ui/src/features/message-editor/commands.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/commands.ts
@@ -1,7 +1,10 @@
import type { AvailableCommand } from "@agentclientprotocol/sdk";
+import {
+ AI_FEEDBACK_TEXT_MAX_LENGTH,
+ buildSlashFeedbackEvents,
+} from "@posthog/core/analytics/aiFeedback";
import {
basename,
- buildFeedbackEventPayload,
parseCommandLine,
} from "@posthog/core/message-editor/commands";
import { escapeXmlAttr, type SkillSource } from "@posthog/shared";
@@ -22,10 +25,9 @@ interface CommandContext {
repoPath: string | null | undefined;
session: {
taskRunId?: string;
- logUrl?: string;
events: unknown[];
} | null;
- taskRun: { id?: string; log_url?: string } | null;
+ taskRun: { id?: string } | null;
/** Fires a "/btw" side question. Absent when the session doesn't support them. */
/** Returns false when a side question is already pending for this run. */
askSideQuestion?: (question: string) => boolean;
@@ -40,7 +42,10 @@ export interface CodeCommandInsertContext {
interface CodeCommand {
name: string;
description: string;
- input?: { hint: string };
+ /** `required` is the message shown when the command is sent without input.
+ * `maxLength` bounds the input; over-limit submits are rejected pre-submit
+ * so the composer keeps the text. */
+ input?: { hint: string; required?: string; maxLength?: number };
/** Optional override for the chip attrs inserted when this command is committed. */
placeholderChip?: Partial<MentionChipAttrs>;
/** Fires immediately after the chip is inserted into the editor. */
@@ -52,27 +57,35 @@ interface CodeCommand {
) => Promise<void> | void;
}
+const FEEDBACK_COMMENT_REQUIRED =
+ "Add a comment after /feedback. To rate without a comment, use /good or /bad.";
+
function makeFeedbackCommand(
name: string,
feedbackType: FeedbackType,
label: string,
+ input: NonNullable<CodeCommand["input"]>,
): CodeCommand {
return {
name,
description: `Capture ${label.toLowerCase()} feedback`,
- input: { hint: "optional comment" },
+ input: { ...input, maxLength: AI_FEEDBACK_TEXT_MAX_LENGTH },
execute(args, ctx) {
- track(
- ANALYTICS_EVENTS.TASK_FEEDBACK,
- buildFeedbackEventPayload({
+ if (input.required && !args?.trim()) {
+ toast.error(input.required);
+ return;
+ }
+ const { metric, feedback } = buildSlashFeedbackEvents({
+ run: {
taskId: ctx.taskId,
taskRunId: ctx.session?.taskRunId ?? ctx.taskRun?.id,
- logUrl: ctx.session?.logUrl ?? ctx.taskRun?.log_url,
- eventCount: ctx.session?.events.length ?? 0,
- feedbackType,
- comment: args,
- }),
- );
+ },
+ eventCount: ctx.session?.events.length ?? 0,
+ feedbackType,
+ comment: args,
+ });
+ if (metric) track(ANALYTICS_EVENTS.AI_METRIC, metric);
+ if (feedback) track(ANALYTICS_EVENTS.AI_FEEDBACK, feedback);
toast.success(`${label} feedback captured`);
},
};
@@ -113,7 +126,7 @@ const btwCommand: CodeCommand = {
name: BTW_COMMAND_NAME,
description:
"Ask a quick side question without interrupting the conversation",
- input: { hint: "your question" },
+ input: { hint: "your question", required: "Add a question after /btw" },
execute(args, ctx) {
const question = args?.trim();
if (!question) {
@@ -133,15 +146,20 @@ const btwCommand: CodeCommand = {
const commands: CodeCommand[] = [
addDirCommand,
btwCommand,
- makeFeedbackCommand("good", "good", "Positive"),
- makeFeedbackCommand("bad", "bad", "Negative"),
- makeFeedbackCommand("feedback", "general", "General"),
+ makeFeedbackCommand("good", "good", "Positive", {
+ hint: "optional comment",
+ }),
+ makeFeedbackCommand("bad", "bad", "Negative", { hint: "optional comment" }),
+ makeFeedbackCommand("feedback", "general", "General", {
+ hint: "your comment",
+ required: FEEDBACK_COMMENT_REQUIRED,
+ }),
];
export const CODE_COMMANDS: AvailableCommand[] = commands.map((cmd) => ({
name: cmd.name,
description: cmd.description,
- input: cmd.input,
+ input: cmd.input ? { hint: cmd.input.hint } : undefined,
}));
const commandMap = new Map(commands.map((cmd) => [cmd.name, cmd]));
@@ -150,6 +168,26 @@ export function getCodeCommand(name: string): CodeCommand | undefined {
return commandMap.get(name);
}
+/**
+ * Message to show instead of sending, when `text` is a code command that
+ * requires input and has none, or the input exceeds the command's limit.
+ * Checked before submit so the composer keeps the text for the user to
+ * complete or trim.
+ */
+export function getCodeCommandInputError(text: string): string | null {
+ const parsed = parseCommandLine(text.trim());
+ if (!parsed) return null;
+ const input = commandMap.get(parsed.name)?.input;
+ const args = parsed.args?.trim();
+ if (input?.required && !args) {
+ return input.required;
+ }
+ if (input?.maxLength && args && args.length > input.maxLength) {
+ return `Your comment is ${args.length.toLocaleString()} characters and the limit is ${input.maxLength.toLocaleString()}. Shorten it and try again.`;
+ }
+ return null;
+}
+
export async function tryExecuteCodeCommand(
text: string,
context: CommandContext,
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
index 6233a43f91eb..49e021d7f194 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -24,6 +24,7 @@ import {
} from "@posthog/ui/features/billing/useSpendStop";
import { showOfflineToast } from "@posthog/ui/features/connectivity/connectivityToast";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { getCodeCommandInputError } from "@posthog/ui/features/message-editor/commands";
import type { AttachmentUploadStatus } from "@posthog/ui/features/message-editor/components/AttachmentsBar";
import {
PromptInput,
@@ -518,6 +519,11 @@ export function SessionView({
showOfflineToast();
return false;
}
+ const commandInputError = getCodeCommandInputError(text);
+ if (commandInputError) {
+ toast.error(commandInputError);
+ return false;
+ }
return onBeforeSubmit ? onBeforeSubmit(text, clearEditor) : true;
},
[isOnline, onBeforeSubmit],
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index 339c20e45d79..f9ffa07c6b5e 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -9,6 +9,7 @@ import {
ThumbsUp,
} from "@phosphor-icons/react";
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
+import { buildTurnRatingMetric } from "@posthog/core/analytics/aiFeedback";
import { channelDisplayLabel } from "@posthog/core/canvas/channelName";
import { useService } from "@posthog/di/react";
import {
@@ -123,6 +124,7 @@ import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useCon
import {
useOptimisticItemsForTask,
useSessionIsCloud,
+ useSessionSelector,
} from "@posthog/ui/features/sessions/sessionStore";
import {
useSessionViewActions,
@@ -394,16 +396,23 @@ function TurnFeedback({
sentiment: AgentTurnFeedbackSentiment | null;
}) {
const taskId = useSessionTaskId();
+ const taskRunId = useSessionSelector(
+ taskId ?? undefined,
+ (session) => session?.taskRunId,
+ );
const { setTurnFeedback } = useSessionViewActions();
const rate = (next: AgentTurnFeedbackSentiment) => {
if (sentiment === next) return;
setTurnFeedback(turnId, next);
- track(ANALYTICS_EVENTS.AGENT_TURN_FEEDBACK, {
- task_id: taskId,
- turn_id: turnId,
- sentiment: next,
- });
+ track(
+ ANALYTICS_EVENTS.AI_METRIC,
+ buildTurnRatingMetric({
+ run: { taskId, taskRunId },
+ turnId,
+ sentiment: next,
+ }),
+ );
};
return (
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts
index 9cc9ffde16e8..61dc74e1f06d 100644
--- a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts
@@ -73,7 +73,6 @@ export function useSessionCallbacks({
session: currentSession
? {
taskRunId: currentSession.taskRunId,
- logUrl: currentSession.logUrl,
events: currentEvents,
}
: null,
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index 90b83850456e..9f42754ce5ff 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -49,9 +49,9 @@ export interface RunSurfaceProps {
interface RunSurfaceContextValue {
/** Original run id passed to `bootstrapRun`; `null`/`''` while the surface is pending (no run yet). */
- rawRunId: string | null
- /** Logic key (used for child stream keys). */
- runId: string
+ runId: string | null
+ /** Logic key the bound `runStreamLogic` and child stream consumers share. */
+ streamKey: string
taskId: string
conversationId?: string
interaction: 'live' | 'read-only'
@@ -127,8 +127,8 @@ function RunSurfaceRoot({
<BindLogic logic={runStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>
<RunSurfaceContext.Provider
value={{
- rawRunId: runId,
- runId: logicKey,
+ runId,
+ streamKey: logicKey,
taskId,
conversationId,
interaction,
@@ -144,7 +144,7 @@ function RunSurfaceRoot({
/** Drives the run bootstrap as a side effect; renders nothing. Kept separate so slots stay presentational. */
function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
- const { rawRunId, interaction } = useRunSurfaceContext()
+ const { runId, interaction } = useRunSurfaceContext()
const { bootstrapRun, reset } = useActions(runStreamLogic)
// The bootstrap decision reads logic-resident state (not a per-component ref) so it survives the
// optimistic create-thread → detail-page component swap onto the same `streamKey` instance.
@@ -153,7 +153,7 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
useEffect(() => {
// Pending: no run to bootstrap yet — leave the seeded optimistic thread (first message +
// provisioning indicator) untouched until the consumer supplies the real id.
- if (!rawRunId) {
+ if (!runId) {
return
}
// Wait for the project to resolve before bootstrapping — firing without it races to an
@@ -163,13 +163,13 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
}
// Already bootstrapped this run on this instance — idempotent across re-renders and across a
// consumer swap that adopts the same seeded instance (no reset, so the seed/stream survives).
- if (bootstrappedRunId === rawRunId) {
+ if (bootstrappedRunId === runId) {
return
}
if (awaitingOptimisticAttach) {
// Attaching a freshly-created run to a seeded optimistic instance: skip the reset so the seed
// survives, and take the fresh-run fast path. The live SSE echo dedups the seeded message.
- bootstrapRun({ taskId, runId: rawRunId, justCreatedRun: true })
+ bootstrapRun({ taskId, runId, justCreatedRun: true })
return
}
// Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run
@@ -177,17 +177,8 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
// `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right
// mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.
reset()
- bootstrapRun({ taskId, runId: rawRunId })
- }, [
- taskId,
- rawRunId,
- interaction,
- bootstrappedRunId,
- awaitingOptimisticAttach,
- currentProjectId,
- bootstrapRun,
- reset,
- ])
+ bootstrapRun({ taskId, runId })
+ }, [taskId, runId, interaction, bootstrappedRunId, awaitingOptimisticAttach, currentProjectId, bootstrapRun, reset])
return null
}
@@ -198,34 +189,33 @@ function RunSurfaceThread({
listClassName,
rowClassName,
}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {
- const { interaction, isScout, taskId, conversationId, runId } = useRunSurfaceContext()
+ const { interaction, isScout, taskId, streamKey, runId } = useRunSurfaceContext()
const { bootstrapLoading, threadItems } = useValues(runStreamLogic)
- // Feedback identity: the conversation where one exists (Max chats), else the task.
- const feedbackSessionId = conversationId ?? taskId
+ // Feedback identity: always the task, matching `$ai_session_id` on other surfaces.
+ const feedbackSessionId = taskId
const collectsFeedback = interaction === 'live' && !isScout && !!feedbackSessionId
// Memoized so the footer keeps a stable element identity across streamed frames.
const feedbackPrompt = useMemo(
() =>
collectsFeedback ? (
- <FeedbackPromptTrailer
- sessionId={feedbackSessionId}
- sessionKind={conversationId ? 'conversation' : 'task'}
- streamKey={runId}
- />
+ <FeedbackPromptTrailer sessionId={feedbackSessionId} sessionKind="task" streamKey={streamKey} />
) : undefined,
- [collectsFeedback, feedbackSessionId, conversationId, runId]
+ [collectsFeedback, feedbackSessionId, streamKey]
)
+ // Stable identity so the memoized trailer rows don't re-render on every streamed frame.
+ const feedbackRun = useMemo(() => ({ taskId, runId: runId ?? undefined }), [taskId, runId])
const renderTurnTrailer = useCallback(
(trailer: TurnTrailer): JSX.Element | null =>
feedbackSessionId ? (
<TurnFeedbackActions
sessionId={feedbackSessionId}
turnIndex={trailer.turnIndex}
+ run={feedbackRun}
isLastTurn={trailer.isLastTurn}
turnText={trailer.turnText}
/>
) : null,
- [feedbackSessionId]
+ [feedbackSessionId, feedbackRun]
)
const showSkeleton = bootstrapLoading && threadItems.length === 0
if (showSkeleton) {
@@ -255,7 +245,7 @@ function RunSurfaceThread({
* message), is hidden during bootstrap, and is replaced by the prompt while a request is pending.
*/
function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element | null {
- const { interaction, runId } = useRunSurfaceContext()
+ const { interaction, streamKey } = useRunSurfaceContext()
const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)
if (interaction !== 'live') {
return null
@@ -267,9 +257,9 @@ function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element
<div className="border-t px-4 py-3">
<div className="mx-auto w-full max-w-180">
{isQuestion ? (
- <QuestionInput streamKey={runId} request={pendingPermissionRequest} />
+ <QuestionInput streamKey={streamKey} request={pendingPermissionRequest} />
) : (
- <PermissionInput streamKey={runId} request={pendingPermissionRequest} />
+ <PermissionInput streamKey={streamKey} request={pendingPermissionRequest} />
)}
</div>
</div>
diff --git a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
index 4cc7b85dfd7a..8a567b5f1d56 100644
--- a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
+++ b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
@@ -1,4 +1,4 @@
-import { useActions, useMountedLogic, useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { useState, memo } from 'react'
import { IconCopy, IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'
@@ -13,10 +13,11 @@ import { MessageTemplate } from '../messages/MessageTemplate'
import { RunRef, captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'
export interface TurnFeedbackActionsProps {
- /** Conversation id where one exists (Max chats), else the task id. Lands in `$ai_session_id`. */
+ /** Task id backing the sandbox conversation. Lands in `$ai_session_id`. */
sessionId: string
/** Ordinal of the completed turn — the rating's identity, stable across reloads. */
turnIndex: number
+ run: RunRef
isLastTurn: boolean
turnText: string
}
@@ -29,13 +30,13 @@ export interface TurnFeedbackActionsProps {
export const TurnFeedbackActions = memo(function TurnFeedbackActions({
sessionId,
turnIndex,
+ run,
isLastTurn,
turnText,
}: TurnFeedbackActionsProps): JSX.Element {
const { ratingForKey } = useValues(messageRatingsLogic)
const { setRating } = useActions(messageRatingsLogic)
const { traceId } = useValues(runStreamLogic)
- const mountedStreamLogic = useMountedLogic(runStreamLogic)
const ratingKey = `${sessionId}:turn-${turnIndex}`
const rating = ratingForKey(ratingKey)
@@ -46,16 +47,12 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
// the only truthful value. Older turns send null rather than a synthetic id.
const turnTraceId = isLastTurn ? traceId : null
- function activeRun(): RunRef | undefined {
- return mountedStreamLogic.cache.activeRun as RunRef | undefined
- }
-
function submitRating(newRating: 'good' | 'bad'): void {
if (rating) {
return // Already rated
}
setRating({ key: ratingKey, rating: newRating })
- captureTurnRating(sessionId, turnTraceId, newRating, turnIndex, activeRun())
+ captureTurnRating(sessionId, turnTraceId, newRating, turnIndex, run)
if (newRating === 'bad') {
setFeedbackInputStatus('pending')
}
@@ -65,7 +62,7 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
if (!feedback) {
return // Input is empty
}
- captureTurnFeedbackText(sessionId, turnTraceId, feedback, turnIndex, activeRun())
+ captureTurnFeedbackText(sessionId, turnTraceId, feedback, turnIndex, run)
setFeedbackInputStatus('submitted')
}
diff --git a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
index 5f7790df72a5..14dd8cd31b25 100644
--- a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
+++ b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
@@ -19,7 +19,7 @@ export interface FeedbackPromptConfig {
const LAST_SHOWN_STORAGE_KEY = 'posthog_ai_feedback_last_shown'
export interface FeedbackPromptLogicProps {
- /** Conversation id where one exists, else the task id. Lands in `$ai_session_id`. */
+ /** Task id backing the sandbox conversation. Lands in `$ai_session_id`. */
sessionId: string
/** Key of the live `runStreamLogic` instance this prompt observes. */
streamKey: string
diff --git a/products/posthog_ai/frontend/utils/feedbackEvents.ts b/products/posthog_ai/frontend/utils/feedbackEvents.ts
index 1e067845b17f..a4d5379843aa 100644
--- a/products/posthog_ai/frontend/utils/feedbackEvents.ts
+++ b/products/posthog_ai/frontend/utils/feedbackEvents.ts
@@ -10,6 +10,7 @@ function feedbackContext(sessionId: string, traceId: string | null, run: RunRef
return {
$ai_session_id: sessionId,
$ai_trace_id: traceId,
+ ai_product: 'posthog_ai',
agent_runtime: 'sandbox',
task_id: run?.taskId ?? null,
run_id: run?.runId ?? null,
@@ -40,7 +41,6 @@ export function captureTurnFeedbackText(
): void {
posthog.capture('$ai_feedback', {
$ai_feedback_text: feedbackText,
- ai_product: 'posthog_ai',
turn_index: turnIndex,
...feedbackContext(sessionId, traceId, run),
})
@@ -69,7 +69,6 @@ export function capturePromptFeedback(
if (feedbackText) {
posthog.capture('$ai_feedback', {
$ai_feedback_text: feedbackText,
- ai_product: 'posthog_ai',
turn_index: turnIndex,
...feedbackContext(sessionId, traceId, run),
})