: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
chore(desktop): remove deprecated fleet product (#86700)
Dylan Martin8a2aa85d7219
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.tsindex e49e0c8237ec..cece435150cd 100644--- a/products/desktop/apps/code/src/main/di/bindings.ts+++ b/products/desktop/apps/code/src/main/di/bindings.ts@@ -46,11 +46,9 @@ import type {SLACK_INTEGRATION_SERVICE,} from "@posthog/core/integrations/identifiers";import type { SlackIntegrationService } from "@posthog/core/integrations/slack";-import type { ApprovalLinkService } from "@posthog/core/links/approval-link";import type { CanvasLinkService } from "@posthog/core/links/canvas-link";import type { ChannelLinkService } from "@posthog/core/links/channel-link";import type {- APPROVAL_LINK_SERVICE,CANVAS_LINK_SERVICE,CHANNEL_LINK_SERVICE,INBOX_LINK_SERVICE,@@ -276,7 +274,6 @@ import type { WorkspaceServerService } from "../services/workspace-server/servicimport type { rendererStore } from "../utils/store";import type {APP_LIFECYCLE_SERVICE as MAIN_APP_LIFECYCLE_SERVICE,- APPROVAL_LINK_SERVICE as MAIN_APPROVAL_LINK_SERVICE,ARCHIVE_REPOSITORY as MAIN_ARCHIVE_REPOSITORY,AUTH_PREFERENCE_REPOSITORY as MAIN_AUTH_PREFERENCE_REPOSITORY,AUTH_SERVICE as MAIN_AUTH_SERVICE,@@ -464,7 +461,6 @@ export interface MainBindings {[MAIN_INBOX_LINK_SERVICE]: InboxLinkService;[MAIN_SCOUT_LINK_SERVICE]: ScoutLinkService;[MAIN_NEW_TASK_LINK_SERVICE]: NewTaskLinkService;- [MAIN_APPROVAL_LINK_SERVICE]: ApprovalLinkService;[MAIN_OPEN_TARGET_LINK_SERVICE]: OpenTargetLinkService;[MAIN_CANVAS_LINK_SERVICE]: CanvasLinkService;[MAIN_CHANNEL_LINK_SERVICE]: ChannelLinkService;@@ -473,7 +469,6 @@ export interface MainBindings {[INBOX_LINK_SERVICE]: InboxLinkService;[SCOUT_LINK_SERVICE]: ScoutLinkService;[NEW_TASK_LINK_SERVICE]: NewTaskLinkService;- [APPROVAL_LINK_SERVICE]: ApprovalLinkService;[OPEN_TARGET_LINK_SERVICE]: OpenTargetLinkService;[CANVAS_LINK_SERVICE]: CanvasLinkService;[CHANNEL_LINK_SERVICE]: ChannelLinkService;diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.tsindex d41653c9cb04..3cb6b94bcb93 100644--- a/products/desktop/apps/code/src/main/di/container.ts+++ b/products/desktop/apps/code/src/main/di/container.ts@@ -46,11 +46,9 @@ import { GIT_DIFF_SOURCE } from "@posthog/core/git-pr/identifiers";import { handoffModule } from "@posthog/core/handoff/handoff.module";import { HANDOFF_HOST } from "@posthog/core/handoff/identifiers";import { integrationsModule } from "@posthog/core/integrations/integrations.module";-import { ApprovalLinkService } from "@posthog/core/links/approval-link";import { CanvasLinkService } from "@posthog/core/links/canvas-link";import { ChannelLinkService } from "@posthog/core/links/channel-link";import {- APPROVAL_LINK_SERVICE,CANVAS_LINK_SERVICE,CHANNEL_LINK_SERVICE,INBOX_LINK_SERVICE,@@ -288,7 +286,6 @@ import { quickAskStore, rendererStore } from "../utils/store";import type { MainBindings } from "./bindings";import {APP_LIFECYCLE_SERVICE as MAIN_APP_LIFECYCLE_SERVICE,- APPROVAL_LINK_SERVICE as MAIN_APPROVAL_LINK_SERVICE,ARCHIVE_REPOSITORY as MAIN_ARCHIVE_REPOSITORY,AUTH_PREFERENCE_REPOSITORY as MAIN_AUTH_PREFERENCE_REPOSITORY,AUTH_SERVICE as MAIN_AUTH_SERVICE,@@ -712,8 +709,6 @@ container.bind(MAIN_SCOUT_LINK_SERVICE).to(ScoutLinkService);container.bind(SCOUT_LINK_SERVICE).toService(MAIN_SCOUT_LINK_SERVICE);container.bind(MAIN_NEW_TASK_LINK_SERVICE).to(NewTaskLinkService);container.bind(NEW_TASK_LINK_SERVICE).toService(MAIN_NEW_TASK_LINK_SERVICE);-container.bind(MAIN_APPROVAL_LINK_SERVICE).to(ApprovalLinkService);-container.bind(APPROVAL_LINK_SERVICE).toService(MAIN_APPROVAL_LINK_SERVICE);container.bind(MAIN_OPEN_TARGET_LINK_SERVICE).to(OpenTargetLinkService);container.bind(OPEN_TARGET_LINK_SERVICE)diff --git a/products/desktop/apps/code/src/main/di/tokens.ts b/products/desktop/apps/code/src/main/di/tokens.tsindex ba474e0422bb..a73cbc078c67 100644--- a/products/desktop/apps/code/src/main/di/tokens.ts+++ b/products/desktop/apps/code/src/main/di/tokens.ts@@ -103,9 +103,6 @@ export const SCOUT_LINK_SERVICE = Symbol.for(export const NEW_TASK_LINK_SERVICE = Symbol.for("posthog.host.main.new-task-link.service",);-export const APPROVAL_LINK_SERVICE = Symbol.for(- "posthog.host.main.approval-link.service",-);export const OPEN_TARGET_LINK_SERVICE = Symbol.for("posthog.host.main.open-target-link.service",);diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.tsindex e8c2cce5dccd..b1cb31f1aac9 100644--- a/products/desktop/apps/code/src/main/index.ts+++ b/products/desktop/apps/code/src/main/index.ts@@ -22,7 +22,6 @@ import {SLACK_INTEGRATION_SERVICE,} from "@posthog/core/integrations/identifiers";import type { SlackIntegrationService } from "@posthog/core/integrations/slack";-import type { ApprovalLinkService } from "@posthog/core/links/approval-link";import type { CanvasLinkService } from "@posthog/core/links/canvas-link";import type { ChannelLinkService } from "@posthog/core/links/channel-link";import type { InboxLinkService } from "@posthog/core/links/inbox-link";@@ -53,7 +52,6 @@ import { initializeDeepLinks, registerDeepLinkHandlers } from "./deep-links";import { container } from "./di/container";import {APP_LIFECYCLE_SERVICE,- APPROVAL_LINK_SERVICE,AUTH_SERVICE,CANVAS_LINK_SERVICE,CHANNEL_LINK_SERVICE,@@ -279,7 +277,6 @@ async function initializeServices(): Promise<void> {container.get<InboxLinkService>(INBOX_LINK_SERVICE);container.get<ScoutLinkService>(SCOUT_LINK_SERVICE);container.get<NewTaskLinkService>(NEW_TASK_LINK_SERVICE);- container.get<ApprovalLinkService>(APPROVAL_LINK_SERVICE);// Eagerly resolved so their constructors register the `canvas` / `channel` /// `loop` deep-link handlers at boot, before any link arrives.container.get<CanvasLinkService>(CANVAS_LINK_SERVICE);diff --git a/products/desktop/apps/code/src/renderer/desktop-contributions.ts b/products/desktop/apps/code/src/renderer/desktop-contributions.tsindex e81cbfabc276..b914979a349c 100644--- a/products/desktop/apps/code/src/renderer/desktop-contributions.ts+++ b/products/desktop/apps/code/src/renderer/desktop-contributions.ts@@ -1,4 +1,3 @@-import { agentChatCoreModule } from "@posthog/core/agent-chat/agentChat.module";import { autoresearchCoreModule } from "@posthog/core/autoresearch/autoresearch.module";import { taskThreadCoreModule } from "@posthog/core/canvas/taskThread.module";import { inboxCoreModule } from "@posthog/core/inbox/inbox.module";@@ -33,7 +32,6 @@ import { container } from "@renderer/di/container";export function registerDesktopContributions(): void {for (const module of [- agentChatCoreModule,agentUiModule,authUiModule,autoresearchCoreModule,diff --git a/products/desktop/apps/web/src/web-host-router.ts b/products/desktop/apps/web/src/web-host-router.tsindex f531ccc9085c..5cb4f23021e2 100644--- a/products/desktop/apps/web/src/web-host-router.ts+++ b/products/desktop/apps/web/src/web-host-router.ts@@ -61,7 +61,6 @@ const deepLinkStubRouter = router({getPendingReportLink: publicProcedure.query(() => null),getPendingScoutLink: publicProcedure.query(() => null),getPendingNewTaskLink: publicProcedure.query(() => null),- getPendingApprovalLink: publicProcedure.query(() => null),getPendingOpenTarget: publicProcedure.query(() => null),getPendingCanvasLink: publicProcedure.query(() => null),getPendingChannelLink: publicProcedure.query(() => null),@@ -70,7 +69,6 @@ const deepLinkStubRouter = router({onOpenReport: neverEmit,onOpenScout: neverEmit,onNewTaskAction: neverEmit,- onOpenApproval: neverEmit,onOpenTarget: neverEmit,onOpenCanvas: neverEmit,onOpenChannel: neverEmit,diff --git a/products/desktop/docs/DEEP-LINKS.md b/products/desktop/docs/DEEP-LINKS.mdindex ac3fb2886267..4ea730ed7669 100644--- a/products/desktop/docs/DEEP-LINKS.md+++ b/products/desktop/docs/DEEP-LINKS.md@@ -137,20 +137,6 @@ a loop's detail page.posthog-code://loop/abc123```-### `posthog-code://approval/<requestId>`--Open the agent fleet approvals inbox focused on a specific tool-approval request.-Emitted by the agent-runner on a gated tool call so non-PostHog-Code clients-(Slack, MCP) can land on the approval; the request id alone resolves it.--| Segment / Parameter | Required | Description |-|---|---|---|-| `<requestId>` | Yes | Agent tool-approval request id (e.g. `ar_...`). |--```-posthog-code://approval/ar_abc123-```-### `posthog-code://canvas/<channelId>/<dashboardId>`Open a canvas (a dashboard inside a Channels-space channel) straight in the@@ -255,7 +241,6 @@ In development the same payload is delivered to `http://localhost:8238/mcp-oauth| `inbox` | [packages/core/src/links/inbox-link.ts](../packages/core/src/links/inbox-link.ts) || `scout` | [packages/core/src/links/scout-link.ts](../packages/core/src/links/scout-link.ts) || `loop` | [packages/core/src/links/loop-link.ts](../packages/core/src/links/loop-link.ts) |-| `approval` | [packages/core/src/links/approval-link.ts](../packages/core/src/links/approval-link.ts) || `canvas` | [packages/core/src/links/canvas-link.ts](../packages/core/src/links/canvas-link.ts) || `channel` | [packages/core/src/links/channel-link.ts](../packages/core/src/links/channel-link.ts) || `new`, `plan`, `issue` | [packages/core/src/links/new-task-link.ts](../packages/core/src/links/new-task-link.ts) |diff --git a/products/desktop/docs/LOCAL-DEVELOPMENT.md b/products/desktop/docs/LOCAL-DEVELOPMENT.mdindex d737cff05487..e1d7da44dd01 100644--- a/products/desktop/docs/LOCAL-DEVELOPMENT.md+++ b/products/desktop/docs/LOCAL-DEVELOPMENT.md@@ -110,8 +110,7 @@ Source: `apps/code/src/renderer/features/inbox/devtools/inboxDemoConsole.ts`.Feature flags are read through posthog-js, configured by the `VITE_POSTHOG_*`vars in `.env`. By default these point at PostHog's internal analytics instance,-so flags you create locally never resolve in the dev build (and flag-gated UI —-e.g. the agent-platform surface behind the `agent-platform` flag — stays hidden).+so flags you create locally never resolve in the dev build.To point the flags/analytics client at your local PostHog so locally-syncedflags take effect:@@ -133,7 +132,7 @@ region you pick at login.> One-off override without changing `.env`: the dev build exposes the client on> `window.posthog`, so you can run-> `posthog.featureFlags.override({ "agent-platform": true })` in the renderer+> `posthog.featureFlags.override({ "mcp-gateway": true })` in the renderer> console (clear with `posthog.featureFlags.override(false)`).## Troubleshootingdiff --git a/products/desktop/packages/api-client/src/agent-analytics.test.ts b/products/desktop/packages/api-client/src/agent-analytics.test.tsdeleted file mode 100644index c91c95792f3a..000000000000--- a/products/desktop/packages/api-client/src/agent-analytics.test.ts+++ /dev/null@@ -1,160 +0,0 @@-import { describe, expect, it } from "vitest";-import {- type AgentAnalyticsRaw,- buildAgentAnalyticsQueries,- EMPTY_AGENT_ANALYTICS,- type HogQLGrid,- shapeAgentAnalytics,-} from "./agent-analytics";--const grid = (results: unknown[][]): HogQLGrid => ({ results, columns: [] });--// A 14-day daily series where every day is identical, so prior(7) === recent(7)-// → zero deltas. Columns: [day, cost, sessions, errors, generations].-function flatDaily(): unknown[][] {- return Array.from({ length: 14 }, (_, i) => [- `2026-06-${String(i + 1).padStart(2, "0")}T00:00:00`,- 2, // cost- 5, // sessions- 1, // errors- 10, // generations- ]);-}--describe("buildAgentAnalyticsQueries", () => {- it("scopes to any agent-platform traffic when no application id", () => {- const q = buildAgentAnalyticsQueries();- // Attribution key, not $ai_origin — the gateway's cost event lacks origin.- expect(q.kpi).toContain("notEmpty(properties.$agent_application_id)");- expect(q.kpi).not.toContain("$ai_origin");- expect(q.kpi).not.toContain("$agent_application_id =");- expect(q.kpi).toContain("event = '$ai_generation'");- expect(q.toolErrors).toContain("event = '$ai_span'");- });-- it("narrows to a single application id when given", () => {- const id = "11111111-2222-3333-4444-555566667777";- const q = buildAgentAnalyticsQueries(id);- expect(q.kpi).toContain(`properties.$agent_application_id = '${id}'`);- expect(q.byModel).toContain(`properties.$agent_application_id = '${id}'`);- });-- it("rejects a non-uuid application id", () => {- expect(() => buildAgentAnalyticsQueries("app-uuid-123")).toThrow(- /must be a UUID/,- );- });-});--describe("shapeAgentAnalytics", () => {- it("returns an empty board for empty grids", () => {- const out = shapeAgentAnalytics({});- expect(out.empty).toBe(true);- expect(out.kpis).toEqual(EMPTY_AGENT_ANALYTICS.kpis);- expect(out.byAgent).toEqual([]);- expect(out.deltas).toEqual({- spend: null,- sessions: null,- failureRatePoints: null,- });- });-- it("derives KPIs incl. failure rate from generations", () => {- const raw: Partial<AgentAnalyticsRaw> = {- // cost, sessions, errors, generations, p95- kpi: grid([[12.5, 8, 3, 12, 4.2]]),- };- const out = shapeAgentAnalytics(raw);- expect(out.kpis.spendUsd).toBe(12.5);- expect(out.kpis.sessions).toBe(8);- expect(out.kpis.failureRate).toBeCloseTo(3 / 12);- expect(out.kpis.p95LatencyS).toBe(4.2);- expect(out.empty).toBe(false);- });-- it("coerces numeric strings (HogQL returns decimals as strings)", () => {- const out = shapeAgentAnalytics({- kpi: grid([["1.50", "4", "0", "4", "2"]]),- });- expect(out.kpis.spendUsd).toBe(1.5);- expect(out.kpis.sessions).toBe(4);- expect(out.kpis.failureRate).toBe(0);- });-- it("builds a 14-day daily series with zero deltas for a flat trend", () => {- const out = shapeAgentAnalytics({ daily: grid(flatDaily()) });- expect(out.daily.labels).toHaveLength(14);- expect(out.daily.spend).toHaveLength(14);- expect(out.daily.failureRate.every((r) => r === 0.1)).toBe(true);- // prior 7 === recent 7 → 0% change, and failure-rate delta is 0pp.- expect(out.deltas.spend).toBe(0);- expect(out.deltas.sessions).toBe(0);- expect(out.deltas.failureRatePoints).toBe(0);- });-- it("computes a positive spend delta when recent exceeds prior", () => {- // 7 days at cost 1, then 7 days at cost 3 → +200%.- const days = Array.from({ length: 14 }, (_, i) => [- `2026-06-${String(i + 1).padStart(2, "0")}T00:00:00`,- i < 7 ? 1 : 3,- 1,- 0,- 1,- ]);- const out = shapeAgentAnalytics({ daily: grid(days) });- expect(out.deltas.spend).toBeCloseTo(200);- });-- it("maps per-agent rows and resolves names via the id→name map", () => {- const raw: Partial<AgentAnalyticsRaw> = {- // agent_id, sessions, generations, cost, tokens, errors, p95- perAgent: grid([- ["11111111-2222-3333-4444-555566667777", 5, 10, 4, 2000, 2, 1.5],- ["aaaa", 1, 4, 0.5, 100, 0, 0.2],- ]),- };- const names = new Map([- ["11111111-2222-3333-4444-555566667777", "Support Bot"],- ]);- const out = shapeAgentAnalytics(raw, names);- expect(out.byAgent[0]).toMatchObject({- name: "Support Bot",- sessions: 5,- spendUsd: 4,- tokens: 2000,- p95LatencyS: 1.5,- });- expect(out.byAgent[0].failureRate).toBeCloseTo(2 / 10);- // Unknown id falls back to a short id.- expect(out.byAgent[1].name).toBe("aaaa");- });-- it("maps model spend and tool error rates", () => {- const out = shapeAgentAnalytics({- byModel: grid([["claude-opus-4-8", 9.99, 42]]),- toolErrors: grid([- ["search", 20, 4],- ["fetch", 5, 0],- ]),- });- expect(out.byModel[0]).toEqual({- model: "claude-opus-4-8",- spendUsd: 9.99,- calls: 42,- });- expect(out.toolErrors[0].errorRate).toBeCloseTo(4 / 20);- expect(out.toolErrors[1].errorRate).toBe(0);- });-- it("ignores non-array rows defensively", () => {- const out = shapeAgentAnalytics({- kpi: grid([[1, 1, 0, 1, 1]]),- perAgent: {- results: [null, "oops"] as unknown as unknown[][],- columns: [],- },- });- expect(out.byAgent).toEqual([]);- expect(out.empty).toBe(false);- });-});diff --git a/products/desktop/packages/api-client/src/agent-analytics.ts b/products/desktop/packages/api-client/src/agent-analytics.tsdeleted file mode 100644index f20d88a8b0c0..000000000000--- a/products/desktop/packages/api-client/src/agent-analytics.ts+++ /dev/null@@ -1,266 +0,0 @@-// Agent observability analytics — rolls up the agents' `$ai_*` events into a-// cross-agent / per-agent dashboard. Read-only HogQL via the `/query/` endpoint.-//-// Scoped on `$agent_application_id` (the per-agent attribution key), NOT-// `$ai_origin`: on the ai-gateway path the cost-bearing `$ai_generation` is-// emitted by the gateway, which carries `$agent_application_id` (forwarded by-// the runner via X-PostHog-Properties) but not `$ai_origin`. The attribution-// key is present on generations (gateway or direct), tool spans, and traces, so-// it unifies both paths and keeps a team's other LLM usage out of the view.-//-// The query builders + shaping are kept here (pure, unit-tested) so the client-// method stays a thin "fire queries, shape result" passthrough.--import type {- AgentAnalyticsData,- AgentAnalyticsModelRow,- AgentAnalyticsToolRow,-} from "@posthog/shared/agent-platform-types";--/** A raw HogQL `/query/` result grid: rows of cells plus column names. */-export interface HogQLGrid {- results: unknown[][];- columns: string[];-}--/** The five panels' raw grids, keyed by panel. */-export interface AgentAnalyticsRaw {- kpi: HogQLGrid;- daily: HogQLGrid;- perAgent: HogQLGrid;- byModel: HogQLGrid;- toolErrors: HogQLGrid;-}--/** Any agent-platform traffic — a team's other LLM usage has no agent id. */-const AGENT_SCOPE = "notEmpty(properties.$agent_application_id)";--const UUID_RE =- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;--/**- * Shared WHERE scope. With an `applicationId` (per-agent tab) it narrows to that- * agent; without one (fleet board) it matches any agent traffic via the- * attribution key. `applicationId` is a trusted server UUID, but reject- * non-UUIDs before interpolating into HogQL rather than rely on that.- */-function scope(applicationId?: string): string {- if (applicationId && !UUID_RE.test(applicationId)) {- throw new Error("agent analytics: applicationId must be a UUID");- }- return applicationId- ? `properties.$agent_application_id = '${applicationId}'`- : AGENT_SCOPE;-}--const kpiQuery = (id?: string): string => `-SELECT- coalesce(sum(toFloat(properties.$ai_total_cost_usd)), 0) AS cost,- uniq(properties.$ai_trace_id) AS sessions,- countIf(toString(properties.$ai_is_error) = 'true') AS errors,- count() AS generations,- coalesce(quantile(0.95)(toFloat(properties.$ai_latency)), 0) AS p95-FROM events-WHERE event = '$ai_generation' AND ${scope(id)}- AND timestamp > now() - INTERVAL 7 DAY-`;--const dailyQuery = (id?: string): string => `-SELECT- toStartOfDay(timestamp) AS day,- coalesce(sum(toFloat(properties.$ai_total_cost_usd)), 0) AS cost,- uniq(properties.$ai_trace_id) AS sessions,- countIf(toString(properties.$ai_is_error) = 'true') AS errors,- count() AS generations-FROM events-WHERE event = '$ai_generation' AND ${scope(id)}- AND timestamp > now() - INTERVAL 14 DAY-GROUP BY day ORDER BY day-`;--const perAgentQuery = (id?: string): string => `-SELECT- properties.$agent_application_id AS agent_id,- uniq(properties.$ai_trace_id) AS sessions,- count() AS generations,- coalesce(sum(toFloat(properties.$ai_total_cost_usd)), 0) AS cost,- coalesce(sum(toInt(properties.$ai_input_tokens)), 0)- + coalesce(sum(toInt(properties.$ai_output_tokens)), 0) AS tokens,- countIf(toString(properties.$ai_is_error) = 'true') AS errors,- coalesce(quantile(0.95)(toFloat(properties.$ai_latency)), 0) AS p95-FROM events-WHERE event = '$ai_generation' AND ${scope(id)}- AND timestamp > now() - INTERVAL 7 DAY-GROUP BY agent_id ORDER BY cost DESC LIMIT 50-`;--const byModelQuery = (id?: string): string => `-SELECT- properties.$ai_model AS model,- coalesce(sum(toFloat(properties.$ai_total_cost_usd)), 0) AS cost,- count() AS calls-FROM events-WHERE event = '$ai_generation' AND ${scope(id)}- AND timestamp > now() - INTERVAL 7 DAY AND notEmpty(properties.$ai_model)-GROUP BY model ORDER BY cost DESC LIMIT 8-`;--const toolErrorsQuery = (id?: string): string => `-SELECT- properties.$ai_span_name AS tool,- count() AS calls,- countIf(toString(properties.$ai_is_error) = 'true') AS errors-FROM events-WHERE event = '$ai_span' AND ${scope(id)}- AND timestamp > now() - INTERVAL 7 DAY AND notEmpty(properties.$ai_span_name)-GROUP BY tool ORDER BY errors DESC, calls DESC LIMIT 8-`;--/**- * Build the five panel queries. `applicationId` scopes them to a single agent- * (the per-agent Observability tab); omit it for the fleet-wide board.- */-export function buildAgentAnalyticsQueries(applicationId?: string): {- kpi: string;- daily: string;- perAgent: string;- byModel: string;- toolErrors: string;-} {- return {- kpi: kpiQuery(applicationId),- daily: dailyQuery(applicationId),- perAgent: perAgentQuery(applicationId),- byModel: byModelQuery(applicationId),- toolErrors: toolErrorsQuery(applicationId),- };-}--const EMPTY_GRID: HogQLGrid = { results: [], columns: [] };--/** Zeroed placeholder rendered while the first load is in flight. */-export const EMPTY_AGENT_ANALYTICS: AgentAnalyticsData = {- kpis: { spendUsd: 0, sessions: 0, failureRate: 0, p95LatencyS: 0 },- daily: { labels: [], spend: [], sessions: [], failureRate: [] },- deltas: { spend: null, sessions: null, failureRatePoints: null },- byAgent: [],- byModel: [],- toolErrors: [],- empty: true,-};--function num(v: unknown): number {- const n = typeof v === "number" ? v : Number(v);- return Number.isFinite(n) ? n : 0;-}--function pctChange(recent: number, prior: number): number | null {- if (prior <= 0) {- return null;- }- return ((recent - prior) / prior) * 100;-}--function shortId(id: string): string {- return id.split("-").at(-1)?.slice(0, 8) ?? id.slice(0, 8);-}--function formatDay(iso: string): string {- const d = new Date(iso);- if (Number.isNaN(d.getTime())) {- return iso.slice(5, 10);- }- return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}--/** Coerce a raw HogQL grid into rows of cells, dropping non-array rows. */-function rows(grid: HogQLGrid | undefined): unknown[][] {- return (grid?.results ?? []).filter((r): r is unknown[] => Array.isArray(r));-}--/**- * Fold the five raw HogQL grids into the analytics dashboard shape. Pure: the- * caller fires the queries (and resolves `nameById` from the agent list).- */-export function shapeAgentAnalytics(- raw: Partial<AgentAnalyticsRaw>,- nameById: Map<string, string> = new Map(),-): AgentAnalyticsData {- // KPIs (single row): cost, sessions, errors, generations, p95- const k = rows(raw.kpi)[0] ?? [0, 0, 0, 0, 0];- const generations = num(k[3]);- const kpis = {- spendUsd: num(k[0]),- sessions: num(k[1]),- failureRate: generations > 0 ? num(k[2]) / generations : 0,- p95LatencyS: num(k[4]),- };-- // Daily 14-day series → sparklines + prior-vs-recent deltas.- const dayRows = rows(raw.daily);- const labels = dayRows.map((r) => formatDay(String(r[0])));- const spend = dayRows.map((r) => num(r[1]));- const sessionsByDay = dayRows.map((r) => num(r[2]));- const errorsByDay = dayRows.map((r) => num(r[3]));- const genByDay = dayRows.map((r) => num(r[4]));- const failureRate = dayRows.map((_, i) =>- genByDay[i] > 0 ? errorsByDay[i] / genByDay[i] : 0,- );-- const recent = (arr: number[]): number =>- arr.slice(-7).reduce((s, v) => s + v, 0);- const prior = (arr: number[]): number =>- arr.slice(0, Math.max(0, arr.length - 7)).reduce((s, v) => s + v, 0);- const recentGen = recent(genByDay);- const priorGen = prior(genByDay);- const recentRate = recentGen > 0 ? recent(errorsByDay) / recentGen : 0;- const priorRate = priorGen > 0 ? prior(errorsByDay) / priorGen : 0;- const deltas = {- spend: pctChange(recent(spend), prior(spend)),- sessions: pctChange(recent(sessionsByDay), prior(sessionsByDay)),- failureRatePoints: priorGen > 0 ? (recentRate - priorRate) * 100 : null,- };-- const byAgent = rows(raw.perAgent).map((r) => {- const id = String(r[0]);- const gens = num(r[2]);- return {- id,- name: nameById.get(id) ?? shortId(id),- sessions: num(r[1]),- spendUsd: num(r[3]),- tokens: num(r[4]),- failureRate: gens > 0 ? num(r[5]) / gens : 0,- p95LatencyS: num(r[6]),- };- });-- const byModel: AgentAnalyticsModelRow[] = rows(raw.byModel).map((r) => ({- model: String(r[0]),- spendUsd: num(r[1]),- calls: num(r[2]),- }));-- const toolErrors: AgentAnalyticsToolRow[] = rows(raw.toolErrors).map((r) => {- const calls = num(r[1]);- const errors = num(r[2]);- return {- tool: String(r[0]),- calls,- errors,- errorRate: calls > 0 ? errors / calls : 0,- };- });-- return {- kpis,- daily: { labels, spend, sessions: sessionsByDay, failureRate },- deltas,- byAgent,- byModel,- toolErrors,- empty: kpis.sessions === 0 && byAgent.length === 0 && generations === 0,- };-}--export { EMPTY_GRID };diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 91705757da10..373f19f9c293 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -1972,91 +1972,6 @@ describe("PostHogAPIClient", () => {});});- describe("agent model policy + catalog", () => {- function makeClient(fetch: ReturnType<typeof vi.fn>) {- const client = new PostHogAPIClient(- "http://localhost:8000",- async () => "token",- async () => "token",- 123,- );- (- client as unknown as {- api: { baseUrl: string; fetcher: { fetch: typeof fetch } };- }- ).api = { baseUrl: "http://localhost:8000", fetcher: { fetch } };- return client;- }-- it("createAgentDraftRevisionFrom unwraps the { revision } envelope", async () => {- // Regression: new_draft returns `{ revision, source_revision_id }`, not a- // flat revision — returning the wrapper left `.id` undefined and broke the- // follow-up PATCH (404 on /revisions/undefined/).- const fetch = vi.fn().mockResolvedValue({- json: async () => ({- revision: { id: "draft-1", state: "draft" },- source_revision_id: "rev-0",- }),- });- const client = makeClient(fetch);-- const rev = await client.createAgentDraftRevisionFrom("app-1", "rev-0");-- expect(rev.id).toBe("draft-1");- expect(fetch).toHaveBeenCalledWith(- expect.objectContaining({- method: "post",- path: "/api/projects/123/agent_applications/app-1/revisions/new_draft/",- overrides: {- body: JSON.stringify({- application_id: "app-1",- source_revision_id: "rev-0",- }),- },- }),- );- });-- it("updateAgentRevisionSpec PATCHes the revision with the full spec", async () => {- const fetch = vi.fn().mockResolvedValue({- json: async () => ({ id: "draft-1", state: "draft" }),- });- const client = makeClient(fetch);- const spec = { models: { mode: "auto", level: "high" } };-- await client.updateAgentRevisionSpec(- "agent-slug",- "draft-1",- spec as never,- );-- expect(fetch).toHaveBeenCalledWith(- expect.objectContaining({- method: "patch",- path: "/api/projects/123/agent_applications/agent-slug/revisions/draft-1/",- overrides: { body: JSON.stringify({ spec }) },- }),- );- });-- it("getAgentModelCatalog GETs the project-level models endpoint", async () => {- const catalog = {- models: [{ model: "anthropic/claude-haiku-4.5" }],- levels: { low: ["anthropic/claude-haiku-4.5"] },- };- const fetch = vi.fn().mockResolvedValue({ json: async () => catalog });- const client = makeClient(fetch);-- await expect(client.getAgentModelCatalog()).resolves.toEqual(catalog);- expect(fetch).toHaveBeenCalledWith(- expect.objectContaining({- method: "get",- path: "/api/projects/123/agent_applications/models/",- }),- );- });- });-describe("batched scout emissions", () => {const EMISSIONS_PATH ="/api/projects/123/signals/scout/runs/emissions/batch/";@@ -2552,243 +2467,6 @@ describe("PostHogAPIClient", () => {});});- describe("custom tool authoring", () => {- function makeClient(fetch: ReturnType<typeof vi.fn>) {- const client = new PostHogAPIClient(- "http://localhost:8000",- async () => "token",- async () => "token",- 123,- );- (- client as unknown as {- api: { baseUrl: string; fetcher: { fetch: typeof fetch } };- }- ).api = { baseUrl: "http://localhost:8000", fetcher: { fetch } };- return client;- }-- // The shared fetcher throws `Failed request: [<status>] <json>` on non-2xx.- const failWith = (status: number, body: unknown) =>- new Error(`Failed request: [${status}] ${JSON.stringify(body)}`);-- describe("putRevisionTool", () => {- it("returns an ok result with capabilities on 200", async () => {- const fetch = vi.fn().mockResolvedValue({- json: async () => ({- ok: true,- tool_id: "t1",- capabilities: {- secret_refs: ["API_KEY"],- dynamic_secret_refs: false,- },- }),- });- const client = makeClient(fetch);-- await expect(- client.putRevisionTool("agent", "rev-1", "t1", {- description: "d",- args_schema: {},- source: "export default {}",- }),- ).resolves.toEqual({- ok: true,- tool_id: "t1",- capabilities: {- secret_refs: ["API_KEY"],- dynamic_secret_refs: false,- },- });- const call = fetch.mock.calls[0][0];- expect(call.method).toBe("put");- expect(call.path).toBe(- "/api/projects/123/agent_applications/agent/revisions/rev-1/tools/t1/",- );- });-- it("returns a typed compile-failed result on 422 (not a throw)", async () => {- const errors = [- {- kind: "parse_failed",- message: "Unexpected token",- line: 3,- column: 5,- },- ];- const fetch = vi.fn().mockRejectedValue(- failWith(422, {- error: "tool_compile_failed",- tool_id: "t1",- errors,- }),- );- const client = makeClient(fetch);-- await expect(- client.putRevisionTool("agent", "rev-1", "t1", {- description: "d",- args_schema: {},- source: "bad(",- }),- ).resolves.toEqual({- ok: false,- error: "tool_compile_failed",- tool_id: "t1",- errors,- });- });-- it("rethrows non-422 failures (e.g. 409 sealed revision)", async () => {- const fetch = vi- .fn()- .mockRejectedValue(failWith(409, { error: "revision_sealed" }));- const client = makeClient(fetch);-- await expect(- client.putRevisionTool("agent", "rev-1", "t1", {- description: "d",- args_schema: {},- source: "x",- }),- ).rejects.toThrow("[409]");- });- });-- describe("deleteRevisionTool", () => {- it("resolves on 200", async () => {- const fetch = vi.fn().mockResolvedValue({ json: async () => ({}) });- const client = makeClient(fetch);- await expect(- client.deleteRevisionTool("agent", "rev-1", "t1"),- ).resolves.toBeUndefined();- expect(fetch.mock.calls[0][0].method).toBe("delete");- });-- it("treats a 404 (tool_not_found) as success", async () => {- const fetch = vi- .fn()- .mockRejectedValue(failWith(404, { error: "tool_not_found" }));- const client = makeClient(fetch);- await expect(- client.deleteRevisionTool("agent", "rev-1", "gone"),- ).resolves.toBeUndefined();- });-- it("rethrows other failures", async () => {- const fetch = vi.fn().mockRejectedValue(failWith(500, "boom"));- const client = makeClient(fetch);- await expect(- client.deleteRevisionTool("agent", "rev-1", "t1"),- ).rejects.toThrow("[500]");- });- });-- describe("dryRunRevisionTool", () => {- it("returns a completed envelope on a 200 success", async () => {- const envelope = {- ok: true,- tool_id: "t1",- result: { hello: "world" },- duration_ms: 42,- };- const fetch = vi.fn().mockResolvedValue({ json: async () => envelope });- const client = makeClient(fetch);-- await expect(- client.dryRunRevisionTool("agent", "rev-1", "t1", { args: {} }),- ).resolves.toEqual({ outcome: "completed", envelope });- });-- it("returns a completed envelope for a 200 with ok:false (tool threw)", async () => {- const envelope = {- ok: false,- tool_id: "t1",- error: { code: "timeout", message: "wall clock exceeded" },- duration_ms: 5000,- };- const fetch = vi.fn().mockResolvedValue({ json: async () => envelope });- const client = makeClient(fetch);-- await expect(- client.dryRunRevisionTool("agent", "rev-1", "t1", { args: {} }),- ).resolves.toEqual({ outcome: "completed", envelope });- });-- it("surfaces a 500 envelope as completed (infra failure carries error.code)", async () => {- const envelope = {- ok: false,- tool_id: "t1",- error: { code: "sandbox_acquire_failed", message: "no sandbox" },- duration_ms: 12,- };- const fetch = vi.fn().mockRejectedValue(failWith(500, envelope));- const client = makeClient(fetch);-- await expect(- client.dryRunRevisionTool("agent", "rev-1", "t1", { args: {} }),- ).resolves.toEqual({ outcome: "completed", envelope });- });-- it("returns a throttled outcome on 429 (never throws, carries max_concurrent)", async () => {- const fetch = vi- .fn()- .mockRejectedValue(- failWith(429, { error: "dry_run_throttled", max_concurrent: 2 }),- );- const client = makeClient(fetch);-- await expect(- client.dryRunRevisionTool("agent", "rev-1", "t1", { args: {} }),- ).resolves.toEqual({ outcome: "throttled", max_concurrent: 2 });- });-- it("throttles without a count when max_concurrent is absent", async () => {- const fetch = vi- .fn()- .mockRejectedValue(failWith(429, { error: "dry_run_throttled" }));- const client = makeClient(fetch);-- const result = await client.dryRunRevisionTool("agent", "rev-1", "t1", {- args: {},- });- expect(result).toEqual({ outcome: "throttled" });- expect(- (result as { max_concurrent?: number }).max_concurrent,- ).toBeUndefined();- });-- it("returns an unavailable outcome on 503", async () => {- const fetch = vi- .fn()- .mockRejectedValue(failWith(503, "not configured"));- const client = makeClient(fetch);-- await expect(- client.dryRunRevisionTool("agent", "rev-1", "t1", { args: {} }),- ).resolves.toEqual({ outcome: "unavailable" });- });-- it("passes mock_secrets through in the request body", async () => {- const fetch = vi.fn().mockResolvedValue({- json: async () => ({ ok: true, tool_id: "t1", duration_ms: 1 }),- });- const client = makeClient(fetch);-- await client.dryRunRevisionTool("agent", "rev-1", "t1", {- args: { q: 1 },- mock_secrets: { API_KEY: "placeholder" },- });-- const body = JSON.parse(fetch.mock.calls[0][0].overrides.body);- expect(body).toEqual({- args: { q: 1 },- mock_secrets: { API_KEY: "placeholder" },- });- });- });- });-describe("getMcpServerIconUrl", () => {function makeClient(fetch: ReturnType<typeof vi.fn>) {const client = new PostHogAPIClient(diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 7e925b7e3c9c..75d2d27b3029 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -21,39 +21,6 @@ import {normalizeGatewayModelsResponse,resolveCloudInitialPermissionMode,} from "@posthog/shared";-import type {- AgentAnalyticsData,- AgentApplication,- AgentApplicationSessionDetail,- AgentApplicationSessionsListResponse,- AgentApprovalRequest,- AgentApprovalsListParams,- AgentFleetLiveSessionsResponse,- AgentMemoryFile,- AgentMemorySearchResult,- AgentMemoryTableHeader,- AgentMemoryTableRows,- AgentMemoryTreeNode,- AgentPreviewToken,- AgentRevision,- AgentSessionEvent,- AgentSessionLogEntry,- AgentSessionLogsParams,- AgentSessionsListParams,- AgentSlackManifest,- AgentSpec,- AgentUsersListResponse,- BundleFile,- DecideApprovalRequest,- DryRunToolEnvelope,- DryRunToolRequest,- DryRunToolResult,- ModelCatalog,- ToolCapabilities,- ToolCompileError,- WriteToolRequest,- WriteToolResult,-} from "@posthog/shared/agent-platform-types";import type {ActionabilityJudgmentArtefact,AvailableSuggestedReviewer,@@ -104,11 +71,6 @@ import type {UserBasic,} from "@posthog/shared/domain-types";import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";-import {- buildAgentAnalyticsQueries,- type HogQLGrid,- shapeAgentAnalytics,-} from "./agent-analytics";import {compactCount,dailySparkPoints,@@ -166,6 +128,11 @@ import {type TaskRunArtifactDTO,} from "./task-normalization";+interface HogQLGrid {+ results: unknown[][];+ columns: string[];+}+export type * from "./mcp-gateway";export interface ApiClientLogger {warn(...args: unknown[]): void;@@ -990,29 +957,6 @@ function extractRequestErrorMessage(error: unknown, fallback: string): string {return `${fallback} (HTTP ${match[1]})`;}-/**- * Parse the shared fetcher's `Failed request: [<status>] <json-body>` throw back- * into its status + parsed JSON body, so status-specific responses (422, 429,- * 500, 503) can be handled as data instead of a generic error. Returns null when- * the error isn't that shape (e.g. a network failure).- */-function parseFailedRequest(- error: unknown,-): { status: number; body: unknown } | null {- const raw = error instanceof Error ? error.message : String(error);- const match = raw.match(/^Failed request: \[(\d+)\] (.*)$/s);- if (!match) {- return null;- }- let body: unknown;- try {- body = JSON.parse(match[2]);- } catch {- body = match[2];- }- return { status: Number(match[1]), body };-}-type AnyArtefact =| SignalReportArtefact| PriorityJudgmentArtefact@@ -1589,18 +1533,6 @@ function parseAvailableSuggestedReviewersPayload(};}-/**- * Wraps the ingress preview token in the `parameters.header` shape the fetcher- * merges into request headers without clobbering the auth bearer. Returns- * `undefined` when there is no token so unmodified ingress calls stay byte-for-- * byte identical to today.- */-function previewTokenHeader(- token: string | null | undefined,-): { header: { "X-Agent-Preview-Token": string } } | undefined {- return token ? { header: { "X-Agent-Preview-Token": token } } : undefined;-}-export class PostHogAPIClient {private api: ReturnType<typeof createApiClient>;private _teamId: number | null = null;@@ -6043,1213 +5975,92 @@ export class PostHogAPIClient {return (await response.json()) as LlmSkillFile;}- // --- Agent platform ------------------------------------------------------- // Deployed agents (`agent_platform` Django app). These routes aren't in the- // generated OpenAPI client, so they use the raw fetcher. Applications are- // addressable by UUID or slug in the `{idOrSlug}` segment.-- private agentApplicationsPath(teamId: number): string {- return `/api/projects/${teamId}/agent_applications/`;- }-- /** Lists non-archived agent applications for the current team. */- async listAgentApplications(): Promise<AgentApplication[]> {- const MAX_PAGES = 50;- const teamId = await this.getTeamId();- const all: AgentApplication[] = [];- let urlPath = `${this.agentApplicationsPath(teamId)}?limit=100`;- for (let i = 0; i < MAX_PAGES; i++) {- const url = new URL(`${this.api.baseUrl}${urlPath}`);- const response = await this.api.fetcher.fetch({- method: "get",- url,- path: urlPath,- });- const page = (await response.json()) as {- results?: AgentApplication[];- next?: string | null;- };- all.push(...(page.results ?? []));- if (!page.next) return all;- const nextUrl = new URL(page.next);- urlPath = `${nextUrl.pathname}${nextUrl.search}`;- }- return all;- }-- /** Fetches a single agent application by UUID or slug; null if not found. */- async getAgentApplication(- idOrSlug: string,- ): Promise<AgentApplication | null> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- try {- const response = await this.api.fetcher.fetch({- method: "get",- url,- path,- });- return (await response.json()) as AgentApplication;- } catch (error) {- const msg = error instanceof Error ? error.message : String(error);- if (msg.includes("[404]") || msg.includes("[403]")) {- return null;- }- throw error;- }- }-- /** Lists sessions for an application (paginated, filterable by state). */- async listAgentApplicationSessions(- idOrSlug: string,- params?: AgentSessionsListParams,- ): Promise<AgentApplicationSessionsListResponse> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/sessions/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (params?.limit != null) {- url.searchParams.set("limit", String(params.limit));- }- if (params?.offset != null) {- url.searchParams.set("offset", String(params.offset));- }- if (params?.state?.length) {- url.searchParams.set("state", params.state.join(","));- }- if (params?.revision_id) {- url.searchParams.set("revision_id", params.revision_id);- }- if (params?.agent_user_id) {- url.searchParams.set("agent_user_id", params.agent_user_id);- }- if (params?.created_after) {- url.searchParams.set("created_after", params.created_after);- }- if (params?.created_before) {- url.searchParams.set("created_before", params.created_before);- }- if (params?.search?.trim()) {- url.searchParams.set("search", params.search.trim());- }- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- results?: AgentApplicationSessionsListResponse["results"];- count?: number;- };- return {- results: data.results ?? [],- count: data.count ?? data.results?.length ?? 0,- };- }-- /** Full session detail incl. transcript; `lastN` trims to trailing messages. */- async getAgentApplicationSession(- idOrSlug: string,- sessionId: string,- lastN?: number,- ): Promise<AgentApplicationSessionDetail | null> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/sessions/${encodeURIComponent(sessionId)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (lastN != null) {- url.searchParams.set("last_n", String(lastN));- }- try {- const response = await this.api.fetcher.fetch({- method: "get",- url,- path,- });- return (await response.json()) as AgentApplicationSessionDetail;- } catch (error) {- const msg = error instanceof Error ? error.message : String(error);- if (msg.includes("[404]") || msg.includes("[403]")) {- return null;- }- throw error;- }- }-- /** Structured runtime logs for one session (ClickHouse log_entries). */- async getAgentApplicationSessionLogs(- idOrSlug: string,- sessionId: string,- params?: AgentSessionLogsParams,- ): Promise<AgentSessionLogEntry[]> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/sessions/${encodeURIComponent(sessionId)}/logs/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (params?.limit != null) {- url.searchParams.set("limit", String(params.limit));- }- if (params?.level?.length) {- url.searchParams.set("level", params.level.join(","));- }- if (params?.search) {- url.searchParams.set("search", params.search);- }- if (params?.after) {- url.searchParams.set("after", params.after);- }- if (params?.before) {- url.searchParams.set("before", params.before);- }- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- results?: AgentSessionLogEntry[];- };- return data.results ?? [];- }-- /** Lists tool-approval requests for an application (team-admin only). */- async listAgentApplicationApprovals(- idOrSlug: string,- params?: AgentApprovalsListParams,- ): Promise<AgentApprovalRequest[]> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/approvals/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (params?.state) {- url.searchParams.set("state", params.state);- }- if (params?.limit != null) {- url.searchParams.set("limit", String(params.limit));- }- if (params?.offset != null) {- url.searchParams.set("offset", String(params.offset));- }- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- results?: AgentApprovalRequest[];- };- return data.results ?? [];- }-- /** Approve or reject a queued tool-approval request. */- async decideAgentApproval(- idOrSlug: string,- approvalId: string,- body: DecideApprovalRequest,- ): Promise<AgentApprovalRequest> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/approvals/${encodeURIComponent(approvalId)}/decide/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- overrides: { body: JSON.stringify(body) },- });- return (await response.json()) as AgentApprovalRequest;- }-- /** Lists revisions for an application (newest first, paginated). */- async listAgentRevisions(idOrSlug: string): Promise<AgentRevision[]> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/`;- const url = new URL(`${this.api.baseUrl}${path}?limit=100`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as { results?: AgentRevision[] };- return data.results ?? [];- }-- /** Fetches a single revision by id; null if not found. */- async getAgentRevision(- idOrSlug: string,- revisionId: string,- ): Promise<AgentRevision | null> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- try {- const response = await this.api.fetcher.fetch({- method: "get",- url,- path,- });- return (await response.json()) as AgentRevision;- } catch (error) {- const msg = error instanceof Error ? error.message : String(error);- if (msg.includes("[404]") || msg.includes("[403]")) {- return null;- }- throw error;- }- }-/**- * Mint a short-lived preview token (HS256 JWT) for a non-live revision. The- * token is sent to the ingress on /run /send /listen /cancel via- * `X-Agent-Preview-Token` (alongside the usual bearer) and authorizes those- * calls to route against this specific revision instead of `live_revision`.- * The response also self-describes the per-trigger ingress URLs the caller- * should hit (`endpoints`) so the client never has to construct preview URLs- * by string-mangling `ingress_base_url`.- *- * Note the Django route: app-level path with the revision as a query param,- * NOT nested under /revisions/{id}/.+ * Runs a read-only HogQL query against the team's project and returns the raw+ * result grid. Backs the agent observability rollups (`$ai_*` events the+ * runner captures into this team's own project). The endpoint can answer 200+ * with an `error` field; that's surfaced as a throw.*/- async mintAgentPreviewToken(- idOrSlug: string,- revisionId: string,- ): Promise<AgentPreviewToken> {+ async runHogQLQuery(query: string): Promise<HogQLGrid> {const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/preview-token/`;+ const path = `/api/projects/${teamId}/query/`;const url = new URL(`${this.api.baseUrl}${path}`);- url.searchParams.set("revision_id", revisionId);const response = await this.api.fetcher.fetch({method: "post",url,path,+ overrides: {+ body: JSON.stringify({ query: { kind: "HogQLQuery", query } }),+ },});- return (await response.json()) as AgentPreviewToken;+ const data = (await response.json()) as {+ results?: unknown[][];+ columns?: string[];+ error?: string | null;+ };+ if (data.error) {+ throw new Error(data.error);+ }+ return { results: data.results ?? [], columns: data.columns ?? [] };}/**- * Atomically create a fresh draft revision under this app, seeded with the- * full bundle of `sourceRevisionId`. The standard "edit an immutable- * revision" exit: ready/live/archived bundles are stamped and locked, so- * iterating on them requires forking to a new draft first. Both ids are- * UUIDs; the app's `slug` is not accepted here (the body needs the UUID).+ * Runs an arbitrary typed query node (TrendsQuery, HogQLQuery, ...) against+ * the team's project and returns the raw response. `refresh: "blocking"`+ * serves a fresh-enough cached result and computes synchronously otherwise —+ * the same mode PostHog insights use. Backs inbox report charts, whose query+ * nodes are scout-authored and arrive unparsed.*/- async createAgentDraftRevisionFrom(- applicationId: string,- sourceRevisionId: string,- ): Promise<AgentRevision> {+ async runQuery(+ query: Record<string, unknown>,+ ): Promise<Record<string, unknown>> {const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(applicationId)}/revisions/new_draft/`;+ const path = `/api/projects/${teamId}/query/`;const url = new URL(`${this.api.baseUrl}${path}`);const response = await this.api.fetcher.fetch({method: "post",url,path,overrides: {- body: JSON.stringify({- application_id: applicationId,- source_revision_id: sourceRevisionId,- }),+ body: JSON.stringify({ query, refresh: "blocking" }),},});- // new_draft wraps the created revision: `{ revision, source_revision_id }`.- const data = (await response.json()) as { revision: AgentRevision };- return data.revision;- }-- /** The served-model catalog + curated auto-level → model map (project-agnostic;- * proxies the AI gateway catalog). Powers the config-pane model browser. */- async getAgentModelCatalog(): Promise<ModelCatalog> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}models/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- return (await response.json()) as ModelCatalog;- }-- /** Update a draft revision's spec (PATCH). Draft-only on the server — a- * ready/live spec is frozen. Replaces `spec` wholesale, so callers send the- * full updated spec. Returns the updated revision. */- async updateAgentRevisionSpec(- idOrSlug: string,- revisionId: string,- spec: AgentSpec,- ): Promise<AgentRevision> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "patch",- url,- path,- overrides: { body: JSON.stringify({ spec }) },- });- return (await response.json()) as AgentRevision;- }-- /** Run a revision lifecycle transition: freeze (draft→ready), promote- * (ready→live, demoting the old live), or archive. Returns the updated revision. */- async transitionAgentRevision(- idOrSlug: string,- revisionId: string,- action: "freeze" | "promote" | "archive",- ): Promise<AgentRevision> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/${action}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- });- return (await response.json()) as AgentRevision;+ const data = (await response.json()) as Record<string, unknown>;+ if (typeof data.error === "string" && data.error) {+ throw new Error(data.error);+ }+ return data;}/**- * Write a single bundle file on a draft revision. The server accepts- * `agent.md` and `skills/<id>/SKILL.md` paths only — tool source / schema- * stay read-only this round. Ready / live / archived revisions return 409.+ * The insight's identity and query node, by short id. Backs saved-insight+ * chart cards in agent messages: the caller plans and runs the query.*/- async updateAgentDraftBundleFile(- idOrSlug: string,- revisionId: string,- filePath: string,- content: string,- ): Promise<AgentRevision> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/bundle/file/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "put",- url,- path,- overrides: {- body: JSON.stringify({ path: filePath, content }),- },+ async getInsightDefinition(shortId: string): Promise<{+ name: string | null;+ description: string | null;+ query: unknown;+ } | null> {+ const projectId = (await this.getTeamId()).toString();+ const page = await this.api.get("/api/projects/{project_id}/insights/", {+ path: { project_id: projectId },+ query: { short_id: shortId },});- return (await response.json()) as AgentRevision;+ const insight = page.results[0];+ if (!insight) return null;+ return {+ name: insight.name || insight.derived_name || null,+ description: insight.description || null,+ query: insight.query ?? null,+ };}/**- * Bulk-import a set of `.md` files into a draft revision's bundle — the- * migration hatch for porting an existing multi-file agent in one paste.- * Sets `agent_md` if present and merges `skills[]` by id (adds new ids,- * overwrites bodies for existing ids; skills not mentioned are left alone).- * Draft-only; ready / live / archived return 409.- */- async importAgentDraftBundle(- idOrSlug: string,- revisionId: string,- body: {- agent_md?: string;- skills?: { id: string; description?: string; body: string }[];- },- ): Promise<AgentRevision> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/bundle/import/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- overrides: {- body: JSON.stringify(body),- },- });- return (await response.json()) as AgentRevision;- }-- /**- * A revision's bundle, flattened to per-file rows. The server returns a typed- * `{ bundle: { agent_md, skills[], tools[] } }`; we expand it to the canonical- * file paths the explorer renders (agent.md, skills/<id>/SKILL.md,- * tools/<id>/source.ts, tools/<id>/schema.json).- */- async getAgentRevisionBundle(- idOrSlug: string,- revisionId: string,- ): Promise<BundleFile[]> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/bundle/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- bundle?: {- agent_md?: string;- skills?: { id: string; description?: string; body: string }[];- tools?: {- id: string;- description?: string;- args_schema?: Record<string, unknown>;- source: string;- }[];- };- };- const bundle = data.bundle ?? {};- const out: BundleFile[] = [];- if (bundle.agent_md !== undefined) {- out.push({- path: "agent.md",- content: bundle.agent_md,- language: "markdown",- });- }- for (const skill of bundle.skills ?? []) {- out.push({- path: `skills/${skill.id}/SKILL.md`,- content: skill.body,- language: "markdown",- });- }- for (const tool of bundle.tools ?? []) {- out.push({- path: `tools/${tool.id}/source.ts`,- content: tool.source,- language: "typescript",- });- out.push({- path: `tools/${tool.id}/schema.json`,- content: JSON.stringify(- { description: tool.description, args_schema: tool.args_schema },- null,- 2,- ),- language: "json",- });- }- out.sort((a, b) => a.path.localeCompare(b.path));- return out;- }-- /**- * Author/compile one custom tool on a draft revision (PUT). Draft-only —- * ready/live/archived bundles are sealed and the server returns a conflict.- * A compile failure (HTTP 422) is returned as a typed `{ ok: false }` result- * carrying `errors`, so the caller renders diagnostics inline against the- * source rather than surfacing a generic failure; other non-2xx (400- * invalid_request, 409 sealed revision, …) still throw.- */- async putRevisionTool(- idOrSlug: string,- revisionId: string,- toolId: string,- body: WriteToolRequest,- ): Promise<WriteToolResult> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/tools/${encodeURIComponent(toolId)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- try {- const response = await this.api.fetcher.fetch({- method: "put",- url,- path,- overrides: { body: JSON.stringify(body) },- });- const data = (await response.json()) as {- tool_id: string;- capabilities: ToolCapabilities;- };- return {- ok: true,- tool_id: data.tool_id,- capabilities: data.capabilities,- };- } catch (error) {- const failure = parseFailedRequest(error);- if (- failure?.status === 422 &&- isObjectRecord(failure.body) &&- failure.body.error === "tool_compile_failed"- ) {- return {- ok: false,- error: "tool_compile_failed",- tool_id: optionalString(failure.body.tool_id) ?? toolId,- errors: Array.isArray(failure.body.errors)- ? (failure.body.errors as ToolCompileError[])- : [],- };- }- throw error;- }- }-- /**- * Remove one custom tool from a draft revision (draft-only). A 404- * (tool_not_found) is treated as success — the tool is already gone, which is- * the desired end state.- */- async deleteRevisionTool(- idOrSlug: string,- revisionId: string,- toolId: string,- ): Promise<void> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/tools/${encodeURIComponent(toolId)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- try {- await this.api.fetcher.fetch({ method: "delete", url, path });- } catch (error) {- const failure = parseFailedRequest(error);- if (failure?.status === 404) {- return;- }- throw error;- }- }-- /**- * Execute a persisted tool once in a sandbox (POST …/dry_run). The envelope's- * `ok` is authoritative: a tool-side failure is HTTP 200 with `ok: false`, so- * both 2xx and 500 return `{ outcome: "completed", envelope }` and the caller- * reads `error.code`/`message` from the body. Throttling (429) and an- * unconfigured backend (503) are returned as distinct outcomes — never thrown,- * never retried, since dry-run is interactive and process-capped.- */- async dryRunRevisionTool(- idOrSlug: string,- revisionId: string,- toolId: string,- body: DryRunToolRequest,- ): Promise<DryRunToolResult> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/tools/${encodeURIComponent(toolId)}/dry_run/`;- const url = new URL(`${this.api.baseUrl}${path}`);- try {- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- overrides: { body: JSON.stringify(body) },- });- return {- outcome: "completed",- envelope: (await response.json()) as DryRunToolEnvelope,- };- } catch (error) {- const failure = parseFailedRequest(error);- // A 500 still carries the envelope (ok:false + error.code/duration_ms) —- // surface it as completed so infra failures read like any tool failure.- if (- failure?.status === 500 &&- isObjectRecord(failure.body) &&- "ok" in failure.body- ) {- return {- outcome: "completed",- envelope: failure.body as unknown as DryRunToolEnvelope,- };- }- if (failure?.status === 429) {- const max = isObjectRecord(failure.body)- ? failure.body.max_concurrent- : undefined;- // Omit rather than default to 0 — "0 runs in flight" would be a- // misleading count for a throttle.- return {- outcome: "throttled",- max_concurrent: typeof max === "number" ? max : undefined,- };- }- if (failure?.status === 503) {- return { outcome: "unavailable" };- }- throw error;- }- }-- /**- * The Slack app manifest derived from a revision's slack trigger + tools,- * plus the live Event/Interactivity request URLs and setup notes.- */- async getAgentSlackManifest(- idOrSlug: string,- revisionId: string,- ): Promise<AgentSlackManifest> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/slack_manifest/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- return (await response.json()) as AgentSlackManifest;- }-- /** Fire a cron trigger out-of-band; returns the created session id. */- async fireAgentCron(- idOrSlug: string,- revisionId: string,- cronName: string,- requestId?: string,- ): Promise<{ session_id: string }> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/cron/fire/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- overrides: {- body: JSON.stringify({- cron_name: cronName,- ...(requestId ? { request_id: requestId } : {}),- }),- },- });- return (await response.json()) as { session_id: string };- }-- /**- * The names of env keys currently set on a revision (values never returned).- * Env keys are scoped to a revision, so each revision carries its own secret- * set.- */- async listAgentEnvKeys(- idOrSlug: string,- revisionId: string,- ): Promise<string[]> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/env_keys/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- keys?: string[];- results?: string[];- };- return data.keys ?? data.results ?? [];- }-- /** Set or rotate one encrypted env key on a revision. The value is write-only. */- async setAgentEnvKey(- idOrSlug: string,- revisionId: string,- key: string,- value: string,- ): Promise<void> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/env_keys/${encodeURIComponent(key)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- await this.api.fetcher.fetch({- method: "put",- url,- path,- overrides: { body: JSON.stringify({ value }) },- });- }-- /** Clear one encrypted env key on a revision. No-op server-side if it isn't set. */- async clearAgentEnvKey(- idOrSlug: string,- revisionId: string,- key: string,- ): Promise<void> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/env_keys/${encodeURIComponent(key)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- await this.api.fetcher.fetch({ method: "delete", url, path });- }-- private agentMemoryPath(teamId: number, idOrSlug: string): string {- return `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/memory`;- }-- /** Pre-aggregated folder tree of the agent's memory store. */- async getAgentMemoryTree(idOrSlug: string): Promise<AgentMemoryTreeNode> {- const teamId = await this.getTeamId();- const path = `${this.agentMemoryPath(teamId, idOrSlug)}/tree/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as { root?: AgentMemoryTreeNode };- return data.root ?? { name: "root", type: "folder", children: [] };- }-- /** Read one memory file (header + content). */- async readAgentMemoryFile(- idOrSlug: string,- filePath: string,- ): Promise<AgentMemoryFile> {- const teamId = await this.getTeamId();- const path = `${this.agentMemoryPath(teamId, idOrSlug)}/files/by_path/`;- const url = new URL(`${this.api.baseUrl}${path}`);- url.searchParams.set("path", filePath);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- return (await response.json()) as AgentMemoryFile;- }-- /** BM25 full-text search across the agent's memory. */- async searchAgentMemory(- idOrSlug: string,- query: string,- limit?: number,- ): Promise<AgentMemorySearchResult[]> {- const teamId = await this.getTeamId();- const path = `${this.agentMemoryPath(teamId, idOrSlug)}/search/`;- const url = new URL(`${this.api.baseUrl}${path}`);- url.searchParams.set("q", query);- if (limit != null) url.searchParams.set("limit", String(limit));- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- results?: AgentMemorySearchResult[];- };- return data.results ?? [];- }-- /** List the agent's JSONL reference tables. */- async listAgentMemoryTables(- idOrSlug: string,- ): Promise<AgentMemoryTableHeader[]> {- const teamId = await this.getTeamId();- const path = `${this.agentMemoryPath(teamId, idOrSlug)}/tables/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- tables?: AgentMemoryTableHeader[];- };- return data.tables ?? [];- }-- /** Read rows from one memory table. */- async readAgentMemoryTable(- idOrSlug: string,- name: string,- limit?: number,- ): Promise<AgentMemoryTableRows> {- const teamId = await this.getTeamId();- const path = `${this.agentMemoryPath(teamId, idOrSlug)}/tables/${encodeURIComponent(name)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (limit != null) url.searchParams.set("limit", String(limit));- const response = await this.api.fetcher.fetch({ method: "get", url, path });- return (await response.json()) as AgentMemoryTableRows;- }-- // --- Users / connections --------------------------------------------------- // The agent's end-users (`agent_user`) and their linked external identities- // (`agent_identity_credential`). Connection metadata only — encrypted tokens- // never cross this boundary. Proxied Django → janitor → runtime store, same- // shape as the memory endpoints above.-- /** List the agent's end-users, each with their linked connections. */- async listAgentUsers(idOrSlug: string): Promise<AgentUsersListResponse> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/users/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({ method: "get", url, path });- // The fetcher doesn't throw on non-2xx — surface a genuine failure so the- // pane shows its error branch rather than masking it as "no users yet"- // (a non-2xx that still returns JSON would otherwise coalesce to `[]`).- if (!response.ok) {- throw new Error(`Failed to load agent users: ${response.status}`);- }- const data = (await response.json()) as Partial<AgentUsersListResponse>;- return { results: data.results ?? [], count: data.count ?? 0 };- }-- /** Revoke one linked connection for an agent user (kept for audit, not deleted). */- async deleteAgentUserConnection(- idOrSlug: string,- agentUserId: string,- provider: string,- ): Promise<void> {- const teamId = await this.getTeamId();- const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/users/${encodeURIComponent(agentUserId)}/connections/${encodeURIComponent(provider)}/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "delete",- url,- path,- });- // The fetcher doesn't throw on non-2xx. Revoke is a destructive, audited- // action — fail loudly so the caller's onError fires instead of a false- // "Connection revoked" success. 404 is treated as already-gone (idempotent).- if (!response.ok && response.status !== 404) {- throw new Error(`Failed to revoke connection: ${response.status}`);- }- }-- // --- Live chat (agent-ingress) -------------------------------------------- // These hit the agent's ingress host (`ingress_base_url`, which already- // includes `/agents/<slug>`), not the PostHog API. The shared fetcher- // attaches the same bearer regardless of host, so no proxy is needed (unlike- // the console, which proxied only because browser EventSource can't set- // an Authorization header — `fetch` can).- //- // `previewToken`, when present, scopes the call to a non-live revision via- // `X-Agent-Preview-Token`. The fetcher merges `parameters.header` into the- // built headers (so the bearer survives) — never put preview-token into- // `overrides.headers`, which replaces the whole headers object.-- /** Start a chat session; returns the new session id. */- async runAgentSession(- ingressBaseUrl: string,- message: string,- previewToken?: string | null,- supportedClientTools?: readonly string[],- ): Promise<{ session_id: string; resumed?: boolean }> {- const url = new URL(`${ingressBaseUrl.replace(/\/$/, "")}/run`);- // `supported_client_tools`: the kind:'client' tool ids this client can- // execute this session, so the runner exposes only those to the model.- const body: Record<string, unknown> = { message };- if (supportedClientTools && supportedClientTools.length > 0) {- body.supported_client_tools = supportedClientTools;- }- const response = await this.api.fetcher.fetch({- method: "post",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: { body: JSON.stringify(body) },- });- return (await response.json()) as { session_id: string; resumed?: boolean };- }-- /** Send a follow-up user message to an open session. */- async sendAgentMessage(- ingressBaseUrl: string,- sessionId: string,- message: string,- previewToken?: string | null,- ): Promise<void> {- const url = new URL(`${ingressBaseUrl.replace(/\/$/, "")}/send`);- await this.api.fetcher.fetch({- method: "post",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: { body: JSON.stringify({ session_id: sessionId, message }) },- });- }-- /**- * Decide a `principal`-type tool approval at the ingress, as the session- * principal. The ingress authenticates the preview token / passthrough bearer- * and enforces principal-match — this is the session owner clearing their own- * gated call, not the owner-console (Django) decision path. `agent`-type- * approvals are NOT decidable here; they go through `decideAgentApproval`.- */- async decideAgentApprovalViaIngress(- ingressBaseUrl: string,- approvalId: string,- body: DecideApprovalRequest,- previewToken?: string | null,- ): Promise<{ ok: boolean; state: string }> {- const url = new URL(- `${ingressBaseUrl.replace(/\/$/, "")}/approvals/${encodeURIComponent(approvalId)}/decide`,- );- const response = await this.api.fetcher.fetch({- method: "post",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: { body: JSON.stringify(body) },- });- return (await response.json()) as { ok: boolean; state: string };- }-- /**- * Fetch one approval by id straight from the agent's ingress, authenticated as- * the session principal (the shared bearer). Powers the deep-link approval- * modal: no project-scoped lookup, so it resolves from any project. Returns- * null on 404/403 (gone, or the caller isn't the session principal).- */- async getAgentApprovalViaIngress(- ingressBaseUrl: string,- approvalId: string,- previewToken?: string | null,- ): Promise<AgentApprovalRequest | null> {- const url = new URL(- `${ingressBaseUrl.replace(/\/$/, "")}/approvals/${encodeURIComponent(approvalId)}`,- );- try {- const response = await this.api.fetcher.fetch({- method: "get",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- });- return (await response.json()) as AgentApprovalRequest;- } catch (error) {- const msg = error instanceof Error ? error.message : String(error);- if (msg.includes("[404]") || msg.includes("[403]")) {- return null;- }- throw error;- }- }-- /**- * Fetch a session's transcript straight from the agent's ingress, authenticated- * as the session principal — cross-project transcript reload (dock reopen, a- * web chat-list opening a past session, repainting a pending-approval card- * after a reconnect). Mirrors `getAgentApplicationSession`'s shape; `lastN`- * trims to the trailing messages. Null on 404/403.- */- async getAgentSessionViaIngress(- ingressBaseUrl: string,- sessionId: string,- lastN?: number,- previewToken?: string | null,- ): Promise<AgentApplicationSessionDetail | null> {- const url = new URL(- `${ingressBaseUrl.replace(/\/$/, "")}/sessions/${encodeURIComponent(sessionId)}`,- );- if (lastN != null) {- url.searchParams.set("last_n", String(lastN));- }- try {- const response = await this.api.fetcher.fetch({- method: "get",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- });- return (await response.json()) as AgentApplicationSessionDetail;- } catch (error) {- const msg = error instanceof Error ? error.message : String(error);- if (msg.includes("[404]") || msg.includes("[403]")) {- return null;- }- throw error;- }- }-- /** Return a client-tool result to an open session. */- async sendAgentClientToolResult(- ingressBaseUrl: string,- sessionId: string,- callId: string,- outcome: { result?: unknown; error?: string },- previewToken?: string | null,- ): Promise<void> {- const url = new URL(- `${ingressBaseUrl.replace(/\/$/, "")}/client_tool_result`,- );- await this.api.fetcher.fetch({- method: "post",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: {- body: JSON.stringify({- session_id: sessionId,- call_id: callId,- ...outcome,- }),- },- });- }-- /**- * Return an *interactive* client-tool outcome (e.g. `set_secret`). Unlike the- * sync `/client_tool_result` path, the server-side tool returned `queued` and- * parked the session; posting the outcome via `/send` (as a `client_tool_result`- * marker) wakes it on a fresh turn. Exactly one of `result` / `error` is set.- */- async sendAgentInteractiveToolResult(- ingressBaseUrl: string,- sessionId: string,- callId: string,- outcome: { result: Record<string, unknown> } | { error: string },- previewToken?: string | null,- ): Promise<void> {- const url = new URL(`${ingressBaseUrl.replace(/\/$/, "")}/send`);- const clientToolResult =- "error" in outcome- ? { call_id: callId, error: outcome.error }- : { call_id: callId, result: outcome.result };- await this.api.fetcher.fetch({- method: "post",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: {- body: JSON.stringify({- session_id: sessionId,- client_tool_result: clientToolResult,- }),- },- });- }-- /** Cancel an open session (terminal). */- async cancelAgentSession(- ingressBaseUrl: string,- sessionId: string,- previewToken?: string | null,- ): Promise<void> {- const url = new URL(`${ingressBaseUrl.replace(/\/$/, "")}/cancel`);- await this.api.fetcher.fetch({- method: "post",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: { body: JSON.stringify({ session_id: sessionId }) },- });- }-- /**- * Stream a session's SSE events as an async iterator. Reads the raw response- * body and parses `text/event-stream` frames into `AgentSessionEvent`s.- */- async *streamAgentSession(- ingressBaseUrl: string,- sessionId: string,- signal?: AbortSignal,- previewToken?: string | null,- ): AsyncGenerator<AgentSessionEvent> {- const url = new URL(`${ingressBaseUrl.replace(/\/$/, "")}/listen`);- url.searchParams.set("session_id", sessionId);- // NB: only `signal` in overrides. Passing `headers` here would replace the- // fetcher's Authorization header (it spreads overrides over the built- // headers), which 401s the stream. The preview token rides on- // `parameters.header` — merged in, not replacing. /listen streams SSE- // without an explicit Accept header.- const response = await this.api.fetcher.fetch({- method: "get",- url,- path: url.pathname,- parameters: previewTokenHeader(previewToken),- overrides: { signal },- });- if (!response.body) return;- const reader = response.body.getReader();- const decoder = new TextDecoder();- let buffer = "";- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- buffer += decoder.decode(value, { stream: true });- // Frames are separated by a blank line.- let sep = buffer.indexOf("\n\n");- while (sep !== -1) {- const frame = buffer.slice(0, sep);- buffer = buffer.slice(sep + 2);- const data = frame- .split("\n")- .filter((line) => line.startsWith("data:"))- .map((line) => line.slice(5).trimStart())- .join("\n");- if (data) {- try {- yield JSON.parse(data) as AgentSessionEvent;- } catch {- // Skip unparseable frames (keep-alives, comments).- }- }- sep = buffer.indexOf("\n\n");- }- }- } finally {- reader.releaseLock();- }- }-- /** Live (non-terminal) sessions across every agent on the team. */- async listAgentFleetLiveSessions(- limit?: number,- ): Promise<AgentFleetLiveSessionsResponse> {- const teamId = await this.getTeamId();- const path = `/api/projects/${teamId}/agent_fleet/live_sessions/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (limit != null) {- url.searchParams.set("limit", String(limit));- }- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- results?: AgentFleetLiveSessionsResponse["results"];- };- return { results: data.results ?? [] };- }-- /** All tool-approval requests across the team (team-admin only). */- async listAgentFleetApprovals(- params?: AgentApprovalsListParams,- ): Promise<AgentApprovalRequest[]> {- const teamId = await this.getTeamId();- const path = `/api/projects/${teamId}/agent_fleet/approvals/`;- const url = new URL(`${this.api.baseUrl}${path}`);- if (params?.state) {- url.searchParams.set("state", params.state);- }- if (params?.agent_id) {- url.searchParams.set("agent_id", params.agent_id);- }- if (params?.limit != null) {- url.searchParams.set("limit", String(params.limit));- }- if (params?.offset != null) {- url.searchParams.set("offset", String(params.offset));- }- const response = await this.api.fetcher.fetch({ method: "get", url, path });- const data = (await response.json()) as {- results?: AgentApprovalRequest[];- };- return data.results ?? [];- }-- /**- * Runs a read-only HogQL query against the team's project and returns the raw- * result grid. Backs the agent observability rollups (`$ai_*` events the- * runner captures into this team's own project). The endpoint can answer 200- * with an `error` field; that's surfaced as a throw.- */- async runHogQLQuery(query: string): Promise<HogQLGrid> {- const teamId = await this.getTeamId();- const path = `/api/projects/${teamId}/query/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- overrides: {- body: JSON.stringify({ query: { kind: "HogQLQuery", query } }),- },- });- const data = (await response.json()) as {- results?: unknown[][];- columns?: string[];- error?: string | null;- };- if (data.error) {- throw new Error(data.error);- }- return { results: data.results ?? [], columns: data.columns ?? [] };- }-- /**- * Runs an arbitrary typed query node (TrendsQuery, HogQLQuery, ...) against- * the team's project and returns the raw response. `refresh: "blocking"`- * serves a fresh-enough cached result and computes synchronously otherwise —- * the same mode PostHog insights use. Backs inbox report charts, whose query- * nodes are scout-authored and arrive unparsed.- */- async runQuery(- query: Record<string, unknown>,- ): Promise<Record<string, unknown>> {- const teamId = await this.getTeamId();- const path = `/api/projects/${teamId}/query/`;- const url = new URL(`${this.api.baseUrl}${path}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path,- overrides: {- body: JSON.stringify({ query, refresh: "blocking" }),- },- });- const data = (await response.json()) as Record<string, unknown>;- if (typeof data.error === "string" && data.error) {- throw new Error(data.error);- }- return data;- }-- /**- * The insight's identity and query node, by short id. Backs saved-insight- * chart cards in agent messages: the caller plans and runs the query.- */- async getInsightDefinition(shortId: string): Promise<{- name: string | null;- description: string | null;- query: unknown;- } | null> {- const projectId = (await this.getTeamId()).toString();- const page = await this.api.get("/api/projects/{project_id}/insights/", {- path: { project_id: projectId },- query: { short_id: shortId },- });- const insight = page.results[0];- if (!insight) return null;- return {- name: insight.name || insight.derived_name || null,- description: insight.description || null,- query: insight.query ?? null,- };- }-- /**- * Resolves an `evidence:<kind>/<id>` citation from an agent message to a- * small live summary of the object it points at. Returns null for kinds- * without a lookup and for ids that don't resolve, so the caller can fall- * back to a static reference. Query-backed kinds (hogql, insight) resolve- * in the UI instead, where chart shaping lives.+ * Resolves an `evidence:<kind>/<id>` citation from an agent message to a+ * small live summary of the object it points at. Returns null for kinds+ * without a lookup and for ids that don't resolve, so the caller can fall+ * back to a static reference. Query-backed kinds (hogql, insight) resolve+ * in the UI instead, where chart shaping lives.*/async getEvidencePreview(kind: string,@@ -7478,38 +6289,4 @@ export class PostHogAPIClient {return null;}}-- /**- * Agent observability rollup over the agents' `$ai_*` events — KPIs (spend,- * sessions, failure rate, p95), a 14-day daily trend + WoW deltas, and- * spend-by-agent / cost-by-model / tool-reliability breakdowns. Pass an- * `applicationId` (the agent's UUID) to scope it to a single agent; omit it- * for the fleet-wide board.- *- * The five panels are independent HogQL round-trips fired in parallel. The- * KPI query is the gate — a systemic failure (auth, bad query) rejects the- * whole call so the UI shows an error rather than a silently-empty board; the- * secondary panels degrade to empty individually. The fleet board also reads- * the agent list to label per-agent rows by name.- */- async getAgentAnalytics(applicationId?: string): Promise<AgentAnalyticsData> {- const queries = buildAgentAnalyticsQueries(applicationId);- const empty: HogQLGrid = { results: [], columns: [] };- const [agents, kpi, daily, perAgent, byModel, toolErrors] =- await Promise.all([- applicationId- ? Promise.resolve<AgentApplication[]>([])- : this.listAgentApplications().catch(() => [] as AgentApplication[]),- this.runHogQLQuery(queries.kpi),- this.runHogQLQuery(queries.daily).catch(() => empty),- this.runHogQLQuery(queries.perAgent).catch(() => empty),- this.runHogQLQuery(queries.byModel).catch(() => empty),- this.runHogQLQuery(queries.toolErrors).catch(() => empty),- ]);- const nameById = new Map(agents.map((a) => [a.id, a.name]));- return shapeAgentAnalytics(- { kpi, daily, perAgent, byModel, toolErrors },- nameById,- );- }}diff --git a/products/desktop/packages/core/src/agent-chat/agentChat.module.ts b/products/desktop/packages/core/src/agent-chat/agentChat.module.tsdeleted file mode 100644index c02631285e1e..000000000000--- a/products/desktop/packages/core/src/agent-chat/agentChat.module.ts+++ /dev/null@@ -1,8 +0,0 @@-import { ContainerModule } from "inversify";-import { AgentChatService } from "./agentChatService";-import { AGENT_CHAT_SERVICE } from "./identifiers";--export const agentChatCoreModule = new ContainerModule(({ bind }) => {- bind(AgentChatService).toSelf().inSingletonScope();- bind(AGENT_CHAT_SERVICE).toService(AgentChatService);-});diff --git a/products/desktop/packages/core/src/agent-chat/agentChatService.test.ts b/products/desktop/packages/core/src/agent-chat/agentChatService.test.tsdeleted file mode 100644index bc57ac9e010e..000000000000--- a/products/desktop/packages/core/src/agent-chat/agentChatService.test.ts+++ /dev/null@@ -1,169 +0,0 @@-import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";-import type { AgentSessionEvent } from "@posthog/shared/agent-platform-types";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { AgentChatService } from "./agentChatService";-import { agentChatStore } from "./agentChatStore";-import type { AgentChatSession } from "./identifiers";--const INGRESS = "https://ingress.example";-const SLUG = "my-agent";-const SESSION = "sess-1";--const mockClient = vi.hoisted(() => ({- runAgentSession: vi.fn(),- streamAgentSession: vi.fn(),- sendAgentMessage: vi.fn(),- cancelAgentSession: vi.fn(),- getAgentApplicationSession: vi.fn(),- getAgentSessionViaIngress: vi.fn(),- sendAgentClientToolResult: vi.fn(),- sendAgentInteractiveToolResult: vi.fn(),- mintAgentPreviewToken: vi.fn(),-}));-const client = mockClient as unknown as PostHogAPIClient;--function session(chatId: string): AgentChatSession {- return {- chatId,- agentSlug: SLUG,- ingressBaseUrl: INGRESS,- revisionId: null,- createMapper: () => ({- seedUserMessage: () => [],- setPromptIdBase: () => {},- apply: () => [],- }),- resolveClientTool: async () => null,- buildWireText: (text) => text,- mapConversation: () => [],- };-}--function ev(kind: AgentSessionEvent["kind"], data: unknown): AgentSessionEvent {- return {- kind,- session_id: SESSION,- ts: "2026-06-19T00:00:00Z",- data,- } as AgentSessionEvent;-}--/** A `/listen` stream that emits the given events then ends cleanly. */-async function* streamOf(...events: AgentSessionEvent[]) {- for (const e of events) yield e;-}--/** A `/listen` stream that emits, then drops (throws) like a reset/idle close. */-async function* streamThenDrop(...events: AgentSessionEvent[]) {- for (const e of events) yield e;- throw new Error("network reset");-}--describe("AgentChatService /listen reconnect", () => {- let service: AgentChatService;-- beforeEach(() => {- vi.clearAllMocks();- vi.useFakeTimers();- service = new AgentChatService();- mockClient.runAgentSession.mockResolvedValue({ session_id: SESSION });- });- afterEach(() => {- vi.useRealTimers();- });-- it("reconnects after a dropped tail and finishes on the completed frame", async () => {- const chatId = "reconnect-ok";- mockClient.streamAgentSession- .mockImplementationOnce(() =>- streamThenDrop(ev("assistant_text", { text: "hi" })),- )- .mockImplementationOnce(() => streamOf(ev("completed", {})));-- void service.send(client, session(chatId), "go");- // Let start() + the first pump (delta then drop) settle, then clear the- // reconnect backoff so the second attach runs.- await vi.advanceTimersByTimeAsync(1000);-- expect(mockClient.streamAgentSession).toHaveBeenCalledTimes(2);- // A live drop never asks the api whether the session ended — the re-attach- // produced output, so we know it's still going.- expect(mockClient.getAgentSessionViaIngress).not.toHaveBeenCalled();- const chat = agentChatStore.getState().chats[chatId];- expect(chat?.status).toBe("completed");- expect(chat?.error).toBeNull();- });-- it("finalizes without an error when the session ended during the gap", async () => {- const chatId = "terminal-in-gap";- // Stream drops immediately (no events); the run already finished server-side.- mockClient.streamAgentSession.mockImplementationOnce(() =>- streamThenDrop(),- );- mockClient.getAgentSessionViaIngress.mockResolvedValue({- state: "completed",- conversation: [],- });-- void service.send(client, session(chatId), "go");- await vi.advanceTimersByTimeAsync(0);-- // Silent re-attach → we ask the ingress, see it's terminal, and stop. No- // retry, no error.- expect(mockClient.getAgentSessionViaIngress).toHaveBeenCalledTimes(1);- expect(mockClient.streamAgentSession).toHaveBeenCalledTimes(1);- const chat = agentChatStore.getState().chats[chatId];- expect(chat?.status).toBe("completed");- expect(chat?.error).toBeNull();- });-- it("treats a closed frame as a terminal stream-end", async () => {- const chatId = "closed";- let captured: AbortSignal | undefined;- // A perpetual tail that emits `closed` then would keep yielding: proves the- // pump stops on `closed` rather than draining the generator.- async function* perpetual() {- yield ev("assistant_text_delta", { text: "bye" });- yield ev("closed", {});- yield ev("assistant_text_delta", { text: "should never render" });- }- mockClient.streamAgentSession.mockImplementationOnce(- (_url: string, _id: string, signal: AbortSignal) => {- captured = signal;- return perpetual();- },- );-- void service.send(client, session(chatId), "go");- await vi.advanceTimersByTimeAsync(0);-- const chat = agentChatStore.getState().chats[chatId];- expect(chat?.status).toBe("completed");- expect(chat?.error).toBeNull();- // No reconnect: the terminal frame ends the tail, so neither the stream nor- // the liveness probe is re-invoked.- expect(mockClient.streamAgentSession).toHaveBeenCalledTimes(1);- expect(mockClient.getAgentSessionViaIngress).not.toHaveBeenCalled();- // The still-open socket is released on the terminal exit.- expect(captured?.aborted).toBe(true);- });-- it("surfaces an error only after the reconnect budget is exhausted", async () => {- const chatId = "give-up";- // Always drops with no events; the api keeps reporting the run as live.- mockClient.streamAgentSession.mockImplementation(() => streamThenDrop());- mockClient.getAgentSessionViaIngress.mockResolvedValue({- state: "running",- conversation: [],- });-- void service.send(client, session(chatId), "go");- // Drain the full capped-exponential backoff schedule (≈23.5s).- await vi.advanceTimersByTimeAsync(30_000);-- // Initial attach + MAX_LISTEN_RECONNECTS (6) re-attaches.- expect(mockClient.streamAgentSession).toHaveBeenCalledTimes(7);- const chat = agentChatStore.getState().chats[chatId];- expect(chat?.error).toBeTruthy();- });-});diff --git a/products/desktop/packages/core/src/agent-chat/agentChatService.ts b/products/desktop/packages/core/src/agent-chat/agentChatService.tsdeleted file mode 100644index a6af145eb4b9..000000000000--- a/products/desktop/packages/core/src/agent-chat/agentChatService.ts+++ /dev/null@@ -1,695 +0,0 @@-import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";-import type {- AgentSessionEvent,- DecideApprovalRequest,-} from "@posthog/shared/agent-platform-types";-import { injectable } from "inversify";-import { agentChatStore } from "./agentChatStore";-import type {- AgentChatMapper,- AgentChatSession,- ClientToolCallData,-} from "./identifiers";--/** Session states with no further activity to tail — render stored history only. */-const TERMINAL_SESSION_STATES = new Set([- "completed",- "closed",- "cancelled",- "failed",-]);--/**- * The request id when `text` is the runner's rejection wake envelope- * (`{"approval":{"state":"rejected",…}}`), else null. A reject lands as a- * `user_message` (no tool_call_id), so this is how the live stream clears the- * inline card for a session decided elsewhere (e.g. Slack).- */-function rejectedApprovalRequestId(text: string | undefined): string | null {- if (!text) return null;- try {- const parsed = JSON.parse(text) as {- approval?: { request_id?: string; state?: string };- };- if (- parsed.approval?.state === "rejected" &&- typeof parsed.approval.request_id === "string"- ) {- return parsed.approval.request_id;- }- } catch {- // Not JSON / not an approval envelope — a normal user message.- }- return null;-}--/**- * Bounded reconnect budget for a dropped `/listen` tail. A re-attach that yields- * any event resets the budget, so a healthy long run that keeps getting closed- * out (idle timeouts, proxy recycling) reconnects indefinitely; only a genuinely- * dead or vanished stream exhausts it and surfaces an error.- */-const MAX_LISTEN_RECONNECTS = 6;--/** Reserve a margin so we mint a fresh token before the server rejects the old one. */-const PREVIEW_TOKEN_EARLY_REFRESH_MS = 30_000;--/** Exponential backoff (capped at 8s) between `/listen` reconnect attempts. */-function reconnectBackoffMs(attempt: number): number {- return Math.min(500 * 2 ** (attempt - 1), 8_000);-}--/** Resolve after `ms`, or early (→ false) if `signal` aborts; else → true. */-function delay(ms: number, signal: AbortSignal): Promise<boolean> {- if (signal.aborted) return Promise.resolve(false);- return new Promise((resolve) => {- const onAbort = () => {- clearTimeout(timer);- resolve(false);- };- const timer = setTimeout(() => {- signal.removeEventListener("abort", onAbort);- resolve(true);- }, ms);- signal.addEventListener("abort", onAbort, { once: true });- });-}--/**- * The ingress signals an expired/missing preview token with the fetcher's- * `Failed request: [401] …` shape, same as any other auth failure. Anything- * else falls through to the caller as a normal error.- */-function isPreviewAuthError(err: unknown): boolean {- return err instanceof Error && /\[401\]/.test(err.message);-}--interface CachedPreviewToken {- token: string;- expiresAtMs: number;-}--/** Per-chat saga state — one live `/listen` loop, mapper, and token cache. */-interface ChatRuntime {- mapper: AgentChatMapper;- abort: AbortController | null;- streaming: boolean;- /** Each stream attach bumps this; a superseded loop checks it before touching the store. */- epoch: number;- previewToken: CachedPreviewToken | null;- revisionId: string | null;-}--/**- * Drives live chats against deployed agents' ingress: starts/sends/cancels via- * the api-client, streams SSE through the host's mapper, and pumps the resulting- * ACP messages into the core `agentChatStore` keyed by `chatId` (so the agent- * builder dock and per-agent chats coexist). One `ChatRuntime` per chat holds- * the reconnect loop, epoch supersede, and preview-token cache.- *- * The renderer hook supplies the authenticated client per call and the UI seams- * (mapper, client-tool resolution, context envelope, history) via the session.- */-@injectable()-export class AgentChatService {- private readonly runtimes = new Map<string, ChatRuntime>();-- /** Ensure a runtime exists, dropping a cached token when the revision changes. */- private runtime(session: AgentChatSession): ChatRuntime {- let rt = this.runtimes.get(session.chatId);- if (!rt) {- rt = {- mapper: session.createMapper(),- abort: null,- streaming: false,- epoch: 0,- previewToken: null,- revisionId: session.revisionId,- };- this.runtimes.set(session.chatId, rt);- }- // A token is bound to a specific (app, revision); a stale one wouldn't route- // to the new target when the consumer flips revisions (incl. live ↔ draft).- if (rt.revisionId !== session.revisionId) {- rt.revisionId = session.revisionId;- rt.previewToken = null;- }- return rt;- }-- /**- * Mint a preview token if we don't have one, or refresh it just before expiry.- * `force` skips the cache (post-401 retry). Returns null for live revisions.- */- private async getPreviewToken(- client: PostHogAPIClient,- rt: ChatRuntime,- session: AgentChatSession,- force = false,- ): Promise<string | null> {- if (!session.revisionId) return null;- const cached = rt.previewToken;- if (- !force &&- cached &&- cached.expiresAtMs - Date.now() > PREVIEW_TOKEN_EARLY_REFRESH_MS- ) {- return cached.token;- }- const minted = await client.mintAgentPreviewToken(- session.agentSlug,- session.revisionId,- );- rt.previewToken = {- token: minted.token,- // Backend returns TTL in seconds; store an absolute deadline so the- // early-refresh comparison is straight subtraction.- expiresAtMs: Date.now() + minted.expires_in * 1000,- };- return minted.token;- }-- /**- * Run an ingress call with the cached preview token; on the fetcher's `[401]`,- * mint fresh and retry once. For live revisions this is just `call(null)`.- */- private async withPreviewToken<T>(- client: PostHogAPIClient,- rt: ChatRuntime,- session: AgentChatSession,- call: (token: string | null) => Promise<T>,- ): Promise<T> {- const token = await this.getPreviewToken(client, rt, session);- try {- return await call(token);- } catch (err) {- if (!session.revisionId || !isPreviewAuthError(err)) throw err;- const fresh = await this.getPreviewToken(client, rt, session, true);- return call(fresh);- }- }-- private async dispatchClientTool(- client: PostHogAPIClient,- rt: ChatRuntime,- session: AgentChatSession,- data: ClientToolCallData,- sessionId: string,- ): Promise<void> {- const outcome = await session.resolveClientTool(data);- // Interactive tools (set_secret) post their own outcome later.- if (!outcome || outcome.defer) return;- try {- await this.withPreviewToken(client, rt, session, (token) =>- client.sendAgentClientToolResult(- session.ingressBaseUrl,- sessionId,- data.call_id,- outcome,- token,- ),- );- } catch {- // Best-effort — the session will time the call out if this fails.- }- }-- private async runStream(- client: PostHogAPIClient,- session: AgentChatSession,- sessionId: string,- ): Promise<void> {- const { chatId } = session;- const rt = this.runtime(session);- // Supersede any in-flight stream (resume / new chat) and claim this epoch.- rt.abort?.abort();- const epoch = ++rt.epoch;- const controller = new AbortController();- rt.abort = controller;- rt.streaming = true;- const store = agentChatStore.getState();- // True the moment a (re)attached stream yields a real event, so the- // reconnect loop can tell "still producing output" from "attached to a- // silent or ended session". Reset before every pump attempt.- let madeProgress = false;- // Last non-auth stream error, surfaced only if reconnects are exhausted.- let lastDropError: string | null = null;- // Pump the SSE generator with the supplied token. Returns:- // "remint" — server signalled `preview_token_required`; mint + reconnect.- // "auth_failure" — initial fetch 401'd; safety-net retry once.- // "done" — the stream ended (terminal frame, drop, or supersede).- const pump = async (- token: string | null,- ): Promise<"remint" | "auth_failure" | "done"> => {- try {- for await (const event of client.streamAgentSession(- session.ingressBaseUrl,- sessionId,- controller.signal,- token,- )) {- if (rt.epoch !== epoch) return "done";- // Control event: don't surface to the user, just request a remint.- if (event.kind === "preview_token_required") return "remint";- // Hard end (meta-end-session): the session is sealed and rejects- // further `/send`s. Unlike `completed` (turn-end, stays open), this is- // terminal — finalize and stop tailing. The mapper renders nothing for- // it, so skip the append like the remint.- if (event.kind === "closed") {- store.setStatus(chatId, "completed");- return "done";- }- madeProgress = true;- store.appendMessages(chatId, rt.mapper.apply(event));- this.trackApprovalState(client, rt, session, chatId, epoch, event);- if (event.kind === "client_tool_call") {- void this.dispatchClientTool(- client,- rt,- session,- event.data,- sessionId,- );- } else if (event.kind === "completed") {- store.setStatus(chatId, "completed");- } else if (event.kind === "waiting") {- store.setStatus(chatId, "awaiting_input");- } else if (event.kind === "failed") {- store.setStatus(chatId, "failed");- store.setError(- chatId,- event.data?.reason ?? "The agent run failed.",- );- }- }- return "done";- } catch (err) {- if (- session.revisionId &&- !controller.signal.aborted &&- isPreviewAuthError(err)- ) {- return "auth_failure";- }- // Network reset / idle-timeout close / parse failure: remember it but- // don't surface yet — the loop reconnects, and only errors if the- // session is gone or the reconnect budget is exhausted.- if (!controller.signal.aborted) {- lastDropError = err instanceof Error ? err.message : null;- }- return "done";- }- };- // Is the run still live? `/listen` can't replay a terminal frame missed- // during a gap, so on a silent re-attach we ask the api before retrying.- const sessionLiveState = async (): Promise<- "live" | "terminal" | "unknown"- > => {- try {- const detail = await client.getAgentSessionViaIngress(- session.ingressBaseUrl,- sessionId,- undefined,- await this.getPreviewToken(client, rt, session),- );- return !detail || TERMINAL_SESSION_STATES.has(detail.state)- ? "terminal"- : "live";- } catch {- return "unknown";- }- };- try {- let token = await this.getPreviewToken(client, rt, session);- // `preview_token_required` is unbounded (one re-mint per ~15 min TTL); a- // true `[401]` only gets one retry as a safety net for the initial fetch.- let authRetried = false;- let reconnectAttempts = 0;- while (true) {- madeProgress = false;- const outcome = await pump(token);- if (rt.epoch !== epoch || controller.signal.aborted) break;- if (outcome === "remint") {- token = await this.getPreviewToken(client, rt, session, true);- continue;- }- if (outcome === "auth_failure" && !authRetried) {- authRetried = true;- token = await this.getPreviewToken(client, rt, session, true);- continue;- }- if (outcome === "auth_failure") {- store.setError(- chatId,- "Preview session failed to authenticate. Try again.",- );- break;- }- // outcome === "done": a terminal/`waiting` frame already moved us off- // "streaming" — that's an expected end, so stop.- if (agentChatStore.getState().chats[chatId]?.status !== "streaming") {- break;- }- // Still "streaming" → the connection dropped while the run is live.- if (madeProgress) {- // The re-attach produced output: reset the budget so repeated idle- // drops never exhaust it.- reconnectAttempts = 0;- } else {- // Silence on (re)attach: confirm the run didn't just finish in the gap- // before spending the budget.- const liveState = await sessionLiveState();- if (rt.epoch !== epoch || controller.signal.aborted) break;- if (liveState === "terminal") {- store.setStatus(chatId, "completed");- break;- }- }- if (reconnectAttempts >= MAX_LISTEN_RECONNECTS) {- store.setError(- chatId,- lastDropError ??- "Lost connection to the agent. Send a message to retry.",- );- break;- }- reconnectAttempts += 1;- const waited = await delay(- reconnectBackoffMs(reconnectAttempts),- controller.signal,- );- if (!waited || rt.epoch !== epoch || controller.signal.aborted) break;- // Refresh a preview token that may have lapsed across the gap.- token = await this.getPreviewToken(client, rt, session);- }- } catch (err) {- // A `getPreviewToken` throw (mint or re-mint) lands here — `pump` handles- // its own errors. Without this the rejection would slip past `finally`- // (which only flips status) and the stream would quietly stop.- if (rt.epoch === epoch && !controller.signal.aborted) {- store.setError(- chatId,- err instanceof Error ? err.message : "Preview session unavailable.",- );- }- } finally {- // The loop has fully broken (terminal frame, exhausted budget, or- // supersede), so release the still-open `/listen` socket: the server tails- // perpetually and only tears down on client disconnect. `controller` is- // run-local; re-aborting an aborted one is a no-op.- controller.abort();- if (rt.epoch === epoch) {- rt.streaming = false;- // Stream ended without a terminal frame mid-conversation → treat as- // awaiting input so the composer stays usable.- if (agentChatStore.getState().chats[chatId]?.status === "streaming") {- agentChatStore.getState().setStatus(chatId, "awaiting_input");- }- }- }- }-- async start(- client: PostHogAPIClient,- session: AgentChatSession,- text: string,- ): Promise<void> {- const rt = this.runtime(session);- rt.mapper = session.createMapper();- const s = agentChatStore.getState();- s.begin(session.chatId, session.agentSlug);- // Render the user's clean message immediately; the stream's echo (which- // includes the context envelope) is stripped + deduped by the mapper.- s.appendMessages(session.chatId, rt.mapper.seedUserMessage(text));- try {- const { session_id } = await this.withPreviewToken(- client,- rt,- session,- (token) =>- client.runAgentSession(- session.ingressBaseUrl,- session.buildWireText(text),- token,- session.supportedClientTools,- ),- );- agentChatStore.getState().setSessionId(session.chatId, session_id);- agentChatStore.getState().setStatus(session.chatId, "streaming");- session.onSessionStarted?.(session_id, text);- void this.runStream(client, session, session_id);- } catch (err) {- agentChatStore.getState().setStatus(session.chatId, "failed");- agentChatStore- .getState()- .setError(- session.chatId,- err instanceof Error ? err.message : "Couldn't start chat.",- );- }- }-- async send(- client: PostHogAPIClient,- session: AgentChatSession,- text: string,- ): Promise<void> {- const s = agentChatStore.getState();- const sessionId = s.chats[session.chatId]?.sessionId;- if (!sessionId) return this.start(client, session, text);- const rt = this.runtime(session);- // Render the user's message immediately; the stream's echo is deduped.- s.appendMessages(session.chatId, rt.mapper.seedUserMessage(text));- s.setStatus(session.chatId, "streaming");- try {- await this.withPreviewToken(client, rt, session, (token) =>- client.sendAgentMessage(session.ingressBaseUrl, sessionId, text, token),- );- if (!rt.streaming) void this.runStream(client, session, sessionId);- } catch (err) {- s.setStatus(session.chatId, "failed");- s.setError(- session.chatId,- err instanceof Error ? err.message : "Couldn't send.",- );- }- }-- async cancel(- client: PostHogAPIClient,- session: AgentChatSession,- ): Promise<void> {- const s = agentChatStore.getState();- const sessionId = s.chats[session.chatId]?.sessionId;- const rt = this.runtime(session);- rt.abort?.abort();- s.setStatus(session.chatId, "cancelled");- if (sessionId && session.ingressBaseUrl) {- try {- await this.withPreviewToken(client, rt, session, (token) =>- client.cancelAgentSession(session.ingressBaseUrl, sessionId, token),- );- } catch {- // Best-effort.- }- }- }-- /**- * Keep `chat.pendingApproval` in sync with the stream — what drives the inline- * approval card, with no polling. A `queued` approval marker triggers a- * one-shot fetch of the full request from the ingress (principal-authed,- * cross-project, with the draft preview token when present); a non-queued- * marker for that request, or a rejection wake, clears it.- */- private trackApprovalState(- client: PostHogAPIClient,- rt: ChatRuntime,- session: AgentChatSession,- chatId: string,- epoch: number,- event: AgentSessionEvent,- ): void {- if (event.kind === "tool_result" && event.data.approval) {- const { request_id, state } = event.data.approval;- if (state !== "queued") {- this.clearPendingApprovalIf(chatId, request_id);- return;- }- void (async () => {- try {- const token = await this.getPreviewToken(client, rt, session);- const detail = await client.getAgentApprovalViaIngress(- session.ingressBaseUrl,- request_id,- token,- );- // Skip if the stream was superseded (epoch) or the approval was- // already decided while the fetch was in flight (re-checked state).- if (detail && detail.state === "queued" && rt.epoch === epoch) {- agentChatStore.getState().setPendingApproval(chatId, detail);- }- } catch {- // Best-effort: the card just won't show; a reattach or a later marker- // retries. Never let a detail fetch break the stream.- }- })();- return;- }- if (event.kind === "user_message") {- const rejectedId = rejectedApprovalRequestId(event.data.text);- if (rejectedId) this.clearPendingApprovalIf(chatId, rejectedId);- }- }-- /** Clear the chat's pending approval only when it's the named request. */- private clearPendingApprovalIf(chatId: string, requestId: string): void {- const cur = agentChatStore.getState().chats[chatId]?.pendingApproval;- if (cur?.id === requestId) {- agentChatStore.getState().setPendingApproval(chatId, null);- }- }-- /**- * Decide a `principal`-type tool approval for this chat's session at the- * ingress, carrying the session's preview token so the ingress can- * principal-match. On approve the runner wakes, dispatches the tool, and the- * open `/listen` stream resumes the chat naturally — same as `/send`.- */- async decideApproval(- client: PostHogAPIClient,- session: AgentChatSession,- approvalId: string,- body: DecideApprovalRequest,- ): Promise<void> {- const rt = this.runtime(session);- await this.withPreviewToken(client, rt, session, (token) =>- client.decideAgentApprovalViaIngress(- session.ingressBaseUrl,- approvalId,- body,- token,- ),- );- // Clear the inline card now — the stream's resolved marker clears it too,- // but the approve→dispatch (or reject→wake) can lag, so don't leave the user- // staring at a card they've already decided.- agentChatStore.getState().setPendingApproval(session.chatId, null);- }-- /**- * Resolve an interactive client tool (set_secret) once the user submits its- * form: post the outcome via `/send` (waking the parked session) and make sure- * the stream is attached to receive the resulting turn.- */- async resolveInteractiveTool(- client: PostHogAPIClient,- session: AgentChatSession,- callId: string,- outcome: { result: Record<string, unknown> } | { error: string },- ): Promise<void> {- const sessionId =- agentChatStore.getState().chats[session.chatId]?.sessionId;- if (!sessionId) return;- const rt = this.runtime(session);- agentChatStore.getState().setStatus(session.chatId, "streaming");- try {- await this.withPreviewToken(client, rt, session, (token) =>- client.sendAgentInteractiveToolResult(- session.ingressBaseUrl,- sessionId,- callId,- outcome,- token,- ),- );- if (!rt.streaming) void this.runStream(client, session, sessionId);- } catch (err) {- agentChatStore.getState().setStatus(session.chatId, "awaiting_input");- agentChatStore- .getState()- .setError(- session.chatId,- err instanceof Error ? err.message : "Couldn't submit the secret.",- );- }- }-- /**- * Re-open a past chat. `/listen` only tails (it does not replay), so history is- * rebuilt from the stored transcript; a still-active session then attaches the- * live stream so the user can keep chatting where they left off.- */- async resume(- client: PostHogAPIClient,- session: AgentChatSession,- sessionId: string,- ): Promise<void> {- if (- agentChatStore.getState().chats[session.chatId]?.sessionId === sessionId- )- return;- const rt = this.runtime(session);- rt.abort?.abort();- rt.epoch += 1;- rt.streaming = false;- rt.mapper = session.createMapper();- const s = agentChatStore.getState();- s.begin(session.chatId, session.agentSlug);- s.setSessionId(session.chatId, sessionId);- s.setStatus(session.chatId, "starting");- try {- const detail = await client.getAgentSessionViaIngress(- session.ingressBaseUrl,- sessionId,- undefined,- await this.getPreviewToken(client, rt, session),- );- // A newer resume/new-chat won the race while we were fetching.- if (- agentChatStore.getState().chats[session.chatId]?.sessionId !== sessionId- )- return;- const conversation = detail?.conversation ?? [];- agentChatStore- .getState()- .appendMessages(session.chatId, session.mapConversation(conversation));- rt.mapper.setPromptIdBase(- conversation.filter((m) => m.role === "user").length,- );- if (!detail || TERMINAL_SESSION_STATES.has(detail.state)) {- agentChatStore.getState().setStatus(session.chatId, "completed");- } else {- agentChatStore.getState().setStatus(session.chatId, "streaming");- void this.runStream(client, session, sessionId);- }- } catch (err) {- if (- agentChatStore.getState().chats[session.chatId]?.sessionId !== sessionId- )- return;- agentChatStore.getState().setStatus(session.chatId, "failed");- agentChatStore- .getState()- .setError(- session.chatId,- err instanceof Error ? err.message : "Couldn't load this chat.",- );- }- }-- /** Clear the surface for a brand-new chat; the next send starts a new session. */- newChat(session: AgentChatSession): void {- const rt = this.runtime(session);- rt.abort?.abort();- rt.epoch += 1;- rt.streaming = false;- rt.mapper = session.createMapper();- agentChatStore.getState().reset(session.chatId);- }-- /** Release the open `/listen` socket when the consumer unmounts. */- releaseStream(chatId: string): void {- this.runtimes.get(chatId)?.abort?.abort();- }-}diff --git a/products/desktop/packages/core/src/agent-chat/agentChatStore.test.ts b/products/desktop/packages/core/src/agent-chat/agentChatStore.test.tsdeleted file mode 100644index 6689d11b9eff..000000000000--- a/products/desktop/packages/core/src/agent-chat/agentChatStore.test.ts+++ /dev/null@@ -1,45 +0,0 @@-import type { AcpMessage } from "@posthog/shared";-import { beforeEach, describe, expect, it } from "vitest";-import { agentChatStore, MAX_CHAT_MESSAGES } from "./agentChatStore";--const message = (i: number): AcpMessage =>- ({- message: {- jsonrpc: "2.0",- method: "session/update",- params: { i },- },- }) as unknown as AcpMessage;--describe("agentChatStore", () => {- beforeEach(() => {- agentChatStore.setState({ chats: {} });- });-- it("appends messages in order", () => {- const { begin, appendMessages } = agentChatStore.getState();- begin("chat", "agent");- appendMessages("chat", [message(1), message(2)]);- appendMessages("chat", [message(3)]);-- expect(agentChatStore.getState().chats.chat?.messages).toHaveLength(3);- });-- it("caps retained messages at MAX_CHAT_MESSAGES, dropping oldest", () => {- const { begin, appendMessages } = agentChatStore.getState();- begin("chat", "agent");-- const batch = Array.from({ length: MAX_CHAT_MESSAGES }, (_, i) =>- message(i),- );- appendMessages("chat", batch);- appendMessages("chat", [message(MAX_CHAT_MESSAGES)]);-- const messages = agentChatStore.getState().chats.chat?.messages ?? [];- expect(messages).toHaveLength(MAX_CHAT_MESSAGES);- const first = messages[0]?.message as { params?: { i?: number } };- const last = messages.at(-1)?.message as { params?: { i?: number } };- expect(first.params?.i).toBe(1);- expect(last.params?.i).toBe(MAX_CHAT_MESSAGES);- });-});diff --git a/products/desktop/packages/core/src/agent-chat/agentChatStore.ts b/products/desktop/packages/core/src/agent-chat/agentChatStore.tsdeleted file mode 100644index 9df4578c0edd..000000000000--- a/products/desktop/packages/core/src/agent-chat/agentChatStore.ts+++ /dev/null@@ -1,117 +0,0 @@-import type { AcpMessage } from "@posthog/shared";-import type { AgentApprovalRequest } from "@posthog/shared/agent-platform-types";-import { createStore } from "zustand/vanilla";--/**- * Domain state for deployed-agent live chats. Keyed by an opaque `chatId` so- * several chats can be live at once — e.g. the always-on agent builder dock- * (`"agent-builder"`) and a per-agent chat (`"preview:<slug>"`) side by side.- * The UI hook (`useAgentChat`) owns the transport (run/send/cancel + the SSE- * loop, via the api-client) and pumps mapped `AcpMessage`s in here; components- * read one chat by id and render it through `ConversationView`.- */--export type AgentChatStatus =- | "idle"- | "starting"- | "streaming"- | "awaiting_input"- | "completed"- | "failed"- | "cancelled";--export interface AgentChatState {- /** Which agent this chat targets (slug), or null when idle. */- agentKey: string | null;- sessionId: string | null;- status: AgentChatStatus;- /** Accumulated ACP messages (mapper output) for ConversationView. */- messages: AcpMessage[];- /**- * The approval-gated tool call this chat is currently paused on, or null. Set- * by the service when it sees a `queued` approval marker on the stream (it- * one-shot-fetches the full request from the ingress); cleared when the marker- * resolves or the user decides. Drives the inline approval card — no polling.- */- pendingApproval: AgentApprovalRequest | null;- error: string | null;-}--/**- * Retention cap per chat. A live chat streams an AcpMessage per chunk, so an- * unbounded array grows without limit on long sessions; past this the oldest- * messages fall off (the transcript of record lives server-side).- */-export const MAX_CHAT_MESSAGES = 2000;--export const EMPTY_CHAT: AgentChatState = {- agentKey: null,- sessionId: null,- status: "idle",- messages: [],- pendingApproval: null,- error: null,-};--interface AgentChatStore {- /** All live chats, keyed by `chatId`. */- chats: Record<string, AgentChatState>;-- /** Reset `chatId` for a brand-new chat against `agentKey`. */- begin: (chatId: string, agentKey: string) => void;- setSessionId: (chatId: string, sessionId: string) => void;- setStatus: (chatId: string, status: AgentChatStatus) => void;- appendMessages: (chatId: string, messages: AcpMessage[]) => void;- setPendingApproval: (- chatId: string,- approval: AgentApprovalRequest | null,- ) => void;- setError: (chatId: string, error: string | null) => void;- reset: (chatId: string) => void;-}--export const agentChatStore = createStore<AgentChatStore>((set) => {- const patch = (- chatId: string,- next: Partial<AgentChatState>,- ): ((s: AgentChatStore) => AgentChatStore) => {- return (s) => ({- ...s,- chats: {- ...s.chats,- [chatId]: { ...(s.chats[chatId] ?? EMPTY_CHAT), ...next },- },- });- };-- return {- chats: {},- begin: (chatId, agentKey) =>- set(patch(chatId, { ...EMPTY_CHAT, agentKey, status: "starting" })),- setSessionId: (chatId, sessionId) => set(patch(chatId, { sessionId })),- setStatus: (chatId, status) => set(patch(chatId, { status })),- appendMessages: (chatId, messages) =>- set((s) => {- if (messages.length === 0) return s;- const cur = s.chats[chatId] ?? EMPTY_CHAT;- const appended = [...cur.messages, ...messages];- return {- ...s,- chats: {- ...s.chats,- [chatId]: {- ...cur,- messages:- appended.length > MAX_CHAT_MESSAGES- ? appended.slice(-MAX_CHAT_MESSAGES)- : appended,- },- },- };- }),- setPendingApproval: (chatId, approval) =>- set(patch(chatId, { pendingApproval: approval })),- setError: (chatId, error) => set(patch(chatId, { error })),- reset: (chatId) => set(patch(chatId, { ...EMPTY_CHAT })),- };-});diff --git a/products/desktop/packages/core/src/agent-chat/identifiers.ts b/products/desktop/packages/core/src/agent-chat/identifiers.tsdeleted file mode 100644index 440c954284d0..000000000000--- a/products/desktop/packages/core/src/agent-chat/identifiers.ts+++ /dev/null@@ -1,65 +0,0 @@-import type { AcpMessage } from "@posthog/shared";-import type {- AgentConversationMessage,- AgentSessionEvent,-} from "@posthog/shared/agent-platform-types";--export const AGENT_CHAT_SERVICE = Symbol.for("posthog.core.agentChat.service");--/**- * Incremental SSE→ACP mapper, implemented in the UI (`createAgentChatMapper`)- * and handed to the service per chat. Stateful: a fresh one per session/stream.- */-export interface AgentChatMapper {- /** Optimistically render the user's just-sent message; the echoed frame is deduped. */- seedUserMessage(text: string, ts?: number): AcpMessage[];- /** Continue prompt-id numbering past `count` restored turns (resume). */- setPromptIdBase(count: number): void;- /** Translate one SSE event into zero or more ACP messages. */- apply(event: AgentSessionEvent): AcpMessage[];-}--export type ClientToolCallData = Extract<- AgentSessionEvent,- { kind: "client_tool_call" }->["data"];--/**- * A client-tool result. `defer: true` means the host opened an interactive UI- * and will post the outcome itself, so the service must not post one now.- */-export interface ClientToolOutcome {- result?: unknown;- error?: string;- defer?: boolean;-}--/**- * Per-chat host seam supplied by the renderer hook. The transport saga lives in- * the service; mapping, client-tool resolution, the context envelope, and local- * history are UI concerns the service calls back into. Callbacks are expected to- * be stable and read the latest handlers internally, so a long-lived stream- * always sees current state.- */-export interface AgentChatSession {- /** Opaque key isolating this chat in the store. */- chatId: string;- /** Agent slug the chat targets. */- agentSlug: string;- ingressBaseUrl: string;- /** Non-null routes this chat to a non-live revision (ingress JWT attached per call). */- revisionId: string | null;- /** `kind:'client'` tool ids this client can fulfil; sent to the runner at /run. */- supportedClientTools?: readonly string[];- createMapper(): AgentChatMapper;- /** Resolve a client-tool call; `defer`/null ⇒ the service won't post a result. */- resolveClientTool(- data: ClientToolCallData,- ): Promise<ClientToolOutcome | null>;- /** Compose the wire text for a first message (prepends the context envelope). */- buildWireText(text: string): string;- /** Map a stored transcript to ACP messages (resume). */- mapConversation(messages: AgentConversationMessage[]): AcpMessage[];- /** Fired once a run starts, so the host can index local history. */- onSessionStarted?(sessionId: string, text: string): void;-}diff --git a/products/desktop/packages/core/src/links/approval-link.test.ts b/products/desktop/packages/core/src/links/approval-link.test.tsdeleted file mode 100644index 3e40abb4123b..000000000000--- a/products/desktop/packages/core/src/links/approval-link.test.ts+++ /dev/null@@ -1,172 +0,0 @@-import type {- DeepLinkHandler,- IDeepLinkRegistry,-} from "@posthog/platform/deep-link";-import type { IMainWindow } from "@posthog/platform/main-window";-import { beforeEach, describe, expect, it, vi } from "vitest";-import {- ApprovalLinkEvent,- type ApprovalLinkPayload,- ApprovalLinkService,-} from "./approval-link";--function makeLogger() {- const logger = {- info: vi.fn(),- warn: vi.fn(),- error: vi.fn(),- debug: vi.fn(),- scope: vi.fn(() => logger),- };- return logger;-}--function makeDeepLinkService() {- const handlers = new Map<string, DeepLinkHandler>();- const service = {- registerHandler: vi.fn((key: string, handler: DeepLinkHandler) => {- handlers.set(key, handler);- }),- trigger: (key: string, path: string, search = "") => {- const handler = handlers.get(key);- if (!handler) throw new Error(`No handler for ${key}`);- return handler(path, new URLSearchParams(search));- },- };- return service as unknown as IDeepLinkRegistry & {- trigger: (key: string, path: string, search?: string) => boolean;- };-}--function makeMainWindow() {- return {- focus: vi.fn(),- restore: vi.fn(),- isMinimized: vi.fn().mockReturnValue(false),- } as unknown as IMainWindow & {- focus: ReturnType<typeof vi.fn>;- restore: ReturnType<typeof vi.fn>;- isMinimized: ReturnType<typeof vi.fn>;- };-}--describe("ApprovalLinkService", () => {- let deepLinkService: ReturnType<typeof makeDeepLinkService>;- let mainWindow: ReturnType<typeof makeMainWindow>;- let service: ApprovalLinkService;-- beforeEach(() => {- deepLinkService = makeDeepLinkService();- mainWindow = makeMainWindow();- service = new ApprovalLinkService(- deepLinkService,- mainWindow,- makeLogger(),- );- });-- it("registers an 'approval' handler on the DeepLinkService", () => {- expect(deepLinkService.registerHandler).toHaveBeenCalledWith(- "approval",- expect.any(Function),- );- });-- it.each<{- name: string;- path: string;- expected: ApprovalLinkPayload;- }>([- {- name: "emits OpenApproval with the request id",- path: "ar_abc123",- expected: { requestId: "ar_abc123", agent: null },- },- {- name: "takes only the first path segment as the request id",- path: "ar_abc123/extra/segments",- expected: { requestId: "ar_abc123", agent: null },- },- {- name: "decodes a percent-encoded request id",- path: "ar_abc%2D123",- expected: { requestId: "ar_abc-123", agent: null },- },- ])("$name", ({ path, expected }) => {- const listener = vi.fn();- service.on(ApprovalLinkEvent.OpenApproval, listener);-- const result = deepLinkService.trigger("approval", path);-- expect(result).toBe(true);- expect(listener).toHaveBeenCalledWith(expected);- });-- it.each<{ name: string; search: string; agent: string | null }>([- {- name: "carries the agent slug from the ?agent= query string",- search: "agent=my-agent",- agent: "my-agent",- },- {- name: "drops a slug that is not a single DNS label",- search: "agent=evil.com%2F",- agent: null,- },- ])("$name", ({ search, agent }) => {- const listener = vi.fn();- service.on(ApprovalLinkEvent.OpenApproval, listener);-- const result = deepLinkService.trigger("approval", "ar_abc123", search);-- expect(result).toBe(true);- expect(listener).toHaveBeenCalledWith({- requestId: "ar_abc123",- agent,- });- });-- it("queues a pending deep link when no listener is attached", () => {- deepLinkService.trigger("approval", "ar_xyz789");-- const pending = service.consumePendingDeepLink();- expect(pending).toEqual({ requestId: "ar_xyz789", agent: null });-- // Draining clears it- expect(service.consumePendingDeepLink()).toBeNull();- });-- it("returns false and does not emit when the path is empty", () => {- const listener = vi.fn();- service.on(ApprovalLinkEvent.OpenApproval, listener);-- const result = deepLinkService.trigger("approval", "");-- expect(result).toBe(false);- expect(listener).not.toHaveBeenCalled();- });-- it.each<{ name: string; minimized: boolean; expectRestore: boolean }>([- {- name: "focuses the main window on link arrival",- minimized: false,- expectRestore: false,- },- {- name: "restores then focuses the main window when it is minimized",- minimized: true,- expectRestore: true,- },- ])("$name", ({ minimized, expectRestore }) => {- mainWindow.isMinimized.mockReturnValue(minimized);-- deepLinkService.trigger("approval", "ar_abc123");-- expect(mainWindow.focus).toHaveBeenCalledTimes(1);- if (expectRestore) {- expect(mainWindow.restore).toHaveBeenCalledTimes(1);- } else {- expect(mainWindow.restore).not.toHaveBeenCalled();- }- });-});diff --git a/products/desktop/packages/core/src/links/approval-link.ts b/products/desktop/packages/core/src/links/approval-link.tsdeleted file mode 100644index 44f422d03eeb..000000000000--- a/products/desktop/packages/core/src/links/approval-link.ts+++ /dev/null@@ -1,125 +0,0 @@-import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";-import {- DEEP_LINK_SERVICE,- type IDeepLinkRegistry,-} from "@posthog/platform/deep-link";-import {- type IMainWindow,- MAIN_WINDOW_SERVICE,-} from "@posthog/platform/main-window";-import { isValidAgentSlug, TypedEventEmitter } from "@posthog/shared";-import { inject, injectable } from "inversify";-import type { LinkLogger } from "./identifiers";--export const ApprovalLinkEvent = {- OpenApproval: "openApproval",-} as const;--export interface ApprovalLinkPayload {- /** Agent tool-approval request id. */- requestId: string;- /**- * Agent slug from `?agent=<slug>`, when present. Lets the renderer address- * the slug-routed ingress directly and decide the approval in a modal (works- * from any project). Null on legacy links → fall back to the fleet inbox.- */- agent: string | null;-}--export interface ApprovalLinkEvents {- [ApprovalLinkEvent.OpenApproval]: ApprovalLinkPayload;-}--/**- * Handles agent approval deep links (`<scheme>://approval/{requestId}`, e.g.- * `posthog-code://approval/ar_...` in production and `posthog-code-dev://…` in- * local dev). The agent-runner emits these on a gated tool call so non-PostHog-Code- * clients (Slack, MCP) can open the approval in the desktop app. The request id- * alone resolves the approval in the fleet inbox, so the link carries nothing else.- *- * Mirrors `ScoutLinkService`: queues a link that arrived before the renderer was- * ready, and emits for links delivered while the app is already running.- */-@injectable()-export class ApprovalLinkService extends TypedEventEmitter<ApprovalLinkEvents> {- private pendingDeepLink: ApprovalLinkPayload | null = null;- private readonly log: LinkLogger;-- constructor(- @inject(DEEP_LINK_SERVICE)- private readonly deepLinkService: IDeepLinkRegistry,- @inject(MAIN_WINDOW_SERVICE)- private readonly mainWindow: IMainWindow,- @inject(ROOT_LOGGER)- rootLogger: RootLogger,- ) {- super();- this.log = rootLogger.scope("approval-link-service");-- this.deepLinkService.registerHandler("approval", (path, searchParams) =>- this.handleApprovalLink(path, searchParams),- );- }-- private handleApprovalLink(- path: string,- searchParams: URLSearchParams,- ): boolean {- const requestId = decodeSegment(path.split("/")[0]);-- if (!requestId) {- this.log.warn("Approval link missing request id");- return false;- }-- const rawAgent = searchParams.get("agent");- const agent = isValidAgentSlug(rawAgent) ? rawAgent : null;- if (rawAgent && !agent) {- this.log.warn(- "Approval link carried a malformed agent slug; ignoring it",- );- }-- const payload: ApprovalLinkPayload = { requestId, agent };-- const hasListeners = this.listenerCount(ApprovalLinkEvent.OpenApproval) > 0;-- if (hasListeners) {- this.log.info(`Emitting approval link event: requestId=${requestId}`);- this.emit(ApprovalLinkEvent.OpenApproval, payload);- } else {- this.log.info(- `Queueing approval link (renderer not ready): requestId=${requestId}`,- );- this.pendingDeepLink = payload;- }-- this.log.info("Deep link focusing window", { requestId });- if (this.mainWindow.isMinimized()) {- this.mainWindow.restore();- }- this.mainWindow.focus();-- return true;- }-- public consumePendingDeepLink(): ApprovalLinkPayload | null {- const pending = this.pendingDeepLink;- this.pendingDeepLink = null;- if (pending) {- this.log.info(- `Consumed pending approval link: requestId=${pending.requestId}`,- );- }- return pending;- }-}--function decodeSegment(segment: string | undefined): string {- if (!segment) return "";- try {- return decodeURIComponent(segment);- } catch {- return segment;- }-}diff --git a/products/desktop/packages/core/src/links/identifiers.ts b/products/desktop/packages/core/src/links/identifiers.tsindex 69a3d1fda43e..74c973c709c6 100644--- a/products/desktop/packages/core/src/links/identifiers.ts+++ b/products/desktop/packages/core/src/links/identifiers.ts@@ -11,9 +11,6 @@ export const SCOUT_LINK_SERVICE = Symbol.for("posthog.core.scoutLinkService");export const NEW_TASK_LINK_SERVICE = Symbol.for("posthog.core.newTaskLinkService",);-export const APPROVAL_LINK_SERVICE = Symbol.for(- "posthog.core.approvalLinkService",-);// Carries notification-click "open this target" intent from main → renderer.// Unlike the link services above, it registers no OS URL-scheme handler — it// exists purely so a clicked native notification can navigate to its target.diff --git a/products/desktop/packages/host-router/src/routers/deep-link.router.ts b/products/desktop/packages/host-router/src/routers/deep-link.router.tsindex fb951c5827dc..7a9236666024 100644--- a/products/desktop/packages/host-router/src/routers/deep-link.router.ts+++ b/products/desktop/packages/host-router/src/routers/deep-link.router.ts@@ -1,8 +1,3 @@-import {- ApprovalLinkEvent,- type ApprovalLinkPayload,- type ApprovalLinkService,-} from "@posthog/core/links/approval-link";import {CanvasLinkEvent,type CanvasLinkPayload,@@ -14,7 +9,6 @@ import {type ChannelLinkService,} from "@posthog/core/links/channel-link";import {- APPROVAL_LINK_SERVICE,CANVAS_LINK_SERVICE,CHANNEL_LINK_SERVICE,INBOX_LINK_SERVICE,@@ -149,26 +143,6 @@ export const deepLinkRouter = router({},),- onOpenApproval: publicProcedure.subscription(async function* (opts) {- const service = opts.ctx.container.get<ApprovalLinkService>(- APPROVAL_LINK_SERVICE,- );- const iterable = service.toIterable(ApprovalLinkEvent.OpenApproval, {- signal: opts.signal,- });- for await (const data of iterable) {- yield data;- }- }),-- getPendingApprovalLink: publicProcedure.query(- ({ ctx }): ApprovalLinkPayload | null => {- return ctx.container- .get<ApprovalLinkService>(APPROVAL_LINK_SERVICE)- .consumePendingDeepLink();- },- ),-// Generic "open this target" intents from clicked native notifications. The// renderer subscribes and navigates by target kind (task / canvas / …).onOpenTarget: publicProcedure.subscription(async function* (opts) {diff --git a/products/desktop/packages/shared/package.json b/products/desktop/packages/shared/package.jsonindex 96077e001f5e..68b45e43a3ca 100644--- a/products/desktop/packages/shared/package.json+++ b/products/desktop/packages/shared/package.json@@ -16,10 +16,6 @@"types": "./dist/announcements.d.ts","import": "./dist/announcements.js"},- "./agent-platform-types": {- "types": "./dist/agent-platform-types.d.ts",- "import": "./dist/agent-platform-types.js"- },"./domain-types": {"types": "./dist/domain-types.d.ts","import": "./dist/domain-types.js"diff --git a/products/desktop/packages/shared/src/agent-platform-types.ts b/products/desktop/packages/shared/src/agent-platform-types.tsdeleted file mode 100644index 51cfad450714..000000000000--- a/products/desktop/packages/shared/src/agent-platform-types.ts+++ /dev/null@@ -1,861 +0,0 @@-// Wire shapes mirroring the PostHog Cloud REST serializers (Django app-// `agent_platform`). Field names stay snake_case to match the JSON exactly.--export type AgentSessionState =- | "queued"- | "running"- | "completed"- | "closed"- | "cancelled"- | "failed";--export type AgentSessionPrincipalKind =- | "anonymous"- | "service"- | "internal"- | "shared_secret"- | "slack";--export type AgentRevisionState = "draft" | "ready" | "live" | "archived";--export type AgentApprovalRequestState =- | "queued"- | "approving"- | "dispatched"- | "dispatched_failed"- | "rejected"- | "expired";--export type AgentApprovalDecision = "approve" | "reject";--/** Resolved creator (from `created_by_id`), or null if unset/deleted. */-export interface AgentApplicationCreator {- id?: number;- first_name?: string;- email?: string;-}--export interface AgentApplication {- id: string;- team_id: number;- name: string;- /** Globally-unique URL identifier; server-minted unless explicitly allowed. */- slug?: string;- description?: string;- live_revision: string | null;- archived?: boolean;- archived_at: string | null;- created_by_id: number | null;- created_by: AgentApplicationCreator | null;- created_at: string;- updated_at: string;- /** Slack Event Subscriptions request URL; null without a public ingress URL. */- slack_events_url: string | null;- /** Slack Interactivity request URL; null without a public ingress URL. */- slack_interactivity_url: string | null;- /** Mode-aware base URL the agent's trigger routes hang off; null without ingress. */- ingress_base_url: string | null;-}--export type AgentReasoningEffort =- | "minimal"- | "low"- | "medium"- | "high"- | "xhigh";--export type AgentModelLevel = "low" | "medium" | "high";--/**- * Session model stability vs. resilience. `cost` (default): pin the first served- * model for the whole session — warm prompt cache, no cross-model failover.- * `availability`: lead with the last-served model but fail over on failure.- * Mirrors `spec.models.optimize_for` in the backend.- */-export type AgentModelOptimizeFor = "cost" | "availability";--/** One model in a manual policy: a canonical model id (e.g.- * `anthropic/claude-sonnet-4-6`) plus an optional per-model reasoning override. */-export interface AgentModelEntry {- model: string;- reasoning?: AgentReasoningEffort;-}--/**- * How a revision picks its model. `auto` resolves a maintained, priority-ordered,- * cross-provider list from `level` at runtime; `manual` pins an author-ordered- * fallback list (primary first). Mirrors `spec.models` in the backend.- */-export type AgentModelPolicy =- | {- mode: "auto";- level?: AgentModelLevel;- reasoning?: AgentReasoningEffort;- optimize_for?: AgentModelOptimizeFor;- }- | {- mode: "manual";- models: AgentModelEntry[];- optimize_for?: AgentModelOptimizeFor;- };--/**- * A served model + its cost profile, as the model browser shows it. Mirrors the- * ai-gateway catalog (`@posthog/agent-applications-models`). Pricing is USD per- * million tokens.- */-export interface ModelCatalogEntry {- /** Canonical id, e.g. `anthropic/claude-sonnet-4.6`. */- model: string;- provider: string;- context_window: number;- input: number;- output: number;- cacheRead?: number;- cacheWrite?: number;-}--/** The full served catalog plus the curated `auto` level → model mapping. */-export interface ModelCatalog {- models: ModelCatalogEntry[];- /** Canonical ids each auto level resolves to, in priority order. */- levels: Record<AgentModelLevel, string[]>;-}--/**- * The agent spec carried on a revision. Known top-level fields are surfaced and- * the rest passes through pending fully-typed elaboration.- */-export interface AgentSpec {- /** Model selection. `model` is the legacy single-string form; current specs- * carry `models`. One or the other is present. */- models?: AgentModelPolicy;- model?: string;- triggers?: unknown[];- tools?: unknown[];- mcps?: unknown[];- skills?: unknown[];- secrets?: string[];- limits?: {- max_turns?: number;- max_tool_calls?: number;- max_wall_seconds?: number;- };- reasoning?: AgentReasoningEffort;- [key: string]: unknown;-}--export interface AgentRevision {- id: string;- application: string;- parent_revision?: string | null;- state: AgentRevisionState;- bundle_uri?: string;- bundle_sha256: string | null;- spec?: AgentSpec;- created_by_id: number | null;- created_by: AgentApplicationCreator | null;- created_at: string;- updated_at: string;-}--// `…/agent_applications/{id}/preview-token/?revision_id=<uuid>` mints a-// short-lived HS256 JWT that authorizes the ingress to route /run /send /listen-// /cancel against a non-live revision. Sent on those calls via the-// `X-Agent-Preview-Token` header (or `?preview_token=` query for EventSource),-// alongside the usual PostHog bearer. The response's `endpoints` carry the-// per-trigger preview URLs to hit directly, so the client never derives a-// revision-scoped ingress URL by string-mangling `application.ingress_base_url`.--/** Per-trigger preview URLs, keyed by trigger type → action → absolute URL. */-export type AgentPreviewEndpoints = Record<string, Record<string, string>>;--export interface AgentPreviewToken {- /** HS256 JWT bound to (app, revision). Short TTL. */- token: string;- /** Token TTL in seconds from issue; mint a fresh one before this elapses. */- expires_in: number;- /** `<application_slug>-<revision_uuid_hex>` — the slug ingress uses in routing. */- ingress_slug: string;- /**- * Per-trigger ingress URLs derived from this revision's `spec.triggers[]`.- * Empty when no public agent-ingress URL is configured for the active routing mode.- * Shape: `{ chat: { run, send, listen, cancel, client_tool_result }, slack: {...} }`.- */- endpoints: AgentPreviewEndpoints;- /** Header/query names + per-trigger accepted auth modes. Opaque to most callers. */- auth: Record<string, unknown>;- /** Server-side proxy alternative — opaque shape; preferred path is direct-to-ingress. */- preview_proxy: Record<string, unknown>;-}--// `…/revisions/{id}/bundle/` returns a typed bundle ({ agent_md, skills, tools });-// the client flattens it into these per-file rows keyed by canonical path-// (agent.md, skills/<id>/SKILL.md, tools/<id>/source.ts, tools/<id>/schema.json).--export type BundleFileLanguage = "markdown" | "typescript" | "json" | "text";--export interface BundleFile {- path: string;- content: string;- language: BundleFileLanguage;-}--// Custom-tool authoring on a draft revision (`agent_platform`): compile-on-save-// (PUT …/tools/{id}), delete, and dry-run (POST …/tools/{id}/dry_run). Draft-only-// for writes — ready/live/archived bundles are sealed.--/** Discriminator for a custom-tool compile failure. Mirrors the backend AST/- * transform checks; a failed compile returns one or more of these. */-export type ToolCompileErrorKind =- | "parse_failed"- | "ast_no_default_export"- | "ast_default_not_object"- | "ast_missing_actions"- | "ast_actions_not_object"- | "ast_missing_default_action"- | "ast_default_action_not_callable"- | "ast_dynamic_export"- | "transform_failed";--/** One diagnostic from a failed tool compile. `line`/`column` are 1-based. */-export interface ToolCompileError {- kind: ToolCompileErrorKind;- message: string;- line?: number;- column?: number;-}--/** Static capabilities the compiler extracted from a tool's source. */-export interface ToolCapabilities {- /** Secret names the tool references via `ctx.secrets.ref("NAME")`. */- secret_refs: string[];- /** True when the tool derives secret names dynamically (can't be enumerated). */- dynamic_secret_refs: boolean;-}--/** Body for PUT …/tools/{toolId} — author/compile a tool. */-export interface WriteToolRequest {- description: string;- args_schema: Record<string, unknown>;- source: string;-}--/**- * Outcome of a tool write. A compile failure (HTTP 422) is a first-class result,- * NOT a thrown error, so the caller renders `errors` inline against the source.- * Other non-2xx (400 invalid_request, 409 sealed revision, …) still throw.- */-export type WriteToolResult =- | { ok: true; tool_id: string; capabilities: ToolCapabilities }- | {- ok: false;- error: "tool_compile_failed";- tool_id: string;- errors: ToolCompileError[];- };--/** Body for POST …/tools/{toolId}/dry_run. */-export interface DryRunToolRequest {- /** Free-form JSON passed to the tool's `actions.default`; NOT validated- * against `args_schema` (the author's responsibility). */- args: unknown;- /** `secretName -> placeholder` returned by `ctx.secrets.ref(name)` in the- * sandbox; real secret values never leave the backend. */- mock_secrets?: Record<string, string>;-}--/**- * The dry-run response envelope (returned on HTTP 200 AND 500). A tool-side- * failure is an HTTP 200 with `ok: false` — read `ok` from HERE, not the status.- */-export interface DryRunToolEnvelope {- ok: boolean;- tool_id: string;- result?: unknown;- /** `error.code` is one of sandbox_acquire_failed | sandbox_invoke_failed |- * timeout | secret_not_provisioned | action_not_found | tool_not_found |- * dry_run_unknown. */- error?: { code: string; message: string };- duration_ms: number;-}--/**- * A dry-run outcome. `throttled` (HTTP 429) and `unavailable` (HTTP 503) are- * distinct interactive states — surfaced as data, never thrown, and never- * retried (dry-run is process-capped).- */-export type DryRunToolResult =- | { outcome: "completed"; envelope: DryRunToolEnvelope }- | { outcome: "throttled"; max_concurrent?: number }- | { outcome: "unavailable" };--// `…/revisions/{id}/slack_manifest/` derives the Slack app manifest from the-// revision's slack trigger + tools (scopes + event subscriptions computed).--export interface AgentSlackManifest {- revision_id: string;- /** Opaque Slack app manifest JSON to paste into "create from manifest". */- manifest: Record<string, unknown>;- notes: string[];- events_url: string | null;- interactivity_url: string | null;-}--// The agent's S3-backed memory store: markdown files (`…/memory/…`) plus the-// JSONL reference tables the @posthog/table-* tools write.--export interface AgentMemoryHeader {- path: string;- description: string;- tags: string[];- created_at: string | null;- updated_at: string | null;-}--export interface AgentMemoryFile extends AgentMemoryHeader {- content: string;-}--/** Pre-aggregated folder tree from `…/memory/tree/`. */-export interface AgentMemoryTreeNode {- name: string;- type: "folder" | "file";- path?: string;- description?: string;- tags?: string[];- children?: AgentMemoryTreeNode[];-}--export interface AgentMemorySearchResult {- path: string;- description: string;- tags: string[];- score: number;- snippet?: string | null;-}--export interface AgentMemoryTableHeader {- name: string;- size: number;-}--export interface AgentMemoryTableRows {- name: string;- total: number;- returned: number;- limit: number;- rows: Record<string, unknown>[];-}--// The agent's end-users and their linked external identities. `agent_user` is-// the stable per-principal identity (a Slack user, a JWT `sub`, a PostHog user);-// `agent_identity_credential` is a durable OAuth link that user established so-// the agent can act AS them on an external system. The API exposes connection-// *metadata only* — encrypted tokens are NEVER serialized to the client.--/** A linked external identity for an agent user. Credential material is omitted. */-export interface AgentUserConnection {- id: string;- provider: string;- /** Granted scopes (plaintext; no secret material). */- scopes: string[];- /** `active` once linked; `revoked` after a disconnect (kept for audit). */- state: "active" | "revoked";- /** Proven external subject (e.g. a PostHog user uuid) for identity-establishing- * providers; null for API-only links. */- subject: string | null;- /** When the access token expires, if the provider issues expiring tokens. */- access_expires_at: string | null;- created_at: string;- updated_at: string;- revoked_at: string | null;-}--/** An agent end-user (`agent_user`) plus their linked connections. */-export interface AgentUserWithConnections {- id: string;- /** Edge-identity kind: `slack` | `jwt` | `posthog` | `service` | … */- principal_kind: string;- /** Stable principal id within that kind (Slack user id, JWT `sub`, …). */- principal_id: string;- /** Optional trigger-stamped context (e.g. Slack workspace/display name). */- metadata?: Record<string, unknown>;- created_at: string;- connections: AgentUserConnection[];-}--export interface AgentUsersListResponse {- results: AgentUserWithConnections[];- count: number;-}--export interface AgentSessionUsageTotal {- tokens_in: number;- tokens_out: number;- cache_read: number;- cache_write: number;- cost_input: number;- cost_output: number;- cost_cache_read: number;- cost_cache_write: number;- cost_total: number;-}--export interface AgentSessionPrincipal {- kind: AgentSessionPrincipalKind;- /** Stable principal id (PAT id, slack user id, …); absent for anonymous. */- id?: string;- team_id?: number;-}--/** Trigger-specific metadata stamped at session creation; shape varies by kind. */-export type AgentSessionTriggerMetadata = Record<string, unknown>;--export interface AgentSessionSummary {- id: string;- application_id: string;- revision_id: string;- state: AgentSessionState;- external_key: string | null;- trigger_metadata?: AgentSessionTriggerMetadata | null;- principal: AgentSessionPrincipal | null;- /** Count of messages in the conversation. */- turns: number;- /** Last assistant text (~120 chars); null before any assistant turn. */- preview: string | null;- usage_total: AgentSessionUsageTotal;- retry_count: number;- created_at: string;- updated_at: string;-}--export interface AgentApplicationSessionsListResponse {- results: AgentSessionSummary[];- count: number;-}--// Stored conversation shape on a session: the runtime persists pi-ai's-// `conversation` array. Part shapes mirror what the agent-console apiClient-// narrows (text/thinking/toolCall for assistants; text/image for users; text-// for tool results).--export interface AgentTextPart {- type: "text";- text: string;-}--export interface AgentThinkingPart {- type: "thinking";- thinking: string;-}--export interface AgentImagePart {- type: "image";- [key: string]: unknown;-}--export interface AgentToolCallPart {- type: "toolCall";- id: string;- name: string;- arguments: Record<string, unknown>;-}--export type AgentAssistantContentPart =- | AgentTextPart- | AgentThinkingPart- | AgentToolCallPart;--export type AgentUserContentPart = AgentTextPart | AgentImagePart;--export interface AgentConversationUserMessage {- role: "user";- /** String shorthand, or an array of text/image parts. */- content: string | AgentUserContentPart[];- /** Epoch milliseconds. */- timestamp: number;-}--export interface AgentConversationAssistantMessage {- role: "assistant";- /** Array of text/thinking/toolCall parts. */- content: AgentAssistantContentPart[];- timestamp: number;- api?: string;- provider?: string;- model?: string;- usage?: Record<string, unknown>;- stopReason?: string;- errorMessage?: string;-}--export interface AgentConversationToolResultMessage {- /** Wire value is `toolResult` (NOT `tool`) — matches the runtime serializer. */- role: "toolResult";- toolCallId: string;- toolName: string;- /** Array of text parts (image parts are dropped on render). */- content: AgentTextPart[];- isError: boolean;- timestamp: number;-}--export type AgentConversationMessage =- | AgentConversationUserMessage- | AgentConversationAssistantMessage- | AgentConversationToolResultMessage;--export interface AgentApplicationSessionDetail {- id: string;- application_id: string;- revision_id: string;- team_id: number;- state: AgentSessionState;- external_key: string | null;- trigger_metadata?: AgentSessionTriggerMetadata | null;- principal: AgentSessionPrincipal | null;- usage_total: AgentSessionUsageTotal;- conversation: AgentConversationMessage[];- /** Messages that arrived while a turn was in flight. */- pending_inputs: AgentConversationMessage[];- retry_count: number;- created_at: string;- updated_at: string;- /** True when `last_n` was supplied AND the full conversation exceeded it. */- conversation_trimmed: boolean;- /** Total messages in the untrimmed conversation; present only when trimmed. */- conversation_total_turns?: number;-}--// `…/sessions/{id}/logs/` returns rows from the shared ClickHouse `log_entries`-// table via `fetch_log_entries` — the same flat shape hog_function logs use.--export type AgentLogLevel = "DEBUG" | "LOG" | "INFO" | "WARN" | "ERROR";--export interface AgentSessionLogEntry {- log_source_id: string;- instance_id: string;- /** ISO timestamp. */- timestamp: string;- /** One of AgentLogLevel, but server may emit other casings — keep it open. */- level: string;- message: string;-}--export interface AgentSessionLogsParams {- limit?: number;- /** Comma-separated levels server-side; pass an array, joined by the client. */- level?: AgentLogLevel[];- search?: string;- after?: string;- before?: string;-}--export interface AgentFleetLiveSessionSummary {- id: string;- application_id: string;- revision_id: string;- team_id: number;- state: AgentSessionState;- external_key: string | null;- trigger_metadata?: AgentSessionTriggerMetadata | null;- principal: AgentSessionPrincipal | null;- turns: number;- preview: string | null;- usage_total: AgentSessionUsageTotal;- created_at: string;- updated_at: string;-}--export interface AgentFleetLiveSessionsResponse {- results: AgentFleetLiveSessionSummary[];-}--/**- * Who clears a gated call. `principal` = the session's own principal decides at- * the ingress (generic identity match); `agent` = the owning team's admins- * decide in the console. Mirrors `ApprovalType` in agent-shared `spec.ts`.- */-export type AgentApprovalType = "principal" | "agent";--/** Resolved approval policy stamped on the request at queue time. */-export interface AgentApproverScope {- type: AgentApprovalType;- allow_edit: boolean;-}--export interface AgentApprovalRequest {- id: string;- session_id: string;- application_id: string;- team_id: number;- revision_id: string;- turn: number;- tool_call_id: string;- tool_name: string;- proposed_args: Record<string, unknown>;- decided_args: Record<string, unknown> | null;- assistant_message: Record<string, unknown>;- approver_scope: AgentApproverScope;- state: AgentApprovalRequestState;- decision_by: string | null;- decision_at: string | null;- decision_reason: string | null;- dispatch_outcome: Record<string, unknown> | null;- created_at: string;- expires_at: string;-}--/** Body for POST …/approvals/{id}/decide/. */-export interface DecideApprovalRequest {- decision: AgentApprovalDecision;- /** Honoured only when the tool's approval_policy.allow_edit is true. */- edited_args?: Record<string, unknown>;- reason?: string;-}--export interface AgentSessionsListParams {- limit?: number;- offset?: number;- /** Comma-separated states accepted server-side; pass an array, joined by the client. */- state?: AgentSessionState[];- revision_id?: string;- /** Restrict to sessions started by this agent user (`agent_user.id`). */- agent_user_id?: string;- created_after?: string;- created_before?: string;- /** Case-insensitive server-side match over the conversation text, id, and external key. */- search?: string;-}--export interface AgentApprovalsListParams {- state?: AgentApprovalRequestState;- agent_id?: string;- limit?: number;- offset?: number;-}--// Live session events from the chat trigger's `/listen` endpoint (SSE-// `text/event-stream` JSON frames). The `kind` discriminator and `data`-// payloads come from `agent-ingress/src/triggers/chat.ts` +-// `agent-runner/src/loop/bus.ts`.--interface AgentSessionEventBase {- session_id: string;- /** ISO timestamp the runner stamped on the frame. */- ts: string;-}--/** Session accepted and the runner started — `{ team_id, agent, rev }`. */-export type AgentSessionStartedEvent = AgentSessionEventBase & {- kind: "session_started";- data: { team_id?: number; agent?: string; rev?: string };-};--/** Server-confirmed user message, echoed when drained from `pending_inputs`. */-export type AgentUserMessageEvent = AgentSessionEventBase & {- kind: "user_message";- data: { text: string; timestamp?: string };-};--/** A new assistant turn began — `{ turn }` is the turn index. */-export type AgentTurnStartedEvent = AgentSessionEventBase & {- kind: "turn_started";- data: { turn?: number };-};--/** Streaming assistant text fragment. */-export type AgentAssistantTextDeltaEvent = AgentSessionEventBase & {- kind: "assistant_text_delta";- data: { turn?: number; text: string };-};--/** Streaming assistant thinking fragment. */-export type AgentAssistantThinkingDeltaEvent = AgentSessionEventBase & {- kind: "assistant_thinking_delta";- data: { turn?: number; thinking: string };-};--/** A tool call appeared (name known, args still streaming). */-export type AgentToolCallStartEvent = AgentSessionEventBase & {- kind: "tool_call_start";- data: { turn?: number; id: string; name: string };-};--/** Incremental tool-call args — string fragment or partial object. */-export type AgentToolCallArgsDeltaEvent = AgentSessionEventBase & {- kind: "tool_call_args_delta";- data: { turn?: number; id: string; argsDelta: unknown };-};--/** Turn-end snapshot of the full assistant text (deltas already filled it). */-export type AgentAssistantTextEvent = AgentSessionEventBase & {- kind: "assistant_text";- data: { text: string };-};--/** Canonical tool call with finalized args. */-export type AgentToolCallEvent = AgentSessionEventBase & {- kind: "tool_call";- data: { id: string; name: string; args?: Record<string, unknown> };-};--/** Tool result — `ok` plus `output` on success, `error` on failure. */-export type AgentToolResultEvent = AgentSessionEventBase & {- kind: "tool_result";- data: {- id: string;- tool?: string;- ok?: boolean;- output?: unknown;- error?: string;- /**- * Present when this result is an approval-gated call's synthetic outcome.- * `state: "queued"` means it's awaiting a decision — the chat service keys- * the inline approval card off it (then one-shot-fetches the full request).- * A later result with the same `request_id` and a non-queued state clears- * the card. `allow_edit` + `approver_scope` mirror the persisted envelope.- */- approval?: {- request_id: string;- state: string;- allow_edit?: boolean;- approver_scope?: AgentApproverScope;- };- };-};--/** Turn finished; session stays open for more input. */-export type AgentCompletedEvent = AgentSessionEventBase & {- kind: "completed";- data: { turns?: number; summary?: unknown };-};--/** Session parked for a steering message (`@posthog/meta-ask-for-input`). */-export type AgentWaitingEvent = AgentSessionEventBase & {- kind: "waiting";- data: { turns?: number; prompt?: string };-};--/** Terminal failure — `reason` is for owners/logs, not end users. */-export type AgentFailedEvent = AgentSessionEventBase & {- kind: "failed";- data: { reason?: string; turns?: number };-};--/** Session sealed (terminal); no further `/send`s accepted. */-export type AgentClosedEvent = AgentSessionEventBase & {- kind: "closed";- data: Record<string, unknown>;-};--/** Model invoked a client-fulfilled tool; the host runs it and posts back. */-export type AgentClientToolCallEvent = AgentSessionEventBase & {- kind: "client_tool_call";- data: { call_id: string; tool_id: string; args?: Record<string, unknown> };-};--/** A client tool's outcome landed (sync POST or interactive `/send` wake). */-export type AgentClientToolResultEvent = AgentSessionEventBase & {- kind: "client_tool_result";- data: { call_id: string; result?: unknown; error?: string };-};--/**- * Draft-preview only. Server fires this on `/listen` ~5s before the preview- * token expires (then closes the stream); the client mints a fresh token and- * reconnects. The kind alone is the signal — `data` is unused.- */-export type AgentPreviewTokenRequiredEvent = AgentSessionEventBase & {- kind: "preview_token_required";- data: Record<string, unknown>;-};--export type AgentSessionEvent =- | AgentSessionStartedEvent- | AgentUserMessageEvent- | AgentTurnStartedEvent- | AgentAssistantTextDeltaEvent- | AgentAssistantThinkingDeltaEvent- | AgentToolCallStartEvent- | AgentToolCallArgsDeltaEvent- | AgentAssistantTextEvent- | AgentToolCallEvent- | AgentToolResultEvent- | AgentCompletedEvent- | AgentWaitingEvent- | AgentFailedEvent- | AgentClosedEvent- | AgentClientToolCallEvent- | AgentClientToolResultEvent- | AgentPreviewTokenRequiredEvent;--/** Discriminator values for {@link AgentSessionEvent}. */-export type AgentSessionEventKind = AgentSessionEvent["kind"];--// The runner captures `$ai_*` observability events into the team's OWN PostHog-// project (tagged `$ai_origin = 'agent_platform_runner'`, `$agent_application_id`);-// the observability surface rolls those up via HogQL. These are the *derived*-// analytics shapes the client produces from raw HogQL grids — not a backend wire-// serializer — but live here so UI hooks import them alongside the other types.--export interface AgentAnalyticsKpis {- spendUsd: number;- sessions: number;- /** 0..1 — share of generations that errored. */- failureRate: number;- /** p95 model latency, seconds. */- p95LatencyS: number;-}--export interface AgentAnalyticsDaily {- /** Short date labels, oldest → newest (14 days). */- labels: string[];- spend: number[];- sessions: number[];- /** 0..1 per day. */- failureRate: number[];-}--export interface AgentAnalyticsDeltas {- /** Percent change vs the prior 7 days (e.g. 12 = +12%). `null` when undefined. */- spend: number | null;- sessions: number | null;- /** Change in failure rate, in percentage points. `null` when undefined. */- failureRatePoints: number | null;-}--export interface AgentAnalyticsAgentRow {- id: string;- name: string;- sessions: number;- spendUsd: number;- failureRate: number;- p95LatencyS: number;- tokens: number;-}--export interface AgentAnalyticsModelRow {- model: string;- spendUsd: number;- calls: number;-}--export interface AgentAnalyticsToolRow {- tool: string;- calls: number;- errors: number;- errorRate: number;-}--export interface AgentAnalyticsData {- kpis: AgentAnalyticsKpis;- daily: AgentAnalyticsDaily;- deltas: AgentAnalyticsDeltas;- byAgent: AgentAnalyticsAgentRow[];- byModel: AgentAnalyticsModelRow[];- toolErrors: AgentAnalyticsToolRow[];- /** True when there is no agent AI activity in the window — drives the empty state. */- empty: boolean;-}diff --git a/products/desktop/packages/shared/tsup.config.ts b/products/desktop/packages/shared/tsup.config.tsindex 5f7c08e3dbea..422f9e434710 100644--- a/products/desktop/packages/shared/tsup.config.ts+++ b/products/desktop/packages/shared/tsup.config.ts@@ -3,7 +3,6 @@ import { defineConfig } from "tsup";export default defineConfig({entry: ["src/index.ts",- "src/agent-platform-types.ts","src/analytics-events.ts","src/announcements.ts","src/constants.ts",diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderDock.tsx b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderDock.tsxdeleted file mode 100644index f041a01e67f1..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderDock.tsx+++ /dev/null@@ -1,497 +0,0 @@-import {- ArrowRightIcon,- NavigationArrowIcon,- PlusIcon,- SidebarSimpleIcon,- SparkleIcon,-} from "@phosphor-icons/react";-import type { AgentSpec } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import {- type CustomServerInput,- useMcpConnect,-} from "@posthog/ui/features/mcp-server-manager/useMcpConnect";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Text, Tooltip } from "@radix-ui/themes";-import { useEffect, useRef, useState } from "react";-import { useAuthStateValue } from "../../auth/store";-import { AgentChatPendingApprovalCard } from "../components/AgentChatPendingApprovalCard";-import { AgentChatSurface } from "../components/AgentChatSurface";-import { AgentDetailEmptyState } from "../components/AgentDetailLayout";-import { useAgentChat } from "../hooks/useAgentChat";-import { useAgentChatPendingApproval } from "../hooks/useAgentChatPendingApproval";-import { agentIngressBaseUrl } from "../utils/ingress";-import { AgentBuilderMcpConnectDialog } from "./AgentBuilderMcpConnectDialog";-import { AgentBuilderSecretForm } from "./AgentBuilderSecretForm";-import {- AGENT_BUILDER_CHAT_ID,- AGENT_BUILDER_SLUG,- type AgentBuilderPageContext,- useAgentBuilderStore,-} from "./agentBuilderStore";-import { suggestionsForPage } from "./agentBuilderSuggestions";-import {- AGENT_BUILDER_CLIENT_TOOLS,- useAgentBuilderClientTools,-} from "./useAgentBuilderClientTools";--const CHAT_ID = AGENT_BUILDER_CHAT_ID;--/** A rotating pool of composer placeholders — picked once per dock mount. */-const BUILDER_PLACEHOLDERS = [- "Build me an agent that…",- "What should we build today?",- "Ask me to inspect, debug, or edit an agent…",- "Describe an agent and I'll wire it up…",- "Spin up a new agent, or fix an existing one…",- "What's broken? Let's debug a session…",- "Audit the fleet, tweak a prompt, ship an agent…",- "Tell me what to change…",-];--/** The "what am I looking at" object sent to the agent builder (envelope + get_context). */-function buildAgentBuilderContext(- page: AgentBuilderPageContext,- followEnabled: boolean,- project: { id: number | null; name: string | null; orgId: string | null },-): Record<string, unknown> {- const agent = "slug" in page ? page.slug : undefined;- const sessionId = page.kind === "agent-session" ? page.sessionId : undefined;- const revisionId = page.kind === "agent-config" ? page.revision : undefined;- return {- page: page.kind,- agent,- session_id: sessionId,- // The revision open in the configuration pane — the default target for- // revision-scoped punch-outs (`set_secret`, `connect_mcp`).- revision_id: revisionId,- follow_enabled: followEnabled,- // The project the user is currently in — the agent threads this into the- // `project_id` arg of every `@posthog/*` tool (it's tenant-neutral and acts- // on whatever project we report here).- project_id: project.id ?? undefined,- project_name: project.name ?? undefined,- org_id: project.orgId ?? undefined,- client: { kind: "posthog-code", version: "1" },- };-}--/** Derive a unique, stable `mcps[].id` (tool-name prefix) from a label, avoiding- * collisions with existing entries. Mirrors the config pane's add-from-connection. */-function uniqueMcpId(label: string, mcps: unknown[]): string {- const base =- (label || "mcp")- .toLowerCase()- .replace(/[^a-z0-9]+/g, "-")- .replace(/^-+|-+$/g, "")- .slice(0, 32) || "mcp";- const taken = new Set(- mcps.map((m) =>- m && typeof m === "object"- ? (m as Record<string, unknown>).id- : undefined,- ),- );- let id = base;- for (let n = 2; taken.has(id); n++) id = `${base}-${n}`;- return id;-}--/**- * The Agent Builder chat — an always-on dock talking to the deployed meta-agent- * (backend slug `agent-builder`). Streams through the shared- * `useAgentChat`/`AgentChatSurface` stack, prepends the current `/code/agents`- * page context to the first message, answers `get_context`, and lets the agent- * drive the UI via `focus_*`.- */-export function AgentBuilderDock() {- const cloudRegion = useAuthStateValue((s) => s.cloudRegion);- // The builder is a first-party, slug-routed agent reachable from any project,- // so we address its ingress directly from (slug, region) rather than loading- // its API record — which is project-scoped and 404s outside its home project.- const ingressBaseUrl = agentIngressBaseUrl(AGENT_BUILDER_SLUG, cloudRegion);-- const client = useAuthenticatedClient();- const currentProjectId = useAuthStateValue((s) => s.currentProjectId);- const currentOrgId = useAuthStateValue((s) => s.currentOrgId);- const orgProjectsMap = useAuthStateValue((s) => s.orgProjectsMap);- const projectName =- currentOrgId != null && currentProjectId != null- ? (orgProjectsMap[currentOrgId]?.projects.find(- (p) => p.id === currentProjectId,- )?.name ?? null)- : null;- const page = useAgentBuilderStore((s) => s.page);- const followMode = useAgentBuilderStore((s) => s.followMode);- const setFollowMode = useAgentBuilderStore((s) => s.setFollowMode);- const setVisible = useAgentBuilderStore((s) => s.setVisible);- const seed = useAgentBuilderStore((s) => s.seed);- const consumeSeed = useAgentBuilderStore((s) => s.consumeSeed);- const pendingSecret = useAgentBuilderStore((s) => s.pendingSecret);- const setPendingSecret = useAgentBuilderStore((s) => s.setPendingSecret);- const pendingMcpConnect = useAgentBuilderStore((s) => s.pendingMcpConnect);- const setPendingMcpConnect = useAgentBuilderStore(- (s) => s.setPendingMcpConnect,- );- const lastSession = useAgentBuilderStore((s) => s.lastSession);- const setLastSession = useAgentBuilderStore((s) => s.setLastSession);- const { connectCustomAsync, refetchInstallations } = useMcpConnect();- const [secretBusy, setSecretBusy] = useState(false);- const [mcpConnectBusy, setMcpConnectBusy] = useState(false);- const [placeholder] = useState(- () =>- BUILDER_PLACEHOLDERS[- Math.floor(Math.random() * BUILDER_PLACEHOLDERS.length)- ],- );-- const clientTools = useAgentBuilderClientTools();- const chat = useAgentChat({- chatId: CHAT_ID,- agentSlug: AGENT_BUILDER_SLUG,- ingressBaseUrl,- contextProvider: () =>- buildAgentBuilderContext(page, followMode, {- id: currentProjectId,- name: projectName,- orgId: currentOrgId,- }),- clientTools,- supportedClientTools: AGENT_BUILDER_CLIENT_TOOLS,- });- const pendingApproval = useAgentChatPendingApproval(CHAT_ID);-- // Persist the session (with its project/org) as it's assigned, so a reload can- // resume it in the right context.- useEffect(() => {- if (chat.sessionId) {- setLastSession({- id: chat.sessionId,- projectId: currentProjectId,- orgId: currentOrgId,- });- }- }, [chat.sessionId, currentProjectId, currentOrgId, setLastSession]);-- // On (re)mount, rehydrate the last conversation from the ingress — the- // in-memory chat store doesn't survive a reload. Fires once, after the- // persisted `lastSession` has hydrated, and only when the chat is empty AND- // the session belongs to the current project/org. `resume` re-attaches- // `/listen` only if the session is still live; otherwise it's read-only- // history to continue from.- const resumedRef = useRef(false);- useEffect(() => {- if (resumedRef.current || !lastSession) return;- if (chat.sessionId || chat.messages.length > 0) {- resumedRef.current = true;- return;- }- resumedRef.current = true;- if (- lastSession.projectId === currentProjectId &&- lastSession.orgId === currentOrgId- ) {- void chat.resume(lastSession.id);- }- }, [lastSession, currentProjectId, currentOrgId, chat]);-- // Switching project/org starts the dock fresh — a conversation belongs to the- // context it began in (the builder threads project_id into its tools; the- // session is org-scoped at the ingress, so it isn't reachable from another- // org). Skips the initial render so it doesn't wipe a just-resumed chat.- const contextKeyRef = useRef<string | null>(null);- useEffect(() => {- const key = `${currentOrgId ?? ""}:${currentProjectId ?? ""}`;- if (contextKeyRef.current === null) {- contextKeyRef.current = key;- return;- }- if (contextKeyRef.current === key) return;- contextKeyRef.current = key;- chat.newChat();- setLastSession(null);- }, [currentProjectId, currentOrgId, chat, setLastSession]);-- // Resolve a pending set_secret: PUT the value straight to the env-keys API- // (never through the agent), then wake the parked session with the outcome.- async function submitSecret(value: string) {- if (!pendingSecret) return;- setSecretBusy(true);- try {- await client.setAgentEnvKey(- pendingSecret.agentSlug,- pendingSecret.revisionId,- pendingSecret.secret,- value,- );- await chat.resolveInteractiveTool(pendingSecret.callId, {- result: {- key: pendingSecret.secret,- action: pendingSecret.mode ?? "set",- },- });- setPendingSecret(null);- } catch (err) {- await chat.resolveInteractiveTool(pendingSecret.callId, {- error: err instanceof Error ? err.message : "set_secret_failed",- });- setPendingSecret(null);- } finally {- setSecretBusy(false);- }- }-- function cancelSecret() {- if (!pendingSecret) return;- void chat.resolveInteractiveTool(pendingSecret.callId, {- error: "user_cancelled",- });- setPendingSecret(null);- }-- // Resolve a pending connect_mcp: run the native connect (OAuth/api-key handoff- // — tokens never reach the agent), then attach the resulting connection to the- // target agent's draft spec and wake the parked session with the outcome.- async function submitMcpConnect(values: CustomServerInput) {- const pending = pendingMcpConnect;- if (!pending) return;- setMcpConnectBusy(true);- try {- const result = await connectCustomAsync(values);- if (result && "error" in result && result.error) {- throw new Error(result.error);- }- // The new install is keyed by url server-side ((team, user, url)); refetch- // and match to recover its id (the OAuth callback doesn't return it).- const installs = await refetchInstallations();- const install = installs.find((i) => i.url === values.url);- if (!install) {- throw new Error("connection_not_found_after_connect");- }- // Attach to the target agent's spec: load → append an mcps[] entry that- // references the connection → PATCH the (draft) revision.- const rev = await client.getAgentRevision(- pending.agentSlug,- pending.revisionId,- );- if (!rev) {- throw new Error("revision_not_found");- }- const spec = (rev.spec ?? {}) as AgentSpec;- const mcps = Array.isArray(spec.mcps) ? [...spec.mcps] : [];- const mcpId = uniqueMcpId(values.name || values.url, mcps);- mcps.push({- id: mcpId,- url: values.url,- connection: install.id,- secrets: [],- });- await client.updateAgentRevisionSpec(- pending.agentSlug,- pending.revisionId,- {- ...spec,- mcps,- },- );- await chat.resolveInteractiveTool(pending.callId, {- result: {- connected: true,- connection_id: install.id,- mcp_id: mcpId,- url: values.url,- },- });- setPendingMcpConnect(null);- } catch (err) {- await chat.resolveInteractiveTool(pending.callId, {- error: err instanceof Error ? err.message : "connect_mcp_failed",- });- setPendingMcpConnect(null);- } finally {- setMcpConnectBusy(false);- }- }-- function cancelMcpConnect() {- if (!pendingMcpConnect) return;- void chat.resolveInteractiveTool(pendingMcpConnect.callId, {- error: "user_cancelled",- });- setPendingMcpConnect(null);- }-- // Contextual hand-offs ("New agent" / "Edit with AI" / …): prefill the- // seeded prompt into the composer when a new seed lands — never send it. The- // user reviews and hits send, so opening the dock doesn't fire a chat on its- // own. Prefilling is non-destructive, so no start-fresh-vs-continue prompt is- // needed: it drops into whatever chat is open, and the header "New chat" (+)- // clears first if the user wants a fresh conversation.- const lastSeedRef = useRef(0);- const [draft, setDraft] = useState<{ text: string; token: number } | null>(- null,- );- useEffect(() => {- if (!seed || seed.seq === lastSeedRef.current) return;- lastSeedRef.current = seed.seq;- consumeSeed(seed.seq);- setDraft({ text: seed.prompt, token: seed.seq });- }, [seed, consumeSeed]);-- return (- <Flex- direction="column"- className="h-full min-h-0 border-(--amber-5) border-l-2 bg-(--amber-1)/30"- >- <Flex- align="center"- gap="2"- className="shrink-0 border-(--amber-4) border-b bg-(--amber-2)/40 px-3 py-2"- >- <SparkleIcon size={15} weight="fill" className="text-(--accent-9)" />- <Text className="font-medium text-[13px] text-gray-12">- Agent Builder- </Text>- <Flex align="center" gap="2" className="ml-auto">- <Tooltip- content={- followMode- ? "Following — the agent builder can navigate your screen"- : "Paused — the agent builder won't navigate"- }- >- <Button- variant={followMode ? "soft" : "ghost"}- color={followMode ? undefined : "gray"}- size="1"- onClick={() => setFollowMode(!followMode)}- >- <NavigationArrowIcon- size={13}- weight={followMode ? "fill" : "regular"}- />- </Button>- </Tooltip>- <Tooltip content="New chat">- <Button- variant="ghost"- color="gray"- size="1"- onClick={() => {- setPendingSecret(null);- setPendingMcpConnect(null);- chat.newChat();- setLastSession(null);- }}- >- <PlusIcon size={14} />- </Button>- </Tooltip>- <Tooltip content="Hide agent builder (⌘⇧I)">- <Button- variant="ghost"- color="gray"- size="1"- onClick={() => setVisible(false)}- >- <SidebarSimpleIcon size={14} />- </Button>- </Tooltip>- </Flex>- </Flex>-- {!ingressBaseUrl ? (- <div className="p-4">- <AgentDetailEmptyState- title="Agent Builder unavailable"- description="Couldn't resolve your PostHog region, so the Agent Builder ingress can't be reached yet."- />- </div>- ) : (- <AgentChatSurface- messages={chat.messages}- isStreaming={chat.isStreaming}- error={chat.error}- scrollX={false}- placeholder={placeholder}- emptyState={<AgentBuilderEmptyState page={page} onPick={chat.send} />}- emptyHint="Ask the agent builder to inspect, debug, or edit your agents. It can see what you're looking at and walk you there."- draft={draft ?? undefined}- belowConversation={- pendingApproval ? (- <AgentChatPendingApprovalCard- idOrSlug={AGENT_BUILDER_SLUG}- approval={pendingApproval}- decide={chat.decideApproval}- />- ) : null- }- aboveComposer={- pendingSecret ? (- <AgentBuilderSecretForm- pending={pendingSecret}- busy={secretBusy}- onSubmit={submitSecret}- onCancel={cancelSecret}- />- ) : null- }- composerDisabledReason={- pendingApproval ? "Waiting on your approval decision" : undefined- }- onSend={chat.send}- onCancel={chat.cancel}- />- )}-- <AgentBuilderMcpConnectDialog- pending={pendingMcpConnect}- busy={mcpConnectBusy}- onSubmit={submitMcpConnect}- onCancel={cancelMcpConnect}- />- </Flex>- );-}--/** Empty-dock state: a short prompt plus page-aware starter suggestions. */-function AgentBuilderEmptyState({- page,- onPick,-}: {- page: AgentBuilderPageContext;- onPick: (prompt: string) => void;-}) {- const suggestions = suggestionsForPage(page);- return (- <Flex direction="column" className="h-full min-h-0 justify-end gap-3 p-3">- <Text className="px-1 text-[12px] text-gray-10 leading-snug">- Ask the agent builder to inspect, debug, or edit your agents — it can- see what you're looking at and walk you there. Try:- </Text>- <Flex direction="column" className="gap-2.5">- {suggestions.map((s) => (- <button- key={s.label}- type="button"- onClick={() => onPick(s.prompt)}- className="group flex items-center gap-2 rounded-(--radius-3) border border-(--gray-5) bg-(--gray-2) px-3 py-2 text-left transition-colors hover:border-(--gray-7) hover:bg-(--gray-3)"- >- <SparkleIcon- size={13}- weight="fill"- className="shrink-0 text-(--accent-9)"- />- <span className="min-w-0 flex-1 truncate text-[12.5px] text-gray-12">- {s.label}- </span>- <ArrowRightIcon- size={12}- className="shrink-0 text-gray-8 transition-colors group-hover:text-gray-11"- />- </button>- ))}- </Flex>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderDockLayout.tsx b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderDockLayout.tsxdeleted file mode 100644index 37691439372b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderDockLayout.tsx+++ /dev/null@@ -1,86 +0,0 @@-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";-import { type ReactNode, useEffect } from "react";-import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";-import { AGENT_PLATFORM_FLAG } from "../featureFlag";-import { AgentBuilderDock } from "./AgentBuilderDock";-import { useAgentBuilderStore } from "./agentBuilderStore";--/**- * Wraps the `/code/agents` content in a resizable split with the always-on- * agent builder dock pinned right. Gated behind the `agent-platform` flag — when- * disabled, the content renders unchanged with no dock or affordance. Hidden by- * default; toggled via the edge affordance, the dock's hide button, or- * Cmd/Ctrl+I. Panel sizes persist (`autoSaveId`).- *- * The content panel is always mounted in the same tree position; only the dock- * panel + resize handle toggle. Keeping the content's React identity stable- * across show/hide means panes don't remount — so per-pane state (the memory- * file you had open, a sessions filter, scroll position) survives toggling.- */-export function AgentBuilderDockLayout({ children }: { children: ReactNode }) {- const enabled = useFeatureFlag(AGENT_PLATFORM_FLAG);- const visible = useAgentBuilderStore((s) => s.visible);- const toggleVisible = useAgentBuilderStore((s) => s.toggleVisible);-- useEffect(() => {- if (!enabled) return;- const onKey = (e: KeyboardEvent) => {- // Cmd/Ctrl+Shift+I — Cmd+I alone is taken by the inbox.- if (!(e.metaKey || e.ctrlKey) || e.altKey || !e.shiftKey) return;- if (e.key.toLowerCase() !== "i") return;- const t = e.target as HTMLElement | null;- if (- t?.tagName === "INPUT" ||- t?.tagName === "TEXTAREA" ||- t?.isContentEditable- ) {- return;- }- e.preventDefault();- toggleVisible();- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [enabled, toggleVisible]);-- // Flag off → no agent builder anywhere in /code/agents.- if (!enabled) {- return <>{children}</>;- }-- // The content panel stays mounted whether the dock is open or not; only the- // dock panel + handle render conditionally. The open affordance lives in the- // agents page headers (AgentBuilderHeaderControls); Cmd/Ctrl+Shift+I toggles.- return (- <PanelGroup- direction="horizontal"- autoSaveId="agents-agent-builder-dock"- className="h-full min-h-0"- >- <Panel- id="agents-content"- order={1}- defaultSize={68}- minSize={40}- className="flex min-h-0 flex-col"- >- {children}- </Panel>- {visible ? (- <>- <PanelResizeHandle className="w-px bg-(--gray-5) transition-colors hover:bg-(--gray-7) data-[resize-handle-state=drag]:bg-(--accent-9)" />- <Panel- id="agents-dock"- order={2}- defaultSize={32}- minSize={22}- maxSize={48}- className="flex min-h-0 flex-col"- >- <AgentBuilderDock />- </Panel>- </>- ) : null}- </PanelGroup>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderHeaderControls.tsx b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderHeaderControls.tsxdeleted file mode 100644index edf3c9d2448d..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderHeaderControls.tsx+++ /dev/null@@ -1,124 +0,0 @@-import { SidebarSimpleIcon, SparkleIcon } from "@phosphor-icons/react";-import {- Button,- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@posthog/quill";-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";-import { Flex } from "@radix-ui/themes";-import { AGENT_PLATFORM_FLAG } from "../featureFlag";-import { headerActionForPage } from "./agentBuilderActions";-import { useAgentBuilderStore } from "./agentBuilderStore";--/**- * The agents-header control cluster — identical across every agents view.- *- * Pinned absolutely to the top-right of the nearest `relative` ancestor so it- * sits on the same row as the Agent Builder dock header (matching `py-2`),- * keeping the two halves of the agents UI visually aligned across views.- *- * One split button is the single entry point into the Agent Builder dock:- * - the primary segment is the contextual "edit with AI" action for the view- * you're on (New agent / Edit configuration / Explain this session / …) — it- * opens the dock and seeds the matching prompt,- * - the trailing segment just opens the dock without seeding, so you can peek- * at the existing conversation; once the dock is open it disappears so we- * don't double up with the dock's own close button.- * Views with no obvious action (Scouts) collapse to the lone open toggle.- * Renders nothing unless the `agent-platform` flag is on.- */-export function AgentBuilderHeaderControls() {- const enabled = useFeatureFlag(AGENT_PLATFORM_FLAG);- const visible = useAgentBuilderStore((s) => s.visible);- const page = useAgentBuilderStore((s) => s.page);- const toggleVisible = useAgentBuilderStore((s) => s.toggleVisible);- const startAgentBuilder = useAgentBuilderStore((s) => s.startAgentBuilder);-- if (!enabled) return null;-- const action = headerActionForPage(page);- const openTip = "Open the agent builder (⌘⇧I)";-- return (- <TooltipProvider delay={500}>- <Flex- align="center"- gap="2"- className="absolute top-0 right-0 z-10 shrink-0 px-6 py-2"- >- {action ? (- <div className="flex items-center">- <Tooltip>- <TooltipTrigger- render={- <Button- variant="outline"- size="sm"- className={- visible- ? "rounded-[3px]"- : "rounded-s-[3px] rounded-e-none"- }- onClick={() =>- startAgentBuilder(action.prompt, action.agentSlug)- }- >- <SparkleIcon- size={14}- weight="fill"- className="text-(--accent-9)"- />- {action.label}- </Button>- }- />- <TooltipContent side="top">- Open the agent builder and start here- </TooltipContent>- </Tooltip>- {visible ? null : (- <Tooltip>- <TooltipTrigger- render={- <Button- variant="outline"- size="icon-sm"- className="rounded-s-none rounded-e-[3px] border-s-0"- aria-label={openTip}- onClick={toggleVisible}- >- <SidebarSimpleIcon size={14} weight="regular" />- </Button>- }- />- <TooltipContent side="top">{openTip}</TooltipContent>- </Tooltip>- )}- </div>- ) : visible ? null : (- <Tooltip>- <TooltipTrigger- render={- <Button- variant="outline"- size="icon-sm"- aria-label={openTip}- onClick={toggleVisible}- >- <SparkleIcon- size={14}- weight="fill"- className="text-(--accent-9)"- />- </Button>- }- />- <TooltipContent side="top">{openTip}</TooltipContent>- </Tooltip>- )}- </Flex>- </TooltipProvider>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderMcpConnectDialog.tsx b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderMcpConnectDialog.tsxdeleted file mode 100644index a778fb30fd2f..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderMcpConnectDialog.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { AddCustomServerDialog } from "@posthog/ui/features/mcp-server-manager/AddCustomServerDialog";-import type { CustomServerInput } from "@posthog/ui/features/mcp-server-manager/useMcpConnect";-import type { PendingMcpConnect } from "./agentBuilderStore";--/**- * Modal for the agent builder's `connect_mcp` punch-out. The agent parks its- * turn and supplies a prefilled name/url; the user reviews + completes the- * connect (OAuth / api key) here — the agent never sees the credentials. On- * success the connection is written onto the target agent's spec and the- * session woken. Thin wrapper over {@link AddCustomServerDialog} with- * punch-out-specific copy and the agent's prefilled values.- */-export function AgentBuilderMcpConnectDialog({- pending,- busy,- onSubmit,- onCancel,-}: {- pending: PendingMcpConnect | null;- busy: boolean;- onSubmit: (values: CustomServerInput) => void;- onCancel: () => void;-}) {- return (- <AddCustomServerDialog- open={!!pending}- pending={busy}- onOpenChange={(open) => {- if (!open) onCancel();- }}- onSubmit={onSubmit}- initialValues={- pending ? { name: pending.name, url: pending.url } : undefined- }- title="Connect an MCP server"- description={- pending?.purpose ??- "Connect a server for this agent. You complete the sign-in — the agent builder never sees your credentials."- }- />- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderSecretForm.tsx b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderSecretForm.tsxdeleted file mode 100644index 3d0da2dc2cc0..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/AgentBuilderSecretForm.tsx+++ /dev/null@@ -1,87 +0,0 @@-import { KeyIcon } from "@phosphor-icons/react";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Text, TextField } from "@radix-ui/themes";-import { type KeyboardEvent, useState } from "react";-import type { PendingSecret } from "./agentBuilderStore";--/**- * Inline punch-out for the agent builder's `set_secret` tool. The agent never sees- * the raw value: the form PUTs it straight to the env-keys API and only the- * `{ key, action }` outcome is posted back to wake the session. Shown above the- * dock composer while a secret is pending.- */-export function AgentBuilderSecretForm({- pending,- busy,- onSubmit,- onCancel,-}: {- pending: PendingSecret;- busy: boolean;- onSubmit: (value: string) => void;- onCancel: () => void;-}) {- const [value, setValue] = useState("");- const action = pending.mode === "rotate" ? "Rotate" : "Set";-- function submit() {- const trimmed = value.trim();- if (!trimmed || busy) return;- onSubmit(trimmed);- }- function onKeyDown(e: KeyboardEvent) {- if (e.key === "Enter") {- e.preventDefault();- submit();- }- }-- return (- <Flex- direction="column"- gap="2"- className="shrink-0 border-(--gray-5) border-t bg-(--gray-2) px-4 py-3"- >- <Flex align="center" gap="2">- <KeyIcon size={14} className="shrink-0 text-(--accent-9)" />- <Text className="font-medium text-[12.5px] text-gray-12">- {action} secret{" "}- <span className="font-mono text-(--accent-11)">{pending.secret}</span>- </Text>- </Flex>- {pending.purpose ? (- <Text className="text-[11.5px] text-gray-10 leading-snug">- {pending.purpose}- </Text>- ) : null}- <Text className="text-[11px] text-gray-9 leading-snug">- The value is sent straight to your agent's secrets — the agent builder- never sees it.- </Text>- <Flex align="center" gap="2">- <TextField.Root- type="password"- autoComplete="off"- value={value}- onChange={(e) => setValue(e.target.value)}- onKeyDown={onKeyDown}- placeholder={`Value for ${pending.secret}`}- className="flex-1 text-[13px]"- autoFocus- />- <Button size="1" onClick={submit} disabled={!value.trim() || busy}>- {busy ? "Saving…" : action}- </Button>- <Button- variant="soft"- color="gray"- size="1"- onClick={onCancel}- disabled={busy}- >- Cancel- </Button>- </Flex>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderActions.ts b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderActions.tsdeleted file mode 100644index 3643e8bfabc5..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderActions.ts+++ /dev/null@@ -1,76 +0,0 @@-import type { AgentBuilderPageContext } from "./agentBuilderStore";--export interface AgentBuilderAction {- /** Short button label, e.g. "New agent" / "Explain this session". */- label: string;- /** Seed prompt sent to the agent builder when clicked. */- prompt: string;- /** Subject agent for the context envelope (null for fleet-level actions). */- agentSlug: string | null;-}--/**- * The contextual agent-builder action for a given view — the AI button's- * content. Drives the abstract header controls so every agents view gets a- * button that fits what you're looking at. Returns null for views with no- * obvious action (just the show/following affordances remain).- */-export function headerActionForPage(- page: AgentBuilderPageContext,-): AgentBuilderAction | null {- switch (page.kind) {- case "agent-list":- return {- label: "New agent",- prompt:- "Help me create a new agent — walk me through what it should do, then set it up.",- agentSlug: null,- };- case "agent":- return {- label: "Explain this agent",- prompt: "Explain what this agent does and how it's configured.",- agentSlug: page.slug,- };- case "agent-config":- return {- label: "Edit configuration",- prompt: "Help me change this agent's configuration.",- agentSlug: page.slug,- };- case "agent-sessions":- return {- label: "Review sessions",- prompt:- "Review this agent's recent sessions and surface anything notable.",- agentSlug: page.slug,- };- case "agent-session":- return {- label: "Explain this session",- prompt: "Explain what happened in this session, step by step.",- agentSlug: page.slug,- };- case "agent-approvals":- return {- label: "Review approvals",- prompt: "Review the pending approval requests for this agent.",- agentSlug: page.slug,- };- case "agent-memory":- return {- label: "Ask about memory",- prompt: "Summarize what's stored in this agent's memory.",- agentSlug: page.slug,- };- case "agent-observability":- return {- label: "Ask about performance",- prompt:- "Summarize this agent's spend, volume, and failure rate, and call out anything notable.",- agentSlug: page.slug,- };- default:- return null;- }-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderStore.ts b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderStore.tsdeleted file mode 100644index 3609a191d447..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderStore.ts+++ /dev/null@@ -1,170 +0,0 @@-import { electronStorage } from "@posthog/ui/shell/rendererStorage";-import { create } from "zustand";-import { persist } from "zustand/middleware";--/** The deployed meta-agent the agent builder dock always talks to. */-export const AGENT_BUILDER_SLUG = "agent-builder";--/** Key for the agent builder's chat in the core `agentChatStore`. */-export const AGENT_BUILDER_CHAT_ID = "agent-builder";--/**- * What the user is currently looking at in `/code/agents`. Mirrors the console's- * `AgentBuilderPageContext` so the agent builder can resolve deictic references ("this- * agent", "this session") and drive the right `focus_*` target. Each route- * registers its context on mount via `useSetAgentBuilderPage`.- */-export type AgentBuilderPageContext =- | { kind: "agent-list" }- | { kind: "scouts" }- | { kind: "agent"; slug: string }- | { kind: "agent-config"; slug: string; node?: string; revision?: string }- | { kind: "agent-sessions"; slug: string }- | { kind: "agent-session"; slug: string; sessionId: string }- | { kind: "agent-approvals"; slug: string; request?: string }- | { kind: "agent-memory"; slug: string }- | { kind: "agent-observability"; slug: string }- | { kind: "agent-chat"; slug: string }- | { kind: "unknown" };--/** A pending contextual hand-off: open the dock and prefill the composer with- * `prompt` (the user reviews and sends — it is never auto-sent). */-export interface AgentBuilderSeed {- /** Monotonic id so a consumer can mark exactly one seed handled. */- seq: number;- prompt: string;- /** Agent the seed is about, for the context envelope. */- agentSlug: string | null;-}--/**- * An in-flight `set_secret` punch-out. The agent parked its turn; the dock- * renders a form for these, and on submit PUTs the key + wakes the session.- */-export interface PendingSecret {- /** The parked tool call to resolve via `/send`. */- callId: string;- agentSlug: string;- /**- * Revision the secret is written to. Env keys are revision-scoped, so the- * `set_secret` punch-out must target a specific revision (the one the agent- * is editing). Sourced from the tool args, falling back to the dock's- * current `agent-config` page context.- */- revisionId: string;- /** Env key name, e.g. "ANTHROPIC_KEY". The value is never seen by the agent. */- secret: string;- mode?: "set" | "rotate";- purpose?: string;-}--/**- * An in-flight `connect_mcp` punch-out. The agent parked its turn; the dock- * renders a prefilled connect form, the user completes the auth (OAuth / api- * key — tokens never reach the agent), and on success the new connection is- * written into the target agent's spec and the session woken.- */-export interface PendingMcpConnect {- /** The parked tool call to resolve via `/send`. */- callId: string;- /** Agent whose spec gets the `mcps[].connection` entry. */- agentSlug: string;- /** Draft revision the mcps[] entry is written to (spec edits are revision- * scoped). Sourced from the tool args, falling back to the dock's current- * `agent-config` page context. */- revisionId: string;- /** Prefilled server name (editable by the user). */- name?: string;- /** Prefilled MCP server URL (editable by the user). */- url?: string;- /** One-line reason shown above the form. */- purpose?: string;-}--interface AgentBuilderStore {- /** Dock open/closed (persisted). */- visible: boolean;- /** Whether the agent's `focus_*` tools may navigate the UI (persisted). */- followMode: boolean;- /** Current page context (ephemeral — re-registered per route). */- page: AgentBuilderPageContext;- /** Pending edit-with-AI hand-off (ephemeral). */- seed: AgentBuilderSeed | null;- /** In-flight set_secret punch-out the dock renders a form for (ephemeral). */- pendingSecret: PendingSecret | null;- /** In-flight connect_mcp punch-out the dock renders a connect form for- * (ephemeral). */- pendingMcpConnect: PendingMcpConnect | null;- /**- * The dock's most recent chat session (persisted) plus the project/org it- * belongs to. On reload the dock resumes it from the slug-routed ingress so- * the conversation survives a refresh — the in-memory `agentChatStore`- * doesn't. The context is stamped so resume only restores a session in the- * project/org it started in: the builder threads `project_id` into its tools- * and the session is org-scoped at the ingress, so a conversation doesn't- * carry across a project/org switch.- */- lastSession: {- id: string;- projectId: number | null;- orgId: string | null;- } | null;-- toggleVisible: () => void;- setVisible: (visible: boolean) => void;- setFollowMode: (followMode: boolean) => void;- setPage: (page: AgentBuilderPageContext) => void;- /** Open the dock and prefill the composer with a prompt (not sent). */- startAgentBuilder: (prompt: string, agentSlug?: string | null) => void;- /** Mark a seed handled (no-op if a newer seed has since replaced it). */- consumeSeed: (seq: number) => void;- setPendingSecret: (pending: PendingSecret | null) => void;- setPendingMcpConnect: (pending: PendingMcpConnect | null) => void;- setLastSession: (- session: {- id: string;- projectId: number | null;- orgId: string | null;- } | null,- ) => void;-}--export const useAgentBuilderStore = create<AgentBuilderStore>()(- persist(- (set) => ({- visible: false,- followMode: true,- page: { kind: "unknown" },- seed: null,- pendingSecret: null,- pendingMcpConnect: null,- lastSession: null,-- toggleVisible: () => set((s) => ({ visible: !s.visible })),- setVisible: (visible) => set({ visible }),- setFollowMode: (followMode) => set({ followMode }),- setPage: (page) => set({ page }),- startAgentBuilder: (prompt, agentSlug = null) =>- set((s) => ({- visible: true,- seed: { seq: (s.seed?.seq ?? 0) + 1, prompt, agentSlug },- })),- consumeSeed: (seq) =>- set((s) => (s.seed?.seq === seq ? { seed: null } : s)),- setPendingSecret: (pendingSecret) => set({ pendingSecret }),- setPendingMcpConnect: (pendingMcpConnect) => set({ pendingMcpConnect }),- setLastSession: (lastSession) => set({ lastSession }),- }),- {- name: "agent-builder-dock",- storage: electronStorage,- // Page + seed are ephemeral; persist the layout prefs + the last session- // (with its project/org) so the dock can resume across a reload.- partialize: (s) => ({- visible: s.visible,- followMode: s.followMode,- lastSession: s.lastSession,- }),- },- ),-);diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderSuggestions.ts b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderSuggestions.tsdeleted file mode 100644index 3b201b3235ba..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/agentBuilderSuggestions.ts+++ /dev/null@@ -1,126 +0,0 @@-import type { AgentBuilderPageContext } from "./agentBuilderStore";--export interface AgentBuilderSuggestion {- label: string;- prompt: string;-}--/**- * Starter prompts shown in the empty Agent Builder dock, tailored to what the- * user is looking at. The agent resolves "this agent"/"this session" from the- * page-context envelope, so prompts can stay deictic. Mirrors the old console's- * contextual suggestions.- */-export function suggestionsForPage(- page: AgentBuilderPageContext,-): AgentBuilderSuggestion[] {- switch (page.kind) {- case "agent-list":- case "scouts":- case "unknown":- return [- {- label: "Create a new agent",- prompt:- "Help me create a new agent — walk me through what it should do, then set it up.",- },- {- label: "What's changed in the last week?",- prompt:- "Summarize what's changed across my agents in the last week — new revisions, notable sessions, and any failures.",- },- {- label: "Audit my agents",- prompt:- "Audit all my agents and flag anything underperforming or misconfigured.",- },- ];- case "agent":- return [- {- label: "What does this agent do?",- prompt: "Explain what this agent does and how it's configured.",- },- {- label: "Is this agent healthy?",- prompt:- "Check this agent's recent sessions and tell me whether it's healthy.",- },- {- label: "Suggest improvements",- prompt: "Review this agent and suggest concrete improvements.",- },- ];- case "agent-config":- return [- {- label: "Explain this configuration",- prompt: "Walk me through this agent's configuration.",- },- {- label: "Edit the system prompt",- prompt: "I want to change this agent's system prompt.",- },- {- label: "Add a tool or skill",- prompt: "Help me add a tool or skill to this agent.",- },- ];- case "agent-sessions":- return [- {- label: "Any failing sessions?",- prompt:- "Look at this agent's recent sessions and surface any failures.",- },- {- label: "Summarize recent activity",- prompt: "Summarize this agent's recent session activity.",- },- ];- case "agent-session":- return [- {- label: "What happened here?",- prompt: "Explain what happened in this session, step by step.",- },- {- label: "Debug this session",- prompt: "Debug this session — what went wrong and how do I fix it?",- },- ];- case "agent-approvals":- return [- {- label: "Review pending approvals",- prompt: "Review the pending approval requests for this agent.",- },- ];- case "agent-memory":- return [- {- label: "What's in memory?",- prompt: "Summarize what's stored in this agent's memory.",- },- ];- case "agent-observability":- return [- {- label: "How is this agent performing?",- prompt:- "Summarize this agent's spend, volume, and failure rate, and call out anything notable.",- },- ];- default:- return [- {- label: "Create a new agent",- prompt: "Help me create a new agent.",- },- {- label: "What's changed in the last week?",- prompt: "Summarize what's changed across my agents in the last week.",- },- ];- }-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useAgentBuilderClientTools.test.ts b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useAgentBuilderClientTools.test.tsdeleted file mode 100644index 62e250600bde..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useAgentBuilderClientTools.test.ts+++ /dev/null@@ -1,231 +0,0 @@-import { renderHook } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--vi.mock("@tanstack/react-router", () => ({- useNavigate: () => vi.fn(),-}));--const client = {- getAgentApplication: vi.fn(),- listAgentRevisions: vi.fn(),- getAgentRevision: vi.fn(),-};--vi.mock("@posthog/ui/features/auth/authClient", () => ({- useAuthenticatedClient: () => client,-}));--import type { ClientToolCallData } from "@posthog/core/agent-chat/identifiers";-import { useAgentBuilderStore } from "./agentBuilderStore";-import { useAgentBuilderClientTools } from "./useAgentBuilderClientTools";--function call(- tool_id: string,- args: Record<string, unknown>,-): ClientToolCallData {- return { call_id: "call-1", tool_id, args };-}--function handler() {- return renderHook(() => useAgentBuilderClientTools()).result.current;-}--describe("useAgentBuilderClientTools revision resolution", () => {- beforeEach(() => {- client.getAgentApplication.mockReset();- client.listAgentRevisions.mockReset();- client.getAgentRevision.mockReset();- useAgentBuilderStore.setState({- page: { kind: "unknown" },- pendingSecret: null,- pendingMcpConnect: null,- });- });-- it("uses an explicit revision_id once it verifies as belonging to the agent", async () => {- client.getAgentRevision.mockResolvedValue({ id: "rev-explicit" });-- const outcome = await handler()(- call("set_secret", {- agent_slug: "my-agent",- secret: "API_KEY",- revision_id: "rev-explicit",- }),- );-- expect(outcome).toEqual({ defer: true });- expect(useAgentBuilderStore.getState().pendingSecret).toMatchObject({- agentSlug: "my-agent",- secret: "API_KEY",- revisionId: "rev-explicit",- });- expect(client.getAgentRevision).toHaveBeenCalledWith(- "my-agent",- "rev-explicit",- );- expect(client.getAgentApplication).not.toHaveBeenCalled();- expect(client.listAgentRevisions).not.toHaveBeenCalled();- });-- it("rejects an explicit revision_id that does not belong to the agent", async () => {- // The nested revision route 404s (→ null) for another agent's revision.- client.getAgentRevision.mockResolvedValue(null);-- const outcome = await handler()(- call("set_secret", {- agent_slug: "my-agent",- secret: "API_KEY",- revision_id: "rev-of-other-agent",- }),- );-- expect(outcome).toEqual({- error: "revision_not_found: rev-of-other-agent on my-agent",- });- expect(useAgentBuilderStore.getState().pendingSecret).toBeNull();- });-- it("falls back to the revision open on this agent's config page", async () => {- useAgentBuilderStore.setState({- page: { kind: "agent-config", slug: "my-agent", revision: "rev-page" },- });-- const outcome = await handler()(- call("set_secret", { agent_slug: "my-agent", secret: "API_KEY" }),- );-- expect(outcome).toEqual({ defer: true });- expect(useAgentBuilderStore.getState().pendingSecret?.revisionId).toBe(- "rev-page",- );- expect(client.getAgentApplication).not.toHaveBeenCalled();- });-- it("rotation targets live even while a draft config page is open", async () => {- useAgentBuilderStore.setState({- page: { kind: "agent-config", slug: "my-agent", revision: "rev-draft" },- });- client.getAgentApplication.mockResolvedValue({ live_revision: "rev-live" });- client.listAgentRevisions.mockResolvedValue([- { id: "rev-draft", state: "draft" },- { id: "rev-live", state: "ready" },- ]);-- await handler()(- call("set_secret", {- agent_slug: "my-agent",- secret: "API_KEY",- mode: "rotate",- }),- );-- expect(useAgentBuilderStore.getState().pendingSecret?.revisionId).toBe(- "rev-live",- );- });-- it("ignores the page revision when it belongs to a different agent", async () => {- useAgentBuilderStore.setState({- page: { kind: "agent-config", slug: "other-agent", revision: "rev-page" },- });- client.getAgentApplication.mockResolvedValue({ live_revision: null });- client.listAgentRevisions.mockResolvedValue([- { id: "rev-draft", state: "draft" },- ]);-- await handler()(- call("set_secret", { agent_slug: "my-agent", secret: "API_KEY" }),- );-- expect(useAgentBuilderStore.getState().pendingSecret?.revisionId).toBe(- "rev-draft",- );- });-- it.each([- // A new secret targets the draft being authored (secrets only copy- // forward at draft creation), even when a live revision exists.- { mode: "set", expected: "rev-draft" },- // A rotation targets what's running.- { mode: "rotate", expected: "rev-live" },- ])(- "set_secret mode=$mode resolves to $expected via the API",- async ({ mode, expected }) => {- client.getAgentApplication.mockResolvedValue({- live_revision: "rev-live",- });- client.listAgentRevisions.mockResolvedValue([- { id: "rev-draft", state: "draft" },- { id: "rev-live", state: "ready" },- ]);-- await handler()(- call("set_secret", { agent_slug: "my-agent", secret: "API_KEY", mode }),- );-- expect(useAgentBuilderStore.getState().pendingSecret?.revisionId).toBe(- expected,- );- },- );-- it("set_secret falls back to the newest revision when no live or draft exists", async () => {- client.getAgentApplication.mockResolvedValue({ live_revision: null });- client.listAgentRevisions.mockResolvedValue([- { id: "rev-newest", state: "ready" },- { id: "rev-older", state: "ready" },- ]);-- await handler()(- call("set_secret", { agent_slug: "my-agent", secret: "API_KEY" }),- );-- expect(useAgentBuilderStore.getState().pendingSecret?.revisionId).toBe(- "rev-newest",- );- });-- it("errors when the agent has no revisions at all", async () => {- client.getAgentApplication.mockResolvedValue({ live_revision: null });- client.listAgentRevisions.mockResolvedValue([]);-- const outcome = await handler()(- call("set_secret", { agent_slug: "my-agent", secret: "API_KEY" }),- );-- expect(outcome).toEqual({ error: "no_target_revision: my-agent" });- expect(useAgentBuilderStore.getState().pendingSecret).toBeNull();- });-- it("errors when revision lookup fails", async () => {- client.getAgentApplication.mockRejectedValue(new Error("network"));- client.listAgentRevisions.mockRejectedValue(new Error("network"));-- const outcome = await handler()(- call("set_secret", { agent_slug: "my-agent", secret: "API_KEY" }),- );-- expect(outcome).toEqual({ error: "no_target_revision: my-agent" });- });-- it("connect_mcp prefers the newest draft (spec edits are draft-only)", async () => {- client.getAgentApplication.mockResolvedValue({- live_revision: "rev-live",- });- client.listAgentRevisions.mockResolvedValue([- { id: "rev-draft", state: "draft" },- { id: "rev-live", state: "ready" },- ]);-- const outcome = await handler()(- call("connect_mcp", { agent_slug: "my-agent", url: "https://mcp.test" }),- );-- expect(outcome).toEqual({ defer: true });- expect(useAgentBuilderStore.getState().pendingMcpConnect).toMatchObject({- agentSlug: "my-agent",- revisionId: "rev-draft",- url: "https://mcp.test",- });- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useAgentBuilderClientTools.ts b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useAgentBuilderClientTools.tsdeleted file mode 100644index dcbc19adea14..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useAgentBuilderClientTools.ts+++ /dev/null@@ -1,262 +0,0 @@-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useNavigate } from "@tanstack/react-router";-import { useCallback, useRef } from "react";-import type { ClientToolHandler } from "../hooks/useAgentChat";-import { useAgentBuilderStore } from "./agentBuilderStore";--/**- * The `kind:'client'` tool ids the agent-builder dock can fulfil — sent to the- * runner as `supported_client_tools` at /run so it exposes only these to the- * model. Keep in sync with the handlers below (plus the built-in- * toast/get_context). `set_secret`/`connect_mcp` are interactive punch-outs.- */-export const AGENT_BUILDER_CLIENT_TOOLS = [- "set_secret",- "connect_mcp",- "focus_tab",- "focus_file",- "focus_spec_section",- "focus_revision",- "focus_session",- "toast",- "get_context",-] as const;--/**- * The agent builder's UI-driving client tools. The agent calls these to steer the- * user's screen (`focus_*`, which navigate code's agent routes and report back- * `{ focused }`) and to set secrets (`set_secret`, an interactive punch-out:- * park the call and render a form — see the dock). Returning `null` defers to- * the built-in toast/get_context handlers.- *- * `focus_*` navigations are gated by follow-mode: when off, they report- * `{ focused: false, reason: "user_paused_follow" }` instead of moving the UI.- */-export function useAgentBuilderClientTools(): ClientToolHandler {- const navigate = useNavigate();- const client = useAuthenticatedClient();- const followMode = useAgentBuilderStore((s) => s.followMode);- const setPendingSecret = useAgentBuilderStore((s) => s.setPendingSecret);- const setPendingMcpConnect = useAgentBuilderStore(- (s) => s.setPendingMcpConnect,- );- const page = useAgentBuilderStore((s) => s.page);- const followRef = useRef(followMode);- followRef.current = followMode;- // Latest page context without re-creating the handler each render — resolves- // the revision a `set_secret` punch-out targets when the agent omits one.- const pageRef = useRef(page);- pageRef.current = page;-- return useCallback(- async (data) => {- const args = (data.args ?? {}) as Record<string, unknown>;- const str = (v: unknown) => (typeof v === "string" ? v : undefined);-- // Env keys and spec edits are revision-scoped, but the punch-out tool- // schemas don't define `revision_id`, so the agent usually omits it.- // Resolve the target: explicit arg → the revision the user is viewing on- // this agent's config page → API fallback. Preference matters because- // secrets only copy forward at draft creation and spec PATCHes only land- // on drafts: a *new* secret or MCP connection targets the draft being- // authored, while a rotation targets what's running (live).- const resolveRevision = async (- agentSlug: string,- prefer: "live" | "draft",- ): Promise<string | undefined> => {- const p = pageRef.current;- // The viewed revision only stands in for authoring flows: a rotation- // must reach what's running even while the user is viewing a draft.- if (- prefer === "draft" &&- p.kind === "agent-config" &&- p.slug === agentSlug &&- p.revision- ) {- return p.revision;- }- try {- // A revision's `state` stays "ready" when promoted — live is the- // application's `live_revision` pointer, not a revision state.- const [app, revisions] = await Promise.all([- client.getAgentApplication(agentSlug),- client.listAgentRevisions(agentSlug),- ]);- const live = app?.live_revision ?? undefined;- const draft = revisions.find((r) => r.state === "draft")?.id;- const newest = revisions[0]?.id;- return prefer === "draft"- ? (draft ?? live ?? newest)- : (live ?? draft ?? newest);- } catch {- return undefined;- }- };-- // An explicit `revision_id` must belong to `agent_slug` before we park- // the punch-out. The nested env/spec routes reject mismatches- // server-side anyway, but that failure would only surface at submit —- // after the user has already typed a secret into a doomed form.- const verifyExplicitRevision = async (- agentSlug: string,- revisionId: string,- ): Promise<boolean> => {- const revision = await client- .getAgentRevision(agentSlug, revisionId)- .catch(() => null);- return revision != null;- };-- // set_secret — interactive punch-out. Park the call (defer) and render a- // form; the dock PUTs the key and wakes the session on submit.- if (data.tool_id === "set_secret") {- const agentSlug = str(args.agent_slug);- const secret = str(args.secret);- if (!agentSlug) return { error: "missing_arg: agent_slug" };- if (!secret) return { error: "missing_arg: secret" };- const mode = args.mode === "rotate" ? "rotate" : "set";- const explicit = str(args.revision_id);- if (explicit && !(await verifyExplicitRevision(agentSlug, explicit))) {- return { error: `revision_not_found: ${explicit} on ${agentSlug}` };- }- const revisionId =- explicit ??- (await resolveRevision(- agentSlug,- mode === "rotate" ? "live" : "draft",- ));- if (!revisionId) return { error: `no_target_revision: ${agentSlug}` };- setPendingSecret({- callId: data.call_id,- agentSlug,- revisionId,- secret,- mode,- purpose: str(args.purpose),- });- return { defer: true };- }-- // connect_mcp — interactive punch-out. Park the call and render a prefilled- // connect form; the dock runs the native OAuth/api-key connect (auth never- // touches the agent), writes the resulting mcps[].connection onto the- // target agent's spec, and wakes the session. Same revision resolution as- // set_secret.- if (data.tool_id === "connect_mcp") {- const agentSlug = str(args.agent_slug);- if (!agentSlug) return { error: "missing_arg: agent_slug" };- const explicit = str(args.revision_id);- if (explicit && !(await verifyExplicitRevision(agentSlug, explicit))) {- return { error: `revision_not_found: ${explicit} on ${agentSlug}` };- }- const revisionId =- explicit ?? (await resolveRevision(agentSlug, "draft"));- if (!revisionId) return { error: `no_target_revision: ${agentSlug}` };- setPendingMcpConnect({- callId: data.call_id,- agentSlug,- revisionId,- name: str(args.name),- url: str(args.url),- purpose: str(args.purpose),- });- return { defer: true };- }-- if (!data.tool_id.startsWith("focus_")) return null;- const slug = str(args.slug);- if (!followRef.current) {- return { result: { focused: false, reason: "user_paused_follow" } };- }- if (!slug) {- return { result: { focused: false, reason: "missing_slug" } };- }- const params = { idOrSlug: slug };-- switch (data.tool_id) {- case "focus_tab": {- const tab = str(args.tab) ?? "overview";- switch (tab) {- case "configuration":- navigate({- to: "/code/agents/applications/$idOrSlug/configuration",- params,- });- break;- case "sessions":- navigate({- to: "/code/agents/applications/$idOrSlug/sessions",- params,- });- break;- case "memory":- navigate({- to: "/code/agents/applications/$idOrSlug/memory",- params,- });- break;- case "approvals":- navigate({- to: "/code/agents/applications/$idOrSlug/approvals",- params,- });- break;- case "observability":- navigate({- to: "/code/agents/applications/$idOrSlug/observability",- params,- });- break;- case "chat":- navigate({- to: "/code/agents/applications/$idOrSlug/chat",- params,- });- break;- default:- navigate({- to: "/code/agents/applications/$idOrSlug",- params,- });- }- return { result: { focused: true } };- }- case "focus_file":- navigate({- to: "/code/agents/applications/$idOrSlug/configuration",- params,- search: { node: str(args.path) },- });- return { result: { focused: true } };- case "focus_spec_section":- navigate({- to: "/code/agents/applications/$idOrSlug/configuration",- params,- search: { node: str(args.section) },- });- return { result: { focused: true } };- case "focus_revision":- navigate({- to: "/code/agents/applications/$idOrSlug/configuration",- params,- search: { revision: str(args.revisionId) },- });- return { result: { focused: true } };- case "focus_session": {- const sessionId = str(args.sessionId);- if (!sessionId) {- return { result: { focused: false, reason: "missing_session_id" } };- }- navigate({- to: "/code/agents/applications/$idOrSlug/sessions/$sessionId",- params: { idOrSlug: slug, sessionId },- });- return { result: { focused: true } };- }- default:- return { result: { focused: false, reason: "unknown_focus_target" } };- }- },- [navigate, client, setPendingSecret, setPendingMcpConnect],- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useSetAgentBuilderPage.ts b/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useSetAgentBuilderPage.tsdeleted file mode 100644index 76dbe9d563ab..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/agent-builder/useSetAgentBuilderPage.ts+++ /dev/null@@ -1,19 +0,0 @@-import { useEffect } from "react";-import {- type AgentBuilderPageContext,- useAgentBuilderStore,-} from "./agentBuilderStore";--/**- * Registers what the user is currently looking at so the agent builder can resolve- * deictic references and drive the right `focus_*` target. Each `/code/agents`- * route calls this on mount. No cleanup: the next route overwrites the page, so- * the last-viewed context persists (the dock only reads it inside `/code/agents`).- */-export function useSetAgentBuilderPage(page: AgentBuilderPageContext): void {- const setPage = useAgentBuilderStore((s) => s.setPage);- const key = JSON.stringify(page);- useEffect(() => {- setPage(JSON.parse(key) as AgentBuilderPageContext);- }, [key, setPage]);-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/acpEnvelope.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/acpEnvelope.tsdeleted file mode 100644index 417f3b0c39b9..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/acpEnvelope.ts+++ /dev/null@@ -1,147 +0,0 @@-/**- * Pure constructors for the JSON-RPC `AcpMessage` envelopes that code's- * `buildConversationItems` reducer consumes.- *- * The agent_platform runtime speaks a different wire protocol (agent-ingress- * SSE frames + a stored pi-ai `conversation` array). Rather than re-implement- * the console's `runnerReducer`, we translate each agent_platform event into- * the equivalent ACP message and let code's existing builder do all the- * accumulation (streaming-text concatenation, tool-call merging, turn- * tracking). These helpers mint those messages.- *- * Mapping summary:- * user message → `session/prompt` request → opens a turn + user bubble- * assistant text → `session/update` (agent_message_chunk)- * assistant thinking → `session/update` (agent_thought_chunk)- * tool call → `session/update` (tool_call)- * tool result → `session/update` (tool_call_update)- * turn end → `_posthog/turn_complete` notification- */--import type {- ContentBlock,- SessionUpdate,- ToolCallContent,- ToolCallStatus,-} from "@agentclientprotocol/sdk";-import { POSTHOG_NOTIFICATIONS } from "@posthog/agent/acp-extensions";-import type { AcpMessage } from "@posthog/shared";--/** A plain-text ACP content block. */-export function textBlock(text: string): ContentBlock {- return { type: "text", text };-}--/** A tool-call content item wrapping plain text (rendered under the call). */-export function textToolContent(text: string): ToolCallContent {- return { type: "content", content: { type: "text", text } };-}--/**- * A `session/prompt` JSON-RPC request. The builder keys a turn off the request- * `id` and renders the prompt text as the user bubble, so each user message- * needs a unique, monotonic id within the conversation.- */-export function promptRequestMessage(- id: number,- text: string,- ts: number,-): AcpMessage {- return {- type: "acp_message",- ts,- message: {- jsonrpc: "2.0",- id,- method: "session/prompt",- params: { prompt: [textBlock(text)] },- },- };-}--/** A `session/update` notification wrapping an ACP `SessionUpdate`. */-export function sessionUpdateMessage(- update: SessionUpdate,- ts: number,-): AcpMessage {- return {- type: "acp_message",- ts,- message: {- jsonrpc: "2.0",- method: "session/update",- params: { update },- },- };-}--/** A `_posthog/turn_complete` notification — closes the active turn. */-export function turnCompleteMessage(- ts: number,- stopReason?: string,-): AcpMessage {- return {- type: "acp_message",- ts,- message: {- jsonrpc: "2.0",- method: POSTHOG_NOTIFICATIONS.TURN_COMPLETE,- params: stopReason ? { stopReason } : {},- },- };-}--/** Streaming/settled assistant text fragment. */-export function agentTextUpdate(text: string): SessionUpdate {- return { sessionUpdate: "agent_message_chunk", content: textBlock(text) };-}--/** Assistant thinking/reasoning fragment. */-export function agentThoughtUpdate(text: string): SessionUpdate {- return { sessionUpdate: "agent_thought_chunk", content: textBlock(text) };-}--/**- * A new tool call. Status is left to a later `tool_call_update` (from the- * tool result) so a call without a result reads as still-running rather than- * falsely completed.- */-export function toolCallStartUpdate(- toolCallId: string,- title: string,- rawInput?: unknown,- status?: ToolCallStatus,-): SessionUpdate {- return {- sessionUpdate: "tool_call",- toolCallId,- title,- ...(rawInput === undefined ? {} : { rawInput }),- ...(status ? { status } : {}),- };-}--/** Merge canonical args onto an existing tool call. */-export function toolCallArgsUpdate(- toolCallId: string,- title: string,- rawInput: unknown,-): SessionUpdate {- return { sessionUpdate: "tool_call_update", toolCallId, title, rawInput };-}--/** Finalize a tool call with its outcome (text body + completed/failed). */-export function toolResultUpdate(- toolCallId: string,- text: string,- isError: boolean,- rawOutput?: unknown,-): SessionUpdate {- return {- sessionUpdate: "tool_call_update",- toolCallId,- status: isError ? "failed" : "completed",- content: [textToolContent(text)],- ...(rawOutput === undefined ? {} : { rawOutput }),- };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/chatHistoryStore.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/chatHistoryStore.tsdeleted file mode 100644index 69f8068d453e..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/chatHistoryStore.ts+++ /dev/null@@ -1,63 +0,0 @@-import { electronStorage } from "@posthog/ui/shell/rendererStorage";-import { create } from "zustand";-import { persist } from "zustand/middleware";--/**- * Locally-persisted index of chats the user started against an agent- * *from this app*. These are the only sessions surfaced in the chat pane's- * rail — deliberately NOT the agent's full server session list, which can- * include real customer conversations. Keyed by agent slug; each entry is just- * enough to re-attach (`/listen` replays the transcript) and label the rail.- */-export interface ChatHistoryEntry {- sessionId: string;- /** First user message of the chat, for the rail label. */- title: string;- /** Epoch ms when the chat was started here. */- startedAt: number;- /**- * Revision the chat targets, when the user opened it as a chat against a- * non-live revision. Undefined for sessions that ran against `live_revision`.- * Lets the rail label draft chats and route resumes back to the right- * revision surface.- */- revisionId?: string;-}--interface ChatHistoryState {- byAgent: Record<string, ChatHistoryEntry[]>;- /** Record (or move-to-top) a chat the user started here. */- record: (agentKey: string, entry: ChatHistoryEntry) => void;- remove: (agentKey: string, sessionId: string) => void;-}--/** Per-agent cap; entries are throwaway, so an old tail is fine to drop. */-const MAX_PER_AGENT = 50;--export const useChatHistoryStore = create<ChatHistoryState>()(- persist(- (set) => ({- byAgent: {},- record: (agentKey, entry) =>- set((s) => {- const existing = s.byAgent[agentKey] ?? [];- // Newest first, de-duped by sessionId, capped.- const next = [- entry,- ...existing.filter((e) => e.sessionId !== entry.sessionId),- ].slice(0, MAX_PER_AGENT);- return { byAgent: { ...s.byAgent, [agentKey]: next } };- }),- remove: (agentKey, sessionId) =>- set((s) => ({- byAgent: {- ...s.byAgent,- [agentKey]: (s.byAgent[agentKey] ?? []).filter(- (e) => e.sessionId !== sessionId,- ),- },- })),- }),- { name: "agent-preview-chats", storage: electronStorage },- ),-);diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/consoleContext.test.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/consoleContext.test.tsdeleted file mode 100644index d2482a0274e3..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/consoleContext.test.ts+++ /dev/null@@ -1,33 +0,0 @@-import { describe, expect, it } from "vitest";-import {- buildConsoleContextEnvelope,- stripConsoleContext,-} from "./consoleContext";--describe("console context envelope", () => {- it("round-trips: strip removes a prepended envelope", () => {- const envelope = buildConsoleContextEnvelope({ page: "agent", agent: "x" });- const wire = `${envelope}\n\nHello there`;- expect(stripConsoleContext(wire)).toBe("Hello there");- });-- it("leaves plain text untouched", () => {- expect(stripConsoleContext("just a message")).toBe("just a message");- });-- it("only strips a leading envelope, not one mid-message", () => {- const text =- "please render [console-context]{}[/console-context] literally";- expect(stripConsoleContext(text)).toBe(text);- });-- it("tolerates leading whitespace before the envelope", () => {- const wire = ` ${buildConsoleContextEnvelope({ page: "agent-list" })}\n\nhi`;- expect(stripConsoleContext(wire)).toBe("hi");- });-- it("is a no-op when the closing delimiter is missing", () => {- const text = "[console-context]{oops";- expect(stripConsoleContext(text)).toBe(text);- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/consoleContext.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/consoleContext.tsdeleted file mode 100644index 4ae9d0bb6a23..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/consoleContext.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * The agent builder's "what am I looking at" envelope. Mirrors the console: the- * current page context is prepended to the *first* user message of a session,- * delimited so the agent can resolve deictic references ("this agent", "this- * session") without asking — and so the client can strip it before display.- */--const OPEN = "[console-context]";-const CLOSE = "[/console-context]";--/** Wrap a context object in the delimited envelope (prepended to msg one). */-export function buildConsoleContextEnvelope(context: unknown): string {- return `${OPEN}\n${JSON.stringify(context)}\n${CLOSE}`;-}--/**- * Strip a leading console-context block (and the blank line after it) so the- * envelope never shows in the rendered transcript. No-op when absent.- */-export function stripConsoleContext(text: string): string {- const start = text.indexOf(OPEN);- if (start === -1) return text;- const end = text.indexOf(CLOSE, start);- if (end === -1) return text;- const before = text.slice(0, start);- // Only strip a *leading* envelope (allow leading whitespace before it).- if (before.trim() !== "") return text;- return text.slice(end + CLOSE.length).replace(/^\s*\n/, "");-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/conversationToAcp.test.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/conversationToAcp.test.tsdeleted file mode 100644index fa6d7fc3022a..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/conversationToAcp.test.ts+++ /dev/null@@ -1,184 +0,0 @@-import type {- SessionNotification,- SessionUpdate,-} from "@agentclientprotocol/sdk";-import type {- AcpMessage,- JsonRpcNotification,- JsonRpcRequest,-} from "@posthog/shared";-import type { AgentConversationMessage } from "@posthog/shared/agent-platform-types";-import { describe, expect, it } from "vitest";-import {- conversationToAcpMessages,- userMessageText,-} from "./conversationToAcp";--function methodOf(m: AcpMessage): string | undefined {- return "method" in m.message ? m.message.method : undefined;-}--function updateOf(m: AcpMessage): SessionUpdate {- const params = (m.message as JsonRpcNotification)- .params as SessionNotification;- return params.update;-}--describe("conversationToAcpMessages", () => {- it("maps a single user→assistant turn to prompt + text chunk + turn_complete", () => {- const convo: AgentConversationMessage[] = [- { role: "user", content: "hello there", timestamp: 1000 },- {- role: "assistant",- content: [{ type: "text", text: "hi back" }],- timestamp: 2000,- },- ];-- const out = conversationToAcpMessages(convo);-- expect(out.map(methodOf)).toEqual([- "session/prompt",- "session/update",- "_posthog/turn_complete",- ]);- const prompt = out[0].message as JsonRpcRequest<{- prompt: { type: string; text: string }[];- }>;- expect(prompt.id).toBe(1);- expect(prompt.params?.prompt[0]).toEqual({- type: "text",- text: "hello there",- });- expect(updateOf(out[1])).toEqual({- sessionUpdate: "agent_message_chunk",- content: { type: "text", text: "hi back" },- });- });-- it("emits thinking as an agent_thought_chunk", () => {- const out = conversationToAcpMessages([- { role: "user", content: "think", timestamp: 1 },- {- role: "assistant",- content: [- { type: "thinking", thinking: "hmm" },- { type: "text", text: "answer" },- ],- timestamp: 2,- },- ]);- expect(updateOf(out[1])).toEqual({- sessionUpdate: "agent_thought_chunk",- content: { type: "text", text: "hmm" },- });- expect(updateOf(out[2]).sessionUpdate).toBe("agent_message_chunk");- });-- it("maps a tool call + its result onto the same toolCallId", () => {- const out = conversationToAcpMessages([- { role: "user", content: "run it", timestamp: 1 },- {- role: "assistant",- content: [- {- type: "toolCall",- id: "call_1",- name: "@posthog/query",- arguments: { sql: "select 1" },- },- ],- timestamp: 2,- },- {- role: "toolResult",- toolCallId: "call_1",- toolName: "@posthog/query",- content: [{ type: "text", text: "42" }],- isError: false,- timestamp: 3,- },- ]);-- const call = updateOf(out[1]);- expect(call).toMatchObject({- sessionUpdate: "tool_call",- toolCallId: "call_1",- title: "@posthog/query",- rawInput: { sql: "select 1" },- });- // No premature status on the call itself.- expect("status" in call).toBe(false);-- const result = updateOf(out[2]);- expect(result).toMatchObject({- sessionUpdate: "tool_call_update",- toolCallId: "call_1",- status: "completed",- content: [{ type: "content", content: { type: "text", text: "42" } }],- });- });-- it("marks an errored tool result as failed", () => {- const out = conversationToAcpMessages([- { role: "user", content: "x", timestamp: 1 },- {- role: "assistant",- content: [{ type: "toolCall", id: "c1", name: "t", arguments: {} }],- timestamp: 2,- },- {- role: "toolResult",- toolCallId: "c1",- toolName: "t",- content: [{ type: "text", text: "boom" }],- isError: true,- timestamp: 3,- },- ]);- expect(updateOf(out[2])).toMatchObject({ status: "failed" });- });-- it("closes the prior turn before each new user prompt and gives unique ids", () => {- const out = conversationToAcpMessages([- { role: "user", content: "first", timestamp: 1 },- {- role: "assistant",- content: [{ type: "text", text: "a" }],- timestamp: 2,- },- { role: "user", content: "second", timestamp: 3 },- {- role: "assistant",- content: [{ type: "text", text: "b" }],- timestamp: 4,- },- ]);-- expect(out.map(methodOf)).toEqual([- "session/prompt",- "session/update",- "_posthog/turn_complete",- "session/prompt",- "session/update",- "_posthog/turn_complete",- ]);- expect((out[0].message as JsonRpcRequest).id).toBe(1);- expect((out[3].message as JsonRpcRequest).id).toBe(2);- });-- it("returns nothing for an empty conversation", () => {- expect(conversationToAcpMessages([])).toEqual([]);- });-- it("flattens array-form user content", () => {- expect(- userMessageText([- { type: "text", text: "a" },- { type: "image", url: "x" },- { type: "text", text: "b" },- ]),- ).toBe("ab");- expect(userMessageText("plain")).toBe("plain");- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/conversationToAcp.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/conversationToAcp.tsdeleted file mode 100644index 782316affbe7..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/conversationToAcp.ts+++ /dev/null@@ -1,119 +0,0 @@-/**- * Maps a stored agent_platform conversation transcript (the pi-ai- * `conversation` array returned by the session-detail endpoint) into the- * `AcpMessage[]` that code's `ConversationView` renders.- *- * Pure and order-preserving. Tool results arrive as their own `toolResult`- * messages after the assistant turn that issued the call; we emit them as- * `tool_call_update`s keyed by `toolCallId`, and the builder attaches them to- * the matching call. Each `user` message opens a new turn, so we close the- * previous one with a `_posthog/turn_complete` first (and once more at the- * end) to bracket turns for duration/finalization.- */--import type { AcpMessage } from "@posthog/shared";-import type {- AgentAssistantContentPart,- AgentConversationMessage,- AgentUserContentPart,-} from "@posthog/shared/agent-platform-types";-import {- agentTextUpdate,- agentThoughtUpdate,- promptRequestMessage,- sessionUpdateMessage,- toolCallStartUpdate,- toolResultUpdate,- turnCompleteMessage,-} from "./acpEnvelope";--/** Flatten a user message's content (string shorthand or text/image parts). */-export function userMessageText(- content: string | AgentUserContentPart[],-): string {- if (typeof content === "string") {- return content;- }- return content- .map((part) => (part.type === "text" ? part.text : ""))- .join("");-}--/** Concatenate the text parts of a tool result's content. */-function toolResultText(content: { type: "text"; text: string }[]): string {- return content.map((part) => part.text).join("");-}--function assistantPartToMessage(- part: AgentAssistantContentPart,- ts: number,-): AcpMessage | null {- switch (part.type) {- case "text":- return sessionUpdateMessage(agentTextUpdate(part.text), ts);- case "thinking":- return sessionUpdateMessage(agentThoughtUpdate(part.thinking), ts);- case "toolCall":- return sessionUpdateMessage(- toolCallStartUpdate(part.id, part.name, part.arguments),- ts,- );- default:- return null;- }-}--export function conversationToAcpMessages(- messages: AgentConversationMessage[],-): AcpMessage[] {- const out: AcpMessage[] = [];- let promptId = 0;- let turnOpen = false;- let lastTs = 0;-- for (const message of messages) {- const ts = message.timestamp;- lastTs = ts;-- if (message.role === "user") {- // A new user prompt starts a new turn — close the prior one first.- if (turnOpen) {- out.push(turnCompleteMessage(ts));- turnOpen = false;- }- promptId += 1;- out.push(- promptRequestMessage(promptId, userMessageText(message.content), ts),- );- turnOpen = true;- continue;- }-- if (message.role === "assistant") {- for (const part of message.content) {- const acp = assistantPartToMessage(part, ts);- if (acp) {- out.push(acp);- }- }- continue;- }-- // toolResult — finalize the matching tool call within the open turn.- out.push(- sessionUpdateMessage(- toolResultUpdate(- message.toolCallId,- toolResultText(message.content),- message.isError,- ),- ts,- ),- );- }-- if (turnOpen) {- out.push(turnCompleteMessage(lastTs));- }- return out;-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/sessionEventToAcp.test.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/sessionEventToAcp.test.tsdeleted file mode 100644index 3b049fee24de..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/sessionEventToAcp.test.ts+++ /dev/null@@ -1,233 +0,0 @@-import type {- SessionNotification,- SessionUpdate,-} from "@agentclientprotocol/sdk";-import type {- AcpMessage,- JsonRpcNotification,- JsonRpcRequest,-} from "@posthog/shared";-import type { AgentSessionEvent } from "@posthog/shared/agent-platform-types";-import { describe, expect, it } from "vitest";-import {- createAgentChatMapper,- sessionEventsToAcpMessages,-} from "./sessionEventToAcp";--const TS = "2024-01-01T00:00:00.000Z";--function ev<K extends AgentSessionEvent["kind"]>(- kind: K,- data: Extract<AgentSessionEvent, { kind: K }>["data"],-): AgentSessionEvent {- return { session_id: "s1", ts: TS, kind, data } as AgentSessionEvent;-}--function methodOf(m: AcpMessage): string | undefined {- return "method" in m.message ? m.message.method : undefined;-}--function updateOf(m: AcpMessage): SessionUpdate {- const params = (m.message as JsonRpcNotification)- .params as SessionNotification;- return params.update;-}--describe("createAgentChatMapper", () => {- it("maps user messages to prompt requests with monotonic ids", () => {- const mapper = createAgentChatMapper();- const first = mapper.apply(ev("user_message", { text: "hi" }));- const second = mapper.apply(ev("user_message", { text: "again" }));-- expect(methodOf(first[0])).toBe("session/prompt");- expect((first[0].message as JsonRpcRequest).id).toBe(1);- expect((second[0].message as JsonRpcRequest).id).toBe(2);- });-- it("drops empty user messages", () => {- const mapper = createAgentChatMapper();- expect(mapper.apply(ev("user_message", { text: "" }))).toEqual([]);- });-- it.each([- ["exact match", "hello", "hello"],- ["trailing newline", "hello", "hello\n"],- ["leading spaces", "hello", " hello"],- ])(- "swallows the echo of an optimistically-seeded message (%s)",- (_, seeded, echoed) => {- const mapper = createAgentChatMapper();- mapper.seedUserMessage(seeded);- expect(mapper.apply(ev("user_message", { text: echoed }))).toEqual([]);- },- );-- it("swallows echoes out of order across rapid sends", () => {- const mapper = createAgentChatMapper();- mapper.seedUserMessage("first");- mapper.seedUserMessage("second");- // Echoes arrive in reverse — both must dedup, neither should render.- expect(mapper.apply(ev("user_message", { text: "second" }))).toEqual([]);- expect(mapper.apply(ev("user_message", { text: "first" }))).toEqual([]);- });-- it("drops a duplicate user_message the runner re-emits", () => {- const mapper = createAgentChatMapper();- mapper.seedUserMessage("hello");- expect(mapper.apply(ev("user_message", { text: "hello" }))).toEqual([]);- // The runner re-emits the same user_message later in the stream — there's- // nothing left in `pendingOptimistic`, but we've already rendered this- // text, so it must still be dropped.- expect(mapper.apply(ev("user_message", { text: "hello" }))).toEqual([]);- });-- it("maps text and thinking deltas", () => {- const mapper = createAgentChatMapper();- expect(- updateOf(mapper.apply(ev("assistant_text_delta", { text: "a" }))[0]),- ).toEqual({- sessionUpdate: "agent_message_chunk",- content: { type: "text", text: "a" },- });- expect(- updateOf(- mapper.apply(ev("assistant_thinking_delta", { thinking: "t" }))[0],- ),- ).toEqual({- sessionUpdate: "agent_thought_chunk",- content: { type: "text", text: "t" },- });- });-- it("emits tool_call on first sighting, tool_call_update on follow-up", () => {- const mapper = createAgentChatMapper();- const start = mapper.apply(- ev("tool_call_start", { id: "c1", name: "@posthog/query" }),- );- expect(updateOf(start[0])).toMatchObject({- sessionUpdate: "tool_call",- toolCallId: "c1",- title: "@posthog/query",- status: "in_progress",- });-- // Canonical tool_call for an already-seen id → update (merges args).- const canonical = mapper.apply(- ev("tool_call", { id: "c1", name: "@posthog/query", args: { sql: "x" } }),- );- expect(updateOf(canonical[0])).toMatchObject({- sessionUpdate: "tool_call_update",- toolCallId: "c1",- rawInput: { sql: "x" },- });- });-- it("emits tool_call when the canonical event is the first sighting", () => {- const mapper = createAgentChatMapper();- const out = mapper.apply(- ev("tool_call", { id: "c2", name: "t", args: { a: 1 } }),- );- expect(updateOf(out[0])).toMatchObject({- sessionUpdate: "tool_call",- toolCallId: "c2",- rawInput: { a: 1 },- });- });-- it("maps a successful tool_result to a completed update", () => {- const mapper = createAgentChatMapper();- mapper.apply(ev("tool_call_start", { id: "c1", name: "t" }));- const out = mapper.apply(- ev("tool_result", { id: "c1", ok: true, output: { rows: 1 } }),- );- expect(updateOf(out[0])).toMatchObject({- sessionUpdate: "tool_call_update",- toolCallId: "c1",- status: "completed",- });- });-- it("maps an errored tool_result to a failed update with the error text", () => {- const mapper = createAgentChatMapper();- mapper.apply(ev("tool_call_start", { id: "c1", name: "t" }));- const out = mapper.apply(- ev("tool_result", { id: "c1", ok: false, error: "boom" }),- );- const update = updateOf(out[0]);- expect(update).toMatchObject({ status: "failed" });- expect(JSON.stringify(update)).toContain("boom");- });-- it("synthesizes a call for a tool_result with no prior start", () => {- const mapper = createAgentChatMapper();- const out = mapper.apply(- ev("tool_result", {- id: "orphan",- tool: "mystery",- ok: true,- output: "ok",- }),- );- expect(out).toHaveLength(2);- expect(updateOf(out[0])).toMatchObject({- sessionUpdate: "tool_call",- toolCallId: "orphan",- });- expect(updateOf(out[1])).toMatchObject({- sessionUpdate: "tool_call_update",- status: "completed",- });- });-- it("drops streaming arg deltas, snapshots, and lifecycle frames", () => {- const mapper = createAgentChatMapper();- expect(mapper.apply(ev("session_started", {}))).toEqual([]);- expect(mapper.apply(ev("turn_started", { turn: 1 }))).toEqual([]);- expect(- mapper.apply(ev("tool_call_args_delta", { id: "c1", argsDelta: '{"a' })),- ).toEqual([]);- expect(mapper.apply(ev("assistant_text", { text: "full" }))).toEqual([]);- expect(mapper.apply(ev("closed", {}))).toEqual([]);- });-- it("maps completed/waiting/failed to turn_complete", () => {- const mapper = createAgentChatMapper();- expect(methodOf(mapper.apply(ev("completed", {}))[0])).toBe(- "_posthog/turn_complete",- );- expect(methodOf(mapper.apply(ev("waiting", {}))[0])).toBe(- "_posthog/turn_complete",- );- const failed = mapper.apply(ev("failed", { reason: "x" }));- expect((failed[0].message as JsonRpcNotification).params).toEqual({- stopReason: "failed",- });- });-- it("folds a full streaming turn end-to-end", () => {- const out = sessionEventsToAcpMessages([- ev("session_started", {}),- ev("user_message", { text: "hello" }),- ev("turn_started", { turn: 1 }),- ev("assistant_thinking_delta", { thinking: "let me" }),- ev("assistant_text_delta", { text: "Hi " }),- ev("assistant_text_delta", { text: "there" }),- ev("tool_call_start", { id: "c1", name: "@posthog/query" }),- ev("tool_call", { id: "c1", name: "@posthog/query", args: { sql: "1" } }),- ev("tool_result", { id: "c1", ok: true, output: "done" }),- ev("assistant_text", { text: "Hi there" }),- ev("completed", {}),- ]);-- expect(out.map(methodOf)).toEqual([- "session/prompt",- "session/update", // thinking- "session/update", // text "Hi "- "session/update", // text "there"- "session/update", // tool_call- "session/update", // tool_call_update (args)- "session/update", // tool_call_update (result)- "_posthog/turn_complete",- ]);- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/chat/sessionEventToAcp.ts b/products/desktop/packages/ui/src/features/agent-applications/chat/sessionEventToAcp.tsdeleted file mode 100644index 2a0f9381539e..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/chat/sessionEventToAcp.ts+++ /dev/null@@ -1,228 +0,0 @@-/**- * Maps the live agent-ingress SSE stream (`AgentSessionEvent`) into the- * `AcpMessage[]` code's `ConversationView` renders, incrementally.- *- * Stateful by necessity: user messages need monotonic JSON-RPC request ids,- * and tool-call lifecycle events arrive by id and must be distinguished- * between "first sighting" (emit a `tool_call`) and "follow-up" (emit a- * `tool_call_update` the builder merges). A fresh mapper is created per- * session/stream.- *- * As with the stored-transcript mapper, code's `buildConversationItems` does- * all the accumulation — this only translates the wire shape. Streaming- * tool-call arg deltas (`tool_call_args_delta`) are intentionally dropped:- * the canonical `tool_call` event carries the full args a beat later, and- * rendering half-streamed JSON as `rawInput` reads worse than a brief gap.- */--import type { AgentChatMapper } from "@posthog/core/agent-chat/identifiers";-import type { AcpMessage } from "@posthog/shared";-import type { AgentSessionEvent } from "@posthog/shared/agent-platform-types";-import {- agentTextUpdate,- agentThoughtUpdate,- promptRequestMessage,- sessionUpdateMessage,- toolCallArgsUpdate,- toolCallStartUpdate,- toolResultUpdate,- turnCompleteMessage,-} from "./acpEnvelope";-import { stripConsoleContext } from "./consoleContext";--function toEpochMs(iso: string): number {- const ms = Date.parse(iso);- return Number.isNaN(ms) ? 0 : ms;-}--/** Render a tool result's `output`/`error` payload as display text. */-function outputText(value: unknown): string {- if (value == null) {- return "";- }- if (typeof value === "string") {- return value;- }- try {- return JSON.stringify(value, null, 2);- } catch {- return String(value);- }-}--export type { AgentChatMapper };--export function createAgentChatMapper(): AgentChatMapper {- let promptId = 0;- const seenToolCalls = new Set<string>();- // Texts shown optimistically and awaiting their echoed `user_message` frame.- // Compared by trimmed form so runner-side whitespace normalization- // (trailing `\n`, padding around envelopes, etc.) doesn't break dedup.- const pendingOptimistic: string[] = [];- // Every user text we've rendered this session, normalized. Catches the runner- // re-emitting the same `user_message` event twice (the second arrival has- // nothing left in `pendingOptimistic` to swallow it).- const seenUserTexts = new Set<string>();-- return {- seedUserMessage(text: string, ts?: number): AcpMessage[] {- if (!text) {- return [];- }- promptId += 1;- pendingOptimistic.push(text);- seenUserTexts.add(text.trim());- return [promptRequestMessage(promptId, text, ts ?? Date.now())];- },-- setPromptIdBase(count: number): void {- promptId = Math.max(promptId, count);- },-- apply(event: AgentSessionEvent): AcpMessage[] {- const ts = toEpochMs(event.ts);-- switch (event.kind) {- case "user_message": {- if (!event.data.text) {- return [];- }- // The first message may carry a agent builder context envelope — strip it- // so it never shows in the transcript (and so dedup matches the clean- // optimistic text the composer rendered).- const text = stripConsoleContext(event.data.text);- const normalized = text.trim();- // Echo of a message we already rendered optimistically. Scan the- // queue (not just `[0]`) so out-of-order echoes from rapid sends- // still match, and compare trimmed forms so trailing/leading- // whitespace from the runner doesn't break the match.- const pendingIdx = pendingOptimistic.findIndex(- (p) => p.trim() === normalized,- );- if (pendingIdx !== -1) {- pendingOptimistic.splice(pendingIdx, 1);- return [];- }- // The runner re-emitted a `user_message` we've already rendered- // (either as optimistic seed or as a non-dedup'd echo). Drop it so- // the bubble doesn't appear twice.- if (seenUserTexts.has(normalized)) {- return [];- }- seenUserTexts.add(normalized);- promptId += 1;- return [promptRequestMessage(promptId, text, ts)];- }-- case "assistant_text_delta":- return event.data.text- ? [sessionUpdateMessage(agentTextUpdate(event.data.text), ts)]- : [];-- case "assistant_thinking_delta":- return event.data.thinking- ? [- sessionUpdateMessage(- agentThoughtUpdate(event.data.thinking),- ts,- ),- ]- : [];-- case "tool_call_start": {- const { id, name } = event.data;- if (seenToolCalls.has(id)) {- return [];- }- seenToolCalls.add(id);- return [- sessionUpdateMessage(- toolCallStartUpdate(id, name, undefined, "in_progress"),- ts,- ),- ];- }-- case "tool_call": {- const { id, name, args } = event.data;- if (seenToolCalls.has(id)) {- return [- sessionUpdateMessage(- toolCallArgsUpdate(id, name, args ?? {}),- ts,- ),- ];- }- seenToolCalls.add(id);- return [- sessionUpdateMessage(- toolCallStartUpdate(id, name, args ?? {}, "in_progress"),- ts,- ),- ];- }-- case "tool_result": {- const { id, ok, output, error, tool } = event.data;- const isError = ok === false;- const text = isError ? (error ?? "tool failed") : outputText(output);- const messages: AcpMessage[] = [];- // Defensive: a result for a call we never saw start — synthesize the- // call so the builder has something to attach the result to.- if (!seenToolCalls.has(id)) {- seenToolCalls.add(id);- messages.push(- sessionUpdateMessage(toolCallStartUpdate(id, tool ?? "tool"), ts),- );- }- messages.push(- sessionUpdateMessage(- toolResultUpdate(id, text, isError, output),- ts,- ),- );- return messages;- }-- case "client_tool_result": {- const { call_id, result, error } = event.data;- const isError = typeof error === "string";- const text = isError- ? (error ?? "client tool failed")- : outputText(result);- return [- sessionUpdateMessage(- toolResultUpdate(call_id, text, isError, result),- ts,- ),- ];- }-- case "completed":- return [turnCompleteMessage(ts)];-- case "waiting":- return [turnCompleteMessage(ts)];-- case "failed":- return [turnCompleteMessage(ts, "failed")];-- // Frames that carry no renderable transcript content. `turn_started`- // is implicit in the prompt request; `assistant_text` is a turn-end- // snapshot the deltas already produced; `tool_call_args_delta` is- // dropped (see file header); `client_tool_call` is handled by the- // host transport (M4); the rest are lifecycle bookkeeping.- default:- return [];- }- },- };-}--/** Fold a full event buffer through a fresh mapper — handy for replay/tests. */-export function sessionEventsToAcpMessages(- events: AgentSessionEvent[],-): AcpMessage[] {- const mapper = createAgentChatMapper();- return events.flatMap((event) => mapper.apply(event));-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentAnalyticsView.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentAnalyticsView.tsxdeleted file mode 100644index 637af9502715..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentAnalyticsView.tsx+++ /dev/null@@ -1,375 +0,0 @@-import {- ArrowSquareOutIcon,- ChartLineIcon,- WarningIcon,-} from "@phosphor-icons/react";-import {- BarChart,- MetricCard,- type Series,- useChartTheme,-} from "@posthog/quill-charts";-import type {- AgentAnalyticsData,- AgentAnalyticsModelRow,- AgentAnalyticsToolRow,-} from "@posthog/shared/agent-platform-types";-import { openExternalUrl } from "@posthog/ui/shell/openExternal";-import { Flex, Text } from "@radix-ui/themes";-import type { ReactNode } from "react";--const usd = (v: number): string =>- v >= 100 ? `$${v.toFixed(0)}` : `$${v.toFixed(2)}`;-const pct = (v: number): string => `${(v * 100).toFixed(1)}%`;-const secs = (v: number): string => `${v.toFixed(v < 10 ? 1 : 0)}s`;-const int = (v: number): string => v.toLocaleString();--// Delta-pill label: magnitude only — MetricCard's arrow + colour carry the-// direction (sign of the change) and good/bad (`goodDirection`).-const pctDelta = (p: number): string => `${Math.abs(Math.round(p))}%`;-const ppDelta = (p: number): string => `${Math.abs(p).toFixed(1)}pp`;--// Compact uppercase tile label, matching the surrounding panes (MetricCard's-// own title styling is larger than this strip wants).-const tileTitle = (label: string): ReactNode => (- <span className="text-[11px] text-gray-10 uppercase tracking-wide">- {label}- </span>-);--/**- * The agent observability dashboard: top-line KPIs with 14-day spark trends +- * WoW deltas plus charts. Pure presentation — `useAgentAnalytics` runs the- * HogQL and shapes the data; this renders one of loading / error / empty /- * populated.- *- * `scope` "overview" is the fleet board blended into the Fleet landing- * (KPIs + spend-by-agent + cost-by-model; the agent list below carries the- * per-agent breakdown). "agent" is the per-agent Observability tab (KPIs +- * cost-by-model + tool reliability — spend-by-agent is meaningless for one).- */-export function AgentAnalyticsView({- data,- title = "Observability",- subtitle = "Last 7 days · 14-day trend",- aiObservabilityUrl,- isLoading,- isError,- errorMessage,-}: {- data: AgentAnalyticsData | undefined;- title?: string;- subtitle?: string;- /** Deep link into the team's AI observability product for trace-level depth. */- aiObservabilityUrl?: string | null;- isLoading?: boolean;- isError?: boolean;- errorMessage?: string | null;-}) {- return (- <Flex direction="column" gap="5">- <Flex align="end" justify={title ? "between" : "end"} gap="3">- {title ? (- <Flex direction="column" gap="0.5">- <Text className="font-semibold text-[15px] text-gray-12 leading-tight">- {title}- </Text>- <Text className="text-[12px] text-gray-10">{subtitle}</Text>- </Flex>- ) : null}- {aiObservabilityUrl ? (- <button- type="button"- onClick={() => openExternalUrl(aiObservabilityUrl)}- className="inline-flex shrink-0 items-center gap-1 text-[12px] text-gray-11 no-underline hover:text-gray-12"- >- Open in AI observability- <ArrowSquareOutIcon size={12} />- </button>- ) : null}- </Flex>-- {isLoading && !data ? (- <LoadingSkeleton />- ) : isError ? (- <ErrorState message={errorMessage} />- ) : !data || data.empty ? (- <EmptyState />- ) : (- <>- <AgentAnalyticsKpiStrip data={data} />- <Panel title="Cost by model">- <CostByModelChart rows={data.byModel} />- </Panel>- <Panel title="Tool reliability">- <ToolTable rows={data.toolErrors} />- </Panel>- </>- )}- </Flex>- );-}--/**- * The four top-line KPI tiles (spend / sessions / failure rate / p95) with- * 14-day spark trends + WoW deltas. Reused standalone on the per-agent Overview- * tab, where it owns its own loading / empty rendering.- */-export function AgentAnalyticsKpiStrip({- data,- isLoading,-}: {- data: AgentAnalyticsData | undefined;- isLoading?: boolean;-}) {- const theme = useChartTheme();- if (isLoading && !data) {- return (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- {[0, 1, 2, 3].map((i) => (- <Skel key={i} className="h-28" />- ))}- </div>- );- }- if (!data || data.empty) {- return <EmptyHint text="No AI activity in the last 7 days." />;- }- const { kpis, deltas, daily } = data;- // Cost can come back negative from upstream LLM-observability cost calc (a- // negative `$ai_total_cost_usd` on some generations). A negative aggregate- // spend is never meaningful to show, so clamp the headline + sparkline to 0.- const spendSeries = daily.spend.map((v) => Math.max(0, v));- return (- <Flex className="overflow-hidden rounded-(--radius-2) border border-border bg-(--color-panel-solid)">- <KpiCell>- <MetricCard- title={tileTitle("Spend · 7d")}- value={Math.max(0, kpis.spendUsd)}- data={spendSeries}- labels={daily.labels}- theme={theme}- formatValue={(v) => usd(Math.max(0, v))}- change={deltas.spend != null ? { value: deltas.spend } : null}- formatChange={pctDelta}- goodDirection="down"- sparklineHeight={28}- />- </KpiCell>- <KpiCell>- <MetricCard- title={tileTitle("Sessions · 7d")}- value={kpis.sessions}- data={daily.sessions}- labels={daily.labels}- theme={theme}- formatValue={int}- change={deltas.sessions != null ? { value: deltas.sessions } : null}- formatChange={pctDelta}- goodDirection="up"- sparklineHeight={28}- />- </KpiCell>- <KpiCell>- <MetricCard- title={tileTitle("Failure rate · 7d")}- value={kpis.failureRate}- data={daily.failureRate}- labels={daily.labels}- theme={theme}- formatValue={pct}- change={- deltas.failureRatePoints != null- ? { value: deltas.failureRatePoints }- : null- }- formatChange={ppDelta}- goodDirection="down"- sparklineHeight={28}- />- </KpiCell>- <KpiCell last>- <MetricCard- title={tileTitle("p95 latency · 7d")}- value={kpis.p95LatencyS}- theme={theme}- formatValue={secs}- change={null}- sparklineHeight={28}- />- </KpiCell>- </Flex>- );-}--/** One cell of the connected KPI strip: equal width with a divider between. */-function KpiCell({ children, last }: { children: ReactNode; last?: boolean }) {- return (- <div- className={`min-w-0 flex-1 px-4 py-3 ${last ? "" : "border-(--gray-5) border-r"}`}- >- {children}- </div>- );-}--function CostByModelChart({ rows }: { rows: AgentAnalyticsModelRow[] }) {- const theme = useChartTheme();- if (rows.length === 0) {- return <EmptyHint text="No model usage recorded yet." />;- }- const series: Series[] = [- { key: "cost", label: "Cost (USD)", data: rows.map((r) => r.spendUsd) },- ];- return (- // flex-col + fixed height: the quill BarChart sizes its canvas by filling a- // flex-column parent (its root is `flex-1`); a plain block collapses the- // canvas to height 0 and the chart renders blank.- <div className="flex h-56 w-full flex-col">- <BarChart- series={series}- labels={rows.map((r) => r.model)}- config={{- axisOrientation: "horizontal",- showGrid: false,- bars: { fitToHeight: true },- }}- theme={theme}- />- </div>- );-}--function ToolTable({ rows }: { rows: AgentAnalyticsToolRow[] }) {- if (rows.length === 0) {- return <EmptyHint text="No tool calls recorded yet." />;- }- return (- <table className="w-full text-[12px]">- <thead>- <tr className="border-(--gray-5) border-b text-left text-gray-10">- <Th className="text-left">Tool</Th>- <Th>Calls</Th>- <Th>Errors</Th>- <Th>Error rate</Th>- </tr>- </thead>- <tbody>- {rows.map((r) => (- <tr key={r.tool} className="border-(--gray-4) border-b last:border-0">- <td className="py-1.5 pr-2 font-mono text-gray-12">{r.tool}</td>- <Td>{int(r.calls)}</Td>- <Td>{int(r.errors)}</Td>- <Td>- <span- className={r.errorRate > 0 ? "text-(--red-11)" : "text-gray-12"}- >- {pct(r.errorRate)}- </span>- </Td>- </tr>- ))}- </tbody>- </table>- );-}--function Panel({ title, children }: { title: string; children: ReactNode }) {- return (- <div className="overflow-hidden rounded-(--radius-2) border border-border bg-(--color-panel-solid)">- <div className="border-(--gray-5) border-b px-3 py-2">- <Text className="font-medium text-[11px] text-gray-10 uppercase tracking-wide">- {title}- </Text>- </div>- <div className="px-3 py-3">{children}</div>- </div>- );-}--function Th({- children,- className,-}: {- children: ReactNode;- className?: string;-}) {- return (- <th className={`py-1.5 pr-2 font-medium ${className ?? "text-right"}`}>- {children}- </th>- );-}--function Td({ children }: { children: ReactNode }) {- return (- <td className="py-1.5 pr-2 text-right text-gray-12 tabular-nums">- {children}- </td>- );-}--function EmptyHint({ text }: { text: string }) {- return <Text className="text-[12px] text-gray-10 italic">{text}</Text>;-}--function EmptyState() {- return (- <Flex- direction="column"- align="center"- gap="2"- className="rounded-(--radius-2) border border-(--gray-5) border-dashed py-16 text-center"- >- <ChartLineIcon size={24} className="text-gray-9" />- <Text className="font-medium text-[13px] text-gray-12">- No AI activity yet- </Text>- <Text className="max-w-sm text-[12px] text-gray-11 leading-snug">- Once your agents run, their model calls, tool spans, cost and latency- show up here — and in full detail in AI observability.- </Text>- </Flex>- );-}--function ErrorState({ message }: { message?: string | null }) {- return (- <Flex- direction="column"- align="center"- gap="2"- className="rounded-(--radius-2) border border-(--red-6) border-dashed py-16 text-center"- >- <WarningIcon size={24} className="text-(--red-11)" />- <Text className="font-medium text-[13px] text-gray-12">- Couldn't load analytics- </Text>- <Text className="max-w-md text-[12px] text-gray-11 leading-snug">- {message ?? "The query endpoint returned an error."}- </Text>- </Flex>- );-}--function LoadingSkeleton() {- return (- <Flex direction="column" gap="5">- <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">- {[0, 1, 2, 3].map((i) => (- <Skel key={i} className="h-20" />- ))}- </div>- <Skel className="h-64" />- <Skel className="h-32" />- </Flex>- );-}--function Skel({ className }: { className?: string }) {- return (- <div- className={`animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2) ${className ?? ""}`}- />- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApplicationDetailView.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentApplicationDetailView.tsxdeleted file mode 100644index ea96141cbc06..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApplicationDetailView.tsx+++ /dev/null@@ -1,88 +0,0 @@-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useAgentAnalytics } from "../hooks/useAgentAnalytics";-import { useAgentApplication } from "../hooks/useAgentApplication";-import { useAgentApplicationSessions } from "../hooks/useAgentApplicationSessions";-import { AgentAnalyticsKpiStrip } from "./AgentAnalyticsView";-import { AgentDetailEmptyState, AgentDetailLayout } from "./AgentDetailLayout";-import { AgentSessionRow } from "./AgentSessionRow";--/**- * Per-agent Overview pane: the top-level observability KPIs (spend / sessions /- * failure rate / p95 over the last 7 days, with trends + WoW deltas — the same- * metrics as the Observability tab) plus recent sessions. Rendered inside the- * shared {@link AgentDetailLayout} tab shell.- */-export function AgentApplicationDetailView({ idOrSlug }: { idOrSlug: string }) {- const { data: application } = useAgentApplication(idOrSlug);- const { data: analytics, isLoading: analyticsLoading } = useAgentAnalytics(- application?.id,- "agent",- );- const {- data: sessions,- isLoading: sessionsLoading,- isError: sessionsError,- } = useAgentApplicationSessions(idOrSlug, { limit: 25 });-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="overview">- <Flex direction="column" gap="6">- <section>- <Flex align="center" justify="between" className="mb-3">- <Text className="font-semibold text-[13px] text-gray-12">- Activity · last 7 days- </Text>- <Link- to="/code/agents/applications/$idOrSlug/observability"- params={{ idOrSlug }}- className="text-[12px] text-gray-11 no-underline hover:text-gray-12"- >- View observability →- </Link>- </Flex>- <AgentAnalyticsKpiStrip- data={analytics}- isLoading={analyticsLoading || !application}- />- </section>-- <section>- <Text className="mb-3 block font-semibold text-[13px] text-gray-12">- Recent sessions- </Text>- {sessionsLoading ? (- <Flex direction="column" gap="2">- {[0, 1, 2].map((i) => (- <div- key={i}- className="h-[52px] animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- ) : sessionsError ? (- <AgentDetailEmptyState- title="Couldn't load recent sessions"- description="The agent platform API returned an error."- />- ) : !sessions || sessions.results.length === 0 ? (- <AgentDetailEmptyState- title="No sessions yet"- description="Sessions this agent runs will appear here."- />- ) : (- <Flex direction="column" gap="2">- {sessions.results.map((session) => (- <AgentSessionRow- key={session.id}- session={session}- idOrSlug={idOrSlug}- />- ))}- </Flex>- )}- </section>- </Flex>- </AgentDetailLayout>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApplicationsListView.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentApplicationsListView.tsxdeleted file mode 100644index f1a01ff94bd9..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApplicationsListView.tsx+++ /dev/null@@ -1,392 +0,0 @@-import {- ArrowSquareOutIcon,- CaretRightIcon,- LockKeyIcon,- MagnifyingGlassIcon,- RobotIcon,-} from "@phosphor-icons/react";-import type {- AgentAnalyticsAgentRow,- AgentApplication,-} from "@posthog/shared/agent-platform-types";-import { AgentsTabLayout } from "@posthog/ui/features/agents/components/AgentsTabLayout";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Button } from "@posthog/ui/primitives/Button";-import { openExternalUrl } from "@posthog/ui/shell/openExternal";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useMemo, useState } from "react";-import { useAuthStateValue } from "../../auth/store";-import { useAgentAnalytics } from "../hooks/useAgentAnalytics";-import { useAgentApplications } from "../hooks/useAgentApplications";-import { useAgentFleetApprovals } from "../hooks/useAgentFleetApprovals";-import { formatSpendUsd } from "../utils/format";-import { aiObservabilityTracesUrl } from "../utils/observabilityLinks";-import { AgentAnalyticsKpiStrip } from "./AgentAnalyticsView";-import { AgentDetailEmptyState } from "./AgentDetailLayout";-import { AgentFleetLiveSessionsPanel } from "./AgentFleetLiveSessionsPanel";--type StatusFilter = "all" | "live" | "drafts";--/** Agents per page in the fleet list. */-const PAGE_SIZE = 8;--/**- * The Fleet tab. Renders the deployed-agent fleet as the primary- * surface: a searchable, status-filtered, paged list with the 7-day activity- * strip pinned at the top and operational / live-now panels below.- */-export function AgentApplicationsListView() {- const region = useAuthStateValue((s) => s.cloudRegion);- const projectId = useAuthStateValue((s) => s.currentProjectId);-- const {- data: applications,- isLoading,- isError,- error,- } = useAgentApplications();- const { data: analytics, isLoading: analyticsLoading } = useAgentAnalytics();- const { data: queuedApprovals } = useAgentFleetApprovals({ state: "queued" });- const aiObservabilityUrl = aiObservabilityTracesUrl(region, projectId);- const pendingCount = queuedApprovals?.length ?? 0;- const hasAnalytics = analytics ? !analytics.empty : false;-- // Index the per-agent rollups by application id so each row can show its own- // sessions / spend / failure rate without a second request.- const statsById = useMemo(() => {- const map = new Map<string, AgentAnalyticsAgentRow>();- for (const row of analytics?.byAgent ?? []) {- map.set(row.id, row);- }- return map;- }, [analytics]);-- // Live agents sort ahead of drafts so the operational view foregrounds what's- // serving traffic. Search + status filter + paging keep a large fleet- // navigable.- const [query, setQuery] = useState("");- const [status, setStatus] = useState<StatusFilter>("all");- const [page, setPage] = useState(0);-- const allApps = useMemo(() => applications ?? [], [applications]);- const liveCount = useMemo(- () => allApps.filter((a) => a.live_revision != null).length,- [allApps],- );- const draftCount = allApps.length - liveCount;-- const filtered = useMemo(() => {- const q = query.trim().toLowerCase();- return allApps- .filter((app) => {- if (status === "live" && app.live_revision == null) return false;- if (status === "drafts" && app.live_revision != null) return false;- if (!q) return true;- return (- app.name.toLowerCase().includes(q) ||- (app.slug?.toLowerCase().includes(q) ?? false) ||- (app.description?.toLowerCase().includes(q) ?? false)- );- })- .sort(- (a, b) =>- Number(b.live_revision != null) - Number(a.live_revision != null),- );- }, [allApps, status, query]);-- const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));- const safePage = Math.min(page, pageCount - 1);- const pageItems = filtered.slice(- safePage * PAGE_SIZE,- safePage * PAGE_SIZE + PAGE_SIZE,- );-- function changeStatus(next: StatusFilter) {- setStatus(next);- setPage(0);- }-- function changeQuery(next: string) {- setQuery(next);- setPage(0);- }-- const statusFilters: { id: StatusFilter; label: string; count: number }[] = [- { id: "all", label: "All", count: allApps.length },- { id: "live", label: "Live", count: liveCount },- { id: "drafts", label: "Drafts", count: draftCount },- ];-- return (- <AgentsTabLayout activeTab="applications">- <Flex direction="column" gap="6">- {hasAnalytics ? (- <section>- <Flex align="center" justify="between" gap="3" className="mb-3">- <Text className="font-semibold text-[13px] text-gray-12">- Activity · last 7 days- </Text>- {aiObservabilityUrl ? (- <button- type="button"- onClick={() => openExternalUrl(aiObservabilityUrl)}- className="inline-flex shrink-0 items-center gap-1 text-[12px] text-gray-11 no-underline hover:text-gray-12"- >- Open in AI observability- <ArrowSquareOutIcon size={12} />- </button>- ) : null}- </Flex>- <AgentAnalyticsKpiStrip- data={analytics}- isLoading={analyticsLoading}- />- </section>- ) : null}-- <section>- {isLoading ? (- <ApplicationsSkeleton />- ) : isError ? (- <AgentDetailEmptyState- title="Couldn't load applications"- description={- error instanceof Error- ? error.message- : "The agent platform API returned an error."- }- />- ) : allApps.length === 0 ? (- <AgentDetailEmptyState- title="No agents yet"- description="Deployed agents on the agent platform will show up here."- />- ) : (- <Flex direction="column" gap="3">- <Flex align="center" justify="between" gap="3" wrap="wrap">- <div className="relative min-w-0 flex-1 sm:max-w-xs">- <MagnifyingGlassIcon- size={13}- className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-2.5 text-gray-10"- />- <input- type="search"- value={query}- onChange={(e) => changeQuery(e.currentTarget.value)}- placeholder="Search agents…"- aria-label="Search agents"- className="h-8 w-full rounded-(--radius-2) border border-border bg-(--color-panel-solid) pr-2 pl-8 text-[12.5px]"- />- </div>- <Flex gap="2" wrap="wrap" className="shrink-0">- {statusFilters.map((f) => (- <button- key={f.id}- type="button"- onClick={() => changeStatus(f.id)}- className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[12px] ${- status === f.id- ? "border-(--accent-7) bg-(--accent-3) text-gray-12"- : "border-border text-gray-11 hover:border-(--gray-7)"- }`}- >- {f.label}- <span className="text-[11px] text-gray-10 tabular-nums">- {f.count}- </span>- </button>- ))}- </Flex>- </Flex>-- {pageItems.length === 0 ? (- <AgentDetailEmptyState- title="No matching agents"- description="No agents match your search and filters."- />- ) : (- <Flex direction="column" gap="2">- {pageItems.map((app) => (- <ApplicationRow- key={app.id}- application={app}- stats={statsById.get(app.id)}- />- ))}- </Flex>- )}-- {filtered.length > 0 ? (- <Flex- align="center"- justify="between"- gap="3"- wrap="wrap"- className="pt-1"- >- <Text className="text-[11px] text-gray-10 tabular-nums">- Showing {safePage * PAGE_SIZE + 1}–- {safePage * PAGE_SIZE + pageItems.length} of{" "}- {filtered.length}- </Text>- {pageCount > 1 ? (- <Flex align="center" gap="2">- <Button- variant="soft"- size="1"- disabled={safePage === 0}- onClick={() => setPage((p) => Math.max(0, p - 1))}- >- Previous- </Button>- <Text className="text-[11px] text-gray-10 tabular-nums">- {safePage + 1} / {pageCount}- </Text>- <Button- variant="soft"- size="1"- disabled={safePage >= pageCount - 1}- onClick={() =>- setPage((p) => Math.min(pageCount - 1, p + 1))- }- >- Next- </Button>- </Flex>- ) : null}- </Flex>- ) : null}- </Flex>- )}- </section>-- <OperationalStrip pendingCount={pendingCount} />-- <AgentFleetLiveSessionsPanel />- </Flex>- </AgentsTabLayout>- );-}--function ApplicationRow({- application,- stats,-}: {- application: AgentApplication;- stats?: AgentAnalyticsAgentRow;-}) {- const isLive = application.live_revision != null;- return (- <Link- to="/code/agents/applications/$idOrSlug"- params={{ idOrSlug: application.slug ?? application.id }}- className="flex items-center justify-between gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 no-underline transition-colors duration-150 hover:border-(--gray-6) hover:bg-(--gray-2)"- >- <Flex align="center" gap="3" className="min-w-0">- <RobotIcon size={20} className="shrink-0 text-gray-11" />- <Flex direction="column" gap="0.5" className="min-w-0">- <Flex align="center" gap="2" className="min-w-0">- <Text className="truncate font-medium text-[13px] text-gray-12">- {application.name}- </Text>- <Badge color={isLive ? "green" : "gray"}>- {isLive ? "Live" : "Draft"}- </Badge>- </Flex>- <Text className="truncate text-[12px] text-gray-11 leading-snug">- {application.description?.trim()- ? application.description- : (application.slug ?? application.id)}- </Text>- </Flex>- </Flex>- <Flex align="center" gap="4" className="shrink-0">- {stats ? <RowStats stats={stats} /> : null}- <CaretRightIcon size={14} className="shrink-0 text-gray-10" />- </Flex>- </Link>- );-}--/** Inline 7-day rollups shown on an agent row, joined from the fleet query. */-function RowStats({ stats }: { stats: AgentAnalyticsAgentRow }) {- return (- <Flex align="center" gap="4" className="hidden sm:flex">- <RowStat label="Sessions" value={stats.sessions.toLocaleString()} />- <RowStat label="Spend" value={formatSpendUsd(stats.spendUsd)} />- <RowStat- label="Fail rate"- value={`${(stats.failureRate * 100).toFixed(1)}%`}- attention={stats.failureRate > 0}- />- </Flex>- );-}--function RowStat({- label,- value,- attention,-}: {- label: string;- value: string;- attention?: boolean;-}) {- return (- <Flex direction="column" align="end" gap="0.5" className="shrink-0">- <Text- className={`font-medium text-[12px] tabular-nums ${- attention ? "text-(--red-11)" : "text-gray-12"- }`}- >- {value}- </Text>- <Text className="text-[10px] text-gray-10 uppercase tracking-wide">- {label}- </Text>- </Flex>- );-}--/**- * Operational counts strip — always renders the pending-approvals count as a- * deep link to the fleet approvals queue, and visually emphasizes the row when- * `pendingCount > 0`.- */-function OperationalStrip({ pendingCount }: { pendingCount: number }) {- const pendingAttention = pendingCount > 0;- return (- <Flex align="center" gap="5" className="text-[12.5px]">- <Link- to="/code/agents/applications/approvals"- className="inline-flex items-center gap-1 text-gray-11 no-underline hover:text-gray-12"- >- <LockKeyIcon- size={13}- className={`mr-1 ${pendingAttention ? "text-(--amber-11)" : "text-gray-10"}`}- />- <Text- className={`font-medium tabular-nums ${pendingAttention ? "text-(--amber-11)" : "text-gray-12"}`}- >- {pendingCount}- </Text>- <Text>pending approval{pendingCount === 1 ? "" : "s"}</Text>- <CaretRightIcon size={11} className="text-gray-10" />- </Link>- </Flex>- );-}--function ApplicationsSkeleton() {- return (- <Flex direction="column" gap="2">- {[0, 1, 2].map((i) => (- <div- key={i}- className="h-[58px] animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalDecisionForm.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalDecisionForm.tsxdeleted file mode 100644index 5e3aff503d92..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalDecisionForm.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { CheckIcon, XIcon } from "@phosphor-icons/react";-import type {- AgentApprovalRequest,- DecideApprovalRequest,-} from "@posthog/shared/agent-platform-types";-import { Button } from "@posthog/ui/primitives/Button";-import { Checkbox, Flex, Text, TextArea } from "@radix-ui/themes";-import { useState } from "react";--/**- * Presentational approve/reject controls for a queued approval — proposed-args- * editor (when allowed), reason note, error surface, and the two action- * buttons. Owns its own UI state but takes the decision callback from the- * caller, so both the full `AgentApprovalDetail` (Approvals tab + Fleet route)- * and the inline `AgentChatPendingApprovalCard` (chat pane) can wrap- * it with their own `useDecideAgentApproval` glue.- */-export function AgentApprovalDecisionForm({- approval,- busy,- error,- onSubmit,-}: {- approval: AgentApprovalRequest;- busy: boolean;- error: string | null;- onSubmit: (body: DecideApprovalRequest) => void;-}) {- const allowEdit = approval.approver_scope?.allow_edit === true;- const [reason, setReason] = useState("");- const [editMode, setEditMode] = useState(false);- const [argsText, setArgsText] = useState(() =>- JSON.stringify(approval.proposed_args, null, 2),- );- const [parseError, setParseError] = useState<string | null>(null);-- function submit(decision: "approve" | "reject") {- const body: DecideApprovalRequest = { decision };- if (reason.trim()) body.reason = reason.trim();- if (decision === "approve" && allowEdit && editMode) {- try {- body.edited_args = JSON.parse(argsText);- } catch (err) {- setParseError(err instanceof Error ? err.message : "Invalid JSON");- return;- }- }- setParseError(null);- onSubmit(body);- }-- return (- <Flex direction="column" gap="3" className="mt-4">- {allowEdit ? (- <Text as="label" className="w-fit text-[12px] text-gray-11">- <Flex gap="2" align="center">- <Checkbox- size="1"- checked={editMode}- onCheckedChange={(c) => setEditMode(c === true)}- />- Approve with edits- </Flex>- </Text>- ) : null}-- {allowEdit && editMode ? (- <div>- <TextArea- value={argsText}- onChange={(e) => setArgsText(e.target.value)}- rows={8}- className="text-[12px] [font-family:var(--font-mono)]"- spellCheck={false}- />- {parseError ? (- <Text className="mt-1 block text-(--red-11) text-[11px]">- {parseError}- </Text>- ) : null}- </div>- ) : null}-- <TextArea- value={reason}- onChange={(e) => setReason(e.target.value)}- placeholder="Reason (optional)"- rows={2}- className="text-[12px]"- />-- {error ? (- <Text className="text-(--red-11) text-[11px]">{error}</Text>- ) : null}-- <Flex gap="2">- <Button- color="green"- size="2"- onClick={() => submit("approve")}- disabled={busy}- loading={busy}- >- <CheckIcon size={14} />- Approve- </Button>- <Button- color="red"- variant="soft"- size="2"- onClick={() => submit("reject")}- disabled={busy}- >- <XIcon size={14} />- Reject- </Button>- </Flex>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalDetail.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalDetail.tsxdeleted file mode 100644index 6b4fccdc4b70..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalDetail.tsx+++ /dev/null@@ -1,247 +0,0 @@-import {- CheckCircleIcon,- LockKeyIcon,- WarningIcon,- XCircleIcon,- XIcon,-} from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type { AgentApprovalRequest } from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";-import { Flex, IconButton, Text } from "@radix-ui/themes";-import { useState } from "react";-import { useDecideAgentApproval } from "../hooks/useDecideAgentApproval";-import { approvalStateColor, approvalStateLabel } from "../utils/format";-import { AgentApprovalDecisionForm } from "./AgentApprovalDecisionForm";-import { AgentSessionDetailBody } from "./AgentSessionDetailBody";--type Pane = "approval" | "session";--/**- * Master-detail panel for a single approval. The **Approval** tab carries the- * proposed args + decision controls; the **Session** tab embeds the agent run- * that proposed the gated call (via {@link AgentSessionDetailBody}) so the- * approver can read the full context that led to it.- */-export function AgentApprovalDetail({- idOrSlug,- approval,- onClose,-}: {- idOrSlug: string;- approval: AgentApprovalRequest;- onClose: () => void;-}) {- const [pane, setPane] = useState<Pane>("approval");- const isQueued = approval.state === "queued";-- return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="3"- className="shrink-0 border-(--gray-5) border-b px-5 pt-4"- >- <Flex align="start" justify="between" gap="3">- <Flex direction="column" gap="1" className="min-w-0">- <Flex align="center" gap="2" className="min-w-0">- <LockKeyIcon size={14} className="shrink-0 text-gray-10" />- <Text className="truncate font-semibold text-[14px] text-gray-12 [font-family:var(--font-mono)]">- {approval.tool_name}- </Text>- <Badge color={approvalStateColor(approval.state)}>- {approvalStateLabel(approval.state)}- </Badge>- </Flex>- <Text className="text-[11px] text-gray-10">- {isQueued- ? `expires ${formatRelativeTimeShort(approval.expires_at)}`- : `created ${formatRelativeTimeShort(approval.created_at)}`}- </Text>- </Flex>- <IconButton- size="1"- variant="ghost"- color="gray"- onClick={onClose}- aria-label="Close approval"- >- <XIcon size={15} />- </IconButton>- </Flex>-- <Flex gap="1" className="-mb-px">- {(["approval", "session"] as const).map((p) => (- <button- key={p}- type="button"- onClick={() => setPane(p)}- className={`border-b-2 px-3 pb-2.5 text-[12.5px] capitalize ${- p === pane- ? "border-(--accent-9) font-medium text-gray-12"- : "border-transparent text-gray-11 hover:text-gray-12"- }`}- >- {p}- </button>- ))}- </Flex>- </Flex>-- {pane === "approval" ? (- <div className="min-h-0 flex-1 overflow-auto px-5 py-4">- <ArgsSection- label="Proposed arguments"- args={approval.proposed_args}- />- {isQueued ? (- <DecisionForm idOrSlug={idOrSlug} approval={approval} />- ) : (- <DecidedOutcome approval={approval} />- )}- </div>- ) : (- <div className="min-h-0 flex-1">- <AgentSessionDetailBody- idOrSlug={idOrSlug}- sessionId={approval.session_id}- />- </div>- )}- </Flex>- );-}--function DecisionForm({- idOrSlug,- approval,-}: {- idOrSlug: string;- approval: AgentApprovalRequest;-}) {- const decide = useDecideAgentApproval(idOrSlug);- return (- <AgentApprovalDecisionForm- approval={approval}- busy={decide.isPending}- error={- decide.isError- ? decide.error instanceof Error- ? decide.error.message- : "Decision failed"- : null- }- onSubmit={(body) => decide.mutate({ approvalId: approval.id, body })}- />- );-}--function DecidedOutcome({ approval }: { approval: AgentApprovalRequest }) {- const dispatchError =- approval.dispatch_outcome &&- typeof approval.dispatch_outcome === "object" &&- "error" in approval.dispatch_outcome- ? String(approval.dispatch_outcome.error)- : null;- const banner = outcomeBanner(approval.state, !!dispatchError);-- return (- <Flex direction="column" gap="3" className="mt-4">- <Flex- align="center"- gap="2"- className={`rounded-(--radius-2) border px-3 py-2 ${banner.classes}`}- >- <banner.Icon size={16} weight="fill" className={banner.iconClass} />- <Flex direction="column" gap="0.5" className="min-w-0">- <Text className="font-medium text-[12.5px] text-gray-12">- {banner.title}- </Text>- {approval.decision_at ? (- <Text className="text-[11px] text-gray-11">- {formatRelativeTimeShort(approval.decision_at)}- {approval.decision_by ? ` by ${approval.decision_by}` : ""}- </Text>- ) : null}- </Flex>- </Flex>- {approval.decision_reason ? (- <Text className="text-[12px] text-gray-11">- Reason: {approval.decision_reason}- </Text>- ) : null}- {approval.decided_args ? (- <ArgsSection label="Edited arguments" args={approval.decided_args} />- ) : null}- {dispatchError ? (- <Text className="text-(--red-11) text-[12px]">- Dispatch error: {dispatchError}- </Text>- ) : null}- </Flex>- );-}--function outcomeBanner(- state: AgentApprovalRequest["state"],- hasDispatchError: boolean,-): {- title: string;- classes: string;- Icon: typeof CheckCircleIcon;- iconClass: string;-} {- if (hasDispatchError || state === "dispatched_failed") {- return {- title: "Approved, but dispatch failed",- classes: "border-(--red-6) bg-(--red-2)",- Icon: WarningIcon,- iconClass: "text-(--red-11)",- };- }- if (state === "rejected") {- return {- title: "Rejected",- classes: "border-(--gray-6) bg-(--gray-2)",- Icon: XCircleIcon,- iconClass: "text-gray-11",- };- }- if (state === "expired") {- return {- title: "Expired before a decision",- classes: "border-(--amber-6) bg-(--amber-2)",- Icon: WarningIcon,- iconClass: "text-(--amber-11)",- };- }- return {- title: "Approved & dispatched",- classes: "border-(--green-6) bg-(--green-2)",- Icon: CheckCircleIcon,- iconClass: "text-(--green-11)",- };-}--export function ArgsSection({- label,- args,-}: {- label: string;- args: Record<string, unknown>;-}) {- const isEmpty = !args || Object.keys(args).length === 0;- return (- <Flex direction="column" gap="1.5">- <Text className="text-[11px] text-gray-10 uppercase tracking-wide">- {label}- </Text>- {isEmpty ? (- <Text className="text-[12px] text-gray-10">No arguments</Text>- ) : (- <CodeBlock>{JSON.stringify(args, null, 2)}</CodeBlock>- )}- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalsPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalsPane.tsxdeleted file mode 100644index 8ad318945e0c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentApprovalsPane.tsx+++ /dev/null@@ -1,194 +0,0 @@-import { LockKeyIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type { AgentApprovalRequest } from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { useMemo } from "react";-import { useAgentApplicationApprovals } from "../hooks/useAgentApplicationApprovals";-import { approvalStateColor, approvalStateLabel } from "../utils/format";-import { AgentApprovalDetail } from "./AgentApprovalDetail";-import { AgentDetailEmptyState, AgentDetailLayout } from "./AgentDetailLayout";-import { APPROVAL_FILTERS, type ApprovalFilter } from "./agentApprovalsFilters";-import { RefreshIndicator } from "./RefreshIndicator";--export type { ApprovalFilter };--/**- * Per-agent Approvals pane, master-detail: a filterable list on the left and,- * when a row is selected (URL `?request=<id>`), an {@link AgentApprovalDetail}- * panel on the right with the proposed args, decision controls, and the- * embedded session that proposed the gated call.- */-export function AgentApprovalsPane({- idOrSlug,- selectedId,- onSelect,- filter,- onFilterChange,-}: {- idOrSlug: string;- selectedId: string | null;- onSelect: (id: string | null) => void;- filter: ApprovalFilter;- onFilterChange: (f: ApprovalFilter) => void;-}) {- const {- data,- isLoading,- isError,- isPermissionError,- isFetching,- dataUpdatedAt,- refetch,- } = useAgentApplicationApprovals(- idOrSlug,- filter === "all" ? undefined : { state: filter },- );- const approvals = useMemo(() => data ?? [], [data]);- const selected = selectedId- ? (approvals.find((a) => a.id === selectedId) ?? null)- : null;-- const filters = (- <Flex align="center" justify="between" gap="3" wrap="wrap">- <Flex gap="2" wrap="wrap" className="min-w-0">- {APPROVAL_FILTERS.map((f) => (- <button- key={f.id}- type="button"- onClick={() => onFilterChange(f.id)}- className={`rounded-full border px-3 py-1 text-[12px] ${- filter === f.id- ? "border-(--accent-7) bg-(--accent-3) text-gray-12"- : "border-border text-gray-11 hover:border-(--gray-7)"- }`}- >- {f.label}- </button>- ))}- </Flex>- <RefreshIndicator- updatedAt={dataUpdatedAt}- isFetching={isFetching}- onRefresh={() => void refetch()}- compact={!!selectedId}- />- </Flex>- );-- const list = isLoading ? (- <Flex direction="column" gap="2">- {[0, 1, 2].map((i) => (- <div- key={i}- className="h-[60px] animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- ) : isPermissionError ? (- // A 404 here means the admin gate: AgentDetailLayout only renders this- // pane's content once the application itself has loaded successfully.- <AgentDetailEmptyState- title="You need organization admin access"- description="Tool approvals can only be viewed and decided by organization admins. Ask an admin to review pending requests."- />- ) : isError ? (- <AgentDetailEmptyState- title="Couldn't load approvals"- description="The agent platform API returned an error while loading approvals. Try again shortly."- />- ) : approvals.length === 0 ? (- <AgentDetailEmptyState- title="Nothing here"- description={- filter === "queued"- ? "No tool calls are waiting for a decision."- : "No approval requests match this filter."- }- />- ) : (- <Flex direction="column" gap="2">- {approvals.map((approval) => (- <ApprovalRow- key={approval.id}- approval={approval}- selected={approval.id === selectedId}- onSelect={() => onSelect(approval.id)}- />- ))}- </Flex>- );-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="approvals" fill>- <Flex direction="column" className="h-full min-h-0">- <div className="shrink-0 px-5 pt-5 pb-3">{filters}</div>- {selected ? (- <div className="grid min-h-0 flex-1 grid-cols-[minmax(300px,380px)_minmax(0,1fr)] divide-x divide-(--gray-5) overflow-hidden border-(--gray-5) border-t">- <aside className="min-h-0 overflow-y-auto px-3 py-3">{list}</aside>- <main className="min-h-0 overflow-hidden">- <AgentApprovalDetail- idOrSlug={idOrSlug}- approval={selected}- onClose={() => onSelect(null)}- />- </main>- </div>- ) : (- <div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-5 pb-6">{list}</div>- </div>- )}- </Flex>- </AgentDetailLayout>- );-}--function ApprovalRow({- approval,- selected,- onSelect,-}: {- approval: AgentApprovalRequest;- selected: boolean;- onSelect: () => void;-}) {- const isQueued = approval.state === "queued";- return (- <button- type="button"- onClick={onSelect}- className={`flex w-full items-center gap-3 rounded-(--radius-2) border px-4 py-3 text-left ${- selected- ? "border-(--accent-7) bg-(--accent-3)"- : "border-border bg-(--color-panel-solid) hover:border-(--gray-7)"- }`}- >- <LockKeyIcon size={13} className="shrink-0 text-gray-10" />- <Flex direction="column" gap="1" className="min-w-0 flex-1">- <Flex align="center" gap="2" className="min-w-0">- <Badge color={approvalStateColor(approval.state)}>- {approvalStateLabel(approval.state)}- </Badge>- <Text className="truncate font-medium text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {approval.tool_name}- </Text>- </Flex>- <Text className="truncate text-[11px] text-gray-10">- {summarizeArgs(approval.proposed_args)}- </Text>- </Flex>- <Text className="shrink-0 text-[11px] text-gray-10">- {isQueued- ? `expires ${formatRelativeTimeShort(approval.expires_at)}`- : formatRelativeTimeShort(approval.created_at)}- </Text>- </button>- );-}--function summarizeArgs(args: Record<string, unknown>): string {- if (!args || Object.keys(args).length === 0) return "No arguments";- const compact = JSON.stringify(args);- return compact.length > 140 ? `${compact.slice(0, 140)}…` : compact;-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentBundleImportDialog.test.ts b/products/desktop/packages/ui/src/features/agent-applications/components/AgentBundleImportDialog.test.tsdeleted file mode 100644index 1982d39409d6..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentBundleImportDialog.test.ts+++ /dev/null@@ -1,100 +0,0 @@-import { describe, expect, it } from "vitest";-import { type ParsedBundle, parseBundleInput } from "../utils/parseBundleInput";--type Expected =- | { ok: true; value: ParsedBundle }- | { ok: false; errorMatch?: RegExp };--const cases: Array<{ name: string; input: string; expected: Expected }> = [- {- name: "rejects empty input",- input: "",- expected: { ok: false },- },- {- name: "parses a single agent.md block",- input: "--- agent.md ---\nYou are the growth review agent.\n",- expected: {- ok: true,- value: { agent_md: "You are the growth review agent." },- },- },- {- name: "parses multiple skill blocks",- input: [- "--- skills/research/SKILL.md ---",- "Research body",- "--- skills/draft-post/SKILL.md ---",- "Draft body",- ].join("\n"),- expected: {- ok: true,- value: {- skills: [- { id: "research", body: "Research body" },- { id: "draft-post", body: "Draft body" },- ],- },- },- },- {- name: "parses agent.md plus skills together",- input: [- "--- agent.md ---",- "Main prompt",- "",- "--- skills/research/SKILL.md ---",- "Research body",- ].join("\n"),- expected: {- ok: true,- value: {- agent_md: "Main prompt",- skills: [{ id: "research", body: "Research body" }],- },- },- },- {- name: "tolerates CRLF line endings",- input: "--- agent.md ---\r\nMain prompt\r\n",- expected: { ok: true, value: { agent_md: "Main prompt" } },- },- {- name: "rejects an unsupported file path",- input: "--- tools/foo/source.ts ---\nconsole.log('hi')\n",- expected: { ok: false, errorMatch: /Unsupported file path/ },- },- {- name: "rejects skill ids with spaces",- input: "--- skills/Bad Id/SKILL.md ---\nbody\n",- expected: { ok: false },- },- {- name: "rejects skill ids with uppercase letters",- input: "--- skills/MySkill/SKILL.md ---\nbody\n",- expected: { ok: false },- },- {- name: "ignores leading content before the first header",- input: [- "# notes for myself, not in any block",- "--- agent.md ---",- "Prompt",- ].join("\n"),- expected: { ok: true, value: { agent_md: "Prompt" } },- },-];--describe("parseBundleInput", () => {- it.each(cases)("$name", ({ input, expected }) => {- const out = parseBundleInput(input);- if (expected.ok) {- expect(out).toEqual(expected);- return;- }- expect(out.ok).toBe(false);- if (!out.ok && expected.errorMatch) {- expect(out.error).toMatch(expected.errorMatch);- }- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentBundleImportDialog.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentBundleImportDialog.tsxdeleted file mode 100644index 5cda1242a192..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentBundleImportDialog.tsx+++ /dev/null@@ -1,151 +0,0 @@-import { Badge } from "@posthog/ui/primitives/Badge";-import { Button } from "@posthog/ui/primitives/Button";-import { Dialog, Flex, Text } from "@radix-ui/themes";-import { useMemo, useState } from "react";-import { useImportAgentDraftBundle } from "../hooks/useImportAgentDraftBundle";-import { parseBundleInput } from "../utils/parseBundleInput";--const SAMPLE = `--- agent.md ----You are the growth review agent. …----- skills/research/SKILL.md ----When asked to research, …----- skills/draft-post/SKILL.md ----When asked to draft, …-`;--/**- * Bulk-paste a markdown bundle into a draft revision. Designed for migrating- * an existing multi-file agent in one paste — concatenate the source files- * with a `--- path ---` header between each. Existing skill ids are- * overwritten; new ids are added; skills not mentioned are left alone.- */-export function AgentBundleImportDialog({- open,- onOpenChange,- idOrSlug,- revisionId,- existingSkillIds,- onSuccess,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- idOrSlug: string;- revisionId: string;- existingSkillIds: string[];- onSuccess?: () => void;-}) {- const [input, setInput] = useState("");- const mutation = useImportAgentDraftBundle(idOrSlug, revisionId);-- const parsed = useMemo(() => {- if (input.trim().length === 0) return null;- return parseBundleInput(input);- }, [input]);-- const value = parsed?.ok ? parsed.value : null;- const existing = useMemo(() => new Set(existingSkillIds), [existingSkillIds]);-- const onConfirm = () => {- if (!value) return;- mutation.mutate(value, {- onSuccess: () => {- setInput("");- mutation.reset();- onOpenChange(false);- onSuccess?.();- },- });- };-- const close = () => {- if (mutation.isPending) return;- setInput("");- mutation.reset();- onOpenChange(false);- };-- return (- <Dialog.Root- open={open}- onOpenChange={(isOpen) => {- if (!isOpen) close();- }}- >- <Dialog.Content maxWidth="640px">- <Dialog.Title className="text-base">Paste markdown bundle</Dialog.Title>- <Dialog.Description size="2" className="text-gray-11">- Paste one or more <code>--- path ---</code> blocks. Accepts{" "}- <code>agent.md</code> and <code>skills/[id]/SKILL.md</code>. Existing- skills are overwritten by id; new ids are added.- </Dialog.Description>- <textarea- aria-label="Markdown bundle"- value={input}- onChange={(e) => setInput(e.currentTarget.value)}- placeholder={SAMPLE}- disabled={mutation.isPending}- spellCheck={false}- className="mt-3 min-h-[280px] w-full resize-y rounded-(--radius-2) border border-border bg-(--color-panel-solid) p-3 text-[12.5px] text-gray-12 [font-family:var(--font-mono)] focus:border-(--accent-7) focus:outline-none"- />- {parsed && !parsed.ok ? (- <Text className="mt-2 block text-(--red-11) text-[12px]">- {parsed.error}- </Text>- ) : null}- {value ? (- <div className="mt-3 rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2">- <Text className="block text-[11px] text-gray-10 uppercase tracking-wide">- Will write- </Text>- <Flex direction="column" gap="1" className="mt-1.5">- {value.agent_md !== undefined ? (- <Flex align="center" gap="2">- <code className="text-[12px] text-gray-12 [font-family:var(--font-mono)]">- agent.md- </code>- <Badge color="blue">update</Badge>- </Flex>- ) : null}- {value.skills?.map((s) => (- <Flex key={s.id} align="center" gap="2">- <code className="text-[12px] text-gray-12 [font-family:var(--font-mono)]">- skills/{s.id}/SKILL.md- </code>- <Badge color={existing.has(s.id) ? "blue" : "green"}>- {existing.has(s.id) ? "update" : "new"}- </Badge>- </Flex>- ))}- </Flex>- </div>- ) : null}- {mutation.isError ? (- <Text className="mt-2 block text-(--red-11) text-[12px]">- {mutation.error?.message ?? "Import failed"}- </Text>- ) : null}- <Flex justify="end" gap="2" mt="4">- <Button- size="1"- variant="soft"- color="gray"- disabled={mutation.isPending}- onClick={close}- >- Cancel- </Button>- <Button- size="1"- loading={mutation.isPending}- disabled={!value}- onClick={onConfirm}- >- Import- </Button>- </Flex>- </Dialog.Content>- </Dialog.Root>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatPane.tsxdeleted file mode 100644index de649d10042c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatPane.tsx+++ /dev/null@@ -1,414 +0,0 @@-import {- ChatCircleIcon,- InfoIcon,- PlusIcon,- TrashIcon,-} from "@phosphor-icons/react";-import type { CloudRegion } from "@posthog/shared";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Text } from "@radix-ui/themes";-import { useNavigate } from "@tanstack/react-router";-import { useEffect, useMemo, useRef, useState } from "react";-import { useAuthStateValue } from "../../auth/store";-import {- type ChatHistoryEntry,- useChatHistoryStore,-} from "../chat/chatHistoryStore";-import { useAgentApplication } from "../hooks/useAgentApplication";-import { useAgentChat } from "../hooks/useAgentChat";-import { useAgentChatPendingApproval } from "../hooks/useAgentChatPendingApproval";-import { useAgentRevision } from "../hooks/useAgentRevision";-import { resolveIngressBaseUrl } from "../utils/ingress";-import { AgentChatPendingApprovalCard } from "./AgentChatPendingApprovalCard";-import { AgentChatSurface } from "./AgentChatSurface";-import { AgentDetailEmptyState, AgentDetailLayout } from "./AgentDetailLayout";--const EMPTY_CHATS: ChatHistoryEntry[] = [];--function rec(v: unknown): Record<string, unknown> {- return v && typeof v === "object" ? (v as Record<string, unknown>) : {};-}--/** Compact "x ago" for the rail, from an epoch-ms timestamp. */-function relativeTime(ms: number): string {- const diff = Date.now() - ms;- const s = Math.floor(diff / 1000);- if (s < 60) return "just now";- const m = Math.floor(s / 60);- if (m < 60) return `${m}m ago`;- const h = Math.floor(m / 60);- if (h < 24) return `${h}h ago`;- return `${Math.floor(h / 24)}d ago`;-}--/**- * In-app chat against a deployed agent. Streams the agent-ingress SSE through- * the native `ConversationView`. Only meaningful for agents that expose a chat- * trigger and have a public ingress URL.- *- * A left rail lists the chats the user started *here* (persisted locally —- * never the agent's full server session list, which can include real customer- * chats), and a banner makes clear which revision this targets.- *- * When `revisionId` targets a non-live revision (the "Test draft" affordance- * from the revision bar), the hook mints a short-lived ingress JWT and routes- * the run to that draft; chatId/banner switch accordingly so a draft session- * can't be confused with a live one. Side effects (Slack, approvals, tools)- * still run for real — only the revision serving the request differs.- */-export function AgentChatPane({- idOrSlug,- revisionId,- resumeSessionId,-}: {- idOrSlug: string;- revisionId?: string | null;- /**- * Optional session id from the route (`?session=`); when set, the pane- * re-attaches to that session on first mount. Lets rail clicks that cross- * revisions land on the right surface AND immediately resume — without it,- * the new mount would render an empty composer.- */- resumeSessionId?: string | null;-}) {- const navigate = useNavigate();- const { data: application } = useAgentApplication(idOrSlug);- // null/equal-to-live → fall back to the live revision; explicit non-live- // revision id → route this chat to the draft.- const targetRevisionId =- revisionId && revisionId !== application?.live_revision- ? revisionId- : (application?.live_revision ?? null);- const isDraftRevisionChat =- !!revisionId && revisionId !== application?.live_revision;- const { data: revision } = useAgentRevision(idOrSlug, targetRevisionId);- const cloudRegion = useAuthStateValue((s) => s.cloudRegion);- const ingressBaseUrl = resolveIngressBaseUrl(- application?.ingress_base_url,- cloudRegion,- );- const hasChatTrigger = (revision?.spec?.triggers ?? []).some(- (t) => rec(t).type === "chat",- );- // Keyed by revision so a draft chat and the live chat coexist in the store- // without trampling each other.- const chatId = isDraftRevisionChat- ? `preview:${idOrSlug}:${revisionId}`- : `preview:${idOrSlug}`;- const chat = useAgentChat({- chatId,- agentSlug: idOrSlug,- ingressBaseUrl,- revisionId: isDraftRevisionChat ? revisionId : null,- recordHistory: true,- });- const pendingApproval = useAgentChatPendingApproval(chatId);- const chats = useChatHistoryStore((s) => s.byAgent[idOrSlug]) ?? EMPTY_CHATS;- const removeChat = useChatHistoryStore((s) => s.remove);-- // Partition the rail into "matches the current target" vs everything else- // so a live view doesn't drown in old draft chats (and vice-versa). The- // expander reveals the rest on demand.- const currentRev = isDraftRevisionChat ? (revisionId ?? null) : null;- const { matchingChats, otherChats } = useMemo(() => {- const matching: ChatHistoryEntry[] = [];- const other: ChatHistoryEntry[] = [];- for (const c of chats) {- if ((c.revisionId ?? null) === currentRev) matching.push(c);- else other.push(c);- }- return { matchingChats: matching, otherChats: other };- }, [chats, currentRev]);- const [showOthers, setShowOthers] = useState(false);- // Reset the expander whenever the target switches so each surface starts- // focused on its own chats.- const lastRevRef = useRef(currentRev);- if (lastRevRef.current !== currentRev) {- lastRevRef.current = currentRev;- if (showOthers) setShowOthers(false);- }-- // Auto-resume the URL-named session exactly once per param value. Tracked by- // a ref so a re-render or chat.resume identity change can't re-fire on the- // same id. After kicking it off we clear the URL hint so an in-pane "New- // chat" can't be silently undone by a refresh.- const resumedRef = useRef<string | null>(null);- useEffect(() => {- if (!resumeSessionId || resumedRef.current === resumeSessionId) return;- resumedRef.current = resumeSessionId;- chat.resume(resumeSessionId);- // Anchored to this route so TanStack can resolve the search-fn against the- // chat route's typed shape (the no-`to` form widens to `never`).- navigate({- to: "/code/agents/applications/$idOrSlug/chat",- params: { idOrSlug },- search: (prev) => ({ ...prev, session: undefined }),- });- }, [resumeSessionId, chat.resume, navigate, idOrSlug]);-- // The rail mixes chats from every revision; decide per click whether to- // resume inline (same target) or navigate to a different revision's surface.- const handleRailSelect = (entry: ChatHistoryEntry) => {- if ((entry.revisionId ?? null) === currentRev) {- chat.resume(entry.sessionId);- return;- }- navigate({- to: "/code/agents/applications/$idOrSlug/chat",- params: { idOrSlug },- search: entry.revisionId- ? { revision: entry.revisionId, session: entry.sessionId }- : { session: entry.sessionId },- });- };-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="chat" fill>- {!ingressBaseUrl ? (- <div className="p-6">- <AgentDetailEmptyState- title="No ingress URL"- description="This deployment has no public ingress URL, so the agent can't be reached for a live chat."- />- </div>- ) : !hasChatTrigger ? (- <div className="p-6">- <AgentDetailEmptyState- title="No chat trigger"- description={- isDraftRevisionChat- ? "This draft revision doesn't expose a chat trigger, so there's nothing to chat with. Add a chat trigger via the agent builder to test it here."- : "This agent's live revision doesn't expose a chat trigger, so there's nothing to chat with. Add a chat trigger via the agent builder to test it here."- }- />- </div>- ) : (- <Flex className="h-full min-h-0">- <ChatHistoryRail- chats={matchingChats}- otherChats={otherChats}- showOthers={showOthers}- onToggleShowOthers={() => setShowOthers((v) => !v)}- activeSessionId={chat.sessionId}- onNewChat={chat.newChat}- onSelect={handleRailSelect}- onDelete={(sessionId) => removeChat(idOrSlug, sessionId)}- />- <Flex direction="column" className="min-w-0 flex-1">- <RevisionChatBanner- revisionId={targetRevisionId}- isDraft={isDraftRevisionChat}- model={revision?.spec?.model}- region={cloudRegion}- />- <AgentChatSurface- messages={chat.messages}- isStreaming={chat.isStreaming}- error={chat.error}- emptyHint="Send a message to start a session and test this agent live."- belowConversation={- pendingApproval ? (- <AgentChatPendingApprovalCard- idOrSlug={idOrSlug}- approval={pendingApproval}- decide={chat.decideApproval}- />- ) : null- }- composerDisabledReason={- pendingApproval- ? "Waiting on your approval decision"- : undefined- }- onSend={chat.send}- onCancel={chat.cancel}- />- </Flex>- </Flex>- )}- </AgentDetailLayout>- );-}--function RevisionChatBanner({- revisionId,- isDraft,- model,- region,-}: {- revisionId: string | null;- isDraft: boolean;- model: string | undefined;- region: CloudRegion | null;-}) {- return (- <Flex- align="center"- gap="2"- className={`shrink-0 border-(--gray-5) border-b px-4 py-2 ${- isDraft ? "bg-(--amber-2)" : "bg-(--gray-2)"- }`}- >- <InfoIcon size={14} className="shrink-0 text-gray-10" />- <Text className="text-[12px] text-gray-11 leading-snug">- {isDraft- ? "Chatting with a draft revision — Slack posts, approvals, and tools all run for real. Promote the revision to make this the live one."- : "Chatting with the live revision — messages run against the currently deployed revision. Only chats you start here appear in the list."}- </Text>- <Flex align="center" gap="2" className="ml-auto shrink-0">- {model ? (- <Text className="text-[11px] text-gray-10">{model}</Text>- ) : null}- {revisionId ? (- <Text- className="font-mono text-[11px] text-gray-10"- title={revisionId}- >- rev {revisionId.slice(0, 8)}- </Text>- ) : null}- {region ? (- <Text className="text-[11px] text-gray-10 uppercase">{region}</Text>- ) : null}- </Flex>- </Flex>- );-}--function ChatHistoryRail({- chats,- otherChats,- showOthers,- onToggleShowOthers,- activeSessionId,- onNewChat,- onSelect,- onDelete,-}: {- chats: ChatHistoryEntry[];- /** Chats from other revisions — hidden behind an expander to keep this surface focused. */- otherChats: ChatHistoryEntry[];- showOthers: boolean;- onToggleShowOthers: () => void;- activeSessionId: string | null;- onNewChat: () => void;- /** Receives the full entry so the parent can route by revision, not just resume. */- onSelect: (entry: ChatHistoryEntry) => void;- onDelete: (sessionId: string) => void;-}) {- return (- <Flex- direction="column"- className="w-56 shrink-0 border-(--gray-5) border-r"- >- <div className="shrink-0 p-2">- <Button- variant="soft"- color="gray"- size="1"- className="w-full justify-start"- onClick={onNewChat}- >- <PlusIcon size={13} />- New chat- </Button>- </div>- <div className="min-h-0 flex-1 overflow-auto px-2 pb-2">- {chats.length === 0 && (otherChats.length === 0 || !showOthers) ? (- <Text className="block px-1 py-2 text-[11.5px] text-gray-9 leading-snug">- Chats you start here will show up in this list.- </Text>- ) : (- <Flex direction="column" gap="1">- {chats.map((c) => (- <RailEntry- key={c.sessionId}- entry={c}- active={c.sessionId === activeSessionId}- onSelect={onSelect}- onDelete={onDelete}- />- ))}- {otherChats.length > 0 ? (- <>- <button- type="button"- onClick={onToggleShowOthers}- className="mt-1 block rounded-(--radius-2) px-2 py-1 text-left text-[10.5px] text-gray-10 uppercase tracking-wide hover:bg-(--gray-3) hover:text-gray-12"- >- {showOthers- ? "Hide other revisions"- : `Show ${otherChats.length} from other revision${otherChats.length === 1 ? "" : "s"}`}- </button>- {showOthers- ? otherChats.map((c) => (- <RailEntry- key={c.sessionId}- entry={c}- active={c.sessionId === activeSessionId}- onSelect={onSelect}- onDelete={onDelete}- />- ))- : null}- </>- ) : null}- </Flex>- )}- </div>- </Flex>- );-}--function RailEntry({- entry,- active,- onSelect,- onDelete,-}: {- entry: ChatHistoryEntry;- active: boolean;- onSelect: (entry: ChatHistoryEntry) => void;- onDelete: (sessionId: string) => void;-}) {- return (- <div className="group relative">- <button- type="button"- onClick={() => onSelect(entry)}- className={`flex w-full items-start gap-2 rounded-(--radius-2) py-1.5 pr-7 pl-2 text-left ${- active ? "bg-(--accent-3)" : "hover:bg-(--gray-3)"- }`}- >- <ChatCircleIcon size={13} className="mt-0.5 shrink-0 text-gray-10" />- <span className="min-w-0 flex-1">- <span className="block truncate text-[12px] text-gray-12 leading-tight">- {entry.title || "Untitled chat"}- </span>- <Flex align="center" gap="1" className="text-[10.5px] text-gray-9">- <span>{relativeTime(entry.startedAt)}</span>- {entry.revisionId ? (- <>- <span aria-hidden>·</span>- <span- className="rounded-(--radius-1) bg-(--amber-3) px-1 font-mono text-(--amber-11) text-[10px]"- title={`Chat against draft revision ${entry.revisionId}`}- >- rev {entry.revisionId.slice(0, 8)}- </span>- </>- ) : null}- </Flex>- </span>- </button>- <button- type="button"- aria-label="Remove chat"- onClick={() => onDelete(entry.sessionId)}- className="absolute top-1.5 right-1 rounded p-0.5 text-gray-9 opacity-0 hover:text-gray-12 group-hover:opacity-100"- >- <TrashIcon size={12} />- </button>- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatPendingApprovalCard.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatPendingApprovalCard.tsxdeleted file mode 100644index 1cf57fc59fd9..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatPendingApprovalCard.tsx+++ /dev/null@@ -1,119 +0,0 @@-import { ArrowSquareOutIcon, LockKeyIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type {- AgentApprovalRequest,- DecideApprovalRequest,-} from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { toast } from "@posthog/ui/primitives/toast";-import { Flex, Text } from "@radix-ui/themes";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { Link } from "@tanstack/react-router";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "../hooks/agentApplicationsKeys";-import { approvalStateColor, approvalStateLabel } from "../utils/format";-import { AgentApprovalDecisionForm } from "./AgentApprovalDecisionForm";-import { ArgsSection } from "./AgentApprovalDetail";--/**- * Inline pending-approval card surfaced in the chat pane / agent builder- * dock. Renders between the conversation and the composer when the- * agent has paused on an approval-gated tool call.- *- * Decision routing follows the approval `type`:- * - `principal` (the default) — the person driving this chat IS the session- * principal, so they decide right here. The decision posts to the ingress- * via the chat session's `decide` (principal-match, not the owner console),- * and the open `/listen` stream resumes the chat on approve.- * - `agent` — an owner/admin must decide in the console; the card shows that- * and links to the Approvals view rather than offering buttons.- */-export function AgentChatPendingApprovalCard({- idOrSlug,- approval,- decide,-}: {- idOrSlug: string;- approval: AgentApprovalRequest;- /** Chat-session decide (ingress, principal-match) from `useAgentChat`. */- decide: (approvalId: string, body: DecideApprovalRequest) => Promise<void>;-}) {- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);- const isOwnerGate = approval.approver_scope?.type === "agent";-- const mutation = useMutation<void, Error, DecideApprovalRequest>({- mutationFn: (body) => decide(approval.id, body),- onSuccess: (_data, body) => {- toast.success(body.decision === "approve" ? "Approved" : "Rejected", {- description:- body.decision === "approve"- ? "Dispatched to the agent."- : "The agent will see the rejection.",- });- // Clear the card now rather than waiting for the 2s poll; the server-side- // row has flipped and the stream resumes the chat on approve.- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.approvalsPrefix(projectId, idOrSlug),- });- },- onError: (err) => {- toast.error("Decision failed", {- description: err instanceof Error ? err.message : undefined,- });- },- });-- return (- <div className="shrink-0 border-(--amber-6) border-t bg-(--amber-2) px-4 pt-3 pb-2">- <Flex align="start" justify="between" gap="3" className="mb-2">- <Flex direction="column" gap="1" className="min-w-0">- <Flex align="center" gap="2" className="min-w-0">- <LockKeyIcon size={13} className="shrink-0 text-(--amber-11)" />- <Text className="font-semibold text-[12.5px] text-gray-12">- Approval needed- </Text>- <Badge color={approvalStateColor(approval.state)}>- {approvalStateLabel(approval.state)}- </Badge>- <Text className="truncate font-medium font-mono text-[12.5px] text-gray-12">- {approval.tool_name}- </Text>- </Flex>- <Text className="text-[11px] text-gray-10">- expires {formatRelativeTimeShort(approval.expires_at)}- </Text>- </Flex>- <Link- to="/code/agents/applications/$idOrSlug/approvals"- params={{ idOrSlug }}- search={{ request: approval.id }}- className="inline-flex shrink-0 items-center gap-1 text-[11.5px] text-gray-11 no-underline hover:text-gray-12"- >- Open in Approvals- <ArrowSquareOutIcon size={11} />- </Link>- </Flex>- <ArgsSection label="Proposed arguments" args={approval.proposed_args} />- {isOwnerGate ? (- <Text className="text-[11.5px] text-gray-10">- This call needs an owner or admin to approve it in the console — open- it in Approvals above.- </Text>- ) : (- <AgentApprovalDecisionForm- approval={approval}- busy={mutation.isPending}- error={- mutation.isError- ? mutation.error instanceof Error- ? mutation.error.message- : "Decision failed"- : null- }- onSubmit={(body) => mutation.mutate(body)}- />- )}- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatSurface.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatSurface.tsxdeleted file mode 100644index cd44d9adfe3b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentChatSurface.tsx+++ /dev/null@@ -1,204 +0,0 @@-import { ArrowUp, StopCircle } from "@phosphor-icons/react";-import {- InputGroup,- InputGroupAddon,- InputGroupButton,- InputGroupTextarea,-} from "@posthog/quill";-import type { AcpMessage } from "@posthog/shared";-import { ThreadView } from "@posthog/ui/features/sessions/components/ThreadView";-import { Flex, Text, Tooltip } from "@radix-ui/themes";-import {- type KeyboardEvent,- type ReactNode,- useEffect,- useRef,- useState,-} from "react";--/**- * The conversation + composer half of a deployed-agent chat, shared by the- * per-agent chat pane and the agent builder dock. Renders the live ACP messages- * through the native `ConversationView` (collapse disabled so the agent's prose- * shows inline) and an auto-growing composer with Enter-to-send / Cancel that- * mirrors the main task chat's input shell.- */-export function AgentChatSurface({- messages,- isStreaming,- error,- emptyHint,- emptyState,- aboveComposer,- belowConversation,- composerDisabledReason,- scrollX = true,- placeholder = "Message this agent…",- draft,- onSend,- onCancel,-}: {- messages: AcpMessage[];- isStreaming: boolean;- error: string | null;- emptyHint: string;- /** Richer empty-state content (e.g. suggestions); falls back to `emptyHint`. */- emptyState?: ReactNode;- /** Optional content rendered between the transcript and the composer. */- aboveComposer?: ReactNode;- /** Optional content rendered between the transcript and `aboveComposer`,- * anchored to the conversation rather than the input. */- belowConversation?: ReactNode;- /** When set, the composer is disabled and this string is shown as a tooltip- * on the send button. Use when the chat is parked (e.g. waiting on an- * inline approval decision). */- composerDisabledReason?: string;- /** Allow horizontal scroll of the transcript (false in the narrow dock). */- scrollX?: boolean;- /** Composer placeholder. */- placeholder?: string;- /** When set, prefills the composer with `text` (without sending). Bump- * `token` each time a new draft should repopulate the input — the same text- * re-applies on a fresh token so re-triggering a seeded prompt works. */- draft?: { text: string; token: number };- onSend: (text: string) => void;- onCancel: () => void;-}) {- return (- <Flex direction="column" className="min-h-0 flex-1">- <div className="flex min-h-0 flex-1 flex-col">- {messages.length === 0 ? (- (emptyState ?? (- <div className="flex h-full items-center justify-center px-6 text-center">- <Text className="max-w-sm text-[13px] text-gray-10 leading-snug">- {emptyHint}- </Text>- </div>- ))- ) : (- <ThreadView- events={messages}- isPromptPending={isStreaming}- // This pane is the agent's work; a chip over it would hide the point of the surface.- groupToolCalls={false}- scrollX={scrollX}- />- )}- </div>- {belowConversation}- {error ? (- <Text className="shrink-0 px-4 pb-1 text-(--red-11) text-[12px]">- {error}- </Text>- ) : null}- {aboveComposer}- <Composer- isStreaming={isStreaming}- placeholder={placeholder}- disabledReason={composerDisabledReason}- draft={draft}- onSend={onSend}- onCancel={onCancel}- />- </Flex>- );-}--function Composer({- isStreaming,- placeholder,- disabledReason,- draft,- onSend,- onCancel,-}: {- isStreaming: boolean;- placeholder: string;- disabledReason?: string;- draft?: { text: string; token: number };- onSend: (text: string) => void;- onCancel: () => void;-}) {- const [text, setText] = useState("");- const parked = !!disabledReason;- const textareaRef = useRef<HTMLTextAreaElement>(null);-- // Prefill (but don't send) when a new draft lands — a seeded prompt drops into- // the composer for the user to review, edit, and send. Keyed on `token` so the- // same prompt re-applies on a fresh trigger. Never clobber text the user has- // already typed but not sent: if the composer is non-empty, leave it as-is- // (still focusing it) so a seeded prompt is genuinely non-destructive.- const lastDraftToken = useRef<number | null>(null);- useEffect(() => {- if (!draft || draft.token === lastDraftToken.current) return;- lastDraftToken.current = draft.token;- setText((current) => (current.trim() ? current : draft.text));- textareaRef.current?.focus();- }, [draft]);-- function submit() {- if (parked) return;- const trimmed = text.trim();- if (!trimmed) return;- onSend(trimmed);- setText("");- }- function onKeyDown(e: KeyboardEvent) {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- submit();- }- }-- const submitBlocked = parked || !text.trim();- const sendTooltip = parked- ? (disabledReason as string)- : submitBlocked- ? "Enter a message"- : "Send message";-- return (- <div className="shrink-0 px-3 pt-2 pb-3">- <InputGroup className="h-auto cursor-text bg-card focus-within:ring-1 focus-within:ring-purple-9">- <InputGroupTextarea- ref={textareaRef}- value={text}- onChange={(e) => setText(e.target.value)}- onKeyDown={onKeyDown}- placeholder={parked ? (disabledReason as string) : placeholder}- rows={1}- disabled={parked}- className="max-h-[160px] min-h-[40px] resize-none text-[14px] [field-sizing:content]"- />- <InputGroupAddon align="block-end" className="p-1">- <span className="ml-auto flex items-center gap-1">- {isStreaming ? (- <Tooltip content="Stop">- <InputGroupButton- variant="destructive"- size="icon-sm"- onClick={onCancel}- aria-label="Stop"- >- <StopCircle size={14} weight="fill" />- </InputGroupButton>- </Tooltip>- ) : (- <Tooltip content={sendTooltip}>- <InputGroupButton- variant="primary"- size="icon-sm"- onClick={submit}- disabled={submitBlocked}- aria-label="Send message"- >- <ArrowUp size={14} weight="bold" />- </InputGroupButton>- </Tooltip>- )}- </span>- </InputGroupAddon>- </InputGroup>- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentConfigurationPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentConfigurationPane.tsxdeleted file mode 100644index 95668a9df502..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentConfigurationPane.tsx+++ /dev/null@@ -1,2860 +0,0 @@-import {- ChatCircleIcon,- ChatTextIcon,- ClockIcon,- CodeIcon,- FingerprintIcon,- GaugeIcon,- GlobeIcon,- HardDrivesIcon,- InfoIcon,- KeyIcon,- LightningIcon,- LockKeyIcon,- PuzzlePieceIcon,- ScrollIcon,- SparkleIcon,- TrashIcon,- UserIcon,- WarningIcon,- WebhooksLogoIcon,- WrenchIcon,-} from "@phosphor-icons/react";-import type {- McpApprovalState,- McpInstallationTool,-} from "@posthog/api-client/posthog-client";-import type {- AgentRevisionState,- AgentSpec,- BundleFile,-} from "@posthog/shared/agent-platform-types";-import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";-import { AddCustomServerDialog } from "@posthog/ui/features/mcp-server-manager/AddCustomServerDialog";-import { useMcpConnect } from "@posthog/ui/features/mcp-server-manager/useMcpConnect";-import { ToolPermissionList } from "@posthog/ui/features/mcp-servers/components/parts/ToolPermissionList";-import { useMcpInstallationTools } from "@posthog/ui/features/mcp-servers/hooks/useMcpInstallationTools";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Button } from "@posthog/ui/primitives/Button";-import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";-import { toast } from "@posthog/ui/primitives/toast";-import { Flex, Select, Switch, Text, TextField } from "@radix-ui/themes";-import { type ReactNode, useCallback, useMemo, useState } from "react";-import { AGENT_PLATFORM_FLAG } from "../featureFlag";-import { useAgentApplication } from "../hooks/useAgentApplication";-import { useAgentEnvKeys } from "../hooks/useAgentEnvKeys";-import { useAgentRevision } from "../hooks/useAgentRevision";-import { useAgentRevisionBundle } from "../hooks/useAgentRevisionBundle";-import { useAgentRevisions } from "../hooks/useAgentRevisions";-import { useApplyAgentSpec } from "../hooks/useApplyAgentSpec";-import { useUpdateAgentDraftBundleFile } from "../hooks/useUpdateAgentDraftBundleFile";-import { triggerRequiredSecretsFor } from "../utils/triggerSecrets";-import { AgentDetailEmptyState, AgentDetailLayout } from "./AgentDetailLayout";-import { AgentModelConfig } from "./AgentModelConfig";-import { AgentRevisionBar } from "./AgentRevisionBar";-import { CopyButton } from "./CopyButton";-import { CronFireButton } from "./CronFireButton";-import { FileExplorer, type FileTreeNode } from "./FileExplorer";-import { SecretEditor } from "./SecretEditor";-import { SlackSetupCard } from "./SlackSetupCard";-import { ToolSourcePanel } from "./ToolSourcePanel";--// Value readers — spec items are loosely typed on the wire.-function rec(v: unknown): Record<string, unknown> {- return v && typeof v === "object" ? (v as Record<string, unknown>) : {};-}-function str(v: unknown): string | undefined {- return typeof v === "string" ? v : undefined;-}-function arr(v: unknown): unknown[] {- return Array.isArray(v) ? v : [];-}--const ICON = { size: 14, className: "shrink-0 text-gray-10" } as const;-const USAGE_HOST = "https://<ingress-host>";--/** Context threaded to every detail body. */-interface Ctx {- idOrSlug: string;- revisionId: string;- /** Application UUID — needed to branch a new draft on save. */- applicationId?: string;- /** State of the revision being viewed — gates the editable .md surface and drives draft-only edit vs auto-clone. */- revisionState: AgentRevisionState;- ingressBaseUrl?: string;- setKeys: string[];- onSelect: (node: string) => void;- /** Select a revision in the picker (used to jump to a freshly branched draft). */- onSelectRevision?: (revisionId: string) => void;- onOpenSession?: (sessionId: string) => void;-}--function triggerType(t: unknown): string {- return str(rec(t).type) ?? "trigger";-}-function triggerIcon(type: string): ReactNode {- switch (type) {- case "cron":- return <ClockIcon {...ICON} />;- case "slack":- return <ChatCircleIcon {...ICON} />;- case "webhook":- return <WebhooksLogoIcon {...ICON} />;- case "chat":- return <ChatTextIcon {...ICON} />;- case "mcp":- return <HardDrivesIcon {...ICON} />;- default:- return <GlobeIcon {...ICON} />;- }-}-function authModes(t: unknown): string[] {- const modes = rec(rec(t).auth).modes;- return (Array.isArray(modes) ? modes : []).map(- (m) => str(rec(m).type) ?? "?",- );-}-function isPublic(t: unknown): boolean {- return authModes(t).includes("public");-}-function toolId(t: unknown): string {- return str(rec(t).id) ?? "tool";-}-function toolIcon(kind: string | undefined): ReactNode {- if (kind === "client") return <UserIcon {...ICON} />;- if (kind === "custom") return <CodeIcon {...ICON} />;- return <SparkleIcon {...ICON} />;-}-function shortName(id: string): string {- const slash = id.lastIndexOf("/");- return slash >= 0 ? id.slice(slash + 1) : id;-}-function missingSecretsFor(t: unknown, setKeys: string[]): string[] {- return triggerRequiredSecretsFor(t)- .map((s) => s.key)- .filter((k) => !setKeys.includes(k));-}-function mcpMissingSecrets(m: unknown, setKeys: string[]): string[] {- return arr(rec(m).secrets)- .filter((s): s is string => typeof s === "string")- .filter((k) => !setKeys.includes(k));-}--function allSecretKeys(spec: AgentSpec, setKeys: string[]): string[] {- const set = new Set<string>(- arr(spec.secrets).filter((s): s is string => typeof s === "string"),- );- for (const t of arr(spec.triggers))- for (const s of triggerRequiredSecretsFor(t)) set.add(s.key);- for (const k of setKeys) set.add(k);- return [...set].sort();-}--// --- Identity providers (the credential axis) ----// `spec.identity_providers[]` are the providers an asker can link against so the-// agent acts AS them when a tool/MCP needs it. Two consumers are declared in the-// spec and cross-linked here: custom tools (`requires_identity`) and MCP servers-// (`auth.provider`). Native @posthog/* tools declare their provider intrinsically-// in the tool registry, so they don't appear in the spec — noted in the UI.-function identityProviders(spec: AgentSpec): unknown[] {- return arr(spec.identity_providers);-}-function providerId(p: unknown): string {- return str(rec(p).id) ?? "provider";-}-function toolRequiresIdentity(t: unknown): string | undefined {- return str(rec(t).requires_identity);-}-function mcpProvider(m: unknown): string | undefined {- return str(rec(rec(m).auth).provider);-}--// `spec.authoritative_provider` = the one identity_providers[] id that gates-// admission. It can only be authoritative if it proves a subject (kind posthog,-// or oauth2 + userinfo_url) — mirrors AgentSpecSchema.superRefine.-// The leading NUL byte makes this sentinel structurally impossible as a-// user-typed provider id, so it can't collide with a real Select.Item value.-const NONE_PROVIDER = "\0none";-function authoritativeProviderId(spec: AgentSpec): string | undefined {- return str(spec.authoritative_provider);-}-function establishesIdentity(p: unknown): boolean {- const r = rec(p);- const kind = str(r.kind);- return kind === "posthog" || (kind === "oauth2" && !!str(r.userinfo_url));-}--// --- Per-agent MCP tool permissions (agent-level shared connection) ----// The spec carries allow/approve/deny; the shared ToolPermissionList speaks the-// mcp_store vocabulary (approved/needs_approval/do_not_use). Map at the boundary-// so that component is reused verbatim.-type ToolApprovalLevel = "allow" | "approve" | "deny";-// New connections start safe-by-default: every tool parks for approval until the-// owner relaxes specific tools. Mirrors the runner's fallback.-const DEFAULT_TOOL_APPROVAL: ToolApprovalLevel = "approve";-const LEVEL_TO_APPROVAL: Record<ToolApprovalLevel, McpApprovalState> = {- allow: "approved",- approve: "needs_approval",- deny: "do_not_use",-};-const APPROVAL_TO_LEVEL: Record<McpApprovalState, ToolApprovalLevel> = {- approved: "allow",- needs_approval: "approve",- do_not_use: "deny",-};-function toToolApprovalLevel(v: unknown): ToolApprovalLevel | undefined {- return v === "allow" || v === "approve" || v === "deny" ? v : undefined;-}-/** The per-tool override `level` declared in `mcps[].tools[]`, keyed by name. */-function toolLevelOverrides(mcpEntry: unknown): Map<string, ToolApprovalLevel> {- const out = new Map<string, ToolApprovalLevel>();- for (const t of arr(rec(mcpEntry).tools)) {- if (typeof t === "object" && t) {- const name = str(rec(t).name);- const level = toToolApprovalLevel(rec(t).level);- if (name && level) out.set(name, level);- }- }- return out;-}-interface IdentityConsumers {- tools: string[];- mcps: string[];-}-function identityConsumers(spec: AgentSpec, id: string): IdentityConsumers {- return {- tools: arr(spec.tools).flatMap((t) =>- toolRequiresIdentity(t) === id ? [toolId(t)] : [],- ),- mcps: arr(spec.mcps).flatMap((m) =>- mcpProvider(m) === id ? [str(rec(m).id) ?? "mcp"] : [],- ),- };-}-function consumerCount(c: IdentityConsumers): number {- return c.tools.length + c.mcps.length;-}--function WarnBadge({ title }: { title: string }) {- return (- <span title={title}>- <WarningIcon size={13} className="text-amber-10" />- </span>- );-}--function buildTree(spec: AgentSpec, setKeys: string[]): FileTreeNode {- // Order chosen for how operators read an agent: what it is, what starts it,- // what it needs, what it knows, what it can do.- const children: FileTreeNode[] = [- {- type: "file",- name: "instructions",- path: "cfg:instructions",- icon: <ScrollIcon {...ICON} />,- },- {- type: "file",- name: "model",- path: "cfg:model",- icon: <SparkleIcon {...ICON} />,- },- ];-- // Above triggers: admission gates whether any trigger can start a session.- const identities = identityProviders(spec);- const authProviderId = authoritativeProviderId(spec);- children.push({- type: "folder",- name: "auth & identity",- path: "cfg:identities",- icon: <FingerprintIcon {...ICON} />,- children: identities.map((p) => {- const id = providerId(p);- const used = consumerCount(identityConsumers(spec, id));- return {- type: "file" as const,- name: id,- path: `cfg:identity/${id}`,- icon: <FingerprintIcon {...ICON} />,- trailing:- id === authProviderId ? (- <Badge color="iris">auth</Badge>- ) : used === 0 ? (- <Badge color="amber">unused</Badge>- ) : undefined,- };- }),- });-- const triggers = arr(spec.triggers);- children.push({- type: "folder",- name: "triggers",- path: "cfg:triggers",- icon: <LightningIcon {...ICON} />,- children: triggers.map((t, i) => {- const type = triggerType(t);- const missing = missingSecretsFor(t, setKeys);- return {- type: "file" as const,- name: type,- path: `cfg:trigger/${i}`,- icon: triggerIcon(type),- trailing:- missing.length > 0 ? (- <WarnBadge title={`Needs secret(s): ${missing.join(", ")}`} />- ) : isPublic(t) ? (- <Badge color="amber">public</Badge>- ) : undefined,- };- }),- });-- const secretKeys = allSecretKeys(spec, setKeys);- children.push({- type: "folder",- name: "secrets",- path: "cfg:secrets",- icon: <KeyIcon {...ICON} />,- children: secretKeys.map((key) => ({- type: "file" as const,- name: key,- path: `cfg:secret/${key}`,- icon: <KeyIcon {...ICON} />,- trailing: setKeys.includes(key) ? undefined : (- <Badge color="amber">not set</Badge>- ),- })),- });-- const skills = arr(spec.skills);- children.push({- type: "folder",- name: "skills",- path: "cfg:skills",- icon: <PuzzlePieceIcon {...ICON} />,- children: skills.map((s) => {- const r = rec(s);- const id = str(r.id) ?? str(r.path) ?? "skill";- return {- type: "file" as const,- name: id,- path: `cfg:skill/${id}`,- description: str(r.description),- icon: <PuzzlePieceIcon {...ICON} />,- };- }),- });-- const tools = arr(spec.tools);- children.push({- type: "folder",- name: "tools",- path: "cfg:tools",- icon: <WrenchIcon {...ICON} />,- children: tools.map((t) => {- const r = rec(t);- const id = toolId(t);- return {- type: "file" as const,- name: shortName(id),- path: `cfg:tool/${id}`,- icon: toolIcon(str(r.kind)),- trailing:- r.requires_approval === true ? (- <LockKeyIcon size={11} className="text-amber-10" />- ) : undefined,- };- }),- });-- // Top-level authorable sections always render — even with no entries — so the- // add/connect affordance is reachable on a fresh agent (you add MCP servers,- // tools, skills, triggers, secrets and identities from the empty section).- const mcps = arr(spec.mcps);- children.push({- type: "folder",- name: "mcps",- path: "cfg:mcps",- icon: <HardDrivesIcon {...ICON} />,- children: mcps.map((m) => {- const id = str(rec(m).id) ?? "mcp";- const missing = mcpMissingSecrets(m, setKeys);- return {- type: "file" as const,- name: id,- path: `cfg:mcp/${id}`,- icon: <HardDrivesIcon {...ICON} />,- trailing:- missing.length > 0 ? (- <WarnBadge title={`Needs secret(s): ${missing.join(", ")}`} />- ) : undefined,- };- }),- });-- children.push({- type: "file",- name: "limits",- path: "cfg:limits",- icon: <GaugeIcon {...ICON} />,- });-- return { type: "folder", name: "root", children };-}--export function AgentConfigurationPane({- idOrSlug,- selectedNode,- onSelectNode,- selectedRevisionId,- onSelectRevision,- onOpenSession,-}: {- idOrSlug: string;- selectedNode: string | null;- onSelectNode: (node: string) => void;- /** Revision viewed in the explorer (URL `?revision=`); defaults to live. */- selectedRevisionId: string | null;- onSelectRevision: (revisionId: string) => void;- onOpenSession?: (sessionId: string) => void;-}) {- const { data: application } = useAgentApplication(idOrSlug);- const { data: revisions } = useAgentRevisions(idOrSlug);-- // The explorer shows the selected revision, falling back to live then newest.- const revisionId =- selectedRevisionId ??- application?.live_revision ??- revisions?.[0]?.id ??- null;-- const { data: revision, isLoading } = useAgentRevision(idOrSlug, revisionId);- const { data: bundle } = useAgentRevisionBundle(idOrSlug, revisionId);- const { data: envKeys } = useAgentEnvKeys(idOrSlug, revisionId);-- const spec = revision?.spec ?? null;- const setKeys = useMemo(() => envKeys ?? [], [envKeys]);- const files = useMemo(() => bundle ?? [], [bundle]);- const tree = useMemo(- () => (spec ? buildTree(spec, setKeys) : null),- [spec, setKeys],- );- const node = selectedNode ?? "cfg:instructions";-- const ctx: Ctx | null = revisionId- ? {- idOrSlug,- revisionId,- applicationId: application?.id,- // `revision` may still be loading; fall back to the picker's view so- // the editable-on-draft gating doesn't briefly flash on for a ready- // revision while data resolves. Default to `ready` (immutable).- revisionState:- revision?.state ??- revisions?.find((r) => r.id === revisionId)?.state ??- "ready",- ingressBaseUrl: application?.ingress_base_url ?? undefined,- setKeys,- onSelect: onSelectNode,- onSelectRevision,- onOpenSession,- }- : null;-- const bar =- application && revisions && revisions.length > 0 ? (- <AgentRevisionBar- idOrSlug={idOrSlug}- agent={application}- revisions={revisions}- selectedRevisionId={revisionId}- onSelectRevision={onSelectRevision}- />- ) : null;-- return (- <AgentDetailLayout- idOrSlug={idOrSlug}- activeTab="configuration"- fill- configRevision={revisionId}- >- {!revisionId ? (- <div className="p-6">- <AgentDetailEmptyState- title="No revisions yet"- description="This agent has no revisions, so there's no configuration to show."- />- </div>- ) : !spec || !ctx ? (- <Flex direction="column" className="h-full min-h-0">- {bar}- <div className="p-6">- {isLoading ? (- <div className="h-40 animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)" />- ) : (- <AgentDetailEmptyState- title="Couldn't load configuration"- description="This revision's spec could not be loaded."- />- )}- </div>- </Flex>- ) : (- <Flex direction="column" className="h-full min-h-0">- {bar}- <div className="min-h-0 flex-1">- <FileExplorer- tree={tree}- selectedPath={node}- onSelectPath={onSelectNode}- storageKey="agent-config-explorer"- >- <DetailPane node={node} spec={spec} files={files} ctx={ctx} />- </FileExplorer>- </div>- </Flex>- )}- </AgentDetailLayout>- );-}--const SECTION_INFO: Record<string, string> = {- "cfg:model":- "How the agent picks its model. `auto` resolves a level (low/medium/high) to a maintained cross-provider list at runtime; `manual` pins an explicit priority list. `reasoning` sets the extended-thinking budget.",- "cfg:instructions":- "The agent's entrypoint prompt (agent.md) — the always-on system instructions.",- "cfg:triggers": "What can start a session — chat, webhook, mcp, slack, cron.",- "cfg:tools": "The callable functions this agent has, by where they run.",- "cfg:skills":- "Markdown playbooks the agent loads on demand. Only the description is in the prompt until loaded.",- "cfg:mcps": "Remote MCP servers the agent connects to at session start.",- "cfg:identities":- "Identity providers an asker links against, so the agent can act AS them when a tool or MCP call needs it (per-asker, binding: principal). Admission: pick ONE as the authoritative provider to gate every session — a verified identity from it is required before any session runs (Slack, HTTP, …).",- "cfg:secrets": "Env keys this agent reads. Values are never shown.",- "cfg:limits": "Hard caps on a single run.",-};--function DetailPane({- node,- spec,- files,- ctx,-}: {- node: string;- spec: AgentSpec;- files: BundleFile[];- ctx: Ctx;-}) {- const [section, ...idParts] = node.replace(/^cfg:/, "").split("/");- const id = idParts.join("/");- const meta = nodeHeader(section, id, spec);-- return (- <div className="flex h-full min-h-0 flex-col">- <DetailHeader- icon={meta.icon}- title={meta.title}- node={node}- info={SECTION_INFO[`cfg:${section}`]}- />- <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">- <DetailBody- section={section}- id={id}- spec={spec}- files={files}- ctx={ctx}- />- </div>- </div>- );-}--function nodeHeader(- section: string,- id: string,- spec: AgentSpec,-): { icon: ReactNode; title: string } {- switch (section) {- case "model":- return { icon: <SparkleIcon {...ICON} />, title: "Model" };- case "instructions":- return { icon: <ScrollIcon {...ICON} />, title: "Instructions" };- case "triggers":- return { icon: <LightningIcon {...ICON} />, title: "Triggers" };- case "trigger": {- const type = triggerType(arr(spec.triggers)[Number(id)]);- return { icon: triggerIcon(type), title: `${type} trigger` };- }- case "tools":- return { icon: <WrenchIcon {...ICON} />, title: "Tools" };- case "tool":- return { icon: <WrenchIcon {...ICON} />, title: shortName(id) };- case "skills":- return { icon: <PuzzlePieceIcon {...ICON} />, title: "Skills" };- case "skill":- return { icon: <PuzzlePieceIcon {...ICON} />, title: id };- case "mcps":- return { icon: <HardDrivesIcon {...ICON} />, title: "MCP servers" };- case "mcp":- return { icon: <HardDrivesIcon {...ICON} />, title: id };- case "identities":- return { icon: <FingerprintIcon {...ICON} />, title: "Auth & identity" };- case "identity":- return { icon: <FingerprintIcon {...ICON} />, title: id };- case "secrets":- return { icon: <KeyIcon {...ICON} />, title: "Secrets" };- case "secret":- return { icon: <KeyIcon {...ICON} />, title: id };- case "limits":- return { icon: <GaugeIcon {...ICON} />, title: "Limits" };- default:- return { icon: <SparkleIcon {...ICON} />, title: section };- }-}--function DetailHeader({- icon,- title,- node,- info,-}: {- icon: ReactNode;- title: string;- node: string;- info?: string;-}) {- const [showInfo, setShowInfo] = useState(false);- return (- <div className="shrink-0 border-(--gray-5) border-b px-5 py-3">- <Flex align="center" gap="2">- {icon}- <Text className="font-semibold text-[14px] text-gray-12">{title}</Text>- {info ? (- <button- type="button"- onClick={() => setShowInfo((s) => !s)}- className="text-gray-10 hover:text-gray-12"- aria-label="About this section"- >- <InfoIcon size={14} />- </button>- ) : null}- <span className="ml-auto truncate rounded-(--radius-1) border border-border bg-(--gray-2) px-1.5 py-0.5 text-[10.5px] text-gray-10 [font-family:var(--font-mono)]">- {node}- </span>- </Flex>- {showInfo && info ? (- <Text className="mt-2 block text-[12px] text-gray-11 leading-snug">- {info}- </Text>- ) : null}- </div>- );-}--function DetailBody({- section,- id,- spec,- files,- ctx,-}: {- section: string;- id: string;- spec: AgentSpec;- files: BundleFile[];- ctx: Ctx;-}) {- switch (section) {- case "model":- return <ModelBody key={ctx.revisionId} spec={spec} ctx={ctx} />;- case "instructions":- return (- <BundleFileBody- file={byPath(files, "agent.md")}- emptyLabel="No agent.md in this revision."- editable={- ctx.revisionState === "draft"- ? {- idOrSlug: ctx.idOrSlug,- revisionId: ctx.revisionId,- path: "agent.md",- }- : undefined- }- />- );- case "triggers":- return <TriggersOverview spec={spec} ctx={ctx} />;- case "trigger":- return <TriggerBody trigger={arr(spec.triggers)[Number(id)]} ctx={ctx} />;- case "tools":- return <ToolsOverview spec={spec} ctx={ctx} />;- case "tool":- return (- <ToolBody- tool={findById(arr(spec.tools), id)}- files={files}- id={id}- spec={spec}- ctx={ctx}- />- );- case "skills":- return <SkillsOverview spec={spec} ctx={ctx} />;- case "skill":- return (- <SkillBody- skill={findById(arr(spec.skills), id)}- file={byPath(files, `skills/${id}/SKILL.md`)}- id={id}- ctx={ctx}- />- );- case "mcps":- return <McpsOverview spec={spec} ctx={ctx} />;- case "mcp":- return (- <McpBody mcp={findById(arr(spec.mcps), id)} spec={spec} ctx={ctx} />- );- case "identities":- return <IdentitiesOverview spec={spec} ctx={ctx} />;- case "identity":- return (- <IdentityBody- provider={findById(identityProviders(spec), id)}- id={id}- spec={spec}- ctx={ctx}- />- );- case "secrets":- return <SecretsOverview spec={spec} ctx={ctx} />;- case "secret":- return (- <SecretBody- keyName={id}- setKeys={ctx.setKeys}- idOrSlug={ctx.idOrSlug}- revisionId={ctx.revisionId}- />- );- case "limits":- return <LimitsBody spec={spec} />;- default:- return <Muted>Nothing to show.</Muted>;- }-}--function findById(items: unknown[], id: string): unknown {- return items.find((it) => str(rec(it).id) === id);-}-function byPath(files: BundleFile[], path: string): BundleFile | undefined {- return files.find((f) => f.path === path);-}--function ModelBody({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- return (- <AgentModelConfig- spec={spec}- idOrSlug={ctx.idOrSlug}- applicationId={ctx.applicationId}- revisionId={ctx.revisionId}- revisionState={ctx.revisionState}- onSelectRevision={ctx.onSelectRevision}- />- );-}--function LimitsBody({ spec }: { spec: AgentSpec }) {- const entries = Object.entries(spec.limits ?? {}).filter(- ([, v]) => v != null,- );- if (entries.length === 0) return <Muted>No limits configured.</Muted>;- return (- <Flex direction="column" gap="2">- {entries.map(([k, v]) => (- <Row key={k} label={k.replace(/_/g, " ")} value={String(v)} />- ))}- </Flex>- );-}--const TRIGGER_EXPLAINER: Record<string, string> = {- cron: "Fires on a schedule from the platform scheduler — no inbound endpoint, no inbound auth.",- slack:- "Responds to Slack mentions + thread replies for trusted workspaces. Auth is intrinsic — every request is verified by Slack request signature.",- webhook:- "A POST to the webhook endpoint starts a session — the raw JSON body becomes the first message. Callers satisfy one of the auth modes below.",- chat: "Interactive sessions over /run + /send. Every caller is authenticated per the auth modes below.",- mcp: "Exposes the agent as an MCP server over streamable-HTTP; clients authenticate per the auth modes below.",-};--const AUTH_MODE_BLURB: Record<string, string> = {- public:- "Anonymous — anyone can call. Explicitly acknowledged as public exposure.",- posthog:- "A PostHog credential (personal API key / OAuth) — end-user identity.",- jwt: "Signed JWT verified with a per-agent secret.",- shared_secret: "A shared secret sent in a named header (webhook-style).",- posthog_internal: "PostHog server-to-server internal token.",-};--const DECLARATIVE_TRIGGERS = new Set(["webhook", "chat", "mcp"]);--const TRIGGER_ENDPOINTS: Record<- string,- { method: string; path: string; blurb: string }[]-> = {- chat: [- { method: "POST", path: "/run", blurb: "start a session" },- { method: "POST", path: "/send", blurb: "send a follow-up" },- { method: "GET", path: "/listen", blurb: "stream events (SSE)" },- ],- webhook: [- {- method: "POST",- path: "/webhook",- blurb: "JSON body becomes the first message",- },- ],- mcp: [{ method: "POST", path: "/mcp", blurb: "HTTP MCP server" }],- slack: [- { method: "POST", path: "/slack/events", blurb: "Event Subscriptions URL" },- {- method: "POST",- path: "/slack/interactivity",- blurb: "Interactivity URL",- },- ],-};--function ingressBase(ctx: Ctx): string {- return (ctx.ingressBaseUrl ?? `${USAGE_HOST}/agents/${ctx.idOrSlug}`).replace(- /\/$/,- "",- );-}--function TriggersOverview({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- const triggers = arr(spec.triggers);- if (triggers.length === 0) return <Muted>No triggers configured.</Muted>;- const base = ingressBase(ctx);- const withEndpoints = triggers.filter(- (t) => TRIGGER_ENDPOINTS[triggerType(t)],- );- return (- <Flex direction="column" gap="4">- <Muted>What can start a session — {triggers.length} configured.</Muted>- <Flex direction="column" gap="2">- {triggers.map((t, i) => {- const type = triggerType(t);- const cfg = rec(rec(t).config);- const disc =- str(cfg.name) ?? str(cfg.path) ?? str(cfg.channel_id) ?? String(i);- const missing = missingSecretsFor(t, ctx.setKeys);- return (- <JumpRow- key={`${type}:${disc}`}- icon={triggerIcon(type)}- title={type}- subtitle={TRIGGER_EXPLAINER[type]}- trailing={- missing.length > 0 ? (- <WarnBadge title={`Needs: ${missing.join(", ")}`} />- ) : isPublic(t) ? (- <Badge color="amber">public</Badge>- ) : (- <Badge color="gray">private</Badge>- )- }- onClick={() => ctx.onSelect(`cfg:trigger/${i}`)}- />- );- })}- </Flex>- {withEndpoints.length > 0 ? (- <div>- <Subhead>Endpoints</Subhead>- {!ctx.ingressBaseUrl ? (- <Muted>- No public ingress URL is configured — placeholder host shown.- </Muted>- ) : null}- <Flex direction="column" gap="1" className="mt-1.5">- {withEndpoints.flatMap((t) =>- (TRIGGER_ENDPOINTS[triggerType(t)] ?? []).map((ep) => {- const url = `${base}${ep.path}`;- return (- <Flex- key={`${triggerType(t)}${ep.path}`}- align="center"- gap="2"- className="text-[11px]"- >- <span className="w-8 shrink-0 text-gray-10 [font-family:var(--font-mono)]">- {ep.method}- </span>- <code className="min-w-0 flex-1 truncate text-gray-12 [font-family:var(--font-mono)]">- {url}- </code>- <CopyButton text={url} />- </Flex>- );- }),- )}- </Flex>- </div>- ) : null}- </Flex>- );-}--// Short, operator-facing hints for the well-known trigger config fields. Keyed-// by field name (shared across trigger types); unknown fields render with no-// hint. Mirrors the field docs on `TriggerSchema` in agent-shared/src/spec.-const TRIGGER_FIELD_HINTS: Record<string, string> = {- mention_only:- "Only @-mentions start a session; plain channel messages are ignored.",- auto_resume_threads:- "Replies in an already-open thread continue without re-mentioning the bot.",- allow_workspace_participants:- "Any trusted-workspace user can advance the thread, not just the opener.",- allow_direct_messages:- "The bot also answers DMs and group DMs, not just channel mentions.",- ack_reaction:- "Emoji the bot adds the instant it receives a message, for sub-3s feedback.",- trusted_workspaces:- 'Slack workspaces allowed to invoke this agent ("*" = any workspace).',- channel_id: "The channel this trigger is scoped to.",- schedule: "Cron expression for when the job fires.",- timezone: "IANA timezone the schedule is evaluated in.",- prompt:- "The task handed to the agent as the first message when the cron fires.",- external_key: "Reuses one rolling session across firings when set.",- catch_up: "What to fire for runs missed during downtime.",- max_catch_up_age_seconds: "How far back catch-up will look for missed runs.",- name: "Stable handle for this cron job (used in session metadata).",- allow_restart:- "A /send to a closed session reopens it instead of returning 410.",- path: "URL path the webhook is mounted at.",-};--function isLongText(v: string): boolean {- return v.length > 64 || v.includes("\n");-}--/** A single trigger config field rendered by value type: booleans as on/off- * pills, string arrays as chips, long text in a block, scalars inline. */-function OptionRow({- label,- value,- hint,-}: {- label: string;- value: unknown;- hint?: string;-}) {- const human = label.replace(/_/g, " ");- if (typeof value === "boolean") {- return (- <OptionCard- label={human}- hint={hint}- trailing={- <Badge color={value ? "green" : "gray"}>{value ? "on" : "off"}</Badge>- }- />- );- }- if (Array.isArray(value)) {- const items = value.map((x) =>- typeof x === "string" ? x : JSON.stringify(x),- );- return (- <OptionCard label={human} hint={hint}>- <Flex gap="1.5" wrap="wrap">- {items.length === 0 ? (- <Text className="text-[12px] text-gray-10">none</Text>- ) : (- items.map((x, i) => (- // biome-ignore lint/suspicious/noArrayIndexKey: display-only chips; values (e.g. trusted_workspaces) can repeat- <Badge key={i} color="gray">- {x}- </Badge>- ))- )}- </Flex>- </OptionCard>- );- }- if (typeof value === "string" && isLongText(value)) {- return (- <OptionCard label={human} hint={hint}>- <Text className="block whitespace-pre-wrap text-[12.5px] text-gray-12 leading-snug">- {value}- </Text>- </OptionCard>- );- }- const display =- typeof value === "string" || typeof value === "number"- ? String(value)- : JSON.stringify(value);- return (- <OptionCard- label={human}- hint={hint}- trailing={- <Text className="truncate text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {display}- </Text>- }- />- );-}--function OptionCard({- label,- hint,- trailing,- children,-}: {- label: string;- hint?: string;- trailing?: ReactNode;- children?: ReactNode;-}) {- return (- <div className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2">- <Flex align="center" justify="between" gap="3">- <Text className="shrink-0 text-[11px] text-gray-10 uppercase tracking-wide">- {label}- </Text>- {/* No `shrink-0`: the label is shrink-0, so letting this side shrink- gives an inner `truncate` a width bound to ellipsize a long scalar- against (small trailing chips/buttons are unaffected). */}- {trailing ? <span className="min-w-0">{trailing}</span> : null}- </Flex>- {hint ? (- <Text className="mt-0.5 block text-[11px] text-gray-10 leading-snug">- {hint}- </Text>- ) : null}- {children ? <div className="mt-1.5">{children}</div> : null}- </div>- );-}--function TriggerOptions({- type,- config,-}: {- type: string;- config: Record<string, unknown>;-}) {- const entries = Object.entries(config);- if (entries.length === 0)- return <Muted>No options for the {type} trigger.</Muted>;- return (- <Flex direction="column" gap="2">- {entries.map(([k, v]) => (- <OptionRow key={k} label={k} value={v} hint={TRIGGER_FIELD_HINTS[k]} />- ))}- </Flex>- );-}--function TriggerBody({ trigger, ctx }: { trigger: unknown; ctx: Ctx }) {- const r = rec(trigger);- const type = triggerType(trigger);- const config = rec(r.config);- const modes = authModes(trigger);- const missing = missingSecretsFor(trigger, ctx.setKeys);- const cronName = type === "cron" ? str(config.name) : undefined;-- return (- <Flex direction="column" gap="3">- {TRIGGER_EXPLAINER[type] ? (- <Muted>{TRIGGER_EXPLAINER[type]}</Muted>- ) : null}-- <Row label="type" value={type} mono />-- <div>- <Subhead>Options</Subhead>- <div className="mt-1.5">- <TriggerOptions type={type} config={config} />- </div>- </div>-- {missing.length > 0 ? (- <Attention>- <Text className="text-[12px] text-gray-12">- Missing required secret{missing.length > 1 ? "s" : ""}:- </Text>- <Flex gap="1.5" wrap="wrap" className="mt-1.5">- {missing.map((key) => (- <Button- key={key}- size="1"- variant="soft"- color="amber"- onClick={() => ctx.onSelect(`cfg:secret/${key}`)}- >- Set {key}- </Button>- ))}- </Flex>- </Attention>- ) : null}-- <div>- <Subhead>Auth</Subhead>- {DECLARATIVE_TRIGGERS.has(type) ? (- modes.length > 0 ? (- <Flex direction="column" gap="1.5" className="mt-1">- {modes.map((m) => (- <Flex key={m} align="baseline" gap="2">- <Badge color={m === "public" ? "amber" : "gray"}>{m}</Badge>- <Text className="text-[11.5px] text-gray-10">- {AUTH_MODE_BLURB[m] ?? ""}- </Text>- </Flex>- ))}- </Flex>- ) : (- <Muted>No auth modes configured.</Muted>- )- ) : (- <Muted>- Intrinsic — verified by the trigger's own protocol, not- configurable.- </Muted>- )}- {isPublic(trigger) ? (- <Attention tone="warn">- This trigger is public — it accepts anonymous, unauthenticated- callers.- </Attention>- ) : null}- </div>-- {cronName ? (- <div>- <Subhead>Test</Subhead>- <CronFireButton- idOrSlug={ctx.idOrSlug}- revisionId={ctx.revisionId}- cronName={cronName}- onFired={(sessionId) => ctx.onOpenSession?.(sessionId)}- />- </div>- ) : null}-- <TriggerUsage trigger={trigger} ctx={ctx} />-- {type === "slack" ? (- <SlackSetupCard idOrSlug={ctx.idOrSlug} revisionId={ctx.revisionId} />- ) : null}- </Flex>- );-}--function authHeaderExample(modes: string[], trigger: unknown): string {- if (modes.includes("public") && modes.length === 1) return "";- if (modes.includes("shared_secret")) {- const m = (arr(rec(rec(trigger).auth).modes) as unknown[]).find(- (x) => str(rec(x).type) === "shared_secret",- );- const header = str(rec(m).header) ?? "X-Webhook-Secret";- return ` -H '${header}: <your-secret>' \\\n`;- }- if (modes.includes("posthog"))- return " -H 'Authorization: Bearer <POSTHOG_API_KEY>' \\\n";- if (modes.includes("jwt"))- return " -H 'Authorization: Bearer <SIGNED_JWT>' \\\n";- if (modes.includes("posthog_internal"))- return " -H 'x-posthog-internal: <INTERNAL_SECRET>' \\\n";- return "";-}--function TriggerUsage({ trigger, ctx }: { trigger: unknown; ctx: Ctx }) {- const type = triggerType(trigger);- const base = ingressBase(ctx);- const modes = authModes(trigger);- const authHeader = authHeaderExample(modes, trigger);- let examples: { title: string; code: string }[] = [];- if (type === "webhook") {- examples = [- {- title: "Send a webhook",- code: `curl -X POST '${base}/webhook' \\\n${authHeader} -H 'Content-Type: application/json' \\\n -d '{"message":"hello"}'`,- },- ];- } else if (type === "chat") {- examples = [- {- title: "Start a session",- code: `curl -X POST '${base}/run' \\\n${authHeader} -H 'Content-Type: application/json' \\\n -d '{"message":"hello"}'`,- },- ];- } else if (type === "mcp") {- examples = [- {- title: "Add to an MCP client",- code: `claude mcp add --transport http ${ctx.idOrSlug} '${base}/mcp'`,- },- ];- }- if (examples.length === 0) return null;- return (- <div>- <Subhead>Usage</Subhead>- <Flex direction="column" gap="2" className="mt-1">- {examples.map((ex) => (- <div key={ex.title}>- <Text className="mb-1 block text-[11px] text-gray-10">- {ex.title}- </Text>- <CodeBlock>{ex.code}</CodeBlock>- </div>- ))}- </Flex>- </div>- );-}--function ToolsOverview({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- const tools = arr(spec.tools);- if (tools.length === 0) return <Muted>No tools.</Muted>;- const counts = tools.reduce<Record<string, number>>((acc, t) => {- const kind = str(rec(t).kind) ?? "native";- acc[kind] = (acc[kind] ?? 0) + 1;- return acc;- }, {});- return (- <Flex direction="column" gap="3">- <Muted>- {Object.entries(counts)- .map(([k, n]) => `${n} ${k}`)- .join(" · ")}- </Muted>- <Flex direction="column" gap="2">- {tools.map((t) => {- const r = rec(t);- const id = toolId(t);- return (- <JumpRow- key={id}- icon={toolIcon(str(r.kind))}- title={shortName(id)}- subtitle={str(r.description)}- trailing={- r.requires_approval === true ? (- <Badge color="amber">approval</Badge>- ) : undefined- }- onClick={() => ctx.onSelect(`cfg:tool/${id}`)}- />- );- })}- </Flex>- </Flex>- );-}--/** Read `{ description, args_schema }` from a tool's schema.json bundle file,- * falling back to the spec description. v0 tool edits change source only, so we- * round-trip these unchanged on save. */-function parseToolSchema(- content: string | undefined,- fallbackDescription: string | undefined,-): { description: string; args_schema: Record<string, unknown> } {- if (content) {- try {- const parsed = JSON.parse(content) as {- description?: unknown;- args_schema?: unknown;- };- return {- description: str(parsed.description) ?? fallbackDescription ?? "",- args_schema:- parsed.args_schema && typeof parsed.args_schema === "object"- ? (parsed.args_schema as Record<string, unknown>)- : {},- };- } catch {- // Malformed schema.json — fall back below rather than block editing.- }- }- return { description: fallbackDescription ?? "", args_schema: {} };-}--function ToolBody({- tool,- files,- id,- spec,- ctx,-}: {- tool: unknown;- files: BundleFile[];- id: string;- spec: AgentSpec;- ctx: Ctx;-}) {- const r = rec(tool);- const kind = str(r.kind);- const identity = toolRequiresIdentity(tool);- const source = byPath(files, `tools/${id}/source.ts`);- const schemaFile = byPath(files, `tools/${id}/schema.json`);- const specDescription = str(r.description);- // Authoring (edit/save/dry-run) lives behind the same flag as the rest of the- // surface; custom tools are the only ones with editable source.- const authoringEnabled = useFeatureFlag(AGENT_PLATFORM_FLAG);- const isCustom = kind === "custom" || !!source;- const isDraft = ctx.revisionState === "draft";- const canAuthor = authoringEnabled && isCustom && isDraft;- const schema = useMemo(- () => parseToolSchema(schemaFile?.content, specDescription),- [schemaFile?.content, specDescription],- );- return (- <Flex direction="column" gap="2">- <Row label="id" value={id} mono />- {kind ? <Row label="kind" value={kind} /> : null}- <Row- label="approval"- value={- r.requires_approval === true- ? "required before each call"- : "not gated"- }- />- {specDescription ? (- <Text className="text-[12.5px] text-gray-11 leading-snug">- {specDescription}- </Text>- ) : null}- {identity ? (- <IdentityLink provider={identity} spec={spec} ctx={ctx} />- ) : null}- {source ? (- <ToolSourcePanel- // Remount on revision/tool switch so the buffer + toggles reset.- key={`${ctx.revisionId}:${id}`}- idOrSlug={ctx.idOrSlug}- revisionId={ctx.revisionId}- toolId={id}- source={source}- description={schema.description}- argsSchema={schema.args_schema}- canEdit={canAuthor}- canDryRun={authoringEnabled && isCustom}- />- ) : null}- </Flex>- );-}--/** A back-link from a tool/MCP to the identity provider it acts as. Warns when- * the referenced provider id isn't declared in `spec.identity_providers[]`. */-function IdentityLink({- provider,- spec,- ctx,-}: {- provider: string;- spec: AgentSpec;- ctx: Ctx;-}) {- const declared = identityProviders(spec).some(- (p) => providerId(p) === provider,- );- return (- <div>- <Subhead>Acts as identity</Subhead>- <div className="mt-1">- <JumpRow- icon={<FingerprintIcon {...ICON} />}- title={provider}- mono- subtitle={- declared- ? "per-asker linked identity"- : "not declared in identities"- }- trailing={- declared ? undefined : <Badge color="amber">undeclared</Badge>- }- onClick={() => ctx.onSelect(`cfg:identity/${provider}`)}- />- </div>- </div>- );-}--function SkillsOverview({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- const skills = arr(spec.skills);- if (skills.length === 0) return <Muted>No skills.</Muted>;- return (- <Flex direction="column" gap="3">- <Muted>- Markdown playbooks loaded on demand — {skills.length} here. Only the- description is in the prompt until a skill is loaded.- </Muted>- <Flex direction="column" gap="2">- {skills.map((s) => {- const r = rec(s);- const id = str(r.id) ?? str(r.path) ?? "skill";- return (- <JumpRow- key={id}- icon={<PuzzlePieceIcon {...ICON} />}- title={id}- subtitle={str(r.description)}- onClick={() => ctx.onSelect(`cfg:skill/${id}`)}- />- );- })}- </Flex>- </Flex>- );-}--function SkillBody({- skill,- file,- id,- ctx,-}: {- skill: unknown;- file: BundleFile | undefined;- id: string;- ctx: Ctx;-}) {- const r = rec(skill);- const skillId = str(r.id) ?? id;- const path = `skills/${skillId}/SKILL.md`;- return (- <Flex direction="column" gap="2">- <Row label="id" value={skillId} mono />- <Text className="text-[12.5px] text-gray-11 leading-snug">- {str(r.description) ?? "No description."}- </Text>- <div className="mt-2">- <Subhead>body · {path}</Subhead>- <BundleFileBody- file={file}- emptyLabel="Body not in the loaded bundle."- editable={- ctx.revisionState === "draft"- ? {- idOrSlug: ctx.idOrSlug,- revisionId: ctx.revisionId,- path,- }- : undefined- }- />- </div>- </Flex>- );-}--function McpsOverview({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- const mcps = arr(spec.mcps);- const { installations, connectCustom, connectCustomPending } =- useMcpConnect();- const applySpec = useApplyAgentSpec(ctx.idOrSlug, ctx.applicationId);- const [showAdd, setShowAdd] = useState(false);- const canEdit = !!ctx.revisionState;-- // Append a new mcps[] entry referencing the chosen connection (id derived- // from its name, url filled from the installation), then select it.- const addFromConnection = (installId: string) => {- const install = (installations ?? []).find((i) => i.id === installId);- if (!install || !ctx.revisionState) return;- const base =- (install.display_name || install.url || "mcp")- .toLowerCase()- .replace(/[^a-z0-9]+/g, "-")- .replace(/^-+|-+$/g, "")- .slice(0, 32) || "mcp";- const taken = new Set(mcps.map((m) => str(rec(m).id)));- let newId = base;- for (let n = 2; taken.has(newId); n++) newId = `${base}-${n}`;- const entry = {- id: newId,- url: install.url ?? "",- connection: install.id,- secrets: [] as string[],- // Safe-by-default: every tool parks for approval until the owner relaxes- // specific ones. Activates the per-agent permission model (vs the legacy- // allowlist) so the runtime + the detail UI agree from the first save.- default_tool_approval: "approve" as const,- };- applySpec.mutate(- {- revision: { id: ctx.revisionId, state: ctx.revisionState },- spec: { ...spec, mcps: [...mcps, entry] },- },- {- onSuccess: (rev) => {- if (rev.id !== ctx.revisionId) ctx.onSelectRevision?.(rev.id);- ctx.onSelect(`cfg:mcp/${newId}`);- },- onError: (e) => toast.error(e.message || "Failed to add MCP server"),- },- );- };-- return (- <Flex direction="column" gap="2">- {mcps.length === 0 ? (- <Muted>No MCP servers declared.</Muted>- ) : (- mcps.map((m) => {- const r = rec(m);- const id = str(r.id) ?? "mcp";- const missing = mcpMissingSecrets(m, ctx.setKeys);- return (- <JumpRow- key={id}- icon={<HardDrivesIcon {...ICON} />}- title={id}- subtitle={str(r.connection) ? "shared connection" : str(r.url)}- trailing={- missing.length > 0 ? (- <WarnBadge title={`Needs: ${missing.join(", ")}`} />- ) : undefined- }- onClick={() => ctx.onSelect(`cfg:mcp/${id}`)}- />- );- })- )}- {canEdit ? (- <Flex align="center" gap="2" className="mt-1" wrap="wrap">- {(installations ?? []).length > 0 ? (- <Select.Root- value=""- onValueChange={addFromConnection}- disabled={applySpec.isPending}- >- <Select.Trigger- placeholder="+ Add from a connection"- className="min-w-[220px]"- />- <Select.Content>- {(installations ?? []).map((i) => (- <Select.Item key={i.id} value={i.id}>- {i.display_name || i.url || i.id}- </Select.Item>- ))}- </Select.Content>- </Select.Root>- ) : (- <Muted>No connected MCP servers yet.</Muted>- )}- <Button- size="1"- variant="soft"- onClick={() => setShowAdd(true)}- disabled={connectCustomPending}- >- Connect new- </Button>- </Flex>- ) : null}- <AddCustomServerDialog- open={showAdd}- pending={connectCustomPending}- onOpenChange={setShowAdd}- onSubmit={(values) => {- connectCustom(values);- setShowAdd(false);- }}- />- </Flex>- );-}--function McpBody({- mcp,- spec,- ctx,-}: {- mcp: unknown;- spec: AgentSpec;- ctx: Ctx;-}) {- const r = rec(mcp);- const id = str(r.id) ?? "mcp";- const tools = arr(r.tools);- const missing = mcpMissingSecrets(mcp, ctx.setKeys);- const provider = mcpProvider(mcp);- const connection = str(r.connection);- const providers = identityProviders(spec);- // `spec.mcps[].kind` is the authoritative, explicit credential model.- // Fall back to inferring from the credential fields for any legacy entry- // written before `kind` was required.- const declaredKind = str(r.kind);- const authMode: "agent" | "principal" =- declaredKind === "agent" || declaredKind === "principal"- ? declaredKind- : connection- ? "agent"- : "principal";- // Whether the chosen `auth.provider` is actually declared in- // `spec.identity_providers[]` — drives the preview card's status/badge.- const identityDeclared =- !!provider && providers.some((p) => providerId(p) === provider);-- const {- installations,- installationsLoading,- connectCustom,- connectCustomPending,- } = useMcpConnect();- const applySpec = useApplyAgentSpec(ctx.idOrSlug, ctx.applicationId);- const [showAdd, setShowAdd] = useState(false);- const canEdit = !!ctx.revisionState;- const saving = applySpec.isPending;-- // Live tool catalog for an agent-level shared connection — the connection id- // IS the mcp_store installation id, so we can list its tools and show a- // per-tool permission against each. A principal-level (auth.provider) MCP has- // no installation here, so `connection` is null and this stays empty.- const { tools: catalogTools, isLoading: catalogLoading } =- useMcpInstallationTools(connection ?? null, { autoRefreshIfEmpty: true });- // Per-agent override level keyed by remote tool name, plus the connection-wide- // default. Effective level per tool = override ?? default.- const overrides = toolLevelOverrides(r);- const defaultLevel = toToolApprovalLevel(r.default_tool_approval);- const effectiveDefault = defaultLevel ?? DEFAULT_TOOL_APPROVAL;- // Project the live catalog into the shared list's vocabulary: each tool's- // displayed state is its override (if any) resolved against the default. The- // panel is permission-agnostic, so the override/default math stays here.- const displayTools: McpInstallationTool[] = catalogTools.map((t) => ({- ...t,- approval_state:- LEVEL_TO_APPROVAL[overrides.get(t.tool_name) ?? effectiveDefault],- }));-- // Rebuild the full spec with this mcps[] entry transformed, then draft-branch- // (if needed) + PATCH. Lands on (and selects) a new draft off a non-draft.- // Destructure the ctx fields the callback reads so the dep array is stable —- // `ctx` is a fresh object literal on every parent render, which would- // otherwise change identity each time and defeat the useCallback memoization.- const { revisionId, revisionState, onSelectRevision } = ctx;- const apply = useCallback(- (mutate: (entry: Record<string, unknown>) => Record<string, unknown>) => {- if (!revisionState) return;- const nextMcps = arr(spec.mcps).map((m) =>- (str(rec(m).id) ?? "mcp") === id ? mutate(rec(m)) : m,- );- applySpec.mutate(- {- revision: { id: revisionId, state: revisionState },- spec: { ...spec, mcps: nextMcps },- },- {- onSuccess: (rev) => {- if (rev.id !== revisionId) onSelectRevision?.(rev.id);- },- onError: (e) => toast.error(e.message || "Failed to save"),- },- );- },- [applySpec, revisionId, revisionState, onSelectRevision, id, spec],- );-- const setConnection = (value: string) => {- if (value === "none") {- apply((entry) => {- const next: Record<string, unknown> = { ...entry, kind: "agent" };- delete next.connection;- return next;- });- return;- }- const install = (installations ?? []).find((i) => i.id === value);- apply((entry) => ({- ...entry,- kind: "agent",- connection: value,- url: install?.url ?? entry.url,- }));- };-- // Switch the credential model. The two are mutually exclusive (enforced by- // the spec schema), so flipping clears the other side: → agent drops the- // per-asker identity (pick a connection next); → principal drops the shared- // connection and wires an identity provider (defaults to the current one,- // else the first declared).- const setAuthMode = (next: "agent" | "principal") => {- if (next === "agent") {- apply((entry) => {- const n: Record<string, unknown> = { ...entry, kind: "agent" };- delete n.auth;- return n;- });- return;- }- const fallback =- provider ?? (providers[0] ? providerId(providers[0]) : undefined);- apply((entry) => {- const n: Record<string, unknown> = { ...entry, kind: "principal" };- delete n.connection;- if (fallback) n.auth = { ...rec(entry.auth), provider: fallback };- return n;- });- };-- const setIdentityProvider = (value: string) => {- apply((entry) => ({- ...entry,- kind: "principal",- auth: { ...rec(entry.auth), provider: value },- }));- };-- const setToolApproval = (toolName: string, requiresApproval: boolean) => {- apply((entry) => ({- ...entry,- tools: arr(entry.tools).map((t) => {- const name = typeof t === "string" ? t : (str(rec(t).name) ?? "");- if (name !== toolName) return t;- const base = typeof t === "object" ? rec(t) : {};- return { ...base, name, requires_approval: requiresApproval };- }),- }));- };-- // Set the connection-wide default permission (allow / approve / deny). Setting- // it activates the per-agent model on this entry (the runner stops treating- // tools[] as a legacy allowlist).- const setDefaultLevel = (level: ToolApprovalLevel) => {- apply((entry) => ({ ...entry, default_tool_approval: level }));- };-- // Override one tool's permission. Dropping it back to the connection default- // removes the override so the spec stays minimal (no entry ⇒ inherits default).- const setToolLevel = (toolName: string, level: ToolApprovalLevel) => {- apply((entry) => {- const others = arr(entry.tools).filter(- (t) => (typeof t === "string" ? t : str(rec(t).name)) !== toolName,- );- const tools =- level === effectiveDefault- ? others- : [...others, { name: toolName, level }];- return {- ...entry,- default_tool_approval: entry.default_tool_approval ?? effectiveDefault,- tools,- };- });- };-- // Drop this whole mcps[] entry from the spec and return to the list. The- // shared connection (the mcp_store installation) is untouched — only the- // agent's reference to it goes away.- const removeMcp = () => {- if (!revisionState) return;- const nextMcps = arr(spec.mcps).filter(- (m) => (str(rec(m).id) ?? "mcp") !== id,- );- applySpec.mutate(- {- revision: { id: revisionId, state: revisionState },- spec: { ...spec, mcps: nextMcps },- },- {- onSuccess: (rev) => {- if (rev.id !== revisionId) onSelectRevision?.(rev.id);- ctx.onSelect("cfg:mcps");- },- onError: (e) => toast.error(e.message || "Failed to remove MCP server"),- },- );- };-- const connectionMissing =- !!connection && !(installations ?? []).some((i) => i.id === connection);-- return (- <Flex direction="column" gap="3">- <Flex align="center" justify="between" gap="2">- <Select.Root- value={authMode}- onValueChange={(v) => setAuthMode(v as "agent" | "principal")}- disabled={!canEdit || saving}- >- <Select.Trigger className="min-w-60" />- <Select.Content>- <Select.Item value="agent">- Agent-level — shared credential- </Select.Item>- <Select.Item value="principal">- Principal-level — per-asker identity- </Select.Item>- </Select.Content>- </Select.Root>- {canEdit ? (- <Button- size="1"- variant="soft"- color="red"- onClick={removeMcp}- disabled={saving}- >- <TrashIcon size={12} />- Remove server- </Button>- ) : null}- </Flex>- <Muted>- {authMode === "agent"- ? "One shared credential every asker reuses — an OAuth/API-key connection, or a bring-your-own token."- : "Each asker acts as themselves through a linked identity provider."}- </Muted>-- {authMode === "agent" ? (- <div>- <Subhead>Connection</Subhead>- <Muted>- One shared credential an owner connects once (OAuth or API key) and- every asker reuses — askers never sign in. Leave unset to bring your- own token via secrets + headers.- </Muted>- <Flex align="center" gap="2" className="mt-1.5">- <Select.Root- value={connection ?? "none"}- onValueChange={setConnection}- disabled={!canEdit || saving || installationsLoading}- >- <Select.Trigger- placeholder="No connection"- className="min-w-[220px]"- />- <Select.Content>- <Select.Item value="none">No connection</Select.Item>- {(installations ?? []).map((i) => (- <Select.Item key={i.id} value={i.id}>- {i.display_name || i.url || i.id}- </Select.Item>- ))}- </Select.Content>- </Select.Root>- <Button- size="1"- variant="soft"- onClick={() => setShowAdd(true)}- disabled={connectCustomPending}- >- Connect new- </Button>- </Flex>- {connectionMissing ? (- <Text className="mt-1 block text-[12px] text-amber-11">- Referenced connection isn't in this project — reconnect it or pick- another.- </Text>- ) : null}- </div>- ) : (- <div>- <Subhead>Acts as identity</Subhead>- <Muted>- Each asker connects as themselves through this identity provider —- required for principal-level. Manage providers in the identities- section.- </Muted>- {providers.length > 0 ? (- <Flex direction="column" gap="2" className="mt-1.5">- <Select.Root- value={provider}- onValueChange={setIdentityProvider}- disabled={!canEdit || saving}- >- <Select.Trigger- placeholder="Choose an identity"- className="min-w-60"- />- <Select.Content>- {providers.map((p) => {- const pid = providerId(p);- return (- <Select.Item key={pid} value={pid}>- <Flex align="center" gap="2">- <FingerprintIcon {...ICON} />- {pid}- </Flex>- </Select.Item>- );- })}- </Select.Content>- </Select.Root>- {provider ? (- <JumpRow- icon={<FingerprintIcon {...ICON} />}- title={provider}- mono- subtitle={- identityDeclared- ? "per-asker linked identity — each asker connects as themselves"- : "not declared in identities"- }- trailing={- identityDeclared ? undefined : (- <Badge color="amber">undeclared</Badge>- )- }- onClick={() => ctx.onSelect(`cfg:identity/${provider}`)}- />- ) : (- <Text className="block text-[12px] text-amber-11">- Principal-level needs a linked identity — choose one above.- </Text>- )}- </Flex>- ) : (- <Attention>- <Text className="text-[12px] text-gray-12">- No identity providers declared. Add one in the identities- section to use principal-level auth.- </Text>- <Flex className="mt-1.5">- <Button- size="1"- variant="soft"- color="amber"- onClick={() => ctx.onSelect("cfg:identities")}- >- Manage identities- </Button>- </Flex>- </Attention>- )}- </div>- )}-- <AddCustomServerDialog- open={showAdd}- pending={connectCustomPending}- onOpenChange={setShowAdd}- onSubmit={(values) => {- connectCustom(values);- setShowAdd(false);- }}- />-- {str(r.url) ? (- <Row label="url" value={str(r.url) as string} mono />- ) : null}- {!connection && missing.length > 0 ? (- <Attention>- <Text className="text-[12px] text-gray-12">- Missing secret{missing.length > 1 ? "s" : ""}:- </Text>- <Flex gap="1.5" wrap="wrap" className="mt-1.5">- {missing.map((key) => (- <Button- key={key}- size="1"- variant="soft"- color="amber"- onClick={() => ctx.onSelect(`cfg:secret/${key}`)}- >- Set {key}- </Button>- ))}- </Flex>- </Attention>- ) : null}-- {connection ? (- <div>- <Subhead>Tool permissions</Subhead>- <Muted>- The default applies to every tool this server exposes; override- individual tools below. Allow = runs automatically · Approve = asks- the approver each call · Deny = hidden from the agent.- </Muted>- <Attention>- <Text className="text-[12px] text-gray-12">- These settings govern this agent. The connection owner's approval- marks are informational — they aren't enforced for this agent.- </Text>- </Attention>- <div className="mt-2">- <ToolPermissionList- tools={displayTools}- isLoading={catalogLoading}- disabled={!canEdit || saving}- defaultControl={{- value: LEVEL_TO_APPROVAL[effectiveDefault],- onChange: (v) => setDefaultLevel(APPROVAL_TO_LEVEL[v]),- }}- onSetTool={(name, state) =>- setToolLevel(name, APPROVAL_TO_LEVEL[state])- }- emptyTitle="No tools discovered yet."- emptyHint="They appear once the connection is verified."- />- </div>- </div>- ) : (- <div>- <Subhead>Tools · {tools.length}</Subhead>- {tools.length === 0 ? (- <Muted>No tools selected from this server.</Muted>- ) : (- <Flex direction="column" gap="1.5" className="mt-1">- {tools.map((t) => {- const name =- typeof t === "string" ? t : (str(rec(t).name) ?? "tool");- const requiresApproval =- typeof t === "object" && rec(t).requires_approval === true;- return (- <Flex- key={name}- align="center"- gap="2"- className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-3 py-2"- >- <Text className="min-w-0 flex-1 truncate text-[12px] text-gray-12 [font-family:var(--font-mono)]">- {name}- </Text>- <Text className="text-[11px] text-gray-10">- Requires approval- </Text>- <Switch- size="1"- checked={requiresApproval}- onCheckedChange={(v) => setToolApproval(name, v === true)}- disabled={!canEdit || saving}- />- </Flex>- );- })}- </Flex>- )}- </div>- )}- </Flex>- );-}--function providerSummary(p: unknown, used: number): string {- const r = rec(p);- const binding = str(r.binding) === "agent" ? "shared (agent)" : "per-asker";- const parts = [str(r.kind), binding].filter(Boolean) as string[];- parts.push(used === 0 ? "unused" : `${used} consumer${used > 1 ? "s" : ""}`);- return parts.join(" · ");-}--// Both identity components apply a full-spec PATCH the same way — same mutation,-// same success (auto-jump to a newly branched draft) and error handling — so-// share the wiring. The default error string is the only thing that differs.-function useSaveIdentitySpec(ctx: Ctx, defaultError: string) {- const applySpec = useApplyAgentSpec(ctx.idOrSlug, ctx.applicationId);- const saveSpec = (next: AgentSpec, onDone?: () => void) => {- if (!ctx.revisionState) return;- applySpec.mutate(- {- revision: { id: ctx.revisionId, state: ctx.revisionState },- spec: next,- },- {- onSuccess: (rev) => {- if (rev.id !== ctx.revisionId) ctx.onSelectRevision?.(rev.id);- onDone?.();- },- onError: (e) => toast.error(e.message || defaultError),- },- );- };- return { saveSpec, saving: applySpec.isPending };-}--function IdentitiesOverview({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- const providers = identityProviders(spec);- const { saveSpec, saving } = useSaveIdentitySpec(- ctx,- "Failed to save identity providers",- );- const canEdit = !!ctx.revisionState;- const authoritative = authoritativeProviderId(spec);- const [showOauth, setShowOauth] = useState(false);- const hasPosthog = providers.some((p) => str(rec(p).kind) === "posthog");-- // The PATCH replaces `spec` wholesale, so omit the key to clear it.- const setAuthoritative = (value: string) => {- const next: AgentSpec = { ...spec };- if (value && value !== NONE_PROVIDER) next.authoritative_provider = value;- else delete next.authoritative_provider;- saveSpec(next);- };-- const addPosthog = () => {- if (hasPosthog) return;- saveSpec(- {- ...spec,- identity_providers: [- ...providers,- { kind: "posthog", id: "posthog", binding: "principal", scopes: [] },- ],- },- () => ctx.onSelect("cfg:identity/posthog"),- );- };-- const addOauth2 = (entry: Record<string, unknown>) => {- saveSpec({ ...spec, identity_providers: [...providers, entry] }, () => {- setShowOauth(false);- ctx.onSelect(`cfg:identity/${providerId(entry)}`);- });- };-- const authEntry = authoritative- ? providers.find((p) => providerId(p) === authoritative)- : undefined;- const authInvalid =- !!authoritative && (!authEntry || !establishesIdentity(authEntry));-- return (- <Flex direction="column" gap="4">- <div>- <Subhead>Admission</Subhead>- <Text className="mt-1 mb-2 block text-[12px] text-gray-10 leading-snug">- Gate every session on a verified identity from one provider. When set,- an unauthenticated Slack/HTTP request is handed an authorize link and- no session runs until it resolves. Unset = the transport claim is the- identity (passthrough / public).- </Text>- {canEdit ? (- <Select.Root- value={authoritative ?? NONE_PROVIDER}- onValueChange={setAuthoritative}- disabled={saving}- >- <Select.Trigger className="min-w-[260px]" />- <Select.Content>- <Select.Item value={NONE_PROVIDER}>- None — transport identity- </Select.Item>- {providers.map((p) => {- const id = providerId(p);- const ok = establishesIdentity(p);- return (- <Select.Item key={id} value={id} disabled={!ok}>- {id}- {ok ? "" : " — can't prove a subject"}- </Select.Item>- );- })}- </Select.Content>- </Select.Root>- ) : (- <Row- label="authoritative"- value={authoritative ?? "none (transport identity)"}- mono- />- )}- {authInvalid ? (- <Attention tone="warn">- <Text className="text-[12px] text-gray-12">- Authoritative provider{" "}- <code className="[font-family:var(--font-mono)]">- {authoritative}- </code>{" "}- {authEntry- ? "can't prove a subject — use kind posthog, or oauth2 with a userinfo_url."- : "isn't declared in identity_providers."}{" "}- Admission will fail at runtime.- </Text>- </Attention>- ) : null}- </div>-- <div>- <Subhead>Providers · {providers.length}</Subhead>- {providers.length === 0 ? (- <Muted>No identity providers declared.</Muted>- ) : (- <Flex direction="column" gap="2" className="mt-1.5">- {providers.map((p) => {- const id = providerId(p);- const used = consumerCount(identityConsumers(spec, id));- const isAuth = id === authoritative;- return (- <JumpRow- key={id}- icon={<FingerprintIcon {...ICON} />}- title={id}- mono- subtitle={providerSummary(p, used)}- trailing={- isAuth ? (- <Badge color="iris">authoritative</Badge>- ) : used === 0 ? (- <Badge color="amber">unused</Badge>- ) : undefined- }- onClick={() => ctx.onSelect(`cfg:identity/${id}`)}- />- );- })}- </Flex>- )}- </div>-- {canEdit ? (- <Flex align="center" gap="2" wrap="wrap">- {!hasPosthog ? (- <Button- size="1"- variant="soft"- onClick={addPosthog}- disabled={saving}- >- Add PostHog identity- </Button>- ) : null}- <Button- size="1"- variant="soft"- onClick={() => setShowOauth((v) => !v)}- disabled={saving}- >- {showOauth ? "Cancel" : "Add OAuth2 provider"}- </Button>- </Flex>- ) : null}-- {showOauth && canEdit ? (- <AddOauth2ProviderForm- existingIds={providers.map((p) => providerId(p))}- pending={saving}- onAdd={addOauth2}- />- ) : null}- </Flex>- );-}--// userinfo_url is what lets an oauth2 provider be picked as authoritative.-// The form intentionally omits `client_secret`: it's a secret, so it lives in-// the agent's secret store (referenced by env-key via the top-level `secrets`-// list, not inlined on the provider entry) and is looked up server-side at-// token-exchange time. See posthog PR #66050 for the admission spec.-function AddOauth2ProviderForm({- existingIds,- pending,- onAdd,-}: {- existingIds: string[];- pending: boolean;- onAdd: (entry: Record<string, unknown>) => void;-}) {- const [id, setId] = useState("");- const [authorizeUrl, setAuthorizeUrl] = useState("");- const [tokenUrl, setTokenUrl] = useState("");- const [clientId, setClientId] = useState("");- const [userinfoUrl, setUserinfoUrl] = useState("");- const [scopes, setScopes] = useState("");-- const trimmedId = id.trim();- const duplicate = existingIds.includes(trimmedId);- const valid =- !!trimmedId &&- !duplicate &&- !!authorizeUrl.trim() &&- !!tokenUrl.trim() &&- !!clientId.trim();-- const submit = () => {- if (!valid) return;- const entry: Record<string, unknown> = {- kind: "oauth2",- id: trimmedId,- binding: "principal",- authorize_url: authorizeUrl.trim(),- token_url: tokenUrl.trim(),- client_id: clientId.trim(),- scopes: scopes- .split(/[\s,]+/)- .map((s) => s.trim())- .filter(Boolean),- };- const ui = userinfoUrl.trim();- if (ui) entry.userinfo_url = ui;- onAdd(entry);- };-- const field = (- label: string,- value: string,- set: (v: string) => void,- placeholder: string,- ) => (- <div className="flex flex-col gap-1">- <Text className="text-[11px] text-gray-10 uppercase tracking-wide">- {label}- </Text>- <TextField.Root- value={value}- onChange={(e) => set(e.target.value)}- placeholder={placeholder}- size="1"- />- </div>- );-- return (- <Flex- direction="column"- gap="2.5"- className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-3"- >- {field("id", id, setId, "e.g. google")}- {duplicate ? (- <Text className="text-[11px] text-amber-11">- A provider with this id already exists.- </Text>- ) : null}- {field(- "authorize url",- authorizeUrl,- setAuthorizeUrl,- "https://accounts.google.com/o/oauth2/v2/auth",- )}- {field(- "token url",- tokenUrl,- setTokenUrl,- "https://oauth2.googleapis.com/token",- )}- {field("client id", clientId, setClientId, "the OAuth app client id")}- {field(- "userinfo url (required to be authoritative)",- userinfoUrl,- setUserinfoUrl,- "https://openidconnect.googleapis.com/v1/userinfo",- )}- {field("scopes", scopes, setScopes, "space or comma separated")}- <Flex justify="end">- <Button- size="1"- variant="solid"- onClick={submit}- disabled={!valid || pending}- >- Add provider- </Button>- </Flex>- </Flex>- );-}--function IdentityBody({- provider,- id,- spec,- ctx,-}: {- provider: unknown;- id: string;- spec: AgentSpec;- ctx: Ctx;-}) {- const r = rec(provider);- const declared = provider != null;- const kind = str(r.kind);- const binding = str(r.binding) ?? "principal";- const scopes = arr(r.scopes).filter(- (s): s is string => typeof s === "string",- );- const consumers = identityConsumers(spec, id);- const used = consumerCount(consumers);- const authoritative = authoritativeProviderId(spec);- const isAuth = declared && id === authoritative;- const establishes = establishesIdentity(provider);- const { saveSpec, saving } = useSaveIdentitySpec(- ctx,- "Failed to save identity provider",- );- const canEdit = !!ctx.revisionState;-- const setAuthoritative = (on: boolean) => {- const next: AgentSpec = { ...spec };- if (on) next.authoritative_provider = id;- else delete next.authoritative_provider;- saveSpec(next);- };- const removeProvider = () => {- const next: AgentSpec = {- ...spec,- identity_providers: identityProviders(spec).filter(- (p) => providerId(p) !== id,- ),- };- if (authoritative === id) delete next.authoritative_provider;- saveSpec(next, () => ctx.onSelect("cfg:identities"));- };-- return (- <Flex direction="column" gap="3">- {!declared ? (- <Attention tone="warn">- <Text className="text-[12px] text-gray-12">- A tool or MCP references identity{" "}- <code className="[font-family:var(--font-mono)]">{id}</code>, but it- isn't declared in <code>identity_providers</code>. Linking will fail- at runtime.- </Text>- </Attention>- ) : null}-- <Flex direction="column" gap="2">- <Row label="id" value={id} mono />- {kind ? <Row label="kind" value={kind} /> : null}- <Row- label="binding"- value={- binding === "agent"- ? "agent — one shared link (not yet enforced)"- : "principal — one link per asker"- }- />- {str(r.authorize_url) ? (- <Row- label="authorize url"- value={str(r.authorize_url) as string}- mono- />- ) : null}- {str(r.client_id) ? (- <Row label="client id" value={str(r.client_id) as string} mono />- ) : null}- </Flex>-- {declared ? (- <div>- <Subhead>Admission</Subhead>- {isAuth ? (- <Attention>- <Text className="text-[12px] text-gray-12">- Authoritative provider — every session must resolve a verified- identity here before it runs.- </Text>- </Attention>- ) : (- <Muted>- {establishes- ? "Make this the authoritative provider to gate every session on it."- : "Can't be authoritative — it doesn't prove a subject (needs kind posthog, or oauth2 with a userinfo_url)."}- </Muted>- )}- {canEdit ? (- <Flex gap="2" className="mt-2" wrap="wrap">- {isAuth ? (- <Button- size="1"- variant="soft"- onClick={() => setAuthoritative(false)}- disabled={saving}- >- Clear authoritative- </Button>- ) : (- <Button- size="1"- variant="soft"- onClick={() => setAuthoritative(true)}- disabled={saving || !establishes}- >- Make authoritative- </Button>- )}- </Flex>- ) : null}- </div>- ) : null}-- {scopes.length > 0 ? (- <div>- <Subhead>Scopes</Subhead>- <Flex gap="1.5" wrap="wrap" className="mt-1.5">- {scopes.map((s) => (- <Badge key={s} color="gray">- {s}- </Badge>- ))}- </Flex>- </div>- ) : null}-- <div>- <Subhead>Used by · {used}</Subhead>- {used === 0 ? (- <Muted>No custom tool or MCP server declares this provider.</Muted>- ) : (- <Flex direction="column" gap="1.5" className="mt-1">- {consumers.tools.map((tid) => (- <JumpRow- key={`tool:${tid}`}- icon={<WrenchIcon {...ICON} />}- title={shortName(tid)}- subtitle="custom tool"- onClick={() => ctx.onSelect(`cfg:tool/${tid}`)}- />- ))}- {consumers.mcps.map((mid) => (- <JumpRow- key={`mcp:${mid}`}- icon={<HardDrivesIcon {...ICON} />}- title={mid}- subtitle="MCP server"- onClick={() => ctx.onSelect(`cfg:mcp/${mid}`)}- />- ))}- </Flex>- )}- <Text className="mt-2 block text-[11px] text-gray-10 leading-snug">- Native{" "}- <span className="[font-family:var(--font-mono)]">@posthog/*</span>{" "}- tools declare their provider intrinsically and aren't listed here.- </Text>- </div>-- {canEdit && declared ? (- <Flex justify="end">- <Button- size="1"- variant="soft"- onClick={removeProvider}- disabled={saving}- >- <TrashIcon size={13} /> Remove provider- </Button>- </Flex>- ) : null}- </Flex>- );-}--function SecretsOverview({ spec, ctx }: { spec: AgentSpec; ctx: Ctx }) {- const keys = allSecretKeys(spec, ctx.setKeys);- if (keys.length === 0) return <Muted>No secrets declared.</Muted>;- return (- <Flex direction="column" gap="3">- <Muted>Env keys this agent reads. Values are never shown.</Muted>- <Flex direction="column" gap="2">- {keys.map((key) => (- <JumpRow- key={key}- icon={<KeyIcon {...ICON} />}- title={key}- mono- trailing={- ctx.setKeys.includes(key) ? (- <Badge color="green">set</Badge>- ) : (- <Badge color="amber">not set</Badge>- )- }- onClick={() => ctx.onSelect(`cfg:secret/${key}`)}- />- ))}- </Flex>- </Flex>- );-}--function SecretBody({- keyName,- setKeys,- idOrSlug,- revisionId,-}: {- keyName: string;- setKeys: string[];- idOrSlug: string;- revisionId: string;-}) {- const isSet = setKeys.includes(keyName);- return (- <Flex direction="column" gap="2">- <Row label="key" value={keyName} mono />- <Row- label="status"- value={isSet ? "set" : "not set"}- valueColor={isSet ? "var(--green-11)" : "var(--amber-11)"}- />- <SecretEditor- idOrSlug={idOrSlug}- revisionId={revisionId}- keyName={keyName}- isSet={isSet}- />- </Flex>- );-}--interface EditableBundle {- idOrSlug: string;- revisionId: string;- /** Canonical bundle path written through the per-file PUT endpoint. */- path: string;-}--function BundleFileBody({- file,- emptyLabel = "Not in the loaded bundle.",- editable,-}: {- file: BundleFile | undefined;- emptyLabel?: string;- editable?: EditableBundle;-}) {- if (editable) {- return (- <EditableMarkdownBody- // Remount when the user picks a different file so we start fresh- // instead of carrying draft/edit state across paths via an effect.- key={editable.path}- file={file}- emptyLabel={emptyLabel}- editable={editable}- />- );- }- if (!file) return <Muted>{emptyLabel}</Muted>;- if (file.language === "markdown") {- return (- <div className="text-[13px]">- <MarkdownRenderer content={file.content} />- </div>- );- }- return <CodeBlock>{file.content}</CodeBlock>;-}--/**- * Edit/view toggle backed by the per-file PUT endpoint. Used for `agent.md`- * and `skills/<id>/SKILL.md` on draft revisions. Tool source / schema stay on- * the read-only branch above. When `file` is undefined (e.g. a skill scaffold- * with no body yet) we still let the user write fresh content for `path`.- */-function EditableMarkdownBody({- file,- emptyLabel,- editable,-}: {- file: BundleFile | undefined;- emptyLabel: string;- editable: EditableBundle;-}) {- const initial = file?.content ?? "";- const [editing, setEditing] = useState(false);- const [draft, setDraft] = useState(initial);- const [syncedInitial, setSyncedInitial] = useState(initial);- const mutation = useUpdateAgentDraftBundleFile(- editable.idOrSlug,- editable.revisionId,- );-- // Pull in upstream content changes (initial bundle load, post-save refetch)- // during render rather than via an effect, but only while the user isn't- // actively editing — otherwise an unrelated refetch (e.g. a concurrent bulk- // import) would silently wipe their draft. File-switch resets are handled by- // `key={editable.path}` at the call site.- if (initial !== syncedInitial && !editing) {- setSyncedInitial(initial);- setDraft(initial);- }-- if (!editing) {- return (- <Flex direction="column" gap="2">- <Flex justify="end">- <Button- size="1"- variant="soft"- color="gray"- onClick={() => setEditing(true)}- >- Edit- </Button>- </Flex>- {file ? (- <div className="text-[13px]">- <MarkdownRenderer content={file.content} />- </div>- ) : (- <Muted>{emptyLabel}</Muted>- )}- </Flex>- );- }-- return (- <Flex direction="column" gap="2">- <textarea- aria-label={editable.path}- value={draft}- onChange={(e) => setDraft(e.currentTarget.value)}- disabled={mutation.isPending}- spellCheck={false}- className="min-h-[280px] w-full resize-y rounded-(--radius-2) border border-border bg-(--color-panel-solid) p-3 text-[12.5px] text-gray-12 [font-family:var(--font-mono)] focus:border-(--accent-7) focus:outline-none"- />- {mutation.isError ? (- <Text className="text-(--red-11) text-[12px]">- {mutation.error?.message ?? "Save failed"}- </Text>- ) : null}- <Flex justify="end" gap="2">- <Button- size="1"- variant="soft"- color="gray"- disabled={mutation.isPending}- onClick={() => {- setDraft(initial);- setEditing(false);- mutation.reset();- }}- >- Cancel- </Button>- <Button- size="1"- loading={mutation.isPending}- disabled={draft === initial}- onClick={() =>- mutation.mutate(- { path: editable.path, content: draft },- { onSuccess: () => setEditing(false) },- )- }- >- Save- </Button>- </Flex>- </Flex>- );-}--function Row({- label,- value,- mono,- valueColor,-}: {- label: string;- value: string;- mono?: boolean;- valueColor?: string;-}) {- return (- <Flex- align="center"- justify="between"- gap="3"- className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2"- >- <Text className="shrink-0 text-[11px] text-gray-10 uppercase tracking-wide">- {label}- </Text>- <Text- className={`truncate text-[12.5px] text-gray-12 ${mono ? "[font-family:var(--font-mono)]" : ""}`}- style={valueColor ? { color: valueColor } : undefined}- >- {value}- </Text>- </Flex>- );-}--function JumpRow({- icon,- title,- subtitle,- trailing,- mono,- onClick,-}: {- icon: ReactNode;- title: string;- subtitle?: string;- trailing?: ReactNode;- mono?: boolean;- onClick: () => void;-}) {- return (- <button- type="button"- onClick={onClick}- className="flex w-full items-center gap-2.5 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-3 py-2.5 text-left hover:border-(--gray-7)"- >- {icon}- <Flex direction="column" gap="0.5" className="min-w-0 flex-1">- <Text- className={`truncate text-[12.5px] text-gray-12 ${mono ? "[font-family:var(--font-mono)]" : ""}`}- >- {title}- </Text>- {subtitle ? (- <Text className="truncate text-[11px] text-gray-10">{subtitle}</Text>- ) : null}- </Flex>- {trailing ? <span className="shrink-0">{trailing}</span> : null}- </button>- );-}--function Attention({- children,- tone = "default",-}: {- children: ReactNode;- tone?: "default" | "warn";-}) {- return (- <div- className={`rounded-(--radius-2) border px-3 py-2 ${- tone === "warn"- ? "border-(--amber-6) bg-(--amber-3)"- : "border-(--amber-6) bg-(--amber-2)"- }`}- >- {children}- </div>- );-}--function Subhead({ children }: { children: ReactNode }) {- return (- <Text className="block text-[11px] text-gray-10 uppercase tracking-wide [font-family:var(--font-mono)]">- {children}- </Text>- );-}--function Muted({ children }: { children: ReactNode }) {- return (- <Text className="text-[12px] text-gray-10 leading-snug">{children}</Text>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentDetailLayout.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentDetailLayout.tsxdeleted file mode 100644index baa4ac51b867..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentDetailLayout.tsx+++ /dev/null@@ -1,251 +0,0 @@-import { ArrowLeftIcon, RobotIcon } from "@phosphor-icons/react";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { type ReactNode, useMemo } from "react";-import { AgentBuilderHeaderControls } from "../agent-builder/AgentBuilderHeaderControls";-import type { AgentBuilderPageContext } from "../agent-builder/agentBuilderStore";-import { useSetAgentBuilderPage } from "../agent-builder/useSetAgentBuilderPage";-import { useAgentApplication } from "../hooks/useAgentApplication";--/** Map a detail sub-tab to the agent builder page context for this agent. */-function tabToAgentBuilderPage(- tab: AgentDetailTab,- slug: string,- configRevision?: string,-): AgentBuilderPageContext {- switch (tab) {- case "chat":- return { kind: "agent-chat", slug };- case "sessions":- return { kind: "agent-sessions", slug };- case "configuration":- return { kind: "agent-config", slug, revision: configRevision };- case "memory":- return { kind: "agent-memory", slug };- case "approvals":- return { kind: "agent-approvals", slug };- case "observability":- return { kind: "agent-observability", slug };- default:- return { kind: "agent", slug };- }-}--export type AgentDetailTab =- | "overview"- | "chat"- | "sessions"- | "users"- | "configuration"- | "memory"- | "approvals"- | "observability";--const TABS: { id: AgentDetailTab; label: string; to: string }[] = [- {- id: "overview",- label: "Overview",- to: "/code/agents/applications/$idOrSlug",- },- {- id: "configuration",- label: "Configuration",- to: "/code/agents/applications/$idOrSlug/configuration",- },- {- id: "sessions",- label: "Sessions",- to: "/code/agents/applications/$idOrSlug/sessions",- },- {- id: "users",- label: "Users",- to: "/code/agents/applications/$idOrSlug/users",- },- {- id: "memory",- label: "Memory",- to: "/code/agents/applications/$idOrSlug/memory",- },- {- id: "approvals",- label: "Approvals",- to: "/code/agents/applications/$idOrSlug/approvals",- },- {- id: "observability",- label: "Observability",- to: "/code/agents/applications/$idOrSlug/observability",- },- {- id: "chat",- label: "Chat",- to: "/code/agents/applications/$idOrSlug/chat",- },-];--/**- * Shared chrome for a single agent's detail panes: back link, title + state- * badge + description, and the sub-tab bar. Each pane (Overview, Approvals, …)- * renders its body as `children`; the layout owns the agent fetch and gates the- * body on it so every pane shows consistent loading/error states. The session- * transcript view deliberately does NOT use this layout — it keeps its own- * focused full-screen chrome.- */-export function AgentDetailLayout({- idOrSlug,- activeTab,- children,- /**- * Fill mode: the content area becomes a full-height, full-width,- * non-scrolling flex child and the pane manages its own layout/scroll (for- * master-detail panes like Approvals). Default is a centered, padded,- * scrolling document column.- */- fill = false,- /**- * Resolved revision the Configuration pane is showing. Threaded into the- * agent-builder page context so revision-scoped punch-outs (`set_secret`,- * `connect_mcp`) target the revision the user is looking at.- */- configRevision,-}: {- idOrSlug: string;- activeTab: AgentDetailTab;- children: ReactNode;- fill?: boolean;- configRevision?: string | null;-}) {- const {- data: application,- isLoading,- isError,- } = useAgentApplication(idOrSlug);-- const title = application?.name ?? idOrSlug;- const headerContent = useMemo(- () => (- <Flex align="center" gap="2" className="w-full min-w-0">- <RobotIcon size={12} className="shrink-0 text-gray-10" />- <Text- className="truncate whitespace-nowrap font-medium text-[13px]"- title={title}- >- {title}- </Text>- </Flex>- ),- [title],- );- useSetHeaderContent(headerContent);- const pageContext = tabToAgentBuilderPage(- activeTab,- idOrSlug,- configRevision ?? undefined,- );- useSetAgentBuilderPage(pageContext);-- return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="3"- className="relative cursor-default select-none border-(--gray-5) border-b px-6 pt-5"- >- <AgentBuilderHeaderControls />- <Link- to="/code/agents/applications"- className="flex w-fit items-center gap-1.5 text-[12px] text-gray-11 no-underline hover:text-gray-12"- >- <ArrowLeftIcon size={13} />- Fleet- </Link>- <Flex align="center" gap="2" wrap="wrap" className="pr-44">- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- {title}- </Text>- {application?.slug ? (- <Text- className="rounded-(--radius-1) border border-border bg-(--gray-2) px-1.5 py-0.5 text-[12px] text-gray-10 [font-family:var(--font-mono)]"- title="Agent slug — its URL identifier"- >- {application.slug}- </Text>- ) : null}- {application ? (- <Badge color={application.live_revision ? "green" : "gray"}>- {application.live_revision ? "Live" : "Draft"}- </Badge>- ) : null}- </Flex>- {application?.description?.trim() ? (- <Text className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">- {application.description}- </Text>- ) : null}- <div className="scrollbar-overlay -mb-px">- <Flex gap="1" className="w-max">- {TABS.map((tab) => (- <Link- key={tab.id}- to={tab.to}- params={{ idOrSlug }}- className={`shrink-0 whitespace-nowrap border-b-2 px-3 pb-2.5 text-[12.5px] no-underline ${- tab.id === activeTab- ? "border-(--accent-9) font-medium text-gray-12"- : "border-transparent text-gray-11 hover:text-gray-12"- }`}- >- {tab.label}- </Link>- ))}- </Flex>- </div>- </Flex>-- {(() => {- const gated = isLoading ? (- <div className="h-24 animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)" />- ) : isError || !application ? (- <AgentDetailEmptyState- title="Couldn't load this agent"- description="It may have been archived, or the agent platform API returned an error."- />- ) : (- children- );- return fill ? (- <div className="flex min-h-0 flex-1 flex-col">{gated}</div>- ) : (- <div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-6 py-6">{gated}</div>- </div>- );- })()}- </Flex>- );-}--export function AgentDetailEmptyState({- title,- description,-}: {- title: string;- description: ReactNode;-}) {- return (- <Flex- direction="column"- align="center"- gap="1"- className="rounded-(--radius-2) border border-(--gray-5) border-dashed px-6 py-10 text-center"- >- <Text className="font-medium text-[13px] text-gray-12">{title}</Text>- <Text className="max-w-md text-[12px] text-gray-11 leading-snug">- {description}- </Text>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentFleetApprovalsPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentFleetApprovalsPane.tsxdeleted file mode 100644index 266adc57b97b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentFleetApprovalsPane.tsx+++ /dev/null@@ -1,247 +0,0 @@-import { ArrowLeftIcon, LockKeyIcon, RobotIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type {- AgentApplication,- AgentApprovalRequest,-} from "@posthog/shared/agent-platform-types";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useMemo } from "react";-import { useSetAgentBuilderPage } from "../agent-builder/useSetAgentBuilderPage";-import { useAgentApplications } from "../hooks/useAgentApplications";-import { useAgentFleetApprovals } from "../hooks/useAgentFleetApprovals";-import { approvalStateColor, approvalStateLabel } from "../utils/format";-import { AgentApprovalDetail } from "./AgentApprovalDetail";-import { AgentDetailEmptyState } from "./AgentDetailLayout";-import { APPROVAL_FILTERS, type ApprovalFilter } from "./agentApprovalsFilters";-import { RefreshIndicator } from "./RefreshIndicator";--/**- * Fleet-wide approvals queue: a master/detail mirror of the per-agent- * `AgentApprovalsPane` but cross-agent. Each row shows the agent it belongs to- * (joined client-side with `useAgentApplications`) and the detail pane reuses- * `AgentApprovalDetail` once we resolve the application's `idOrSlug`. Owns its- * own chrome (back link + title) rather than nesting under the Scouts /- * Fleet tab bar, matching how per-agent detail pages render.- */-export function AgentFleetApprovalsPane({- selectedId,- onSelect,- filter,- onFilterChange,-}: {- selectedId: string | null;- onSelect: (id: string | null) => void;- filter: ApprovalFilter;- onFilterChange: (f: ApprovalFilter) => void;-}) {- const {- data,- isLoading,- isError,- isPermissionError,- isFetching,- dataUpdatedAt,- refetch,- } = useAgentFleetApprovals(filter === "all" ? undefined : { state: filter });- const { data: applications } = useAgentApplications();-- const approvals = useMemo(() => data ?? [], [data]);- const appsById = useMemo(() => {- const map = new Map<string, AgentApplication>();- for (const app of applications ?? []) {- map.set(app.id, app);- }- return map;- }, [applications]);-- const selected = selectedId- ? (approvals.find((a) => a.id === selectedId) ?? null)- : null;- const selectedApp = selected ? appsById.get(selected.application_id) : null;- const selectedIdOrSlug = selectedApp?.slug ?? selectedApp?.id ?? null;-- const headerContent = useMemo(- () => (- <Flex align="center" gap="2" className="w-full min-w-0">- <LockKeyIcon size={12} className="shrink-0 text-gray-10" />- <Text- className="truncate whitespace-nowrap font-medium text-[13px]"- title="Fleet approvals"- >- Fleet approvals- </Text>- </Flex>- ),- [],- );- useSetHeaderContent(headerContent);- useSetAgentBuilderPage({ kind: "agent-list" });-- const filters = (- <Flex align="center" justify="between" gap="3" wrap="wrap">- <Flex gap="2" wrap="wrap" className="min-w-0">- {APPROVAL_FILTERS.map((f) => (- <button- key={f.id}- type="button"- onClick={() => onFilterChange(f.id)}- className={`rounded-full border px-3 py-1 text-[12px] ${- filter === f.id- ? "border-(--accent-7) bg-(--accent-3) text-gray-12"- : "border-border text-gray-11 hover:border-(--gray-7)"- }`}- >- {f.label}- </button>- ))}- </Flex>- <RefreshIndicator- updatedAt={dataUpdatedAt}- isFetching={isFetching}- onRefresh={() => void refetch()}- compact={!!selectedId}- />- </Flex>- );-- const list = isLoading ? (- <Flex direction="column" gap="2">- {[0, 1, 2].map((i) => (- <div- key={i}- className="h-[60px] animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- ) : isPermissionError ? (- <AgentDetailEmptyState- title="You need organization admin access"- description="Tool approvals can only be viewed and decided by organization admins. Ask an admin to review pending requests."- />- ) : isError ? (- <AgentDetailEmptyState- title="Couldn't load approvals"- description="The agent platform API returned an error while loading fleet approvals. Try again shortly."- />- ) : approvals.length === 0 ? (- <AgentDetailEmptyState- title="Nothing here"- description={- filter === "queued"- ? "No tool calls are waiting for a decision across the fleet."- : "No approval requests match this filter."- }- />- ) : (- <Flex direction="column" gap="2">- {approvals.map((approval) => (- <FleetApprovalRow- key={approval.id}- approval={approval}- application={appsById.get(approval.application_id)}- selected={approval.id === selectedId}- onSelect={() => onSelect(approval.id)}- />- ))}- </Flex>- );-- return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="3"- className="shrink-0 cursor-default select-none border-(--gray-5) border-b px-6 pt-5"- >- <Link- to="/code/agents/applications"- className="flex w-fit items-center gap-1.5 text-[12px] text-gray-11 no-underline hover:text-gray-12"- >- <ArrowLeftIcon size={13} />- Fleet- </Link>- <Flex align="center" gap="2" wrap="wrap">- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- Fleet approvals- </Text>- </Flex>- <Text className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">- Tool calls across every deployed agent that are waiting on (or have- received) a human decision.- </Text>- </Flex>-- <Flex direction="column" className="min-h-0 flex-1">- <div className="shrink-0 px-5 pt-5 pb-3">{filters}</div>- {selected && selectedIdOrSlug ? (- <div className="grid min-h-0 flex-1 grid-cols-[minmax(300px,380px)_minmax(0,1fr)] divide-x divide-(--gray-5) overflow-hidden border-(--gray-5) border-t">- <aside className="min-h-0 overflow-y-auto px-3 py-3">{list}</aside>- <main className="min-h-0 overflow-hidden">- <AgentApprovalDetail- idOrSlug={selectedIdOrSlug}- approval={selected}- onClose={() => onSelect(null)}- />- </main>- </div>- ) : (- <div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-5 pb-6">{list}</div>- </div>- )}- </Flex>- </Flex>- );-}--function FleetApprovalRow({- approval,- application,- selected,- onSelect,-}: {- approval: AgentApprovalRequest;- application: AgentApplication | undefined;- selected: boolean;- onSelect: () => void;-}) {- const isQueued = approval.state === "queued";- const agentLabel =- application?.name ?? application?.slug ?? approval.application_id;- return (- <button- type="button"- onClick={onSelect}- className={`flex w-full items-center gap-3 rounded-(--radius-2) border px-4 py-3 text-left ${- selected- ? "border-(--accent-7) bg-(--accent-3)"- : "border-border bg-(--color-panel-solid) hover:border-(--gray-7)"- }`}- >- <Flex direction="column" gap="1" className="min-w-0 flex-1">- <Flex align="center" gap="2" className="min-w-0">- <Badge color={approvalStateColor(approval.state)}>- {approvalStateLabel(approval.state)}- </Badge>- <Text className="truncate font-medium text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {approval.tool_name}- </Text>- </Flex>- <Flex align="center" gap="1.5" className="min-w-0">- <RobotIcon size={11} className="shrink-0 text-gray-10" />- <Text className="truncate text-[11px] text-gray-11">- {agentLabel}- </Text>- </Flex>- </Flex>- <Text className="shrink-0 text-[11px] text-gray-10">- {isQueued- ? `expires ${formatRelativeTimeShort(approval.expires_at)}`- : formatRelativeTimeShort(approval.created_at)}- </Text>- </button>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentFleetLiveSessionsPanel.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentFleetLiveSessionsPanel.tsxdeleted file mode 100644index 5381bb277eec..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentFleetLiveSessionsPanel.tsx+++ /dev/null@@ -1,161 +0,0 @@-import { BroadcastIcon, CaretRightIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type {- AgentApplication,- AgentFleetLiveSessionSummary,- AgentSessionTriggerMetadata,-} from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useMemo } from "react";-import { useAgentApplications } from "../hooks/useAgentApplications";-import { useAgentFleetLiveSessions } from "../hooks/useAgentFleetLiveSessions";-import { sessionStateColor } from "../utils/format";-import { RefreshIndicator } from "./RefreshIndicator";--/**- * Cross-agent in-flight sessions, surfaced on the Fleet landing. Lists- * non-terminal sessions across the fleet with state, agent, trigger, turn count- * and started-ago; clicking a row navigates to the per-agent session detail.- * Polls aggressively (see {@link useAgentFleetLiveSessions}) so the panel feels- * live without an SSE channel.- */-export function AgentFleetLiveSessionsPanel() {- const { data, isLoading, isError, isFetching, dataUpdatedAt, refetch } =- useAgentFleetLiveSessions();- const { data: applications } = useAgentApplications();-- const appsById = useMemo(() => {- const map = new Map<string, AgentApplication>();- for (const app of applications ?? []) {- map.set(app.id, app);- }- return map;- }, [applications]);-- const sessions = data?.results ?? [];-- return (- <section>- <Flex align="center" justify="between" className="mb-3">- <Flex align="center" gap="2">- <BroadcastIcon size={13} className="text-gray-11" />- <Text className="font-semibold text-[13px] text-gray-12">- Live now- </Text>- {sessions.length > 0 ? (- <Badge color="blue">{sessions.length}</Badge>- ) : null}- </Flex>- <RefreshIndicator- updatedAt={dataUpdatedAt}- isFetching={isFetching}- onRefresh={() => void refetch()}- />- </Flex>-- {isLoading ? (- <Flex direction="column" gap="2">- {[0, 1].map((i) => (- <div- key={i}- className="h-[52px] animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- ) : isError ? (- <EmptyTile- title="Couldn't load live sessions"- description="The agent platform API returned an error."- />- ) : sessions.length === 0 ? (- <EmptyTile- title="Nothing running"- description="In-flight agent sessions across the fleet will show up here."- />- ) : (- <Flex direction="column" gap="2">- {sessions.map((session) => (- <LiveSessionRow- key={session.id}- session={session}- application={appsById.get(session.application_id)}- />- ))}- </Flex>- )}- </section>- );-}--function LiveSessionRow({- session,- application,-}: {- session: AgentFleetLiveSessionSummary;- application: AgentApplication | undefined;-}) {- const agentLabel =- application?.name ?? application?.slug ?? session.application_id;- const idOrSlug =- application?.slug ?? application?.id ?? session.application_id;- const trigger = triggerLabel(session.trigger_metadata);- return (- <Link- to="/code/agents/applications/$idOrSlug/sessions/$sessionId"- params={{ idOrSlug, sessionId: session.id }}- className="flex items-center justify-between gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3 no-underline transition-colors duration-150 hover:border-(--gray-6) hover:bg-(--gray-2)"- >- <Flex align="center" gap="3" className="min-w-0">- <Badge color={sessionStateColor(session.state)}>{session.state}</Badge>- <Flex direction="column" gap="0.5" className="min-w-0">- <Text className="truncate font-medium text-[12.5px] text-gray-12">- {agentLabel}- </Text>- <Text className="truncate text-[11px] text-gray-10">- {trigger ? `${trigger} · ` : ""}- {session.turns} turn{session.turns === 1 ? "" : "s"}- {session.preview ? ` · ${session.preview}` : ""}- </Text>- </Flex>- </Flex>- <Flex align="center" gap="3" className="shrink-0">- <Text className="text-[11px] text-gray-10">- {formatRelativeTimeShort(session.created_at)}- </Text>- <CaretRightIcon size={14} className="shrink-0 text-gray-10" />- </Flex>- </Link>- );-}--function triggerLabel(- meta: AgentSessionTriggerMetadata | null | undefined,-): string | null {- if (!meta || typeof meta !== "object") return null;- const kind = (meta as { kind?: unknown }).kind;- return typeof kind === "string" ? kind : null;-}--function EmptyTile({- title,- description,-}: {- title: string;- description: string;-}) {- return (- <Flex- direction="column"- align="center"- gap="1"- className="rounded-(--radius-2) border border-(--gray-5) border-dashed px-6 py-8 text-center"- >- <Text className="font-medium text-[12.5px] text-gray-12">{title}</Text>- <Text className="max-w-md text-[11.5px] text-gray-11 leading-snug">- {description}- </Text>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentMemoryPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentMemoryPane.tsxdeleted file mode 100644index 76fe4ae001cf..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentMemoryPane.tsx+++ /dev/null@@ -1,296 +0,0 @@-import { formatRelativeTimeShort } from "@posthog/shared";-import type { AgentMemoryTreeNode } from "@posthog/shared/agent-platform-types";-import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { useMemo, useState } from "react";-import {- useAgentMemoryFile,- useAgentMemorySearch,- useAgentMemoryTable,- useAgentMemoryTables,- useAgentMemoryTree,-} from "../hooks/useAgentMemory";-import { AgentDetailLayout } from "./AgentDetailLayout";-import { FileExplorer, type FileTreeNode } from "./FileExplorer";--type View = "files" | "tables";--/**- * Per-agent Memory pane: the agent's S3-backed memory store, browsed through the- * same reusable {@link FileExplorer} as the config bundle — a folder tree + read- * view with BM25 search, plus the JSONL reference tables. Render-only;- * create/update/delete is deferred (and operational, not authoring, if added).- */-export function AgentMemoryPane({ idOrSlug }: { idOrSlug: string }) {- const [view, setView] = useState<View>("files");-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="memory" fill>- <Flex direction="column" className="h-full min-h-0">- <Flex gap="2" className="shrink-0 border-(--gray-5) border-b px-4 py-2">- {(["files", "tables"] as const).map((v) => (- <button- key={v}- type="button"- onClick={() => setView(v)}- className={`rounded-(--radius-2) px-3 py-1 text-[12px] capitalize ${- v === view- ? "bg-(--accent-3) font-medium text-gray-12"- : "text-gray-11 hover:bg-(--gray-3)"- }`}- >- {v}- </button>- ))}- </Flex>- <div className="min-h-0 flex-1">- {view === "files" ? (- <MemoryFiles idOrSlug={idOrSlug} />- ) : (- <MemoryTables idOrSlug={idOrSlug} />- )}- </div>- </Flex>- </AgentDetailLayout>- );-}--function toFileTree(node: AgentMemoryTreeNode): FileTreeNode {- return {- type: node.type,- name: node.name,- path: node.path,- description: node.description,- children: node.children?.map(toFileTree),- };-}--function MemoryFiles({ idOrSlug }: { idOrSlug: string }) {- const [selected, setSelected] = useState<string | null>(null);- const [query, setQuery] = useState("");- const { data: root, isLoading, isError } = useAgentMemoryTree(idOrSlug);- const search = useAgentMemorySearch(idOrSlug, query);-- const tree = useMemo(() => (root ? toFileTree(root) : null), [root]);- const results = useMemo(- () =>- (search.data ?? []).map((r) => ({- path: r.path,- description: r.description,- snippet: r.snippet ?? undefined,- score: r.score,- })),- [search.data],- );-- return (- <FileExplorer- tree={tree}- selectedPath={selected}- onSelectPath={setSelected}- loading={isLoading}- error={isError ? new Error("Couldn't load memory") : null}- emptyMessage="No memory files yet."- storageKey="agent-memory-explorer"- search={{- query,- onChange: setQuery,- results: query.trim() ? results : null,- loading: search.isLoading,- placeholder: "Search memory…",- }}- >- {selected ? (- <MemoryFileDetail idOrSlug={idOrSlug} path={selected} />- ) : (- <Centered>Select a memory file to read it.</Centered>- )}- </FileExplorer>- );-}--function MemoryFileDetail({- idOrSlug,- path,-}: {- idOrSlug: string;- path: string;-}) {- const { data: file, isLoading, isError } = useAgentMemoryFile(idOrSlug, path);-- return (- <div className="flex h-full min-h-0 flex-col">- <div className="shrink-0 border-(--gray-5) border-b px-5 py-3">- <Text className="block truncate font-medium text-[13px] text-gray-12 [font-family:var(--font-mono)]">- {path}- </Text>- {file ? (- <Flex align="center" gap="2" wrap="wrap" className="mt-1">- {file.tags.map((t) => (- <Badge key={t} color="gray">- {t}- </Badge>- ))}- {file.updated_at ? (- <Text className="text-[11px] text-gray-10">- updated {formatRelativeTimeShort(file.updated_at)}- </Text>- ) : null}- </Flex>- ) : null}- {file?.description ? (- <Text className="mt-1 block text-[12px] text-gray-11 leading-snug">- {file.description}- </Text>- ) : null}- </div>- <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">- {isLoading ? (- <div className="h-40 animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)" />- ) : isError || !file ? (- <Text className="text-[12px] text-gray-10">- Couldn't load this file.- </Text>- ) : (- <div className="text-[13px]">- <MarkdownRenderer content={file.content} />- </div>- )}- </div>- </div>- );-}--function MemoryTables({ idOrSlug }: { idOrSlug: string }) {- const [selected, setSelected] = useState<string | null>(null);- const { data: tables, isLoading, isError } = useAgentMemoryTables(idOrSlug);-- const tree = useMemo<FileTreeNode | null>(- () =>- tables- ? {- type: "folder",- name: "root",- children: tables.map((t) => ({- type: "file" as const,- name: t.name,- path: t.name,- description: `${t.size} row${t.size === 1 ? "" : "s"}`,- })),- }- : null,- [tables],- );-- return (- <FileExplorer- tree={tree}- selectedPath={selected}- onSelectPath={setSelected}- loading={isLoading}- error={isError ? new Error("Couldn't load tables") : null}- emptyMessage="No tables yet."- storageKey="agent-memory-tables"- >- {selected ? (- <MemoryTableDetail idOrSlug={idOrSlug} name={selected} />- ) : (- <Centered>Select a table to read its rows.</Centered>- )}- </FileExplorer>- );-}--function MemoryTableDetail({- idOrSlug,- name,-}: {- idOrSlug: string;- name: string;-}) {- const { data, isLoading, isError } = useAgentMemoryTable(idOrSlug, name);- const columns = useMemo(() => {- const cols = new Set<string>();- for (const row of data?.rows ?? []) {- for (const k of Object.keys(row)) cols.add(k);- }- return [...cols];- }, [data]);-- return (- <div className="flex h-full min-h-0 flex-col">- <div className="shrink-0 border-(--gray-5) border-b px-5 py-3">- <Text className="block font-medium text-[13px] text-gray-12 [font-family:var(--font-mono)]">- {name}- </Text>- {data ? (- <Text className="text-[11px] text-gray-10">- showing {data.returned} of {data.total} rows- </Text>- ) : null}- </div>- <div className="min-h-0 flex-1 overflow-auto px-5 py-4">- {isLoading ? (- <div className="h-40 animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)" />- ) : isError || !data ? (- <Text className="text-[12px] text-gray-10">- Couldn't load this table.- </Text>- ) : data.rows.length === 0 ? (- <Text className="text-[12px] text-gray-10">No rows.</Text>- ) : (- <div className="overflow-x-auto rounded-(--radius-2) border border-border">- <table className="w-full border-collapse text-[12px]">- <thead>- <tr className="border-(--gray-5) border-b bg-(--gray-2)">- {columns.map((c) => (- <th- key={c}- className="whitespace-nowrap px-3 py-2 text-left font-medium text-gray-11 [font-family:var(--font-mono)]"- >- {c}- </th>- ))}- </tr>- </thead>- <tbody>- {data.rows.map((row, i) => (- <tr- // biome-ignore lint/suspicious/noArrayIndexKey: table rows have no stable id- key={i}- className="border-(--gray-4) border-b last:border-0"- >- {columns.map((c) => (- <td- key={c}- className="max-w-xs truncate px-3 py-1.5 text-gray-12"- title={cellText(row[c])}- >- {cellText(row[c])}- </td>- ))}- </tr>- ))}- </tbody>- </table>- </div>- )}- </div>- </div>- );-}--function cellText(v: unknown): string {- if (v == null) return "";- if (typeof v === "object") return JSON.stringify(v);- return String(v);-}--function Centered({ children }: { children: React.ReactNode }) {- return (- <div className="flex h-full items-center justify-center px-6 text-center text-[12px] text-gray-10">- {children}- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentModelConfig.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentModelConfig.tsxdeleted file mode 100644index 2a2ba8411c88..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentModelConfig.tsx+++ /dev/null@@ -1,755 +0,0 @@-import { PointerSensor } from "@dnd-kit/dom";-import { type DragDropEvents, DragDropProvider } from "@dnd-kit/react";-import { useSortable } from "@dnd-kit/react/sortable";-import {- CaretDownIcon,- GaugeIcon,- MagnifyingGlassIcon,- ScalesIcon,- SlidersHorizontalIcon,-} from "@phosphor-icons/react";-import type {- AgentModelEntry,- AgentModelLevel,- AgentModelOptimizeFor,- AgentModelPolicy,- AgentReasoningEffort,- AgentRevisionState,- AgentSpec,- ModelCatalogEntry,-} from "@posthog/shared/agent-platform-types";-import { ReasoningLevelDropdown } from "@posthog/ui/features/sessions/components/ReasoningLevelDropdown";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Popover, Text } from "@radix-ui/themes";-import { type ReactNode, type RefCallback, useMemo, useState } from "react";-import { useApplyAgentSpec } from "../hooks/useApplyAgentSpec";-import { useModelCatalog } from "../hooks/useModelCatalog";--/**- * The rich model section: an interactive policy editor (mode + level +- * reasoning), a preview of what an `auto` level resolves to, and a searchable- * browser of every served model with its cost profile. Save goes through- * `useApplyAgentSpec`, which PATCHes a draft in place or branches a fresh- * draft from a non-draft revision first.- */-export function AgentModelConfig({- spec,- idOrSlug,- applicationId,- revisionId,- revisionState,- onSelectRevision,-}: {- spec: AgentSpec;- idOrSlug: string;- applicationId?: string;- revisionId: string;- revisionState?: AgentRevisionState;- onSelectRevision?: (revisionId: string) => void;-}) {- const { catalog } = useModelCatalog();- const apply = useApplyAgentSpec(idOrSlug, applicationId);- const initial = spec.models;-- const [mode, setMode] = useState<"auto" | "manual">(initial?.mode ?? "auto");- const [level, setLevel] = useState<AgentModelLevel>(- initial?.mode === "auto" ? (initial.level ?? "medium") : "medium",- );- const [reasoning, setReasoning] = useState<AgentReasoningEffort | undefined>(- initial?.mode === "auto" ? initial.reasoning : spec.reasoning,- );- const [manual, setManual] = useState<AgentModelEntry[]>(- initial?.mode === "manual" ? initial.models : [],- );- const [optimizeFor, setOptimizeFor] = useState<AgentModelOptimizeFor>(- initial?.optimize_for ?? "cost",- );-- const policy: AgentModelPolicy =- mode === "auto"- ? {- mode: "auto",- level,- optimize_for: optimizeFor,- ...(reasoning ? { reasoning } : {}),- }- : { mode: "manual", models: manual, optimize_for: optimizeFor };-- const dirty =- stableStringify(policy) !==- stableStringify(- initial ?? { mode: "auto", level: "medium", optimize_for: "cost" },- );- const willBranch = revisionState !== "draft";-- const byId = useMemo(- () => new Map(catalog.models.map((m) => [m.model, m])),- [catalog.models],- );-- function reset() {- setMode(initial?.mode ?? "auto");- setLevel(initial?.mode === "auto" ? (initial.level ?? "medium") : "medium");- setReasoning(initial?.mode === "auto" ? initial.reasoning : spec.reasoning);- setManual(initial?.mode === "manual" ? initial.models : []);- setOptimizeFor(initial?.optimize_for ?? "cost");- }-- function changeMode(next: "auto" | "manual") {- // Switching to manual with an empty list seeds it from the level you were- // on, so you start from auto's choices and edit rather than a blank slate.- if (next === "manual" && manual.length === 0) {- setManual((catalog.levels[level] ?? []).map((model) => ({ model })));- }- setMode(next);- }-- function save() {- apply.mutate(- {- revision: { id: revisionId, state: revisionState ?? "draft" },- spec: { ...spec, models: policy },- },- { onSuccess: (rev) => onSelectRevision?.(rev.id) },- );- }-- return (- <Flex direction="column" gap="4">- {dirty ? (- <Flex- direction="column"- gap="1.5"- className="rounded-(--radius-2) border border-(--amber-6) bg-(--amber-2) px-3 py-2"- >- <Flex align="center" justify="between" gap="2">- <Text className="text-[12px] text-amber-11">- {willBranch- ? "Unsaved changes — saving branches a new draft."- : "Unsaved changes."}- </Text>- <Flex gap="2" className="shrink-0">- <Button- size="1"- variant="soft"- color="gray"- disabled={apply.isPending}- onClick={reset}- >- Reset- </Button>- <Button size="1" loading={apply.isPending} onClick={save}>- {willBranch ? "Save to new draft" : "Save"}- </Button>- </Flex>- </Flex>- {apply.isError ? (- <Text className="text-(--red-11) text-[11px]">- {apply.error?.message ?? "Save failed"}- </Text>- ) : null}- </Flex>- ) : null}-- <Flex direction="column" gap="3">- <Select- label="mode"- icon={<SlidersHorizontalIcon size={14} />}- value={mode}- onChange={(v) => changeMode(v as "auto" | "manual")}- options={MODE_OPTIONS}- />-- <Select- label="optimize for"- icon={<ScalesIcon size={14} />}- value={optimizeFor}- onChange={(v) => setOptimizeFor(v as AgentModelOptimizeFor)}- options={OPTIMIZE_OPTIONS}- />-- {mode === "auto" ? (- <>- <Select- label="level"- icon={<GaugeIcon size={14} />}- value={level}- onChange={(v) => setLevel(v as AgentModelLevel)}- options={LEVEL_OPTIONS}- />- <ReasoningLevelDropdown- value={reasoning ?? "default"}- onChange={(v) =>- setReasoning(- v === "default" ? undefined : (v as AgentReasoningEffort),- )- }- options={REASONING_OPTIONS.map((option) => ({- value: option.value,- label: option.title,- description: option.description,- }))}- side="bottom"- triggerVariant="outline"- />- </>- ) : null}- </Flex>-- {mode === "auto" ? (- <AutoLevelPreview- level={level}- ids={catalog.levels[level]}- byId={byId}- />- ) : (- <ManualEditor models={manual} byId={byId} onChange={setManual} />- )}-- <Subhead>browse all models · {catalog.models.length}</Subhead>- <ModelBrowser- models={catalog.models}- canAdd={mode === "manual"}- selected={mode === "manual" ? manual.map((m) => m.model) : []}- onAdd={(id) =>- setManual((prev) =>- prev.some((m) => m.model === id) ? prev : [...prev, { model: id }],- )- }- />- </Flex>- );-}--const MODE_OPTIONS = [- {- value: "auto",- title: "Auto",- description: "Platform-managed list, resolved across providers at runtime.",- },- {- value: "manual",- title: "Manual",- description: "Explicit, author-ordered fallback list you pin yourself.",- },-] as const;--const OPTIMIZE_OPTIONS = [- {- value: "cost",- title: "Cost",- description:- "Pin the first working model for the whole session — keeps the prompt cache warm, no mid-session failover.",- },- {- value: "availability",- title: "Availability",- description:- "Fail over to the next model if the session's model goes down — survives outages, but re-reads context cold.",- },-] as const;--const LEVEL_OPTIONS = [- {- value: "low",- title: "Low",- description: "Cheapest — short, formulaic, no-reasoning jobs.",- },- {- value: "medium",- title: "Medium",- description: "Balanced default — multi-step but bounded work.",- },- {- value: "high",- title: "High",- description: "Top-tier — long, branching, reasoning-heavy work.",- },-] as const;--const REASONING_OPTIONS = [- {- value: "default",- title: "Default",- description: "Provider / spec default — no explicit budget.",- },- {- value: "minimal",- title: "Minimal",- description: "No deliberation — cheapest, fastest.",- },- { value: "low", title: "Low", description: "Light deliberation." },- { value: "medium", title: "Medium", description: "Moderate deliberation." },- { value: "high", title: "High", description: "Deep deliberation." },- {- value: "xhigh",- title: "Xhigh",- description: "Maximal — research-grade, ~5–10× the per-turn cost.",- },-] as const;--const LEVEL_BLURB: Record<AgentModelLevel, string> = {- low: "Cheapest — short, formulaic, no-reasoning jobs (lookups, FAQ bots).",- medium: "Balanced default — multi-step but bounded work.",- high: "Top-tier — long, branching, reasoning-heavy work.",-};--function AutoLevelPreview({- level,- ids,- byId,-}: {- level: AgentModelLevel;- ids: string[];- byId: Map<string, ModelCatalogEntry>;-}) {- return (- <Flex direction="column" gap="2">- <Muted>- <b className="text-gray-12">auto</b> resolves the level to a maintained,- priority-ordered, cross-provider list at runtime — the runner tries each- in order until one answers, so the agent rides upgrades and survives a- provider outage without a spec change. <b>{level}</b>:{" "}- {LEVEL_BLURB[level]}- </Muted>- <Subhead>{level} resolves to · priority order</Subhead>- {ids.map((id, i) => {- const m = byId.get(id);- return (- <Flex- key={id}- align="center"- justify="between"- gap="3"- className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2"- >- <Flex align="center" gap="2" className="min-w-0">- <Text className="shrink-0 text-[11px] text-gray-10">- {i === 0 ? "primary" : `#${i + 1}`}- </Text>- <Text className="truncate text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {id}- </Text>- </Flex>- {m ? <CostInline m={m} /> : <Muted>not in catalog</Muted>}- </Flex>- );- })}- </Flex>- );-}--function ManualEditor({- models,- byId,- onChange,-}: {- models: AgentModelEntry[];- byId: Map<string, ModelCatalogEntry>;- onChange: (next: AgentModelEntry[]) => void;-}) {- const ids = models.map((m) => m.model);- const handleDragOver: DragDropEvents["dragover"] = (event) => {- const sourceId = event.operation.source?.id;- const targetId = event.operation.target?.id;- if (!sourceId || !targetId || sourceId === targetId) return;- const from = ids.indexOf(String(sourceId));- const to = ids.indexOf(String(targetId));- if (from === -1 || to === -1 || from === to) return;- const next = [...models];- const [moved] = next.splice(from, 1);- next.splice(to, 0, moved);- onChange(next);- };- return (- <Flex direction="column" gap="2">- <Muted>- <b className="text-gray-12">manual</b> pins an explicit fallback list- (primary first). Add models from the browser below; order them- provider-diverse so a single provider outage degrades instead of- failing.- </Muted>- <Subhead>models · priority order · drag to reorder</Subhead>- {models.length === 0 ? (- <Text className="rounded-(--radius-2) border border-(--gray-5) border-dashed px-3 py-3 text-[12px] text-gray-10">- No models yet — add one from the browser below.- </Text>- ) : (- <DragDropProvider- onDragOver={handleDragOver}- sensors={[- {- plugin: PointerSensor,- options: { activationConstraints: { distance: { value: 5 } } },- },- ]}- >- <Flex direction="column" gap="2">- {models.map((entry, i) => (- <SortableModelRow- key={entry.model}- id={entry.model}- index={i}- entry={entry}- m={byId.get(entry.model)}- onRemove={() => onChange(models.filter((_, k) => k !== i))}- />- ))}- </Flex>- </DragDropProvider>- )}- </Flex>- );-}--function SortableModelRow({- id,- index,- entry,- m,- onRemove,-}: {- id: string;- index: number;- entry: AgentModelEntry;- m?: ModelCatalogEntry;- onRemove: () => void;-}) {- const { ref, handleRef, isDragging } = useSortable({- id,- index,- group: "manual-models",- transition: { duration: 200, easing: "ease" },- });- return (- <div ref={ref} style={{ opacity: isDragging ? 0.5 : 1 }}>- <Flex- align="center"- justify="between"- gap="3"- className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2"- >- <Flex align="center" gap="2" className="min-w-0">- <button- ref={handleRef as RefCallback<HTMLButtonElement>}- type="button"- title="Drag to reorder"- className="shrink-0 cursor-grab text-[13px] text-gray-9 leading-none hover:text-gray-11"- >- ⠿- </button>- <Text className="shrink-0 text-[11px] text-gray-10">- {index === 0 ? "primary" : `#${index + 1}`}- </Text>- <Text className="truncate text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {entry.model}- </Text>- </Flex>- <Flex align="center" gap="2" className="shrink-0">- {m ? <CostInline m={m} /> : null}- <MiniBtn label="remove" title="Remove" onClick={onRemove} />- </Flex>- </Flex>- </div>- );-}--type SortKey = "name" | "cheapest" | "priciest";--function ModelBrowser({- models,- canAdd,- selected,- onAdd,-}: {- models: ModelCatalogEntry[];- canAdd: boolean;- selected: string[];- onAdd: (id: string) => void;-}) {- const [q, setQ] = useState("");- const [sort, setSort] = useState<SortKey>("name");-- const rows = useMemo(() => {- const needle = q.trim().toLowerCase();- const filtered = needle- ? models.filter(- (m) =>- m.model.toLowerCase().includes(needle) ||- m.provider.toLowerCase().includes(needle),- )- : models;- // Blended per-Mtok cost (input + output), not input alone: reasoning- // models can have cheap input but dominant output, so input-only mis-ranks- // exactly the models cost-conscious authors most need to compare.- const blended = (m: ModelCatalogEntry) => m.input + m.output;- const sorted = [...filtered];- if (sort === "name") sorted.sort((a, b) => a.model.localeCompare(b.model));- if (sort === "cheapest") sorted.sort((a, b) => blended(a) - blended(b));- if (sort === "priciest") sorted.sort((a, b) => blended(b) - blended(a));- return sorted;- }, [models, q, sort]);-- return (- <Flex direction="column" gap="2">- <Flex align="center" gap="2" wrap="wrap">- <div className="relative min-w-0 flex-1">- <MagnifyingGlassIcon- size={13}- className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-2.5 text-gray-10"- />- <input- type="search"- value={q}- onChange={(e) => setQ(e.currentTarget.value)}- placeholder="Search models…"- aria-label="Search models"- className="h-8 w-full rounded-(--radius-2) border border-border bg-(--color-panel-solid) pr-2 pl-8 text-[12.5px]"- />- </div>- <Seg- value={sort}- onChange={(v) => setSort(v as SortKey)}- options={[- { value: "name", label: "Name" },- { value: "cheapest", label: "Cheapest" },- { value: "priciest", label: "Priciest" },- ]}- />- </Flex>-- <Flex direction="column" gap="1">- {rows.map((m) => {- const added = selected.includes(m.model);- return (- <Flex- key={m.model}- direction="column"- gap="1"- className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2"- >- <Flex align="center" justify="between" gap="2">- <Text className="truncate text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {m.model}- </Text>- {canAdd ? (- <MiniBtn- label={added ? "added" : "+ add"}- title={added ? "Already in the list" : "Add to manual list"}- onClick={() => onAdd(m.model)}- disabled={added}- />- ) : null}- </Flex>- <Flex align="center" gap="2" wrap="wrap">- <Badge color="gray">{m.provider}</Badge>- <Stat label="ctx" value={fmtCtx(m.context_window)} />- <Stat label="in" value={fmtUsd(m.input)} />- <Stat label="out" value={fmtUsd(m.output)} />- {m.cacheRead != null ? (- <Stat label="cache" value={fmtUsd(m.cacheRead)} />- ) : null}- </Flex>- </Flex>- );- })}- {rows.length === 0 ? (- <Text className="px-1 py-2 text-[12px] text-gray-10">- No models match “{q}”.- </Text>- ) : null}- </Flex>- </Flex>- );-}--// --- small presentational helpers -----function CostInline({ m }: { m: ModelCatalogEntry }) {- return (- <Text className="shrink-0 text-[11px] text-gray-10">- in {fmtUsd(m.input)} · out {fmtUsd(m.output)}- <span className="text-gray-9"> /Mtok</span>- </Text>- );-}--function Stat({ label, value }: { label: string; value: string }) {- return (- <Text className="text-[11px] text-gray-10">- {label} <span className="text-gray-12">{value}</span>- </Text>- );-}--function Select({- label,- icon,- value,- onChange,- options,-}: {- label: string;- icon?: ReactNode;- value: string;- onChange: (v: string) => void;- options: readonly { value: string; title: string; description: string }[];-}) {- const [open, setOpen] = useState(false);- const current = options.find((o) => o.value === value) ?? options[0];- return (- <Flex direction="column" gap="1">- <Flex align="center" justify="between" gap="3">- <Flex align="center" gap="2" className="shrink-0 text-gray-10">- {icon}- <Text className="text-[11px] uppercase tracking-wide">{label}</Text>- </Flex>- <Popover.Root open={open} onOpenChange={setOpen}>- <Popover.Trigger>- <button- type="button"- className="inline-flex w-fit items-center gap-2 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-2.5 py-1.5 text-left hover:border-(--gray-7)"- >- <Text className="text-[12.5px] text-gray-12">- {current?.title}- </Text>- <CaretDownIcon size={12} className="shrink-0 text-gray-10" />- </button>- </Popover.Trigger>- <Popover.Content size="1" width="360px" className="p-0">- <ul className="max-h-72 divide-y divide-(--gray-4) overflow-auto">- {options.map((o) => (- <li key={o.value}>- <button- type="button"- onClick={() => {- onChange(o.value);- setOpen(false);- }}- aria-current={o.value === value ? "true" : undefined}- className={`flex w-full flex-col gap-0.5 px-3 py-2 text-left ${- o.value === value- ? "bg-(--accent-3)"- : "hover:bg-(--gray-3)"- }`}- >- <Text className="text-[12.5px] text-gray-12">- {o.title}- </Text>- <Text className="text-[11px] text-gray-10 leading-snug">- {o.description}- </Text>- </button>- </li>- ))}- </ul>- </Popover.Content>- </Popover.Root>- </Flex>- {current?.description ? (- <Text className="text-[11px] text-gray-10 leading-snug">- {current.description}- </Text>- ) : null}- </Flex>- );-}--function Seg<T extends string>({- value,- onChange,- options,-}: {- value: T;- onChange: (v: T) => void;- options: { value: T; label: string }[];-}) {- return (- <Flex gap="1" wrap="wrap">- {options.map((o) => (- <button- key={o.value}- type="button"- onClick={() => onChange(o.value)}- className={`rounded-full border px-3 py-1 text-[12px] capitalize ${- value === o.value- ? "border-(--accent-7) bg-(--accent-3) text-gray-12"- : "border-border bg-(--color-panel-solid) text-gray-11 hover:text-gray-12"- }`}- >- {o.label}- </button>- ))}- </Flex>- );-}--function MiniBtn({- label,- title,- onClick,- disabled,-}: {- label: string;- title: string;- onClick: () => void;- disabled?: boolean;-}) {- return (- <button- type="button"- title={title}- onClick={onClick}- disabled={disabled}- className="rounded-(--radius-1) border border-border px-2 py-0.5 text-[11px] text-gray-11 hover:text-gray-12 disabled:opacity-40"- >- {label}- </button>- );-}--function Subhead({ children }: { children: ReactNode }) {- return (- <Text className="block text-[11px] text-gray-10 uppercase tracking-wide [font-family:var(--font-mono)]">- {children}- </Text>- );-}--function Muted({ children }: { children: ReactNode }) {- return (- <Text className="text-[12px] text-gray-10 leading-snug">{children}</Text>- );-}--function fmtUsd(n: number): string {- // Fixed precision so the cost column reads consistently ($1.00, $0.075)- // and survives float noise from the catalog API.- return `$${n.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 4,- })}`;-}--/**- * Deterministic JSON: recursively sorts object keys so the dirty check- * doesn't fire just because the server serialised `spec.models` with a- * different key order than the locally-built policy. Arrays keep their order.- */-function stableStringify(value: unknown): string {- return JSON.stringify(value, (_key, val) =>- val && typeof val === "object" && !Array.isArray(val)- ? Object.fromEntries(- Object.entries(val).sort(([a], [b]) => a.localeCompare(b)),- )- : val,- );-}--function fmtCtx(n: number): string {- if (n >= 1_000_000) {- return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;- }- return `${Math.round(n / 1000)}K`;-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentObservabilityPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentObservabilityPane.tsxdeleted file mode 100644index 4a54a02b0470..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentObservabilityPane.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { useAuthStateValue } from "../../auth/store";-import { useAgentAnalytics } from "../hooks/useAgentAnalytics";-import { useAgentApplication } from "../hooks/useAgentApplication";-import { aiObservabilityTracesUrl } from "../utils/observabilityLinks";-import { AgentAnalyticsView } from "./AgentAnalyticsView";-import { AgentDetailLayout } from "./AgentDetailLayout";--/**- * Per-agent Observability tab: the same rollups as the fleet analytics board,- * scoped to this one agent's `$ai_*` events (by `$agent_application_id`), plus- * a kick-out to the full AI observability product for trace-level depth.- *- * The analytics query keys on the application's UUID, so it waits for the- * agent to resolve from `idOrSlug` before firing.- */-export function AgentObservabilityPane({ idOrSlug }: { idOrSlug: string }) {- const region = useAuthStateValue((s) => s.cloudRegion);- const projectId = useAuthStateValue((s) => s.currentProjectId);-- const { data: application } = useAgentApplication(idOrSlug);- const { data, isLoading, isError, error } = useAgentAnalytics(- application?.id,- "agent",- );-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="observability">- <AgentAnalyticsView- data={data}- title="Observability"- subtitle={`${application?.name ?? "This agent"} · last 7 days (14-day trend)`}- aiObservabilityUrl={aiObservabilityTracesUrl(region, projectId)}- isLoading={isLoading || !application}- isError={isError}- errorMessage={error instanceof Error ? error.message : null}- />- </AgentDetailLayout>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentRevisionBar.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentRevisionBar.tsxdeleted file mode 100644index 11fd02686e34..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentRevisionBar.tsx+++ /dev/null@@ -1,401 +0,0 @@-import { CaretDownIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type {- AgentApplication,- AgentRevision,- AgentRevisionState,-} from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Button } from "@posthog/ui/primitives/Button";-import { AlertDialog, Flex, Popover, Text } from "@radix-ui/themes";-import { useNavigate } from "@tanstack/react-router";-import { useMemo, useState } from "react";-import { useAgentRevisionLifecycle } from "../hooks/useAgentRevisionLifecycle";-import { useCreateAgentDraftFromRevision } from "../hooks/useCreateAgentDraftFromRevision";-import { revisionStateColor } from "../utils/format";-import { AgentBundleImportDialog } from "./AgentBundleImportDialog";--type LifecycleAction = "freeze" | "promote" | "archive";--/** Last segment, first 8 chars — a stable short handle for a revision UUID. */-function shortId(id: string): string {- return id.split("-").at(-1)?.slice(0, 8) ?? id.slice(0, 8);-}--function stateLabel(rev: AgentRevision, isLive: boolean): string {- return isLive ? "live" : rev.state;-}--const STATE_FILTERS: AgentRevisionState[] = [- "live",- "ready",- "draft",- "archived",-];--function lifecycleActionsFor(- state: AgentRevisionState,- isLive: boolean,- hasLiveRevision: boolean,-): { label: string; action: LifecycleAction; destructive?: boolean }[] {- const out: {- label: string;- action: LifecycleAction;- destructive?: boolean;- }[] = [];- if (state === "draft") out.push({ label: "Freeze", action: "freeze" });- if (state === "ready")- out.push({ label: "Promote to live", action: "promote" });- if (state !== "archived" && !(isLive && hasLiveRevision))- out.push({ label: "Archive", action: "archive", destructive: true });- return out;-}--function dialogCopy(- action: LifecycleAction,- revision: AgentRevision,- agent: AgentApplication,-): { title: string; description: string; confirmLabel: string } {- const id = shortId(revision.id);- if (action === "freeze") {- return {- title: `Freeze revision ${id}`,- description:- "Stamps the bundle and locks the spec — the revision moves from draft to ready and becomes immutable. Required before promoting to live.",- confirmLabel: "Freeze",- };- }- if (action === "promote") {- const replacing =- agent.live_revision && agent.live_revision !== revision.id;- return {- title: `Promote ${id} to live`,- description: replacing- ? `The current live revision will be archived and traffic switches to ${id} immediately.`- : `This becomes the live revision for ${agent.name}. Triggers start serving from it immediately.`,- confirmLabel: "Promote to live",- };- }- return {- title: `Archive revision ${id}`,- description:- revision.id === agent.live_revision- ? "This is the live revision — archiving it leaves the agent with no deployable version until another is promoted."- : "This revision will be hidden from the default list and can no longer be promoted.",- confirmLabel: "Archive",- };-}--/**- * The bar above the config explorer: a revision picker (state-filtered list)- * plus the operational lifecycle actions for the selected revision- * (freeze / promote / archive), each behind a confirm. Authoring a revision's- * contents is the agent builder's job — this only moves a revision through its- * lifecycle.- */-export function AgentRevisionBar({- idOrSlug,- agent,- revisions,- selectedRevisionId,- onSelectRevision,-}: {- idOrSlug: string;- agent: AgentApplication;- revisions: AgentRevision[];- selectedRevisionId: string | null;- onSelectRevision: (id: string) => void;-}) {- const lifecycle = useAgentRevisionLifecycle(idOrSlug);- const cloneToDraft = useCreateAgentDraftFromRevision(idOrSlug, agent.id);- const navigate = useNavigate();- const [pickerOpen, setPickerOpen] = useState(false);- const [filters, setFilters] = useState<Set<AgentRevisionState>>(- () => new Set<AgentRevisionState>(["live", "ready", "draft"]),- );- const [pending, setPending] = useState<{- action: LifecycleAction;- revision: AgentRevision;- } | null>(null);- const [importOpen, setImportOpen] = useState(false);-- const selected =- revisions.find((r) => r.id === selectedRevisionId) ?? revisions[0] ?? null;- const isLive = !!selected && selected.id === agent.live_revision;- const actions = selected- ? lifecycleActionsFor(selected.state, isLive, !!agent.live_revision)- : [];- // Skill ids already declared on the selected revision — drives the- // new / update badge in the bulk-import preview.- const existingSkillIds = useMemo<string[]>(() => {- const skills = selected?.spec?.skills;- if (!Array.isArray(skills)) return [];- return skills.flatMap((s) => {- const id =- s && typeof s === "object" && "id" in s- ? (s as { id?: unknown }).id- : undefined;- return typeof id === "string" ? [id] : [];- });- }, [selected]);-- const visible = useMemo(- () =>- [...revisions]- .sort(- (a, b) =>- new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(),- )- .filter((r) =>- filters.has(r.id === agent.live_revision ? "live" : r.state),- ),- [revisions, filters, agent.live_revision],- );-- function toggleFilter(f: AgentRevisionState) {- setFilters((prev) => {- const next = new Set(prev);- if (next.has(f)) next.delete(f);- else next.add(f);- return next;- });- }-- if (!selected) return null;- const copy = pending- ? dialogCopy(pending.action, pending.revision, agent)- : null;-- return (- <Flex- align="center"- justify="between"- gap="3"- className="shrink-0 border-(--gray-5) border-b px-4 py-2"- >- <Popover.Root open={pickerOpen} onOpenChange={setPickerOpen}>- <Popover.Trigger>- <button- type="button"- className="flex items-center gap-2 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-2.5 py-1.5 text-left hover:border-(--gray-7)"- >- <Badge color={revisionStateColor(selected.state)}>- {stateLabel(selected, isLive)}- </Badge>- <code className="text-[12px] text-gray-12 [font-family:var(--font-mono)]">- {shortId(selected.id)}- </code>- <Text className="text-[11px] text-gray-10">- {formatRelativeTimeShort(selected.updated_at)}- </Text>- <CaretDownIcon size={12} className="text-gray-10" />- </button>- </Popover.Trigger>- <Popover.Content size="1" width="320px" className="p-0">- <div className="border-(--gray-5) border-b px-2 py-2">- <Flex gap="1" wrap="wrap">- {STATE_FILTERS.map((f) => {- const active = filters.has(f);- return (- <button- key={f}- type="button"- onClick={() => toggleFilter(f)}- aria-pressed={active}- className={`rounded-(--radius-2) border px-1.5 py-[3px] text-[10.5px] uppercase leading-none tracking-wide ${- active- ? "border-(--accent-7) bg-(--accent-3) text-gray-12"- : "border-border text-gray-10 hover:border-(--gray-7)"- }`}- >- {f}- </button>- );- })}- </Flex>- </div>- <ul className="max-h-72 divide-y divide-(--gray-4) overflow-auto">- {visible.length === 0 ? (- <li className="px-3 py-3 text-[12px] text-gray-10">- No matching revisions.- </li>- ) : (- visible.map((r) => {- const live = r.id === agent.live_revision;- return (- <li key={r.id}>- <button- type="button"- onClick={() => {- onSelectRevision(r.id);- setPickerOpen(false);- }}- aria-current={r.id === selected.id ? "true" : undefined}- className={`flex w-full items-center gap-2 px-3 py-2 text-left ${- r.id === selected.id- ? "bg-(--accent-3)"- : "hover:bg-(--gray-3)"- }`}- >- <Badge color={revisionStateColor(r.state)}>- {stateLabel(r, live)}- </Badge>- <div className="min-w-0 flex-1">- <code className="text-[11.5px] text-gray-12 [font-family:var(--font-mono)]">- {shortId(r.id)}- </code>- <div className="text-[10.5px] text-gray-10">- {formatRelativeTimeShort(r.updated_at)}- {r.created_by?.first_name- ? ` · ${r.created_by.first_name}`- : ""}- </div>- </div>- </button>- </li>- );- })- )}- </ul>- </Popover.Content>- </Popover.Root>-- <Flex gap="2">- {/*- * Test — routes this not-yet-promoted revision through the ingress- * with a short-lived JWT (the chat tab mints + attaches it via- * useAgentChat). Side effects run for real; the revision serving the- * request is the only difference from a live chat. Live uses the- * default Chat tab; archived can't be exercised.- */}- {selected.state !== "live" &&- selected.state !== "archived" &&- !isLive ? (- <Button- size="1"- variant="soft"- color="gray"- onClick={() =>- navigate({- to: "/code/agents/applications/$idOrSlug/chat",- params: { idOrSlug },- search: { revision: selected.id },- })- }- >- {selected.state === "draft" ? "Test draft" : "Test"}- </Button>- ) : null}- {/*- * Clone to draft — fork this revision into a fresh editable draft (the- * exit when a ready/live/archived bundle is immutable but you want to- * keep iterating). Pre-selects the new draft.- */}- {selected.state !== "draft" ? (- <Button- size="1"- variant="soft"- color="gray"- loading={cloneToDraft.isPending}- disabled={!agent.id}- onClick={() =>- cloneToDraft.mutate(- { sourceRevisionId: selected.id },- { onSuccess: (rev) => onSelectRevision(rev.id) },- )- }- >- Clone to draft- </Button>- ) : null}- {/*- * Paste markdown bundle — bulk import for the multi-file migration- * case (e.g. porting an existing growth-review agent in one paste).- * Per-file edit lives in the configuration pane; this is the hatch- * when there are several files to seed at once.- */}- {selected.state === "draft" ? (- <Button- size="1"- variant="soft"- color="gray"- onClick={() => setImportOpen(true)}- >- Paste markdown bundle…- </Button>- ) : null}- {actions.map((a) => (- <Button- key={a.action}- size="1"- variant="soft"- color={a.destructive ? "red" : "gray"}- onClick={() => setPending({ action: a.action, revision: selected })}- >- {a.label}- </Button>- ))}- </Flex>-- {selected.state === "draft" ? (- <AgentBundleImportDialog- open={importOpen}- onOpenChange={setImportOpen}- idOrSlug={idOrSlug}- revisionId={selected.id}- existingSkillIds={existingSkillIds}- />- ) : null}-- <AlertDialog.Root- open={!!pending}- onOpenChange={(open) => {- if (!open && !lifecycle.isPending) setPending(null);- }}- >- <AlertDialog.Content maxWidth="440px" size="2">- {copy && pending ? (- <>- <AlertDialog.Title className="text-base">- {copy.title}- </AlertDialog.Title>- <AlertDialog.Description size="2" className="text-gray-11">- {copy.description}- </AlertDialog.Description>- {lifecycle.isError ? (- <Text className="mt-2 block text-(--red-11) text-[12px]">- {lifecycle.error?.message ?? "Action failed"}- </Text>- ) : null}- <Flex gap="3" mt="4" justify="end">- <Button- variant="soft"- color="gray"- disabled={lifecycle.isPending}- onClick={() => setPending(null)}- >- Cancel- </Button>- <Button- color={pending.action === "archive" ? "red" : "green"}- loading={lifecycle.isPending}- onClick={() =>- lifecycle.mutate(- {- revisionId: pending.revision.id,- action: pending.action,- },- { onSuccess: () => setPending(null) },- )- }- >- {copy.confirmLabel}- </Button>- </Flex>- </>- ) : null}- </AlertDialog.Content>- </AlertDialog.Root>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionDetailBody.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionDetailBody.tsxdeleted file mode 100644index 25d5eb6ec005..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionDetailBody.tsx+++ /dev/null@@ -1,298 +0,0 @@-import type { AgentApplicationSessionDetail } from "@posthog/shared/agent-platform-types";-import { ThreadView } from "@posthog/ui/features/sessions/components/ThreadView";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { type ReactNode, useMemo, useState } from "react";-import { conversationToAcpMessages } from "../chat/conversationToAcp";-import { useAgentApplicationSession } from "../hooks/useAgentApplicationSession";-import {- formatDuration,- formatSpendUsd,- sessionStateColor,-} from "../utils/format";-import { RefreshIndicator } from "./RefreshIndicator";-import { SessionLogsView } from "./SessionLogsView";--type DetailTab = "conversation" | "logs";--interface SessionMetrics {- messages: number;- toolCalls: number;- errors: number;- /** Distinct models that answered, in first-seen order. Usually one; more than- * one means the turn(s) fell back across the policy list. */- models: string[];-}--function computeMetrics(- session: AgentApplicationSessionDetail,-): SessionMetrics {- let toolCalls = 0;- let errors = 0;- const models: string[] = [];- const seenModels = new Set<string>();- for (const msg of session.conversation) {- if (msg.role === "assistant") {- for (const part of msg.content) {- if (part.type === "toolCall") toolCalls += 1;- }- if (msg.errorMessage) errors += 1;- if (msg.model && !seenModels.has(msg.model)) {- seenModels.add(msg.model);- models.push(msg.model);- }- } else if (msg.role === "toolResult" && msg.isError) {- errors += 1;- }- }- return {- messages: session.conversation_total_turns ?? session.conversation.length,- toolCalls,- errors,- models,- };-}--/** Reads a cron "fired by" descriptor off trigger_metadata, if present. */-function cronFiredBy(- meta: AgentApplicationSessionDetail["trigger_metadata"],-): { cronName: string; schedule?: string } | null {- if (!meta || typeof meta !== "object") return null;- if ((meta as { kind?: unknown }).kind !== "cron") return null;- const cronName = (meta as { cron_name?: unknown }).cron_name;- if (typeof cronName !== "string") return null;- const schedule = (meta as { schedule?: unknown }).schedule;- return {- cronName,- schedule: typeof schedule === "string" ? schedule : undefined,- };-}--/**- * The session detail body: state/cron badges + KPI strip + a refresh control,- * with Conversation (read-only, through code's native `ConversationView`) and- * structured Logs tabs. Reused by the full-screen session route and embedded in- * the approval detail's Session tab. Owns no page chrome (no back link/title).- */-export function AgentSessionDetailBody({- idOrSlug,- sessionId,- showStateBadge = true,-}: {- idOrSlug: string;- sessionId: string;- /** Hide the state badge when the host already shows it (full-screen header). */- showStateBadge?: boolean;-}) {- const {- data: session,- isLoading,- isError,- isFetching,- dataUpdatedAt,- refetch,- } = useAgentApplicationSession(idOrSlug, sessionId);- const [tab, setTab] = useState<DetailTab>("conversation");-- const events = useMemo(- () => (session ? conversationToAcpMessages(session.conversation) : []),- [session],- );- const metrics = useMemo(- () => (session ? computeMetrics(session) : null),- [session],- );- const firedBy = session ? cronFiredBy(session.trigger_metadata) : null;-- return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="3"- className="shrink-0 cursor-default select-none border-(--gray-5) border-b px-6 pt-4"- >- {(showStateBadge && session) ||- firedBy ||- session?.conversation_trimmed ? (- <Flex align="center" gap="2" wrap="wrap">- {showStateBadge && session ? (- <Badge color={sessionStateColor(session.state)}>- {session.state}- </Badge>- ) : null}- {firedBy ? (- <Badge color="gray" title={firedBy.schedule}>- cron · {firedBy.cronName}- </Badge>- ) : null}- {session?.conversation_trimmed ? (- <Badge color="gray">- showing last {session.conversation.length} of{" "}- {session.conversation_total_turns ??- session.conversation.length}- </Badge>- ) : null}- </Flex>- ) : null}-- <Flex align="center" justify="between" gap="3">- <Flex gap="5" wrap="wrap" className="min-w-0">- {session && metrics ? (- <>- <MetricItem label="Messages" value={String(metrics.messages)} />- <MetricItem- label="Tool calls"- value={String(metrics.toolCalls)}- />- {metrics.models.length > 0 ? (- <MetricItem- label="Model"- value={- metrics.models.length === 1- ? metrics.models[0]- : `${metrics.models[0]} +${metrics.models.length - 1}`- }- title={metrics.models.join(", ")}- mono- />- ) : null}- <MetricItem- label="Cost"- value={formatSpendUsd(session.usage_total.cost_total)}- />- <MetricItem- label="Duration"- value={formatDuration(session.created_at, session.updated_at)}- />- <MetricItem- label="Errors"- value={String(metrics.errors)}- tone={metrics.errors > 0 ? "bad" : undefined}- />- </>- ) : null}- </Flex>- <RefreshIndicator- updatedAt={dataUpdatedAt}- isFetching={isFetching}- onRefresh={() => void refetch()}- />- </Flex>-- <Flex gap="1" className="-mb-px">- {(["conversation", "logs"] as const).map((t) => (- <button- key={t}- type="button"- onClick={() => setTab(t)}- className={`border-b-2 px-3 pb-2.5 text-[12.5px] capitalize ${- t === tab- ? "border-(--accent-9) font-medium text-gray-12"- : "border-transparent text-gray-11 hover:text-gray-12"- }`}- >- {t}- </button>- ))}- </Flex>- </Flex>-- {/* Flex column with a definite height: ConversationView's root is- `relative flex-1` with an absolutely-positioned VirtualizedList, so it- only gets height inside a flex column (matches prod SessionView). */}- <div className="flex min-h-0 flex-1 flex-col">- {isLoading ? (- <Centered>- <div className="h-24 w-full max-w-2xl animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)" />- </Centered>- ) : isError || !session ? (- <Centered>- <EmptyState- title="Couldn't load this session"- description="It may have been purged, or the agent platform API returned an error."- />- </Centered>- ) : tab === "logs" ? (- // ConversationView owns its own scroll; the logs list does not.- <div className="h-full overflow-auto">- <SessionLogsView- idOrSlug={idOrSlug}- sessionId={sessionId}- startIso={session.created_at}- enabled={tab === "logs"}- />- </div>- ) : session.conversation.length === 0 ? (- <Centered>- <EmptyState- title="No messages yet"- description="This session hasn't produced any conversation turns."- />- </Centered>- ) : (- <ThreadView events={events} isPromptPending={null} />- )}- </div>- </Flex>- );-}--function MetricItem({- label,- value,- tone,- mono,- title,-}: {- label: string;- value: string;- tone?: "bad";- mono?: boolean;- title?: string;-}) {- return (- <Flex direction="column" gap="0.5">- <Text className="text-[10px] text-gray-10 uppercase tracking-wide">- {label}- </Text>- <Text- title={title}- className={`font-semibold leading-none ${- mono ? "text-[12.5px] [font-family:var(--font-mono)]" : "text-[14px]"- } ${tone === "bad" ? "text-(--red-11)" : "text-gray-12"}`}- >- {value}- </Text>- </Flex>- );-}--function Centered({ children }: { children: ReactNode }) {- return (- <div className="flex h-full items-center justify-center px-6 py-10">- {children}- </div>- );-}--function EmptyState({- title,- description,-}: {- title: string;- description: ReactNode;-}) {- return (- <Flex- direction="column"- align="center"- gap="1"- className="rounded-(--radius-2) border border-(--gray-5) border-dashed px-6 py-10 text-center"- >- <Text className="font-medium text-[13px] text-gray-12">{title}</Text>- <Text className="max-w-md text-[12px] text-gray-11 leading-snug">- {description}- </Text>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionRow.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionRow.tsxdeleted file mode 100644index 574c731530fb..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionRow.tsx+++ /dev/null@@ -1,58 +0,0 @@-import { formatRelativeTimeShort } from "@posthog/shared";-import type {- AgentSessionPrincipal,- AgentSessionSummary,-} from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { formatSpendUsd, sessionStateColor } from "../utils/format";--function principalLabel(principal: AgentSessionPrincipal | null): string {- if (!principal) return "anonymous";- return principal.kind;-}--/** A single session row linking to its transcript. Shared by Overview + Sessions. */-export function AgentSessionRow({- session,- idOrSlug,-}: {- session: AgentSessionSummary;- idOrSlug: string;-}) {- return (- <Link- to="/code/agents/applications/$idOrSlug/sessions/$sessionId"- params={{ idOrSlug, sessionId: session.id }}- className="no-underline"- >- <Flex- align="center"- justify="between"- gap="3"- className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3 hover:border-(--gray-7)"- >- <Flex direction="column" gap="1" className="min-w-0">- <Flex align="center" gap="2" className="min-w-0">- <Badge color={sessionStateColor(session.state)}>- {session.state}- </Badge>- <Text className="truncate text-[12.5px] text-gray-12">- {session.preview?.trim()- ? session.preview- : "No assistant output"}- </Text>- </Flex>- <Text className="truncate text-[11px] text-gray-10">- {principalLabel(session.principal)} · {session.turns} turns ·{" "}- {formatSpendUsd(session.usage_total.cost_total)}- </Text>- </Flex>- <Text className="shrink-0 text-[11px] text-gray-10">- {formatRelativeTimeShort(session.updated_at)}- </Text>- </Flex>- </Link>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionTranscriptView.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionTranscriptView.tsxdeleted file mode 100644index b716e4e622a8..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionTranscriptView.tsx+++ /dev/null@@ -1,89 +0,0 @@-import { ArrowLeftIcon } from "@phosphor-icons/react";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useMemo } from "react";-import { AgentBuilderHeaderControls } from "../agent-builder/AgentBuilderHeaderControls";-import { useSetAgentBuilderPage } from "../agent-builder/useSetAgentBuilderPage";-import { useAgentApplicationSession } from "../hooks/useAgentApplicationSession";-import { sessionStateColor } from "../utils/format";-import { AgentSessionDetailBody } from "./AgentSessionDetailBody";-import { CopyButton } from "./CopyButton";--/**- * Full-screen session view: page chrome (back link + title) wrapping the shared- * {@link AgentSessionDetailBody} (KPI strip + Conversation/Logs tabs). The body- * renders the transcript read-only through code's native `ConversationView`.- */-export function AgentSessionTranscriptView({- idOrSlug,- sessionId,-}: {- idOrSlug: string;- sessionId: string;-}) {- const { data: session } = useAgentApplicationSession(idOrSlug, sessionId);- const headerContent = useMemo(- () => (- <Text className="truncate whitespace-nowrap font-medium text-[13px]">- Session- </Text>- ),- [],- );- useSetHeaderContent(headerContent);- const pageContext = {- kind: "agent-session" as const,- slug: idOrSlug,- sessionId,- };- useSetAgentBuilderPage(pageContext);-- return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="3"- className="relative shrink-0 cursor-default select-none px-6 pt-5"- >- <AgentBuilderHeaderControls />- <Link- to="/code/agents/applications/$idOrSlug/sessions"- params={{ idOrSlug }}- className="flex w-fit items-center gap-1.5 text-[12px] text-gray-11 no-underline hover:text-gray-12"- >- <ArrowLeftIcon size={13} />- Sessions- </Link>- <Flex align="center" gap="2" wrap="wrap" className="pr-44">- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- Session- </Text>- <Flex- align="center"- gap="1"- className="rounded-(--radius-1) border border-border bg-(--gray-2) py-0.5 pr-0.5 pl-2 text-[12px] text-gray-10"- >- <span className="font-mono" title="Session id">- {sessionId}- </span>- <CopyButton text={sessionId} label="Copy session id" bare />- </Flex>- {session ? (- <Badge color={sessionStateColor(session.state)}>- {session.state}- </Badge>- ) : null}- </Flex>- </Flex>- <div className="min-h-0 flex-1">- <AgentSessionDetailBody- idOrSlug={idOrSlug}- sessionId={sessionId}- showStateBadge={false}- />- </div>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionsPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionsPane.tsxdeleted file mode 100644index f21f50bf56eb..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentSessionsPane.tsx+++ /dev/null@@ -1,289 +0,0 @@-import {- CaretDownIcon,- MagnifyingGlassIcon,- UserIcon,-} from "@phosphor-icons/react";-import {- Combobox,- ComboboxChip,- ComboboxChips,- ComboboxChipsInput,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxItem,- ComboboxList,- ComboboxTrigger,- ComboboxValue,- Button as QuillButton,-} from "@posthog/quill";-import type {- AgentSessionState,- AgentUserWithConnections,-} from "@posthog/shared/agent-platform-types";-import { Button } from "@posthog/ui/primitives/Button";-import { useDebouncedValue } from "@posthog/ui/primitives/hooks/useDebouncedValue";-import { Flex, Text } from "@radix-ui/themes";-import { useMemo, useRef, useState } from "react";-import { useAgentApplicationSessions } from "../hooks/useAgentApplicationSessions";-import { useAgentUsers } from "../hooks/useAgentUsers";-import { userDisplayName } from "../utils/format";-import { AgentDetailEmptyState, AgentDetailLayout } from "./AgentDetailLayout";-import { AgentSessionRow } from "./AgentSessionRow";-import { RefreshIndicator } from "./RefreshIndicator";--const STATE_OPTIONS: AgentSessionState[] = [- "running",- "completed",- "failed",- "cancelled",- "queued",-];--function stateLabel(state: AgentSessionState): string {- return state.charAt(0).toUpperCase() + state.slice(1);-}--const ALL_USERS = "all";--function userLabel(u: AgentUserWithConnections): string {- return `${u.principal_kind}: ${userDisplayName(u) ?? u.principal_id}`;-}--const PAGE = 25;--/** Per-agent Sessions pane: searchable, state + user filtered, paged history. */-export function AgentSessionsPane({ idOrSlug }: { idOrSlug: string }) {- const [queryInput, setQueryInput] = useState("");- const { debounced: search } = useDebouncedValue(queryInput.trim(), 300);- const [states, setStates] = useState<AgentSessionState[]>([]);- const [userId, setUserId] = useState<string>(ALL_USERS);- const [limit, setLimit] = useState(PAGE);-- const changeQuery = (next: string) => {- setQueryInput(next);- setLimit(PAGE);- };- const changeStates = (next: AgentSessionState[]) => {- setStates(next);- setLimit(PAGE);- };- const changeUser = (next: string) => {- setUserId(next);- setLimit(PAGE);- };-- const { data, isLoading, isError, isFetching, dataUpdatedAt, refetch } =- useAgentApplicationSessions(idOrSlug, {- limit,- state: states.length > 0 ? states : undefined,- agent_user_id: userId === ALL_USERS ? undefined : userId,- search: search || undefined,- });-- const { data: usersData } = useAgentUsers(idOrSlug);- const users = usersData?.results ?? [];-- const sessions = data?.results ?? [];- const total = data?.count ?? sessions.length;- const hasMore = sessions.length < total;- const hasFilters =- states.length > 0 || userId !== ALL_USERS || search.length > 0;-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="sessions">- <Flex direction="column" gap="4">- <Flex align="center" justify="between" gap="3" wrap="wrap">- <div className="relative min-w-0 flex-1 sm:max-w-xs">- <MagnifyingGlassIcon- size={13}- className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-2.5 text-gray-10"- />- <input- type="search"- value={queryInput}- onChange={(e) => changeQuery(e.currentTarget.value)}- placeholder="Search conversations…"- aria-label="Search sessions"- className="h-8 w-full rounded-(--radius-2) border border-border bg-(--color-panel-solid) pr-2 pl-8 text-[12.5px]"- />- </div>- <Flex align="center" gap="2" wrap="wrap" className="shrink-0">- <SessionStateFilter value={states} onChange={changeStates} />- {users.length > 0 ? (- <SessionUserFilter- users={users}- value={userId}- onChange={changeUser}- />- ) : null}- <RefreshIndicator- updatedAt={dataUpdatedAt}- isFetching={isFetching}- onRefresh={() => void refetch()}- />- </Flex>- </Flex>-- {isLoading ? (- <Flex direction="column" gap="2">- {[0, 1, 2, 3].map((i) => (- <div- key={i}- className="h-13 animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- ) : isError ? (- <AgentDetailEmptyState- title="Couldn't load sessions"- description="The agent platform API returned an error."- />- ) : sessions.length === 0 ? (- <AgentDetailEmptyState- title="No sessions"- description={- hasFilters- ? "No sessions match your search and filters."- : "This agent hasn't run any sessions yet."- }- />- ) : (- <Flex direction="column" gap="2">- {sessions.map((session) => (- <AgentSessionRow- key={session.id}- session={session}- idOrSlug={idOrSlug}- />- ))}- <Flex align="center" justify="between" className="pt-1">- <Text className="text-[11px] text-gray-10">- Showing {sessions.length} of {total}- </Text>- {hasMore ? (- <Button- variant="soft"- size="1"- onClick={() => setLimit((l) => l + PAGE)}- loading={isFetching}- >- Load more- </Button>- ) : null}- </Flex>- </Flex>- )}- </Flex>- </AgentDetailLayout>- );-}--function SessionStateFilter({- value,- onChange,-}: {- value: AgentSessionState[];- onChange: (next: AgentSessionState[]) => void;-}) {- const anchorRef = useRef<HTMLDivElement>(null);- return (- <Combobox<AgentSessionState, true>- multiple- items={STATE_OPTIONS}- value={value}- onValueChange={(next) => onChange(next ?? [])}- itemToStringLabel={stateLabel}- >- <ComboboxChips- ref={anchorRef}- className="flex min-h-8 w-52 flex-wrap items-center gap-1 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-1.5 py-1"- >- <ComboboxValue>- {(selected: AgentSessionState[]) =>- selected.map((state) => (- <ComboboxChip key={state} showRemove>- {stateLabel(state)}- </ComboboxChip>- ))- }- </ComboboxValue>- <ComboboxChipsInput- placeholder={value.length === 0 ? "All states" : ""}- aria-label="Filter by state"- className="min-w-12 flex-1 bg-transparent text-[12px] text-gray-12 outline-none placeholder:text-gray-10"- />- </ComboboxChips>- <ComboboxContent anchor={anchorRef} align="start" sideOffset={4}>- <ComboboxEmpty>No states</ComboboxEmpty>- <ComboboxList>- {(state: AgentSessionState) => (- <ComboboxItem key={state} value={state}>- {stateLabel(state)}- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>- );-}--function SessionUserFilter({- users,- value,- onChange,-}: {- users: AgentUserWithConnections[];- value: string;- onChange: (next: string) => void;-}) {- const anchorRef = useRef<HTMLButtonElement>(null);- const items = useMemo(() => [ALL_USERS, ...users.map((u) => u.id)], [users]);- const labelById = useMemo(() => {- const map = new Map<string, string>([[ALL_USERS, "All users"]]);- for (const u of users) map.set(u.id, userLabel(u));- return map;- }, [users]);- const labelFor = (id: string) => labelById.get(id) ?? id;-- return (- <Combobox<string, false>- items={items}- value={value}- onValueChange={(next) => onChange(next ?? ALL_USERS)}- itemToStringLabel={labelFor}- >- <ComboboxTrigger- render={- <QuillButton- ref={anchorRef}- variant="outline"- size="sm"- aria-label="Filter by user"- className="min-w-0 max-w-52"- >- <UserIcon size={13} className="shrink-0 text-gray-10" />- <span className="min-w-0 truncate">{labelFor(value)}</span>- <CaretDownIcon size={10} className="shrink-0 text-gray-10" />- </QuillButton>- }- />- <ComboboxContent- anchor={anchorRef}- align="end"- sideOffset={6}- className="min-w-55"- >- <ComboboxInput placeholder="Search users…" />- <ComboboxEmpty>No users found.</ComboboxEmpty>- <ComboboxList>- {(id: string) => (- <ComboboxItem key={id} value={id} title={labelFor(id)}>- {labelFor(id)}- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/AgentUsersPane.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/AgentUsersPane.tsxdeleted file mode 100644index 245fe0a3800c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/AgentUsersPane.tsx+++ /dev/null@@ -1,243 +0,0 @@-import { FingerprintIcon, ProhibitIcon, UserIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import type {- AgentUserConnection,- AgentUserWithConnections,-} from "@posthog/shared/agent-platform-types";-import { Badge } from "@posthog/ui/primitives/Badge";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Text } from "@radix-ui/themes";-import { useState } from "react";-import {- useAgentUsers,- useDisconnectAgentUserConnection,-} from "../hooks/useAgentUsers";-import { userDisplayName } from "../utils/format";-import { AgentDetailEmptyState, AgentDetailLayout } from "./AgentDetailLayout";-import { RefreshIndicator } from "./RefreshIndicator";--/**- * Per-agent Users pane: the agent's end-users (`agent_user`) and each user's- * linked external identities (`agent_identity_credential`). Connection metadata- * only — credentials are never sent to the client. Lightweight operational- * tooling: revoke a connection now; banning a user is stubbed for later.- */-export function AgentUsersPane({ idOrSlug }: { idOrSlug: string }) {- const { data, isLoading, isError, isFetching, dataUpdatedAt, refetch } =- useAgentUsers(idOrSlug);-- const users = data?.results ?? [];- const total = data?.count ?? users.length;-- return (- <AgentDetailLayout idOrSlug={idOrSlug} activeTab="users">- <Flex direction="column" gap="4">- <Flex align="center" justify="between" gap="3">- <Flex align="center" gap="2">- <Text className="font-semibold text-[13px] text-gray-12">- Users- </Text>- {!isLoading && !isError ? (- <Text className="text-[12px] text-gray-10 tabular-nums">- {total}- </Text>- ) : null}- </Flex>- <RefreshIndicator- updatedAt={dataUpdatedAt}- isFetching={isFetching}- onRefresh={() => void refetch()}- />- </Flex>-- <Text className="text-[12px] text-gray-10 leading-snug">- People who have interacted with this agent and the external identities- they've linked, so the agent can act as them. Credentials are never- shown — only the connection.- </Text>-- {isLoading ? (- <UsersSkeleton />- ) : isError ? (- <AgentDetailEmptyState- title="Couldn't load users"- description="The agent platform API returned an error fetching this agent's users."- />- ) : users.length === 0 ? (- <AgentDetailEmptyState- title="No users yet"- description="Once people interact with this agent, they'll appear here with any identities they link."- />- ) : (- <Flex direction="column" gap="2">- {users.map((user) => (- <UserCard key={user.id} idOrSlug={idOrSlug} user={user} />- ))}- </Flex>- )}- </Flex>- </AgentDetailLayout>- );-}--function UserCard({- idOrSlug,- user,-}: {- idOrSlug: string;- user: AgentUserWithConnections;-}) {- const displayName = userDisplayName(user);-- return (- <div className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3">- <Flex align="center" justify="between" gap="3">- <Flex align="center" gap="2.5" className="min-w-0">- <UserIcon size={18} className="shrink-0 text-gray-11" />- <Flex direction="column" gap="0.5" className="min-w-0">- <Flex align="center" gap="2" className="min-w-0">- <Badge color="gray">{user.principal_kind}</Badge>- <Text className="truncate text-[12.5px] text-gray-12 [font-family:var(--font-mono)]">- {displayName ?? user.principal_id}- </Text>- </Flex>- <Text className="text-[11px] text-gray-10">- {displayName ? `${user.principal_id} · ` : ""}first seen{" "}- {formatRelativeTimeShort(user.created_at)}- </Text>- </Flex>- </Flex>- {/* Banning a user is not yet supported by the backend — stubbed so the- placement is visible while we design the semantics. */}- <Button- size="1"- variant="ghost"- color="gray"- disabled- title="Banning users isn't available yet"- >- <ProhibitIcon size={13} />- Ban- </Button>- </Flex>-- <div className="mt-2.5 border-(--gray-4) border-t pt-2.5">- {user.connections.length === 0 ? (- <Text className="text-[11.5px] text-gray-10">- No linked connections.- </Text>- ) : (- <Flex direction="column" gap="1.5">- {user.connections.map((c) => (- <ConnectionRow- key={c.id}- idOrSlug={idOrSlug}- agentUserId={user.id}- connection={c}- />- ))}- </Flex>- )}- </div>- </div>- );-}--function ConnectionRow({- idOrSlug,- agentUserId,- connection,-}: {- idOrSlug: string;- agentUserId: string;- connection: AgentUserConnection;-}) {- const [confirming, setConfirming] = useState(false);- const disconnect = useDisconnectAgentUserConnection(idOrSlug);- const active = connection.state === "active";-- return (- <Flex- align="center"- gap="2"- className="rounded-(--radius-1) bg-(--gray-2) px-2.5 py-1.5"- >- <FingerprintIcon size={13} className="shrink-0 text-gray-10" />- <Text className="shrink-0 text-[12px] text-gray-12 [font-family:var(--font-mono)]">- {connection.provider}- </Text>- <Badge color={active ? "green" : "gray"}>{connection.state}</Badge>- {connection.subject ? (- <Text- className="min-w-0 truncate text-[11px] text-gray-10"- title={`subject: ${connection.subject}`}- >- {connection.subject}- </Text>- ) : null}- {connection.scopes.length > 0 ? (- <Text- className="shrink-0 text-[11px] text-gray-10"- title={connection.scopes.join(", ")}- >- {connection.scopes.length} scope- {connection.scopes.length === 1 ? "" : "s"}- </Text>- ) : null}- <Text className="ml-auto shrink-0 text-[11px] text-gray-10">- linked {formatRelativeTimeShort(connection.created_at)}- </Text>- {active ? (- confirming ? (- <Flex align="center" gap="1" className="shrink-0">- <Button- size="1"- variant="solid"- color="red"- disabled={disconnect.isPending}- onClick={() =>- disconnect.mutate(- { agentUserId, provider: connection.provider },- { onSettled: () => setConfirming(false) },- )- }- >- {disconnect.isPending ? "Revoking…" : "Confirm"}- </Button>- <Button- size="1"- variant="soft"- color="gray"- onClick={() => setConfirming(false)}- >- Cancel- </Button>- </Flex>- ) : (- <Button- size="1"- variant="soft"- color="gray"- className="shrink-0"- onClick={() => setConfirming(true)}- >- Disconnect- </Button>- )- ) : null}- </Flex>- );-}--function UsersSkeleton() {- return (- <Flex direction="column" gap="2">- {[0, 1, 2].map((i) => (- <div- key={i}- className="h-[84px] animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)"- />- ))}- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/CronFireButton.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/CronFireButton.tsxdeleted file mode 100644index 0677cdb5dbc1..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/CronFireButton.tsx+++ /dev/null@@ -1,49 +0,0 @@-import {- PlayIcon,- SpinnerIcon,- WarningCircleIcon,-} from "@phosphor-icons/react";-import { Button } from "@posthog/ui/primitives/Button";-import { useFireAgentCron } from "../hooks/useFireAgentCron";--/**- * "Run now" — fires a cron trigger out-of-band (not on its schedule) so an- * author can test it. On success, hands the created session id back so the- * caller can jump straight to the run.- */-export function CronFireButton({- idOrSlug,- revisionId,- cronName,- onFired,-}: {- idOrSlug: string;- revisionId: string;- cronName: string;- onFired?: (sessionId: string) => void;-}) {- const fire = useFireAgentCron(idOrSlug, revisionId);- return (- <Button- size="1"- variant="soft"- color={fire.isError ? "red" : "gray"}- disabled={fire.isPending}- onClick={() =>- fire.mutate(- { cronName },- { onSuccess: (res) => onFired?.(res.session_id) },- )- }- >- {fire.isPending ? (- <SpinnerIcon size={13} className="animate-spin" />- ) : fire.isError ? (- <WarningCircleIcon size={13} />- ) : (- <PlayIcon size={13} />- )}- {fire.isPending ? "Firing…" : fire.isError ? "Failed" : "Run now"}- </Button>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/DeepLinkApprovalModal.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/DeepLinkApprovalModal.tsxdeleted file mode 100644index d39fba40b971..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/DeepLinkApprovalModal.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { LockKeyIcon } from "@phosphor-icons/react";-import type { DecideApprovalRequest } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { toast } from "@posthog/ui/primitives/toast";-import { Dialog, Flex, Text } from "@radix-ui/themes";-import { useMutation, useQuery } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import type { PendingApprovalDeepLink } from "../hooks/useApprovalDeepLink";-import { agentIngressBaseUrl } from "../utils/ingress";-import { AgentApprovalDecisionForm } from "./AgentApprovalDecisionForm";-import { ArgsSection } from "./AgentApprovalDetail";--/**- * The approval surface for non-Code channels (MCP, a Slack link): a- * `<scheme>://approval/<id>?agent=<slug>` deep link opens PostHog into this- * modal. Fetch + decide go straight to the slug-routed ingress, authenticated- * as the session principal (the user's bearer) — no project-scoped console call,- * so it resolves from any project. The link carries only a non-actionable id +- * slug, never a credential.- */-export function DeepLinkApprovalModal({- pending,- onClose,-}: {- pending: PendingApprovalDeepLink;- onClose: () => void;-}) {- const client = useAuthenticatedClient();- const region = useAuthStateValue((s) => s.cloudRegion);- const ingressBaseUrl = agentIngressBaseUrl(pending.agent, region);-- const {- data: approval,- isLoading,- isError,- } = useQuery({- queryKey: ["deep-link-approval", pending.agent, pending.requestId],- queryFn: () =>- ingressBaseUrl- ? client.getAgentApprovalViaIngress(ingressBaseUrl, pending.requestId)- : null,- enabled: !!ingressBaseUrl,- staleTime: 10_000,- });-- const decide = useMutation<unknown, Error, DecideApprovalRequest>({- mutationFn: (body) => {- if (!ingressBaseUrl) {- throw new Error(- "Couldn't resolve the agent's ingress for your region.",- );- }- return client.decideAgentApprovalViaIngress(- ingressBaseUrl,- pending.requestId,- body,- );- },- onSuccess: (_data, body) => {- toast.success(body.decision === "approve" ? "Approved" : "Rejected", {- description:- body.decision === "approve"- ? "Dispatched to the agent."- : "The agent will see the rejection.",- });- onClose();- },- onError: (err) => {- toast.error("Decision failed", {- description: err instanceof Error ? err.message : undefined,- });- },- });-- return (- <Dialog.Root open onOpenChange={(o) => !o && onClose()}>- <Dialog.Content maxWidth="520px">- <Dialog.Title>- <Flex align="center" gap="2">- <LockKeyIcon size={16} className="text-(--amber-11)" />- <Text className="font-semibold text-[14px]">Approval needed</Text>- </Flex>- </Dialog.Title>-- {isLoading ? (- <Text className="text-[13px] text-gray-10">Loading approval…</Text>- ) : isError || !approval ? (- <Dialog.Description>- <Text className="text-[13px] text-gray-11">- Couldn't load this approval — it may have expired, already been- decided, or belong to a session you don't own.- </Text>- </Dialog.Description>- ) : (- <Flex direction="column" gap="2">- <Text className="font-medium font-mono text-[13px] text-gray-12">- {approval.tool_name}- </Text>- <ArgsSection- label="Proposed arguments"- args={approval.proposed_args}- />- <AgentApprovalDecisionForm- approval={approval}- busy={decide.isPending}- error={- decide.isError- ? decide.error instanceof Error- ? decide.error.message- : "Decision failed"- : null- }- onSubmit={(body) => decide.mutate(body)}- />- </Flex>- )}- </Dialog.Content>- </Dialog.Root>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/FileExplorer.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/FileExplorer.tsxdeleted file mode 100644index 2c7268a2cfe7..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/FileExplorer.tsx+++ /dev/null@@ -1,361 +0,0 @@-import {- CaretDownIcon,- CaretRightIcon,- FileIcon,- FolderIcon,- FolderOpenIcon,- MagnifyingGlassIcon,-} from "@phosphor-icons/react";-import { type ReactNode, useMemo, useState } from "react";-import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";--export interface FileTreeNode {- type: "file" | "folder";- name: string;- /** Set on files (and optionally folders) — the click target for selection. */- path?: string;- /** One-line annotation under the name (e.g. a skill/memory description). */- description?: string;- /** Icon override for the row. Defaults to a generic file/folder icon. */- icon?: ReactNode;- /** Right-aligned slot (e.g. an approval lock or a "needs attention" badge). */- trailing?: ReactNode;- children?: FileTreeNode[];-}--export interface FileExplorerSearchResult {- path: string;- name?: string;- description?: string;- snippet?: string;- score?: number;-}--interface SearchConfig {- query: string;- onChange: (query: string) => void;- /** Non-null = results mode (flat list). Null/undefined = tree mode. */- results?: FileExplorerSearchResult[] | null;- placeholder?: string;- loading?: boolean;-}--export interface FileExplorerProps {- tree: FileTreeNode | null;- selectedPath: string | null;- onSelectPath: (path: string) => void;- /** Optional search input + flat results override (e.g. memory BM25 search). */- search?: SearchConfig;- /** Top-of-left-pane action (e.g. a "+ New" button). */- topAction?: ReactNode;- /** Right-pane content — the consumer renders whatever fits the selection. */- children: ReactNode;- emptyMessage?: string;- loading?: boolean;- error?: Error | null;- /**- * Distinct localStorage key per surface so the bundle tree and the memory- * tree persist their widths independently.- */- storageKey: string;-}--/**- * Generic two-pane file explorer: a collapsible folder tree (or flat search- * results) on the left, arbitrary `children` on the right. Selection is- * controlled so URL state + refetch stay with the consumer. The same wrapper- * backs the read-only config bundle and the editable memory surface, so the- * two feel identical to navigate. Ported from the agent-console's FileExplorer.- */-export function FileExplorer({- tree,- selectedPath,- onSelectPath,- search,- topAction,- children,- emptyMessage = "No files yet.",- loading,- error,- storageKey,-}: FileExplorerProps) {- const searching = !!search && search.query.trim().length > 0;-- return (- <PanelGroup- direction="horizontal"- autoSaveId={storageKey}- className="h-full overflow-hidden bg-(--color-panel-solid)"- >- <Panel defaultSize={24} minSize={15} maxSize={42} order={1}>- <div className="flex h-full flex-col bg-(--gray-2)">- {search || topAction ? (- <div className="space-y-2 border-(--gray-5) border-b px-2 py-2">- {search ? (- <div className="relative">- <MagnifyingGlassIcon- size={12}- className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-2 text-gray-10"- />- <input- type="search"- value={search.query}- onChange={(e) => search.onChange(e.currentTarget.value)}- placeholder={search.placeholder ?? "Search…"}- className="h-7 w-full rounded-(--radius-1) border border-border bg-(--color-panel-solid) pr-2 pl-7 text-[12px]"- />- </div>- ) : null}- {topAction ? <div>{topAction}</div> : null}- </div>- ) : null}- <div className="min-h-0 flex-1 overflow-y-auto py-1.5">- {loading ? (- <div className="px-3 py-2 text-[12px] text-gray-10">Loading…</div>- ) : error ? (- <div className="px-3 py-2 text-(--red-11) text-[12px]">- {error.message}- </div>- ) : searching ? (- <SearchResultsList- results={search?.results ?? []}- loading={search?.loading}- selectedPath={selectedPath}- onSelectPath={onSelectPath}- />- ) : tree?.children && tree.children.length > 0 ? (- <TreeView- node={tree}- selected={selectedPath}- onSelect={onSelectPath}- depth={0}- />- ) : (- <div className="px-3 py-2 text-[12px] text-gray-10">- {emptyMessage}- </div>- )}- </div>- </div>- </Panel>- <PanelResizeHandle className="w-px bg-(--gray-5) transition-colors hover:bg-(--gray-7) data-[resize-handle-state=drag]:bg-(--accent-9)" />- <Panel order={2}>- <div className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">- {children}- </div>- </Panel>- </PanelGroup>- );-}--const ROW_SELECTED =- "bg-(--accent-3) font-medium text-gray-12 shadow-[inset_2px_0_0_0_var(--accent-9)]";-const ROW_IDLE = "text-gray-11 hover:bg-(--gray-3) hover:text-gray-12";--function subtreeContains(node: FileTreeNode, path: string | null): boolean {- if (!path) return false;- for (const child of node.children ?? []) {- if (child.path === path || subtreeContains(child, path)) return true;- }- return false;-}--function TreeView({- node,- selected,- onSelect,- depth,-}: {- node: FileTreeNode;- selected: string | null;- onSelect: (path: string) => void;- depth: number;-}) {- return (- <ul className="text-[12px]">- {(node.children ?? []).map((child) =>- child.type === "folder" ? (- <FolderRow- key={`d:${child.name}:${child.path ?? ""}`}- node={child}- selected={selected}- onSelect={onSelect}- depth={depth}- />- ) : (- <FileRow- key={`f:${child.path}`}- node={child}- selected={!!child.path && selected === child.path}- onSelect={onSelect}- depth={depth}- />- ),- )}- </ul>- );-}--function FolderRow({- node,- selected,- onSelect,- depth,-}: {- node: FileTreeNode;- selected: string | null;- onSelect: (path: string) => void;- depth: number;-}) {- const [open, setOpen] = useState(true);- const isSelected = !!node.path && selected === node.path;- const hasSelectedChild = useMemo(- () => subtreeContains(node, selected),- [node, selected],- );- // Auto-expand when the selection moves into a descendant. Reconciled during- // render (not in an effect) so the folder opens before paint.- const [prevHasSelectedChild, setPrevHasSelectedChild] =- useState(hasSelectedChild);- if (hasSelectedChild !== prevHasSelectedChild) {- setPrevHasSelectedChild(hasSelectedChild);- if (hasSelectedChild) setOpen(true);- }-- return (- <li>- <button- type="button"- onClick={() => {- setOpen((o) => !o);- if (node.path) onSelect(node.path);- }}- aria-current={isSelected ? "true" : undefined}- className={`flex w-full cursor-pointer items-center gap-1 px-2 py-1 text-left transition-colors ${isSelected ? ROW_SELECTED : ROW_IDLE}`}- style={{ paddingLeft: `${8 + depth * 12}px` }}- >- {open ? (- <CaretDownIcon size={11} className="shrink-0" />- ) : (- <CaretRightIcon size={11} className="shrink-0" />- )}- {node.icon ??- (open ? (- <FolderOpenIcon size={14} className="shrink-0" />- ) : (- <FolderIcon size={14} className="shrink-0" />- ))}- <span className="min-w-0 flex-1 truncate">{node.name}</span>- {node.trailing ? (- <span className="ml-auto shrink-0 pl-1">{node.trailing}</span>- ) : null}- </button>- {open && node.children && node.children.length > 0 ? (- <TreeView- node={{ type: "folder", name: node.name, children: node.children }}- selected={selected}- onSelect={onSelect}- depth={depth + 1}- />- ) : null}- </li>- );-}--function FileRow({- node,- selected,- onSelect,- depth,-}: {- node: FileTreeNode;- selected: boolean;- onSelect: (path: string) => void;- depth: number;-}) {- if (!node.path) return null;- const path = node.path;- return (- <li>- <button- type="button"- onClick={() => onSelect(path)}- aria-current={selected ? "true" : undefined}- className={`flex w-full cursor-pointer items-start gap-1.5 px-2 py-1 text-left transition-colors ${selected ? ROW_SELECTED : ROW_IDLE}`}- style={{ paddingLeft: `${8 + depth * 12 + 16}px` }}- >- <span className="mt-px shrink-0">- {node.icon ?? <FileIcon size={14} className="shrink-0" />}- </span>- <span className="min-w-0 flex-1">- <span className="block truncate">{node.name}</span>- {node.description ? (- <span className="block truncate text-[10.5px] text-gray-9">- {node.description}- </span>- ) : null}- </span>- {node.trailing ? (- <span className="mt-px shrink-0 pl-1">{node.trailing}</span>- ) : null}- </button>- </li>- );-}--function SearchResultsList({- results,- loading,- selectedPath,- onSelectPath,-}: {- results: FileExplorerSearchResult[];- loading?: boolean;- selectedPath: string | null;- onSelectPath: (path: string) => void;-}) {- if (loading) {- return <div className="px-3 py-2 text-[12px] text-gray-10">Searching…</div>;- }- if (results.length === 0) {- return (- <div className="px-3 py-2 text-[12px] text-gray-10">No matches.</div>- );- }- return (- <ul className="space-y-0.5 px-1">- {results.map((r) => {- const isActive = selectedPath === r.path;- return (- <li key={r.path}>- <button- type="button"- onClick={() => onSelectPath(r.path)}- aria-current={isActive ? "true" : undefined}- className={`flex w-full cursor-pointer flex-col gap-0.5 rounded-(--radius-1) px-2 py-1 text-left text-[12px] transition-colors ${isActive ? ROW_SELECTED : ROW_IDLE}`}- >- <div className="flex items-center justify-between gap-2">- <span className="truncate font-medium">{r.name ?? r.path}</span>- {typeof r.score === "number" ? (- <span className="shrink-0 text-[10px] text-gray-9">- {r.score.toFixed(2)}- </span>- ) : null}- </div>- {r.description ? (- <span className="truncate text-[10.5px] text-gray-10">- {r.description}- </span>- ) : null}- {r.snippet ? (- <span className="truncate text-[10.5px] text-gray-9 italic">- {r.snippet}- </span>- ) : null}- </button>- </li>- );- })}- </ul>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/RefreshIndicator.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/RefreshIndicator.tsxdeleted file mode 100644index a39b324fc192..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/RefreshIndicator.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { ArrowsClockwiseIcon } from "@phosphor-icons/react";-import { formatRelativeTimeShort } from "@posthog/shared";-import { IconButton, Text, Tooltip } from "@radix-ui/themes";--/**- * "Updated Xs ago" label + a manual refresh button. Pairs with a react-query- * `refetchInterval` (which auto-polls and pauses when the tab is unfocused);- * this just surfaces freshness and a manual nudge. `updatedAt` is the query's- * `dataUpdatedAt` (epoch ms; 0 before the first load).- */-export function RefreshIndicator({- updatedAt,- isFetching,- onRefresh,- compact = false,-}: {- updatedAt: number;- isFetching: boolean;- onRefresh: () => void;- compact?: boolean;-}) {- return (- <div className="flex items-center gap-1.5">- {!compact ? (- <Text className="text-[11px] text-gray-10">- {isFetching- ? "updating…"- : updatedAt- ? `updated ${formatRelativeTimeShort(updatedAt)}`- : ""}- </Text>- ) : null}- <Tooltip content="Refresh">- <IconButton- size="1"- variant="ghost"- color="gray"- onClick={onRefresh}- disabled={isFetching}- aria-label="Refresh"- >- <ArrowsClockwiseIcon- size={14}- className={isFetching ? "animate-spin" : undefined}- />- </IconButton>- </Tooltip>- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/SecretEditor.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/SecretEditor.tsxdeleted file mode 100644index a6802eaf9a88..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/SecretEditor.tsx+++ /dev/null@@ -1,181 +0,0 @@-import { CheckCircleIcon } from "@phosphor-icons/react";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Text, TextField } from "@radix-ui/themes";-import { useState } from "react";-import { useAgentEnvKeyMutations } from "../hooks/useAgentEnvKeyMutations";--/**- * Inline set/rotate/clear for one encrypted env key. The value is write-only —- * posted straight to `env_keys` PUT, never read back. On success the env-keys- * list refetches, flipping set/not-set status across the explorer.- *- * A set secret shows only its status + a Rotate affordance (the input stays- * hidden until you opt in) and Clear is a two-step confirm — clearing a live- * credential is destructive and must never be a single click.- */-export function SecretEditor({- idOrSlug,- revisionId,- keyName,- isSet,-}: {- idOrSlug: string;- revisionId: string;- keyName: string;- isSet: boolean;-}) {- const { setKey, clearKey } = useAgentEnvKeyMutations(idOrSlug, revisionId);- // For a set secret the input is hidden until the user chooses to rotate.- const [editing, setEditing] = useState(false);- const [value, setValue] = useState("");- const [confirmingClear, setConfirmingClear] = useState(false);- const [justSaved, setJustSaved] = useState(false);-- const busy = setKey.isPending || clearKey.isPending;- const showInput = !isSet || editing;-- function save() {- if (!value.trim()) return;- setKey.mutate(- { key: keyName, value },- {- onSuccess: () => {- setValue("");- setEditing(false);- setJustSaved(true);- setTimeout(() => setJustSaved(false), 2000);- },- },- );- }-- function cancelEdit() {- setEditing(false);- setValue("");- }-- function confirmClear() {- clearKey.mutate(- { key: keyName },- { onSettled: () => setConfirmingClear(false) },- );- }-- return (- <Flex direction="column" gap="2" className="mt-2">- {showInput ? (- <>- <Text className="text-[11px] text-gray-10 uppercase tracking-wide">- {isSet ? "Rotate value" : "Set value"}- </Text>- <TextField.Root- type="password"- value={value}- onChange={(e) => setValue(e.target.value)}- placeholder="paste secret value"- autoComplete="off"- spellCheck={false}- onKeyDown={(e) => {- if (e.key === "Enter") save();- }}- />- {isSet ? (- <Text className="text-[11px] text-gray-10">- A value is already set — saving will replace it.- </Text>- ) : null}- {setKey.isError ? (- <Text className="text-(--red-11) text-[11px]">- {setKey.error?.message ?? "Couldn't save"}- </Text>- ) : null}- <Flex align="center" gap="2">- <Button- size="1"- color="green"- onClick={save}- disabled={busy || !value.trim()}- loading={setKey.isPending}- >- {isSet ? "Save new value" : "Set"}- </Button>- {isSet ? (- <Button- size="1"- variant="soft"- color="gray"- onClick={cancelEdit}- disabled={busy}- >- Cancel- </Button>- ) : null}- </Flex>- </>- ) : confirmingClear ? (- <div className="rounded-(--radius-2) border border-(--red-6) bg-(--red-2) px-3 py-2.5">- <Text className="block text-[12px] text-gray-12">- Clear{" "}- <code className="[font-family:var(--font-mono)]">{keyName}</code>?- This deletes the stored value — the agent will stop being able to- read it until you set it again.- </Text>- {clearKey.isError ? (- <Text className="mt-1 block text-(--red-11) text-[11px]">- {clearKey.error?.message ?? "Couldn't clear"}- </Text>- ) : null}- <Flex gap="2" className="mt-2">- <Button- size="1"- color="red"- onClick={confirmClear}- disabled={busy}- loading={clearKey.isPending}- >- Yes, clear it- </Button>- <Button- size="1"- variant="soft"- color="gray"- onClick={() => setConfirmingClear(false)}- disabled={busy}- >- Cancel- </Button>- </Flex>- </div>- ) : (- <Flex align="center" gap="2">- <Button- size="1"- variant="soft"- color="gray"- onClick={() => setEditing(true)}- >- Rotate- </Button>- <Button- size="1"- variant="soft"- color="red"- onClick={() => setConfirmingClear(true)}- >- Clear- </Button>- {justSaved ? (- <Flex align="center" gap="1" className="text-(--green-11)">- <CheckCircleIcon size={14} />- <Text className="text-[12px]">Saved</Text>- </Flex>- ) : null}- </Flex>- )}- <Text className="text-[11px] text-gray-10 leading-snug">- The value is never shown again. It's encrypted at rest and only read by- the agent at runtime.- </Text>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/SessionLogsView.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/SessionLogsView.tsxdeleted file mode 100644index 8b77a4587946..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/SessionLogsView.tsx+++ /dev/null@@ -1,143 +0,0 @@-import { formatRelativeTimeShort } from "@posthog/shared";-import type { AgentSessionLogEntry } from "@posthog/shared/agent-platform-types";-import { Flex, Text, TextField } from "@radix-ui/themes";-import { useMemo, useState } from "react";-import { useAgentApplicationSessionLogs } from "../hooks/useAgentApplicationSessionLogs";-import { formatDuration, logLevelColor } from "../utils/format";--type LevelFilter = "all" | "DEBUG" | "INFO" | "WARN" | "ERROR";--const LEVELS: LevelFilter[] = ["all", "DEBUG", "INFO", "WARN", "ERROR"];--/** Relative offset from session start ("+1.2s"), falling back to a clock label. */-function offsetLabel(startIso: string, ts: string): string {- const d = formatDuration(startIso, ts);- return d === "—" ? formatRelativeTimeShort(ts) : `+${d}`;-}--/**- * Structured runtime log viewer for one session: level dot, offset from session- * start, message. Level + substring filtering is client-side over the fetched- * page (the API also filters server-side, but a page is small enough to scan).- */-export function SessionLogsView({- idOrSlug,- sessionId,- startIso,- enabled,-}: {- idOrSlug: string;- sessionId: string;- startIso: string;- enabled: boolean;-}) {- const [level, setLevel] = useState<LevelFilter>("all");- const [search, setSearch] = useState("");-- const { data, isLoading, isError } = useAgentApplicationSessionLogs(- idOrSlug,- sessionId,- { enabled, params: { limit: 200 } },- );-- const filtered = useMemo(() => {- const entries = data ?? [];- const q = search.trim().toLowerCase();- return entries.filter((e) => {- if (level !== "all" && e.level.toUpperCase() !== level) return false;- if (q && !e.message.toLowerCase().includes(q)) return false;- return true;- });- }, [data, level, search]);-- return (- <Flex direction="column" gap="3" className="mx-auto max-w-4xl px-6 py-5">- <Flex align="center" gap="3" wrap="wrap" justify="between">- <Flex gap="1.5" wrap="wrap">- {LEVELS.map((l) => (- <button- key={l}- type="button"- onClick={() => setLevel(l)}- className={`rounded-full border px-2.5 py-0.5 text-[11px] uppercase ${- level === l- ? "border-(--accent-7) bg-(--accent-3) text-gray-12"- : "border-border text-gray-11 hover:border-(--gray-7)"- }`}- >- {l === "all" ? "All" : l}- </button>- ))}- </Flex>- <TextField.Root- size="1"- placeholder="Search messages"- value={search}- onChange={(e) => setSearch(e.target.value)}- className="w-48"- />- </Flex>-- {isLoading ? (- <Flex direction="column" gap="1">- {[0, 1, 2, 3, 4].map((i) => (- <div- key={i}- className="h-6 animate-pulse rounded-(--radius-1) bg-(--gray-2)"- />- ))}- </Flex>- ) : isError ? (- <Text className="text-[12px] text-gray-11">- Couldn't load logs for this session.- </Text>- ) : filtered.length === 0 ? (- <Text className="text-[12px] text-gray-10">- {(data?.length ?? 0) === 0- ? "No logs recorded for this session."- : "No logs match the current filter."}- </Text>- ) : (- <div className="overflow-hidden rounded-(--radius-2) border border-border">- {filtered.map((entry, i) => (- <LogRow- key={`${entry.timestamp}-${i}`}- entry={entry}- startIso={startIso}- last={i === filtered.length - 1}- />- ))}- </div>- )}- </Flex>- );-}--function LogRow({- entry,- startIso,- last,-}: {- entry: AgentSessionLogEntry;- startIso: string;- last: boolean;-}) {- return (- <Flex- align="start"- gap="3"- className={`px-3 py-1.5 ${last ? "" : "border-(--gray-4) border-b"} hover:bg-(--gray-2)`}- >- <span- className="mt-1.5 size-1.5 shrink-0 rounded-full"- style={{ backgroundColor: logLevelColor(entry.level) }}- />- <Text className="w-14 shrink-0 text-[11px] text-gray-10 tabular-nums [font-family:var(--font-mono)]">- {offsetLabel(startIso, entry.timestamp)}- </Text>- <Text className="min-w-0 whitespace-pre-wrap break-words text-[12px] text-gray-12 [font-family:var(--font-mono)]">- {entry.message}- </Text>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/SlackSetupCard.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/SlackSetupCard.tsxdeleted file mode 100644index 8d87df73515c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/SlackSetupCard.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { ArrowSquareOutIcon, ChatCircleIcon } from "@phosphor-icons/react";-import { Flex, Text } from "@radix-ui/themes";-import { useAgentSlackManifest } from "../hooks/useAgentSlackManifest";-import { CopyButton } from "./CopyButton";--/**- * Deterministic Slack app setup for a slack-triggered agent: the manifest the- * backend derives from the trigger + tools (scopes + event subscriptions- * computed), the "create from manifest" link, the live request URLs, and setup- * notes. Surfaced under the slack trigger's detail.- */-export function SlackSetupCard({- idOrSlug,- revisionId,-}: {- idOrSlug: string;- revisionId: string;-}) {- const { data, isLoading, isError, error } = useAgentSlackManifest(- idOrSlug,- revisionId,- );- const manifestJson = data ? JSON.stringify(data.manifest, null, 2) : "";- const interactivity = data- ? (data.manifest as { settings?: { interactivity?: unknown } }).settings- ?.interactivity- : undefined;-- return (- <section className="mt-3 overflow-hidden rounded-(--radius-2) border border-border">- <Flex- align="center"- gap="2"- className="border-(--gray-5) border-b bg-(--gray-2) px-4 py-1.5 text-[10.5px] text-gray-10 uppercase tracking-wide"- >- <ChatCircleIcon size={13} />- Slack app setup- </Flex>- {isLoading && !data ? (- <Text className="block px-4 py-3 text-[12px] text-gray-10">- Generating manifest…- </Text>- ) : isError ? (- <Text className="block px-4 py-3 text-[12px] text-gray-10">- Could not generate the Slack manifest: {error?.message}- </Text>- ) : data ? (- <Flex direction="column" gap="3" className="px-4 py-3">- <Text className="text-[11.5px] text-gray-10 leading-snug">- Paste this manifest into Slack to create the app with the right- scopes and event subscriptions already filled in — derived from this- agent's trigger config and tools.- </Text>- <Flex align="center" gap="2" wrap="wrap">- <a- href="https://api.slack.com/apps?new_app=1"- target="_blank"- rel="noreferrer"- className="inline-flex h-7 items-center gap-1.5 rounded-(--radius-2) bg-(--accent-9) px-2.5 font-medium text-[11.5px] text-white no-underline hover:opacity-90"- >- <ArrowSquareOutIcon size={12} />- Create Slack app from manifest- </a>- <CopyButton text={manifestJson} label="Copy manifest" showLabel />- </Flex>- <Text className="text-[11.5px] text-gray-10 leading-snug">- In Slack, choose “From an app manifest”, pick the workspace, then- paste the JSON below (use the JSON tab).- </Text>- <pre className="max-h-80 overflow-auto rounded-(--radius-2) border border-border bg-(--gray-2) p-2.5 text-[11px] leading-relaxed">- <code className="[font-family:var(--font-mono)]">- {manifestJson}- </code>- </pre>- <Flex direction="column" gap="1.5" className="text-[11.5px]">- <RequestUrlRow- label="Event Subscriptions Request URL"- url={data.events_url}- />- {interactivity ? (- <RequestUrlRow- label="Interactivity Request URL"- url={data.interactivity_url}- />- ) : null}- </Flex>- {data.notes.length > 0 ? (- <ul className="list-disc space-y-0.5 pl-4 text-[10.5px] text-gray-10">- {data.notes.map((note) => (- <li key={note}>{note}</li>- ))}- </ul>- ) : null}- </Flex>- ) : (- <Text className="block px-4 py-3 text-[12px] text-gray-10">- No manifest available.- </Text>- )}- </section>- );-}--function RequestUrlRow({ label, url }: { label: string; url: string | null }) {- return (- <Flex align="baseline" gap="2">- <Text className="shrink-0 text-gray-10">{label}:</Text>- {url ? (- <Flex align="center" gap="1.5" className="min-w-0">- <code className="truncate [font-family:var(--font-mono)]">{url}</code>- <CopyButton text={url} />- </Flex>- ) : (- <Text className="text-gray-9 italic">- not available (no public ingress URL configured)- </Text>- )}- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/ToolDryRunPanel.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/ToolDryRunPanel.tsxdeleted file mode 100644index 61d0fce37af0..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/ToolDryRunPanel.tsx+++ /dev/null@@ -1,272 +0,0 @@-import {- CheckCircleIcon,- PlayIcon,- PlusIcon,- TrashIcon,- WarningCircleIcon,-} from "@phosphor-icons/react";-import type { DryRunToolResult } from "@posthog/shared/agent-platform-types";-import { Button } from "@posthog/ui/primitives/Button";-import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";-import { Flex, IconButton, Text, TextArea, TextField } from "@radix-ui/themes";-import { type ReactNode, useRef, useState } from "react";-import { useDryRunRevisionTool } from "../hooks/useDryRunRevisionTool";--interface SecretRow {- /** Stable per-row id so React keys survive reordering/removal. */- id: number;- name: string;- value: string;-}--/**- * Minimal dry-run surface for a persisted tool: an args JSON editor, an optional- * mock-secrets key/value editor, and a Test button that runs the tool once in a- * sandbox. The dry-run envelope's `ok` is authoritative (a throwing tool is HTTP- * 200 with ok:false), and throttled (429) / unavailable (503) are handled as- * explicit states — no retries, since dry-run is process-capped.- */-export function ToolDryRunPanel({- idOrSlug,- revisionId,- toolId,-}: {- idOrSlug: string;- revisionId: string;- toolId: string;-}) {- const dryRun = useDryRunRevisionTool(idOrSlug, revisionId);- const [argsText, setArgsText] = useState("{}");- const [argsError, setArgsError] = useState<string | null>(null);- const [secrets, setSecrets] = useState<SecretRow[]>([]);- const [result, setResult] = useState<DryRunToolResult | null>(null);- const nextSecretId = useRef(0);-- function run() {- let args: unknown;- try {- args = argsText.trim() ? JSON.parse(argsText) : {};- } catch {- setArgsError("Args must be valid JSON.");- return;- }- setArgsError(null);- setResult(null);-- const mockSecrets: Record<string, string> = {};- for (const s of secrets) {- const name = s.name.trim();- if (name) mockSecrets[name] = s.value;- }- const hasSecrets = Object.keys(mockSecrets).length > 0;-- dryRun.mutate(- {- toolId,- body: { args, ...(hasSecrets ? { mock_secrets: mockSecrets } : {}) },- },- { onSuccess: (res) => setResult(res) },- );- }-- return (- <div className="mt-3 rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-3">- <Text className="block text-[11px] text-gray-10 uppercase tracking-wide [font-family:var(--font-mono)]">- Dry run- </Text>- <Text className="mt-0.5 mb-2 block text-[11px] text-gray-10 leading-snug">- Runs the saved tool once in a sandbox. Args are passed straight to{" "}- <code className="[font-family:var(--font-mono)]">actions.default</code>{" "}- — they aren't validated against the schema.- </Text>-- <Text className="mb-1 block text-[11px] text-gray-10">Args (JSON)</Text>- <TextArea- value={argsText}- onChange={(e) => setArgsText(e.target.value)}- rows={5}- spellCheck={false}- className="text-[12px] [font-family:var(--font-mono)]"- />- {argsError ? (- <Text className="mt-1 block text-(--red-11) text-[11px]">- {argsError}- </Text>- ) : null}-- <Flex align="center" justify="between" className="mt-3 mb-1">- <Text className="text-[11px] text-gray-10">- Mock secrets (optional)- </Text>- <Button- size="1"- variant="ghost"- color="gray"- onClick={() =>- setSecrets((s) => [- ...s,- { id: nextSecretId.current++, name: "", value: "" },- ])- }- >- <PlusIcon size={12} />- Add- </Button>- </Flex>- {secrets.length === 0 ? (- <Text className="block text-[11px] text-gray-9 leading-snug">- Each entry is the placeholder{" "}- <code className="[font-family:var(--font-mono)]">- ctx.secrets.ref("NAME")- </code>{" "}- returns in the sandbox. Real secret values never leave the backend.- </Text>- ) : (- <Flex direction="column" gap="1.5">- {secrets.map((row) => (- <Flex key={row.id} align="center" gap="2">- <TextField.Root- value={row.name}- placeholder="SECRET_NAME"- spellCheck={false}- className="flex-1 text-[12px] [font-family:var(--font-mono)]"- onChange={(e) =>- setSecrets((s) =>- s.map((r) =>- r.id === row.id ? { ...r, name: e.target.value } : r,- ),- )- }- />- <TextField.Root- value={row.value}- placeholder="placeholder value"- spellCheck={false}- className="flex-1 text-[12px] [font-family:var(--font-mono)]"- onChange={(e) =>- setSecrets((s) =>- s.map((r) =>- r.id === row.id ? { ...r, value: e.target.value } : r,- ),- )- }- />- <IconButton- size="1"- variant="ghost"- color="gray"- aria-label="Remove secret"- onClick={() =>- setSecrets((s) => s.filter((r) => r.id !== row.id))- }- >- <TrashIcon size={12} />- </IconButton>- </Flex>- ))}- </Flex>- )}-- <Flex align="center" gap="2" className="mt-3">- <Button- size="1"- onClick={run}- disabled={dryRun.isPending}- loading={dryRun.isPending}- >- {!dryRun.isPending ? <PlayIcon size={12} /> : null}- {dryRun.isPending ? "Running…" : "Test tool"}- </Button>- </Flex>-- {dryRun.isError ? (- <Text className="mt-2 block text-(--red-11) text-[11px]">- {dryRun.error?.message ?? "Dry run failed."}- </Text>- ) : null}-- {result ? <DryRunResult result={result} /> : null}- </div>- );-}--function DryRunResult({ result }: { result: DryRunToolResult }) {- if (result.outcome === "throttled") {- return (- <Attn tone="warn">- <Text className="text-[12px] text-gray-12">- {result.max_concurrent != null- ? `Dry-run is busy — the ${result.max_concurrent}-run limit is already in flight. Try again in a moment.`- : "Dry-run is busy — too many runs in flight. Try again in a moment."}- </Text>- </Attn>- );- }- if (result.outcome === "unavailable") {- return (- <Attn tone="warn">- <Text className="text-[12px] text-gray-12">- Dry-run isn't available on this deployment — the sandbox backend isn't- configured here.- </Text>- </Attn>- );- }-- const { envelope } = result;- return (- <div className="mt-2">- <Flex align="center" gap="1.5" className="mb-1">- {envelope.ok ? (- <>- <CheckCircleIcon size={13} className="text-(--green-11)" />- <Text className="font-medium text-(--green-11) text-[12px]">- Success- </Text>- </>- ) : (- <>- <WarningCircleIcon size={13} className="text-(--red-11)" />- <Text className="font-medium text-(--red-11) text-[12px]">- {envelope.error?.code ?? "error"}- </Text>- </>- )}- <Text className="ml-auto text-[11px] text-gray-10 [font-family:var(--font-mono)]">- {envelope.duration_ms} ms- </Text>- </Flex>- {envelope.ok ? (- <CodeBlock>{formatResult(envelope.result)}</CodeBlock>- ) : (- <div className="rounded-(--radius-2) border border-(--red-6) bg-(--red-2) px-3 py-2">- <Text className="block text-[12px] text-gray-12 leading-snug">- {envelope.error?.message ?? "The tool failed with no message."}- </Text>- </div>- )}- </div>- );-}--function formatResult(result: unknown): string {- if (result === undefined) return "undefined";- if (typeof result === "string") return result;- try {- return JSON.stringify(result, null, 2);- } catch {- return String(result);- }-}--function Attn({ children, tone }: { children: ReactNode; tone: "warn" }) {- return (- <div- className={`mt-2 rounded-(--radius-2) border px-3 py-2 ${- tone === "warn" ? "border-(--amber-6) bg-(--amber-2)" : ""- }`}- >- {children}- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/ToolSourceEditor.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/ToolSourceEditor.tsxdeleted file mode 100644index 34a9b27a8f9b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/ToolSourceEditor.tsx+++ /dev/null@@ -1,184 +0,0 @@-import { CheckCircleIcon, WarningCircleIcon } from "@phosphor-icons/react";-import type { ToolCompileError } from "@posthog/shared/agent-platform-types";-import { Button } from "@posthog/ui/primitives/Button";-import { Flex, Text, TextArea } from "@radix-ui/themes";-import { useEffect, useRef, useState } from "react";-import { useSaveRevisionTool } from "../hooks/useSaveRevisionTool";--/**- * Editable source for one custom tool on a draft revision, with a Save that- * compiles server-side. A compile failure (HTTP 422) comes back as a typed- * result, not an error, so we render each {@link ToolCompileError} inline- * (message + 1-based line/column) and DON'T mark the edit as saved. `description`- * and `args_schema` are preserved from the tool's existing schema.json — v0 edits- * source only.- */-export function ToolSourceEditor({- idOrSlug,- revisionId,- toolId,- source,- description,- argsSchema,-}: {- idOrSlug: string;- revisionId: string;- toolId: string;- source: string;- description: string;- argsSchema: Record<string, unknown>;-}) {- const save = useSaveRevisionTool(idOrSlug, revisionId);- // The textarea is uncontrolled (seeded from `source` via defaultValue); the- // parent keys this component by revision+tool, so switching either remounts it- // with a fresh buffer. We track only whether it diverges from `source`.- const textareaRef = useRef<HTMLTextAreaElement>(null);- const [dirty, setDirty] = useState(false);- const [errors, setErrors] = useState<ToolCompileError[] | null>(null);- const [justSaved, setJustSaved] = useState(false);-- // Clear the transient "saved" tick on unmount (or before the next save) so a- // stale timer can't fire setState after the component is gone.- const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);- useEffect(- () => () => {- if (savedTimer.current) clearTimeout(savedTimer.current);- },- [],- );-- function onSave() {- const draft = textareaRef.current?.value ?? source;- setJustSaved(false);- if (savedTimer.current) clearTimeout(savedTimer.current);- save.mutate(- {- toolId,- body: { description, args_schema: argsSchema, source: draft },- },- {- onSuccess: (result) => {- if (result.ok) {- // Persisted — the buffer now matches the saved source.- setErrors(null);- setDirty(false);- setJustSaved(true);- savedTimer.current = setTimeout(() => setJustSaved(false), 2000);- } else {- // Compile failed — nothing persisted; surface the diagnostics.- setErrors(result.errors);- }- },- },- );- }-- function onRevert() {- if (textareaRef.current) textareaRef.current.value = source;- setDirty(false);- setErrors(null);- }-- return (- <Flex direction="column" gap="2" className="mt-1.5">- <TextArea- ref={textareaRef}- defaultValue={source}- onChange={(e) => {- setDirty(e.target.value !== source);- if (justSaved) setJustSaved(false);- }}- rows={16}- spellCheck={false}- className="text-[12px] [font-family:var(--font-mono)]"- />-- {errors && errors.length > 0 ? (- <div className="rounded-(--radius-2) border border-(--red-6) bg-(--red-2) px-3 py-2">- <Flex align="center" gap="1.5" className="text-(--red-11)">- <WarningCircleIcon size={13} />- <Text className="font-medium text-[12px]">- {errors.length} compile error{errors.length > 1 ? "s" : ""} — not- saved- </Text>- </Flex>- <Flex direction="column" gap="1.5" className="mt-2">- {errors.map((err) => (- <div- key={`${err.kind}:${err.line ?? ""}:${err.column ?? ""}:${err.message}`}- className="rounded-(--radius-1) border border-border bg-(--color-panel-solid) px-2 py-1.5"- >- <Flex align="baseline" gap="2">- <Text className="text-(--red-11) text-[10.5px] uppercase tracking-wide [font-family:var(--font-mono)]">- {err.kind}- </Text>- {err.line != null ? (- <Text className="text-[10.5px] text-gray-10 [font-family:var(--font-mono)]">- line {err.line}- {err.column != null ? `:${err.column}` : ""}- </Text>- ) : null}- </Flex>- <Text className="mt-0.5 block text-[12px] text-gray-12 leading-snug">- {err.message}- </Text>- </div>- ))}- </Flex>- </div>- ) : null}-- {save.isError ? (- <Text className="text-(--red-11) text-[11px]">- {save.error?.message ?? "Couldn't save the tool."}- </Text>- ) : null}-- <Flex align="center" gap="2">- <Button- size="1"- color="green"- onClick={onSave}- disabled={save.isPending || !dirty}- loading={save.isPending}- >- {save.isPending ? "Compiling…" : "Save"}- </Button>- {dirty && !save.isPending ? (- <Button size="1" variant="soft" color="gray" onClick={onRevert}>- Revert- </Button>- ) : null}- {justSaved ? (- <Flex align="center" gap="1" className="text-(--green-11)">- <CheckCircleIcon size={14} />- <Text className="text-[12px]">Saved & compiled</Text>- </Flex>- ) : null}- </Flex>-- {save.data?.ok ? (- <div className="rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-2">- <Text className="block text-[11px] text-gray-10 uppercase tracking-wide [font-family:var(--font-mono)]">- Capabilities- </Text>- <Text className="mt-1 block text-[12px] text-gray-11 leading-snug">- {save.data.capabilities.secret_refs.length > 0- ? `Secrets referenced: ${save.data.capabilities.secret_refs.join(", ")}`- : "No secret references detected."}- </Text>- {save.data.capabilities.dynamic_secret_refs ? (- <Text className="mt-0.5 block text-[11px] text-amber-11 leading-snug">- This tool derives secret names dynamically — they can't be fully- enumerated ahead of time.- </Text>- ) : null}- </div>- ) : null}-- <Text className="text-[11px] text-gray-10 leading-snug">- Saving compiles the tool on the server. Only a clean compile persists.- </Text>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/ToolSourcePanel.tsx b/products/desktop/packages/ui/src/features/agent-applications/components/ToolSourcePanel.tsxdeleted file mode 100644index e5bc744e934c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/ToolSourcePanel.tsx+++ /dev/null@@ -1,137 +0,0 @@-import {- CaretDownIcon,- CaretRightIcon,- PencilSimpleIcon,- PlayIcon,-} from "@phosphor-icons/react";-import type { BundleFile } from "@posthog/shared/agent-platform-types";-import { Button } from "@posthog/ui/primitives/Button";-import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";-import { Flex, Text } from "@radix-ui/themes";-import { useState } from "react";-import { ToolDryRunPanel } from "./ToolDryRunPanel";-import { ToolSourceEditor } from "./ToolSourceEditor";--/**- * Read-first container for a custom tool's source. The resting state is a- * collapsed, read-only view — editing and dry-run are explicit, opt-in toggles- * so the surface never looks like a code editor bolted into the builder. The- * parent keys this by revision+tool, so switching either resets the toggles.- */-export function ToolSourcePanel({- idOrSlug,- revisionId,- toolId,- source,- description,- argsSchema,- canEdit,- canDryRun,-}: {- idOrSlug: string;- revisionId: string;- toolId: string;- source: BundleFile;- description: string;- argsSchema: Record<string, unknown>;- /** Draft revision + flag: offer inline editing. */- canEdit: boolean;- /** Flag + custom tool: offer the dry-run panel. */- canDryRun: boolean;-}) {- const [editing, setEditing] = useState(false);- const [sourceOpen, setSourceOpen] = useState(false);- const [testing, setTesting] = useState(false);-- return (- <div className="mt-2">- <Flex align="center" justify="between" gap="2">- <Text className="block text-[11px] text-gray-10 uppercase tracking-wide [font-family:var(--font-mono)]">- source · {source.path}- </Text>- <Flex align="center" gap="1">- {!editing ? (- <Button- size="1"- variant="ghost"- color="gray"- onClick={() => setSourceOpen((v) => !v)}- >- {sourceOpen ? (- <CaretDownIcon size={12} />- ) : (- <CaretRightIcon size={12} />- )}- {sourceOpen ? "Hide source" : "Show source"}- </Button>- ) : null}- {canEdit ? (- <Button- size="1"- variant="ghost"- color="gray"- onClick={() => {- setEditing((v) => !v);- setSourceOpen(true);- }}- >- {editing ? "Done" : <PencilSimpleIcon size={12} />}- {editing ? "" : "Edit source"}- </Button>- ) : null}- </Flex>- </Flex>-- {editing ? (- <ToolSourceEditor- idOrSlug={idOrSlug}- revisionId={revisionId}- toolId={toolId}- source={source.content}- description={description}- argsSchema={argsSchema}- />- ) : sourceOpen ? (- <div className="mt-1.5">- <CodeBlock>{source.content}</CodeBlock>- </div>- ) : (- <Text className="mt-1 block text-[12px] text-gray-10 leading-snug">- Source is hidden.{" "}- {canEdit- ? "Show it to read, or edit it inline."- : "Show it to read the compiled tool."}- </Text>- )}-- {canDryRun ? (- <div className="mt-3">- {testing ? (- <>- <Flex justify="end" className="mb-1">- <Button- size="1"- variant="ghost"- color="gray"- onClick={() => setTesting(false)}- >- Hide test- </Button>- </Flex>- <ToolDryRunPanel- idOrSlug={idOrSlug}- revisionId={revisionId}- toolId={toolId}- />- </>- ) : (- <Button size="1" variant="soft" onClick={() => setTesting(true)}>- <PlayIcon size={12} />- Test tool- </Button>- )}- </div>- ) : null}- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/agentApprovalsFilters.ts b/products/desktop/packages/ui/src/features/agent-applications/components/agentApprovalsFilters.tsdeleted file mode 100644index 0e49e5ac847e..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/components/agentApprovalsFilters.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { AgentApprovalRequestState } from "@posthog/shared/agent-platform-types";--export type ApprovalFilter = AgentApprovalRequestState | "all";--export const APPROVAL_FILTERS: { id: ApprovalFilter; label: string }[] = [- { id: "queued", label: "Queued" },- { id: "dispatched", label: "Approved" },- { id: "rejected", label: "Rejected" },- { id: "expired", label: "Expired" },- { id: "all", label: "All" },-];diff --git a/products/desktop/packages/ui/src/features/agent-applications/featureFlag.ts b/products/desktop/packages/ui/src/features/agent-applications/featureFlag.tsdeleted file mode 100644index cb18f27a4c49..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/featureFlag.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * Gates the whole agent-platform surface in PostHog: the Fleet tab- * content (list + per-agent detail) and the always-on Agent Builder dock. The- * Scouts tab is unaffected. Mirrors the `agent-platform` flag on the PostHog- * side (`FEATURE_FLAGS.AGENT_PLATFORM`). Hidden until GA.- */-export const AGENT_PLATFORM_FLAG = "agent-platform";diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/agentApplicationsKeys.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/agentApplicationsKeys.tsdeleted file mode 100644index 86545a7da05c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/agentApplicationsKeys.ts+++ /dev/null@@ -1,134 +0,0 @@-export const agentApplicationsKeys = {- list: (projectId: number | null) =>- ["agent-applications", "list", projectId] as const,- detail: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "detail", projectId, idOrSlug] as const,- sessions: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "sessions", projectId, idOrSlug] as const,- session: (projectId: number | null, idOrSlug: string, sessionId: string) =>- ["agent-applications", "session", projectId, idOrSlug, sessionId] as const,- sessionLogs: (- projectId: number | null,- idOrSlug: string,- sessionId: string,- ) =>- [- "agent-applications",- "session-logs",- projectId,- idOrSlug,- sessionId,- ] as const,- /**- * Shared prefix for every approval query of an agent — both the list- * (`approvals`) and the in-chat pending-approval poll (`chatPendingApproval`)- * live under it, so invalidating this prefix clears both at once.- */- approvalsPrefix: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "approvals", projectId, idOrSlug] as const,- approvals: (projectId: number | null, idOrSlug: string, state?: string) =>- [- "agent-applications",- "approvals",- projectId,- idOrSlug,- state ?? "all",- ] as const,- /**- * Tight-poll cache for the in-chat pending-approval card. Lives under the- * same "approvals" prefix that `useDecideAgentApproval` invalidates, so a- * decide hits this hook too (clears the card optimistically).- */- chatPendingApproval: (- projectId: number | null,- idOrSlug: string,- sessionId: string | null,- ) =>- [- "agent-applications",- "approvals",- projectId,- idOrSlug,- "chat-pending",- sessionId,- ] as const,- revisions: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "revisions", projectId, idOrSlug] as const,- /**- * Prefix over every single-revision query (any `revisionId`) for one agent.- * Invalidate it to refresh all `revision(...)` caches at once — derive the- * prefix here so it can't drift from the `revision` key it must match.- */- revisionPrefix: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "revision", projectId, idOrSlug] as const,- revision: (projectId: number | null, idOrSlug: string, revisionId: string) =>- [- "agent-applications",- "revision",- projectId,- idOrSlug,- revisionId,- ] as const,- bundle: (projectId: number | null, idOrSlug: string, revisionId: string) =>- ["agent-applications", "bundle", projectId, idOrSlug, revisionId] as const,- envKeys: (- projectId: number | null,- idOrSlug: string,- revisionId: string | null,- ) =>- [- "agent-applications",- "env-keys",- projectId,- idOrSlug,- revisionId,- ] as const,- slackManifest: (- projectId: number | null,- idOrSlug: string,- revisionId: string,- ) =>- [- "agent-applications",- "slack-manifest",- projectId,- idOrSlug,- revisionId,- ] as const,- memoryTree: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "memory-tree", projectId, idOrSlug] as const,- memoryFile: (projectId: number | null, idOrSlug: string, path: string) =>- ["agent-applications", "memory-file", projectId, idOrSlug, path] as const,- memorySearch: (projectId: number | null, idOrSlug: string, query: string) =>- [- "agent-applications",- "memory-search",- projectId,- idOrSlug,- query,- ] as const,- memoryTables: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "memory-tables", projectId, idOrSlug] as const,- memoryTable: (projectId: number | null, idOrSlug: string, name: string) =>- ["agent-applications", "memory-table", projectId, idOrSlug, name] as const,- users: (projectId: number | null, idOrSlug: string) =>- ["agent-applications", "users", projectId, idOrSlug] as const,- fleetLiveSessions: (projectId: number | null) =>- ["agent-applications", "fleet", "live-sessions", projectId] as const,- fleetApprovals: (projectId: number | null, state?: string) =>- [- "agent-applications",- "fleet",- "approvals",- projectId,- state ?? "all",- ] as const,- /** `applicationId` is undefined for the fleet-wide board. */- analytics: (projectId: number | null, applicationId?: string) =>- [- "agent-applications",- "analytics",- projectId,- applicationId ?? "fleet",- ] as const,-};diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/approvalsPermission.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/approvalsPermission.tsdeleted file mode 100644index e3c05ef2289a..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/approvalsPermission.ts+++ /dev/null@@ -1,12 +0,0 @@-import { requestErrorStatus } from "@posthog/api-client/fetcher";--/**- * The backend gates the approvals endpoints behind an org-membership ADMIN- * check and answers 404 (not 403) for non-admins, so a 404 from these- * endpoints means "no permission". For the per-agent endpoint this only- * holds when the application is known to exist — AgentApprovalsPane renders- * inside AgentDetailLayout, which gates on the application having loaded.- */-export function isApprovalsPermissionError(error: unknown): boolean {- return requestErrorStatus(error) === 404;-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentAnalytics.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentAnalytics.tsdeleted file mode 100644index 03144072eb45..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentAnalytics.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { AgentAnalyticsData } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Agent observability rollup over the team's own `$ai_*` events. Pass an- * `applicationId` (the agent's UUID) to scope the board to a single agent (the- * per-agent Observability tab); omit it for the fleet-wide analytics board.- *- * The fleet board is enabled as soon as a project is selected; the per-agent- * board waits for the resolved `applicationId` so it doesn't fetch an- * unscoped (whole-fleet) board for one agent's tab.- */-export function useAgentAnalytics(applicationId?: string, scope?: "agent") {- const projectId = useAuthStateValue((state) => state.currentProjectId);- const enabled = !!projectId && (scope !== "agent" || !!applicationId);- return useAuthenticatedQuery<AgentAnalyticsData>(- agentApplicationsKeys.analytics(projectId, applicationId),- (client) => client.getAgentAnalytics(applicationId),- { enabled, staleTime: 30_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplication.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplication.tsdeleted file mode 100644index 74a7951c41d8..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplication.ts+++ /dev/null@@ -1,14 +0,0 @@-import type { AgentApplication } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** Fetches a single agent application by UUID or slug. */-export function useAgentApplication(idOrSlug: string) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentApplication | null>(- agentApplicationsKeys.detail(projectId, idOrSlug),- (client) => client.getAgentApplication(idOrSlug),- { enabled: !!projectId && !!idOrSlug, staleTime: 30_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationApprovals.test.tsx b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationApprovals.test.tsxdeleted file mode 100644index c31dd11bcfeb..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationApprovals.test.tsx+++ /dev/null@@ -1,83 +0,0 @@-import { ApiRequestError } from "@posthog/api-client/fetcher";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { renderHook, waitFor } from "@testing-library/react";-import type { ReactNode } from "react";-import { beforeEach, describe, expect, it, vi } from "vitest";--const mockListAgentApplicationApprovals = vi.hoisted(() => vi.fn());-const mockClient = vi.hoisted(() => ({- listAgentApplicationApprovals: mockListAgentApplicationApprovals,-}));--vi.mock("@posthog/ui/features/auth/authClient", () => ({- useOptionalAuthenticatedClient: () => mockClient,-}));--vi.mock("../../auth/store", () => ({- useAuthStateValue: <T,>(- selector: (state: { currentProjectId: number }) => T,- ) => selector({ currentProjectId: 2 }),-}));--import { useAgentApplicationApprovals } from "./useAgentApplicationApprovals";--function renderApprovalsHook(idOrSlug: string) {- const queryClient = new QueryClient({- // Zero out the backoff so the hook's own `retry` option (under test)- // drives the call count without slowing the suite.- defaultOptions: { queries: { retryDelay: 0 } },- });- const wrapper = ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- );- return renderHook(() => useAgentApplicationApprovals(idOrSlug), { wrapper });-}--describe("useAgentApplicationApprovals", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("flags a 404 as a permission error without retrying", async () => {- mockListAgentApplicationApprovals.mockRejectedValue(- new ApiRequestError(404, '{"detail":"Not found"}'),- );- const { result } = renderApprovalsHook("my-agent");-- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.isPermissionError).toBe(true);- // The admin gate never clears on retry, so the hook must not retry.- expect(mockListAgentApplicationApprovals).toHaveBeenCalledTimes(1);- });-- it("treats non-404 failures as genuine errors and retries them", async () => {- mockListAgentApplicationApprovals.mockRejectedValue(- new ApiRequestError(500, '{"error":"boom"}'),- );- const { result } = renderApprovalsHook("my-agent");-- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.isPermissionError).toBe(false);- expect(mockListAgentApplicationApprovals).toHaveBeenCalledTimes(4);- });-- it("returns approvals on success", async () => {- mockListAgentApplicationApprovals.mockResolvedValue([{ id: "approval-1" }]);- const { result } = renderApprovalsHook("my-agent");-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data).toEqual([{ id: "approval-1" }]);- expect(result.current.isPermissionError).toBe(false);- });-- it("stays disabled and never fetches without an idOrSlug", async () => {- mockListAgentApplicationApprovals.mockResolvedValue([]);- const { result } = renderApprovalsHook("");-- // enabled gates on !!idOrSlug — the query must stay pending with no fetch.- await new Promise((resolve) => setTimeout(resolve, 50));- expect(mockListAgentApplicationApprovals).not.toHaveBeenCalled();- expect(result.current.isPending).toBe(true);- expect(result.current.isPermissionError).toBe(false);- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationApprovals.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationApprovals.tsdeleted file mode 100644index dab302b67358..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationApprovals.ts+++ /dev/null@@ -1,40 +0,0 @@-import type {- AgentApprovalRequest,- AgentApprovalsListParams,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";-import { isApprovalsPermissionError } from "./approvalsPermission";--/**- * Lists tool-approval requests for one agent (organization-admin only).- * Optionally filtered to a single state (the backend accepts one `state`- * value); omit for all states. `isPermissionError` is true when the viewer- * lacks admin access.- */-export function useAgentApplicationApprovals(- idOrSlug: string,- params?: AgentApprovalsListParams,-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- const query = useAuthenticatedQuery<AgentApprovalRequest[]>(- agentApplicationsKeys.approvals(projectId, idOrSlug, params?.state),- (client) => client.listAgentApplicationApprovals(idOrSlug, params),- {- enabled: !!projectId && !!idOrSlug,- staleTime: 10_000,- // Queued approvals change as agents run; poll while the tab is focused —- // but stop once we know the viewer lacks org-admin access.- refetchInterval: (q) =>- isApprovalsPermissionError(q.state.error) ? false : 10_000,- // A 404 here is the admin gate, not a transient failure — don't retry.- retry: (failureCount, error) =>- !isApprovalsPermissionError(error) && failureCount < 3,- },- );- return {- ...query,- isPermissionError: isApprovalsPermissionError(query.error),- };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSession.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSession.tsdeleted file mode 100644index 231785c35a16..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSession.ts+++ /dev/null@@ -1,34 +0,0 @@-import type { AgentApplicationSessionDetail } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--const TERMINAL_STATES = new Set(["completed", "closed", "cancelled", "failed"]);--/** Fetches one session's detail, including its stored conversation transcript. */-export function useAgentApplicationSession(- idOrSlug: string,- sessionId: string,- lastN?: number,-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentApplicationSessionDetail | null>(- [- ...agentApplicationsKeys.session(projectId, idOrSlug, sessionId),- lastN ?? null,- ],- (client) =>- projectId- ? client.getAgentApplicationSession(idOrSlug, sessionId, lastN)- : Promise.resolve(null),- {- enabled: !!projectId && !!idOrSlug && !!sessionId,- staleTime: 15_000,- // Poll only while the session is still active; terminal sessions are immutable.- refetchInterval: (query) =>- query.state.data && !TERMINAL_STATES.has(query.state.data.state)- ? 10_000- : false,- },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSessionLogs.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSessionLogs.tsdeleted file mode 100644index 9abb6feb75fe..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSessionLogs.ts+++ /dev/null@@ -1,36 +0,0 @@-import type {- AgentSessionLogEntry,- AgentSessionLogsParams,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Structured runtime logs for one session. `enabled` lets callers defer the- * fetch until the Logs tab is actually opened.- */-export function useAgentApplicationSessionLogs(- idOrSlug: string,- sessionId: string,- options?: { enabled?: boolean; params?: AgentSessionLogsParams },-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentSessionLogEntry[]>(- [- ...agentApplicationsKeys.sessionLogs(projectId, idOrSlug, sessionId),- options?.params ?? null,- ],- (client) =>- client.getAgentApplicationSessionLogs(- idOrSlug,- sessionId,- options?.params,- ),- {- enabled:- !!projectId && !!idOrSlug && !!sessionId && (options?.enabled ?? true),- staleTime: 10_000,- },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSessions.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSessions.tsdeleted file mode 100644index 3ddd77c6d74c..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplicationSessions.ts+++ /dev/null@@ -1,30 +0,0 @@-import type {- AgentApplicationSessionsListResponse,- AgentSessionsListParams,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--const EMPTY: AgentApplicationSessionsListResponse = { results: [], count: 0 };--/** Lists sessions for an agent application. */-export function useAgentApplicationSessions(- idOrSlug: string,- params?: AgentSessionsListParams,-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentApplicationSessionsListResponse>(- [...agentApplicationsKeys.sessions(projectId, idOrSlug), params ?? null],- (client) =>- projectId- ? client.listAgentApplicationSessions(idOrSlug, params)- : Promise.resolve(EMPTY),- {- enabled: !!projectId && !!idOrSlug,- staleTime: 15_000,- // Auto-poll; react-query pauses this while the tab is unfocused.- refetchInterval: 15_000,- },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplications.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplications.tsdeleted file mode 100644index b6230d000d1b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentApplications.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { AgentApplication } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** Lists the deployed agent applications for the current project. */-export function useAgentApplications() {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentApplication[]>(- agentApplicationsKeys.list(projectId),- (client) =>- projectId ? client.listAgentApplications() : Promise.resolve([]),- { enabled: !!projectId, staleTime: 30_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentChat.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentChat.tsdeleted file mode 100644index a7f1eac7df49..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentChat.ts+++ /dev/null@@ -1,248 +0,0 @@-import type { AgentChatService } from "@posthog/core/agent-chat/agentChatService";-import { agentChatStore } from "@posthog/core/agent-chat/agentChatStore";-import {- AGENT_CHAT_SERVICE,- type AgentChatSession,- type ClientToolCallData,- type ClientToolOutcome,-} from "@posthog/core/agent-chat/identifiers";-import { useService } from "@posthog/di/react";-import type { DecideApprovalRequest } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { toast } from "@posthog/ui/primitives/toast";-import { useCallback, useEffect, useMemo, useRef } from "react";-import { useStore } from "zustand";-import { useChatHistoryStore } from "../chat/chatHistoryStore";-import { buildConsoleContextEnvelope } from "../chat/consoleContext";-import { conversationToAcpMessages } from "../chat/conversationToAcp";-import { createAgentChatMapper } from "../chat/sessionEventToAcp";--export type { ClientToolOutcome };--/**- * Resolves a client-tool call, or returns null to defer to the built-in- * handlers (toast / get_context). Used by the agent builder to drive the UI- * (focus_*) and the secret punch-out.- */-export type ClientToolHandler = (- data: ClientToolCallData,-) => ClientToolOutcome | null | Promise<ClientToolOutcome | null>;--export interface UseAgentChatOptions {- /** Opaque key isolating this chat in the store (e.g. "agent-builder", "preview:<slug>"). */- chatId: string;- /** Agent slug the chat targets (drives client-tool context + history). */- agentSlug: string;- ingressBaseUrl: string | null;- /**- * When set, this chat routes to a specific non-live revision. The service- * mints a short-lived ingress JWT scoped to that revision and attaches it on- * every call; side effects still run for real. Leave null/unset to use the- * agent's currently live revision.- */- revisionId?: string | null;- /** Index started sessions in the local chat-history rail. */- recordHistory?: boolean;- /**- * Supplies the "what am I looking at" object. When set, it's prepended as a- * delimited envelope to the first message and answers the `get_context`- * client tool. AgentBuilder only.- */- contextProvider?: () => unknown;- /** AgentBuilder UI-driving tools (focus_*, set_secret); null → built-in handling. */- clientTools?: ClientToolHandler;- /**- * `kind:'client'` tool ids this client can fulfil; sent to the runner at /run.- * Pass a stable (module-level) array — it keys the session-config memo.- */- supportedClientTools?: readonly string[];-}--/**- * Renderer entry point for a live chat against a deployed agent. Resolves the- * core `AgentChatService` (which owns the transport saga and writes the- * `agentChatStore`), supplies the authenticated client plus the UI seams- * (mapper, client-tool resolution, context envelope, history), and exposes the- * store-backed chat state and callbacks. Components read the chat by id and- * render through `ConversationView`.- */-export function useAgentChat({- chatId,- agentSlug,- ingressBaseUrl,- revisionId = null,- recordHistory = false,- contextProvider,- clientTools,- supportedClientTools,-}: UseAgentChatOptions) {- const client = useAuthenticatedClient();- const service = useService<AgentChatService>(AGENT_CHAT_SERVICE);- const chat = useStore(agentChatStore, (s) => s.chats[chatId]);- const recordChat = useChatHistoryStore((s) => s.record);-- // Latest provider/handler read at dispatch time without rebuilding the session.- const contextProviderRef = useRef(contextProvider);- contextProviderRef.current = contextProvider;- const clientToolsRef = useRef(clientTools);- clientToolsRef.current = clientTools;-- // Stable per-chat seam handed to the service. The callbacks read refs, so a- // long-lived stream always sees the latest handler/provider.- const session = useMemo<AgentChatSession>(- () => ({- chatId,- agentSlug,- ingressBaseUrl: ingressBaseUrl ?? "",- revisionId,- supportedClientTools,- createMapper: createAgentChatMapper,- resolveClientTool: (data) =>- resolveClientTool(- data,- agentSlug,- clientToolsRef.current,- contextProviderRef.current,- ),- buildWireText: (text) => {- const envelope = contextProviderRef.current?.();- return envelope- ? `${buildConsoleContextEnvelope(envelope)}\n\n${text}`- : text;- },- mapConversation: conversationToAcpMessages,- onSessionStarted: recordHistory- ? (sessionId, text) =>- recordChat(agentSlug, {- sessionId,- title: text.slice(0, 120),- startedAt: Date.now(),- revisionId: revisionId ?? undefined,- })- : undefined,- }),- [- chatId,- agentSlug,- ingressBaseUrl,- revisionId,- supportedClientTools,- recordHistory,- recordChat,- ],- );-- const send = useCallback(- (text: string): Promise<void> =>- ingressBaseUrl ? service.send(client, session, text) : Promise.resolve(),- [service, client, session, ingressBaseUrl],- );-- const cancel = useCallback(- () => service.cancel(client, session),- [service, client, session],- );-- const resume = useCallback(- (sessionId: string): Promise<void> =>- ingressBaseUrl- ? service.resume(client, session, sessionId)- : Promise.resolve(),- [service, client, session, ingressBaseUrl],- );-- // Decide a `principal`-type tool approval for this chat at the ingress (the- // session owner clears their own gated call). The open stream resumes the- // chat on approve.- const decideApproval = useCallback(- (approvalId: string, body: DecideApprovalRequest): Promise<void> =>- ingressBaseUrl- ? service.decideApproval(client, session, approvalId, body)- : // No live session to decide against — reject (not a silent resolve) so- // the card's mutation shows an error, not a false success toast.- Promise.reject(- new Error("This chat has no live session to decide the approval."),- ),- [service, client, session, ingressBaseUrl],- );-- const resolveInteractiveTool = useCallback(- (- callId: string,- outcome: { result: Record<string, unknown> } | { error: string },- ): Promise<void> =>- ingressBaseUrl- ? service.resolveInteractiveTool(client, session, callId, outcome)- : Promise.resolve(),- [service, client, session, ingressBaseUrl],- );-- const newChat = useCallback(- () => service.newChat(session),- [service, session],- );-- // Release the open `/listen` socket when the consumer unmounts.- useEffect(() => () => service.releaseStream(chatId), [service, chatId]);-- return {- messages: chat?.messages ?? [],- status: chat?.status ?? "idle",- error: chat?.error ?? null,- isStreaming: chat?.status === "streaming" || chat?.status === "starting",- hasSession: !!chat?.sessionId,- sessionId: chat?.sessionId ?? null,- send,- cancel,- resume,- newChat,- resolveInteractiveTool,- decideApproval,- };-}--/**- * Resolve a client-tool call: agent builder handler (focus_*, set_secret), then- * `get_context` from the context provider, then the built-in toast / unhandled- * fallback. Never resolves to null — `handleClientTool` is terminal.- */-async function resolveClientTool(- data: ClientToolCallData,- agentSlug: string,- clientTools: ClientToolHandler | undefined,- contextProvider: (() => unknown) | undefined,-): Promise<ClientToolOutcome> {- const handled = (await clientTools?.(data)) ?? null;- if (handled) return handled;- if (data.tool_id === "get_context") {- return {- result: contextProvider?.() ?? {- agent: agentSlug,- client: "posthog-code",- },- };- }- return handleClientTool(data, agentSlug);-}--/** Resolve a client-tool call. Immediate tools only; the rest degrade. */-function handleClientTool(- data: ClientToolCallData,- agentSlug: string,-): { result?: unknown; error?: string } {- switch (data.tool_id) {- case "toast": {- const args = (data.args ?? {}) as { message?: string; level?: string };- const message = args.message ?? "";- if (args.level === "error") toast.error(message);- else if (args.level === "warn") toast.warning(message);- else toast.info(message);- return { result: { shown: true } };- }- case "get_context":- return { result: { agent: agentSlug, client: "posthog-code" } };- default:- // focus_*, set_secret, … land with the agent builder milestone.- return { error: `unhandled_client_tool: ${data.tool_id}` };- }-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentChatPendingApproval.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentChatPendingApproval.tsdeleted file mode 100644index 1671b8e4f0c5..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentChatPendingApproval.ts+++ /dev/null@@ -1,22 +0,0 @@-import { agentChatStore } from "@posthog/core/agent-chat/agentChatStore";-import type { AgentApprovalRequest } from "@posthog/shared/agent-platform-types";-import { useStore } from "zustand";--/**- * The approval-gated tool call this chat is currently paused on, or null —- * what drives the inline approval card in the chat pane / agent builder dock.- *- * The chat service maintains it from the stream: a `queued` approval marker- * triggers a one-shot fetch of the full request from the ingress, and a- * resolve/decide clears it. So the card is push-driven (no polling) and works- * from any project — the detail comes from the slug-routed ingress, not the- * project-scoped console API.- */-export function useAgentChatPendingApproval(- chatId: string,-): AgentApprovalRequest | null {- return useStore(- agentChatStore,- (s) => s.chats[chatId]?.pendingApproval ?? null,- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentEnvKeyMutations.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentEnvKeyMutations.tsdeleted file mode 100644index 7b238e3b8bba..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentEnvKeyMutations.ts+++ /dev/null@@ -1,32 +0,0 @@-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Set/rotate and clear one revision-scoped env key. Both invalidate the- * env-keys list for the revision so set/not-set status (tree badges, secret- * detail) reflects the change.- */-export function useAgentEnvKeyMutations(idOrSlug: string, revisionId: string) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- const invalidate = () =>- queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.envKeys(projectId, idOrSlug, revisionId),- });-- const setKey = useMutation<void, Error, { key: string; value: string }>({- mutationFn: ({ key, value }) =>- client.setAgentEnvKey(idOrSlug, revisionId, key, value),- onSuccess: () => void invalidate(),- });- const clearKey = useMutation<void, Error, { key: string }>({- mutationFn: ({ key }) => client.clearAgentEnvKey(idOrSlug, revisionId, key),- onSuccess: () => void invalidate(),- });-- return { setKey, clearKey };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentEnvKeys.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentEnvKeys.tsdeleted file mode 100644index 633a0b7f81a3..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentEnvKeys.ts+++ /dev/null@@ -1,19 +0,0 @@-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Names of env keys currently set on a revision (values are never returned).- * Env keys are revision-scoped, so callers must pass the revision in scope.- */-export function useAgentEnvKeys(idOrSlug: string, revisionId: string | null) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<string[]>(- agentApplicationsKeys.envKeys(projectId, idOrSlug, revisionId),- (client) => client.listAgentEnvKeys(idOrSlug, revisionId as string),- {- enabled: !!projectId && !!idOrSlug && !!revisionId,- staleTime: 15_000,- },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetApprovals.test.tsx b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetApprovals.test.tsxdeleted file mode 100644index c718098b0440..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetApprovals.test.tsx+++ /dev/null@@ -1,84 +0,0 @@-import { ApiRequestError } from "@posthog/api-client/fetcher";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { renderHook, waitFor } from "@testing-library/react";-import type { ReactNode } from "react";-import { beforeEach, describe, expect, it, vi } from "vitest";--const mockListAgentFleetApprovals = vi.hoisted(() => vi.fn());-const mockClient = vi.hoisted(() => ({- listAgentFleetApprovals: mockListAgentFleetApprovals,-}));--vi.mock("@posthog/ui/features/auth/authClient", () => ({- useOptionalAuthenticatedClient: () => mockClient,-}));--vi.mock("../../auth/store", () => ({- useAuthStateValue: <T,>(- selector: (state: { currentProjectId: number }) => T,- ) => selector({ currentProjectId: 2 }),-}));--import { isApprovalsPermissionError } from "./approvalsPermission";-import { useAgentFleetApprovals } from "./useAgentFleetApprovals";--function renderApprovalsHook() {- const queryClient = new QueryClient({- // Zero out the backoff so the hook's own `retry` option (under test)- // drives the call count without slowing the suite.- defaultOptions: { queries: { retryDelay: 0 } },- });- const wrapper = ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- );- return renderHook(() => useAgentFleetApprovals(), { wrapper });-}--describe("useAgentFleetApprovals", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("flags a 404 as a permission error without retrying", async () => {- mockListAgentFleetApprovals.mockRejectedValue(- new ApiRequestError(404, '{"detail":"Not found"}'),- );- const { result } = renderApprovalsHook();-- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.isPermissionError).toBe(true);- // The admin gate never clears on retry, so the hook must not retry.- expect(mockListAgentFleetApprovals).toHaveBeenCalledTimes(1);- });-- it("treats non-404 failures as genuine errors and retries them", async () => {- mockListAgentFleetApprovals.mockRejectedValue(- new ApiRequestError(500, '{"error":"boom"}'),- );- const { result } = renderApprovalsHook();-- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.isPermissionError).toBe(false);- expect(mockListAgentFleetApprovals).toHaveBeenCalledTimes(4);- });-- it("returns approvals on success", async () => {- mockListAgentFleetApprovals.mockResolvedValue([{ id: "approval-1" }]);- const { result } = renderApprovalsHook();-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data).toEqual([{ id: "approval-1" }]);- expect(result.current.isPermissionError).toBe(false);- });-});--describe("isApprovalsPermissionError", () => {- it.each([- [new ApiRequestError(404, "{}"), true],- [new ApiRequestError(500, "{}"), false],- [new Error("Failed request: [404] {}"), false],- [null, false],- ])("maps %s to %s", (error, expected) => {- expect(isApprovalsPermissionError(error)).toBe(expected);- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetApprovals.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetApprovals.tsdeleted file mode 100644index 04cb0bfbea30..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetApprovals.ts+++ /dev/null@@ -1,35 +0,0 @@-import type {- AgentApprovalRequest,- AgentApprovalsListParams,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";-import { isApprovalsPermissionError } from "./approvalsPermission";--/**- * Fleet-wide tool-approval requests across every agent on the team- * (organization-admin only). Optionally filtered to a single state; omit for- * all. `isPermissionError` is true when the viewer lacks admin access.- */-export function useAgentFleetApprovals(params?: AgentApprovalsListParams) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- const query = useAuthenticatedQuery<AgentApprovalRequest[]>(- agentApplicationsKeys.fleetApprovals(projectId, params?.state),- (client) => client.listAgentFleetApprovals(params),- {- enabled: !!projectId,- staleTime: 10_000,- // Stop polling once we know the viewer lacks org-admin access.- refetchInterval: (q) =>- isApprovalsPermissionError(q.state.error) ? false : 10_000,- // A 404 here is the admin gate, not a transient failure — don't retry.- retry: (failureCount, error) =>- !isApprovalsPermissionError(error) && failureCount < 3,- },- );- return {- ...query,- isPermissionError: isApprovalsPermissionError(query.error),- };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetLiveSessions.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetLiveSessions.tsdeleted file mode 100644index 4e2f57997d79..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentFleetLiveSessions.ts+++ /dev/null@@ -1,26 +0,0 @@-import type { AgentFleetLiveSessionsResponse } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--const EMPTY: AgentFleetLiveSessionsResponse = { results: [] };--/**- * Cross-agent live (non-terminal) sessions. Polls aggressively (5s) since live- * sessions move fast; react-query pauses when the tab is unfocused.- */-export function useAgentFleetLiveSessions(limit?: number) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentFleetLiveSessionsResponse>(- [...agentApplicationsKeys.fleetLiveSessions(projectId), limit ?? null],- (client) =>- projectId- ? client.listAgentFleetLiveSessions(limit)- : Promise.resolve(EMPTY),- {- enabled: !!projectId,- staleTime: 5_000,- refetchInterval: 5_000,- },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentMemory.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentMemory.tsdeleted file mode 100644index 72d6064d1953..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentMemory.ts+++ /dev/null@@ -1,71 +0,0 @@-import type {- AgentMemoryFile,- AgentMemorySearchResult,- AgentMemoryTableHeader,- AgentMemoryTableRows,- AgentMemoryTreeNode,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** The agent's memory folder tree. */-export function useAgentMemoryTree(idOrSlug: string) {- const projectId = useAuthStateValue((s) => s.currentProjectId);- return useAuthenticatedQuery<AgentMemoryTreeNode | null>(- agentApplicationsKeys.memoryTree(projectId, idOrSlug),- (client) => client.getAgentMemoryTree(idOrSlug),- { enabled: !!projectId && !!idOrSlug, staleTime: 15_000 },- );-}--/** One memory file's header + content. Fetches only when `path` is set. */-export function useAgentMemoryFile(- idOrSlug: string,- path: string | null | undefined,-) {- const projectId = useAuthStateValue((s) => s.currentProjectId);- return useAuthenticatedQuery<AgentMemoryFile | null>(- agentApplicationsKeys.memoryFile(projectId, idOrSlug, path ?? ""),- (client) =>- path ? client.readAgentMemoryFile(idOrSlug, path) : Promise.resolve(null),- { enabled: !!projectId && !!idOrSlug && !!path, staleTime: 15_000 },- );-}--/** BM25 search. Fetches only when `query` is non-empty. */-export function useAgentMemorySearch(idOrSlug: string, query: string) {- const projectId = useAuthStateValue((s) => s.currentProjectId);- const q = query.trim();- return useAuthenticatedQuery<AgentMemorySearchResult[]>(- agentApplicationsKeys.memorySearch(projectId, idOrSlug, q),- (client) => client.searchAgentMemory(idOrSlug, q, 50),- { enabled: !!projectId && !!idOrSlug && q.length > 0, staleTime: 10_000 },- );-}--/** The agent's memory tables. */-export function useAgentMemoryTables(idOrSlug: string) {- const projectId = useAuthStateValue((s) => s.currentProjectId);- return useAuthenticatedQuery<AgentMemoryTableHeader[]>(- agentApplicationsKeys.memoryTables(projectId, idOrSlug),- (client) => client.listAgentMemoryTables(idOrSlug),- { enabled: !!projectId && !!idOrSlug, staleTime: 15_000 },- );-}--/** Rows from one memory table. Fetches only when `name` is set. */-export function useAgentMemoryTable(- idOrSlug: string,- name: string | null | undefined,-) {- const projectId = useAuthStateValue((s) => s.currentProjectId);- return useAuthenticatedQuery<AgentMemoryTableRows | null>(- agentApplicationsKeys.memoryTable(projectId, idOrSlug, name ?? ""),- (client) =>- name- ? client.readAgentMemoryTable(idOrSlug, name, 100)- : Promise.resolve(null),- { enabled: !!projectId && !!idOrSlug && !!name, staleTime: 15_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentMissingSecrets.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentMissingSecrets.tsdeleted file mode 100644index 62c7a1d2da26..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentMissingSecrets.ts+++ /dev/null@@ -1,35 +0,0 @@-import { useMemo } from "react";-import { useAgentEnvKeys } from "./useAgentEnvKeys";-import { useAgentRevision } from "./useAgentRevision";--const EMPTY: string[] = [];--/**- * Names of secrets the given revision declares in its spec but the revision- * doesn't have set yet. Env keys are revision-scoped, so a draft carries its- * own secret set; for any name in this list the runner will fail at use-site- * until the author sets it on this revision.- *- * Returns the empty list when no revision is targeted (live chat doesn't- * surface this — drafts are the only place where unset secrets are an- * authoring blocker).- */-export function useAgentMissingSecrets(- idOrSlug: string,- revisionId: string | null,-): string[] {- const { data: revision } = useAgentRevision(idOrSlug, revisionId);- const { data: envKeys } = useAgentEnvKeys(idOrSlug, revisionId);- return useMemo(() => {- if (!revisionId) return EMPTY;- const declared = revision?.spec?.secrets ?? [];- if (declared.length === 0) return EMPTY;- const set = new Set(envKeys ?? []);- const missing = declared.filter((name) => !set.has(name));- return missing.length === declared.length && envKeys == null- ? // env-keys query hasn't loaded yet; avoid flashing the card with the- // full list before we know what's actually set.- EMPTY- : missing;- }, [revisionId, revision, envKeys]);-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevision.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevision.tsdeleted file mode 100644index a9b00aad1ae0..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevision.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { AgentRevision } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** Fetches a single revision (carries the agent `spec`). */-export function useAgentRevision(- idOrSlug: string,- revisionId: string | null | undefined,-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentRevision | null>(- agentApplicationsKeys.revision(projectId, idOrSlug, revisionId ?? ""),- (client) =>- revisionId- ? client.getAgentRevision(idOrSlug, revisionId)- : Promise.resolve(null),- { enabled: !!projectId && !!idOrSlug && !!revisionId, staleTime: 30_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisionBundle.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisionBundle.tsdeleted file mode 100644index fc5507db3b54..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisionBundle.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { BundleFile } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** A revision's bundle files (agent.md, skill bodies, tool sources + schemas). */-export function useAgentRevisionBundle(- idOrSlug: string,- revisionId: string | null | undefined,-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<BundleFile[]>(- agentApplicationsKeys.bundle(projectId, idOrSlug, revisionId ?? ""),- (client) =>- revisionId- ? client.getAgentRevisionBundle(idOrSlug, revisionId)- : Promise.resolve([]),- { enabled: !!projectId && !!idOrSlug && !!revisionId, staleTime: 30_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisionLifecycle.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisionLifecycle.tsdeleted file mode 100644index 160cf65a3623..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisionLifecycle.ts+++ /dev/null@@ -1,37 +0,0 @@-import type { AgentRevision } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--type LifecycleAction = "freeze" | "promote" | "archive";--/**- * Run a revision lifecycle transition (freeze / promote / archive). Promote- * rewrites the application's live_revision and demotes the old live, so on- * success we invalidate the application detail, the revisions list, and the- * per-revision + bundle caches.- */-export function useAgentRevisionLifecycle(idOrSlug: string) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<- AgentRevision,- Error,- { revisionId: string; action: LifecycleAction }- >({- mutationFn: ({ revisionId, action }) =>- client.transitionAgentRevision(idOrSlug, revisionId, action),- onSuccess: () => {- for (const key of [- agentApplicationsKeys.detail(projectId, idOrSlug),- agentApplicationsKeys.revisions(projectId, idOrSlug),- ["agent-applications", "revision", projectId, idOrSlug],- ]) {- void queryClient.invalidateQueries({ queryKey: key });- }- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisions.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisions.tsdeleted file mode 100644index 48eef494596f..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentRevisions.ts+++ /dev/null@@ -1,14 +0,0 @@-import type { AgentRevision } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** All revisions for an agent (newest first), for the revision picker. */-export function useAgentRevisions(idOrSlug: string) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentRevision[]>(- agentApplicationsKeys.revisions(projectId, idOrSlug),- (client) => client.listAgentRevisions(idOrSlug),- { enabled: !!projectId && !!idOrSlug, staleTime: 30_000 },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentSlackManifest.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentSlackManifest.tsdeleted file mode 100644index 688c40617ba9..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentSlackManifest.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { AgentSlackManifest } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** The Slack app manifest for a revision. `enabled` defers until the card shows. */-export function useAgentSlackManifest(- idOrSlug: string,- revisionId: string | null | undefined,- enabled = true,-) {- const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<AgentSlackManifest | null>(- agentApplicationsKeys.slackManifest(projectId, idOrSlug, revisionId ?? ""),- (client) =>- revisionId- ? client.getAgentSlackManifest(idOrSlug, revisionId)- : Promise.resolve(null),- {- enabled: !!projectId && !!idOrSlug && !!revisionId && enabled,- staleTime: 60_000,- },- );-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentUsers.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentUsers.tsdeleted file mode 100644index 938e0971b3d1..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useAgentUsers.ts+++ /dev/null@@ -1,58 +0,0 @@-import type { AgentUsersListResponse } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { toast } from "@posthog/ui/primitives/toast";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/** The agent's end-users, each with their linked connections (metadata only). */-export function useAgentUsers(idOrSlug: string) {- const projectId = useAuthStateValue((s) => s.currentProjectId);- return useAuthenticatedQuery<AgentUsersListResponse>(- agentApplicationsKeys.users(projectId, idOrSlug),- (client) => client.listAgentUsers(idOrSlug),- // No retry: this only powers an optional filter dropdown (hidden when- // empty). Until the `/users/` endpoint ships it 404s, and the Sessions tab- // that calls this auto-polls — retrying would multiply avoidable failing- // traffic for a feature that degrades gracefully to "no dropdown".- { enabled: !!projectId && !!idOrSlug, staleTime: 15_000, retry: false },- );-}--interface DisconnectArgs {- agentUserId: string;- provider: string;-}--/**- * Revoke one of a user's linked connections. The credential is revoked (kept- * for audit), not hard-deleted; the agent can no longer act as that user on the- * provider. Refetches the users list on settle so the row reflects the new- * state, and toasts the outcome.- */-export function useDisconnectAgentUserConnection(idOrSlug: string) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((s) => s.currentProjectId);-- return useMutation<void, Error, DisconnectArgs>({- mutationFn: ({ agentUserId, provider }) =>- client.deleteAgentUserConnection(idOrSlug, agentUserId, provider),- onSuccess: (_data, { provider }) => {- toast.success("Connection revoked", {- description: `The agent can no longer act as this user on ${provider}.`,- });- },- onError: (err) => {- toast.error("Couldn't revoke connection", {- description: err instanceof Error ? err.message : undefined,- });- },- onSettled: () => {- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.users(projectId, idOrSlug),- });- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useApplyAgentSpec.test.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useApplyAgentSpec.test.tsdeleted file mode 100644index b3b60d5443ab..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useApplyAgentSpec.test.ts+++ /dev/null@@ -1,156 +0,0 @@-import { renderHook } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--// Capture the mutationFn and onSuccess the hook hands to react-query so we can-// exercise the create-draft-vs-patch branching and the cache invalidation-// directly, without a live QueryClient.-let mutationFn: (vars: {- revision: { id: string; state: string };- spec: unknown;-}) => Promise<unknown>;-let onSuccess: (() => void) | undefined;-let invalidateQueries: ReturnType<typeof vi.fn>;--vi.mock("@tanstack/react-query", () => ({- useMutation: (opts: {- mutationFn: typeof mutationFn;- onSuccess?: () => void;- }) => {- mutationFn = opts.mutationFn;- onSuccess = opts.onSuccess;- return { mutate: vi.fn() };- },- useQueryClient: () => {- invalidateQueries = vi.fn();- return { invalidateQueries };- },-}));--const client = {- createAgentDraftRevisionFrom: vi.fn(),- updateAgentRevisionSpec: vi.fn(),- transitionAgentRevision: vi.fn(),-};--vi.mock("@posthog/ui/features/auth/authClient", () => ({- useAuthenticatedClient: () => client,-}));-vi.mock("../../auth/store", () => ({- useAuthStateValue: () => 1,-}));--import { agentApplicationsKeys } from "./agentApplicationsKeys";-import { useApplyAgentSpec } from "./useApplyAgentSpec";--describe("useApplyAgentSpec", () => {- beforeEach(() => {- client.createAgentDraftRevisionFrom.mockReset();- client.updateAgentRevisionSpec.mockReset();- client.transitionAgentRevision.mockReset();- });-- it("PATCHes a draft in place — no new draft branched", async () => {- client.updateAgentRevisionSpec.mockResolvedValue({- id: "d1",- state: "draft",- });- renderHook(() => useApplyAgentSpec("agent-slug", "app-1"));- const spec = { models: { mode: "auto", level: "high" } };-- await mutationFn({ revision: { id: "d1", state: "draft" }, spec });-- expect(client.createAgentDraftRevisionFrom).not.toHaveBeenCalled();- expect(client.updateAgentRevisionSpec).toHaveBeenCalledWith(- "agent-slug",- "d1",- spec,- );- });-- it("clones to a fresh draft then PATCHes it when the source isn't a draft", async () => {- client.createAgentDraftRevisionFrom.mockResolvedValue({- id: "new-draft",- state: "draft",- });- client.updateAgentRevisionSpec.mockResolvedValue({- id: "new-draft",- state: "draft",- });- renderHook(() => useApplyAgentSpec("agent-slug", "app-1"));- const spec = { models: { mode: "manual", models: [{ model: "x" }] } };-- await mutationFn({ revision: { id: "live-1", state: "live" }, spec });-- expect(client.createAgentDraftRevisionFrom).toHaveBeenCalledWith(- "app-1",- "live-1",- );- expect(client.updateAgentRevisionSpec).toHaveBeenCalledWith(- "agent-slug",- "new-draft",- spec,- );- });-- it("throws when a clone is needed but the application id is missing", async () => {- renderHook(() => useApplyAgentSpec("agent-slug", undefined));-- await expect(- mutationFn({ revision: { id: "live-1", state: "live" }, spec: {} }),- ).rejects.toThrow(/Application/);- expect(client.createAgentDraftRevisionFrom).not.toHaveBeenCalled();- });-- it("archives the orphaned draft (and rethrows) when the PATCH fails after a clone", async () => {- client.createAgentDraftRevisionFrom.mockResolvedValue({- id: "new-draft",- state: "draft",- });- const patchErr = new Error("spec.models: invalid");- client.updateAgentRevisionSpec.mockRejectedValue(patchErr);- client.transitionAgentRevision.mockResolvedValue({ id: "new-draft" });- renderHook(() => useApplyAgentSpec("agent-slug", "app-1"));-- await expect(- mutationFn({ revision: { id: "live-1", state: "live" }, spec: {} }),- ).rejects.toThrow(patchErr);- // The just-cloned, never-landed draft gets archived as cleanup.- expect(client.transitionAgentRevision).toHaveBeenCalledWith(- "agent-slug",- "new-draft",- "archive",- );- });-- it("does NOT archive when an in-place draft PATCH fails (nothing was cloned)", async () => {- client.updateAgentRevisionSpec.mockRejectedValue(new Error("boom"));- renderHook(() => useApplyAgentSpec("agent-slug", "app-1"));-- await expect(- mutationFn({ revision: { id: "d1", state: "draft" }, spec: {} }),- ).rejects.toThrow(/boom/);- expect(client.createAgentDraftRevisionFrom).not.toHaveBeenCalled();- expect(client.transitionAgentRevision).not.toHaveBeenCalled();- });-- it("onSuccess invalidates the detail, revisions, and per-revision caches via the shared key factory", () => {- // projectId is mocked to 1 (useAuthStateValue). Asserting against the- // factory rather than literal arrays means these keys can't silently drift- // from the fetch hooks that own the caches — the gap when useMutation is- // mocked away.- renderHook(() => useApplyAgentSpec("agent-slug", "app-1"));- expect(onSuccess).toBeDefined();- onSuccess?.();-- const invalidated = invalidateQueries.mock.calls.map((c) => c[0].queryKey);- expect(invalidated).toContainEqual(- agentApplicationsKeys.detail(1, "agent-slug"),- );- expect(invalidated).toContainEqual(- agentApplicationsKeys.revisions(1, "agent-slug"),- );- expect(invalidated).toContainEqual(- agentApplicationsKeys.revisionPrefix(1, "agent-slug"),- );- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useApplyAgentSpec.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useApplyAgentSpec.tsdeleted file mode 100644index 9f59794c927b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useApplyAgentSpec.ts+++ /dev/null@@ -1,72 +0,0 @@-import type {- AgentRevision,- AgentRevisionState,- AgentSpec,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Apply a spec change ("create draft and apply changes"): if the target- * revision is already a draft, PATCH its spec in place; otherwise clone it to a- * fresh draft first and PATCH that. Freeze/promote stay separate (the revision- * bar's lifecycle buttons) — this only lands the edit on an editable draft.- *- * Returns the revision the change landed on so the caller can select it (it's a- * new draft whenever the source wasn't a draft).- */-export function useApplyAgentSpec(- idOrSlug: string,- applicationId: string | undefined,-) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<- AgentRevision,- Error,- { revision: { id: string; state: AgentRevisionState }; spec: AgentSpec }- >({- mutationFn: async ({ revision, spec }) => {- let targetId = revision.id;- const clonedDraft = revision.state !== "draft";- if (clonedDraft) {- if (!applicationId) {- throw new Error("Application not loaded yet");- }- const draft = await client.createAgentDraftRevisionFrom(- applicationId,- revision.id,- );- targetId = draft.id;- }- try {- return await client.updateAgentRevisionSpec(idOrSlug, targetId, spec);- } catch (err) {- // If we cloned a fresh draft and the spec PATCH then failed, that- // draft is an orphan (a copy of the source with no edit landed).- // Archive it best-effort so repeated failed applies don't pile up- // empty drafts; never mask the original error. A pre-existing draft- // passed in by the caller is left untouched.- if (clonedDraft) {- await client- .transitionAgentRevision(idOrSlug, targetId, "archive")- .catch(() => undefined);- }- throw err;- }- },- onSuccess: () => {- for (const key of [- agentApplicationsKeys.detail(projectId, idOrSlug),- agentApplicationsKeys.revisions(projectId, idOrSlug),- agentApplicationsKeys.revisionPrefix(projectId, idOrSlug),- ]) {- void queryClient.invalidateQueries({ queryKey: key });- }- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useApprovalDeepLink.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useApprovalDeepLink.tsdeleted file mode 100644index a7d216c659ba..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useApprovalDeepLink.ts+++ /dev/null@@ -1,80 +0,0 @@-import { useHostTRPC } from "@posthog/host-router/react";-import { useAuthStateValue } from "@posthog/ui/features/auth/store";-import { navigateToApproval } from "@posthog/ui/router/navigationBridge";-import { logger } from "@posthog/ui/shell/logger";-import { useQuery } from "@tanstack/react-query";-import { useSubscription } from "@trpc/tanstack-react-query";-import { useCallback, useEffect, useState } from "react";--const log = logger.scope("approval-deep-link");--/** A deep link that should open the ingress-backed approval modal. */-export interface PendingApprovalDeepLink {- requestId: string;- /** Agent slug — needed to address the slug-routed ingress. */- agent: string;-}--/**- * Handles agent approval deep links (`<scheme>://approval/{requestId}?agent=<slug>`).- * The agent-runner emits these on a gated tool call so non-PostHog-Code clients- * (MCP, a Slack link) can decide in the desktop app.- *- * When the link carries `?agent=<slug>` we open an ingress-backed modal: fetch +- * decide go straight to the slug-routed ingress (principal-authed), so it works- * from any project. A legacy link without a slug falls back to the- * (project-scoped) fleet Approvals inbox.- *- * Mirrors `useScoutDeepLink`: drains a link that arrived before the renderer was- * ready (the main process clears its pending entry on read) and subscribes for- * links delivered while the app is already running. Returns the pending modal- * target (or null) for a host component to render.- */-export function useApprovalDeepLink(): {- pending: PendingApprovalDeepLink | null;- clear: () => void;-} {- const trpcReact = useHostTRPC();- const isAuthenticated = useAuthStateValue(- (s) => s.status === "authenticated",- );- const [pending, setPending] = useState<PendingApprovalDeepLink | null>(null);-- const open = useCallback((requestId: string, agent: string | null) => {- if (agent) {- log.info(`Opening approval modal: requestId=${requestId} agent=${agent}`);- setPending({ requestId, agent });- } else {- // Legacy link with no slug — can't address the ingress; fall back to the- // project-scoped fleet Approvals inbox.- log.info(`Opening approval in inbox (no agent): requestId=${requestId}`);- navigateToApproval(requestId);- }- }, []);-- const pendingDeepLink = useQuery(- trpcReact.deepLink.getPendingApprovalLink.queryOptions(undefined, {- enabled: isAuthenticated,- // Drain once per session – the main process clears its pending entry on read.- staleTime: Number.POSITIVE_INFINITY,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- }),- );-- useEffect(() => {- if (pendingDeepLink.data?.requestId) {- open(pendingDeepLink.data.requestId, pendingDeepLink.data.agent);- }- }, [pendingDeepLink.data, open]);-- useSubscription(- trpcReact.deepLink.onOpenApproval.subscriptionOptions(undefined, {- onData: (data) => {- if (data?.requestId) open(data.requestId, data.agent);- },- }),- );-- return { pending, clear: useCallback(() => setPending(null), []) };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useCreateAgentDraftFromRevision.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useCreateAgentDraftFromRevision.tsdeleted file mode 100644index 52d6de8f45fc..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useCreateAgentDraftFromRevision.ts+++ /dev/null@@ -1,42 +0,0 @@-import type { AgentRevision } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Fork an existing revision into a fresh editable draft (one round trip via- * `…/revisions/new_draft/`). The standard exit for "I want to keep iterating- * on this ready / live / archived revision" — the source bundle is immutable,- * so we branch off a copy. Returns the new revision so the caller can select- * it in the picker immediately.- *- * The body wants the application's UUID, not its slug, so callers pass- * `application.id` explicitly (the URL slug used elsewhere wouldn't work).- */-export function useCreateAgentDraftFromRevision(- idOrSlug: string,- applicationId: string | undefined,-) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<AgentRevision, Error, { sourceRevisionId: string }>({- mutationFn: ({ sourceRevisionId }) => {- if (!applicationId) {- throw new Error("Application not loaded yet");- }- return client.createAgentDraftRevisionFrom(- applicationId,- sourceRevisionId,- );- },- onSuccess: () => {- // Refresh the revisions list so the new draft shows up in the picker.- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.revisions(projectId, idOrSlug),- });- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useDecideAgentApproval.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useDecideAgentApproval.tsdeleted file mode 100644index 11b040fec8b0..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useDecideAgentApproval.ts+++ /dev/null@@ -1,98 +0,0 @@-import type {- AgentApprovalRequest,- DecideApprovalRequest,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { toast } from "@posthog/ui/primitives/toast";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--interface DecideArgs {- approvalId: string;- body: DecideApprovalRequest;-}--type ApprovalCacheSnapshot = [readonly unknown[], unknown][];--/**- * Approve or reject a queued tool-approval request. Optimistically clears the- * approval from every cached approvals shape so the in-chat card unmounts- * immediately (no decide-roundtrip → invalidate → list-refetch lag); restores- * on failure. On success, refetches the agent's approval lists so the row- * reflects its outcome, and fires a toast so the caller doesn't have to add- * post-decide UX.- */-export function useDecideAgentApproval(idOrSlug: string) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<- AgentApprovalRequest,- Error,- DecideArgs,- { snapshot: ApprovalCacheSnapshot }- >({- mutationFn: ({ approvalId, body }) =>- client.decideAgentApproval(idOrSlug, approvalId, body),- onMutate: async ({ approvalId }) => {- // Cancel in-flight approvals queries so a slow refetch can't overwrite- // the optimistic clear after the user has already moved on.- const prefix = agentApplicationsKeys.approvalsPrefix(projectId, idOrSlug);- await queryClient.cancelQueries({ queryKey: prefix });- const snapshot: ApprovalCacheSnapshot =- queryClient.getQueriesData<unknown>({ queryKey: prefix });- // One updater for both shapes: chatPendingApproval stores- // `AgentApprovalRequest | null`; list queries store `AgentApprovalRequest[]`.- queryClient.setQueriesData<unknown>(- { queryKey: prefix },- (old: unknown) => {- if (old == null) return old;- if (Array.isArray(old)) {- return (old as AgentApprovalRequest[]).filter(- (r) => r.id !== approvalId,- );- }- if (typeof old === "object" && old !== null && "id" in old) {- return (old as AgentApprovalRequest).id === approvalId ? null : old;- }- return old;- },- );- return { snapshot };- },- onSuccess: (_data, { body }) => {- if (body.decision === "approve") {- toast.success("Approved", {- description:- body.edited_args !== undefined- ? "Dispatched with edited arguments."- : "Dispatched to the agent.",- });- } else {- toast.success("Rejected", {- description: "The agent will see the rejection.",- });- }- },- onError: (err, _vars, context) => {- // Restore each shape exactly as it was before the optimistic clear.- if (context?.snapshot) {- for (const [key, data] of context.snapshot) {- queryClient.setQueryData(key, data);- }- }- toast.error("Decision failed", {- description: err instanceof Error ? err.message : undefined,- });- },- onSettled: () => {- // Converge with server truth — handles next-in-line pending approvals- // for the same session, and refreshes any state-filtered list views.- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.approvalsPrefix(projectId, idOrSlug),- });- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useDeleteRevisionTool.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useDeleteRevisionTool.tsdeleted file mode 100644index 75b42e21dddb..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useDeleteRevisionTool.ts+++ /dev/null@@ -1,24 +0,0 @@-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Delete one custom tool from a draft revision (draft-only). On success the- * bundle query is invalidated so the removed tool drops out of the explorer.- */-export function useDeleteRevisionTool(idOrSlug: string, revisionId: string) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<void, Error, { toolId: string }>({- mutationFn: ({ toolId }) =>- client.deleteRevisionTool(idOrSlug, revisionId, toolId),- onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.bundle(projectId, idOrSlug, revisionId),- });- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useDryRunRevisionTool.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useDryRunRevisionTool.tsdeleted file mode 100644index e43d3abc66a4..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useDryRunRevisionTool.ts+++ /dev/null@@ -1,25 +0,0 @@-import type {- DryRunToolRequest,- DryRunToolResult,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation } from "@tanstack/react-query";--interface DryRunArgs {- toolId: string;- body: DryRunToolRequest;-}--/**- * Execute a persisted tool once in a sandbox (POST …/dry_run). No cache- * invalidation — dry-run is a side-effect-free probe. Throttled (429) and- * unavailable (503) are returned as {@link DryRunToolResult} outcomes, not- * errors, so the panel handles them explicitly; callers must NOT retry a 429.- */-export function useDryRunRevisionTool(idOrSlug: string, revisionId: string) {- const client = useAuthenticatedClient();- return useMutation<DryRunToolResult, Error, DryRunArgs>({- mutationFn: ({ toolId, body }) =>- client.dryRunRevisionTool(idOrSlug, revisionId, toolId, body),- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useFireAgentCron.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useFireAgentCron.tsdeleted file mode 100644index a3e5dca45257..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useFireAgentCron.ts+++ /dev/null@@ -1,14 +0,0 @@-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation } from "@tanstack/react-query";--/**- * Fires a cron trigger out-of-band. Returns the created session id so the caller- * can jump straight to the run it kicked off.- */-export function useFireAgentCron(idOrSlug: string, revisionId: string) {- const client = useAuthenticatedClient();- return useMutation<{ session_id: string }, Error, { cronName: string }>({- mutationFn: ({ cronName }) =>- client.fireAgentCron(idOrSlug, revisionId, cronName),- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useImportAgentDraftBundle.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useImportAgentDraftBundle.tsdeleted file mode 100644index 534dd309d88e..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useImportAgentDraftBundle.ts+++ /dev/null@@ -1,43 +0,0 @@-import type { AgentRevision } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--interface ImportBody {- agent_md?: string;- skills?: { id: string; description?: string; body: string }[];-}--/**- * Bulk-paste a set of `.md` files into a draft revision — the migration- * hatch when porting an existing multi-file agent. Merges by skill id (adds- * new skills, overwrites bodies for existing ids; skills not mentioned are- * left alone). Draft-only on the server. Invalidates the same caches as the- * per-file update so the explorer reflects all touched files at once.- */-export function useImportAgentDraftBundle(- idOrSlug: string,- revisionId: string,-) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<AgentRevision, Error, ImportBody>({- mutationFn: (body) =>- client.importAgentDraftBundle(idOrSlug, revisionId, body),- onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.bundle(projectId, idOrSlug, revisionId),- });- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.revision(- projectId,- idOrSlug,- revisionId,- ),- });- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useModelCatalog.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useModelCatalog.tsdeleted file mode 100644index c805c4725f06..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useModelCatalog.ts+++ /dev/null@@ -1,34 +0,0 @@-import type { ModelCatalog } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";-import { useAuthStateValue } from "../../auth/store";--// Levels rarely change and the auto-level preview needs them even while the-// catalog request is in flight; the authoritative values still come from the-// endpoint. Models are left empty until the fetch resolves.-const FALLBACK: ModelCatalog = {- models: [],- levels: {- low: ["anthropic/claude-haiku-4.5", "openai/gpt-5-mini"],- medium: ["anthropic/claude-sonnet-4.6", "openai/gpt-5"],- high: ["anthropic/claude-opus-4.7", "openai/gpt-5-pro"],- },-};--/**- * The served-model catalog + curated auto-level → model map, from- * `GET …/agent_applications/models/` (which proxies the AI gateway catalog).- * Feeds the model browser and the auto-level preview. Falls back to an empty- * catalog (with the known levels) while loading or if the endpoint is down.- */-export function useModelCatalog(): {- catalog: ModelCatalog;- isLoading: boolean;-} {- const projectId = useAuthStateValue((state) => state.currentProjectId);- const { data, isLoading } = useAuthenticatedQuery<ModelCatalog>(- ["agent-applications", "model-catalog", projectId],- (client) => client.getAgentModelCatalog(),- { enabled: !!projectId, staleTime: 5 * 60_000 },- );- return { catalog: data ?? FALLBACK, isLoading };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useSaveRevisionTool.test.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useSaveRevisionTool.test.tsdeleted file mode 100644index 57b8c6a90cda..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useSaveRevisionTool.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { renderHook } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--// Capture the mutationFn + onSuccess handed to react-query so we can drive the-// PUT call and the "invalidate only when the compile actually persisted" branch-// without a live QueryClient.-let mutationFn: (vars: { toolId: string; body: unknown }) => Promise<unknown>;-let onSuccess: ((result: unknown) => void) | undefined;-let invalidateQueries: ReturnType<typeof vi.fn>;--vi.mock("@tanstack/react-query", () => ({- useMutation: (opts: {- mutationFn: typeof mutationFn;- onSuccess?: (result: unknown) => void;- }) => {- mutationFn = opts.mutationFn;- onSuccess = opts.onSuccess;- return { mutate: vi.fn() };- },- useQueryClient: () => {- invalidateQueries = vi.fn();- return { invalidateQueries };- },-}));--const client = {- putRevisionTool: vi.fn(),-};--vi.mock("@posthog/ui/features/auth/authClient", () => ({- useAuthenticatedClient: () => client,-}));-vi.mock("../../auth/store", () => ({- useAuthStateValue: () => 7,-}));--import { agentApplicationsKeys } from "./agentApplicationsKeys";-import { useSaveRevisionTool } from "./useSaveRevisionTool";--describe("useSaveRevisionTool", () => {- beforeEach(() => {- client.putRevisionTool.mockReset();- });-- it("PUTs the tool body via the client", async () => {- client.putRevisionTool.mockResolvedValue({ ok: true });- renderHook(() => useSaveRevisionTool("agent", "rev-1"));- const body = { description: "d", args_schema: {}, source: "x" };-- await mutationFn({ toolId: "t1", body });-- expect(client.putRevisionTool).toHaveBeenCalledWith(- "agent",- "rev-1",- "t1",- body,- );- });-- it("invalidates the bundle query when the compile persisted (ok)", () => {- renderHook(() => useSaveRevisionTool("agent", "rev-1"));- onSuccess?.({ ok: true, tool_id: "t1", capabilities: {} });-- expect(invalidateQueries).toHaveBeenCalledWith({- queryKey: agentApplicationsKeys.bundle(7, "agent", "rev-1"),- });- });-- it("does NOT invalidate when the compile failed (422, nothing persisted)", () => {- renderHook(() => useSaveRevisionTool("agent", "rev-1"));- onSuccess?.({- ok: false,- error: "tool_compile_failed",- tool_id: "t1",- errors: [],- });-- expect(invalidateQueries).not.toHaveBeenCalled();- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useSaveRevisionTool.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useSaveRevisionTool.tsdeleted file mode 100644index edb8ea1df5d8..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useSaveRevisionTool.ts+++ /dev/null@@ -1,42 +0,0 @@-import type {- WriteToolRequest,- WriteToolResult,-} from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--interface SaveToolArgs {- toolId: string;- body: WriteToolRequest;-}--/**- * Author/compile one custom tool on a draft revision (PUT). A compile failure is- * a typed `{ ok: false }` result (HTTP 422), not a throw, so the caller inspects- * the returned {@link WriteToolResult} to render inline diagnostics. Only a- * successful compile persists, so the bundle query is invalidated only then — the- * explorer/editor then reflects the saved source.- */-export function useSaveRevisionTool(idOrSlug: string, revisionId: string) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<WriteToolResult, Error, SaveToolArgs>({- mutationFn: ({ toolId, body }) =>- client.putRevisionTool(idOrSlug, revisionId, toolId, body),- onSuccess: (result) => {- if (result.ok) {- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.bundle(- projectId,- idOrSlug,- revisionId,- ),- });- }- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/hooks/useUpdateAgentDraftBundleFile.ts b/products/desktop/packages/ui/src/features/agent-applications/hooks/useUpdateAgentDraftBundleFile.tsdeleted file mode 100644index 2df7c0e21d4b..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/hooks/useUpdateAgentDraftBundleFile.ts+++ /dev/null@@ -1,37 +0,0 @@-import type { AgentRevision } from "@posthog/shared/agent-platform-types";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useAuthStateValue } from "../../auth/store";-import { agentApplicationsKeys } from "./agentApplicationsKeys";--/**- * Write a single bundle file (agent.md or skills/<id>/SKILL.md) on a draft- * revision. The server rejects non-draft revisions with 409, so the UI gates- * on revision state too. Invalidates the bundle (the rendered file body) and- * the revision (updated_at moves) on success.- */-export function useUpdateAgentDraftBundleFile(- idOrSlug: string,- revisionId: string,-) {- const client = useAuthenticatedClient();- const queryClient = useQueryClient();- const projectId = useAuthStateValue((state) => state.currentProjectId);-- return useMutation<AgentRevision, Error, { path: string; content: string }>({- mutationFn: ({ path, content }) =>- client.updateAgentDraftBundleFile(idOrSlug, revisionId, path, content),- onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.bundle(projectId, idOrSlug, revisionId),- });- void queryClient.invalidateQueries({- queryKey: agentApplicationsKeys.revision(- projectId,- idOrSlug,- revisionId,- ),- });- },- });-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/utils/format.ts b/products/desktop/packages/ui/src/features/agent-applications/utils/format.tsdeleted file mode 100644index bf2e70aa3900..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/utils/format.ts+++ /dev/null@@ -1,129 +0,0 @@-import type {- AgentApprovalRequestState,- AgentRevisionState,- AgentSessionState,- AgentUserWithConnections,-} from "@posthog/shared/agent-platform-types";--/**- * Display name from a user's trigger-stamped metadata (`display_name` → `name`),- * or null when neither is present. Shared by the Users pane and the Sessions- * user-filter so the resolution lives in one place.- */-export function userDisplayName(user: AgentUserWithConnections): string | null {- const meta = user.metadata;- if (typeof meta?.display_name === "string") return meta.display_name;- if (typeof meta?.name === "string") return meta.name;- return null;-}-/** Formats a USD spend value for the fleet / agent stat strips. */-export function formatSpendUsd(value: number | null | undefined): string {- if (value == null) return "$0";- // Clamp non-positive to $0: cost is never legitimately negative, and an- // upstream cost-calc artifact (negative `$ai_total_cost_usd`) shouldn't- // surface as "-$2.74" or fall into the sub-cent "<$0.01" branch below.- if (value <= 0) return "$0";- if (value < 0.01) return "<$0.01";- return `$${value.toLocaleString(undefined, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}`;-}--/** Radix Badge colour for a session lifecycle state. */-export function sessionStateColor(- state: AgentSessionState,-): "green" | "blue" | "gray" | "red" | "amber" {- switch (state) {- case "running":- return "blue";- case "queued":- return "amber";- case "completed":- case "closed":- return "green";- case "failed":- return "red";- case "cancelled":- return "gray";- default:- return "gray";- }-}--/** Radix Badge colour for a tool-approval request state. */-export function approvalStateColor(- state: AgentApprovalRequestState,-): "green" | "blue" | "gray" | "red" | "amber" {- switch (state) {- case "queued":- return "amber";- case "approving":- return "blue";- case "dispatched":- return "green";- case "dispatched_failed":- case "rejected":- return "red";- default:- return "gray";- }-}--/** Human label for a tool-approval request state. */-export function approvalStateLabel(state: AgentApprovalRequestState): string {- switch (state) {- case "dispatched":- return "approved";- case "dispatched_failed":- return "dispatch failed";- default:- return state;- }-}--/** Dot/text colour CSS var for a log level. */-export function logLevelColor(level: string): string {- switch (level.toUpperCase()) {- case "ERROR":- case "FATAL":- return "var(--red-9)";- case "WARN":- case "WARNING":- return "var(--amber-9)";- case "INFO":- return "var(--blue-9)";- case "DEBUG":- return "var(--gray-7)";- default:- return "var(--gray-9)";- }-}--/** Compact elapsed time between two ISO timestamps (e.g. "1.2s", "3m 4s"). */-export function formatDuration(startIso: string, endIso: string): string {- const ms = new Date(endIso).getTime() - new Date(startIso).getTime();- if (!Number.isFinite(ms) || ms < 0) return "—";- const s = ms / 1000;- if (s < 1) return `${Math.round(ms)}ms`;- if (s < 60) return `${s.toFixed(1)}s`;- const m = Math.floor(s / 60);- const rem = Math.round(s % 60);- return `${m}m ${rem}s`;-}--/** Radix Badge colour for a revision lifecycle state. */-export function revisionStateColor(- state: AgentRevisionState,-): "green" | "blue" | "gray" | "amber" {- switch (state) {- case "live":- return "green";- case "ready":- return "blue";- case "draft":- return "amber";- default:- return "gray";- }-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/utils/ingress.test.ts b/products/desktop/packages/ui/src/features/agent-applications/utils/ingress.test.tsdeleted file mode 100644index 877881cccc6e..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/utils/ingress.test.ts+++ /dev/null@@ -1,21 +0,0 @@-import type { CloudRegion } from "@posthog/shared";-import { describe, expect, it } from "vitest";-import { agentIngressBaseUrl } from "./ingress";--describe("agentIngressBaseUrl", () => {- it.each<{ region: CloudRegion; expected: string }>([- { region: "us", expected: "https://my-agent.agents.us.posthog.com" },- { region: "eu", expected: "https://my-agent.agents.eu.posthog.com" },- { region: "dev", expected: "http://localhost:3030/agents/my-agent" },- ])("builds the $region URL for a valid slug", ({ region, expected }) => {- expect(agentIngressBaseUrl("my-agent", region)).toBe(expected);- });-- it.each(["evil.com/", ""])("refuses to interpolate the slug %s", (slug) => {- expect(agentIngressBaseUrl(slug, "us")).toBeNull();- });-- it("returns null without a region", () => {- expect(agentIngressBaseUrl("my-agent", null)).toBeNull();- });-});diff --git a/products/desktop/packages/ui/src/features/agent-applications/utils/ingress.ts b/products/desktop/packages/ui/src/features/agent-applications/utils/ingress.tsdeleted file mode 100644index f4f1a11a68bf..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/utils/ingress.ts+++ /dev/null@@ -1,53 +0,0 @@-import { type CloudRegion, isValidAgentSlug } from "@posthog/shared";--/**- * Resolve the agent-ingress base URL for live (streaming) calls, derived per- * region the same way the PostHog API base is (`getCloudUrlFromRegion`).- *- * In `dev` the backend hands out a trycloudflare quick-tunnel URL in- * `ingress_base_url`, and those tunnels BUFFER SSE — so `/listen` never streams- * incrementally through them. The local agent-ingress (localhost:3030) streams- * fine, so for `dev` we keep the record's `/agents/<slug>` path but point the- * origin at the local ingress. us/eu ingress URLs stream natively, so their- * (region-correct) `ingress_base_url` is used as-is.- */-const LOCAL_INGRESS_ORIGIN = "http://localhost:3030";--export function resolveIngressBaseUrl(- ingressBaseUrl: string | null | undefined,- region: CloudRegion | null,-): string | null {- if (!ingressBaseUrl) return null;- if (region === "dev") {- return ingressBaseUrl.replace(/^https?:\/\/[^/]+/, LOCAL_INGRESS_ORIGIN);- }- return ingressBaseUrl;-}--/**- * Construct an agent's ingress base URL from `(slug, region)` alone, without- * loading its API record. The ingress is slug-routed and team-agnostic (the- * slug is a single global namespace), so this resolves an agent from any- * project — including one the agent isn't hosted in. Mirrors the deployed- * routing config (charts `AGENT_INGRESS_*`): us/eu address agents in domain mode- * (`<slug>.agents.<region>.posthog.com`); local dev uses the path-mode local- * ingress, which streams SSE (the dev quick-tunnel buffers it).- *- * Use this for first-party agents reachable cross-project (the agent builder).- * Per-agent console views stay on {@link resolveIngressBaseUrl} + the record,- * which carries other fields and is correctly project-scoped.- */-export function agentIngressBaseUrl(- slug: string,- region: CloudRegion | null,-): string | null {- if (!isValidAgentSlug(slug) || !region) return null;- switch (region) {- case "us":- return `https://${slug}.agents.us.posthog.com`;- case "eu":- return `https://${slug}.agents.eu.posthog.com`;- case "dev":- return `${LOCAL_INGRESS_ORIGIN}/agents/${slug}`;- }-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/utils/observabilityLinks.ts b/products/desktop/packages/ui/src/features/agent-applications/utils/observabilityLinks.tsdeleted file mode 100644index 016945d81ad3..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/utils/observabilityLinks.ts+++ /dev/null@@ -1,18 +0,0 @@-import { type CloudRegion, getCloudUrlFromRegion } from "@posthog/shared";--/**- * Deep link into the team's own AI observability product. The runner captures- * the agents' `$ai_*` events into that project, so the trace / generation /- * cost detail lives there; the observability surface shows lightweight rollups- * inline and links out here for depth. Returns null until region + project are- * both known.- */-export function aiObservabilityTracesUrl(- region: CloudRegion | null,- projectId: number | null,-): string | null {- if (!region || projectId == null) {- return null;- }- return `${getCloudUrlFromRegion(region)}/project/${projectId}/ai-observability/traces`;-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/utils/parseBundleInput.ts b/products/desktop/packages/ui/src/features/agent-applications/utils/parseBundleInput.tsdeleted file mode 100644index cc0ef965e0f4..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/utils/parseBundleInput.ts+++ /dev/null@@ -1,66 +0,0 @@-const HEADER_RE = /^---\s*(.+?)\s*---\s*$/;-const SKILL_PATH_RE = /^skills\/([a-z0-9-]+)\/SKILL\.md$/;--export interface ParsedBundle {- agent_md?: string;- skills?: { id: string; body: string }[];-}--/**- * Splits a fenced paste — alternating `--- <path> ---` headers and bodies —- * into the import payload the server accepts. The format is deliberately- * simple so the source files can be cat'd together as-is; only `agent.md`- * and `skills/<id>/SKILL.md` are recognised.- */-export function parseBundleInput(- input: string,-): { ok: true; value: ParsedBundle } | { ok: false; error: string } {- const lines = input.replace(/\r\n/g, "\n").split("\n");- const value: ParsedBundle = {};- let current: { kind: "agent" } | { kind: "skill"; id: string } | null = null;- let buf: string[] = [];-- const flush = () => {- if (!current) return;- const content = buf.join("\n").replace(/^\n+|\n+$/g, "");- if (current.kind === "agent") {- value.agent_md = content;- } else {- if (!value.skills) value.skills = [];- value.skills.push({ id: current.id, body: content });- }- };-- for (const line of lines) {- const m = HEADER_RE.exec(line);- if (m) {- flush();- buf = [];- const path = m[1];- if (path === "agent.md") {- current = { kind: "agent" };- } else {- const skill = SKILL_PATH_RE.exec(path);- if (!skill) {- return {- ok: false,- error: `Unsupported file path: "${path}". Use "agent.md" or "skills/<id>/SKILL.md".`,- };- }- current = { kind: "skill", id: skill[1] };- }- continue;- }- if (current) buf.push(line);- }- flush();-- if (value.agent_md === undefined && !value.skills?.length) {- return {- ok: false,- error:- "Nothing to import. Add at least one `--- agent.md ---` or `--- skills/<id>/SKILL.md ---` block.",- };- }- return { ok: true, value };-}diff --git a/products/desktop/packages/ui/src/features/agent-applications/utils/triggerSecrets.ts b/products/desktop/packages/ui/src/features/agent-applications/utils/triggerSecrets.tsdeleted file mode 100644index 2944de5820c5..000000000000--- a/products/desktop/packages/ui/src/features/agent-applications/utils/triggerSecrets.ts+++ /dev/null@@ -1,108 +0,0 @@-import type { AgentSpec } from "@posthog/shared/agent-platform-types";--/**- * Secrets a trigger needs in encrypted_env, derived from the spec. Mirrors the- * agent-console `triggerSecrets.ts` (itself a mirror of the agent-shared +- * Django `spec_schema` source). Used to surface "missing secret" warnings on- * triggers/mcps alongside the spec's top-level `secrets[]`.- */--export const SLACK_SIGNING_SECRET_KEY = "SLACK_SIGNING_SECRET";-export const SLACK_BOT_TOKEN_KEY = "SLACK_BOT_TOKEN";--export interface DerivedTriggerSecret {- key: string;- label: string;- description: string;- /** Which trigger type contributed this requirement. */- trigger: string;-}--function rec(v: unknown): Record<string, unknown> {- return v && typeof v === "object" ? (v as Record<string, unknown>) : {};-}-function str(v: unknown): string | undefined {- return typeof v === "string" ? v : undefined;-}--const SLACK_SECRETS: Omit<DerivedTriggerSecret, "trigger">[] = [- {- key: SLACK_SIGNING_SECRET_KEY,- label: "Slack signing secret",- description:- "Your Slack app's signing secret (Settings → Basic Information). Verifies inbound Slack event signatures.",- },- {- key: SLACK_BOT_TOKEN_KEY,- label: "Slack bot user OAuth token",- description:- "Your Slack app's bot token (xoxb-…), from Settings → Install App. Used by native Slack tools.",- },-];--/** A secret referenced by a webhook/jwt auth mode, or null. */-function authModeSecret(- mode: unknown,-): Omit<DerivedTriggerSecret, "trigger"> | null {- const m = rec(mode);- if (m.type === "shared_secret" && str(m.secret_ref)) {- return {- key: str(m.secret_ref) as string,- label: "Webhook shared secret",- description: `Expected value for the \`${str(m.header) ?? ""}\` header. Callers must send this exact secret.`,- };- }- if (m.type === "jwt" && str(m.issuer_secret_ref)) {- return {- key: str(m.issuer_secret_ref) as string,- label: "JWT signing secret",- description: "HMAC secret used to verify inbound JWT signatures.",- };- }- return null;-}--/** Required secrets for a single trigger (slack keys + its auth-mode secrets). */-export function triggerRequiredSecretsFor(- trigger: unknown,-): Omit<DerivedTriggerSecret, "trigger">[] {- const type = str(rec(trigger).type) ?? "trigger";- const out: Omit<DerivedTriggerSecret, "trigger">[] = [];- if (type === "slack") out.push(...SLACK_SECRETS);- const modes = rec(rec(trigger).auth).modes;- for (const mode of Array.isArray(modes) ? modes : []) {- const s = authModeSecret(mode);- if (s) out.push(s);- }- return out;-}--/** Per-trigger required secrets, deduped by key (first trigger wins). */-export function getTriggerRequiredSecrets(- spec: AgentSpec,-): DerivedTriggerSecret[] {- const triggers = Array.isArray(spec.triggers) ? spec.triggers : [];- const seen = new Set<string>();- const out: DerivedTriggerSecret[] = [];- const add = (- s: Omit<DerivedTriggerSecret, "trigger">,- trigger: string,- ): void => {- if (seen.has(s.key)) return;- seen.add(s.key);- out.push({ ...s, trigger });- };- for (const t of triggers) {- const type = str(rec(t).type) ?? "trigger";- if (type === "slack") {- for (const s of SLACK_SECRETS) add(s, type);- }- for (const mode of Array.isArray(rec(rec(t).auth).modes)- ? (rec(rec(t).auth).modes as unknown[])- : []) {- const s = authModeSecret(mode);- if (s) add(s, type);- }- }- return out;-}diff --git a/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsx b/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsxindex a5c635c568a8..746672d2bf80 100644--- a/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsx+++ b/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsx@@ -1,114 +1,41 @@import { RobotIcon } from "@phosphor-icons/react";-import { AgentBuilderHeaderControls } from "@posthog/ui/features/agent-applications/agent-builder/AgentBuilderHeaderControls";-import type { AgentBuilderPageContext } from "@posthog/ui/features/agent-applications/agent-builder/agentBuilderStore";-import { useSetAgentBuilderPage } from "@posthog/ui/features/agent-applications/agent-builder/useSetAgentBuilderPage";-import { AGENT_PLATFORM_FLAG } from "@posthog/ui/features/agent-applications/featureFlag";-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";import { type ReactNode, useMemo } from "react";-export type AgentsTab = "scouts" | "applications";--/** Per-tab header copy so the chrome describes what you're actually looking at. */-const TAB_DESCRIPTION: Record<AgentsTab, string> = {- scouts:- "Self-driving agents that watch your project and surface work for review — enroll in the canonical fleet or author your own.",- applications:- "Talk it through. Ship it. Watch it work. The Agent Builder turns ideas into production agents.",-};--/**- * Shared chrome for the two top-level Agents tabs. Each tab view renders its- * own content inside this layout and declares which tab is active, so the- * header + tab bar stay identical across Scouts and Fleet while detail- * pages (a scout, an agent, a session) keep their own focused chrome.- */-export function AgentsTabLayout({- activeTab,- children,-}: {- activeTab: AgentsTab;- children: ReactNode;-}) {+export function AgentsTabLayout({ children }: { children: ReactNode }) {const headerContent = useMemo(() => (- <Flex align="center" gap="2" className="w-full min-w-0">+ <div className="flex w-full min-w-0 items-center gap-2"><RobotIcon size={12} className="shrink-0 text-gray-10" />- <Text+ <spanclassName="truncate whitespace-nowrap font-medium text-[13px]"title="Agents">Agents- </Text>- </Flex>+ </span>+ </div>),[],);useSetHeaderContent(headerContent);- const pageContext: AgentBuilderPageContext =- activeTab === "applications" ? { kind: "agent-list" } : { kind: "scouts" };- useSetAgentBuilderPage(pageContext);- // The Fleet tab is gated behind the agent-platform flag.- const applicationsEnabled = useFeatureFlag(AGENT_PLATFORM_FLAG);return (- <Flex direction="column" className="h-full min-h-0">- <div className="relative cursor-default select-none border-(--gray-5) border-b px-6 pt-5">- <AgentBuilderHeaderControls />- <Flex direction="column" gap="0.5" className="pr-44 pb-3.5">- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">+ <div className="flex h-full min-h-0 flex-col">+ <div className="cursor-default select-none border-(--gray-5) border-b px-6 py-5">+ <div className="flex flex-col gap-0.5">+ <h1 className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">Agents- </Text>- <Text className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">- {applicationsEnabled- ? TAB_DESCRIPTION[activeTab]- : "Design, schedule, and deploy the agents that work on your product."}- </Text>- </Flex>- <Flex gap="5" align="center">- <TabLink- to="/code/agents/scouts"- label="Scouts"- active={activeTab === "scouts"}- />- {applicationsEnabled ? (- <TabLink- to="/code/agents/applications"- label="Fleet"- active={activeTab === "applications"}- />- ) : null}- </Flex>+ </h1>+ <p className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">+ Self-driving agents that watch your project and surface work for+ review.+ </p>+ </div></div><div className="min-h-0 flex-1 overflow-auto"><div className="mx-auto max-w-4xl px-6 py-6">{children}</div></div>- </Flex>- );-}--function TabLink({- to,- label,- active,-}: {- to: string;- label: string;- active: boolean;-}) {- return (- <Link- to={to}- className={`-mb-px border-b-2 px-0.5 pb-2.5 text-[13px] no-underline transition-colors ${- active- ? "border-(--accent-9) font-medium text-gray-12"- : "border-transparent text-gray-11 hover:text-gray-12"- }`}- >- {label}- </Link>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx b/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsxindex 2ac39fd4a6de..1a8733d189e3 100644--- a/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx+++ b/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx@@ -1,14 +1,9 @@import { ConfigureAgentsSection } from "@posthog/ui/features/inbox/components/ConfigureAgentsSection";import { AgentsTabLayout } from "./AgentsTabLayout";-/**- * The Scouts tab: the scheduled-agent / self-driving configuration that has- * always lived under Agents. Deployed agent applications get their own tab- * (see {@link AgentApplicationsListView}).- */export function AgentsView() {return (- <AgentsTabLayout activeTab="scouts">+ <AgentsTabLayout><ConfigureAgentsSection /></AgentsTabLayout>);diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsxindex 22ea07964012..cad39dd74e4e 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx@@ -32,8 +32,8 @@ import {ToggleGroup,ToggleGroupItem,} from "@posthog/quill";-import { CopyButton } from "@posthog/ui/features/agent-applications/components/CopyButton";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";+import { CopyButton } from "@posthog/ui/primitives/CopyButton";import { TimezonePicker } from "@posthog/ui/primitives/TimezonePicker";import { TimezoneTimestamp } from "@posthog/ui/primitives/TimezoneTimestamp";import {diff --git a/products/desktop/packages/ui/src/features/mcp-server-manager/useMcpConnect.ts b/products/desktop/packages/ui/src/features/mcp-server-manager/useMcpConnect.tsindex 0a4e171d5646..719b630226c3 100644--- a/products/desktop/packages/ui/src/features/mcp-server-manager/useMcpConnect.ts+++ b/products/desktop/packages/ui/src/features/mcp-server-manager/useMcpConnect.ts@@ -51,7 +51,7 @@ export interface CustomServerInput {/*** Shared MCP connect/list primitives: the `mcp_store` install flow behind an* injectable host OAuth callback, plus the team's installations query. Consumed- * by both the standalone MCP-servers scene and the agent-applications builder.+ * by the standalone MCP-servers scene.*/export function useMcpConnect() {const trpc = useHostTRPC();diff --git a/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpServers.ts b/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpServers.tsindex 6717f52734e6..67db98125a60 100644--- a/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpServers.ts+++ b/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpServers.ts@@ -21,7 +21,7 @@ import { useSubscription } from "@trpc/tanstack-react-query";import { useCallback, useMemo } from "react";// `mcpKeys` + `createOAuthCallback` now live in the shared mcp-server-manager-// module (also used by the agent-applications builder). Re-exported here so+// module. Re-exported here so// existing importers (e.g. useMcpInstallationTools) keep their path.export { mcpKeys };diff --git a/products/desktop/packages/ui/src/features/agent-applications/components/CopyButton.tsx b/products/desktop/packages/ui/src/primitives/CopyButton.tsxsimilarity index 82%rename from products/desktop/packages/ui/src/features/agent-applications/components/CopyButton.tsxrename to products/desktop/packages/ui/src/primitives/CopyButton.tsxindex aa489017ee39..a4da8ac0b264 100644--- a/products/desktop/packages/ui/src/features/agent-applications/components/CopyButton.tsx+++ b/products/desktop/packages/ui/src/primitives/CopyButton.tsx@@ -1,10 +1,6 @@import { CheckIcon, CopyIcon } from "@phosphor-icons/react";import { useState } from "react";-/**- * Copy-to-clipboard button with a transient check. Icon-only by default;- * `bare` drops the border/background so it can nest inside another pill.- */export function CopyButton({text,label = "Copy",@@ -17,15 +13,17 @@ export function CopyButton({bare?: boolean;}) {const [copied, setCopied] = useState(false);- async function copy() {++ async function copy(): Promise<void> {try {await navigator.clipboard.writeText(text);setCopied(true);setTimeout(() => setCopied(false), 1500);} catch {- // Clipboard can be blocked (insecure context) — the text stays selectable.+ // Clipboard access can be blocked while the text remains selectable.}}+return (<buttontype="button"diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.tsindex 299392834fc3..36129da0b00d 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts@@ -189,13 +189,6 @@ export function navigateToAgents(): void {void getRouterOrNull()?.navigate({ to: "/code/agents" });}-export function navigateToApproval(requestId: string): void {- void getRouterOrNull()?.navigate({- to: "/code/agents/applications/approvals",- search: { request: requestId },- });-}-export function navigateToArchived(): void {void getRouterOrNull()?.navigate({ to: "/code/archived" });}diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.tsindex b707c82ec852..ac7188ed2e99 100644--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts@@ -50,14 +50,12 @@ import { Route as CodeInboxPullsRouteImport } from './routes/code/inbox/pulls'import { Route as CodeInboxDismissedRouteImport } from './routes/code/inbox/dismissed'import { Route as CodeInboxAgentsRouteImport } from './routes/code/inbox/agents'import { Route as CodeAgentsScoutsRouteImport } from './routes/code/agents/scouts'-import { Route as CodeAgentsApplicationsRouteImport } from './routes/code/agents/applications'import { Route as CodeLoopsLoopIdIndexRouteImport } from './routes/code/loops/$loopId/index'import { Route as CodeInboxRunsIndexRouteImport } from './routes/code/inbox/runs.index'import { Route as CodeInboxReportsIndexRouteImport } from './routes/code/inbox/reports.index'import { Route as CodeInboxPullsIndexRouteImport } from './routes/code/inbox/pulls.index'import { Route as CodeInboxDismissedIndexRouteImport } from './routes/code/inbox/dismissed.index'import { Route as CodeAgentsScoutsIndexRouteImport } from './routes/code/agents/scouts.index'-import { Route as CodeAgentsApplicationsIndexRouteImport } from './routes/code/agents/applications/index'import { Route as WebsiteChannelIdTasksTaskIdRouteImport } from './routes/website/$channelId/tasks/$taskId'import { Route as WebsiteChannelIdDashboardsDashboardIdRouteImport } from './routes/website/$channelId/dashboards/$dashboardId'import { Route as CodeTasksPendingKeyRouteImport } from './routes/code/tasks/pending.$key'@@ -69,18 +67,7 @@ import { Route as CodeInboxDismissedReportIdRouteImport } from './routes/code/inimport { Route as CodeAgentsScoutsScratchpadRouteImport } from './routes/code/agents/scouts.scratchpad'import { Route as CodeAgentsScoutsFindingsRouteImport } from './routes/code/agents/scouts.findings'import { Route as CodeAgentsScoutsSkillNameRouteImport } from './routes/code/agents/scouts.$skillName'-import { Route as CodeAgentsApplicationsApprovalsRouteImport } from './routes/code/agents/applications/approvals'-import { Route as CodeAgentsApplicationsIdOrSlugRouteImport } from './routes/code/agents/applications/$idOrSlug'import { Route as CodeAgentsScoutsSkillNameIndexRouteImport } from './routes/code/agents/scouts.$skillName.index'-import { Route as CodeAgentsApplicationsIdOrSlugIndexRouteImport } from './routes/code/agents/applications/$idOrSlug/index'-import { Route as CodeAgentsApplicationsIdOrSlugUsersRouteImport } from './routes/code/agents/applications/$idOrSlug/users'-import { Route as CodeAgentsApplicationsIdOrSlugObservabilityRouteImport } from './routes/code/agents/applications/$idOrSlug/observability'-import { Route as CodeAgentsApplicationsIdOrSlugMemoryRouteImport } from './routes/code/agents/applications/$idOrSlug/memory'-import { Route as CodeAgentsApplicationsIdOrSlugConfigurationRouteImport } from './routes/code/agents/applications/$idOrSlug/configuration'-import { Route as CodeAgentsApplicationsIdOrSlugChatRouteImport } from './routes/code/agents/applications/$idOrSlug/chat'-import { Route as CodeAgentsApplicationsIdOrSlugApprovalsRouteImport } from './routes/code/agents/applications/$idOrSlug/approvals'-import { Route as CodeAgentsApplicationsIdOrSlugSessionsIndexRouteImport } from './routes/code/agents/applications/$idOrSlug/sessions.index'-import { Route as CodeAgentsApplicationsIdOrSlugSessionsSessionIdRouteImport } from './routes/code/agents/applications/$idOrSlug/sessions.$sessionId'const WebsiteRoute = WebsiteRouteImport.update({id: '/website',@@ -289,11 +276,6 @@ const CodeAgentsScoutsRoute = CodeAgentsScoutsRouteImport.update({path: '/scouts',getParentRoute: () => CodeAgentsRoute,} as any)-const CodeAgentsApplicationsRoute = CodeAgentsApplicationsRouteImport.update({- id: '/applications',- path: '/applications',- getParentRoute: () => CodeAgentsRoute,-} as any)const CodeLoopsLoopIdIndexRoute = CodeLoopsLoopIdIndexRouteImport.update({id: '/',path: '/',@@ -324,12 +306,6 @@ const CodeAgentsScoutsIndexRoute = CodeAgentsScoutsIndexRouteImport.update({path: '/',getParentRoute: () => CodeAgentsScoutsRoute,} as any)-const CodeAgentsApplicationsIndexRoute =- CodeAgentsApplicationsIndexRouteImport.update({- id: '/',- path: '/',- getParentRoute: () => CodeAgentsApplicationsRoute,- } as any)const WebsiteChannelIdTasksTaskIdRoute =WebsiteChannelIdTasksTaskIdRouteImport.update({id: '/$channelId/tasks/$taskId',@@ -392,78 +368,12 @@ const CodeAgentsScoutsSkillNameRoute =path: '/$skillName',getParentRoute: () => CodeAgentsScoutsRoute,} as any)-const CodeAgentsApplicationsApprovalsRoute =- CodeAgentsApplicationsApprovalsRouteImport.update({- id: '/approvals',- path: '/approvals',- getParentRoute: () => CodeAgentsApplicationsRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugRoute =- CodeAgentsApplicationsIdOrSlugRouteImport.update({- id: '/$idOrSlug',- path: '/$idOrSlug',- getParentRoute: () => CodeAgentsApplicationsRoute,- } as any)const CodeAgentsScoutsSkillNameIndexRoute =CodeAgentsScoutsSkillNameIndexRouteImport.update({id: '/',path: '/',getParentRoute: () => CodeAgentsScoutsSkillNameRoute,} as any)-const CodeAgentsApplicationsIdOrSlugIndexRoute =- CodeAgentsApplicationsIdOrSlugIndexRouteImport.update({- id: '/',- path: '/',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugUsersRoute =- CodeAgentsApplicationsIdOrSlugUsersRouteImport.update({- id: '/users',- path: '/users',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugObservabilityRoute =- CodeAgentsApplicationsIdOrSlugObservabilityRouteImport.update({- id: '/observability',- path: '/observability',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugMemoryRoute =- CodeAgentsApplicationsIdOrSlugMemoryRouteImport.update({- id: '/memory',- path: '/memory',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugConfigurationRoute =- CodeAgentsApplicationsIdOrSlugConfigurationRouteImport.update({- id: '/configuration',- path: '/configuration',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugChatRoute =- CodeAgentsApplicationsIdOrSlugChatRouteImport.update({- id: '/chat',- path: '/chat',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugApprovalsRoute =- CodeAgentsApplicationsIdOrSlugApprovalsRouteImport.update({- id: '/approvals',- path: '/approvals',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugSessionsIndexRoute =- CodeAgentsApplicationsIdOrSlugSessionsIndexRouteImport.update({- id: '/sessions/',- path: '/sessions/',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)-const CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute =- CodeAgentsApplicationsIdOrSlugSessionsSessionIdRouteImport.update({- id: '/sessions/$sessionId',- path: '/sessions/$sessionId',- getParentRoute: () => CodeAgentsApplicationsIdOrSlugRoute,- } as any)export interface FileRoutesByFullPath {'/': typeof IndexRoute@@ -487,7 +397,6 @@ export interface FileRoutesByFullPath {'/code/': typeof CodeIndexRoute'/settings/': typeof SettingsIndexRoute'/website/': typeof WebsiteIndexRoute- '/code/agents/applications': typeof CodeAgentsApplicationsRouteWithChildren'/code/agents/scouts': typeof CodeAgentsScoutsRouteWithChildren'/code/inbox/agents': typeof CodeInboxAgentsRoute'/code/inbox/dismissed': typeof CodeInboxDismissedRouteWithChildren@@ -508,8 +417,6 @@ export interface FileRoutesByFullPath {'/code/inbox/': typeof CodeInboxIndexRoute'/code/loops/': typeof CodeLoopsIndexRoute'/website/$channelId/': typeof WebsiteChannelIdIndexRoute- '/code/agents/applications/$idOrSlug': typeof CodeAgentsApplicationsIdOrSlugRouteWithChildren- '/code/agents/applications/approvals': typeof CodeAgentsApplicationsApprovalsRoute'/code/agents/scouts/$skillName': typeof CodeAgentsScoutsSkillNameRouteWithChildren'/code/agents/scouts/findings': typeof CodeAgentsScoutsFindingsRoute'/code/agents/scouts/scratchpad': typeof CodeAgentsScoutsScratchpadRoute@@ -521,23 +428,13 @@ export interface FileRoutesByFullPath {'/code/tasks/pending/$key': typeof CodeTasksPendingKeyRoute'/website/$channelId/dashboards/$dashboardId': typeof WebsiteChannelIdDashboardsDashboardIdRoute'/website/$channelId/tasks/$taskId': typeof WebsiteChannelIdTasksTaskIdRoute- '/code/agents/applications/': typeof CodeAgentsApplicationsIndexRoute'/code/agents/scouts/': typeof CodeAgentsScoutsIndexRoute'/code/inbox/dismissed/': typeof CodeInboxDismissedIndexRoute'/code/inbox/pulls/': typeof CodeInboxPullsIndexRoute'/code/inbox/reports/': typeof CodeInboxReportsIndexRoute'/code/inbox/runs/': typeof CodeInboxRunsIndexRoute'/code/loops/$loopId/': typeof CodeLoopsLoopIdIndexRoute- '/code/agents/applications/$idOrSlug/approvals': typeof CodeAgentsApplicationsIdOrSlugApprovalsRoute- '/code/agents/applications/$idOrSlug/chat': typeof CodeAgentsApplicationsIdOrSlugChatRoute- '/code/agents/applications/$idOrSlug/configuration': typeof CodeAgentsApplicationsIdOrSlugConfigurationRoute- '/code/agents/applications/$idOrSlug/memory': typeof CodeAgentsApplicationsIdOrSlugMemoryRoute- '/code/agents/applications/$idOrSlug/observability': typeof CodeAgentsApplicationsIdOrSlugObservabilityRoute- '/code/agents/applications/$idOrSlug/users': typeof CodeAgentsApplicationsIdOrSlugUsersRoute- '/code/agents/applications/$idOrSlug/': typeof CodeAgentsApplicationsIdOrSlugIndexRoute'/code/agents/scouts/$skillName/': typeof CodeAgentsScoutsSkillNameIndexRoute- '/code/agents/applications/$idOrSlug/sessions/$sessionId': typeof CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute- '/code/agents/applications/$idOrSlug/sessions/': typeof CodeAgentsApplicationsIdOrSlugSessionsIndexRoute}export interface FileRoutesByTo {'/': typeof IndexRoute@@ -572,7 +469,6 @@ export interface FileRoutesByTo {'/code/inbox': typeof CodeInboxIndexRoute'/code/loops': typeof CodeLoopsIndexRoute'/website/$channelId': typeof WebsiteChannelIdIndexRoute- '/code/agents/applications/approvals': typeof CodeAgentsApplicationsApprovalsRoute'/code/agents/scouts/findings': typeof CodeAgentsScoutsFindingsRoute'/code/agents/scouts/scratchpad': typeof CodeAgentsScoutsScratchpadRoute'/code/inbox/dismissed/$reportId': typeof CodeInboxDismissedReportIdRoute@@ -583,23 +479,13 @@ export interface FileRoutesByTo {'/code/tasks/pending/$key': typeof CodeTasksPendingKeyRoute'/website/$channelId/dashboards/$dashboardId': typeof WebsiteChannelIdDashboardsDashboardIdRoute'/website/$channelId/tasks/$taskId': typeof WebsiteChannelIdTasksTaskIdRoute- '/code/agents/applications': typeof CodeAgentsApplicationsIndexRoute'/code/agents/scouts': typeof CodeAgentsScoutsIndexRoute'/code/inbox/dismissed': typeof CodeInboxDismissedIndexRoute'/code/inbox/pulls': typeof CodeInboxPullsIndexRoute'/code/inbox/reports': typeof CodeInboxReportsIndexRoute'/code/inbox/runs': typeof CodeInboxRunsIndexRoute'/code/loops/$loopId': typeof CodeLoopsLoopIdIndexRoute- '/code/agents/applications/$idOrSlug/approvals': typeof CodeAgentsApplicationsIdOrSlugApprovalsRoute- '/code/agents/applications/$idOrSlug/chat': typeof CodeAgentsApplicationsIdOrSlugChatRoute- '/code/agents/applications/$idOrSlug/configuration': typeof CodeAgentsApplicationsIdOrSlugConfigurationRoute- '/code/agents/applications/$idOrSlug/memory': typeof CodeAgentsApplicationsIdOrSlugMemoryRoute- '/code/agents/applications/$idOrSlug/observability': typeof CodeAgentsApplicationsIdOrSlugObservabilityRoute- '/code/agents/applications/$idOrSlug/users': typeof CodeAgentsApplicationsIdOrSlugUsersRoute- '/code/agents/applications/$idOrSlug': typeof CodeAgentsApplicationsIdOrSlugIndexRoute'/code/agents/scouts/$skillName': typeof CodeAgentsScoutsSkillNameIndexRoute- '/code/agents/applications/$idOrSlug/sessions/$sessionId': typeof CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute- '/code/agents/applications/$idOrSlug/sessions': typeof CodeAgentsApplicationsIdOrSlugSessionsIndexRoute}export interface FileRoutesById {__root__: typeof rootRouteImport@@ -624,7 +510,6 @@ export interface FileRoutesById {'/code/': typeof CodeIndexRoute'/settings/': typeof SettingsIndexRoute'/website/': typeof WebsiteIndexRoute- '/code/agents/applications': typeof CodeAgentsApplicationsRouteWithChildren'/code/agents/scouts': typeof CodeAgentsScoutsRouteWithChildren'/code/inbox/agents': typeof CodeInboxAgentsRoute'/code/inbox/dismissed': typeof CodeInboxDismissedRouteWithChildren@@ -645,8 +530,6 @@ export interface FileRoutesById {'/code/inbox/': typeof CodeInboxIndexRoute'/code/loops/': typeof CodeLoopsIndexRoute'/website/$channelId/': typeof WebsiteChannelIdIndexRoute- '/code/agents/applications/$idOrSlug': typeof CodeAgentsApplicationsIdOrSlugRouteWithChildren- '/code/agents/applications/approvals': typeof CodeAgentsApplicationsApprovalsRoute'/code/agents/scouts/$skillName': typeof CodeAgentsScoutsSkillNameRouteWithChildren'/code/agents/scouts/findings': typeof CodeAgentsScoutsFindingsRoute'/code/agents/scouts/scratchpad': typeof CodeAgentsScoutsScratchpadRoute@@ -658,23 +541,13 @@ export interface FileRoutesById {'/code/tasks/pending/$key': typeof CodeTasksPendingKeyRoute'/website/$channelId/dashboards/$dashboardId': typeof WebsiteChannelIdDashboardsDashboardIdRoute'/website/$channelId/tasks/$taskId': typeof WebsiteChannelIdTasksTaskIdRoute- '/code/agents/applications/': typeof CodeAgentsApplicationsIndexRoute'/code/agents/scouts/': typeof CodeAgentsScoutsIndexRoute'/code/inbox/dismissed/': typeof CodeInboxDismissedIndexRoute'/code/inbox/pulls/': typeof CodeInboxPullsIndexRoute'/code/inbox/reports/': typeof CodeInboxReportsIndexRoute'/code/inbox/runs/': typeof CodeInboxRunsIndexRoute'/code/loops/$loopId/': typeof CodeLoopsLoopIdIndexRoute- '/code/agents/applications/$idOrSlug/approvals': typeof CodeAgentsApplicationsIdOrSlugApprovalsRoute- '/code/agents/applications/$idOrSlug/chat': typeof CodeAgentsApplicationsIdOrSlugChatRoute- '/code/agents/applications/$idOrSlug/configuration': typeof CodeAgentsApplicationsIdOrSlugConfigurationRoute- '/code/agents/applications/$idOrSlug/memory': typeof CodeAgentsApplicationsIdOrSlugMemoryRoute- '/code/agents/applications/$idOrSlug/observability': typeof CodeAgentsApplicationsIdOrSlugObservabilityRoute- '/code/agents/applications/$idOrSlug/users': typeof CodeAgentsApplicationsIdOrSlugUsersRoute- '/code/agents/applications/$idOrSlug/': typeof CodeAgentsApplicationsIdOrSlugIndexRoute'/code/agents/scouts/$skillName/': typeof CodeAgentsScoutsSkillNameIndexRoute- '/code/agents/applications/$idOrSlug/sessions/$sessionId': typeof CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute- '/code/agents/applications/$idOrSlug/sessions/': typeof CodeAgentsApplicationsIdOrSlugSessionsIndexRoute}export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPath@@ -700,7 +573,6 @@ export interface FileRouteTypes {| '/code/'| '/settings/'| '/website/'- | '/code/agents/applications'| '/code/agents/scouts'| '/code/inbox/agents'| '/code/inbox/dismissed'@@ -721,8 +593,6 @@ export interface FileRouteTypes {| '/code/inbox/'| '/code/loops/'| '/website/$channelId/'- | '/code/agents/applications/$idOrSlug'- | '/code/agents/applications/approvals'| '/code/agents/scouts/$skillName'| '/code/agents/scouts/findings'| '/code/agents/scouts/scratchpad'@@ -734,23 +604,13 @@ export interface FileRouteTypes {| '/code/tasks/pending/$key'| '/website/$channelId/dashboards/$dashboardId'| '/website/$channelId/tasks/$taskId'- | '/code/agents/applications/'| '/code/agents/scouts/'| '/code/inbox/dismissed/'| '/code/inbox/pulls/'| '/code/inbox/reports/'| '/code/inbox/runs/'| '/code/loops/$loopId/'- | '/code/agents/applications/$idOrSlug/approvals'- | '/code/agents/applications/$idOrSlug/chat'- | '/code/agents/applications/$idOrSlug/configuration'- | '/code/agents/applications/$idOrSlug/memory'- | '/code/agents/applications/$idOrSlug/observability'- | '/code/agents/applications/$idOrSlug/users'- | '/code/agents/applications/$idOrSlug/'| '/code/agents/scouts/$skillName/'- | '/code/agents/applications/$idOrSlug/sessions/$sessionId'- | '/code/agents/applications/$idOrSlug/sessions/'fileRoutesByTo: FileRoutesByToto:| '/'@@ -785,7 +645,6 @@ export interface FileRouteTypes {| '/code/inbox'| '/code/loops'| '/website/$channelId'- | '/code/agents/applications/approvals'| '/code/agents/scouts/findings'| '/code/agents/scouts/scratchpad'| '/code/inbox/dismissed/$reportId'@@ -796,23 +655,13 @@ export interface FileRouteTypes {| '/code/tasks/pending/$key'| '/website/$channelId/dashboards/$dashboardId'| '/website/$channelId/tasks/$taskId'- | '/code/agents/applications'| '/code/agents/scouts'| '/code/inbox/dismissed'| '/code/inbox/pulls'| '/code/inbox/reports'| '/code/inbox/runs'| '/code/loops/$loopId'- | '/code/agents/applications/$idOrSlug/approvals'- | '/code/agents/applications/$idOrSlug/chat'- | '/code/agents/applications/$idOrSlug/configuration'- | '/code/agents/applications/$idOrSlug/memory'- | '/code/agents/applications/$idOrSlug/observability'- | '/code/agents/applications/$idOrSlug/users'- | '/code/agents/applications/$idOrSlug'| '/code/agents/scouts/$skillName'- | '/code/agents/applications/$idOrSlug/sessions/$sessionId'- | '/code/agents/applications/$idOrSlug/sessions'id:| '__root__'| '/'@@ -836,7 +685,6 @@ export interface FileRouteTypes {| '/code/'| '/settings/'| '/website/'- | '/code/agents/applications'| '/code/agents/scouts'| '/code/inbox/agents'| '/code/inbox/dismissed'@@ -857,8 +705,6 @@ export interface FileRouteTypes {| '/code/inbox/'| '/code/loops/'| '/website/$channelId/'- | '/code/agents/applications/$idOrSlug'- | '/code/agents/applications/approvals'| '/code/agents/scouts/$skillName'| '/code/agents/scouts/findings'| '/code/agents/scouts/scratchpad'@@ -870,23 +716,13 @@ export interface FileRouteTypes {| '/code/tasks/pending/$key'| '/website/$channelId/dashboards/$dashboardId'| '/website/$channelId/tasks/$taskId'- | '/code/agents/applications/'| '/code/agents/scouts/'| '/code/inbox/dismissed/'| '/code/inbox/pulls/'| '/code/inbox/reports/'| '/code/inbox/runs/'| '/code/loops/$loopId/'- | '/code/agents/applications/$idOrSlug/approvals'- | '/code/agents/applications/$idOrSlug/chat'- | '/code/agents/applications/$idOrSlug/configuration'- | '/code/agents/applications/$idOrSlug/memory'- | '/code/agents/applications/$idOrSlug/observability'- | '/code/agents/applications/$idOrSlug/users'- | '/code/agents/applications/$idOrSlug/'| '/code/agents/scouts/$skillName/'- | '/code/agents/applications/$idOrSlug/sessions/$sessionId'- | '/code/agents/applications/$idOrSlug/sessions/'fileRoutesById: FileRoutesById}export interface RootRouteChildren {@@ -1200,13 +1036,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CodeAgentsScoutsRouteImportparentRoute: typeof CodeAgentsRoute}- '/code/agents/applications': {- id: '/code/agents/applications'- path: '/applications'- fullPath: '/code/agents/applications'- preLoaderRoute: typeof CodeAgentsApplicationsRouteImport- parentRoute: typeof CodeAgentsRoute- }'/code/loops/$loopId/': {id: '/code/loops/$loopId/'path: '/'@@ -1249,13 +1078,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CodeAgentsScoutsIndexRouteImportparentRoute: typeof CodeAgentsScoutsRoute}- '/code/agents/applications/': {- id: '/code/agents/applications/'- path: '/'- fullPath: '/code/agents/applications/'- preLoaderRoute: typeof CodeAgentsApplicationsIndexRouteImport- parentRoute: typeof CodeAgentsApplicationsRoute- }'/website/$channelId/tasks/$taskId': {id: '/website/$channelId/tasks/$taskId'path: '/$channelId/tasks/$taskId'@@ -1333,20 +1155,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CodeAgentsScoutsSkillNameRouteImportparentRoute: typeof CodeAgentsScoutsRoute}- '/code/agents/applications/approvals': {- id: '/code/agents/applications/approvals'- path: '/approvals'- fullPath: '/code/agents/applications/approvals'- preLoaderRoute: typeof CodeAgentsApplicationsApprovalsRouteImport- parentRoute: typeof CodeAgentsApplicationsRoute- }- '/code/agents/applications/$idOrSlug': {- id: '/code/agents/applications/$idOrSlug'- path: '/$idOrSlug'- fullPath: '/code/agents/applications/$idOrSlug'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugRouteImport- parentRoute: typeof CodeAgentsApplicationsRoute- }'/code/agents/scouts/$skillName/': {id: '/code/agents/scouts/$skillName/'path: '/'@@ -1354,69 +1162,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CodeAgentsScoutsSkillNameIndexRouteImportparentRoute: typeof CodeAgentsScoutsSkillNameRoute}- '/code/agents/applications/$idOrSlug/': {- id: '/code/agents/applications/$idOrSlug/'- path: '/'- fullPath: '/code/agents/applications/$idOrSlug/'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugIndexRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/users': {- id: '/code/agents/applications/$idOrSlug/users'- path: '/users'- fullPath: '/code/agents/applications/$idOrSlug/users'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugUsersRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/observability': {- id: '/code/agents/applications/$idOrSlug/observability'- path: '/observability'- fullPath: '/code/agents/applications/$idOrSlug/observability'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugObservabilityRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/memory': {- id: '/code/agents/applications/$idOrSlug/memory'- path: '/memory'- fullPath: '/code/agents/applications/$idOrSlug/memory'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugMemoryRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/configuration': {- id: '/code/agents/applications/$idOrSlug/configuration'- path: '/configuration'- fullPath: '/code/agents/applications/$idOrSlug/configuration'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugConfigurationRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/chat': {- id: '/code/agents/applications/$idOrSlug/chat'- path: '/chat'- fullPath: '/code/agents/applications/$idOrSlug/chat'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugChatRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/approvals': {- id: '/code/agents/applications/$idOrSlug/approvals'- path: '/approvals'- fullPath: '/code/agents/applications/$idOrSlug/approvals'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugApprovalsRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/sessions/': {- id: '/code/agents/applications/$idOrSlug/sessions/'- path: '/sessions'- fullPath: '/code/agents/applications/$idOrSlug/sessions/'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugSessionsIndexRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }- '/code/agents/applications/$idOrSlug/sessions/$sessionId': {- id: '/code/agents/applications/$idOrSlug/sessions/$sessionId'- path: '/sessions/$sessionId'- fullPath: '/code/agents/applications/$idOrSlug/sessions/$sessionId'- preLoaderRoute: typeof CodeAgentsApplicationsIdOrSlugSessionsSessionIdRouteImport- parentRoute: typeof CodeAgentsApplicationsIdOrSlugRoute- }}}@@ -1464,64 +1209,6 @@ const WebsiteRouteChildren: WebsiteRouteChildren = {const WebsiteRouteWithChildren =WebsiteRoute._addFileChildren(WebsiteRouteChildren)-interface CodeAgentsApplicationsIdOrSlugRouteChildren {- CodeAgentsApplicationsIdOrSlugApprovalsRoute: typeof CodeAgentsApplicationsIdOrSlugApprovalsRoute- CodeAgentsApplicationsIdOrSlugChatRoute: typeof CodeAgentsApplicationsIdOrSlugChatRoute- CodeAgentsApplicationsIdOrSlugConfigurationRoute: typeof CodeAgentsApplicationsIdOrSlugConfigurationRoute- CodeAgentsApplicationsIdOrSlugMemoryRoute: typeof CodeAgentsApplicationsIdOrSlugMemoryRoute- CodeAgentsApplicationsIdOrSlugObservabilityRoute: typeof CodeAgentsApplicationsIdOrSlugObservabilityRoute- CodeAgentsApplicationsIdOrSlugUsersRoute: typeof CodeAgentsApplicationsIdOrSlugUsersRoute- CodeAgentsApplicationsIdOrSlugIndexRoute: typeof CodeAgentsApplicationsIdOrSlugIndexRoute- CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute: typeof CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute- CodeAgentsApplicationsIdOrSlugSessionsIndexRoute: typeof CodeAgentsApplicationsIdOrSlugSessionsIndexRoute-}--const CodeAgentsApplicationsIdOrSlugRouteChildren: CodeAgentsApplicationsIdOrSlugRouteChildren =- {- CodeAgentsApplicationsIdOrSlugApprovalsRoute:- CodeAgentsApplicationsIdOrSlugApprovalsRoute,- CodeAgentsApplicationsIdOrSlugChatRoute:- CodeAgentsApplicationsIdOrSlugChatRoute,- CodeAgentsApplicationsIdOrSlugConfigurationRoute:- CodeAgentsApplicationsIdOrSlugConfigurationRoute,- CodeAgentsApplicationsIdOrSlugMemoryRoute:- CodeAgentsApplicationsIdOrSlugMemoryRoute,- CodeAgentsApplicationsIdOrSlugObservabilityRoute:- CodeAgentsApplicationsIdOrSlugObservabilityRoute,- CodeAgentsApplicationsIdOrSlugUsersRoute:- CodeAgentsApplicationsIdOrSlugUsersRoute,- CodeAgentsApplicationsIdOrSlugIndexRoute:- CodeAgentsApplicationsIdOrSlugIndexRoute,- CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute:- CodeAgentsApplicationsIdOrSlugSessionsSessionIdRoute,- CodeAgentsApplicationsIdOrSlugSessionsIndexRoute:- CodeAgentsApplicationsIdOrSlugSessionsIndexRoute,- }--const CodeAgentsApplicationsIdOrSlugRouteWithChildren =- CodeAgentsApplicationsIdOrSlugRoute._addFileChildren(- CodeAgentsApplicationsIdOrSlugRouteChildren,- )--interface CodeAgentsApplicationsRouteChildren {- CodeAgentsApplicationsIdOrSlugRoute: typeof CodeAgentsApplicationsIdOrSlugRouteWithChildren- CodeAgentsApplicationsApprovalsRoute: typeof CodeAgentsApplicationsApprovalsRoute- CodeAgentsApplicationsIndexRoute: typeof CodeAgentsApplicationsIndexRoute-}--const CodeAgentsApplicationsRouteChildren: CodeAgentsApplicationsRouteChildren =- {- CodeAgentsApplicationsIdOrSlugRoute:- CodeAgentsApplicationsIdOrSlugRouteWithChildren,- CodeAgentsApplicationsApprovalsRoute: CodeAgentsApplicationsApprovalsRoute,- CodeAgentsApplicationsIndexRoute: CodeAgentsApplicationsIndexRoute,- }--const CodeAgentsApplicationsRouteWithChildren =- CodeAgentsApplicationsRoute._addFileChildren(- CodeAgentsApplicationsRouteChildren,- )-interface CodeAgentsScoutsSkillNameRouteChildren {CodeAgentsScoutsSkillNameIndexRoute: typeof CodeAgentsScoutsSkillNameIndexRoute}@@ -1554,13 +1241,11 @@ const CodeAgentsScoutsRouteWithChildren =CodeAgentsScoutsRoute._addFileChildren(CodeAgentsScoutsRouteChildren)interface CodeAgentsRouteChildren {- CodeAgentsApplicationsRoute: typeof CodeAgentsApplicationsRouteWithChildrenCodeAgentsScoutsRoute: typeof CodeAgentsScoutsRouteWithChildrenCodeAgentsIndexRoute: typeof CodeAgentsIndexRoute}const CodeAgentsRouteChildren: CodeAgentsRouteChildren = {- CodeAgentsApplicationsRoute: CodeAgentsApplicationsRouteWithChildren,CodeAgentsScoutsRoute: CodeAgentsScoutsRouteWithChildren,CodeAgentsIndexRoute: CodeAgentsIndexRoute,}diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsxindex 89793f7e1c8d..2de0cbacac51 100644--- a/products/desktop/packages/ui/src/router/routes/__root.tsx+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx@@ -8,8 +8,6 @@ import { Button, ButtonGroup } from "@posthog/quill";import { BILLING_FLAG, PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { isContentlessTask } from "@posthog/shared/domain-types";-import { DeepLinkApprovalModal } from "@posthog/ui/features/agent-applications/components/DeepLinkApprovalModal";-import { useApprovalDeepLink } from "@posthog/ui/features/agent-applications/hooks/useApprovalDeepLink";import { AnnouncementBanner } from "@posthog/ui/features/announcements/AnnouncementBanner";import { AnnouncementsHost } from "@posthog/ui/features/announcements/AnnouncementsHost";import { useServerArchiveSync } from "@posthog/ui/features/archive/useServerArchiveSync";@@ -233,7 +231,6 @@ function RootLayout() {useChannelDeepLink();useLoopDeepLink();useShareLinkInterceptor();- const approvalDeepLink = useApprovalDeepLink();useSetupDiscovery();useNewTaskDeepLink();useServerArchiveSync();@@ -526,12 +523,6 @@ function RootLayout() {mode={feedbackMode}onFinished={handleFeedbackFinished}/>- {approvalDeepLink.pending ? (- <DeepLinkApprovalModal- pending={approvalDeepLink.pending}- onClose={approvalDeepLink.clear}- />- ) : null}<ExistingWorktreeDialog /><HedgehogMode /></Flex>diff --git a/products/desktop/packages/ui/src/router/routes/code/agents.tsx b/products/desktop/packages/ui/src/router/routes/code/agents.tsxindex bf671aa16966..46a68ca205c8 100644--- a/products/desktop/packages/ui/src/router/routes/code/agents.tsx+++ b/products/desktop/packages/ui/src/router/routes/code/agents.tsx@@ -1,4 +1,3 @@-import { AgentBuilderDockLayout } from "@posthog/ui/features/agent-applications/agent-builder/AgentBuilderDockLayout";import {AppPageSkeleton,withRouteSkeleton,@@ -11,9 +10,5 @@ export const Route = createFileRoute("/code/agents")({});function AgentsLayout() {- return (- <AgentBuilderDockLayout>- <Outlet />- </AgentBuilderDockLayout>- );+ return <Outlet />;}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications.tsxdeleted file mode 100644index 0a3df8d4d83b..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { AGENT_PLATFORM_FLAG } from "@posthog/ui/features/agent-applications/featureFlag";-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";-import { Flex, Text } from "@radix-ui/themes";-import { createFileRoute, Outlet } from "@tanstack/react-router";--export const Route = createFileRoute("/code/agents/applications")({- component: ApplicationsGate,-});--/**- * Gates the entire Applications surface (list + per-agent detail) behind the- * `agent-platform` flag. When disabled the tab is also hidden from the agents- * chrome; direct navigation here lands on this placeholder.- */-function ApplicationsGate() {- const enabled = useFeatureFlag(AGENT_PLATFORM_FLAG);- if (!enabled) {- return (- <Flex align="center" justify="center" className="h-full min-h-0 p-6">- <Text className="max-w-sm text-center text-[13px] text-gray-10 leading-snug">- Agent applications aren't available yet.- </Text>- </Flex>- );- }- return <Outlet />;-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug.tsxdeleted file mode 100644index 1a2e3a3ca871..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { createFileRoute, Outlet } from "@tanstack/react-router";--export const Route = createFileRoute("/code/agents/applications/$idOrSlug")({- component: Outlet,-});diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/approvals.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/approvals.tsxdeleted file mode 100644index e8abd23fa2ab..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/approvals.tsx+++ /dev/null@@ -1,36 +0,0 @@-import {- AgentApprovalsPane,- type ApprovalFilter,-} from "@posthog/ui/features/agent-applications/components/AgentApprovalsPane";-import { createFileRoute } from "@tanstack/react-router";-import { useState } from "react";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/approvals",-)({- validateSearch: (search: Record<string, unknown>): { request?: string } => ({- request: typeof search.request === "string" ? search.request : undefined,- }),- component: AgentApprovalsRoute,-});--function AgentApprovalsRoute() {- const { idOrSlug } = Route.useParams();- const { request } = Route.useSearch();- const navigate = Route.useNavigate();- const [filter, setFilter] = useState<ApprovalFilter>("queued");-- return (- <AgentApprovalsPane- idOrSlug={idOrSlug}- selectedId={request ?? null}- onSelect={(id) =>- navigate({- search: (prev) => ({ ...prev, request: id ?? undefined }),- })- }- filter={filter}- onFilterChange={setFilter}- />- );-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/chat.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/chat.tsxdeleted file mode 100644index 567600ec80cd..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/chat.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { AgentChatPane } from "@posthog/ui/features/agent-applications/components/AgentChatPane";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/chat",-)({- // `revision` routes this chat to a non-live revision (the pane mints a- // short-lived ingress JWT scoped to that revision; side effects still run- // for real, only the revision serving the request changes). `session`- // re-attaches a specific session on mount — set by rail clicks that cross- // revisions so the new mount resumes the right conversation instead of- // starting empty.- validateSearch: (- search: Record<string, unknown>,- ): { revision?: string; session?: string } => ({- revision: typeof search.revision === "string" ? search.revision : undefined,- session: typeof search.session === "string" ? search.session : undefined,- }),- component: AgentChatRoute,-});--function AgentChatRoute() {- const { idOrSlug } = Route.useParams();- const { revision, session } = Route.useSearch();- return (- <AgentChatPane- idOrSlug={idOrSlug}- revisionId={revision ?? null}- resumeSessionId={session ?? null}- />- );-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/configuration.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/configuration.tsxdeleted file mode 100644index 876947fd661d..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/configuration.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { AgentConfigurationPane } from "@posthog/ui/features/agent-applications/components/AgentConfigurationPane";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/configuration",-)({- validateSearch: (- search: Record<string, unknown>,- ): { node?: string; revision?: string } => ({- node: typeof search.node === "string" ? search.node : undefined,- revision: typeof search.revision === "string" ? search.revision : undefined,- }),- component: AgentConfigurationRoute,-});--function AgentConfigurationRoute() {- const { idOrSlug } = Route.useParams();- const { node, revision } = Route.useSearch();- const navigate = Route.useNavigate();-- return (- <AgentConfigurationPane- idOrSlug={idOrSlug}- selectedNode={node ?? null}- onSelectNode={(next) =>- navigate({ search: (prev) => ({ ...prev, node: next }) })- }- selectedRevisionId={revision ?? null}- onSelectRevision={(revisionId) =>- navigate({ search: (prev) => ({ ...prev, revision: revisionId }) })- }- onOpenSession={(sessionId) =>- navigate({- to: "/code/agents/applications/$idOrSlug/sessions/$sessionId",- params: { idOrSlug, sessionId },- })- }- />- );-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/index.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/index.tsxdeleted file mode 100644index 1bf456885504..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/index.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { AgentApplicationDetailView } from "@posthog/ui/features/agent-applications/components/AgentApplicationDetailView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/code/agents/applications/$idOrSlug/")({- component: AgentApplicationDetailRoute,-});--function AgentApplicationDetailRoute() {- const { idOrSlug } = Route.useParams();- return <AgentApplicationDetailView idOrSlug={idOrSlug} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/memory.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/memory.tsxdeleted file mode 100644index 532e642ac89a..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/memory.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { AgentMemoryPane } from "@posthog/ui/features/agent-applications/components/AgentMemoryPane";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/memory",-)({- component: AgentMemoryRoute,-});--function AgentMemoryRoute() {- const { idOrSlug } = Route.useParams();- return <AgentMemoryPane idOrSlug={idOrSlug} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/observability.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/observability.tsxdeleted file mode 100644index 366810ad559d..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/observability.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { AgentObservabilityPane } from "@posthog/ui/features/agent-applications/components/AgentObservabilityPane";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/observability",-)({- component: AgentObservabilityRoute,-});--function AgentObservabilityRoute() {- const { idOrSlug } = Route.useParams();- return <AgentObservabilityPane idOrSlug={idOrSlug} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/sessions.$sessionId.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/sessions.$sessionId.tsxdeleted file mode 100644index b4fbd0a87247..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/sessions.$sessionId.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { AgentSessionTranscriptView } from "@posthog/ui/features/agent-applications/components/AgentSessionTranscriptView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/sessions/$sessionId",-)({- component: AgentSessionRoute,-});--function AgentSessionRoute() {- const { idOrSlug, sessionId } = Route.useParams();- return (- <AgentSessionTranscriptView idOrSlug={idOrSlug} sessionId={sessionId} />- );-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/sessions.index.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/sessions.index.tsxdeleted file mode 100644index 21fd1618a952..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/sessions.index.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { AgentSessionsPane } from "@posthog/ui/features/agent-applications/components/AgentSessionsPane";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/sessions/",-)({- component: AgentSessionsRoute,-});--function AgentSessionsRoute() {- const { idOrSlug } = Route.useParams();- return <AgentSessionsPane idOrSlug={idOrSlug} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/users.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/users.tsxdeleted file mode 100644index 9b7922921cd3..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/$idOrSlug/users.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { AgentUsersPane } from "@posthog/ui/features/agent-applications/components/AgentUsersPane";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute(- "/code/agents/applications/$idOrSlug/users",-)({- component: AgentUsersRoute,-});--function AgentUsersRoute() {- const { idOrSlug } = Route.useParams();- return <AgentUsersPane idOrSlug={idOrSlug} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/approvals.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/approvals.tsxdeleted file mode 100644index 1618c9c72fe1..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/approvals.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { AgentFleetApprovalsPane } from "@posthog/ui/features/agent-applications/components/AgentFleetApprovalsPane";-import type { ApprovalFilter } from "@posthog/ui/features/agent-applications/components/agentApprovalsFilters";-import { createFileRoute } from "@tanstack/react-router";-import { useState } from "react";--export const Route = createFileRoute("/code/agents/applications/approvals")({- validateSearch: (search: Record<string, unknown>): { request?: string } => ({- request: typeof search.request === "string" ? search.request : undefined,- }),- component: AgentFleetApprovalsRoute,-});--function AgentFleetApprovalsRoute() {- const { request } = Route.useSearch();- const navigate = Route.useNavigate();- const [filter, setFilter] = useState<ApprovalFilter>("queued");-- return (- <AgentFleetApprovalsPane- selectedId={request ?? null}- onSelect={(id) =>- navigate({- search: (prev) => ({ ...prev, request: id ?? undefined }),- })- }- filter={filter}- onFilterChange={setFilter}- />- );-}diff --git a/products/desktop/packages/ui/src/router/routes/code/agents/applications/index.tsx b/products/desktop/packages/ui/src/router/routes/code/agents/applications/index.tsxdeleted file mode 100644index 01ee652e953c..000000000000--- a/products/desktop/packages/ui/src/router/routes/code/agents/applications/index.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { AgentApplicationsListView } from "@posthog/ui/features/agent-applications/components/AgentApplicationsListView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/code/agents/applications/")({- component: AgentApplicationsListView,-});diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.tsindex 2927e3fba1b8..b628bd20ff56 100644--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts@@ -122,7 +122,7 @@ export function initializePostHog(sessionId?: string) {isInitialized = true;// Dev-only: expose the posthog instance so flags can be toggled from the- // renderer console, e.g. `posthog.featureFlags.override({ "agent-platform": true })`+ // renderer console, e.g. `posthog.featureFlags.override({ "mcp-gateway": true })`// (and `posthog.featureFlags.override(false)` to clear). The module build// doesn't attach to window otherwise.if (import.meta.env.DEV) {diff --git a/products/desktop/scripts/use-local-posthog.mjs b/products/desktop/scripts/use-local-posthog.mjsindex c2640d1339c6..18a324c060f0 100644--- a/products/desktop/scripts/use-local-posthog.mjs+++ b/products/desktop/scripts/use-local-posthog.mjs@@ -3,8 +3,8 @@* Point the desktop app's analytics + feature-flag client at your LOCAL PostHog* (localhost:8010) for dev. Code reads feature flags through posthog-js, which* is configured by the `VITE_POSTHOG_*` vars in `.env` — by default these point- * at PostHog's internal analytics instance, so flags you sync locally (e.g.- * `manage.py sync_feature_flags` → `agent-platform`) never resolve in dev. This+ * at PostHog's internal analytics instance, so flags you sync locally never+ * resolve in dev. This* rewrites those vars to your local instance so synced flags take effect.** Note: this is the analytics/flags client only — separate from the data API