: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(devex): use the generated api clients in signals, mcp_store and conversations (#104362)
Julian Bez606bda3b4252
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 46e58a369fb9..37dea37b2191 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -232,18 +232,13 @@ import type {ColumnConfigurationApi,PaginatedColumnConfigurationListApi,} from 'products/product_analytics/frontend/generated/api.schemas'-import type { SignalUserAutonomyConfigCreateApi } from 'products/signals/frontend/generated/api.schemas'import {SignalReport,SignalReportArtefact,SignalReportArtefactResponse,SignalReportStateRequest,- SignalScoutEmission,- SignalScoutEmissionReportLink,- SignalScoutRunSummary,SignalSourceConfig,SignalTeamConfig,- SignalUserAutonomyConfig,} from 'products/signals/frontend/inbox/types'import type {TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,@@ -746,19 +741,6 @@ export class ApiRequest {return this.links(teamId).addPathComponent(id)}- // # MCP Store- public mcpServers(teamId?: TeamType['id']): ApiRequest {- return this.teamProjectDetail(teamId).addPathComponent('mcp_servers')- }-- public mcpServerInstallations(teamId?: TeamType['id']): ApiRequest {- return this.teamProjectDetail(teamId).addPathComponent('mcp_server_installations')- }-- public mcpServerInstallation(id: string, teamId?: TeamType['id']): ApiRequest {- return this.mcpServerInstallations(teamId).addPathComponent(id)- }-// # Actionspublic actions(teamId?: TeamType['id']): ApiRequest {return this.projectsDetail(teamId).addPathComponent('actions')@@ -1245,11 +1227,6 @@ export class ApiRequest {return this.signalReports(teamId).addPathComponent(id)}- // Per-user signal autonomy config (singleton keyed by user). Not project-scoped.- public signalUserAutonomy(userId: string | '@me' = '@me'): ApiRequest {- return this.addPathComponent('users').addPathComponent(userId).addPathComponent('signal_autonomy')- }-// # Signal Source Configspublic signalSourceConfigs(teamId?: TeamType['id']): ApiRequest {return this.projectsDetail(teamId).addPathComponent('signals').addPathComponent('source_configs')@@ -1264,23 +1241,6 @@ export class ApiRequest {return this.projectsDetail(teamId).addPathComponent('signals').addPathComponent('config')}- // # Signal Report Artefacts (suggested_reviewers is the only writable type)- public signalReportArtefact(reportId: SignalReport['id'], artefactId: string, teamId?: TeamType['id']): ApiRequest {- return this.signalReport(reportId, teamId).addPathComponent('artefacts').addPathComponent(artefactId)- }-- // # Signal Scouts- public signalScoutRuns(teamId?: TeamType['id']): ApiRequest {- return this.projectsDetail(teamId)- .addPathComponent('signals')- .addPathComponent('scout')- .addPathComponent('runs')- }-- public signalScoutRun(id: string, teamId?: TeamType['id']): ApiRequest {- return this.signalScoutRuns(teamId).addPathComponent(id)- }-// # Taskspublic tasks(teamId?: TeamType['id']): ApiRequest {return this.projectsDetail(teamId).addPathComponent('tasks')@@ -4102,73 +4062,6 @@ const api = {},},- mcpServers: {- async list(): Promise<CountedPaginatedResponse<Record<string, any>>> {- return await new ApiRequest().mcpServers().get()- },- },-- mcpServerInstallations: {- async list(): Promise<CountedPaginatedResponse<Record<string, any>>> {- return await new ApiRequest().mcpServerInstallations().get()- },- async update(id: string, data: Record<string, any>): Promise<Record<string, any>> {- return await new ApiRequest().mcpServerInstallation(id).update({ data })- },- async delete(id: string): Promise<void> {- await new ApiRequest().mcpServerInstallation(id).delete()- },- async share(id: string): Promise<Record<string, any>> {- return await new ApiRequest().mcpServerInstallation(id).withAction('share').create({ data: {} })- },- async unshare(id: string): Promise<Record<string, any>> {- return await new ApiRequest().mcpServerInstallation(id).withAction('unshare').create({ data: {} })- },- async installCustom(data: {- name: string- url: string- auth_type: string- api_key?: string- description?: string- client_id?: string- client_secret?: string- scope?: 'personal' | 'shared'- }): Promise<Record<string, any>> {- return await new ApiRequest().mcpServerInstallations().withAction('install_custom').create({ data })- },- async installTemplate(data: {- template_id: string- api_key?: string- scope?: 'personal' | 'shared'- }): Promise<Record<string, any>> {- return await new ApiRequest().mcpServerInstallations().withAction('install_template').create({ data })- },- async listTools(- id: string,- params?: { include_removed?: boolean }- ): Promise<{ results: Record<string, any>[] }> {- return await new ApiRequest()- .mcpServerInstallation(id)- .withAction('tools')- .withQueryString(params?.include_removed ? { include_removed: '1' } : undefined)- .get()- },- async updateToolApproval(- id: string,- toolName: string,- approvalState: 'approved' | 'needs_approval' | 'do_not_use'- ): Promise<Record<string, any>> {- return await new ApiRequest()- .mcpServerInstallation(id)- .withAction('tools')- .withAction(encodeURIComponent(toolName))- .update({ data: { approval_state: approvalState } })- },- async refreshTools(id: string): Promise<{ results: Record<string, any>[] }> {- return await new ApiRequest().mcpServerInstallation(id).withAction('tools/refresh').create({ data: {} })- },- },-annotations: {async get(annotationId: RawAnnotationType['id']): Promise<RawAnnotationType> {return await new ApiRequest().annotation(annotationId).get()@@ -5197,72 +5090,6 @@ const api = {},},- // Scout runs still use the legacy client. Scout configs use the generated Signals client.- signalScout: {- runs: {- // Newest-first raw array (not paginated), capped at 100 server-side.- async list(params?: {- limit?: number- text?: string- emitted?: boolean- date_from?: string- date_to?: string- }): Promise<SignalScoutRunSummary[]> {- return await new ApiRequest().signalScoutRuns().withQueryString(params).get()- },- async get(runId: string): Promise<SignalScoutRunSummary> {- return await new ApiRequest().signalScoutRun(runId).get()- },- async emissions(runId: string): Promise<SignalScoutEmission[]> {- return await new ApiRequest().signalScoutRun(runId).withAction('emissions').get()- },- // Per-finding reverse lookup: which inbox report each emitted finding grouped into.- // `report` is null when a finding hasn't grouped, was deduped, or its signal was deleted.- async emissionReports(runId: string): Promise<SignalScoutEmissionReportLink[]> {- return await new ApiRequest().signalScoutRun(runId).withAction('emissions/reports').get()- },- // Batched form of `emissions`: every run's findings in one request, flat newest-first- // (each row carries its `run_id`). POST since the run-id set can be large.- async emissionsBatch(runIds: string[]): Promise<SignalScoutEmission[]> {- return await new ApiRequest()- .signalScoutRuns()- .withAction('emissions/batch')- .create({ data: { run_ids: runIds } })- },- // Batched form of `emissionReports`: resolves every run's findings to their inbox report- // in a single ClickHouse round-trip, instead of one query per run.- async emissionReportsBatch(runIds: string[]): Promise<SignalScoutEmissionReportLink[]> {- return await new ApiRequest()- .signalScoutRuns()- .withAction('emissions/reports/batch')- .create({ data: { run_ids: runIds } })- },- },- },-- signalUserAutonomy: {- async get(userId: string | '@me' = '@me'): Promise<SignalUserAutonomyConfig | null> {- try {- return await new ApiRequest().signalUserAutonomy(userId).get()- } catch (error: any) {- // 404 = no config yet (user hasn't opted in). Treat as null.- if (error?.status === 404) {- return null- }- throw error- }- },- async update(- data: SignalUserAutonomyConfigCreateApi,- userId: string | '@me' = '@me'- ): Promise<SignalUserAutonomyConfig> {- return await new ApiRequest().signalUserAutonomy(userId).create({ data })- },- async remove(userId: string | '@me' = '@me'): Promise<void> {- await new ApiRequest().signalUserAutonomy(userId).delete()- },- },-signalSourceConfigs: {async list(): Promise<PaginatedResponse<SignalSourceConfig>> {return await new ApiRequest().signalSourceConfigs().get()@@ -7032,57 +6859,9 @@ const api = {return await new ApiRequest().conversationsTicket(ticketId).get()},- async create(data: {- distinct_id: string- anonymous_traits?: Record<string, any>- channel_source?: string- }): Promise<any> {- return await new ApiRequest().conversationsTickets().create({ data })- },-- async update(- ticketId: string,- data: Partial<{- status: string- escalation_reason: string- assignee: { type: 'user' | 'role'; id: string | number } | null- }>- ): Promise<any> {- return await new ApiRequest().conversationsTicket(ticketId).update({ data })- },-- async delete(ticketId: string): Promise<void> {- return await new ApiRequest().conversationsTicket(ticketId).delete()- },-async unreadCount(): Promise<{ count: number }> {return await new ApiRequest().conversationsTickets().withAction('unread_count').get()},-- async compose(data: {- message: string- recipient_email: string- email_config_id: string- recipient_distinct_id?: string- email_subject?: string- rich_content?: Record<string, unknown> | null- }): Promise<{ id: string; ticket_number: number }> {- return await new ApiRequest().conversationsTickets().withAction('compose').create({ data })- },-- async bulkUpdateStatus(ids: string[], ticketStatus: string): Promise<{ updated: number; ids: string[] }> {- return await new ApiRequest()- .conversationsTickets()- .withAction('bulk_update_status')- .create({ data: { ids, status: ticketStatus } })- },-- async submitAiFeedback(- ticketId: string,- data: { message_id: string; rating: 'good' | 'bad'; feedback_text?: string }- ): Promise<void> {- await new ApiRequest().conversationsTicket(ticketId).withAction('ai_feedback').create({ data })- },},/** Fetch data from specified URL. The result already is JSON-parsed. */diff --git a/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts b/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.tsindex 35a5b465a05b..c0c4c9a0424b 100644--- a/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts+++ b/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts@@ -4,9 +4,10 @@ import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { urls } from 'scenes/urls'+import { conversationsTicketsComposeCreate } from '../../generated/api'import type { EmailConfigStatus } from '../../scenes/settings/supportSettingsLogic'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -216,7 +217,7 @@ export const composeTicketLogic = kea<composeTicketLogicType>([}try {- const result = await api.conversationsTickets.compose({+ const result = await conversationsTicketsComposeCreate(String(ApiConfig.getCurrentProjectId()), {message,recipient_email: recipientEmail,email_config_id: emailConfigId,diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex c23e4bc1f16d..636d1e597416 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -32,6 +32,7 @@ jest.mock('~/lib/api', () => {const actual = jest.requireActual('~/lib/api')return {__esModule: true,+ ApiConfig: actual.ApiConfig,default: {...actual.default,createResponse: jest.fn(),@@ -45,10 +46,7 @@ jest.mock('~/lib/api', () => {},conversationsTickets: {...actual.default?.conversationsTickets,- submitAiFeedback: jest.fn().mockResolvedValue(undefined),- submitAiHumanOutcome: jest.fn().mockResolvedValue(undefined),get: jest.fn(),- update: jest.fn(),list: jest.fn().mockResolvedValue({ results: [] }),},tags: {@@ -60,6 +58,7 @@ jest.mock('~/lib/api', () => {})jest.mock('products/conversations/frontend/generated/api', () => ({+ conversationsTicketsAiFeedbackCreate: jest.fn().mockResolvedValue(undefined),conversationsTicketsAiHumanOutcomeCreate: jest.fn().mockResolvedValue(undefined),conversationsTicketsMessagesFullEmailRetrieve: jest.fn().mockResolvedValue({ content: 'Full email body' }),conversationsTicketsNotesPartialUpdate: jest.fn().mockResolvedValue(undefined),@@ -70,13 +69,14 @@ jest.mock('products/conversations/frontend/generated/api', () => ({import api from '~/lib/api'import {+ conversationsTicketsAiFeedbackCreate,conversationsTicketsAiHumanOutcomeCreate,conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesPartialUpdate,conversationsTicketsPartialUpdate,} from 'products/conversations/frontend/generated/api'-const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mock+const submitAiFeedbackMock = conversationsTicketsAiFeedbackCreate as jest.Mockconst submitAiHumanOutcomeMock = conversationsTicketsAiHumanOutcomeCreate as jest.Mockconst fullEmailRetrieveMock = conversationsTicketsMessagesFullEmailRetrieve as jest.Mock@@ -164,7 +164,7 @@ describe('supportTicketSceneLogic ai reply feedback', () => {})expect(submitAiFeedbackMock).toHaveBeenCalledTimes(1)- expect(submitAiFeedbackMock).toHaveBeenCalledWith('ticket-1', {+ expect(submitAiFeedbackMock).toHaveBeenCalledWith('997', 'ticket-1', {message_id: 'msg-ai-1',rating: 'good',})@@ -180,7 +180,7 @@ describe('supportTicketSceneLogic ai reply feedback', () => {})expect(submitAiFeedbackMock).toHaveBeenCalledTimes(1)- expect(submitAiFeedbackMock).toHaveBeenCalledWith('ticket-1', {+ expect(submitAiFeedbackMock).toHaveBeenCalledWith('997', 'ticket-1', {message_id: 'msg-ai-1',rating: 'bad',})@@ -193,7 +193,7 @@ describe('supportTicketSceneLogic ai reply feedback', () => {await new Promise((r) => setTimeout(r, 10))expect(submitAiFeedbackMock).toHaveBeenCalledTimes(1)- expect(submitAiFeedbackMock).toHaveBeenCalledWith('ticket-1', {+ expect(submitAiFeedbackMock).toHaveBeenCalledWith('997', 'ticket-1', {message_id: 'msg-ai-1',rating: 'bad',feedback_text: 'Wrong answer',diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex e7d28e297a1a..13d1a9ef5760 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -36,7 +36,7 @@ import { userLogic } from 'scenes/userLogic'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'-import api from '~/lib/api'+import api, { ApiConfig } from '~/lib/api'import { PERSON_DISPLAY_NAME_COLUMN_NAME } from '~/lib/constants'import { CLOUD_HOSTNAMES } from '~/lib/constants'import { tagsModel } from '~/models/tagsModel'@@ -46,6 +46,7 @@ import type { Breadcrumb, CommentType, PersonType, UserType } from '~/types'import { ActivityScope, PropertyFilterType, PropertyOperator, Region } from '~/types'import {+ conversationsTicketsAiFeedbackCreate,conversationsTicketsAiHumanOutcomeCreate,conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesDestroy,@@ -1600,7 +1601,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([if (rating !== 'bad') {return}- await api.conversationsTickets.submitAiFeedback(ticket.id, {+ await conversationsTicketsAiFeedbackCreate(String(ApiConfig.getCurrentProjectId()), ticket.id, {message_id: messageId,rating,feedback_text: feedbackText,@@ -1610,7 +1611,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([if (values.feedbackByMessageId[messageId]) {return}- await api.conversationsTickets.submitAiFeedback(ticket.id, {+ await conversationsTicketsAiFeedbackCreate(String(ApiConfig.getCurrentProjectId()), ticket.id, {message_id: messageId,rating,})diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.tsindex cc5004611b6d..0c6e70f28bc1 100644--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts@@ -15,7 +15,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'import { objectsEqual } from 'lib/utils/objects'@@ -24,7 +24,7 @@ import { teamLogic } from 'scenes/teamLogic'import { AccessControlLevel, AccessControlResourceType, Breadcrumb, TeamType } from '~/types'-import { conversationsViewsRetrieve } from '../../generated/api'+import { conversationsTicketsBulkUpdateStatusCreate, conversationsViewsRetrieve } from '../../generated/api'import type { AiTriageResultEnumApi } from '../../generated/api.schemas'import { normalizeAssigneeFilter } from '../../types'import type {@@ -905,7 +905,15 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([bulkUpdateStatus: async ({ ids, status }) => {actions.setBulkUpdating(true)try {- const result = await api.conversationsTickets.bulkUpdateStatus(ids, status)+ // Match the scope api.conversationsTickets reads use below, so a bulk update actually+ // touches the tickets the user selected instead of a same-named row in another environment.+ const result = await conversationsTicketsBulkUpdateStatusCreate(+ String(ApiConfig.getCurrentProjectId()),+ {+ ids,+ status,+ }+ )lemonToast.success(`Updated ${result.updated} ticket${result.updated === 1 ? '' : 's'}`)actions.clearSelectedTickets()actions.loadTickets()diff --git a/products/mcp_store/frontend/mcpStoreLogic.test.ts b/products/mcp_store/frontend/mcpStoreLogic.test.tsindex e31dd942ec98..5aa63681d422 100644--- a/products/mcp_store/frontend/mcpStoreLogic.test.ts+++ b/products/mcp_store/frontend/mcpStoreLogic.test.ts@@ -1,12 +1,13 @@-import api from 'lib/api'-import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'+import * as generated from './generated/api'import type { MCPServerInstallationApi, MCPServerInstallationToolApi } from './generated/api.schemas'import { mcpStoreLogic } from './mcpStoreLogic'-jest.mock('lib/api')+jest.mock('./generated/api')++const mocked = jest.mocked(generated)function installation(id: string, url?: string): MCPServerInstallationApi {return {@@ -52,8 +53,8 @@ describe('mcpStoreLogic', () => {beforeEach(async () => {initKeaTests()jest.resetAllMocks()- jest.spyOn(api.mcpServers, 'list').mockResolvedValue({ count: 0, results: [] })- jest.spyOn(api.mcpServerInstallations, 'list').mockResolvedValue({ count: 0, results: [] })+ mocked.mcpServersList.mockResolvedValue({ count: 0, results: [] })+ mocked.mcpServerInstallationsList.mockResolvedValue({ count: 0, results: [] })logic = mcpStoreLogic()logic.mount()@@ -74,10 +75,10 @@ describe('mcpStoreLogic', () => {]logic.actions.loadInstallationsSuccess(installations)logic.actions.loadInstallationToolsSuccess(Object.fromEntries(installations.map(({ id }) => [id, [tool(id)]])))- jest.spyOn(api.mcpServerInstallations, 'updateToolApproval').mockResolvedValue({})- const listTools = jest- .spyOn(api.mcpServerInstallations, 'listTools')- .mockImplementation(async (installationId) => ({ results: [tool(installationId)] }))+ mocked.mcpServerInstallationsToolsPartialUpdate.mockResolvedValue(tool('source'))+ const listTools = mocked.mcpServerInstallationsToolsRetrieve.mockImplementation(+ async (_projectId, installationId) => ({ count: 1, results: [tool(installationId)] })+ )await expectLogic(logic, () => {logic.actions.setToolApprovalState({@@ -87,6 +88,9 @@ describe('mcpStoreLogic', () => {})}).toFinishAllListeners()- expect(listTools.mock.calls.map(([installationId]) => installationId).sort()).toEqual(['same-server', 'source'])+ expect(listTools.mock.calls.map(([, installationId]) => installationId).sort()).toEqual([+ 'same-server',+ 'source',+ ])})})diff --git a/products/mcp_store/frontend/mcpStoreLogic.ts b/products/mcp_store/frontend/mcpStoreLogic.tsindex 06bb8cecb999..12d03c22108a 100644--- a/products/mcp_store/frontend/mcpStoreLogic.ts+++ b/products/mcp_store/frontend/mcpStoreLogic.ts@@ -6,13 +6,28 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import { ApiConfig } from 'lib/api'import { isPolicyStateAllowedByCeiling } from './gateway/gatewayPolicyUtils'+import {+ mcpServerInstallationsDestroy,+ mcpServerInstallationsInstallCustomCreate,+ mcpServerInstallationsInstallTemplateCreate,+ mcpServerInstallationsList,+ mcpServerInstallationsPartialUpdate,+ mcpServerInstallationsShareCreate,+ mcpServerInstallationsToolsPartialUpdate,+ mcpServerInstallationsToolsRefreshCreate,+ mcpServerInstallationsToolsRetrieve,+ mcpServerInstallationsUnshareCreate,+ mcpServersList,+} from './generated/api'import type {+ InstallCustomApi,MCPServerInstallationApi,MCPServerInstallationToolApi,MCPServerTemplateApi,+ PatchedMCPServerInstallationUpdateApi,} from './generated/api.schemas'export type ToolApprovalState = 'approved' | 'needs_approval' | 'do_not_use'@@ -25,7 +40,7 @@ export interface CustomServerFormValues {name: stringurl: stringdescription: string- auth_type: string+ auth_type: InstallCustomApi['auth_type']api_key: stringclient_id: stringclient_secret: string@@ -47,6 +62,21 @@ const CUSTOM_SERVER_FORM_DEFAULTS: CustomServerFormValues = {template_id: '',}+// The route accepts a team id too (see ApiConfig.teamProjectDetail), and MCPServerInstallationViewSet+// filters on the exact team id, so this must resolve the active environment, not its parent project.+const projectId = (): string => String(ApiConfig.getCurrentTeamId())++function setToolApproval(+ installationId: string,+ toolName: string,+ approvalState: ToolApprovalState+): Promise<MCPServerInstallationToolApi> {+ // The generated URL builder interpolates the tool name raw, so encode it here.+ return mcpServerInstallationsToolsPartialUpdate(projectId(), installationId, encodeURIComponent(toolName), {+ approval_state: approvalState,+ })+}+function loadedInstallationIdsForServer(installations: MCPServerInstallationApi[],installationTools: Record<string, MCPServerInstallationToolApi[]>,@@ -331,9 +361,9 @@ export interface mcpStoreLogicActions {id: string}}- updateInstallation: ({ id, data }: { data: Record<string, any>; id: string }) => {+ updateInstallation: ({ id, data }: { data: PatchedMCPServerInstallationUpdateApi; id: string }) => {id: string- data: Record<string, any>+ data: PatchedMCPServerInstallationUpdateApi}updateInstallationFailure: (error: string,@@ -346,13 +376,13 @@ export interface mcpStoreLogicActions {installations: MCPServerInstallationApi[],payload?: {id: string- data: Record<string, any>+ data: PatchedMCPServerInstallationUpdateApi}) => {installations: MCPServerInstallationApi[]payload?: {id: string- data: Record<string, any>+ data: PatchedMCPServerInstallationUpdateApi}}}@@ -529,12 +559,12 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([}) => {try {const result = template_id- ? await api.mcpServerInstallations.installTemplate({+ ? await mcpServerInstallationsInstallTemplateCreate(projectId(), {template_id,api_key: api_key || undefined,scope,})- : await api.mcpServerInstallations.installCustom({+ : await mcpServerInstallationsInstallCustomCreate(projectId(), {name,url,auth_type,@@ -546,7 +576,7 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([client_secret: client_secret || undefined,scope,})- if (result?.redirect_url) {+ if ('redirect_url' in result) {window.location.href = result.redirect_urlreturn}@@ -569,8 +599,8 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([[] as MCPServerTemplateApi[],{loadServers: async () => {- const response = await api.mcpServers.list()- return response.results as MCPServerTemplateApi[]+ const response = await mcpServersList(projectId())+ return response.results},},],@@ -578,18 +608,24 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([[] as MCPServerInstallationApi[],{loadInstallations: async () => {- const response = await api.mcpServerInstallations.list()- return response.results as MCPServerInstallationApi[]+ const response = await mcpServerInstallationsList(projectId())+ return response.results},- updateInstallation: async ({ id, data }: { id: string; data: Record<string, any> }) => {- const updated = (await api.mcpServerInstallations.update(id, data)) as MCPServerInstallationApi+ updateInstallation: async ({+ id,+ data,+ }: {+ id: string+ data: PatchedMCPServerInstallationUpdateApi+ }) => {+ const updated = await mcpServerInstallationsPartialUpdate(projectId(), id, data)lemonToast.success('Server updated')return values.installations.map((i: MCPServerInstallationApi) =>i.id === updated.id ? updated : i)},uninstallServer: async (installationId: string) => {- await api.mcpServerInstallations.delete(installationId)+ await mcpServerInstallationsDestroy(projectId(), installationId)lemonToast.success('Server uninstalled')return values.installations.filter((i: MCPServerInstallationApi) => i.id !== installationId)},@@ -598,25 +634,25 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([// must drop out of the requester's list entirely.shareInstallation: async ({ id }: { id: string }) => {try {- await api.mcpServerInstallations.share(id)+ await mcpServerInstallationsShareCreate(projectId(), id)lemonToast.success('Server shared with the project')} catch (e: any) {lemonToast.error(e.detail || 'Failed to share server')throw e}- const response = await api.mcpServerInstallations.list()- return response.results as MCPServerInstallationApi[]+ const response = await mcpServerInstallationsList(projectId())+ return response.results},unshareInstallation: async ({ id }: { id: string }) => {try {- await api.mcpServerInstallations.unshare(id)+ await mcpServerInstallationsUnshareCreate(projectId(), id)lemonToast.success('Server is now personal')} catch (e: any) {lemonToast.error(e.detail || 'Failed to unshare server')throw e}- const response = await api.mcpServerInstallations.list()- return response.results as MCPServerInstallationApi[]+ const response = await mcpServerInstallationsList(projectId())+ return response.results},},],@@ -624,19 +660,19 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([{} as Record<string, MCPServerInstallationToolApi[]>,{loadInstallationTools: async ({ installationId }) => {- const response = await api.mcpServerInstallations.listTools(installationId)+ const response = await mcpServerInstallationsToolsRetrieve(projectId(), installationId)return {...values.installationTools,- [installationId]: response.results as MCPServerInstallationToolApi[],+ [installationId]: response.results,}},refreshInstallationTools: async ({ installationId }) => {try {- const response = await api.mcpServerInstallations.refreshTools(installationId)+ const response = await mcpServerInstallationsToolsRefreshCreate(projectId(), installationId)lemonToast.success('Tools refreshed')return {...values.installationTools,- [installationId]: response.results as MCPServerInstallationToolApi[],+ [installationId]: response.results,}} catch (e: any) {lemonToast.error(e.detail || 'Failed to refresh tools')@@ -724,7 +760,9 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([listeners(({ actions, values }) => ({toggleServerEnabled: async ({ id, enabled }) => {try {- await api.mcpServerInstallations.update(id, { is_enabled: enabled })+ await mcpServerInstallationsPartialUpdate(projectId(), id, {+ is_enabled: enabled,+ })} catch (e: any) {lemonToast.error(e.detail || 'Failed to update server')actions.setInstallations(@@ -736,8 +774,10 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([},installTemplate: async ({ templateId }) => {try {- const result = await api.mcpServerInstallations.installTemplate({ template_id: templateId })- if (result?.redirect_url) {+ const result = await mcpServerInstallationsInstallTemplateCreate(projectId(), {+ template_id: templateId,+ })+ if ('redirect_url' in result) {window.location.href = result.redirect_urlreturn}@@ -750,7 +790,7 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([setToolApprovalState: async ({ installationId, toolName, approvalState }) => {// Optimistic update already applied in the reducer. Reload from server on failure.try {- await api.mcpServerInstallations.updateToolApproval(installationId, toolName, approvalState)+ await setToolApproval(installationId, toolName, approvalState)const installation = values.installations.find((candidate) => candidate.id === installationId)if (installation?.scope === 'shared') {const loadedInstallationIds = loadedInstallationIdsForServer(@@ -775,11 +815,7 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([teamScope || (!tool.locked && isPolicyStateAllowedByCeiling(approvalState, tool.team_state ?? null)))try {- await Promise.all(- tools.map((tool) =>- api.mcpServerInstallations.updateToolApproval(installationId, tool.tool_name, approvalState)- )- )+ await Promise.all(tools.map((tool) => setToolApproval(installationId, tool.tool_name, approvalState)))lemonToast.success(`Updated ${tools.length} tools`)const loadedInstallationIds = teamScope? loadedInstallationIdsForServer(values.installations, values.installationTools, installationId)diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsxindex 54e11f15d157..76bbae841f36 100644--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx@@ -15,7 +15,8 @@ import { IntegrationType } from '~/types'import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'import { userAutonomyLogic } from '../../logics/userAutonomyLogic'-import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority, SignalUserAutonomyConfig } from '../../types'+import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority } from '../../types'+import type { SignalUserAutonomyConfigDraft } from '../../types'import { ConfigCardHeader } from './ConfigCardHeader'const NOTIFY_ALL_VALUE = '__all__'@@ -128,7 +129,7 @@ function TeamChannelCard({ integration }: { integration: IntegrationType }): JSX/** Where a saved config sends this user's reviewer pings, and whether that counts as enabled. */function readSlackTarget(- config: SignalUserAutonomyConfig | null,+ config: SignalUserAutonomyConfigDraft | null,integrations: IntegrationType[]): {selectedIntegrationId: number | nulldiff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex 09137a08019f..433d0760836f 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -6,7 +6,7 @@ import type { CaptureOptions } from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { ApiError } from 'lib/api-error'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'@@ -23,7 +23,11 @@ import { Breadcrumb } from '~/types'import type { UserType } from '~/types'import { OriginProduct, Task, TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'-import { signalsReportsRefreshMetricsCreate, signalsReportsViewedCreate } from 'products/signals/frontend/generated/api'+import {+ signalsReportsRefreshMetricsCreate,+ signalsReportsViewedCreate,+ signalsScoutRunsList,+} from 'products/signals/frontend/generated/api'import type { SignalReportMetricSnapshotsApi } from 'products/signals/frontend/generated/api.schemas'import {@@ -695,7 +699,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([{loadRuns: async (_payload: void, breakpoint) => {const [scoutResult, signalResult] = await Promise.allSettled([- api.signalScout.runs.list({ limit: SCOUT_RUNS_LIMIT }),+ signalsScoutRunsList(String(ApiConfig.getCurrentProjectId()), { limit: SCOUT_RUNS_LIMIT }),// `internal: 'all'` so the pipeline's runs (research and implementation, both// created internal) are included. They're hidden from the default task list.api.tasks.list({diff --git a/products/signals/frontend/inbox/logics/findingsLogic.ts b/products/signals/frontend/inbox/logics/findingsLogic.tsindex 04af2b0ac9ea..626d73a92a2a 100644--- a/products/signals/frontend/inbox/logics/findingsLogic.ts+++ b/products/signals/frontend/inbox/logics/findingsLogic.ts@@ -2,14 +2,20 @@ import { MakeLogicType, actions, connect, events, kea, listeners, path, reducersimport { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { dayjs } from 'lib/dayjs'+import {+ signalsScoutRunsEmissionReportsBatch,+ signalsScoutRunsEmissionsBatch,+} from 'products/signals/frontend/generated/api'++import type { SignalScoutEmissionApi } from '../../generated/api.schemas'import {LinkedSignalReport,+ SignalScoutEmission,SignalReport,SignalReportPriority,- SignalScoutEmission,SignalScoutEmissionReportLink,SignalScoutRunSummary,} from '../types'@@ -128,10 +134,10 @@ export interface findingsLogicActions {errorObject?: any}loadEmissionsSuccess: (- emissions: SignalScoutEmission[],+ emissions: SignalScoutEmissionApi[],payload?: any) => {- emissions: SignalScoutEmission[]+ emissions: SignalScoutEmissionApi[]payload?: any}loadScoutReports: (ids?: string[]) => {@@ -335,7 +341,9 @@ export const findingsLogic = kea<findingsLogicType>([// One batched request for the whole window: the backend flattens every run's// findings newest-first (each row carries its run_id). A throw surfaces as the// page's error/retry state — far cheaper than the old per-run fan-out.- return await api.signalScout.runs.emissionsBatch(runs.map((run) => run.run_id))+ return await signalsScoutRunsEmissionsBatch(String(ApiConfig.getCurrentProjectId()), {+ run_ids: runs.map((run) => run.run_id),+ })},},],@@ -357,7 +365,9 @@ export const findingsLogic = kea<findingsLogicType>([// but not `task:read` 403s this endpoint on every poll). The `emissions` loader keeps// throwing: that one is the page's actual content and should surface an error/retry state.try {- return await api.signalScout.runs.emissionReportsBatch(runs.map((run) => run.run_id))+ return await signalsScoutRunsEmissionReportsBatch(String(ApiConfig.getCurrentProjectId()), {+ run_ids: runs.map((run) => run.run_id),+ })} catch {return values.emissionReports}diff --git a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts b/products/signals/frontend/inbox/logics/scoutDetailLogic.tsindex 2075d723ccb4..974c5bbc8aab 100644--- a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutDetailLogic.ts@@ -2,10 +2,12 @@ import { MakeLogicType, connect, kea, key, listeners, path, props, reducers, selimport { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { dayjs } from 'lib/dayjs'import { reconcileById } from 'lib/utils/objects'+import { signalsScoutRunsEmissionReports, signalsScoutRunsEmissions } from 'products/signals/frontend/generated/api'+import {LinkedSignalReport,SignalReport,@@ -198,8 +200,9 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([}// allSettled, not all: one failed run's fetch (transient 500, deleted run)// shouldn't discard every other run's findings — surface the partial set.+ const projectId = String(ApiConfig.getCurrentProjectId())const settled = await Promise.allSettled(- runs.map((run) => api.signalScout.runs.emissions(run.run_id))+ runs.map((run) => signalsScoutRunsEmissions(projectId, run.run_id)))const fulfilled = settled.filter((result): result is PromiseFulfilledResult<SignalScoutEmission[]> =>@@ -240,8 +243,9 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([// all). source_id is `run:<run_id>:finding:<id>`, so prior links for a run are the// ones prefixed with its run_id.const previous = values.emissionReports+ const projectId = String(ApiConfig.getCurrentProjectId())const settled = await Promise.allSettled(- runs.map((run) => api.signalScout.runs.emissionReports(run.run_id))+ runs.map((run) => signalsScoutRunsEmissionReports(projectId, run.run_id)))const merged = runs.flatMap((run, index) => {const result = settled[index]diff --git a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts b/products/signals/frontend/inbox/logics/userAutonomyLogic.tsindex a2c634bea4a7..95f2a77b4dd8 100644--- a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts+++ b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts@@ -3,13 +3,15 @@ import { loaders } from 'kea-loaders'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { isSlackMemberTarget } from 'lib/integrations/slackChannel'+import { usersSignalAutonomyCreate, usersSignalAutonomyRetrieve } from 'products/signals/frontend/generated/api'import type { SignalUserAutonomyConfigCreateApi } from 'products/signals/frontend/generated/api.schemas'+import type { SignalUserAutonomyConfigApi } from '../../generated/api.schemas'import { captureInboxSettingsChanged } from '../inboxAnalytics'-import type { SignalReportPriority, SignalUserAutonomyConfig } from '../types'+import type { SignalReportPriority, SignalUserAutonomyConfigDraft } from '../types'interface SlackNotificationUpdates {integrationId?: number | null@@ -82,7 +84,7 @@ function apiErrorMessage(error: any, fallback: string): string {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface userAutonomyLogicValues {- autonomyConfig: SignalUserAutonomyConfig | null+ autonomyConfig: SignalUserAutonomyConfigDraft | nullautonomyConfigLoading: booleanautostartPriorityUpdating: booleangithubAssignUpdating: boolean@@ -108,10 +110,10 @@ export interface userAutonomyLogicActions {errorObject?: any}loadAutonomyConfigSuccess: (- autonomyConfig: SignalUserAutonomyConfig | null,+ autonomyConfig: SignalUserAutonomyConfigApi | null,payload?: any) => {- autonomyConfig: SignalUserAutonomyConfig | null+ autonomyConfig: SignalUserAutonomyConfigApi | nullpayload?: any}openPullRequestReadySettled: () => {@@ -140,9 +142,9 @@ export interface userAutonomyLogicActions {export type userAutonomyLogicType = MakeLogicType<userAutonomyLogicValues, userAutonomyLogicActions>/**- * Per-user Self-driving autonomy override. Wraps the `users/@me/signal_autonomy`- * endpoint via `api.signalUserAutonomy`. Every field here applies to reports that- * suggest this user as reviewer: the PR auto-start priority threshold, which+ * Per-user Self-driving autonomy override over the `users/@me/signal_autonomy`+ * endpoint. Every field here applies to reports that suggest this user as+ * reviewer: the PR auto-start priority threshold, which* overrides the team default when set and inherits it when `null` (see the backend* `_effective_threshold`); the Slack notification destination; whether to add* this user as a GitHub assignee on the implementation PR; and whether that PR opens@@ -177,10 +179,18 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([}),loaders({autonomyConfig: [- null as SignalUserAutonomyConfig | null,+ null as SignalUserAutonomyConfigDraft | null,{loadAutonomyConfig: async () => {- return await api.signalUserAutonomy.get()+ try {+ return await usersSignalAutonomyRetrieve('@me')+ } catch (error) {+ // 404 = no config yet (user hasn't opted in). Treat as null.+ if (error instanceof ApiError && error.status === 404) {+ return null+ }+ throw error+ }},},],@@ -256,7 +266,7 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([setAutostartPriority: async ({ priority }) => {let success = truetry {- await api.signalUserAutonomy.update({ autostart_priority: priority })+ await usersSignalAutonomyCreate('@me', { autostart_priority: priority })} catch (error: any) {success = falselemonToast.error(error?.detail ?? error?.message ?? 'Failed to update auto-start threshold')@@ -274,7 +284,7 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([setGithubAssignOnPullRequest: async ({ enabled }) => {let success = truetry {- await api.signalUserAutonomy.update({ github_assign_on_pull_request: enabled })+ await usersSignalAutonomyCreate('@me', { github_assign_on_pull_request: enabled })} catch (error: any) {success = falselemonToast.error(error?.detail ?? error?.message ?? 'Failed to update GitHub assignment setting')@@ -292,7 +302,7 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([setOpenPullRequestReady: async ({ ready }) => {let success = truetry {- await api.signalUserAutonomy.update({ github_open_pull_request_ready: ready })+ await usersSignalAutonomyCreate('@me', { github_open_pull_request_ready: ready })} catch (error: any) {success = falselemonToast.error(error?.detail ?? error?.message ?? 'Failed to update pull request state setting')@@ -311,7 +321,7 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([const body = slackNotificationBody(updates)let success = truetry {- const config = await api.signalUserAutonomy.update(body)+ const config = await usersSignalAutonomyCreate('@me', body)actions.loadAutonomyConfigSuccess(config)} catch (error: any) {success = falsediff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex c8082c6915e9..bc600339fcc3 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -8,7 +8,9 @@ import {type SignalReportAssignmentPrStateEnumApi,type SignalReportRefundApi,type SignalReportStateRequestApi,+ type SignalScoutEmissionApi,type SignalScoutRunSummaryApi,+ type SignalUserAutonomyConfigApi,SignalSourceProductApi as SignalSourceProduct,SignalSourceTypeApi as SignalSourceType,} from 'products/signals/frontend/generated/api.schemas'@@ -386,18 +388,8 @@ export const SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP: SignalReportTaskRelatio// ── Autonomy config (per-user override; backend SignalUserAutonomyConfigView) ─-export interface SignalUserAutonomyConfig {- id?: string- autostart_priority: SignalReportPriority | null- slack_notification_integration_id?: number | null- slack_notification_channel?: string | null- slack_notification_min_priority?: SignalReportPriority | null- github_assign_on_pull_request?: boolean- /** Whether PRs for reports suggesting this user open ready for review. Null follows the project default. */- github_open_pull_request_ready?: boolean | null- created_at?: string- updated_at?: string-}+/** The per-user autonomy row, or the subset the optimistic reducers set before the first load lands. */+export type SignalUserAutonomyConfigDraft = Partial<SignalUserAutonomyConfigApi>// ── Team-level autonomy config (backend SignalTeamConfigViewSet; singleton per team) ─@@ -462,18 +454,10 @@ export type SignalScoutRunStatus = SignalScoutRunSummaryApi['status']* instead of inlining `import(...)` references to the generated type. */export interface SignalScoutRunSummary extends SignalScoutRunSummaryApi {}-/** One finding a scout run emitted to the inbox. */-export interface SignalScoutEmission {- id: string- run_id: string- finding_id: string- description: string- severity: SignalReportPriority | null- /** Slug tags the scout attached to this finding (lowercase kebab-case, e.g. `cost-spike`). */- tags: string[]- source_id: string- emitted_at: string-}+/** One finding a scout run emitted to the inbox.+ * An interface extension (not a type alias) so kea-typegen keeps the domain name+ * instead of inlining `import(...)` references to the generated type. */+export interface SignalScoutEmission extends SignalScoutEmissionApi {}/** Minimal projection of the inbox report a scout finding grouped into (for the linked chip). */export interface LinkedSignalReport {