:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(inbox): Inbox 2.0 (#62980)
Michael Matlokab47dc3f89e3d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 524229d0793b..97813d63a3d6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5176,6 +5176,90 @@ snapshots:hash: v1.k794b7964.ccbdd94e59c1029a025b82b148e055fc0f95bbf3d9b22c2e9ec0f6056d573e5b.NZwaV6bkwoSS9a6zSlfpSKp-RCZwNns1fXt5iZawOgIscenes-app-hogfunctions-destination--runs-with-data--light:hash: v1.k794b7964.0096a479368226c8e814746b035ce360a9345b27a081ffc2083cf6e855489432.jMrGy2vE-erlaH_1tAskw0DDuKX-SdTXXjE32rc2uI0+ scenes-app-inbox-badges--all-badges--dark:+ hash: v1.k794b7964.51fa6006ad07b02e6f11a352d76e9c401efd4445bd42d873081e7e7689aa14e0.okUTzDeF87AijpmaUtUxy65qKVS502E1-Eo1nXh10XE+ scenes-app-inbox-badges--all-badges--light:+ hash: v1.k794b7964.cffee6f288a8db013733381d6ece9c3e33145a57c8c1ce4d590b755e50c35b27.ugFqVSEhuPB1cHnuPoWLSnhukpST2KU2k1L4-c1Qct8+ scenes-app-inbox-cards--agent-run-cards--dark:+ hash: v1.k794b7964.fcb982b9e94ae098103fc93d6cac35a02c72982f77983ef6aace36f3b71d08ee.kdUHji6m8w2Nb8xAll_JgMCvh56xcuyAoEPDg17Plg0+ scenes-app-inbox-cards--agent-run-cards--light:+ hash: v1.k794b7964.4fced4761948504f507f7c797cca06f09b9384dc13e053f3af5c893e7c0cd2d2.J1aM-6ZJAZvKQnV4Zd93kTJUK9pMEQYYWijc25ewVbQ+ scenes-app-inbox-cards--pull-request-cards--dark:+ hash: v1.k794b7964.b53c9bb3fd2de55e52f275baa9bb90d7bad568b5c759979522a9ad8429b92f28.WKBQ_N5vGFXTeW_v7A4rrdXeKZM0af-pZuw5o7YMZ00+ scenes-app-inbox-cards--pull-request-cards--light:+ hash: v1.k794b7964.a708b3221d13ade6c1422f5b1a3c100d2c026caa53f466e15817f1a8eb0f3e3d.1UZEVt0l5W7r1ClQ7TwPPYXiKpsu46sSQ5VlziKIC2M+ scenes-app-inbox-cards--report-card-states--dark:+ hash: v1.k794b7964.6488ec9c5ea1a15b0f48a9ccb2d4d63181b65717fba00a369d2edc561a54f58a.-JdaI9RPkMvpsHA5m68iyuSoVid8wYKyFeS7heFLrcM+ scenes-app-inbox-cards--report-card-states--light:+ hash: v1.k794b7964.1bcaa3f21f83ce7aff492151c5766f0468c0ac5001119f4976a909dae010d930.bIK_qGwJqmk4st2S34_eTMvuSEu14g5MozbyqXXujss+ scenes-app-inbox-cards--report-cards--dark:+ hash: v1.k794b7964.4557defabb8b6dcd2b11f2fe6ec8c844e75b613de3c048311871ef3d98298d20.cqt3LDe-eirmnHTS7DYOgjBFon2v4jQFJzcdsPt01Ao+ scenes-app-inbox-cards--report-cards--light:+ hash: v1.k794b7964.5bb0adad16641c593c2f9099d80745749c4e8593b3282540ff391351765ee1cc.xhHXAYDICcr0KlGgZ4C0Kyc_zLqvcr8HBV_1kB9lC4Q+ scenes-app-inbox-cards--skeleton--dark:+ hash: v1.k794b7964.4ab1f8cb97f347a2aae442ca814c70c538c54e4a9efb1c3cdd6681a56cad5e90.wVmcanELl0wz7-rhcnN8K5MGXmKMMxXELkYcCEpCxKs+ scenes-app-inbox-cards--skeleton--light:+ hash: v1.k794b7964.24c19ab5df1e4ccb843b1ad726752e3a98aeadaa08595e66cb4b41aff1a9e9a1.Y3z44tkU4jsAYUyXxfl72fTuZ0MKA6_S6TTNCKt5jSg+ scenes-app-inbox-detail--pull-request--dark:+ hash: v1.k794b7964.ac67048b0e7c3f4cf29e4b38823e3f995365fa7e541c59b308e92c1601a74742.fiRwUgQNIN7pBQOGzA2LTx2xd8dd7VfP985Mj7yBnXE+ scenes-app-inbox-detail--pull-request--light:+ hash: v1.k794b7964.a14ee8b2c4ee70239ec88c9d21cd8aca7e9b6e307b781976bd32155e5b597a8a.Jm0mMI-maDHgsb5C3ab56b178lZzqkRx9lbgqPmLtIo+ scenes-app-inbox-detail--report--dark:+ hash: v1.k794b7964.259f8ed5e3c1a493c90abb64ef41d96e3b9f8e94b9877c00ddc8f7835cfc6cdb.eHbLktOiH9NmNXvlX71F2d9_PyLdZg3xBCy8xfmLVRE+ scenes-app-inbox-detail--report--light:+ hash: v1.k794b7964.3866cb389c9dff632666c161c4dddd54838ec887131000ba060ea3a2156508fc.tlYIYqScTAQ9jVxsTvhiUyUT3sn8ZSdJWZ59eoiPIFU+ scenes-app-inbox-detail--report-minimal--dark:+ hash: v1.k794b7964.33771cbe5dc0cb90c1a962dad910cf88807369236f3de09c711aa8e0e753642f.fn5ipDgqRJStxC4p-SBQc7yCuIoCQoIFUe7pecuTtCs+ scenes-app-inbox-detail--report-minimal--light:+ hash: v1.k794b7964.8d3708d246d553b9d29d028f8ea7804c7ab9e33ebc6b2cddaaaa6f12d3dc1cfe.BW5bHBxSPVtSfQXDtTuZT5aEK4T-HzsJLzA2qhmRpVE+ scenes-app-inbox-detail--run-failed--dark:+ hash: v1.k794b7964.a81e0056d7e41aea91881fa658e2e744c6d38182cb85c8b2ae211c1d01564014.IDM9GRcQT4gRW-yqlq9Ntg-wAZDiQWrkZf69Va0fkjM+ scenes-app-inbox-detail--run-failed--light:+ hash: v1.k794b7964.eff26b30ff1b74bf77e68a9b83242b723a031a84668855f7fe67e29e7593f68b.Bcl6dB6ZwTS4CgbIG19B_Ys3nYY-6BfLZwdo8przN-0+ scenes-app-inbox-detail--run-in-progress--dark:+ hash: v1.k794b7964.6d479c1f9677e027c962151b3993648babea4aa7c1306fb158ed37c1fb10a929.WCZtZiBivqhAZTI7nY5ILqasbFEbISExNLoNOCpL4S8+ scenes-app-inbox-detail--run-in-progress--light:+ hash: v1.k794b7964.f8d95efb0fee8517003a95be0a740c37af51fd888ed5b9dd858f1840f69c49dd.4JG5rL4VNtEUk5shtZag-fimDVAUb2SU9fNd0BQhYXI+ scenes-app-inbox-detail--run-ready--dark:+ hash: v1.k794b7964.2c9966f4b6e2274d884b93b21add25f69cc934e3e580006654ebd1ef5123b563.fPwrKUERAtNpNXvrIgrBcYzWGBQaZtbE4spXnY67KnI+ scenes-app-inbox-detail--run-ready--light:+ hash: v1.k794b7964.4050eb15b9d9c5ac9e2783ff55bdb3db37852d43f71832a59f308396a01c5a14.a5dDQZ2UQnE2VDGVWxSmlofmqd3niKKdxyrO1KQ9YKU+ scenes-app-inbox-scene--empty--dark:+ hash: v1.k794b7964.7294afe8f41728a213a9bd48eb918ec4902887b5b39a94d03fa2c0b48c0d032f.HrAifApnGeL2Y60UklnooAEi4ah0uvR7Q5SUCkjPJXM+ scenes-app-inbox-scene--empty--light:+ hash: v1.k794b7964.3a6ce65683bc9764a08ec055328b6962ae4b00769fb380fa1d054eced1fbae8f.I-sQDDqLKSgM2bjN6f2kjSFb0d20htIXWwumGqOqR78+ scenes-app-inbox-scene--inbox--dark:+ hash: v1.k794b7964.7ac4cd509a3cc40957183200e2055e8ee10fa7ebb4638b886edec47956f3d69a.Kue4fX-RZ4gJowrkDXGSM_LvrLNTzeG98HLiXWgyf84+ scenes-app-inbox-scene--inbox--light:+ hash: v1.k794b7964.40c4ef842c1ebc1de3a430e65869f66fb2ccd2179b3d7c541cfb208e099ccf02.Ffm7PLvZFi-gwk-7K27Mt9jVWJtoI30KpIguGNhVhJU+ scenes-app-inbox-tabs--pull-requests--dark:+ hash: v1.k794b7964.1b389684f50110e0a29fcd8fe1627f5c1184e6a140c68996c2fccbd782309aa0.hp1HJMSMvnHyIAUvhfTXZOnOF4nKOkr5gskBs10efeE+ scenes-app-inbox-tabs--pull-requests--light:+ hash: v1.k794b7964.6a4e11dc09866839a0cc528c1cb657cbeaaefb6998abc54ef01ded88f62442af.smueUB8lJNSe1Q9fQQGITnVq28dYzrK8tU9nBQhpg3E+ scenes-app-inbox-tabs--pull-requests-empty--dark:+ hash: v1.k794b7964.46c7e27bcf7c8eeff940cd1ba52c379fa29c6fd26efa8e5511ce6fae0ebb97f2.LxZ71depKylIFoMgKmsEJGRnkU8SZ7UIOrqU_wn8QQY+ scenes-app-inbox-tabs--pull-requests-empty--light:+ hash: v1.k794b7964.167de2b957533bcc5780f9ddac38b19a4d4892d6fcbb92e985b9a71d8c3fd7d4.rpDhhtvsIxoxhtaVy23_PS6KE1PyvOtTjeh-GlVvaq8+ scenes-app-inbox-tabs--reports--dark:+ hash: v1.k794b7964.701a0ceda712f1d8d834db294d2eff1ebccd88f443d9c8b92d4ab6c6ab8c5ede.Um1YVrlAZdV8TV_L82dVeAn7OlD6VB8kTqTxD5kAXlY+ scenes-app-inbox-tabs--reports--light:+ hash: v1.k794b7964.79457871f1c2a6ddcde75f12bf5f3a669bda1f8adfaefc0dc7449a62899b04dc.UKqUPy4FmQy51-lzVRQK9w7-iPnUVr9LD6FMsDVxk34+ scenes-app-inbox-tabs--reports-empty--dark:+ hash: v1.k794b7964.c3c5ebc57b2f0370c61ca952ce372725898e6242c8c938be810948012c97b49f.1uja5-2bTIAszcF7RaIDcEIAcf3lctJMAzJEuNGWMdQ+ scenes-app-inbox-tabs--reports-empty--light:+ hash: v1.k794b7964.95f6f7ea9cae6c59d6151a4c0a09f48c7a076f5893ecf569fbce27f4a48bee18.IbGFUypZB0-MWlRLFTf7EStrtqNJrOMJUZAhSMcHt6A+ scenes-app-inbox-tabs--runs-empty--dark:+ hash: v1.k794b7964.4d9d8f081534a1d495b60435f0074dc19527f811d235b9627c605e91db1b5beb.8eFwrG5Hl906n9bTGTp56vy2OiMGtSXrmKGy1OpcfkQ+ scenes-app-inbox-tabs--runs-empty--light:+ hash: v1.k794b7964.b5ad42de26512ee604d2f82d267a8b7e16a5c78895e1342ae4e3f622bc941e4f.-A5S3-acRXG7neE_qqLlT5rMA6x-sLGUCDkGJlZGHhw+ scenes-app-inbox-tabs--runs-few-agents--dark:+ hash: v1.k794b7964.27c143c92ee236a0307c8a7876c3ea8cd95d40a162f0a64b3423a5325272c03d.yh6WyVyXIwPCAefIFXTn6an_m-T1oO8rplU9Ab0WNpQ+ scenes-app-inbox-tabs--runs-few-agents--light:+ hash: v1.k794b7964.f177cf82929d595046edcfa81a193e6cc13ec70ac0df1156b7aba75fd384a390.dtXjjAcR5IyCU2PvaSjz6_1fsEtTN02jxLuXmGbEjJM+ scenes-app-inbox-tabs--runs-many-agents--dark:+ hash: v1.k794b7964.dd76b59536653a95f1d064c9bc2ad8aea9da9cb6595b487ce86bace171887a46.jvndkfnDbc-t_ydLYTUnT2psRi3WoFtNmFlZGaVUER0+ scenes-app-inbox-tabs--runs-many-agents--light:+ hash: v1.k794b7964.90b19fdceb30d6d27868420db1123615fe3ae01b3a8b1ec4b6d016bd4885d12d.sk9bQDwr1fH7njWhbM40oMj7px6aZ9NmA2Fz1V78VT0scenes-app-insights-boldnumber--compare-null-previous--dark:hash: v1.k794b7964.ccab3f6785db86e659c4186e305b97ba81c7bda8c51e7fd5c05e179be4393fde.C-X-Y3nG_88O1MxV0YKV52bqS_DKlvdLVHa5HDj0GRIscenes-app-insights-boldnumber--compare-null-previous--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 6a5d0b96e790..ae4421051904 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -14,7 +14,20 @@ import { CohortCalculationHistoryResponse } from 'scenes/cohorts/cohortCalculatiimport { EventSchema } from 'scenes/data-management/events/eventDefinitionSchemaLogic'import { SchemaPropertyGroup } from 'scenes/data-management/schema/schemaManagementLogic'import { SignalNode } from 'scenes/debug/signals/types'-import { SignalReport, SignalReportArtefactResponse, SignalSourceConfig } from 'scenes/inbox/types'+import {+ SignalReport,+ SignalReportArtefact,+ SignalReportArtefactResponse,+ SignalReportStateRequest,+ SignalReportTask,+ SignalScoutConfig,+ SignalScoutConfigUpdate,+ SignalScoutEmission,+ SignalScoutRunSummary,+ SignalSourceConfig,+ SignalTeamConfig,+ SignalUserAutonomyConfig,+} from 'scenes/inbox/types'import { MaxBillingContext } from 'scenes/max/maxBillingContextLogic'import { NotebookListItemType, NotebookNodeResource, NotebookType } from 'scenes/notebooks/types'import { RecordingComment } from 'scenes/session-recordings/player/inspector/playerInspectorLogic'@@ -1177,6 +1190,15 @@ export class ApiRequest {return this.signalReports(teamId).addPathComponent(id)}+ public signalReportTasks(reportId: SignalReport['id'], teamId?: TeamType['id']): ApiRequest {+ return this.signalReport(reportId, teamId).addPathComponent('tasks')+ }++ // 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')@@ -1186,6 +1208,39 @@ export class ApiRequest {return this.signalSourceConfigs(teamId).addPathComponent(id)}+ // # Signal Team Config (singleton per team)+ public signalTeamConfig(teamId?: TeamType['id']): 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)+ }++ public signalScoutConfigs(teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId)+ .addPathComponent('signals')+ .addPathComponent('scout')+ .addPathComponent('configs')+ }++ public signalScoutConfig(id: string, teamId?: TeamType['id']): ApiRequest {+ return this.signalScoutConfigs(teamId).addPathComponent(id)+ }+// # Taskspublic tasks(teamId?: TeamType['id']): ApiRequest {return this.projectsDetail(teamId).addPathComponent('tasks')@@ -5047,6 +5102,16 @@ const api = {status?: stringsearch?: stringordering?: string+ /** Comma-separated source products. */+ source_product?: string+ /** Comma-separated P0–P4. */+ priority?: string+ /** Comma-separated actionability values (immediately_actionable|requires_human_input|not_actionable). */+ actionability?: string+ /** Filter by whether a shipped implementation PR exists. */+ has_implementation_pr?: 'true' | 'false'+ /** Comma-separated reviewer user UUIDs (For-you / teammate scope). */+ suggested_reviewers?: string}): Promise<CountedPaginatedResponse<SignalReport>> {return await new ApiRequest().signalReports().withQueryString(params).get()},@@ -5068,6 +5133,98 @@ const api = {async reingest(id: SignalReport['id']): Promise<{ status: string; report_id: string }> {return await new ApiRequest().signalReport(id).withAction('reingest').create()},+ // SignalReport ↔ Task linkage (read-only list). Backend: SignalReportTaskViewSet.+ async tasks(reportId: SignalReport['id']): Promise<PaginatedResponse<SignalReportTask>> {+ return await new ApiRequest().signalReportTasks(reportId).get()+ },+ // State transitions: suppress (dismiss) or snooze back to potential. Backend: `state` action.+ async setState(id: SignalReport['id'], data: SignalReportStateRequest): Promise<SignalReport> {+ return await new ApiRequest().signalReport(id).withAction('state').create({ data })+ },+ // Backend returns a flat `{ [user_uuid]: { name, email } }` map (not paginated).+ async availableReviewers(query?: string): Promise<{ user_uuid: string; name: string; email: string }[]> {+ const response: Record<string, { name: string; email: string }> = await new ApiRequest()+ .signalReports()+ .withAction('available_reviewers')+ .withQueryString(query ? { query } : undefined)+ .get()+ return Object.entries(response).map(([user_uuid, { name, email }]) => ({ user_uuid, name, email }))+ },+ // PUT replaces the content of a `suggested_reviewers` artefact (only writable type).+ // Backend: SignalReportArtefactViewSet.update.+ async updateArtefact(+ reportId: SignalReport['id'],+ artefactId: string,+ content: Record<string, any>[]+ ): Promise<SignalReportArtefact> {+ return await new ApiRequest().signalReportArtefact(reportId, artefactId).put({ data: { content } })+ },+ },++ // Team-level signal autonomy config (singleton). Backend: SignalTeamConfigViewSet.+ signalTeamConfig: {+ async get(): Promise<SignalTeamConfig> {+ return await new ApiRequest().signalTeamConfig().get()+ },+ // Backend exposes update via POST to the collection (singleton create-or-update, partial).+ async update(data: Partial<SignalTeamConfig>): Promise<SignalTeamConfig> {+ return await new ApiRequest().signalTeamConfig().create({ data })+ },+ },++ // Scouts: scheduled agents that sweep the project and emit findings. Backend:+ // SignalScoutRunViewSet (runs) + SignalScoutConfigViewSet (configs).+ 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()+ },+ },+ configs: {+ // Newest-first raw array, ordered by skill_name.+ async list(): Promise<SignalScoutConfig[]> {+ return await new ApiRequest().signalScoutConfigs().get()+ },+ async update(id: string, data: SignalScoutConfigUpdate): Promise<SignalScoutConfig> {+ return await new ApiRequest().signalScoutConfig(id).update({ data })+ },+ },+ },++ 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: Partial<SignalUserAutonomyConfig>,+ 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: {diff --git a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsxindex d5ac21e53759..70451e569d7d 100644--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx@@ -54,8 +54,11 @@ const SLACK_CHANNEL_ID_PATTERN = /^[CGD][A-Z0-9]{8,}$/const getSlackChannelOptions = (slackChannels?: SlackChannelType[] | null): LemonInputSelectOption[] | null => {return slackChannels? slackChannels.map((x) => {- const name = x.is_private_without_access ? 'Private Channel' : x.name- const displayLabel = `${x.is_private ? '🔒' : '#'}${name} (${x.id})`+ // Channel names are unique per workspace, so the friendly name alone identifies a channel.+ // Inaccessible private channels have no readable name, so there we keep the id to disambiguate.+ const displayLabel = x.is_private_without_access+ ? `🔒Private channel (${x.id})`+ : `${x.is_private ? '🔒' : '#'}${x.name}`return {key: `${x.id}|#${x.name}`,labelComponent: (@@ -140,7 +143,7 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S// /channels returns. Without a direct lookup the channel never makes it into slackChannels, so// LemonInputSelect can't find an option matching the saved value's key and falls back to// displaying the raw value text — e.g. "C0881TYHT41|#sentry-alerts" instead of the friendly- // "#sentry-alerts (C0881TYHT41)". Fire the by-id fetch for both bare and composite values so+ // "#sentry-alerts". Fire the by-id fetch for both bare and composite values so// the channel is merged into slackChannels regardless of bulk-list position; the label only// renders correctly when the option exists in the picker's options list.useEffect(() => {diff --git a/frontend/src/lib/integrations/slackChannel.ts b/frontend/src/lib/integrations/slackChannel.tsindex ed3d70a14bed..736e136de022 100644--- a/frontend/src/lib/integrations/slackChannel.ts+++ b/frontend/src/lib/integrations/slackChannel.ts@@ -7,6 +7,19 @@ export function slackChannelId(channelValue: string): string {return channelValue.split('|')[0]}+/**+ * The friendly name half (`#channel-name`) of a `${channelId}|#${channelName}` picker value, for+ * display. Falls back to the raw value when no name is encoded (e.g. a bare channel id). Mirrors+ * the backend `_channel_display_name`.+ */+export function slackChannelDisplayName(channelValue: string): string {+ const pipe = channelValue.indexOf('|')+ if (pipe === -1) {+ return channelValue+ }+ return channelValue.slice(pipe + 1).trim() || channelValue+}+function storageKey(integrationId: number): string | null {const teamId = getCurrentTeamIdOrNone()if (teamId == null) {diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsxindex ceea3b8ed5a6..b64caa1951db 100644--- a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx@@ -1,6 +1,6 @@import React from 'react'-import { extractTextFromChildren, slugifyHeading } from './LemonMarkdown'+import { extractTextFromChildren, isTrustedImageSrc, slugifyHeading } from './LemonMarkdown'describe('LemonMarkdown utilities', () => {describe('slugifyHeading', () => {@@ -135,4 +135,31 @@ describe('LemonMarkdown utilities', () => {expect(extractTextFromChildren(top)).toBe('deep')})})++ describe('isTrustedImageSrc', () => {+ // jsdom serves tests from http://localhost, so same-origin checks resolve against localhost.+ it.each([+ ['/static/screenshot.png'],+ ['http://localhost/img.png'],+ ['https://posthog.com/img.png'],+ ['https://us.posthog.com/img.png'],+ ['https://app.posthog.com/a/b/c.png'],+ ])('trusts %s', (src) => {+ expect(isTrustedImageSrc(src)).toBe(true)+ })++ it.each([+ ['https://evil.com/img.png'],+ ['https://notposthog.com/img.png'],+ ['https://evil.posthog.com.attacker.com/img.png'],+ ['https://posthog.com.attacker.com/img.png'],+ ['data:image/png;base64,iVBORw0KGgo='],+ ['blob:https://posthog.com/abc'],+ ['javascript:alert(1)'],+ [''],+ [undefined],+ ])('distrusts %s', (src) => {+ expect(isTrustedImageSrc(src)).toBe(false)+ })+ })})diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsxindex 8a9d9460c402..93f1d00a73f1 100644--- a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx@@ -28,8 +28,11 @@ export interface LemonMarkdownProps {/** Whether to disable the docs sidebar panel behavior and always open links in a new tab */disableDocsRedirect?: boolean/**- * Whether to render images as plain links instead of <img> elements. Use for untrusted content- * (e.g. LLM/agent output), where auto-loading images would fire requests to arbitrary URLs.+ * Whether to treat images as untrusted. Use for content we don't control (e.g. LLM/agent or+ * externally-sourced output), where auto-loading an image would fire a request to an arbitrary+ * URL — leaking the viewer's IP, acting as a tracking pixel, or probing internal addresses.+ * When set, only images served from PostHog (same-origin or a `posthog.com` host) render inline+ * as <img>; every other image is rendered as a plain click-to-open link instead.*/disableImages?: booleanclassName?: string@@ -56,6 +59,27 @@ export function slugifyHeading(text: string): string {.replace(/^-|-$/g, '')}+/**+ * Whether an image source is trusted enough to render inline within untrusted content.+ * Trusted = served from PostHog itself: same-origin (incl. relative URLs) or any `posthog.com` host.+ * Anything else (including `data:`/`blob:` URIs) is untrusted and should be rendered as a link.+ */+export function isTrustedImageSrc(src: string | undefined): boolean {+ if (!src) {+ return false+ }+ let url: URL+ try {+ url = new URL(src, window.location.origin)+ } catch {+ return false+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {+ return false+ }+ return url.hostname === window.location.hostname || /(^|\.)posthog\.com$/i.test(url.hostname)+}+export function extractTextFromChildren(children: React.ReactNode): string {if (typeof children === 'string') {return children@@ -122,11 +146,14 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({},...(disableImages? {- img: ({ src, alt }: any): JSX.Element => (- <Link to={src} target="_blank" targetBlankIcon disableDocsPanel>- {alt || src}- </Link>- ),+ img: ({ src, alt }: any): JSX.Element =>+ isTrustedImageSrc(src) ? (+ <img src={src} alt={alt} loading="lazy" />+ ) : (+ <Link to={src} target="_blank" targetBlankIcon disableDocsPanel>+ {alt || src}+ </Link>+ ),}: {}),li: ({ children, node }: any): JSX.Element => {diff --git a/frontend/src/lib/signals/signalCardSourceLine.ts b/frontend/src/lib/signals/signalCardSourceLine.tsindex 5157be5a98e4..fe7091d4884c 100644--- a/frontend/src/lib/signals/signalCardSourceLine.ts+++ b/frontend/src/lib/signals/signalCardSourceLine.ts@@ -1,18 +1,21 @@import { errorTrackingSignalHeaderLine } from './errorTracking'-/** Human-readable “Product · Signal type” line for inbox / debug signal cards. */+/** Human-readable "Product · Signal type" line for inbox / debug signal cards. */export function signalCardSourceLine(signal: { source_product: string; source_type: string }): string {const { source_product, source_type } = signalif (source_product === 'error_tracking') {return errorTrackingSignalHeaderLine(source_type)}- if (source_product === 'session_replay' && source_type === 'session_segment_cluster') {- return 'Session replay · Session segment cluster'+ if (source_product === 'session_replay') {+ return 'Session replay · Problem segment'}if (source_product === 'llm_analytics' && source_type === 'evaluation') {return 'AI observability · Evaluation'}+ if (source_product === 'llm_analytics' && source_type === 'evaluation_report') {+ return 'AI observability · Evaluation report'+ }if (source_product === 'zendesk' && source_type === 'ticket') {return 'Zendesk · Ticket'}@@ -22,6 +25,24 @@ export function signalCardSourceLine(signal: { source_product: string; source_tyif (source_product === 'linear' && source_type === 'issue') {return 'Linear · Issue'}+ if (source_product === 'conversations' && source_type === 'ticket') {+ return 'Conversations · Ticket'+ }+ if (source_product === 'pganalyze' && source_type === 'issue') {+ return 'pganalyze · Issue'+ }+ if (source_product === 'endpoints' && source_type === 'endpoint_execution_failed') {+ return 'Endpoints · Endpoint execution failed'+ }+ if (source_product === 'logs' && source_type === 'alert_state_change') {+ return 'Logs · Alert state change'+ }+ if (source_product === 'health_checks') {+ return 'Health checks · Instrumentation issue'+ }+ if (source_product === 'signals_scout') {+ return 'Scout · Cross-source finding'+ }const productLabel = source_product.replace(/_/g, ' ')const typeLabel = source_type.replace(/_/g, ' ')diff --git a/frontend/src/scenes/inbox/InboxScene.stories.tsx b/frontend/src/scenes/inbox/InboxScene.stories.tsxnew file mode 100644index 000000000000..33d731803557--- /dev/null+++ b/frontend/src/scenes/inbox/InboxScene.stories.tsx@@ -0,0 +1,73 @@+import type { Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import {+ allReports,+ mockArtefacts,+ mockReportTasks,+ mockReviewers,+ mockSignals,+ mockSourceConfigs,+ mockTask,+} from './__mocks__/inboxMocks'+import { InboxScene } from './InboxScene'++// Full Inbox scene with a populated report list. Use this to polish the holistic+// layout: header, tab bar + single border, scope picker, filter bar, and the+// centered list column. Switch tabs / scope inside the story to exercise each view.++const sceneMocks = mswDecorator({+ get: {+ '/api/projects/:id/signals/reports': () => [+ 200,+ { results: allReports, count: allReports.length, next: null, previous: null },+ ],+ '/api/projects/:id/signals/reports/available_reviewers': () => [200, mockReviewers],+ '/api/projects/:id/signals/reports/:reportId/artefacts': (req) => [+ 200,+ mockArtefacts(req.params.reportId as string),+ ],+ '/api/projects/:id/signals/reports/:reportId/signals': (req) => [+ 200,+ { report: null, signals: mockSignals(req.params.reportId as string, 4) },+ ],+ '/api/projects/:id/signals/reports/:reportId/tasks': (req) => [+ 200,+ mockReportTasks(req.params.reportId as string),+ ],+ '/api/projects/:id/tasks/:taskId': (req) => [200, mockTask(req.params.taskId as string)],+ '/api/projects/:id/signals/source_configs': () => [200, mockSourceConfigs],+ '/api/projects/:id/external_data_sources': () => [200, { results: [], count: 0 }],+ '/api/projects/:id/external_data_sources/': () => [200, { results: [], count: 0 }],+ },+})++const meta: Meta = {+ title: 'Scenes-App/Inbox/Scene',+ component: InboxScene,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-06-11',+ // The scene shell keeps a loader element mounted past the VR wait window, so don't block on it.+ testOptions: { waitForLoadersToDisappear: false },+ },+ decorators: [sceneMocks],+}+export default meta++type Story = StoryObj++export const Inbox: Story = {}++export const Empty: Story = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:id/signals/reports': () => [200, { results: [], count: 0, next: null, previous: null }],+ '/api/projects/:id/signals/source_configs': () => [200, { results: [], count: 0 }],+ },+ }),+ ],+}diff --git a/frontend/src/scenes/inbox/InboxScene.tsx b/frontend/src/scenes/inbox/InboxScene.tsxindex 74e734b76010..5a8b8c8ec429 100644--- a/frontend/src/scenes/inbox/InboxScene.tsx+++ b/frontend/src/scenes/inbox/InboxScene.tsx@@ -1,776 +1,145 @@-import clsx from 'clsx'import { useActions, useValues } from 'kea'-import { useEffect, useRef, useState } from 'react'-import {- IconArrowLeft,- IconBug,- IconCheck,- IconChevronRight,- IconFilter,- IconGear,- IconInfo,- IconNotification,- IconRefresh,- IconSearch,- IconSparkles,- IconWarning,- IconX,-} from '@posthog/icons'-import {- LemonBadge,- LemonBanner,- LemonButton,- LemonCheckbox,- LemonDropdown,- LemonInput,- LemonMenuOverlay,- LemonSkeleton,- LemonTabs,- LemonTag,- Link,- Spinner,- Tooltip,-} from '@posthog/lemon-ui'+import { IconBug } from '@posthog/icons'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'-import { GraphsHog, PopUpBinocularsHog } from 'lib/components/hedgehogs'-import { ResizableElement } from 'lib/components/ResizeElement/ResizeElement'-import { TZLabel } from 'lib/components/TZLabel'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { IconArrowDown } from 'lib/lemon-ui/icons'-import { More } from 'lib/lemon-ui/LemonButton/More'-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture/ProfilePicture'-import { statusBadgeColor } from 'scenes/debug/signals/helpers'-import type { SignalNode } from 'scenes/debug/signals/types'-import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { SceneExport } from 'scenes/sceneTypes'-import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { AgentRunDetail } from './components/detail/AgentRunDetail'+import { InboxDetailHeader } from './components/detail/InboxDetailHeader'+import { ReportDetail, ReportDetailSkeleton } from './components/detail/ReportDetail'+import { AgentSetupColumn } from './components/shell/AgentSetupColumn'+import { InboxScopeSelect } from './components/shell/InboxScopeSelect'+import { InboxTabBar } from './components/shell/InboxTabBar'+import { NotActionableTab } from './components/tabs/NotActionableTab'+import { PullRequestsTab } from './components/tabs/PullRequestsTab'+import { ReportsTab } from './components/tabs/ReportsTab'+import { RunsTab } from './components/tabs/RunsTab'import { inboxSceneLogic } from './inboxSceneLogic'-import { SignalCard } from './SignalCard'-import { SignalGraphTab } from './SignalGraphTab'-import { signalSourcesLogic } from './signalSourcesLogic'-import { SourcesModal } from './SourcesModal'-import { EnrichedReviewer, SignalReport, SignalReportArtefact, SignalReportStatus } from './types'+import { InboxTabKey, SignalReport } from './types'export const scene: SceneExport = {component: InboxScene,logic: inboxSceneLogic,}-function ReportListItem({ report }: { report: SignalReport }): JSX.Element {- const { selectedReportId } = useValues(inboxSceneLogic)- const { setSelectedReportId } = useActions(inboxSceneLogic)+/** Min scene-container width at which the setup rail fits beside the list. */+const SETUP_RAIL_MIN_PX = 1024- const isSelected = selectedReportId === report.id-- return (- <Link- to={urls.inbox(report.id)}- onClick={- isSelected- ? (e) => {- e.preventDefault()- setSelectedReportId(null)- }- : undefined- }- className={clsx(- `w-full text-left px-3 py-2.5 flex items-start gap-2 cursor-pointer rounded border overflow-hidden`,- report.is_suggested_reviewer- ? 'border-primary bg-primary-alt-highlight'- : isSelected- ? 'border-primary bg-surface-primary'- : 'border-primary bg-surface-secondary hover:bg-surface-tertiary'- )}- >- <div className="flex-1 min-w-0">- <h4 className="text-sm font-medium m-0 truncate flex-1 flex items-center gap-1.5">- {report.is_suggested_reviewer && <ProfilePicture size="xs" showName={false} />}- {report.title || <i>Untitled report</i>}- </h4>-- {report.summary && (- <p- className={clsx(- 'text-xs mt-0.5 m-0 line-clamp-2',- selectedReportId === report.id ? 'text-secondary' : 'text-tertiary'- )}- >- {report.summary}- </p>- )}-- <div className="flex items-center gap-2 mt-1.5 text-xs text-tertiary whitespace-nowrap">- {report.relevant_user_count !== null && report.relevant_user_count > 0 && (- <span>- {report.relevant_user_count} {report.relevant_user_count === 1 ? 'user' : 'users'}- </span>- )}- {report.signal_count > 0 && (- <span>- {report.signal_count} {report.signal_count === 1 ? 'signal' : 'signals'}- </span>- )}- <LemonTag size="small">Weight: {report.total_weight.toFixed(1)}</LemonTag>-- <span className="grow shrink-0 flex justify-end">- <TZLabel title="Report last updated at" time={report.updated_at} />- </span>- </div>- </div>- </Link>- )-}--function ReportListSkeleton({ active = true }: { active?: boolean }): JSX.Element {- return (- <div className="flex flex-col gap-2">- {Array.from({ length: 8 }).map((_, i) => (- <div key={i} className="px-3 py-2.5 rounded border border-primary">- <LemonSkeleton className="w-3/5 h-4" active={active} />- <LemonSkeleton className="w-full h-3 mt-1" active={active} />- <LemonSkeleton className="w-4/5 h-3 mt-0.5" active={active} />- <div className="flex items-center gap-2 mt-1.5">- <LemonSkeleton className="w-12 h-3" active={active} />- <LemonSkeleton className="w-14 h-3" active={active} />- <LemonSkeleton className="w-16 h-5 rounded-sm" active={active} />- <LemonSkeleton className="w-20 h-3 ml-auto" active={active} />- </div>- </div>- ))}- </div>- )-}--const STATUS_OPTIONS = Object.values(SignalReportStatus)--const STATUS_LABELS: Record<SignalReportStatus, string> = {- [SignalReportStatus.POTENTIAL]: 'Potential',- [SignalReportStatus.CANDIDATE]: 'Candidate',- [SignalReportStatus.IN_PROGRESS]: 'In progress',- [SignalReportStatus.PENDING_INPUT]: 'Pending input',- [SignalReportStatus.READY]: 'Ready',- [SignalReportStatus.RESOLVED]: 'Resolved',- [SignalReportStatus.FAILED]: 'Failed',+/** Tabs that show the centered report list (scope chrome in the header). Runs/Configuration are special. */+function isReportListTab(tab: InboxTabKey): boolean {+ return tab === 'pulls' || tab === 'reports' || tab === 'not-actionable'}-function StatusFilter(): JSX.Element {- const { statusFilters } = useValues(inboxSceneLogic)- const { setStatusFilters } = useActions(inboxSceneLogic)- const [showPopover, setShowPopover] = useState(false)-- const isAllSelected = statusFilters.length === STATUS_OPTIONS.length- const isSomeSelected = statusFilters.length > 0 && statusFilters.length < STATUS_OPTIONS.length-- const handleToggleAll = (): void => {- if (isAllSelected || isSomeSelected) {- setStatusFilters([])- } else {- setStatusFilters([...STATUS_OPTIONS])- }- }-- const handleToggleStatus = (status: SignalReportStatus): void => {- const newStatuses = statusFilters.includes(status)- ? statusFilters.filter((s) => s !== status)- : [...statusFilters, status]- setStatusFilters(newStatuses)+function ActiveTabBody({ tab, runsReports }: { tab: InboxTabKey; runsReports: SignalReport[] }): JSX.Element {+ switch (tab) {+ case 'pulls':+ return <PullRequestsTab />+ case 'reports':+ return <ReportsTab />+ case 'not-actionable':+ return <NotActionableTab />+ case 'runs':+ return <RunsTab reports={runsReports} />+ case 'config':+ return <AgentSetupColumn layout="stacked" />}-- const displayValue = (): string => {- if (statusFilters.length === 0 || isAllSelected) {- return 'All statuses'- }- if (statusFilters.length === 1) {- return STATUS_LABELS[statusFilters[0]]- }- return `${statusFilters.length} statuses`- }-- return (- <LemonDropdown- closeOnClickInside={false}- visible={showPopover}- matchWidth={false}- actionable- onVisibilityChange={setShowPopover}- overlay={- <div className="max-w-60 space-y-px p-1">- <LemonButton fullWidth size="small" onClick={handleToggleAll} className="justify-start">- <span className="flex items-center gap-2">- <LemonCheckbox checked={isAllSelected} className="pointer-events-none" />- <span className="font-semibold">- {isAllSelected || isSomeSelected ? 'Clear all' : 'Select all'}- </span>- </span>- </LemonButton>- <div className="border-t border-border my-1" />- {STATUS_OPTIONS.map((status) => (- <LemonButton- key={status}- fullWidth- size="small"- onClick={() => handleToggleStatus(status)}- className="justify-start"- >- <span className="flex items-center gap-2">- <LemonCheckbox- checked={statusFilters.includes(status)}- className="pointer-events-none"- />- <span className={clsx('w-2 h-2 rounded-full shrink-0', statusBadgeColor(status))} />- <span>{STATUS_LABELS[status]}</span>- </span>- </LemonButton>- ))}- </div>- }- >- <LemonButton type="secondary" size="small" icon={<IconFilter />} className="bg-surface-primary">- {displayValue()}- </LemonButton>- </LemonDropdown>- )}-function ReportListPane(): JSX.Element {- const {- filteredReports,- reportsLoading,- searchQuery,- reports,- selectedReportId,- shouldShowEnablingCtaOnMobile,- statusFilters,- reportsHasMore,- } = useValues(inboxSceneLogic)- const { hasNoSources } = useValues(signalSourcesLogic)- const { setSearchQuery, loadMoreReports, loadReports } = useActions(inboxSceneLogic)- const { openSourcesModal } = useActions(signalSourcesLogic)- const scrollRef = useRef<HTMLDivElement>(null)- const [isScrollable, setIsScrollable] = useState(false)-- useEffect(() => {- const el = scrollRef.current- if (!el) {- return- }- const scrollabilityCheck = (): void => setIsScrollable(el.scrollHeight > el.clientHeight)- scrollabilityCheck()- const observer = new ResizeObserver(scrollabilityCheck)- observer.observe(el)- return () => observer.disconnect()- }, [filteredReports.length])-- return (- <ResizableElement- defaultWidth={420}- minWidth={280}- maxWidth={600}- borderPosition="right"- onResize={() => {}}- className={clsx(- 'flex-shrink-0 h-full',- '@3xl/main-content-container:max-w-[50%] @3xl/main-content-container:border-r border-primary',- (selectedReportId != null || shouldShowEnablingCtaOnMobile) &&- 'hidden @3xl/main-content-container:block'- )}- >- <div ref={scrollRef} className="h-full p-3 overflow-y-auto">- <div className="flex gap-2 sticky top-0 z-10 mb-2">- <LemonInput- type="search"- placeholder="Search reports..."- prefix={<IconSearch />}- value={searchQuery}- onChange={setSearchQuery}- size="small"- fullWidth- disabledReason={- reportsLoading && reports.length === 0 && !searchQuery ? 'Loading reports...' : null- }- />- <StatusFilter />- <LemonButton- type="secondary"- size="small"- icon={<IconRefresh />}- loading={reportsLoading}- onClick={() => loadReports()}- tooltip="Refresh reports"- className="bg-surface-primary"- />- </div>- {hasNoSources && filteredReports.length > 0 && (- <LemonBanner- type="info"- action={{ children: 'Set up sources now', onClick: openSourcesModal, icon: <IconGear /> }}- className="mb-2"- >- No signal sources enabled currently.- <br />- Set up sources to get new reports automatically.- </LemonBanner>- )}- <div className="flex flex-col gap-2">- {reportsLoading && reports.length === 0 ? (- <div className="relative overflow-hidden max-h-[calc(100vh-14rem)]">- <ReportListSkeleton />- <div className="pointer-events-none absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-primary to-transparent" />- </div>- ) : filteredReports.length === 0 ? (- <div className="relative overflow-hidden max-h-[calc(100vh-14rem)]">- <ReportListSkeleton active={false} />- <div className="pointer-events-none absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-primary to-transparent" />- <div className="absolute inset-0 flex flex-col items-center justify-center">- <p className="text-sm text-secondary font-medium m-0 cursor-default">- {searchQuery || statusFilters.length > 0- ? 'No reports matching filters.'- : 'No reports yet.'}- </p>- </div>- </div>- ) : (- <>- {filteredReports.map((report: SignalReport) => (- <ReportListItem key={report.id} report={report} />- ))}- {reportsHasMore && (- <LemonButton- type="secondary"- size="small"- fullWidth- center- loading={reportsLoading}- onClick={() => loadMoreReports()}- className="mt-1"- >- Load more- </LemonButton>- )}- {isScrollable && filteredReports.length > 0 && !reportsHasMore && (- <Tooltip title="You've reached the end, friend." delayMs={0} placement="right">- <PopUpBinocularsHog className="-mb-3.5 mt-1 w-16 self-center h-auto object-bottom" />- </Tooltip>- )}- </>- )}- </div>- </div>- </ResizableElement>+/**+ * List view: a tab bar + scope select over the active tab's body, with the agent-setup+ * widgets to the right as a rail when the scene is wide enough (≥ ~72rem). Below that width+ * the rail is dropped and the widgets live in a Configuration tab instead. Each flat report+ * tab (Pull requests / Reports / Not actionable) owns its own filtered request, count,+ * search/filter chrome, and pagination via the keyed `reportListLogic`. Runs is project-wide+ * and chrome-less.+ */+function InboxListView(): JSX.Element {+ const { activeTab, runsTabReports } = useValues(inboxSceneLogic)+ const { ref: widthRef, size } = useResizeBreakpoints(+ { 0: 'narrow', [SETUP_RAIL_MIN_PX]: 'wide' },+ { initialSize: 'wide' })-}--function JudgmentBadges({ artefacts }: { artefacts: SignalReportArtefact[] }): JSX.Element | null {- const [expanded, setExpanded] = useState(false)-- const safetyArtefact = artefacts.find((a) => a.type === 'safety_judgment')- const actionabilityArtefact = artefacts.find((a) => a.type === 'actionability_judgment')-- if (!safetyArtefact && !actionabilityArtefact) {- return null- }-- const safetyContent = safetyArtefact?.content as Record<string, unknown> | undefined- const actionabilityContent = actionabilityArtefact?.content as Record<string, unknown> | undefined-- const isSafe = safetyContent?.safe === true || safetyContent?.judgment === 'safe'- const actionabilityJudgment = (actionabilityContent?.judgment as string) ?? ''+ const showRail = size === 'wide'+ // The rail and the Configuration tab are mutually exclusive – never leave 'config' active+ // (e.g. via a deep link) while the rail shows, or the rail and a config body would both appear.+ const effectiveTab = showRail && activeTab === 'config' ? 'pulls' : activeTabreturn (- <div className="border rounded bg-surface-primary mb-3">- <button- type="button"- className="w-full flex items-center gap-2 px-3 py-2 text-left cursor-pointer hover:bg-surface-tertiary rounded"- onClick={() => setExpanded(!expanded)}- >- <span className="text-xs font-medium text-tertiary shrink-0">LLM judgment:</span>- <div className="flex items-center gap-1.5 flex-wrap flex-1">- {safetyArtefact && (- <LemonTag size="small" type={isSafe ? 'success' : 'danger'}>- {isSafe ? <IconCheck className="size-3" /> : <IconWarning className="size-3" />}- <span className="ml-0.5">{isSafe ? 'Safe' : 'Unsafe'}</span>- </LemonTag>- )}- {actionabilityArtefact && (- <LemonTag- size="small"- type={- actionabilityJudgment === 'immediately_actionable'- ? 'success'- : actionabilityJudgment === 'requires_human_input'- ? 'caution'- : 'muted'- }- >- {actionabilityJudgment === 'immediately_actionable' ? (- <IconCheck className="size-3" />- ) : actionabilityJudgment === 'requires_human_input' ? (- <IconWarning className="size-3" />- ) : (- <IconX className="size-3" />- )}- <span className="ml-0.5">- {actionabilityJudgment === 'immediately_actionable'- ? 'Immediately actionable'- : actionabilityJudgment === 'requires_human_input'- ? 'Requires human input'- : 'Not actionable'}- </span>- </LemonTag>+ <div ref={widthRef} className="flex min-h-0 flex-1">+ <div className="flex flex-col min-h-0 flex-1 min-w-0">+ {/* pl-5 (20px) aligns the first tab label with the SceneTitleSection description above. */}+ <div className="flex items-end justify-between gap-2 border-b border-primary pl-5 pr-2 shrink-0">+ <InboxTabBar showConfigTab={!showRail} />+ {isReportListTab(effectiveTab) && (+ <div className="pb-1.5">+ <InboxScopeSelect />+ </div>)}</div>- <IconChevronRight- className={clsx('size-4 text-tertiary transition-transform shrink-0', expanded && 'rotate-90')}- />- </button>- {expanded && (- <div className="px-3 pb-3 space-y-2 text-sm text-secondary">- {safetyContent?.explanation ? (- <div>- <span className="font-medium text-xs text-tertiary">Safety:</span>- <LemonMarkdown className="mt-0.5">{String(safetyContent.explanation)}</LemonMarkdown>- </div>- ) : null}- {actionabilityContent?.explanation ? (- <div>- <span className="font-medium text-xs text-tertiary">Actionability:</span>- <LemonMarkdown className="mt-0.5">{String(actionabilityContent.explanation)}</LemonMarkdown>- </div>- ) : null}+ <div className="flex-1 overflow-auto min-h-0">+ <ActiveTabBody tab={effectiveTab} runsReports={runsTabReports} /></div>- )}- </div>- )-}--function SuggestedReviewers({ reviewers }: { reviewers: EnrichedReviewer[] }): JSX.Element | null {- if (reviewers.length === 0) {- return null- }-- return (- <div className="border rounded bg-surface-primary mb-3 px-3 py-2 space-y-1.5">- <div className="text-xs font-medium text-tertiary">Suggested reviewers</div>- <div className="flex flex-col gap-1.5">- {reviewers.map((reviewer) => {- const displayName = reviewer.user?.first_name || reviewer.github_name || reviewer.github_login-- return (- <div key={reviewer.github_login} className="flex items-center gap-1.5">- <Tooltip- title={- reviewer.user- ? undefined- : `${displayName} hasn't connected their GitHub account to PostHog. Ask them to do so in Settings!`- }- >- <span className={!reviewer.user ? 'opacity-75' : undefined}>- <PersonDisplay- person={{- properties: {- email: reviewer.user?.email,- name: displayName,- },- }}- displayName={displayName}- withIcon="xs"- noLink- noPopover- />- </span>- </Tooltip>- <Link- to={`https://github.com/${reviewer.github_login}`}- target="_blank"- className="text-xs text-muted hover:text-primary shrink-0"- >- @{reviewer.github_login}- </Link>- {reviewer.relevant_commits.length > 0 && (- <span className="text-[0.6875rem] text-tertiary">- {reviewer.relevant_commits.map((commit, i) => (- <span key={commit.sha}>- {i > 0 && ', '}- <Tooltip title={commit.reason || undefined}>- <Link- to={commit.url}- target="_blank"- className="font-mono text-tertiary hover:text-primary"- >- {commit.sha.slice(0, 7)}- </Link>- </Tooltip>- </span>- ))}- </span>- )}- </div>- )- })}</div>+ {showRail && (+ <aside className="shrink-0 w-80 overflow-auto min-h-0 border-l border-primary">+ <AgentSetupColumn layout="rail" />+ </aside>+ )}</div>)}-function ReportDetailPane(): JSX.Element {- const {- selectedReport,- shouldShowEnablingCtaOnMobile,- artefacts,- activeDetailTab,- selectedReportSignals,- reportSignalsLoading,- selectedReportReviewers,- } = useValues(inboxSceneLogic)- const { deleteReport, reingestReport, setActiveDetailTab } = useActions(inboxSceneLogic)- const { hasNoSources } = useValues(signalSourcesLogic)- const { openSourcesModal } = useActions(signalSourcesLogic)+/**+ * Detail view: replaces the list full-width. Report / PR / Not actionable render the unified+ * `ReportDetail`, which owns its own merged header (back link, title, copy link). The Runs view+ * keeps `AgentRunDetail` under the shared `InboxDetailHeader`.+ */+function InboxDetailView({ report }: { report: SignalReport }): JSX.Element {+ const { activeTab } = useValues(inboxSceneLogic)- const baseClasses = 'flex-1 p-4 min-w-0 h-full self-start bg-surface-primary flex flex-col overflow-y-auto'-- if (!selectedReport) {+ if (activeTab === 'runs') {return (- <div- className={clsx(- baseClasses,- `items-center justify-center p-8 cursor-default overflow-y-auto`,- // If user has no sources and no reports, always show the CTA area on mobile- !shouldShowEnablingCtaOnMobile && 'hidden @3xl/main-content-container:flex'- )}- >- <GraphsHog className="w-36 mb-8" />- <h3 className="text-xl font-bold mb-4 text-center">- Welcome to your Inbox- <sup>- <IconSparkles className="ml-0.5 text-ai" />- </sup>- </h3>- <div className="flex flex-col items-center gap-1.5 text-center text-xs text-secondary max-w-md leading-normal">- <div>- <strong>Background analysis of your data - while you sleep.</strong>- <br />- Powerful new analysis of sessions watches every recording for you. Integrations with external- sources on the way: issue trackers, support platforms, and more.- </div>- <IconArrowDown className="size-4 opacity-50" />- <div>- <strong>Inbox hands you ready-to-run fixes for real user problems.</strong>- <br />- Just execute the resulting prompt in your favorite coding agent. Each fix's report comes with- hard evidence and impact numbers.- </div>- </div>- {hasNoSources && (- <LemonButton type="primary" onClick={openSourcesModal} icon={<IconNotification />} className="mt-4">- Enable Inbox now- </LemonButton>- )}+ <div className="flex flex-col min-h-0 flex-1 overflow-auto">+ <InboxDetailHeader report={report} tab={activeTab} />+ <AgentRunDetail report={report} /></div>)}- const reportArtefacts = artefacts[selectedReport.id]-return (- <div className={baseClasses} key={selectedReport.id}>- <div className="max-w-200 w-full border border-border-light rounded-lg mx-auto">- {/* Header — always visible above tabs */}- <div className="shrink-0 pt-6 pb-2 px-6">- <Link- to={urls.inbox()}- className="inline-flex items-center gap-1 text-sm text-secondary mb-4 @3xl/main-content-container:hidden"- >- <IconArrowLeft className="size-4" />- All reports- </Link>- <div>- <h2 className="text-xl font-medium mb-4 flex-1 leading-tight">- {selectedReport.title || 'Untitled report'}- </h2>- {selectedReport.summary && (- <LemonMarkdown className="text-sm text-secondary mb-0 mt-2 leading-normal">- {selectedReport.summary}- </LemonMarkdown>- )}- <div className="flex items-center gap-4 mt-4 text-xs text-tertiary cursor-default">- {selectedReport.relevant_user_count !== null && selectedReport.relevant_user_count > 0 && (- <span>- {selectedReport.relevant_user_count}{' '}- {selectedReport.relevant_user_count === 1 ? 'user' : 'users'}- </span>- )}- {selectedReport.signal_count > 0 && (- <span>- {selectedReport.signal_count}{' '}- {selectedReport.signal_count === 1 ? 'signal' : 'signals'}- </span>- )}- <Tooltip- title="Each signal adds weight to the report, depending on the signal's value and confidence. When a report reaches weight >=1.0, it's investigated by an AI agent."- delayMs={0}- >- Weight: {selectedReport.total_weight.toFixed(1)} <IconInfo className="size-3 ml-0.5" />- </Tooltip>- <span className="inline-flex items-center gap-1">- Created: <TZLabel time={selectedReport.created_at} />- </span>- <span className="inline-flex items-center gap-1">- Updated: <TZLabel time={selectedReport.updated_at} />- </span>- <More- overlay={- <LemonMenuOverlay- items={[- {- label: 'Re-ingest signals',- onClick: () =>- LemonDialog.open({- title: `Re-ingest signals from "${selectedReport.title}"?`,- className: 'max-w-120',- description:- 'This will delete the report, then re-run all its signals through the grouping pipeline. Signals may end up in different reports.',- primaryButton: {- children: 'Re-ingest signals',- onClick: () => reingestReport(selectedReport.id),- },- secondaryButton: {- children: 'Cancel',- },- }),- },- {- label: 'Delete report & signals',- status: 'danger',- onClick: () =>- LemonDialog.open({- title: `Delete report "${selectedReport.title}"?`,- className: 'max-w-120',- description:- 'This will delete all signals in this report and remove the report. Report deletion cannot be undone.',- primaryButton: {- children: 'Delete report & signals',- status: 'danger',- onClick: () => deleteReport(selectedReport.id),- },- secondaryButton: {- children: 'Cancel',- },- }),- },- ]}- />- }- />- </div>- </div>- </div>-- <LemonTabs- activeKey={activeDetailTab}- onChange={setActiveDetailTab}- barClassName="px-6 mb-0 [--color-border-primary:var(--border-light)]"- tabs={[- {- key: 'overview',- label: 'Overview',- content: (- <div className="p-6 max-w-200 w-full">- {reportArtefacts && reportArtefacts.length > 0 && (- <JudgmentBadges artefacts={reportArtefacts} />- )}- {selectedReportReviewers && selectedReportReviewers.length > 0 && (- <SuggestedReviewers reviewers={selectedReportReviewers} />- )}- {/* Signal cards as primary content */}- {reportSignalsLoading && !selectedReportSignals ? (- <div className="items-center gap-2 text-sm text-tertiary py-4">- <Spinner className="size-4" />- Loading signals...- </div>- ) : selectedReportSignals && selectedReportSignals.length > 0 ? (- <div className="space-y-3">- {selectedReportSignals.map((signal: SignalNode) => (- <SignalCard key={signal.signal_id} signal={signal} />- ))}- </div>- ) : (- <p className="text-sm text-tertiary m-0">No signals yet.</p>- )}- </div>- ),- },- {- key: 'signals',- label: `Signals graph`,- content: (- <div className="flex-1 overflow-hidden">- {reportSignalsLoading && !selectedReportSignals ? (- <div className="items-center justify-center h-full gap-2 text-sm text-tertiary">- <Spinner className="size-4" />- Loading signals...- </div>- ) : selectedReportSignals && selectedReportSignals.length > 0 ? (- <SignalGraphTab signals={selectedReportSignals} />- ) : (- <p className="text-sm text-tertiary m-0 p-6">No signals yet.</p>- )}- </div>- ),- },- ]}- />- </div>+ <div className="flex flex-col min-h-0 flex-1 overflow-auto">+ <ReportDetail report={report} tab={activeTab} /></div>)}export function InboxScene(): JSX.Element {- const { isRunningSessionAnalysis } = useValues(inboxSceneLogic)+ const { isRunningSessionAnalysis, selectedReportId, selectedReport, selectedReportLoading } =+ useValues(inboxSceneLogic)const { runSessionAnalysis } = useActions(inboxSceneLogic)- const { enabledSourcesCount } = useValues(signalSourcesLogic)- const { openSourcesModal } = useActions(signalSourcesLogic)const { isDev } = useValues(preflightLogic)- const isProductAutonomyEnabled = useFeatureFlag('PRODUCT_AUTONOMY')- if (!isProductAutonomyEnabled) {- return (- <div className="flex flex-col items-center justify-center max-w-[50rem] px-4 mx-auto text-center text-balance h-full">- <GraphsHog className="w-36 mb-2" />- <h1 className="text-2xl font-bold mt-4 mb-0">Inbox is now available in the PostHog Code desktop app</h1>- <p className="text-sm font-semibold italic mt-3 mb-0">- PostHog Code brings Inbox and agentic development right to your desktop.- </p>- <div className="flex justify-center mt-4">- <LemonButton- type="primary"- to="https://posthog.com/code?utm_source=app&utm_medium=in-product&utm_campaign=inbox-cta"- targetBlank- >- Download here- </LemonButton>- </div>- </div>- )- }+ // Detail route renders full-width over the list (desktop parity), but the list view stays *mounted*+ // (just hidden) rather than being unmounted. That keeps `reportListLogic` and the scroll container+ // alive, so clicking "back" lands on the same scroll position with the same loaded pages — instead of+ // remounting and resetting to the first page at the top.+ const showDetail = !!selectedReportIdreturn (- <SceneContent className="gap-y-0 border-b-0">- <SourcesModal />- <SceneTitleSection- name="Inbox"- description={null}- resourceType={{ type: 'inbox' }}- actions={- <div className="flex items-center gap-2">- {isDev && (+ <SceneContent className="gap-y-0 border-b-0 flex-1 min-h-0">+ <div className={showDetail ? 'hidden' : 'flex flex-col gap-y-2 flex-1 min-h-0'}>+ <SceneTitleSection+ name="Inbox"+ description="Work done by your agents – pull requests, reports, and live runs."+ resourceType={{ type: 'inbox' }}+ actions={+ isDev ? (<Tooltip title="Analyze the last 7 days of sessions"><LemonButtontype="secondary"@@ -784,24 +153,30 @@ export function InboxScene(): JSX.Element {Run session analysis</LemonButton></Tooltip>- )}- <LemonButton- type="secondary"- size="small"- icon={<IconGear />}- onClick={openSourcesModal}- sideIcon={<LemonBadge.Number count={enabledSourcesCount} status="muted" size="small" />}- >- Edit sources- </LemonButton>- </div>- }- />+ ) : undefined+ }+ />- <div className="flex items-start -mx-4 h-[calc(100vh-6.375rem+1px)]">- <ReportListPane />- <ReportDetailPane />+ <div className="flex flex-col -mx-4 flex-1 min-h-0">+ <InboxListView />+ </div></div>++ {showDetail && (+ <div className="flex flex-col -mx-4 flex-1 min-h-0">+ {selectedReport ? (+ <InboxDetailView report={selectedReport} />+ ) : selectedReportLoading ? (+ <div className="flex flex-col min-h-0 flex-1 overflow-auto">+ <ReportDetailSkeleton />+ </div>+ ) : (+ <div className="flex flex-1 items-center justify-center text-sm text-tertiary">+ Report not found.+ </div>+ )}+ </div>+ )}</SceneContent>)}diff --git a/frontend/src/scenes/inbox/SignalCard.tsx b/frontend/src/scenes/inbox/SignalCard.tsxindex cd9670983d09..5aded1cce820 100644--- a/frontend/src/scenes/inbox/SignalCard.tsx+++ b/frontend/src/scenes/inbox/SignalCard.tsx@@ -1,314 +1,15 @@-import clsx from 'clsx'-import { useState } from 'react'--import { IconChevronRight, IconExternal, IconWarning } from '@posthog/icons'-import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'--import { TZLabel } from 'lib/components/TZLabel'-import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'-import { signalCardSourceLine } from 'lib/signals/signalCardSourceLine'-import { humanFriendlyDetailedTime } from 'lib/utils/datetime'-import { sourceProductColor } from 'scenes/debug/signals/helpers'import type { SignalNode } from 'scenes/debug/signals/types'-import { urls } from 'scenes/urls'-import type {- ErrorTrackingSignalExtra,- GithubIssueSignalExtra,- LlmEvalSignalExtra,- SessionSegmentClusterSignalExtra,- ZendeskTicketSignalExtra,-} from '~/queries/schema/schema-signals'+import { GenericSignalCard } from './components/signalCards/GenericSignalCard'+import { SIGNAL_CARD_REGISTRY } from './components/signalCards/registry'+/**+ * Renders a single signal as evidence in a report/PR detail view. Dispatches to a per-source card+ * via `SIGNAL_CARD_REGISTRY` (first matching entry wins), falling back to `GenericSignalCard` for+ * sources without a dedicated renderer.+ */export function SignalCard({ signal }: { signal: SignalNode }): JSX.Element {- if (signal.source_product === 'error_tracking' && isErrorTrackingExtra(signal.extra)) {- return <ErrorTrackingSignalCard signal={signal} extra={signal.extra} />- }- if (isSessionReplayExtra(signal.extra)) {- return <SessionReplaySignalCard signal={signal} extra={signal.extra} />- }- if (isGithubIssueExtra(signal.extra)) {- return <GithubIssueSignalCard signal={signal} extra={signal.extra} />- }- if (isZendeskTicketExtra(signal.extra)) {- return <ZendeskTicketSignalCard signal={signal} extra={signal.extra} />- }- if (isLlmEvalExtra(signal.extra)) {- return <LlmEvalSignalCard signal={signal} extra={signal.extra} />- }- return <GenericSignalCard signal={signal} />-}--function SessionReplaySignalCard({- signal,- extra,-}: {- signal: SignalNode- extra: SessionSegmentClusterSignalExtra-}): JSX.Element {- const [showAllSegments, setShowAllSegments] = useState(false)- const maxVisible = 3- const visibleSegments = showAllSegments ? extra.segments : extra.segments.slice(0, maxVisible)-- return (- <div className="border rounded p-3 bg-surface-primary">- <SignalCardHeader signal={signal} label={extra.label_title} />-- {signal.content && <LemonMarkdown className="text-sm text-secondary mb-2">{signal.content}</LemonMarkdown>}-- <div className="flex items-center gap-2 text-xs text-tertiary mb-3">- {extra.metrics.occurrence_count > 0 && (- <span>- {extra.metrics.occurrence_count}{' '}- {extra.metrics.occurrence_count === 1 ? 'occurrence' : 'occurrences'}- </span>- )}- {extra.metrics.relevant_user_count > 0 && (- <span>- {extra.metrics.relevant_user_count} affected{' '}- {extra.metrics.relevant_user_count === 1 ? 'user' : 'users'}- </span>- )}- <LemonTag size="small" type={extra.actionable ? 'success' : 'muted'}>- {extra.actionable ? 'Actionable' : 'Not actionable'}- </LemonTag>- </div>-- {extra.segments.length > 0 && (- <>- <div className="border-t pt-2 mt-2">- <span className="text-xs font-medium text-tertiary">Session segments</span>- </div>- <div className="space-y-2 mt-2">- {visibleSegments.map((segment, i) => (- <div key={i} className="border rounded p-2 bg-surface-secondary">- <div className="flex items-start gap-2">- <LemonMarkdown className="text-sm text-secondary flex-1 line-clamp-2">- {segment.content}- </LemonMarkdown>- <ViewRecordingButton- sessionId={segment.session_id}- timestamp={segment.start_time}- openPlayerIn={RecordingPlayerType.Modal}- size="xsmall"- type="secondary"- label="Play"- />- </div>- <div className="flex items-center gap-1.5 mt-1 text-xs text-tertiary">- <span className="font-mono">{segment.distinct_id.slice(0, 10)}...</span>- <span>·</span>- <span>- {humanFriendlyDetailedTime(segment.start_time)} –{' '}- {humanFriendlyDetailedTime(segment.end_time)}- </span>- </div>- </div>- ))}- </div>- {extra.segments.length > maxVisible && (- <LemonButton- size="xsmall"- type="tertiary"- className="mt-1"- onClick={() => setShowAllSegments(!showAllSegments)}- >- {showAllSegments ? 'Show fewer' : `Show all ${extra.segments.length} segments`}- </LemonButton>- )}- </>- )}- </div>- )-}--function GithubIssueSignalCard({ signal, extra }: { signal: SignalNode; extra: GithubIssueSignalExtra }): JSX.Element {- return (- <div className="border rounded p-3 bg-surface-primary">- <SignalCardHeader signal={signal} />-- {signal.content && <LemonMarkdown className="text-sm text-secondary mb-2">{signal.content}</LemonMarkdown>}-- <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary">- <span className="font-medium">#{extra.number}</span>- {Array.isArray(extra.labels) &&- extra.labels.map((label) => (- <LemonTag key={label} size="small">- {label}- </LemonTag>- ))}- <span className="flex-1" />- <Link to={extra.html_url} target="_blank" className="flex items-center gap-1 text-xs">- View on GitHub <IconExternal className="size-3" />- </Link>- </div>- <div className="text-xs text-tertiary mt-1">Opened: {humanFriendlyDetailedTime(extra.created_at)}</div>- </div>- )-}--function ZendeskTicketSignalCard({- signal,- extra,-}: {- signal: SignalNode- extra: ZendeskTicketSignalExtra-}): JSX.Element {- return (- <div className="border rounded p-3 bg-surface-primary">- <SignalCardHeader signal={signal} />-- {signal.content && <LemonMarkdown className="text-sm text-secondary mb-2">{signal.content}</LemonMarkdown>}-- <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary">- <LemonTag size="small">Priority: {extra.priority}</LemonTag>- <LemonTag size="small">Status: {extra.status}</LemonTag>- {Array.isArray(extra.tags) &&- extra.tags.map((tag) => (- <LemonTag key={tag} size="small" type="muted">- {tag}- </LemonTag>- ))}- <span className="flex-1" />- <Link to={extra.url} target="_blank" className="flex items-center gap-1 text-xs">- Open <IconExternal className="size-3" />- </Link>- </div>- </div>- )-}--function LlmEvalSignalCard({ signal, extra }: { signal: SignalNode; extra: LlmEvalSignalExtra }): JSX.Element {- return (- <div className="border rounded p-3 bg-surface-primary">- <SignalCardHeader signal={signal} />-- {signal.content && <LemonMarkdown className="text-sm text-secondary mb-2">{signal.content}</LemonMarkdown>}-- <div className="flex items-center gap-2 text-xs text-tertiary">- <span>Model: {extra.model}</span>- <span>·</span>- <span>Provider: {extra.provider}</span>- </div>- <div className="text-xs text-tertiary mt-1">- Trace: <span className="font-mono">{extra.trace_id.slice(0, 12)}...</span>- </div>- </div>- )-}--function ErrorTrackingSignalCard({- signal,- extra,-}: {- signal: SignalNode- extra: ErrorTrackingSignalExtra-}): JSX.Element {- const fingerprintShort = extra.fingerprint.length > 14 ? `${extra.fingerprint.slice(0, 14)}…` : extra.fingerprint-- return (- <div className="border rounded p-3 bg-surface-primary">- <SignalCardHeader signal={signal} />-- {signal.content && <LemonMarkdown className="text-sm text-secondary mb-2">{signal.content}</LemonMarkdown>}-- <div className="flex flex-wrap items-center gap-2 text-xs text-tertiary">- <span className="inline-flex items-center gap-1">- <IconWarning className="size-3.5 text-warning shrink-0" />- <span>- Fingerprint{' '}- <span className="font-mono text-primary" title={extra.fingerprint}>- {fingerprintShort}- </span>- </span>- </span>- <span className="flex-1" />- <Link- to={urls.errorTrackingIssue(signal.source_id, { fingerprint: extra.fingerprint })}- className="flex items-center gap-1 text-xs font-medium"- >- View issue <IconExternal className="size-3" />- </Link>- </div>- </div>- )-}--function GenericSignalCard({ signal }: { signal: SignalNode }): JSX.Element {- const [showRaw, setShowRaw] = useState(false)-- return (- <div className="border rounded p-3 bg-surface-primary">- <SignalCardHeader signal={signal} />-- {signal.content && <LemonMarkdown className="text-sm text-secondary mb-2">{signal.content}</LemonMarkdown>}-- <div className="text-xs text-tertiary">- <TZLabel time={signal.timestamp} />- </div>-- {Object.keys(signal.extra).length > 0 && (- <div className="mt-2">- <LemonButton- size="xsmall"- type="tertiary"- onClick={() => setShowRaw(!showRaw)}- icon={- <IconChevronRight className={clsx('size-3 transition-transform', showRaw && 'rotate-90')} />- }- >- Raw metadata- </LemonButton>- {showRaw && (- <pre className="text-xs mt-1 p-2 bg-surface-secondary rounded overflow-x-auto max-h-60">- {JSON.stringify(signal.extra, null, 2)}- </pre>- )}- </div>- )}- </div>- )-}--function SignalCardHeader({ signal, label }: { signal: SignalNode; label?: string }): JSX.Element {- return (- <div className="flex items-center gap-2 mb-2">- <span- className="size-2.5 rounded-full shrink-0"- style={{ backgroundColor: sourceProductColor(signal.source_product) }}- />- <span className="text-xs font-medium text-tertiary">{signalCardSourceLine(signal)}</span>- {label && <span className="text-xs font-medium text-primary flex-1 truncate">{label}</span>}- <LemonTag size="small" className="shrink-0">- Weight: {signal.weight.toFixed(1)}- </LemonTag>- </div>- )-}--function isSessionReplayExtra(- extra: Record<string, unknown>-): extra is Record<string, unknown> & SessionSegmentClusterSignalExtra {- return 'segments' in extra && Array.isArray(extra.segments)-}--function isGithubIssueExtra(extra: Record<string, unknown>): extra is Record<string, unknown> & GithubIssueSignalExtra {- return 'html_url' in extra && 'number' in extra-}--function isZendeskTicketExtra(- extra: Record<string, unknown>-): extra is Record<string, unknown> & ZendeskTicketSignalExtra {- return 'url' in extra && 'priority' in extra-}--function isLlmEvalExtra(extra: Record<string, unknown>): extra is Record<string, unknown> & LlmEvalSignalExtra {- return 'evaluation_id' in extra && 'trace_id' in extra-}--function isErrorTrackingExtra(- extra: Record<string, unknown>-): extra is Record<string, unknown> & ErrorTrackingSignalExtra {- return typeof extra.fingerprint === 'string'+ const entry = SIGNAL_CARD_REGISTRY.find((candidate) => candidate.matches(signal))+ const Component = entry?.Component ?? GenericSignalCard+ return <Component signal={signal} />}diff --git a/frontend/src/scenes/inbox/SourcesList.tsx b/frontend/src/scenes/inbox/SourcesList.tsxindex db677aa5aa2a..f36bb6f6e4ac 100644--- a/frontend/src/scenes/inbox/SourcesList.tsx+++ b/frontend/src/scenes/inbox/SourcesList.tsx@@ -214,7 +214,7 @@ export function SourcesList(): JSX.Element {<Sourceicon={<IconHeartPlus className="size-5 text-danger" />}title="PostHog Health checks"- description="Instrumentation issues — missing events, proxy gaps, outdated SDKs → Signals"+ description="Instrumentation issues – missing events, proxy gaps, outdated SDKs → Signals"variant="available"checked={!!healthChecksConfig?.enabled}loading={isHealthChecksToggling}diff --git a/frontend/src/scenes/inbox/SourcesModal.tsx b/frontend/src/scenes/inbox/SourcesModal.tsxdeleted file mode 100644index d3adf1517135..000000000000--- a/frontend/src/scenes/inbox/SourcesModal.tsx+++ /dev/null@@ -1,162 +0,0 @@-import { BindLogic, useActions, useValues } from 'kea'-import { useEffect } from 'react'-import { createPortal } from 'react-dom'--import { IconArrowLeft } from '@posthog/icons'-import { LemonButton, LemonModal, LemonSkeleton } from '@posthog/lemon-ui'--import { AllowTrainingCallout } from 'lib/components/AllowTrainingCallout/AllowTrainingCallout'-import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'--import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'--import { availableSourcesLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/availableSourcesLogic'-import { sourceWizardLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic'-import SourceForm from 'products/data_warehouse/frontend/shared/components/forms/SourceForm'-import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'--import { SessionAnalysisSetup } from './SessionAnalysisSetup'-import { signalSourcesLogic } from './signalSourcesLogic'-import { SourcesList } from './SourcesList'--// Each signal source reads from specific tables — pre-select them and make them required-const SIGNAL_SOURCE_REQUIRED_TABLES: Partial<Record<ExternalDataSourceType, string[]>> = {- Github: ['issues'],- Linear: ['issues'],- Zendesk: ['tickets'],- PgAnalyze: ['issues', 'servers'],-}--export function SourcesModal(): JSX.Element {- const { sourcesModalOpen, sessionAnalysisSetupOpen, dataSourceSetupProduct } = useValues(signalSourcesLogic)- const { closeSourcesModal, closeSessionAnalysisSetup, closeDataSourceSetup, onDataSourceSetupComplete } =- useActions(signalSourcesLogic)- const { trigger: triggerHogfetti, HogfettiComponent } = useHogfetti({ count: 30, duration: 3000 })-- const isDataSourceSetupOpen = dataSourceSetupProduct !== null-- const handleDataSourceComplete = (): void => {- triggerHogfetti()- setTimeout(() => {- triggerHogfetti()- }, 200)- setTimeout(() => {- triggerHogfetti()- }, 400)- onDataSourceSetupComplete(dataSourceSetupProduct!)- }-- return (- <>- <LemonModal- isOpen={sourcesModalOpen}- onClose={closeSourcesModal}- simple- width={sessionAnalysisSetupOpen || isDataSourceSetupOpen ? '48rem' : '32rem'}- >- <LemonModal.Header>- <div className="flex items-center gap-2">- {(sessionAnalysisSetupOpen || isDataSourceSetupOpen) && (- <LemonButton- type="tertiary"- size="small"- icon={<IconArrowLeft />}- onClick={isDataSourceSetupOpen ? closeDataSourceSetup : closeSessionAnalysisSetup}- />- )}- <h3 className="font-semibold mb-0">- {isDataSourceSetupOpen- ? `Connect ${dataSourceSetupProduct}`- : sessionAnalysisSetupOpen- ? 'Session analysis filters'- : 'Signal sources'}- </h3>- </div>- {!sessionAnalysisSetupOpen && !isDataSourceSetupOpen && (- <p className="text-xs text-secondary mt-1 mb-0">Set up sources feeding the Inbox.</p>- )}- </LemonModal.Header>- <LemonModal.Content className={sessionAnalysisSetupOpen ? 'p-0 rounded-b' : ''}>- <AllowTrainingCallout featureName="Inbox" className="mb-5" />- {isDataSourceSetupOpen ? (- <DataSourceSetup product={dataSourceSetupProduct} onComplete={handleDataSourceComplete} />- ) : sessionAnalysisSetupOpen ? (- <SessionAnalysisSetup />- ) : (- <SourcesList />- )}- </LemonModal.Content>- </LemonModal>- {createPortal(- <HogfettiComponent />,- document.body /* Needs to be in portal to be above ReactModalPortal */- )}- </>- )-}--function DataSourceSetup({- product,- onComplete,-}: {- product: ExternalDataSourceType- onComplete: () => void-}): JSX.Element {- const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)-- if (availableSourcesLoading || availableSources === null) {- return <LemonSkeleton />- }-- const sourceConfig = Object.values(availableSources).find((s: SourceConfig) => s.name === product)- if (!sourceConfig) {- return <div>Source not found</div>- }-- return (- <BindLogic- logic={sourceWizardLogic}- props={{- availableSources,- requiredTables: SIGNAL_SOURCE_REQUIRED_TABLES[product],- onComplete,- }}- >- <DataSourceSetupForm sourceConfig={sourceConfig} />- </BindLogic>- )-}--function DataSourceSetupForm({ sourceConfig }: { sourceConfig: SourceConfig }): JSX.Element {- const { isLoading, canGoNext } = useValues(sourceWizardLogic)- const { setInitialConnector, onSubmit } = useActions(sourceWizardLogic)-- // Set up the connector so sourceWizardLogic knows what source type we're connecting- useEffect(() => {- setInitialConnector(sourceConfig)- }, []) // eslint-disable-line react-hooks/exhaustive-deps-- return (- <div className="space-y-4">- <div className="flex items-center gap-3">- <SourceIcon type={sourceConfig.name} size="small" disableTooltip />- <p className="text-sm text-muted-alt mb-0">- Connect {sourceConfig.label ?? sourceConfig.name} as a data source to enable this signal.- </p>- </div>-- <SourceForm sourceConfig={sourceConfig} showPrefix={false} />-- <div className="flex justify-end">- <LemonButton- type="primary"- loading={isLoading}- disabledReason={!canGoNext ? 'Fill in the required fields' : undefined}- onClick={() => onSubmit()}- >- Connect- </LemonButton>- </div>- </div>- )-}diff --git a/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts b/frontend/src/scenes/inbox/__mocks__/inboxMocks.tsnew file mode 100644index 000000000000..f7b868939c9a--- /dev/null+++ b/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts@@ -0,0 +1,423 @@+// Rich mock data for Inbox Storybook stories. Covers the full range of report+// shapes the polish work needs: every priority / actionability / status, the+// three tab types (reports / pull requests / runs), suggested-reviewer ("for+// you") reports, conventional-commit titles, and varying agent-run volume.++import { SignalNode } from 'scenes/debug/signals/types'++import { SignalReport, SignalReportStatus } from '../types'++const BASE_DATE = '2026-06-10T12:00:00Z'++let idCounter = 0+function nextId(): string {+ idCounter += 1+ return `019e64b8-0000-7000-8000-${String(idCounter).padStart(12, '0')}`+}++export function makeReport(overrides: Partial<SignalReport> = {}): SignalReport {+ return {+ id: nextId(),+ title: 'Untitled report',+ summary: null,+ status: SignalReportStatus.READY,+ total_weight: 1.0,+ signal_count: 1,+ relevant_user_count: null,+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ artefact_count: 0,+ is_suggested_reviewer: false,+ priority: null,+ actionability: null,+ already_addressed: null,+ source_products: [],+ implementation_pr_url: null,+ ...overrides,+ }+}++// ── Reports tab ─────────────────────────────────────────────────────────────++export const reportTabReports: SignalReport[] = [+ makeReport({+ title: 'fix(invites): Handle incomplete recipient data in team invite form',+ summary:+ 'Team invite submissions fail when the recipient list is missing an email, throwing a 500 that users see as a generic "Something went wrong".',+ status: SignalReportStatus.READY,+ priority: 'P1',+ actionability: 'immediately_actionable',+ total_weight: 3.4,+ signal_count: 12,+ relevant_user_count: 47,+ source_products: ['error_tracking'],+ is_suggested_reviewer: true,+ }),+ makeReport({+ title: 'fix(billing): Checkout API timeout during payment session creation',+ summary:+ 'Checkout occasionally times out while creating the Stripe payment session, blocking upgrades. Spikes correlate with high-traffic windows.',+ status: SignalReportStatus.READY,+ priority: 'P0',+ actionability: 'immediately_actionable',+ total_weight: 5.8,+ signal_count: 31,+ relevant_user_count: 118,+ source_products: ['error_tracking', 'session_replay'],+ }),+ makeReport({+ title: 'PDF preview render failure for uploaded files',+ summary:+ 'Uploaded PDFs intermittently fail to render a preview, leaving customers unable to inspect files before sharing.',+ status: SignalReportStatus.READY,+ priority: 'P2',+ actionability: 'requires_human_input',+ total_weight: 2.1,+ signal_count: 8,+ relevant_user_count: 23,+ source_products: ['session_replay'],+ is_suggested_reviewer: true,+ }),+ makeReport({+ title: 'feat(onboarding): Users drop off at the SDK install step',+ summary:+ 'A large share of new projects never send a first event – most stall on the SDK install step of onboarding.',+ status: SignalReportStatus.READY,+ priority: 'P3',+ actionability: 'requires_human_input',+ total_weight: 1.6,+ signal_count: 5,+ relevant_user_count: 210,+ source_products: ['session_replay', 'llm_analytics'],+ }),+ makeReport({+ title: 'Slow dashboard load for large cohorts',+ summary:+ 'Dashboards with large cohort filters take 10s+ to load; users abandon before the first insight renders.',+ status: SignalReportStatus.CANDIDATE,+ priority: null,+ actionability: null,+ total_weight: 0.9,+ signal_count: 3,+ relevant_user_count: 14,+ source_products: ['session_replay'],+ }),+ makeReport({+ title: 'Zendesk: recurring "export stuck" tickets',+ summary: null,+ status: SignalReportStatus.CANDIDATE,+ priority: 'P4',+ actionability: 'not_actionable',+ total_weight: 1.2,+ signal_count: 6,+ relevant_user_count: 9,+ source_products: ['zendesk'],+ }),+]++// ── Pull requests tab ───────────────────────────────────────────────────────++export const pullRequestReports: SignalReport[] = [+ makeReport({+ title: 'fix(invites): validate recipient payload before submit',+ summary: 'Adds client + server validation rejecting incomplete invite rows, with a clear inline error.',+ status: SignalReportStatus.READY,+ priority: 'P1',+ actionability: 'immediately_actionable',+ total_weight: 3.4,+ signal_count: 12,+ source_products: ['error_tracking'],+ implementation_pr_url: 'https://github.com/PostHog/posthog/pull/12001',+ is_suggested_reviewer: true,+ }),+ makeReport({+ title: 'fix(billing): add retry + timeout to checkout session creation',+ summary: 'Wraps the Stripe session call in a bounded retry and surfaces a retryable error to the client.',+ status: SignalReportStatus.READY,+ priority: 'P0',+ actionability: 'immediately_actionable',+ total_weight: 5.8,+ signal_count: 31,+ source_products: ['error_tracking'],+ implementation_pr_url: 'https://github.com/PostHog/posthog/pull/12002',+ }),+ makeReport({+ title: 'perf(dashboards): paginate cohort filter resolution',+ summary: 'Resolves large cohort filters in pages to keep dashboard first-render under 2s.',+ status: SignalReportStatus.READY,+ priority: 'P2',+ actionability: 'immediately_actionable',+ total_weight: 2.0,+ signal_count: 7,+ source_products: ['session_replay'],+ implementation_pr_url: 'https://github.com/PostHog/posthog/pull/12003',+ is_suggested_reviewer: true,+ }),+]++// ── Runs tab (queued / live / finished) ─────────────────────────────────────++const queuedRuns: SignalReport[] = [+ makeReport({+ title: 'Investigate spike in 429s from the events API',+ status: SignalReportStatus.POTENTIAL,+ priority: null,+ total_weight: 0.6,+ signal_count: 2,+ source_products: ['error_tracking'],+ }),+ makeReport({+ title: 'Recurring slow query on persons page',+ status: SignalReportStatus.CANDIDATE,+ priority: 'P3',+ total_weight: 1.1,+ signal_count: 4,+ source_products: ['session_replay'],+ }),+]++const liveRuns: SignalReport[] = [+ makeReport({+ title: 'fix(auth): session dropped after SSO redirect',+ summary: 'Researching why some SSO logins land on a logged-out state after the redirect hop.',+ status: SignalReportStatus.IN_PROGRESS,+ priority: 'P1',+ total_weight: 3.0,+ signal_count: 9,+ signals_at_run: 9,+ source_products: ['error_tracking', 'session_replay'],+ }),+ makeReport({+ title: 'feat(search): empty results for valid queries',+ status: SignalReportStatus.IN_PROGRESS,+ priority: 'P2',+ total_weight: 2.4,+ signal_count: 6,+ signals_at_run: 6,+ source_products: ['session_replay'],+ }),+ makeReport({+ title: 'fix(exports): CSV export truncates at 10k rows',+ summary: 'Needs a product decision on whether to stream or cap; pausing for input.',+ status: SignalReportStatus.PENDING_INPUT,+ priority: 'P2',+ total_weight: 2.2,+ signal_count: 5,+ signals_at_run: 5,+ source_products: ['zendesk', 'error_tracking'],+ }),+]++const finishedRuns: SignalReport[] = [+ makeReport({+ title: 'fix(invites): validate recipient payload before submit',+ status: SignalReportStatus.READY,+ priority: 'P1',+ actionability: 'immediately_actionable',+ total_weight: 3.4,+ signal_count: 12,+ source_products: ['error_tracking'],+ implementation_pr_url: 'https://github.com/PostHog/posthog/pull/12001',+ }),+ makeReport({+ title: 'Investigate webhook delivery failures',+ status: SignalReportStatus.FAILED,+ priority: 'P2',+ total_weight: 1.8,+ signal_count: 5,+ source_products: ['error_tracking'],+ }),+ makeReport({+ title: 'perf(dashboards): paginate cohort filter resolution',+ status: SignalReportStatus.READY,+ priority: 'P2',+ actionability: 'immediately_actionable',+ total_weight: 2.0,+ signal_count: 7,+ source_products: ['session_replay'],+ implementation_pr_url: 'https://github.com/PostHog/posthog/pull/12003',+ }),+]++/** Lots of agents in motion: full queued + live + finished history. */+export const runReportsMany: SignalReport[] = [...queuedRuns, ...liveRuns, ...finishedRuns]+/** Just one agent live, nothing queued, a little history. */+export const runReportsFew: SignalReport[] = [liveRuns[0], finishedRuns[0]]++export const allReports: SignalReport[] = [...reportTabReports, ...pullRequestReports, ...runReportsMany]++// ── Detail-endpoint payloads ────────────────────────────────────────────────++export function mockSignals(reportId: string, count = 4): SignalNode[] {+ return Array.from({ length: count }).map((_, i) => ({+ signal_id: `${reportId}-sig-${i}`,+ content: [+ 'User clicked **Submit** with an empty recipient row; the request returned `500` from `/api/invites`.',+ 'Session shows three retries of the same failing checkout call before the user gave up.',+ 'Error fingerprint `2c6be0b` first seen 2026-05-26, now recurring ~12×/day.',+ 'Support ticket references the same flow: "I keep getting an error when inviting my team".',+ ][i % 4],+ source_product: ['error_tracking', 'session_replay', 'error_tracking', 'zendesk'][i % 4],+ source_type: 'issue',+ source_id: `${reportId}-src-${i}`,+ weight: Number((1.5 - i * 0.2).toFixed(1)),+ timestamp: BASE_DATE,+ extra: {},+ }))+}++export function mockArtefacts(reportId: string): { results: any[]; count: number } {+ const results = [+ {+ id: `${reportId}-pri`,+ type: 'priority_judgment',+ content: { priority: 'P1', explanation: 'High user impact (47 affected) and a clean, low-risk fix.' },+ created_at: BASE_DATE,+ },+ {+ id: `${reportId}-act`,+ type: 'actionability_judgment',+ content: {+ actionability: 'immediately_actionable',+ already_addressed: false,+ explanation: 'The failing endpoint and validation gap are clearly identified in the findings.',+ },+ created_at: BASE_DATE,+ },+ {+ id: `${reportId}-rev`,+ type: 'suggested_reviewers',+ content: [+ {+ github_login: 'octocat',+ github_name: 'Octo Cat',+ relevant_commits: [+ {+ sha: 'a1b2c3d4',+ url: 'https://github.com/PostHog/posthog/commit/a1b2c3d4',+ reason: 'Last touched the invite form',+ },+ ],+ user: { id: 1, uuid: 'u-1', email: '[email protected]', first_name: 'Octo', last_name: 'Cat' },+ },+ {+ github_login: 'hedgehog',+ github_name: 'Hedge Hog',+ relevant_commits: [],+ user: null,+ },+ ],+ created_at: BASE_DATE,+ },+ ]+ return { results, count: results.length }+}++export function mockReportTasks(reportId: string): { results: any[]; count: number; next: null; previous: null } {+ return {+ results: [+ {+ id: `${reportId}-t1`,+ relationship: 'research',+ task_id: `${reportId}-task-research`,+ created_at: BASE_DATE,+ },+ {+ id: `${reportId}-t2`,+ relationship: 'implementation',+ task_id: `${reportId}-task-impl`,+ created_at: BASE_DATE,+ },+ ],+ count: 2,+ next: null,+ previous: null,+ }+}++export function mockTask(taskId: string): any {+ const failed = taskId.includes('research')+ return {+ id: taskId,+ task_number: 42,+ slug: 'inbox-task',+ title: taskId.includes('impl') ? 'Implement invite validation fix' : 'Research invite failures',+ description: 'Auto-created from an Inbox report.',+ origin_product: 'signal_report',+ repository: 'PostHog/posthog',+ github_integration: 1,+ json_schema: null,+ internal: false,+ latest_run: {+ id: `${taskId}-run`,+ task: taskId,+ stage: null,+ branch: 'inbox/fix-invites',+ status: failed ? 'completed' : 'in_progress',+ environment: 'cloud',+ log_url: null,+ error_message: null,+ output: taskId.includes('impl') ? { pr_url: 'https://github.com/PostHog/posthog/pull/12001' } : {},+ state: {},+ artifacts: [],+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ completed_at: failed ? BASE_DATE : null,+ },+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ created_by: null,+ }+}++export const mockSourceConfigs = {+ results: [+ {+ id: 'sc-1',+ source_product: 'session_replay',+ source_type: 'session_analysis_cluster',+ enabled: true,+ config: {},+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ status: 'completed',+ },+ {+ id: 'sc-2',+ source_product: 'error_tracking',+ source_type: 'issue_created',+ enabled: true,+ config: {},+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ status: null,+ },+ {+ id: 'sc-3',+ source_product: 'github',+ source_type: 'issue',+ enabled: false,+ config: {},+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ status: null,+ },+ ],+ count: 3,+}++export const mockReviewers = {+ results: [+ { user_uuid: 'u-1', name: 'Octo Cat', email: '[email protected]' },+ { user_uuid: 'u-2', name: 'Hedge Hog', email: '[email protected]' },+ { user_uuid: 'u-3', name: 'Max AI', email: '[email protected]' },+ ],+ count: 3,+}++export const mockAutonomy = {+ id: 'auto-1',+ autostart_priority: 'P1',+ slack_notification_channel: null,+ slack_notification_min_priority: null,+}diff --git a/frontend/src/scenes/inbox/components/InboxReportList.tsx b/frontend/src/scenes/inbox/components/InboxReportList.tsxnew file mode 100644index 000000000000..25877948e10e--- /dev/null+++ b/frontend/src/scenes/inbox/components/InboxReportList.tsx@@ -0,0 +1,113 @@+import { BindLogic, useActions, useValues } from 'kea'+import { ComponentType, JSX, useEffect, useRef } from 'react'++import { reportListLogic, ReportListLogicProps } from '../logics/reportListLogic'+import { InboxFlatListTabKey, SignalReport } from '../types'+import { DismissalReasonValue } from '../utils/dismissalReasons'+import { CardSkeleton } from './cards/CardSkeleton'+import { InboxBulkSelectionBar } from './shell/InboxBulkSelectionBar'+import { InboxSearchFilterBar } from './shell/InboxSearchFilterBar'++export interface InboxReportCardProps {+ report: SignalReport+ tabKey: InboxFlatListTabKey+ onArchive: (reason: DismissalReasonValue, note: string) => void+ /** Rendered as an attached row inside a shared bordered container (vs. a freestanding card). */+ attached?: boolean+}++interface InboxReportListProps extends ReportListLogicProps {+ Card: ComponentType<InboxReportCardProps>+ emptyState: { icon: JSX.Element; title: string; description: string }+}++/**+ * Shared body for the three flat report-list tabs (Pull requests / Reports /+ * Not actionable). Each is the same primitive – only the `listParams` filter and+ * the empty-state copy differ. Binds the keyed `reportListLogic`, loads the first+ * page lazily on mount, shows a skeleton while a known-non-empty tab loads, and+ * appends pages via an IntersectionObserver sentinel.+ */+export function InboxReportList(props: InboxReportListProps): JSX.Element {+ return (+ <BindLogic logic={reportListLogic} props={{ tabKey: props.tabKey, listParams: props.listParams }}>+ <InboxReportListInner {...props} />+ </BindLogic>+ )+}++function InboxReportListInner({ tabKey, Card, emptyState }: InboxReportListProps): JSX.Element {+ const { reports, count, hasMore, reportsResponseLoading, isLoaded } = useValues(reportListLogic)+ const { ensureLoaded, loadMore, archiveReport, refresh } = useActions(reportListLogic)+ const sentinelRef = useRef<HTMLDivElement>(null)++ // Read fresh state at intersection time via refs so the observer is created once and not+ // rebuilt twice per page fetch (`hasMore`/`reportsResponseLoading` both flip during a load).+ const hasMoreRef = useRef(hasMore)+ hasMoreRef.current = hasMore+ const loadingRef = useRef(reportsResponseLoading)+ loadingRef.current = reportsResponseLoading++ useEffect(() => {+ ensureLoaded()+ }, [ensureLoaded])++ useEffect(() => {+ const el = sentinelRef.current+ if (!el) {+ return+ }+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0]?.isIntersecting && hasMoreRef.current && !loadingRef.current) {+ loadMore()+ }+ },+ // Generous prefetch margin so the next page lands well before the user reaches the bottom.+ { rootMargin: '1500px' }+ )+ observer.observe(el)+ return () => observer.disconnect()+ }, [loadMore])++ // Skeleton while a tab we know is non-empty loads its first page.+ const showSkeleton = !isLoaded && (reportsResponseLoading || (count ?? 0) > 0)++ return (+ <div className="mx-auto max-w-4xl flex flex-col gap-4 px-6 py-4">+ <InboxSearchFilterBar onRefresh={() => refresh()} refreshing={reportsResponseLoading} />+ <InboxBulkSelectionBar />++ {showSkeleton ? (+ <CardSkeleton count={Math.min(count ?? 4, 6)} variant="cards" dashed={tabKey !== 'pulls'} />+ ) : reports.length === 0 ? (+ <div className="mx-auto max-w-md flex flex-col items-center text-center py-12 gap-2">+ <div className="flex items-center justify-center h-12 w-12 rounded-full bg-fill-primary text-secondary mb-1">+ {emptyState.icon}+ </div>+ <h3 className="text-base font-semibold m-0">{emptyState.title}</h3>+ <p className="text-sm text-tertiary m-0">{emptyState.description}</p>+ </div>+ ) : (+ <>+ {/* Each report is its own freestanding card, separated by a small gap. */}+ <div className="flex flex-col gap-1.5">+ {reports.map((report) => (+ <Card+ key={report.id}+ report={report}+ tabKey={tabKey}+ onArchive={(reason, note) => archiveReport(report.id, reason, note)}+ />+ ))}+ {/* Skeleton cards continue the list while the next page loads – sleeker than a spinner. */}+ {isLoaded && reportsResponseLoading && (+ <CardSkeleton count={2} variant="cards" dashed={tabKey !== 'pulls'} />+ )}+ </div>+ {hasMore && <div ref={sentinelRef} className="h-1" aria-hidden />}+ </>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/badges/AnimatedEllipsis.tsx b/frontend/src/scenes/inbox/components/badges/AnimatedEllipsis.tsxnew file mode 100644index 000000000000..b0aa86b587ef--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/AnimatedEllipsis.tsx@@ -0,0 +1,39 @@+/**+ * Animated three-dot ellipsis used while the inbox is warming up.+ *+ * Faithful port of desktop's `inbox-ellipsis-dot` wave. Desktop drives it from a+ * global CSS class (`packages/ui/src/styles/globals.css`); cloud has no such class,+ * so we inline the same keyframe in a scoped <style> and stagger the three dots+ * (0 / 160 / 320ms) exactly as desktop does. The motion is a subtle 1px lift with+ * an opacity dip – intentionally gentler than Tailwind's `animate-bounce`.+ */+export function AnimatedEllipsis(): JSX.Element {+ return (+ <span aria-hidden className="inbox-ellipsis">+ {/* eslint-disable-next-line react/no-danger */}+ <style dangerouslySetInnerHTML={{ __html: ELLIPSIS_CSS }} />+ <span className="inline-flex items-end gap-px leading-none">+ <span className="inbox-ellipsis__dot">.</span>+ <span className="inbox-ellipsis__dot">.</span>+ <span className="inbox-ellipsis__dot">.</span>+ </span>+ </span>+ )+}++const ELLIPSIS_CSS = `+@keyframes inboxEllipsisWave {+ 0%, 60%, 100% { opacity: 0.12; transform: translateY(0); }+ 30% { opacity: 1; transform: translateY(-1px); }+}+.inbox-ellipsis__dot {+ display: inline-block;+ animation: inboxEllipsisWave 1.05s ease-in-out infinite;+}+.inbox-ellipsis__dot:nth-child(1) { animation-delay: 0ms; }+.inbox-ellipsis__dot:nth-child(2) { animation-delay: 160ms; }+.inbox-ellipsis__dot:nth-child(3) { animation-delay: 320ms; }+@media (prefers-reduced-motion: reduce) {+ .inbox-ellipsis__dot { animation: none; opacity: 0.6; }+}+`diff --git a/frontend/src/scenes/inbox/components/badges/ForYouBadge.tsx b/frontend/src/scenes/inbox/components/badges/ForYouBadge.tsxnew file mode 100644index 000000000000..e0819f19e7c3--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/ForYouBadge.tsx@@ -0,0 +1,13 @@+import { IconEye } from '@posthog/icons'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++export function ForYouBadge(): JSX.Element {+ return (+ <Tooltip title="You are a suggested reviewer">+ <LemonTag size="small" type="warning" className="gap-1 cursor-help select-none">+ <IconEye className="shrink-0" />+ For you+ </LemonTag>+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/inbox/components/badges/InboxBadges.stories.tsx b/frontend/src/scenes/inbox/components/badges/InboxBadges.stories.tsxnew file mode 100644index 000000000000..5941b313d6c8--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/InboxBadges.stories.tsx@@ -0,0 +1,64 @@+import type { Meta, StoryObj } from '@storybook/react'++import { SignalReportActionability, SignalReportPriority, SignalReportStatus } from '../../types'+import { AnimatedEllipsis } from './AnimatedEllipsis'+import { ForYouBadge } from './ForYouBadge'+import { SignalReportActionabilityBadge } from './SignalReportActionabilityBadge'+import { SignalReportPriorityBadge } from './SignalReportPriorityBadge'+import { SignalReportStatusBadge } from './SignalReportStatusBadge'++const meta: Meta = {+ title: 'Scenes-App/Inbox/Badges',+ parameters: { layout: 'centered', viewMode: 'story', mockDate: '2026-06-11' },+}+export default meta++type Story = StoryObj++const PRIORITIES: SignalReportPriority[] = ['P0', 'P1', 'P2', 'P3', 'P4']+const STATUSES = Object.values(SignalReportStatus)+const ACTIONABILITIES: SignalReportActionability[] = [+ 'immediately_actionable',+ 'requires_human_input',+ 'not_actionable',+]++function Row({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex items-center gap-3">+ <span className="w-28 shrink-0 text-xs text-tertiary">{label}</span>+ <div className="flex items-center gap-2 flex-wrap">{children}</div>+ </div>+ )+}++export const AllBadges: Story = {+ render: () => (+ <div className="bg-primary p-8 flex flex-col gap-4">+ <Row label="Priority">+ {PRIORITIES.map((p) => (+ <SignalReportPriorityBadge key={p} priority={p} />+ ))}+ </Row>+ <Row label="Status">+ {STATUSES.map((s) => (+ <SignalReportStatusBadge key={s} status={s} />+ ))}+ </Row>+ <Row label="Actionability">+ {ACTIONABILITIES.map((a) => (+ <SignalReportActionabilityBadge key={a} actionability={a} />+ ))}+ </Row>+ <Row label="For you">+ <ForYouBadge />+ </Row>+ <Row label="Working">+ <span className="text-sm text-secondary">+ Investigating+ <AnimatedEllipsis />+ </span>+ </Row>+ </div>+ ),+}diff --git a/frontend/src/scenes/inbox/components/badges/SignalReportActionabilityBadge.tsx b/frontend/src/scenes/inbox/components/badges/SignalReportActionabilityBadge.tsxnew file mode 100644index 000000000000..28183c1fb7d2--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/SignalReportActionabilityBadge.tsx@@ -0,0 +1,75 @@+import { IconQuestion } from '@posthog/icons'+import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'++import { SignalReportActionability } from '../../types'++// `textColor` mirrors the LemonTag text color for each `type` (see LemonTag.scss; for these outlined+// types the text and border share the same var), so the overlaid help icon matches the tag's text.+const ACTIONABILITY_STYLE: Record<+ SignalReportActionability,+ { type: LemonTagType; label: string; tooltip: string; textColor: string }+> = {+ immediately_actionable: {+ type: 'success',+ label: 'Actionable',+ tooltip:+ "The issue can be solved with code. If there isn't a pull request yet, it fell below your auto-PR priority threshold – you can still start one from this report.",+ textColor: 'var(--success)',+ },+ requires_human_input: {+ type: 'caution',+ label: 'Needs input',+ tooltip:+ 'Actionable, but it needs your input first to decide how to resolve it: business context, trade-offs, or a choice between several valid approaches.',+ textColor: 'var(--danger-lighter)',+ },+ not_actionable: {+ type: 'muted',+ label: 'Not actionable',+ tooltip:+ 'No useful code change can be derived – the report is too vague, lacks supporting evidence, or describes expected behavior.',+ textColor: 'var(--color-text-secondary)',+ },+}++export function SignalReportActionabilityBadge({+ actionability,+ explanation,+}: {+ actionability: SignalReportActionability | null | undefined+ /**+ * When set, a circled help icon overlays the tag's top-right corner and the rationale becomes the+ * tag's tooltip (replacing the generic category blurb). Absent, the tag shows the generic meaning.+ */+ explanation?: string | null+}): JSX.Element | null {+ if (actionability == null) {+ return null+ }++ const style = ACTIONABILITY_STYLE[actionability]+ if (!style) {+ return null+ }++ const hasWhy = !!explanation?.trim()+ // Always trigger off the wrapping span (matching the priority badge), rather than handing the bare+ // LemonTag to Base UI as the trigger. When a rationale exists the help icon overlays the (rounded)+ // top-right corner and the tooltip carries the rationale; otherwise it's the generic category blurb.+ return (+ <Tooltip title={hasWhy ? explanation : style.tooltip}>+ <span className="relative inline-flex cursor-help">+ <LemonTag size="small" type={style.type} className="select-none">+ {style.label}+ </LemonTag>+ {hasWhy && (+ <IconQuestion+ className="absolute right-0 top-0 size-3 -translate-y-1/2 translate-x-1/2 rounded-full bg-surface-primary"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ color: style.textColor }}+ />+ )}+ </span>+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/inbox/components/badges/SignalReportPriorityBadge.tsx b/frontend/src/scenes/inbox/components/badges/SignalReportPriorityBadge.tsxnew file mode 100644index 000000000000..2cb65d2d445b--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/SignalReportPriorityBadge.tsx@@ -0,0 +1,70 @@+import { IconQuestion } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++import { SignalReportPriority } from '../../types'++/**+ * Per-priority color, mirroring `PRIORITY_TAG_TYPE`'s LemonTag semantics but as raw CSS vars+ * so the badge can paint its own border + text. Theme-aware, so contrast holds in both modes.+ */+const PRIORITY_COLOR: Record<SignalReportPriority, string> = {+ P0: 'var(--danger)',+ P1: 'var(--warning)',+ P2: 'var(--danger-lighter)',+ P3: 'var(--color-accent)',+ P4: 'var(--color-text-secondary)',+}++/**+ * Sleek priority chip: a square box of accent text on a faint accent fill with a matching border+ * and a tight radius. Built bespoke since no LemonTag variant gives this filled-square look.+ * Shared verbatim between report cards and the detail header.+ */+export function SignalReportPriorityBadge({+ priority,+ explanation,+}: {+ priority: SignalReportPriority | null | undefined+ /**+ * When set, a circled help icon overlays the chip's top-right corner and the whole chip is+ * hoverable, surfacing this rationale. The icon is out of flow, so the chip stays a square.+ */+ explanation?: string | null+}): JSX.Element | null {+ if (priority == null) {+ return null+ }++ const color = PRIORITY_COLOR[priority]+ const borderColor = `color-mix(in srgb, ${color} 40%, transparent)`+ const chip = (+ <span+ className="inline-flex size-6 shrink-0 items-center justify-center rounded-sm border text-[10px] font-semibold tabular-nums select-none"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ color,+ borderColor,+ backgroundColor: `color-mix(in srgb, ${color} 14%, transparent)`,+ }}+ >+ {priority}+ </span>+ )++ if (!explanation?.trim()) {+ return chip+ }+ // Icon center sits on the (rounded) top-right corner; matches the chip's text color, with its own bg to stay legible.+ return (+ <Tooltip title={explanation}>+ <span className="relative inline-flex cursor-help">+ {chip}+ <IconQuestion+ className="absolute right-0 top-0 size-3 -translate-y-1/2 translate-x-1/2 rounded-full bg-surface-primary"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ color }}+ />+ </span>+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsx b/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsxnew file mode 100644index 000000000000..831e94e40f17--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsx@@ -0,0 +1,63 @@+import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'++import { SignalReportStatus } from '../../types'++const STATUS_TOOLTIPS: Partial<Record<SignalReportStatus, string>> = {+ [SignalReportStatus.READY]: 'Research is complete. You can create a task from this report.',+ [SignalReportStatus.PENDING_INPUT]: 'This report needs human input in PostHog before it can proceed.',+ [SignalReportStatus.IN_PROGRESS]: "An AI agent is actively researching this report's findings.",+ [SignalReportStatus.CANDIDATE]: 'Queued for research. An agent will pick this up shortly.',+ [SignalReportStatus.POTENTIAL]: 'Gathering findings. The report will be queued once enough evidence accumulates.',+ [SignalReportStatus.RESOLVED]: 'This report has been resolved.',+ [SignalReportStatus.FAILED]: 'Research failed. The report may be retried automatically.',+ [SignalReportStatus.SUPPRESSED]: 'This report has been suppressed and is out of your inbox.',+ [SignalReportStatus.DELETED]: 'This report has been deleted.',+}++const STATUS_LABELS: Partial<Record<SignalReportStatus, string>> = {+ [SignalReportStatus.READY]: 'Ready',+ [SignalReportStatus.PENDING_INPUT]: 'Needs input',+ [SignalReportStatus.IN_PROGRESS]: 'Researching',+ [SignalReportStatus.CANDIDATE]: 'Queued',+ [SignalReportStatus.POTENTIAL]: 'Gathering',+ [SignalReportStatus.RESOLVED]: 'Resolved',+ [SignalReportStatus.FAILED]: 'Failed',+ [SignalReportStatus.SUPPRESSED]: 'Suppressed',+ [SignalReportStatus.DELETED]: 'Deleted',+}++// Each pipeline status gets a distinct color so the inbox reads at a glance.+function inboxStatusBadgeType(status: SignalReportStatus): LemonTagType {+ switch (status) {+ case SignalReportStatus.READY:+ return 'success'+ case SignalReportStatus.RESOLVED:+ return 'completion'+ case SignalReportStatus.PENDING_INPUT:+ return 'caution'+ case SignalReportStatus.IN_PROGRESS:+ return 'warning'+ case SignalReportStatus.CANDIDATE:+ return 'highlight'+ case SignalReportStatus.FAILED:+ return 'danger'+ case SignalReportStatus.POTENTIAL:+ return 'default'+ // Out-of-inbox terminal states (suppressed / deleted) and any unknown status.+ default:+ return 'muted'+ }+}++export function SignalReportStatusBadge({ status }: { status: SignalReportStatus }): JSX.Element {+ const label = STATUS_LABELS[status] ?? status+ const tooltip = STATUS_TOOLTIPS[status] ?? status++ return (+ <Tooltip title={tooltip}>+ <LemonTag size="small" type={inboxStatusBadgeType(status)} className="cursor-help select-none">+ {label}+ </LemonTag>+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/inbox/components/badges/sourceProductIcons.tsx b/frontend/src/scenes/inbox/components/badges/sourceProductIcons.tsxnew file mode 100644index 000000000000..6f36627ae37a--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/sourceProductIcons.tsx@@ -0,0 +1,151 @@+import {+ IconBolt,+ IconBrain,+ IconBug,+ IconCompass,+ IconDatabase,+ IconGithub,+ IconHeartPlus,+ IconList,+ IconRewindPlay,+ IconStack,+ IconSupport,+ IconReceipt,+} from '@posthog/icons'++import { SignalSourceProduct } from '../../types'++interface SourceProductMeta {+ Icon: typeof IconBolt+ /** CSS color value applied to the icon. */+ color: string+ label: string+}++/**+ * Shared source-product metadata used across inbox cards. Keyed on+ * `SignalSourceProduct` so a typo'd lookup fails to compile rather than+ * silently returning undefined at runtime.+ *+ * `Partial` because the backend may ship a new source product before the+ * renderer learns about it – callers must handle the `undefined` case via+ * `getSourceProductMeta`, which returns `null` for unknown keys.+ */+export const SOURCE_PRODUCT_META: Partial<Record<SignalSourceProduct, SourceProductMeta>> = {+ [SignalSourceProduct.SESSION_REPLAY]: {+ Icon: IconRewindPlay,+ color: 'var(--warning)',+ label: 'Session replay',+ },+ [SignalSourceProduct.ERROR_TRACKING]: {+ Icon: IconBug,+ color: 'var(--danger)',+ label: 'Error tracking',+ },+ [SignalSourceProduct.LLM_ANALYTICS]: {+ Icon: IconBrain,+ color: 'var(--purple)',+ label: 'AI observability',+ },+ [SignalSourceProduct.GITHUB]: {+ Icon: IconGithub,+ color: 'var(--text-secondary)',+ label: 'GitHub',+ },+ [SignalSourceProduct.LINEAR]: {+ Icon: IconStack,+ color: 'var(--blue)',+ label: 'Linear',+ },+ [SignalSourceProduct.ZENDESK]: {+ Icon: IconReceipt,+ color: 'var(--success)',+ label: 'Zendesk',+ },+ [SignalSourceProduct.CONVERSATIONS]: {+ Icon: IconSupport,+ color: 'var(--blue)',+ label: 'Conversations',+ },+ [SignalSourceProduct.PGANALYZE]: {+ Icon: IconDatabase,+ color: 'var(--text-primary)',+ label: 'pganalyze',+ },+ [SignalSourceProduct.SIGNALS_SCOUT]: {+ Icon: IconCompass,+ color: 'var(--purple)',+ label: 'Scout',+ },+ [SignalSourceProduct.ENDPOINTS]: {+ Icon: IconBolt,+ color: 'var(--warning)',+ label: 'Endpoints',+ },+ [SignalSourceProduct.LOGS]: {+ Icon: IconList,+ color: 'var(--text-secondary)',+ label: 'Logs',+ },+ [SignalSourceProduct.HEALTH_CHECKS]: {+ Icon: IconHeartPlus,+ color: 'var(--danger)',+ label: 'Health checks',+ },+}++/**+ * Lookup helper accepting the loosely-typed `source_products` strings from the+ * backend. Returns metadata only for recognized keys, else `null`.+ */+export function getSourceProductMeta(value: string | null | undefined): SourceProductMeta | null {+ if (!value) {+ return null+ }+ return SOURCE_PRODUCT_META[value as SignalSourceProduct] ?? null+}++/** True if at least one source product in `values` has known display metadata. */+export function hasKnownSourceProduct(values: string[] | null | undefined): boolean {+ return (values ?? []).some((value) => getSourceProductMeta(value) !== null)+}++export interface KnownSourceProductEntry {+ key: string+ meta: SourceProductMeta+}++/** Resolve `source_products` strings to entries with known display metadata, preserving order. */+export function knownSourceProductEntries(sourceProducts: string[] | null | undefined): KnownSourceProductEntry[] {+ return (sourceProducts ?? [])+ .map((key) => ({ key, meta: getSourceProductMeta(key) }))+ .filter((entry): entry is KnownSourceProductEntry => entry.meta !== null)+}++/** Row of color-coded source-product icons. Surfaces vary in wrapper layout, so the caller supplies `className`. */+export function SourceProductIconRow({+ entries,+ className,+}: {+ entries: KnownSourceProductEntry[]+ className?: string+}): JSX.Element {+ return (+ <span className={className}>+ {entries.map((entry) => {+ const Icon = entry.meta.Icon+ return (+ <span+ key={entry.key}+ className="inline-flex shrink-0 items-center"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ color: entry.meta.color }}+ aria-hidden+ >+ <Icon className="text-xs" />+ </span>+ )+ })}+ </span>+ )+}diff --git a/frontend/src/scenes/inbox/components/cards/AgentRunCard.tsx b/frontend/src/scenes/inbox/components/cards/AgentRunCard.tsxnew file mode 100644index 000000000000..c98fc5588120--- /dev/null+++ b/frontend/src/scenes/inbox/components/cards/AgentRunCard.tsx@@ -0,0 +1,168 @@+import clsx from 'clsx'++import { LemonTag, LemonTagType, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import { isFinishedRunReport, isLiveRunReport, isQueuedRunReport } from '../../inboxMembership'+import { SignalReport } from '../../types'+import { deriveHeadline, parsePrUrlParts } from '../../utils/reportPresentation'+import { hasKnownSourceProduct, knownSourceProductEntries, SourceProductIconRow } from '../badges/sourceProductIcons'++type RunVariant = 'queued' | 'live' | 'completed' | 'failed'++/** Single source of truth for the four-bucket lifecycle of a run-shaped report. */+export function resolveRunVariant(report: SignalReport): RunVariant {+ if (isQueuedRunReport(report)) {+ return 'queued'+ }+ if (isLiveRunReport(report)) {+ return 'live'+ }+ if (isFinishedRunReport(report)) {+ return report.status === 'failed' ? 'failed' : 'completed'+ }+ return 'live'+}++const RUN_VARIANT_TIMESTAMP_LABEL: Record<RunVariant, string> = {+ queued: 'Queued',+ live: 'Started',+ completed: 'Finished',+ failed: 'Failed',+}++interface VariantMeta {+ label: string+ badgeType: LemonTagType+ orbClass: string+ dotClass: string+ ariaLabel: string+}++const VARIANT_META: Record<RunVariant, VariantMeta> = {+ queued: {+ label: 'Queued',+ badgeType: 'default',+ orbClass: 'bg-fill-primary ring-primary',+ dotClass: 'bg-muted',+ ariaLabel: 'Queued',+ },+ live: {+ label: 'Running',+ badgeType: 'highlight',+ orbClass: 'bg-primary-highlight ring-primary',+ dotClass: 'bg-accent animate-pulse',+ ariaLabel: 'In progress',+ },+ completed: {+ label: 'Completed',+ badgeType: 'success',+ orbClass: 'bg-success-highlight ring-success',+ dotClass: 'bg-success',+ ariaLabel: 'Completed',+ },+ failed: {+ label: 'Failed',+ badgeType: 'danger',+ orbClass: 'bg-danger-highlight ring-danger',+ dotClass: 'bg-danger',+ ariaLabel: 'Failed',+ },+}++function pickTimestamp(report: SignalReport, variant: RunVariant): string {+ if (variant === 'live') {+ return report.created_at+ }+ return report.updated_at ?? report.created_at+}++function RunStatusOrb({ meta }: { meta: VariantMeta }): JSX.Element {+ return (+ <div+ className={clsx(+ 'flex items-center justify-center h-7 w-7 shrink-0 rounded-full ring-1 ring-inset',+ meta.orbClass+ )}+ >+ <span+ className={clsx('block h-1.5 w-1.5 rounded-full', meta.dotClass)}+ role="img"+ aria-label={meta.ariaLabel}+ />+ </div>+ )+}++/** Source-product icon stack reused inside the run card meta row. */+function RunSourceStack({ sourceProducts }: { sourceProducts?: string[] | null }): JSX.Element | null {+ const [primary, ...overflow] = knownSourceProductEntries(sourceProducts)+ if (!primary) {+ return null+ }+ return (+ <span className="inline-flex items-center gap-2 min-w-0">+ <SourceProductIconRow+ entries={[primary, ...overflow]}+ className="inline-flex items-center gap-1.5 shrink-0"+ />+ <span>+ {primary.meta.label}+ {overflow.length > 0 ? ` + ${overflow.length}` : null}+ </span>+ </span>+ )+}++/** PR number from an implementation PR url, e.g. `#12001`. Null when there's no PR. */+function prRef(prUrl: string | null | undefined): string | null {+ const parts = prUrl ? parsePrUrlParts(prUrl) : null+ return parts ? `#${parts.number}` : null+}++export function AgentRunCard({ report }: { report: SignalReport }): JSX.Element {+ const hasSource = hasKnownSourceProduct(report.source_products)+ const pr = prRef(report.implementation_pr_url)+ const variant = resolveRunVariant(report)+ const meta = VARIANT_META[variant]+ const timestampSource = pickTimestamp(report, variant)+ const headline = deriveHeadline(report.summary)++ return (+ <Link+ to={urls.inboxReport('runs', report.id)}+ className="group flex w-full items-start gap-3 rounded border border-primary bg-surface-primary px-4 py-3.5 text-left text-inherit no-underline transition-colors duration-150 hover:border-primary hover:bg-surface-secondary"+ >+ <RunStatusOrb meta={meta} />++ <div className="flex flex-col gap-1.5 min-w-0 flex-1">+ <span className="break-words min-w-0 font-semibold text-sm leading-snug tracking-tight">+ {report.title ?? 'Untitled run'}+ </span>+ {headline ? (+ <p className="break-words line-clamp-2 text-xs text-secondary leading-snug m-0">{headline}</p>+ ) : null}+ <div className="flex items-center gap-2 flex-wrap mt-1.5 text-xs text-tertiary leading-none select-none">+ {hasSource ? (+ <>+ <RunSourceStack sourceProducts={report.source_products} />+ <span aria-hidden>·</span>+ </>+ ) : null}+ <span className="inline-flex items-center gap-1">+ {RUN_VARIANT_TIMESTAMP_LABEL[variant]} <TZLabel time={timestampSource} />+ </span>+ </div>+ </div>++ <div className="flex flex-col items-end justify-center gap-1.5 self-stretch shrink-0 border-l border-primary pl-3">+ <LemonTag size="small" type={meta.badgeType} className="select-none">+ {meta.label}+ </LemonTag>+ {pr ? <span className="font-mono tabular-nums text-[11px] text-tertiary">{pr}</span> : null}+ </div>+ </Link>+ )+}diff --git a/frontend/src/scenes/inbox/components/cards/CardSkeleton.tsx b/frontend/src/scenes/inbox/components/cards/CardSkeleton.tsxnew file mode 100644index 000000000000..05f795970cfa--- /dev/null+++ b/frontend/src/scenes/inbox/components/cards/CardSkeleton.tsx@@ -0,0 +1,68 @@+import clsx from 'clsx'++import { LemonSkeleton } from '@posthog/lemon-ui'++interface CardSkeletonProps {+ /** Number of rows to render. */+ count?: number+ /** Row style: bordered rows joined into a list, or freestanding cards. */+ variant?: 'rows' | 'cards'+ /** Freestanding cards use a dashed border to match report cards; pass false for PR cards (solid). */+ dashed?: boolean+}++export function CardSkeleton({ count = 4, variant = 'rows', dashed = true }: CardSkeletonProps): JSX.Element {+ if (variant === 'cards') {+ return (+ <div className="flex flex-col gap-1.5">+ {Array.from({ length: count }).map((_, i) => (+ <SkeletonRow key={i} rounded dashed={dashed} />+ ))}+ </div>+ )+ }++ return (+ <div className="overflow-hidden rounded border border-primary bg-surface-primary">+ {Array.from({ length: count }).map((_, i) => (+ <SkeletonRow key={i} bordered />+ ))}+ </div>+ )+}++function SkeletonRow({+ rounded,+ bordered,+ dashed,+}: {+ rounded?: boolean+ bordered?: boolean+ dashed?: boolean+}): JSX.Element {+ return (+ <div+ className={clsx(+ 'flex w-full items-stretch gap-3 px-4 py-3.5',+ rounded && 'rounded border border-primary bg-surface-primary',+ rounded && dashed && 'border-dashed',+ bordered && 'border-b border-primary last:border-b-0'+ )}+ >+ {/* Matches the report card's square priority badge (`size-6`). */}+ <LemonSkeleton className="size-6 shrink-0 rounded-sm" />+ <div className="flex min-w-0 flex-1 flex-col gap-2 py-0.5">+ <LemonSkeleton className="h-3.5 w-3/5" />+ <LemonSkeleton className="h-3 w-4/5" />+ <div className="flex items-center gap-1.5 pt-0.5">+ <LemonSkeleton className="h-3.5 w-16" />+ <LemonSkeleton className="h-3.5 w-20" />+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-2 self-center">+ <LemonSkeleton className="h-3 w-10" />+ <LemonSkeleton className="h-7 w-16 rounded" />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/cards/InboxCards.stories.tsx b/frontend/src/scenes/inbox/components/cards/InboxCards.stories.tsxnew file mode 100644index 000000000000..02348bd7e72e--- /dev/null+++ b/frontend/src/scenes/inbox/components/cards/InboxCards.stories.tsx@@ -0,0 +1,109 @@+import type { Meta, StoryObj } from '@storybook/react'++import { makeReport, pullRequestReports, reportTabReports, runReportsMany } from '../../__mocks__/inboxMocks'+import { SignalReportStatus } from '../../types'+import { AgentRunCard } from './AgentRunCard'+import { CardSkeleton } from './CardSkeleton'+import { ReportCard } from './ReportCard'++// Individual card stories across every state, so card design / badges / right-rail+// density can be polished in isolation against the desktop equivalents.++const meta: Meta = {+ title: 'Scenes-App/Inbox/Cards',+ parameters: { layout: 'fullscreen', viewMode: 'story', mockDate: '2026-06-11' },+}+export default meta++type Story = StoryObj++function Stack({ children }: { children: React.ReactNode }): JSX.Element {+ return <div className="bg-primary min-h-screen mx-auto max-w-4xl px-6 py-6 flex flex-col gap-3">{children}</div>+}++export const ReportCards: Story = {+ render: () => (+ <Stack>+ {reportTabReports.map((r) => (+ <ReportCard key={r.id} report={r} />+ ))}+ </Stack>+ ),+}++export const PullRequestCards: Story = {+ render: () => (+ <Stack>+ {pullRequestReports.map((r) => (+ <ReportCard key={r.id} report={r} />+ ))}+ </Stack>+ ),+}++export const AgentRunCards: Story = {+ render: () => (+ <Stack>+ {runReportsMany.map((r) => (+ <AgentRunCard key={r.id} report={r} />+ ))}+ </Stack>+ ),+}++export const ReportCardStates: Story = {+ render: () => (+ <Stack>+ <ReportCard+ report={makeReport({+ title: 'P0 critical, immediately actionable',+ priority: 'P0',+ actionability: 'immediately_actionable',+ source_products: ['error_tracking'],+ is_suggested_reviewer: true,+ summary: 'Highest severity, clean fix available.',+ })}+ />+ <ReportCard+ report={makeReport({+ title: 'Requires human input',+ priority: 'P2',+ actionability: 'requires_human_input',+ source_products: ['session_replay', 'zendesk'],+ summary: 'Needs a product call before an agent can proceed.',+ })}+ />+ <ReportCard+ report={makeReport({+ title: 'No summary yet, still collecting context',+ status: SignalReportStatus.CANDIDATE,+ priority: null,+ actionability: null,+ summary: null,+ source_products: ['llm_analytics'],+ })}+ />+ <ReportCard+ report={makeReport({+ title: 'Not actionable, low priority',+ priority: 'P4',+ actionability: 'not_actionable',+ source_products: ['github'],+ summary: 'Real but insignificant.',+ })}+ />+ </Stack>+ ),+}++export const Skeleton: Story = {+ // Skeletons render permanently, so the VR runner must not wait for loaders to disappear.+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+ render: () => (+ <Stack>+ {/* Dashed report/not-actionable card skeletons, then solid PR card skeletons – matching the live tabs. */}+ <CardSkeleton count={3} variant="cards" />+ <CardSkeleton count={2} variant="cards" dashed={false} />+ </Stack>+ ),+}diff --git a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx b/frontend/src/scenes/inbox/components/cards/ReportCard.tsxnew file mode 100644index 000000000000..3f40cf69b3c1--- /dev/null+++ b/frontend/src/scenes/inbox/components/cards/ReportCard.tsx@@ -0,0 +1,246 @@+import clsx from 'clsx'+import { router } from 'kea-router'++import { IconArchive, IconPullRequest } from '@posthog/icons'+import { LemonButton, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import { InboxFlatListTabKey, SignalReport, SignalReportStatus } from '../../types'+import { DismissalReasonValue } from '../../utils/dismissalReasons'+import {+ deriveHeadline,+ displayConventionalCommitTitle,+ parseConventionalCommitTitle,+ parsePrUrlParts,+ safeHttpUrl,+} from '../../utils/reportPresentation'+import { SignalReportActionabilityBadge } from '../badges/SignalReportActionabilityBadge'+import { SignalReportPriorityBadge } from '../badges/SignalReportPriorityBadge'+import { SignalReportStatusBadge } from '../badges/SignalReportStatusBadge'+import { hasKnownSourceProduct, knownSourceProductEntries, SourceProductIconRow } from '../badges/sourceProductIcons'+import { inboxCardRowClassName, useReportArchive } from './useReportArchive'++// ── Shared card sub-components ────────────────────────────────────────────────++export function ConventionalCommitScopeTag({ type, scope }: { type: string; scope: string | null }): JSX.Element {+ const label = scope ? `${type}(${scope})` : type+ // Rendered as an inline prefix to the title text (not a flex sibling), so it stays on the+ // title's first line and the title wraps beneath it. `align-middle` keeps it centered on that+ // line; `font-normal` stops it inheriting the title's weight.+ return (+ <LemonTag size="small" className="mr-1 align-middle font-mono font-normal select-none" title={label}>+ {label}+ </LemonTag>+ )+}++/** Icon stack + primary source-product label, with a `+ n` tail when more sources contributed. */+export function InboxCardSourceMeta({ sourceProducts }: { sourceProducts?: string[] | null }): JSX.Element | null {+ const [primary, ...overflow] = knownSourceProductEntries(sourceProducts)+ if (!primary) {+ return null+ }+ return (+ <div className="flex items-center gap-2 min-w-0 text-xs text-tertiary leading-none select-none">+ <SourceProductIconRow entries={[primary, ...overflow]} className="flex items-center gap-1.5 shrink-0" />+ <span>+ {primary.meta.label}+ {overflow.length > 0 ? ` + ${overflow.length}` : null}+ </span>+ </div>+ )+}++// ── PR status badge ─────────────────────────────────────────────────────────++/**+ * PR open/merged/closed state, mapped to muted palette tags (outlined: --success / --purple /+ * --danger). We have no real PR status from GitHub on the report, so it's inferred from the+ * report status: a resolved report means its implementation PR merged (webhook-driven on merge),+ * a failed one means the PR never landed, everything else is still an open PR.+ */+const PR_BADGE_STATE: Record<'open' | 'merged' | 'closed', { label: string; type: LemonTagType }> = {+ open: { label: 'open', type: 'success' },+ merged: { label: 'merged', type: 'completion' },+ closed: { label: 'closed', type: 'danger' },+}++type PrBadgeState = keyof typeof PR_BADGE_STATE++function derivePrState(status: SignalReportStatus): PrBadgeState {+ if (status === SignalReportStatus.RESOLVED) {+ return 'merged'+ }+ if (status === SignalReportStatus.FAILED) {+ return 'closed'+ }+ return 'open'+}++/**+ * PR status badge for the card's top-right corner: a state-colored tag with the pull-request+ * icon and `#1234`. When a PR URL is known the whole badge is the GitHub link itself.+ */+function PrBadge({+ prNumber,+ prUrl,+ state,+}: {+ prNumber: string+ prUrl?: string | null+ state: PrBadgeState+}): JSX.Element {+ const { label, type } = PR_BADGE_STATE[state]+ const badge = (+ <LemonTag type={type} size="small" icon={<IconPullRequest />} className="font-mono tabular-nums">+ #{prNumber}+ </LemonTag>+ )++ if (!prUrl) {+ return <Tooltip title={`Pull request #${prNumber} (${label})`}>{badge}</Tooltip>+ }++ return (+ <Tooltip title={`Open pull request #${prNumber} (${label}) on GitHub`}>+ <Link+ to={prUrl}+ target="_blank"+ disableClientSideRouting+ onClick={(e) => e.stopPropagation()}+ aria-label={`Open pull request #${prNumber} (${label}) on GitHub`}+ >+ {badge}+ </Link>+ </Tooltip>+ )+}++// ── ReportCard ────────────────────────────────────────────────────────────────++/**+ * Unified inbox list card for reports and pull requests. The presence of a parseable+ * implementation PR (`hasPr`) drives the divergences: PR cards get a solid border, a+ * `#1234` state badge, the repo slug in the meta row, and no status/actionability chips;+ * plain reports get a dashed border, a summary placeholder, and the status/actionability chips.+ */+export function ReportCard({+ report,+ tabKey = 'reports',+ attached = false,+ onArchive,+}: {+ report: SignalReport+ tabKey?: InboxFlatListTabKey+ attached?: boolean+ onArchive?: (reason: DismissalReasonValue, note: string) => void+}): JSX.Element {+ const prUrl = safeHttpUrl(report.implementation_pr_url)+ const prUrlParts = prUrl ? parsePrUrlParts(prUrl) : null+ const hasPr = prUrlParts != null+ const prNumber = prUrlParts?.number ?? null+ const repoSlug = prUrlParts?.repoSlug ?? null++ const hasSource = hasKnownSourceProduct(report.source_products)+ const isReady = report.status === 'ready'+ const conventionalTitle = parseConventionalCommitTitle(report.title)+ const cardTitle = displayConventionalCommitTitle(report.title, hasPr ? 'Untitled pull request' : 'Untitled report')+ const headline = deriveHeadline(report.summary)+ const detailUrl = urls.inboxReport(tabKey, report.id)++ const { isArchiving, onArchiveClick } = useReportArchive({ reportId: report.id, cardTitle, onArchive })++ // PR cards show repo · source; reports show source · status · actionability.+ const showMeta = hasPr+ ? repoSlug != null || hasSource+ : hasSource || !isReady || report.actionability != null || report.is_suggested_reviewer === true++ return (+ <div className={clsx('relative', inboxCardRowClassName(attached, { dashed: !hasPr }))}>+ {hasPr && prNumber != null ? (+ <div className="absolute right-4 top-3 z-10">+ <PrBadge prNumber={prNumber} prUrl={prUrl} state={derivePrState(report.status)} />+ </div>+ ) : null}++ <div className="absolute right-4 bottom-3 z-10">+ <TZLabel+ time={report.updated_at ?? report.created_at}+ className="text-xs text-tertiary tabular-nums"+ title="Last updated"+ />+ </div>++ <Link to={detailUrl} className="flex min-w-0 flex-1 items-start gap-3 text-left text-inherit no-underline">+ {report.priority && (+ <div className="shrink-0">+ <SignalReportPriorityBadge priority={report.priority} />+ </div>+ )}++ <div className="flex flex-col gap-1.5 min-w-0 flex-1">+ <div className="min-w-0 break-words font-semibold text-sm leading-snug">+ {conventionalTitle && (+ <ConventionalCommitScopeTag type={conventionalTitle.type} scope={conventionalTitle.scope} />+ )}+ {cardTitle}+ </div>++ {headline ? (+ <div className={clsx('mt-0.5 min-w-0', !hasPr && !isReady && 'opacity-80')}>+ <p className="break-words line-clamp-2 text-xs text-secondary leading-snug m-0">+ {headline}+ </p>+ </div>+ ) : !hasPr ? (+ <div className={clsx('mt-0.5 min-w-0', !isReady && 'opacity-80')}>+ <p className="break-words line-clamp-2 text-xs text-tertiary italic leading-snug m-0">+ No summary yet – still collecting context.+ </p>+ </div>+ ) : null}++ {showMeta ? (+ <div className="flex items-center flex-wrap mt-1.5 min-w-0 gap-2.5 text-xs text-tertiary leading-none select-none">+ {hasPr && repoSlug ? <span className="truncate font-mono">{repoSlug}</span> : null}+ <InboxCardSourceMeta sourceProducts={report.source_products} />+ {!hasPr && (!isReady || !report.actionability) && (+ <SignalReportStatusBadge status={report.status} />+ )}+ {!hasPr && report.actionability && (+ <SignalReportActionabilityBadge actionability={report.actionability} />+ )}+ </div>+ ) : null}+ </div>+ </Link>++ <div className="flex items-center gap-2.5 self-stretch shrink-0 border-l border-primary pl-3">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconArchive />}+ tooltip="Archive this report"+ aria-label="Archive this report"+ loading={isArchiving}+ onClick={onArchiveClick}+ >+ Archive+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={(event) => {+ event.preventDefault()+ event.stopPropagation()+ router.actions.push(detailUrl)+ }}+ >+ Review+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/cards/useReportArchive.ts b/frontend/src/scenes/inbox/components/cards/useReportArchive.tsnew file mode 100644index 000000000000..1de4c928f532--- /dev/null+++ b/frontend/src/scenes/inbox/components/cards/useReportArchive.ts@@ -0,0 +1,71 @@+import clsx from 'clsx'+import { useState } from 'react'++import api from 'lib/api'++import { DismissalReasonValue } from '../../utils/dismissalReasons'+import { openDismissReportDialog } from '../shell/DismissReportDialog'++/**+ * Shared archive handler for the inbox cards (Report / Pull request). Opens the dismissal+ * dialog and either delegates to the bound list logic via `onArchive` (optimistic) or, when+ * used standalone (e.g. stories), falls back to a direct `signalReports.setState` call.+ */+export function useReportArchive({+ reportId,+ cardTitle,+ onArchive,+ onArchived,+}: {+ reportId: string+ cardTitle: string+ onArchive?: (reason: DismissalReasonValue, note: string) => void+ /** Fired once the report is archived (after `onArchive`, or after the fallback API call succeeds). */+ onArchived?: () => void+}): { isArchiving: boolean; onArchiveClick: (event: React.MouseEvent) => void } {+ const [isArchiving, setIsArchiving] = useState(false)++ const onArchiveClick = (event: React.MouseEvent): void => {+ event.preventDefault()+ event.stopPropagation()+ openDismissReportDialog({+ reportTitle: cardTitle,+ onConfirm: async ({ reason, note }) => {+ if (onArchive) {+ onArchive(reason, note)+ onArchived?.()+ return+ }+ // Fallback for standalone usage (e.g. stories) without a bound list logic.+ setIsArchiving(true)+ try {+ await api.signalReports.setState(reportId, {+ state: 'suppressed',+ dismissal_reason: reason,+ ...(note ? { dismissal_note: note } : {}),+ })+ onArchived?.()+ } finally {+ setIsArchiving(false)+ }+ },+ })+ }++ return { isArchiving, onArchiveClick }+}++/**+ * Shared row className for inbox cards. Attached rows sit inside a single bordered container+ * (dividers between items); freestanding cards get their own border (dashed for reports).+ */+export function inboxCardRowClassName(attached: boolean, opts?: { dashed?: boolean }): string {+ return clsx(+ 'group flex w-full items-stretch gap-3 bg-surface-primary px-4 py-3.5 transition-all duration-150 hover:bg-surface-secondary',+ attached+ ? 'border-b border-primary last:border-b-0'+ : opts?.dashed+ ? 'rounded border border-dashed border-primary hover:border-secondary'+ : 'rounded border border-primary hover:border-secondary'+ )+}diff --git a/frontend/src/scenes/inbox/components/config/AgentsRoster.tsx b/frontend/src/scenes/inbox/components/config/AgentsRoster.tsxnew file mode 100644index 000000000000..56d7fc00006c--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/AgentsRoster.tsx@@ -0,0 +1,312 @@+import { useActions, useValues } from 'kea'+import { memo, useCallback } from 'react'++import { IconArrowUpRight } from '@posthog/icons'+import { LemonButton, LemonSkeleton, LemonSwitch, LemonTag, Link, Spinner } from '@posthog/lemon-ui'++import { LemonTagType } from 'lib/lemon-ui/LemonTag/LemonTag'++import { signalSourcesLogic } from '../../signalSourcesLogic'+import { SignalSourceConfig, SignalSourceConfigStatus } from '../../types'+import { getSourceProductMeta } from '../badges/sourceProductIcons'+import { AGENT_ROSTER_GROUPS, AgentRosterDefinition, AgentRosterSource } from './agentRosterMeta'++type AgentRosterStatus = 'standby' | 'watching' | 'syncing' | 'sync_failed'++const STATUS_TAG: Record<AgentRosterStatus, { label: string; type: LemonTagType }> = {+ standby: { label: 'Standby', type: 'muted' },+ watching: { label: 'Watching', type: 'success' },+ syncing: { label: 'Syncing', type: 'primary' },+ sync_failed: { label: 'Sync failed', type: 'danger' },+}++function resolveAgentStatus(+ armed: boolean,+ syncStatus: SignalSourceConfigStatus | null | undefined+): AgentRosterStatus {+ if (!armed) {+ return 'standby'+ }+ if (syncStatus === SignalSourceConfigStatus.RUNNING) {+ return 'syncing'+ }+ if (syncStatus === SignalSourceConfigStatus.FAILED) {+ return 'sync_failed'+ }+ return 'watching'+}++/** Per-source derived state assembled by `AgentsRoster` from `signalSourcesLogic`. */+interface AgentSourceState {+ armed: boolean+ loading: boolean+ /** True for data-warehouse sources that haven't been connected yet – shows a Connect button. */+ requiresSetup: boolean+ syncStatus: SignalSourceConfigStatus | null | undefined+}++function AgentIcon({ source }: { source: AgentRosterDefinition }): JSX.Element {+ const meta = getSourceProductMeta(source.sourceProduct)+ const Icon = meta?.Icon+ const color = meta?.color ?? 'var(--accent)'+ return (+ <div+ className="flex items-center justify-center size-8 shrink-0 rounded ring-1 ring-inset ring-primary"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ backgroundColor: `color-mix(in srgb, ${color} 12%, transparent)` }}+ >+ {/* eslint-disable-next-line react/forbid-dom-props */}+ {Icon ? <Icon className="size-[18px]" style={{ color }} /> : null}+ </div>+ )+}++interface AgentCardProps {+ agent: AgentRosterDefinition+ state: AgentSourceState+ onToggle: (source: AgentRosterSource) => void+}++const AgentCard = memo(function AgentCard({ agent, state, onToggle }: AgentCardProps): JSX.Element {+ const { armed, loading, requiresSetup, syncStatus } = state+ const status = resolveAgentStatus(armed, syncStatus)+ const statusTag = STATUS_TAG[status]+ const isInteractive = !loading++ const handleCardClick = useCallback(() => {+ if (!isInteractive) {+ return+ }+ onToggle(agent.source)+ }, [agent.source, isInteractive, onToggle])++ return (+ <div+ onClick={isInteractive ? handleCardClick : undefined}+ className={[+ 'rounded border p-3 transition-colors',+ armed ? 'border-accent bg-accent-highlight-secondary' : 'border-primary bg-surface-primary',+ isInteractive ? 'cursor-pointer hover:border-secondary' : 'cursor-default',+ ].join(' ')}+ >+ <div className="flex items-start justify-between gap-3">+ <div className="flex items-start gap-3 min-w-0 flex-1">+ <AgentIcon source={agent} />+ <div className="flex flex-col gap-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-medium text-sm text-default">{agent.label}</span>+ {agent.alpha && (+ <LemonTag type="completion" size="small">+ Alpha+ </LemonTag>+ )}+ </div>+ <p className="text-sm text-secondary leading-snug mb-0">{agent.description}</p>+ {agent.docsUrl && (+ <Link+ to={agent.docsUrl}+ target="_blank"+ className="inline-flex items-center gap-1 text-sm w-fit"+ onClick={(e) => e.stopPropagation()}+ >+ Learn about {agent.docsLabel ?? agent.label}+ <IconArrowUpRight />+ </Link>+ )}+ </div>+ </div>++ {/* eslint-disable-next-line react/no-unknown-property */}+ <div className="flex flex-col items-end gap-2 shrink-0" onClick={(e) => e.stopPropagation()}>+ <LemonTag type={statusTag.type} size="small">+ {statusTag.label}+ </LemonTag>+ {loading ? (+ <Spinner className="text-lg" />+ ) : requiresSetup ? (+ <LemonButton type="primary" size="small" onClick={() => onToggle(agent.source)}>+ Connect+ </LemonButton>+ ) : (+ <LemonSwitch+ checked={armed}+ onChange={() => onToggle(agent.source)}+ aria-label={`Arm ${agent.label}`}+ />+ )}+ </div>+ </div>++ {armed && agent.source === 'session_replay' && status === 'syncing' && (+ <div className="flex items-center gap-2 mt-2 ml-11">+ <Spinner className="text-sm text-accent" />+ <span className="text-sm text-accent">Session analysis run in progress…</span>+ </div>+ )}+ </div>+ )+})++export function AgentsRoster(): JSX.Element {+ const {+ sessionAnalysisConfig,+ conversationsConfig,+ githubIssuesConfig,+ linearIssuesConfig,+ zendeskTicketsConfig,+ pgAnalyzeIssuesConfig,+ errorTrackingIsFullyEnabled,+ isSessionAnalysisToggling,+ isConversationsToggling,+ isErrorTrackingToggling,+ isGithubIssuesToggling,+ isLinearIssuesToggling,+ isZendeskTicketsToggling,+ isPgAnalyzeIssuesToggling,+ } = useValues(signalSourcesLogic)+ const { toggleSessionAnalysis, toggleConversations, toggleErrorTracking, initiateDataWarehouseSourceToggle } =+ useActions(signalSourcesLogic)++ const stateFor = useCallback(+ (source: AgentRosterSource): AgentSourceState => {+ const dwState = (config: SignalSourceConfig | null, loading: boolean): AgentSourceState => ({+ armed: !!config?.enabled,+ loading,+ // No config row yet → the source has never been connected; surface a Connect button.+ requiresSetup: config === null,+ syncStatus: config?.status,+ })+ switch (source) {+ case 'error_tracking':+ return {+ armed: errorTrackingIsFullyEnabled,+ loading: isErrorTrackingToggling,+ requiresSetup: false,+ syncStatus: null,+ }+ case 'conversations':+ return {+ armed: !!conversationsConfig?.enabled,+ loading: isConversationsToggling,+ requiresSetup: false,+ syncStatus: conversationsConfig?.status,+ }+ case 'session_replay':+ return {+ armed: !!sessionAnalysisConfig?.enabled,+ loading: isSessionAnalysisToggling,+ requiresSetup: false,+ syncStatus: sessionAnalysisConfig?.status,+ }+ case 'github':+ return dwState(githubIssuesConfig, isGithubIssuesToggling)+ case 'linear':+ return dwState(linearIssuesConfig, isLinearIssuesToggling)+ case 'zendesk':+ return dwState(zendeskTicketsConfig, isZendeskTicketsToggling)+ case 'pganalyze':+ return dwState(pgAnalyzeIssuesConfig, isPgAnalyzeIssuesToggling)+ }+ },+ [+ errorTrackingIsFullyEnabled,+ isErrorTrackingToggling,+ conversationsConfig,+ isConversationsToggling,+ sessionAnalysisConfig,+ isSessionAnalysisToggling,+ githubIssuesConfig,+ isGithubIssuesToggling,+ linearIssuesConfig,+ isLinearIssuesToggling,+ zendeskTicketsConfig,+ isZendeskTicketsToggling,+ pgAnalyzeIssuesConfig,+ isPgAnalyzeIssuesToggling,+ ]+ )++ const handleToggle = useCallback(+ (source: AgentRosterSource) => {+ switch (source) {+ case 'error_tracking':+ toggleErrorTracking()+ return+ case 'conversations':+ toggleConversations()+ return+ case 'session_replay':+ toggleSessionAnalysis()+ return+ case 'github':+ initiateDataWarehouseSourceToggle('Github')+ return+ case 'linear':+ initiateDataWarehouseSourceToggle('Linear')+ return+ case 'zendesk':+ initiateDataWarehouseSourceToggle('Zendesk')+ return+ case 'pganalyze':+ initiateDataWarehouseSourceToggle('PgAnalyze')+ return+ }+ },+ [toggleErrorTracking, toggleConversations, toggleSessionAnalysis, initiateDataWarehouseSourceToggle]+ )++ return (+ <div className="flex flex-col gap-5">+ {AGENT_ROSTER_GROUPS.map((group) => (+ <div key={group.label} className="flex flex-col gap-2">+ <span className="text-[13px] font-medium text-muted">{group.label}</span>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {group.agents.map((agent) => (+ <AgentCard+ key={agent.source}+ agent={agent}+ state={stateFor(agent.source)}+ onToggle={handleToggle}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ )+}++function AgentCardSkeleton(): JSX.Element {+ return (+ <div className="rounded border border-primary bg-surface-primary p-3">+ <div className="flex items-start justify-between gap-3">+ <div className="flex items-start gap-3 min-w-0 flex-1">+ <LemonSkeleton className="size-8 shrink-0 rounded" />+ <div className="flex flex-col gap-2 min-w-0 flex-1">+ <LemonSkeleton className="h-3 w-1/2" />+ <LemonSkeleton className="h-3 w-1/3" />+ <LemonSkeleton className="h-3 w-4/5" />+ </div>+ </div>+ <LemonSkeleton className="h-5 w-16 shrink-0" />+ </div>+ </div>+ )+}++export function AgentsRosterSkeleton(): JSX.Element {+ return (+ <div className="flex flex-col gap-5">+ {AGENT_ROSTER_GROUPS.map((group) => (+ <div key={group.label} className="flex flex-col gap-2">+ <LemonSkeleton className="h-3 w-24" />+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {group.agents.map((agent) => (+ <AgentCardSkeleton key={agent.source} />+ ))}+ </div>+ </div>+ ))}+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/AgentsTab.tsx b/frontend/src/scenes/inbox/components/config/AgentsTab.tsxnew file mode 100644index 000000000000..b337235305d0--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/AgentsTab.tsx@@ -0,0 +1,220 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconArrowLeft } from '@posthog/icons'+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'++import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'++import { availableSourcesLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/availableSourcesLogic'+import { sourceWizardLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic'+import SourceForm from 'products/data_warehouse/frontend/shared/components/forms/SourceForm'+import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'++import { SessionAnalysisSetup } from '../../SessionAnalysisSetup'+import { signalSourcesLogic } from '../../signalSourcesLogic'+import { AgentsRoster } from './AgentsRoster'+import { AutoStartThresholdSection } from './AutoStartThresholdSection'+import { ConnectionsSection } from './ConnectionsSection'+import { McpServersSection } from './McpServersSection'+import { ScoutsFleetSection } from './scouts/ScoutsFleetSection'+import { SlackNotificationsSection } from './SlackNotificationsSection'++// Each signal source reads from specific tables – pre-select them and make them required+const SIGNAL_SOURCE_REQUIRED_TABLES: Partial<Record<ExternalDataSourceType, string[]>> = {+ Github: ['issues'],+ Linear: ['issues'],+ Zendesk: ['tickets'],+ PgAnalyze: ['issues', 'servers'],+}++function Subsection({+ title,+ description,+ children,+}: {+ title: string+ description?: string+ children: React.ReactNode+}): JSX.Element {+ return (+ <div className="flex flex-col gap-4 border-t border-primary pt-6 first:border-t-0 first:pt-0">+ <div className="flex flex-col gap-1">+ <h4 className="font-semibold text-sm text-default mb-0">{title}</h4>+ {description && (+ <p className="text-xs text-secondary mt-0 mb-0 max-w-2xl leading-snug">{description}</p>+ )}+ </div>+ {children}+ </div>+ )+}++function BackLink({ onClick }: { onClick: () => void }): JSX.Element {+ return (+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} onClick={onClick} className="-ml-2 w-fit">+ Back+ </LemonButton>+ )+}++/**+ * Full-page Agents tab body for cloud Inbox – a high-fidelity port of the+ * PostHog Code desktop Agents view. Composes Connections, the agent roster,+ * Slack, auto-start, and MCP servers. Session-analysis and data-source setup+ * render inline (replacing the roster) when their sub-flow is open.+ */+export function AgentsTab(): JSX.Element {+ const { sessionAnalysisSetupOpen, dataSourceSetupProduct } = useValues(signalSourcesLogic)+ const {+ loadSources,+ loadSourceConfigs,+ closeSessionAnalysisSetup,+ closeDataSourceSetup,+ onDataSourceSetupComplete,+ } = useActions(signalSourcesLogic)++ useEffect(() => {+ loadSources()+ loadSourceConfigs()+ }, []) // eslint-disable-line react-hooks/exhaustive-deps++ const isDataSourceSetupOpen = dataSourceSetupProduct !== null++ let agentsBody: JSX.Element+ if (isDataSourceSetupOpen) {+ agentsBody = (+ <div className="flex flex-col gap-3">+ <BackLink onClick={closeDataSourceSetup} />+ <DataSourceSetup+ product={dataSourceSetupProduct}+ onComplete={() => onDataSourceSetupComplete(dataSourceSetupProduct)}+ />+ </div>+ )+ } else if (sessionAnalysisSetupOpen) {+ agentsBody = (+ <div className="flex flex-col gap-3">+ <BackLink onClick={closeSessionAnalysisSetup} />+ <SessionAnalysisSetup />+ </div>+ )+ } else {+ agentsBody = <AgentsRoster />+ }++ return (+ <div className="flex flex-col">+ <div className="mx-auto max-w-4xl w-full px-6 py-6 flex flex-col gap-8">+ <Subsection+ title="Connections"+ description="Foundational integrations responders read from and write to."+ >+ <ConnectionsSection />+ </Subsection>++ <Subsection+ title="Scouts"+ description="Scheduled agents that sweep this project on a cadence and emit findings to your inbox."+ >+ <ScoutsFleetSection />+ </Subsection>++ <Subsection+ title="Responders"+ description="Each source: 1. watches for signals, 2. spins up a Responder when something matters, 3. hands you solutions."+ >+ {agentsBody}+ </Subsection>++ <Subsection+ title="Slack"+ description="Post reports to channels and ping suggested reviewers. Invite PostHog with /invite @PostHog in each channel you use."+ >+ <SlackNotificationsSection />+ </Subsection>++ <Subsection+ title="Auto-start"+ description="Self-driving can start coding tasks automatically when a report is immediately actionable and assigned to you."+ >+ <AutoStartThresholdSection />+ </Subsection>++ <Subsection+ title="MCP servers"+ description="External tools agents can read from. PostHog data is always available; this is everything else."+ >+ <McpServersSection />+ </Subsection>+ </div>+ </div>+ )+}++function DataSourceSetup({+ product,+ onComplete,+}: {+ product: ExternalDataSourceType+ onComplete: () => void+}): JSX.Element {+ const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)++ if (availableSourcesLoading || availableSources === null) {+ return <LemonSkeleton />+ }++ const sourceConfig = Object.values(availableSources).find((s: SourceConfig) => s.name === product)+ if (!sourceConfig) {+ return <div>Source not found</div>+ }++ return (+ <BindLogic+ logic={sourceWizardLogic}+ props={{+ availableSources,+ requiredTables: SIGNAL_SOURCE_REQUIRED_TABLES[product],+ onComplete,+ }}+ >+ <DataSourceSetupForm sourceConfig={sourceConfig} />+ </BindLogic>+ )+}++function DataSourceSetupForm({ sourceConfig }: { sourceConfig: SourceConfig }): JSX.Element {+ const { isLoading, canGoNext } = useValues(sourceWizardLogic)+ const { setInitialConnector, onSubmit } = useActions(sourceWizardLogic)++ useEffect(() => {+ setInitialConnector(sourceConfig)+ }, []) // eslint-disable-line react-hooks/exhaustive-deps++ return (+ <div className="space-y-4">+ <div className="flex items-center gap-3">+ <SourceIcon type={sourceConfig.name} size="small" disableTooltip />+ <p className="text-sm text-muted-alt mb-0">+ Connect {sourceConfig.label ?? sourceConfig.name} as a data source to enable this signal.+ </p>+ </div>++ <SourceForm sourceConfig={sourceConfig} showPrefix={false} />++ <div className="flex justify-end">+ <LemonButton+ type="primary"+ loading={isLoading}+ disabledReason={!canGoNext ? 'Fill in the required fields' : undefined}+ onClick={() => onSubmit()}+ >+ Connect+ </LemonButton>+ </div>+ </div>+ )+}++export default AgentsTabdiff --git a/frontend/src/scenes/inbox/components/config/AutoStartThresholdSection.tsx b/frontend/src/scenes/inbox/components/config/AutoStartThresholdSection.tsxnew file mode 100644index 000000000000..b31d80ef3b92--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/AutoStartThresholdSection.tsx@@ -0,0 +1,107 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useEffect } from 'react'++import { IconBolt, IconPeople } from '@posthog/icons'+import { LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'++import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'+import { userAutonomyLogic } from '../../logics/userAutonomyLogic'+import { SignalReportPriority } from '../../types'++const NEVER_AUTOSTART_VALUE = '__never__'++/** P0–P4, matching desktop `AUTOSTART_PRIORITY_OPTIONS`. The team default is non-nullable, so no "Never". */+const TEAM_AUTOSTART_OPTIONS: { value: SignalReportPriority; label: string }[] = [+ { value: 'P0', label: 'P0 – Critical only' },+ { value: 'P1', label: 'P1 – High and above' },+ { value: 'P2', label: 'P2 – Medium and above' },+ { value: 'P3', label: 'P3 – Low and above' },+ { value: 'P4', label: 'P4 – All priorities' },+]++/** Per-user override adds "Never – review everything first" on top of the team options. */+const USER_AUTOSTART_OPTIONS: { value: string; label: string }[] = [+ { value: NEVER_AUTOSTART_VALUE, label: 'Never – review everything first' },+ ...TEAM_AUTOSTART_OPTIONS,+]++function TeamDefaultRow(): JSX.Element {+ useMountedLogic(signalTeamConfigLogic)+ const { teamConfig, teamConfigLoading } = useValues(signalTeamConfigLogic)+ const { loadTeamConfig, setDefaultAutostartPriority } = useActions(signalTeamConfigLogic)++ useEffect(() => {+ loadTeamConfig()+ }, []) // eslint-disable-line react-hooks/exhaustive-deps++ // Backend defaults this to P2, but the row may be unloaded; fall back to P2 for display.+ const value = teamConfig?.default_autostart_priority ?? 'P2'++ return (+ <div className="flex items-center justify-between gap-4 rounded border bg-bg-light px-3 py-2.5">+ <div className="flex items-start gap-3 min-w-0">+ <IconPeople className="size-5 shrink-0 mt-0.5 text-secondary" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default">Team default auto-create PR threshold</div>+ <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">+ The starting point for everyone on this team. Individuals can override it for themselves below.+ </p>+ </div>+ </div>+ {teamConfigLoading && teamConfig === null ? (+ <LemonSkeleton className="h-8 w-[260px] shrink-0" />+ ) : (+ <LemonSelect+ className="min-w-[260px] shrink-0"+ value={value}+ options={TEAM_AUTOSTART_OPTIONS}+ onChange={(next) => setDefaultAutostartPriority(next as SignalReportPriority)}+ />+ )}+ </div>+ )+}++function UserOverrideRow(): JSX.Element {+ useMountedLogic(userAutonomyLogic)+ const { autonomyConfig, autonomyConfigLoading } = useValues(userAutonomyLogic)+ const { setAutostartPriority } = useActions(userAutonomyLogic)++ const value = autonomyConfig?.autostart_priority ?? NEVER_AUTOSTART_VALUE++ return (+ <div className="flex items-center justify-between gap-4 rounded border bg-bg-light px-3 py-2.5">+ <div className="flex items-start gap-3 min-w-0">+ <IconBolt className="size-5 shrink-0 mt-0.5 text-secondary" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default">Your auto-create PR threshold</div>+ <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">+ Reports at or above this priority automatically open a pull request for you. The backend+ deduplicates per report, and these runs count toward usage.+ </p>+ </div>+ </div>+ {autonomyConfigLoading && autonomyConfig === null ? (+ <LemonSkeleton className="h-8 w-[260px] shrink-0" />+ ) : (+ <LemonSelect+ className="min-w-[260px] shrink-0"+ value={value}+ options={USER_AUTOSTART_OPTIONS}+ onChange={(next) =>+ setAutostartPriority(next === NEVER_AUTOSTART_VALUE ? null : (next as SignalReportPriority))+ }+ />+ )}+ </div>+ )+}++export function AutoStartThresholdSection(): JSX.Element {+ return (+ <div className="flex flex-col gap-3">+ <TeamDefaultRow />+ <UserOverrideRow />+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/ConnectionsSection.tsx b/frontend/src/scenes/inbox/components/config/ConnectionsSection.tsxnew file mode 100644index 000000000000..c97dad00a0c4--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/ConnectionsSection.tsx@@ -0,0 +1,45 @@+import { useValues } from 'kea'++import { IconCheckCircle, IconChevronRight, IconGithub } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { urls } from 'scenes/urls'++export function ConnectionsSection(): JSX.Element {+ const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)++ const githubIntegrations = getIntegrationsByKind(['github'])+ const hasGithubIntegration = githubIntegrations.length > 0+ const isConnected = hasGithubIntegration && !integrationsLoading++ return (+ <div className="flex items-center justify-between gap-4 rounded border bg-bg-light px-3 py-2.5">+ <div className="flex items-start gap-3 min-w-0">+ <IconGithub className="size-5 shrink-0 mt-0.5 text-default" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default flex items-center gap-1.5">+ GitHub+ {isConnected && (+ <span className="inline-flex items-center gap-1 text-xs text-success font-normal">+ <IconCheckCircle className="size-3.5" />+ Connected+ </span>+ )}+ </div>+ <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">+ Foundational integration agents read from and write pull requests to.+ </p>+ </div>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ sideIcon={<IconChevronRight />}+ to={urls.settings('environment-integrations', 'integration-github')}+ >+ {hasGithubIntegration ? 'Manage' : 'Connect'}+ </LemonButton>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/McpServersSection.tsx b/frontend/src/scenes/inbox/components/config/McpServersSection.tsxnew file mode 100644index 000000000000..4e51fa42aa94--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/McpServersSection.tsx@@ -0,0 +1,25 @@+import { IconChevronRight, IconServer } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++export function McpServersSection(): JSX.Element {+ return (+ <Link+ to={urls.settings('mcp-servers')}+ className="group flex items-center justify-between gap-3 rounded border bg-bg-light px-3 py-2.5 no-underline transition-colors hover:border-primary-3000 hover:bg-bg-3000"+ >+ <div className="flex items-start gap-3 min-w-0">+ <IconServer className="size-5 shrink-0 mt-0.5 text-secondary" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default">Manage MCP servers</div>+ <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">+ External tools agents can read from. PostHog data is always available; this is everything else —+ connect or disconnect Notion, PagerDuty, Linear, Zendesk, GitHub, anything that speaks MCP.+ </p>+ </div>+ </div>+ <IconChevronRight className="size-4 shrink-0 text-muted transition-colors group-hover:text-default" />+ </Link>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/SignalSourcesPanel.tsx b/frontend/src/scenes/inbox/components/config/SignalSourcesPanel.tsxnew file mode 100644index 000000000000..8de049dcff94--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/SignalSourcesPanel.tsx@@ -0,0 +1,142 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconArrowLeft } from '@posthog/icons'+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'++import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'++import { availableSourcesLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/availableSourcesLogic'+import { sourceWizardLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic'+import SourceForm from 'products/data_warehouse/frontend/shared/components/forms/SourceForm'+import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'++import { SessionAnalysisSetup } from '../../SessionAnalysisSetup'+import { signalSourcesLogic } from '../../signalSourcesLogic'+import { AgentsRoster } from './AgentsRoster'++// Each signal source reads from specific tables – pre-select them and make them required+const SIGNAL_SOURCE_REQUIRED_TABLES: Partial<Record<ExternalDataSourceType, string[]>> = {+ Github: ['issues'],+ Linear: ['issues'],+ Zendesk: ['tickets'],+ PgAnalyze: ['issues', 'servers'],+}++function BackLink({ onClick }: { onClick: () => void }): JSX.Element {+ return (+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} onClick={onClick} className="-ml-2 w-fit">+ Back+ </LemonButton>+ )+}++/**+ * Signal sources management: the per-source roster (each source watches for signals and+ * spins up work when something matters), plus the session-analysis and data-source setup+ * sub-flows that render inline (replacing the roster) when their flow is open. Hosted in+ * the Signal sources setup modal.+ */+export function SignalSourcesPanel(): JSX.Element {+ const { sessionAnalysisSetupOpen, dataSourceSetupProduct } = useValues(signalSourcesLogic)+ const {+ loadSources,+ loadSourceConfigs,+ closeSessionAnalysisSetup,+ closeDataSourceSetup,+ onDataSourceSetupComplete,+ } = useActions(signalSourcesLogic)++ useEffect(() => {+ loadSources()+ loadSourceConfigs()+ }, []) // eslint-disable-line react-hooks/exhaustive-deps++ if (dataSourceSetupProduct !== null) {+ return (+ <div className="flex flex-col gap-3">+ <BackLink onClick={closeDataSourceSetup} />+ <DataSourceSetup+ product={dataSourceSetupProduct}+ onComplete={() => onDataSourceSetupComplete(dataSourceSetupProduct)}+ />+ </div>+ )+ }++ if (sessionAnalysisSetupOpen) {+ return (+ <div className="flex flex-col gap-3">+ <BackLink onClick={closeSessionAnalysisSetup} />+ <SessionAnalysisSetup />+ </div>+ )+ }++ return <AgentsRoster />+}++function DataSourceSetup({+ product,+ onComplete,+}: {+ product: ExternalDataSourceType+ onComplete: () => void+}): JSX.Element {+ const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)++ if (availableSourcesLoading || availableSources === null) {+ return <LemonSkeleton />+ }++ const sourceConfig = Object.values(availableSources).find((s: SourceConfig) => s.name === product)+ if (!sourceConfig) {+ return <div>Source not found</div>+ }++ return (+ <BindLogic+ logic={sourceWizardLogic}+ props={{+ availableSources,+ requiredTables: SIGNAL_SOURCE_REQUIRED_TABLES[product],+ onComplete,+ }}+ >+ <DataSourceSetupForm sourceConfig={sourceConfig} />+ </BindLogic>+ )+}++function DataSourceSetupForm({ sourceConfig }: { sourceConfig: SourceConfig }): JSX.Element {+ const { isLoading, canGoNext } = useValues(sourceWizardLogic)+ const { setInitialConnector, onSubmit } = useActions(sourceWizardLogic)++ useEffect(() => {+ setInitialConnector(sourceConfig)+ }, []) // eslint-disable-line react-hooks/exhaustive-deps++ return (+ <div className="space-y-4">+ <div className="flex items-center gap-3">+ <SourceIcon type={sourceConfig.name} size="small" disableTooltip />+ <p className="text-sm text-muted-alt mb-0">+ Connect {sourceConfig.label ?? sourceConfig.name} as a data source to enable this signal.+ </p>+ </div>++ <SourceForm sourceConfig={sourceConfig} showPrefix={false} />++ <div className="flex justify-end">+ <LemonButton+ type="primary"+ loading={isLoading}+ disabledReason={!canGoNext ? 'Fill in the required fields' : undefined}+ onClick={() => onSubmit()}+ >+ Connect+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/SlackNotificationsSection.tsx b/frontend/src/scenes/inbox/components/config/SlackNotificationsSection.tsxnew file mode 100644index 000000000000..3c15bfb51d2d--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/SlackNotificationsSection.tsx@@ -0,0 +1,181 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { IconChevronRight } from '@posthog/icons'+import { LemonSelect, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'++import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'+import { IconSlack } from 'lib/lemon-ui/icons'+import { urls } from 'scenes/urls'++import { userAutonomyLogic } from '../../logics/userAutonomyLogic'+import { SignalReportPriority } from '../../types'++const NOTIFY_ALL_VALUE = '__all__'++/** Minimum report priority that triggers a Slack ping. "All priorities" maps to a null min-priority. */+const MIN_PRIORITY_OPTIONS: { value: SignalReportPriority | typeof NOTIFY_ALL_VALUE; label: string }[] = [+ { value: NOTIFY_ALL_VALUE, label: 'All priorities' },+ { value: 'P0', label: 'P0 only' },+ { value: 'P1', label: 'P1 and above' },+ { value: 'P2', label: 'P2 and above' },+ { value: 'P3', label: 'P3 and above' },+ { value: 'P4', label: 'P4 and above' },+]++/** Shown when there's no Slack workspace connected – links out to integration settings. */+function ConnectSlackPrompt(): JSX.Element {+ return (+ <Link+ to={urls.settings('environment-integrations', 'integration-slack')}+ className="group flex items-center justify-between gap-3 rounded border bg-bg-light px-3 py-2.5 no-underline transition-colors hover:border-primary-3000 hover:bg-bg-3000"+ >+ <div className="flex items-start gap-3 min-w-0">+ <IconSlack className="size-5 shrink-0 mt-0.5 grayscale" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default">Connect a Slack workspace</div>+ <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">+ Connect Slack to get pinged in your own channel when you're a suggested reviewer on a new inbox+ item.+ </p>+ </div>+ </div>+ <IconChevronRight className="size-4 shrink-0 text-muted transition-colors group-hover:text-default" />+ </Link>+ )+}++/**+ * Per-user Slack notification controls – a cloud port of desktop's+ * `SlackInboxNotificationsSettings` / `SignalSlackNotificationsSettings`.+ * Notifications are enabled when an integration + channel are both set; the+ * enable toggle clears them to disable. Min-priority gates which reports ping.+ * Backed by the `slack_notification_*` fields on `userAutonomyLogic`.+ */+export function SlackNotificationsSection(): JSX.Element {+ useMountedLogic(integrationsLogic)+ useMountedLogic(userAutonomyLogic)+ const { slackIntegrations, integrationsLoading } = useValues(integrationsLogic)+ const { autonomyConfig, autonomyConfigLoading } = useValues(userAutonomyLogic)+ const { updateSlackNotifications } = useActions(userAutonomyLogic)++ if (integrationsLoading && slackIntegrations === undefined) {+ return <LemonSkeleton className="h-20 w-full" />+ }++ const integrations = slackIntegrations ?? []+ if (integrations.length === 0) {+ return <ConnectSlackPrompt />+ }++ // Workspace is shared with the team default. Default to the only workspace, or the user's saved pick.+ const selectedIntegrationId = autonomyConfig?.slack_notification_integration_id ?? null+ const effectiveIntegration =+ integrations.find((i) => i.id === selectedIntegrationId) ?? (integrations.length === 1 ? integrations[0] : null)+ const channel = autonomyConfig?.slack_notification_channel ?? null+ const minPriority = autonomyConfig?.slack_notification_min_priority ?? null+ const notificationsEnabled = !!effectiveIntegration && !!channel++ const onToggleEnabled = (enabled: boolean): void => {+ if (enabled) {+ // Turning on just opens the workspace/channel pickers – the actual enable+ // happens once a channel is chosen. Persist the workspace if it's unambiguous.+ if (effectiveIntegration && selectedIntegrationId === null) {+ updateSlackNotifications({ integrationId: effectiveIntegration.id })+ }+ } else {+ // Disable by clearing the target.+ updateSlackNotifications({ integrationId: null, channel: null })+ }+ }++ const onWorkspaceChange = (integrationId: number): void => {+ // Switching workspaces clears the channel – it won't exist in the new workspace.+ updateSlackNotifications({ integrationId, channel: null })+ }++ const onChannelChange = (next: string | null): void => {+ if (next === null) {+ updateSlackNotifications({ channel: null })+ return+ }+ if (!effectiveIntegration) {+ return+ }+ updateSlackNotifications({ integrationId: effectiveIntegration.id, channel: next })+ }++ const onMinPriorityChange = (value: string): void => {+ updateSlackNotifications({+ minPriority: value === NOTIFY_ALL_VALUE ? null : (value as SignalReportPriority),+ })+ }++ // "On" means the pickers are visible; either an integration is explicitly selected or a channel is set.+ const showPickers = selectedIntegrationId !== null || !!channel++ return (+ <div className="flex flex-col gap-3 rounded border bg-bg-light px-3 py-2.5">+ <div className="flex items-start justify-between gap-4">+ <div className="flex items-start gap-3 min-w-0">+ <IconSlack className="size-5 shrink-0 mt-0.5 grayscale" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default">Notify me directly</div>+ <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">+ When you're a suggested reviewer, get pinged in your own channel. PostHog must be in the+ channel – invite it with <code>/invite @PostHog</code>.+ </p>+ </div>+ </div>+ <LemonSwitch+ checked={showPickers}+ onChange={onToggleEnabled}+ disabled={autonomyConfigLoading && autonomyConfig === null}+ aria-label="Enable Slack notifications"+ />+ </div>++ {showPickers && (+ <div className="flex flex-col gap-3 border-t border-primary border-dashed pt-3">+ {integrations.length > 1 && (+ <div className="flex flex-col gap-1 min-w-0">+ <span className="text-xs text-secondary">Workspace</span>+ <LemonSelect+ className="max-w-[260px]"+ value={effectiveIntegration?.id ?? null}+ options={integrations.map((i) => ({+ value: i.id,+ label: i.display_name || `Slack workspace ${i.id}`,+ }))}+ onChange={(next) => next != null && onWorkspaceChange(next)}+ placeholder="Select workspace"+ />+ </div>+ )}++ {effectiveIntegration && (+ <div className="flex flex-col gap-1 min-w-0 max-w-md">+ <span className="text-xs text-secondary">Channel</span>+ <SlackChannelPicker+ integration={effectiveIntegration}+ value={channel ?? undefined}+ onChange={onChannelChange}+ />+ </div>+ )}++ <div className="flex flex-col gap-1 min-w-0">+ <span className="text-xs text-secondary">Min. priority</span>+ <LemonSelect+ className="max-w-[240px]"+ value={minPriority ?? NOTIFY_ALL_VALUE}+ options={MIN_PRIORITY_OPTIONS}+ disabledReason={!notificationsEnabled ? 'Pick a channel first' : undefined}+ onChange={onMinPriorityChange}+ />+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/agentRosterMeta.ts b/frontend/src/scenes/inbox/components/config/agentRosterMeta.tsnew file mode 100644index 000000000000..a53ab36b4f38--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/agentRosterMeta.ts@@ -0,0 +1,105 @@+import { SignalSourceProduct } from '~/queries/schema/schema-signals'++import { DataWarehouseSource } from '../../signalSourcesLogic'++/**+ * Stable string keys for the agent roster, aligned with the source-product+ * strings the backend uses. These drive icon lookup via `getSourceProductMeta`+ * and the per-source wiring in `AgentsRoster`.+ */+export type AgentRosterSource =+ | 'error_tracking'+ | 'conversations'+ | 'session_replay'+ | 'github'+ | 'linear'+ | 'zendesk'+ | 'pganalyze'++export interface AgentRosterDefinition {+ source: AgentRosterSource+ /** Key into `SOURCE_PRODUCT_META` for the icon tile. */+ sourceProduct: SignalSourceProduct+ label: string+ description: string+ docsUrl?: string+ docsLabel?: string+ alpha?: boolean+ /**+ * For data-warehouse-backed sources, the wizard product passed to+ * `initiateDataWarehouseSourceToggle`. Absent for native PostHog sources+ * (error tracking, session replay).+ */+ dataWarehouseSource?: DataWarehouseSource+}++export interface AgentRosterGroup {+ label: string+ agents: AgentRosterDefinition[]+}++export const AGENT_ROSTER_GROUPS: AgentRosterGroup[] = [+ {+ label: 'PostHog data',+ agents: [+ {+ source: 'error_tracking',+ sourceProduct: SignalSourceProduct.ERROR_TRACKING,+ label: 'Error tracking',+ description: 'Bugs surfaced as new errors, regressions, and spikes.',+ docsUrl: 'https://posthog.com/docs/error-tracking',+ docsLabel: 'Error tracking',+ },+ {+ source: 'conversations',+ sourceProduct: SignalSourceProduct.CONVERSATIONS,+ label: 'Support',+ description: 'Problems customers raise in support.',+ docsUrl: 'https://posthog.com/docs/support',+ docsLabel: 'Support',+ },+ {+ source: 'session_replay',+ sourceProduct: SignalSourceProduct.SESSION_REPLAY,+ label: 'Session replay',+ description: 'UX problems found in session recordings.',+ docsUrl: 'https://posthog.com/docs/session-replay',+ docsLabel: 'Session replay',+ alpha: true,+ },+ ],+ },+ {+ label: 'Connected tools',+ agents: [+ {+ source: 'github',+ sourceProduct: SignalSourceProduct.GITHUB,+ label: 'GitHub Issues',+ description: 'Issues filed in GitHub.',+ dataWarehouseSource: 'Github',+ },+ {+ source: 'linear',+ sourceProduct: SignalSourceProduct.LINEAR,+ label: 'Linear',+ description: 'Issues tracked in Linear.',+ dataWarehouseSource: 'Linear',+ },+ {+ source: 'zendesk',+ sourceProduct: SignalSourceProduct.ZENDESK,+ label: 'Zendesk',+ description: 'Incoming Zendesk tickets.',+ dataWarehouseSource: 'Zendesk',+ },+ {+ source: 'pganalyze',+ sourceProduct: SignalSourceProduct.PGANALYZE,+ label: 'pganalyze',+ description: 'Postgres performance problems – slow queries and bad indexes.',+ dataWarehouseSource: 'PgAnalyze',+ },+ ],+ },+]diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutBadges.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutBadges.tsxnew file mode 100644index 000000000000..229785142400--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutBadges.tsx@@ -0,0 +1,36 @@+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { SignalScoutConfig } from '../../../types'+import { getScoutOrigin } from '../../../utils/scoutRunsWindow'++/** Canonical (PostHog-maintained) vs Custom (team-authored) scout badge. */+export function ScoutOriginBadge({ skillName }: { skillName: string }): JSX.Element {+ const origin = getScoutOrigin(skillName)+ return (+ <Tooltip+ title={+ origin === 'canonical'+ ? 'Part of the standard scout troop built and maintained by PostHog'+ : 'A scout your team created as a signals-scout-* skill in this project'+ }+ >+ <LemonTag type={origin === 'canonical' ? 'muted' : 'highlight'} size="small">+ {origin === 'canonical' ? 'Canonical' : 'Custom'}+ </LemonTag>+ </Tooltip>+ )+}++/** Shown only when a scout runs on schedule but holds back its findings. */+export function DryRunBadge({ config }: { config: SignalScoutConfig }): JSX.Element | null {+ if (config.emit) {+ return null+ }+ return (+ <Tooltip title="Runs on schedule but findings are not emitted to the Signals inbox">+ <LemonTag type="caution" size="small">+ Dry run+ </LemonTag>+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsxnew file mode 100644index 000000000000..7e1b64714511--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsx@@ -0,0 +1,85 @@+import { LemonSelect, LemonSwitch, Tooltip } from '@posthog/lemon-ui'++import { SignalScoutConfig, SignalScoutConfigUpdate } from '../../../types'+import { formatRunInterval, RUN_INTERVAL_OPTIONS } from '../../../utils/scoutRunsWindow'++const MODE_OPTIONS = [+ { value: 'live', label: 'Live' },+ { value: 'dry_run', label: 'Dry run' },+]++interface ScoutConfigControlsProps {+ config: SignalScoutConfig+ onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void+}++function intervalOptions(config: SignalScoutConfig): { value: string; label: string }[] {+ const options = RUN_INTERVAL_OPTIONS.map((option) => ({+ value: String(option.minutes),+ label: option.label,+ }))+ if (!RUN_INTERVAL_OPTIONS.some((option) => option.minutes === config.run_interval_minutes)) {+ options.push({+ value: String(config.run_interval_minutes),+ label: formatRunInterval(config.run_interval_minutes),+ })+ }+ return options+}++/** Enable/disable toggle for a scout. Lives on the row, not in the settings form. */+export function ScoutEnabledSwitch({ config, onUpdate }: ScoutConfigControlsProps): JSX.Element {+ return (+ <Tooltip title={config.enabled ? 'Disable scout' : 'Enable scout'}>+ <span>+ <LemonSwitch+ size="small"+ checked={config.enabled}+ onChange={(checked) => onUpdate(config.id, { enabled: checked })}+ aria-label={`${config.skill_name} enabled`}+ />+ </span>+ </Tooltip>+ )+}++/**+ * Labeled settings form for one scout, shown when a fleet row's gear is toggled+ * open. Everything except enablement, which stays on the row.+ */+export function ScoutConfigForm({ config, onUpdate }: ScoutConfigControlsProps): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-4">+ <div className="flex flex-col min-w-0">+ <span className="text-xs text-default">Mode</span>+ <span className="text-[11.5px] text-muted">+ Dry run executes the scout but holds back its findings+ </span>+ </div>+ <LemonSelect+ size="small"+ value={config.emit ? 'live' : 'dry_run'}+ options={MODE_OPTIONS}+ disabledReason={config.enabled ? undefined : 'Enable the scout first'}+ className="w-24"+ onChange={(value) => onUpdate(config.id, { emit: value === 'live' })}+ />+ </div>+ <div className="flex items-center justify-between gap-4">+ <div className="flex flex-col min-w-0">+ <span className="text-xs text-default">Cadence</span>+ <span className="text-[11.5px] text-muted">How often the scout is dispatched</span>+ </div>+ <LemonSelect+ size="small"+ value={String(config.run_interval_minutes)}+ options={intervalOptions(config)}+ disabledReason={config.enabled ? undefined : 'Enable the scout first'}+ className="w-36"+ onChange={(value) => onUpdate(config.id, { run_interval_minutes: Number(value) })}+ />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutHelperSkillLinks.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutHelperSkillLinks.tsxnew file mode 100644index 000000000000..9e3c816f7106--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutHelperSkillLinks.tsx@@ -0,0 +1,25 @@+import { Link } from '@posthog/lemon-ui'++// Desktop opens these two scout helper skills in its in-app Skills view; cloud has+// no in-app Skills surface, so they link out to the equivalent PostHog docs.+const HELPER_SKILLS = [+ { label: 'authoring scouts', url: 'https://posthog.com/docs/signals' },+ { label: 'exploring scouts', url: 'https://posthog.com/docs/signals' },+]++/** One-line pointer to the two official scout helper skills. */+export function ScoutHelperSkillLinks(): JSX.Element {+ return (+ <span className="text-xs text-muted">+ Helper skills:{' '}+ {HELPER_SKILLS.map((skill, index) => (+ <span key={skill.label}>+ {index > 0 ? ' · ' : null}+ <Link to={skill.url} target="_blank">+ {skill.label}+ </Link>+ </span>+ ))}+ </span>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutRowCard.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutRowCard.tsxnew file mode 100644index 000000000000..007b264dc63d--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutRowCard.tsx@@ -0,0 +1,113 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconGear, IconSparkles } from '@posthog/icons'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'++import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'+import { SignalScoutConfig, SignalScoutConfigUpdate } from '../../../types'+import {+ buildScoutCheckinPrompt,+ formatRunIntervalShort,+ prettifyScoutSkillName,+ ScoutRollup,+} from '../../../utils/scoutRunsWindow'+import { DryRunBadge, ScoutOriginBadge } from './ScoutBadges'+import { ScoutConfigForm, ScoutEnabledSwitch } from './ScoutConfigControls'+import { ScoutRunBoxes } from './ScoutRunBoxes'++/**+ * The one scout card: name, badges, cadence, emitted count, run boxes, enable+ * switch, a chat check-in button, and a gear that expands the settings form.+ */+export function ScoutRowCard({+ config,+ rollup,+ onUpdate,+}: {+ config: SignalScoutConfig+ rollup: ScoutRollup | undefined+ onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void+}): JSX.Element {+ const [settingsOpen, setSettingsOpen] = useState(false)++ return (+ <div+ className={clsx(+ 'group flex flex-col rounded border border-primary bg-bg-light px-4 py-3 transition-colors hover:border-primary-3000 hover:bg-bg-3000',+ !config.enabled && 'opacity-65'+ )}+ >+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <Tooltip title={config.skill_name}>+ <span className="truncate font-medium text-sm text-default">+ {prettifyScoutSkillName(config.skill_name)}+ </span>+ </Tooltip>+ <ScoutOriginBadge skillName={config.skill_name} />+ <DryRunBadge config={config} />+ <span className="whitespace-nowrap text-[11px] text-muted">+ {formatRunIntervalShort(config.run_interval_minutes)}+ </span>+ {rollup && rollup.emittedCount > 0 ? (+ <span className="whitespace-nowrap text-[11px] text-muted">+ · {pluralize(rollup.emittedCount, 'signal')} emitted+ </span>+ ) : null}+ </div>+ <div className="shrink-0">+ <ScoutRunBoxes runs={rollup?.runs ?? []} />+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <ScoutEnabledSwitch config={config} onUpdate={onUpdate} />+ <ScoutChatButton skillName={config.skill_name} />+ <Tooltip title="Scout settings">+ <LemonButton+ size="small"+ icon={<IconGear />}+ active={settingsOpen}+ onClick={() => setSettingsOpen((value) => !value)}+ aria-label={`${config.skill_name} settings`}+ />+ </Tooltip>+ </div>+ </div>+ {settingsOpen ? (+ <div className="mt-3 border-t border-primary pt-3">+ <ScoutConfigForm config={config} onUpdate={onUpdate} />+ </div>+ ) : null}+ </div>+ )+}++/**+ * Icon-only chat CTA on the row: fires a one-click auto-mode cloud task asking+ * about this specific scout, then navigates to it.+ */+function ScoutChatButton({ skillName }: { skillName: string }): JSX.Element {+ const { startScoutChatTask } = useActions(scoutFleetLogic)+ const { chatTaskRunning } = useValues(scoutFleetLogic)+ return (+ <Tooltip title="Ask PostHog about this scout">+ <LemonButton+ size="small"+ icon={<IconSparkles />}+ loading={chatTaskRunning}+ disabledReason={chatTaskRunning ? 'Starting a task…' : undefined}+ onClick={() =>+ startScoutChatTask(+ buildScoutCheckinPrompt(skillName, prettifyScoutSkillName(skillName)),+ 'scout check-in',+ `Scout check-in: ${prettifyScoutSkillName(skillName)}`+ )+ }+ aria-label={`Ask PostHog about the ${skillName} scout`}+ />+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutRunBoxes.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutRunBoxes.tsxnew file mode 100644index 000000000000..0940264ae696--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutRunBoxes.tsx@@ -0,0 +1,91 @@+import { useMemo } from 'react'++import { Link, Tooltip } from '@posthog/lemon-ui'++import { humanFriendlyDetailedTime } from 'lib/utils/datetime'++import { SignalScoutRunSummary } from '../../../types'+import {+ deriveRunOutcome,+ formatRunDuration,+ runDurationSeconds,+ ScoutRunOutcome,+ scoutRunOutcomeLabel,+} from '../../../utils/scoutRunsWindow'++// Quiet is the common, healthy baseline so it recedes to muted; saturated color+// only means something happened – purple emission payoff, red/amber trouble.+const OUTCOME_BOX_CLASS: Record<ScoutRunOutcome, string> = {+ emitted: 'bg-primary-3000',+ quiet: 'bg-border-bold',+ error: 'bg-danger',+ timed_out: 'bg-warning',+ running: 'bg-primary animate-pulse',+ stuck: 'bg-danger animate-pulse',+ queued: 'border border-border-bold bg-transparent',+ unknown: 'bg-border',+}++const MAX_BOXES = 24+const BOX_CLASS = 'block h-3 w-2 rounded-[2px] transition-transform duration-100 hover:scale-y-125'++function runTooltip(run: SignalScoutRunSummary, now: Date): string {+ const parts = [scoutRunOutcomeLabel(run, now)]+ const duration = formatRunDuration(runDurationSeconds(run, now))+ if (duration) {+ parts.push(duration)+ }+ if (run.started_at) {+ parts.push(humanFriendlyDetailedTime(run.started_at))+ }+ return parts.join(' · ')+}++/**+ * One small box per run in the visible window, oldest on the left. Each box+ * links out to cloud's Tasks UI via the run's relative `task_url`; runs without+ * a task link are tooltip-only.+ */+export function ScoutRunBoxes({ runs }: { runs: SignalScoutRunSummary[] }): JSX.Element | null {+ const visible = useMemo(() => {+ const now = new Date()+ return runs.slice(-MAX_BOXES).map((run) => ({+ run,+ outcome: deriveRunOutcome(run, now),+ tooltip: runTooltip(run, now),+ }))+ }, [runs])++ if (runs.length === 0) {+ return null+ }+ const hidden = runs.length - visible.length++ return (+ <div className="flex items-center gap-2 shrink-0">+ {hidden > 0 ? <span className="text-[10px] text-muted">+{hidden}</span> : null}+ <div className="flex items-center gap-1">+ {visible.map(({ run, outcome, tooltip }) => {+ const boxClass = `${BOX_CLASS} ${OUTCOME_BOX_CLASS[outcome]}`+ if (run.task_url) {+ const linkTooltip = `${tooltip} · open task run`+ return (+ <Tooltip key={run.run_id} title={linkTooltip}>+ <Link to={run.task_url} className={boxClass}>+ <span className="sr-only">Run {linkTooltip}</span>+ </Link>+ </Tooltip>+ )+ }+ return (+ <Tooltip key={run.run_id} title={tooltip}>+ <span className={boxClass}>+ <span className="sr-only">Run {tooltip}</span>+ </span>+ </Tooltip>+ )+ })}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsxnew file mode 100644index 000000000000..f37bf8e2a5e1--- /dev/null+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsx@@ -0,0 +1,191 @@+import { useActions, useValues } from 'kea'++import { IconChevronDown, IconCompass, IconPlus, IconSparkles } from '@posthog/icons'+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { percentage } from 'lib/utils/numbers'+import { pluralize } from 'lib/utils/strings'++import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'+import { SignalScoutConfig } from '../../../types'+import {+ FleetSummary,+ SCOUT_AUTHOR_PROMPT,+ SCOUT_FLEET_OVERVIEW_PROMPT,+ SCOUT_RECENT_SIGNALS_PROMPT,+ SCOUT_RUNS_WINDOW_SPAN,+ scoutRunsWindowLabel,+} from '../../../utils/scoutRunsWindow'+import { ScoutHelperSkillLinks } from './ScoutHelperSkillLinks'+import { ScoutRowCard } from './ScoutRowCard'++/**+ * Expandable scout troop manager, hosted in the Scout troop setup modal. Collapsed it is a+ * one-line pulse; expanded it lists every scout with inline config controls.+ * Cloud port of desktop's `ScoutsFleetSection`.+ */+export function ScoutsFleetSection(): JSX.Element {+ const { scoutConfigs, scoutConfigsLoading, expanded, enabledCount, lastRunAt } = useValues(scoutFleetLogic)+ const { setExpanded, loadScoutConfigs } = useActions(scoutFleetLogic)++ if (scoutConfigsLoading && scoutConfigs === null) {+ return <LemonSkeleton className="h-12 w-full rounded" />+ }++ // A failed request must not masquerade as an empty troop – a missing scope or+ // regional rollout gap would otherwise be indistinguishable from "no scouts yet".+ if (scoutConfigs === null) {+ return (+ <div className="flex items-center gap-3 rounded border border-danger bg-danger-highlight px-4 py-3.5">+ <span className="flex-1 text-xs text-danger">+ Couldn't load the scout troop. The scout API may be unavailable or this project may not be enrolled+ yet.+ </span>+ <LemonButton type="secondary" size="small" status="danger" onClick={() => loadScoutConfigs()}>+ Retry+ </LemonButton>+ </div>+ )+ }++ if (scoutConfigs.length === 0) {+ return <ScoutsEmptyState />+ }++ return (+ <div className="flex flex-col gap-3">+ <button+ type="button"+ onClick={() => setExpanded(!expanded)}+ aria-expanded={expanded}+ className="flex w-full items-center justify-between gap-3 rounded border border-primary bg-bg-light px-4 py-3.5 text-left transition-colors hover:border-primary-3000 hover:bg-bg-3000"+ >+ <div className="flex items-center gap-3 min-w-0">+ <IconCompass className="size-5 shrink-0 text-primary-3000" />+ <div className="flex flex-col min-w-0">+ <span className="font-medium text-sm text-default">Scout troop</span>+ <span className="text-xs text-secondary leading-snug">+ {enabledCount} of {scoutConfigs.length} scouts enabled+ {lastRunAt ? (+ <>+ {' · last dispatched '}+ <TZLabel time={lastRunAt} />+ </>+ ) : null}+ </span>+ </div>+ </div>+ <IconChevronDown+ className={`size-4 shrink-0 text-muted transition-transform ${expanded ? '' : '-rotate-90'}`}+ />+ </button>+ {expanded ? <ScoutsFleetList /> : null}+ </div>+ )+}++/** One-line fleet pulse: running, success rate, signals emitted + emit rate. */+function summarize(summary: FleetSummary | null): string {+ if (!summary) {+ return 'None running now'+ }+ const parts = [summary.runningCount > 0 ? `${summary.runningCount} running now` : 'None running now']+ if (summary.successRate !== null) {+ parts.push(`${percentage(summary.successRate, 0)} success`)+ }+ const emittedPart =+ summary.emitRate !== null+ ? `${pluralize(summary.emittedCount, 'signal')} emitted (${percentage(summary.emitRate, 0)})`+ : `${pluralize(summary.emittedCount, 'signal')} emitted`+ parts.push(emittedPart)+ return parts.join(' · ')+}++function ScoutsFleetList(): JSX.Element {+ const { visibleConfigs, rollups, fleetSummary, hideDisabled, runsWindowComplete } = useValues(scoutFleetLogic)+ const { setHideDisabled, updateScoutConfig } = useActions(scoutFleetLogic)++ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-secondary">+ {summarize(fleetSummary)}+ <span className="text-muted"> · {scoutRunsWindowLabel(runsWindowComplete)}</span>+ </span>+ <span className="flex-1" />+ <LemonButton size="xsmall" type="tertiary" onClick={() => setHideDisabled(!hideDisabled)}>+ {hideDisabled ? 'Show disabled' : 'Hide disabled'}+ </LemonButton>+ </div>++ <div className="flex items-center gap-2 flex-wrap">+ <ScoutChatCta label="How is my scout troop performing?" prompt={SCOUT_FLEET_OVERVIEW_PROMPT} />+ <ScoutChatCta label="What signals were emitted recently?" prompt={SCOUT_RECENT_SIGNALS_PROMPT} />+ <ScoutChatCta label="Make a scout" prompt={SCOUT_AUTHOR_PROMPT} icon={<IconPlus />} />+ </div>++ {/* Bounded to roughly 10 rows; larger troops scroll within the section. */}+ <div className="max-h-[710px] overflow-y-auto">+ <div className="flex flex-col gap-2">+ {visibleConfigs.map((config: SignalScoutConfig) => (+ <ScoutRowCard+ key={config.id}+ config={config}+ rollup={rollups.get(config.skill_name)}+ onUpdate={updateScoutConfig}+ />+ ))}+ </div>+ </div>++ <div className="flex flex-col gap-1">+ <span className="text-xs text-muted">+ Run counts and emitted totals cover the last {SCOUT_RUNS_WINDOW_SPAN} of troop runs. New scouts are+ created as <span className="font-mono text-[11px]">signals-scout-*</span> skills in your PostHog+ project.+ </span>+ <ScoutHelperSkillLinks />+ </div>+ </div>+ )+}++/**+ * Suggestion-chip CTA that fires an auto-mode cloud task asking a templated+ * question, then navigates to it – same one-click shape as the inbox+ * discuss / create-PR flows.+ */+function ScoutChatCta({ label, prompt, icon }: { label: string; prompt: string; icon?: JSX.Element }): JSX.Element {+ const { startScoutChatTask } = useActions(scoutFleetLogic)+ const { chatTaskRunning } = useValues(scoutFleetLogic)+ return (+ <LemonButton+ type="secondary"+ size="small"+ icon={icon ?? <IconSparkles />}+ loading={chatTaskRunning}+ disabledReason={chatTaskRunning ? 'Starting a task…' : undefined}+ onClick={() => startScoutChatTask(prompt, label, label)}+ >+ {label}+ </LemonButton>+ )+}++function ScoutsEmptyState(): JSX.Element {+ return (+ <div className="flex flex-col items-start gap-2 rounded border border-primary bg-bg-light px-5 py-5">+ <div className="flex items-center gap-2">+ <IconCompass className="size-[18px] text-primary-3000" />+ <span className="font-medium text-sm text-default">No scouts on this project yet</span>+ </div>+ <p className="max-w-2xl text-xs text-secondary leading-snug mb-0">+ Scouts are rolling out gradually. Once your project is enrolled, the canonical troop appears here+ automatically and you can add custom scouts by creating{' '}+ <span className="font-mono text-[11px]">signals-scout-*</span> skills in PostHog.+ </p>+ <ScoutHelperSkillLinks />+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsxnew file mode 100644index 000000000000..4b13d9b3ccf1--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx@@ -0,0 +1,225 @@+import { useValues } from 'kea'++import {+ IconArrowRight,+ IconCheckCircle,+ IconClock,+ IconDocument,+ IconPullRequest,+ IconSearch,+ IconWarning,+} from '@posthog/icons'+import { Link, Spinner, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { SignalNode } from 'scenes/debug/signals/types'+import { urls } from 'scenes/urls'++import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'+import { SignalCard } from '../../SignalCard'+import { SignalReport, SignalReportStatus } from '../../types'+import { deriveHeadline, parsePrRepoSlug, parsePrUrlParts } from '../../utils/reportPresentation'+import { getSourceProductMeta } from '../badges/sourceProductIcons'+import { DetailSection, RightColumnSection } from './DetailSection'+import { ReportDetailBadges } from './ReportDetail'+import { ReportTasksSection } from './ReportTasksSection'++/**+ * Ready-state run output: a polished outcome card that links to the produced PR or report,+ * mirroring desktop `RunOutputReadyCard`. Status glyph, PR ref / source, headline, and a+ * call-to-action to open the result.+ */+function RunOutputReadyCard({ report }: { report: SignalReport }): JSX.Element {+ const prUrl = report.implementation_pr_url ?? null+ const isPr = !!prUrl+ const prSlug = prUrl ? parsePrRepoSlug(prUrl) : null+ const prNumber = prUrl ? (parsePrUrlParts(prUrl)?.number ?? null) : null+ const sourceMeta = getSourceProductMeta(report.source_products?.[0])+ const headline = report.title || deriveHeadline(report.summary)++ return (+ <Link+ to={urls.inboxReport(isPr ? 'pulls' : 'reports', report.id)}+ className="group flex flex-col gap-2 rounded border border-primary bg-surface-primary px-4 py-3.5 no-underline text-inherit transition-colors duration-150 hover:border-primary hover:bg-surface-secondary"+ >+ <div className="flex items-center gap-2 flex-wrap">+ <span className="flex items-center justify-center size-5 shrink-0 rounded-full bg-success-highlight text-success">+ {isPr ? <IconPullRequest className="text-xs" /> : <IconCheckCircle className="text-xs" />}+ </span>+ {prSlug && prNumber ? (+ <span className="font-mono text-[12.5px] text-primary">+ {prSlug}#{prNumber}+ </span>+ ) : (+ <span className="font-medium text-sm text-primary">Report ready</span>+ )}+ <span className="flex-1" />+ {sourceMeta ? (+ <span className="flex items-center gap-1.5 text-xs text-tertiary">+ <span className="flex shrink-0 items-center" style={{ color: sourceMeta.color }} aria-hidden>+ <sourceMeta.Icon className="text-sm" />+ </span>+ <span>{sourceMeta.label}</span>+ </span>+ ) : null}+ </div>+ {headline ? (+ <span className="line-clamp-2 text-[12.5px] text-secondary leading-snug">{headline}</span>+ ) : null}+ <span className="flex items-center gap-1 text-xs text-tertiary">+ {isPr ? 'Open the pull request' : 'Open the report'}+ <IconArrowRight className="transition-transform group-hover:translate-x-0.5" />+ </span>+ </Link>+ )+}++/**+ * Run-output widget: the headline state of an agent run. Ready → outcome card (PR/report);+ * failed → error banner; in-progress / queued → draft summary that fills in live.+ * Mirrors desktop `RunOutputWidget`.+ */+function RunOutputWidget({ report }: { report: SignalReport }): JSX.Element {+ if (report.status === SignalReportStatus.READY || report.implementation_pr_url) {+ return <RunOutputReadyCard report={report} />+ }++ if (report.status === SignalReportStatus.FAILED) {+ return (+ <div className="flex items-center gap-3 rounded border border-danger bg-danger-highlight px-4 py-3.5">+ <span className="flex items-center justify-center size-9 shrink-0 rounded-full bg-danger-highlight text-danger">+ <IconWarning className="size-4" />+ </span>+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">+ <span className="font-medium text-sm text-primary">Run failed</span>+ <span className="text-xs text-secondary leading-snug">+ Research couldn't complete – check the linked run below for the error. The agent may retry+ automatically.+ </span>+ </div>+ </div>+ )+ }++ return (+ <DetailSection icon={<IconDocument />} title="Draft summary">+ {report.summary ? (+ <LemonMarkdown className="text-sm text-secondary leading-normal" disableImages>+ {report.summary}+ </LemonMarkdown>+ ) : (+ <p className="text-sm text-tertiary m-0">+ {report.status === SignalReportStatus.IN_PROGRESS+ ? 'The agent is investigating – partial findings will appear here as they land.'+ : 'Queued for research.'}+ </p>+ )}+ </DetailSection>+ )+}++/**+ * Compact run-state strip: live/finished status, the produced branch (when a PR exists), and run+ * timing. Mirrors desktop's run-state header line (status · branch · timing) without rebuilding the+ * run log – the actual log lives behind the linked runs (see `ReportTasksSection`).+ */+function RunStateStrip({ report }: { report: SignalReport }): JSX.Element {+ const isLive =+ report.status === SignalReportStatus.IN_PROGRESS || report.status === SignalReportStatus.PENDING_INPUT+ const isFailed = report.status === SignalReportStatus.FAILED+ const prSlug = report.implementation_pr_url ? parsePrRepoSlug(report.implementation_pr_url) : null+ const timestamp = report.updated_at ?? report.created_at++ return (+ <div className="flex items-center gap-x-3 gap-y-1 flex-wrap text-xs text-tertiary">+ <span className="flex items-center gap-1.5 font-medium text-secondary">+ <span+ className={+ 'inline-block size-1.5 shrink-0 rounded-full ' ++ (isFailed ? 'bg-danger' : isLive ? 'bg-primary animate-pulse' : 'bg-success')+ }+ aria-hidden+ />+ {isFailed ? 'Failed' : isLive ? 'Running' : 'Finished'}+ </span>+ {prSlug ? (+ <span className="flex items-center gap-1 font-mono">+ <IconPullRequest className="text-sm" />+ {prSlug}+ </span>+ ) : null}+ <span className="flex items-center gap-1">+ <IconClock className="text-sm" />+ <span>{isLive ? 'Started' : 'Updated'}</span>+ <TZLabel time={timestamp} />+ </span>+ </div>+ )+}++/**+ * Agent run detail body. Shows the run state strip + output state, the linked run(s) (which link out+ * to the task detail page – we do NOT rebuild the run-log viewer here), and contributing evidence.+ * Mirrors desktop `AgentRunDetail`'s intent with cloud's existing task-detail run log.+ */+export function AgentRunDetail({ report }: { report: SignalReport }): JSX.Element {+ const { reportSignals, reportSignalsLoading, isReResearch, priorityExplanation, actionabilityExplanation } =+ useValues(inboxReportDetailLogic({ reportId: report.id, report }))+ const signals = reportSignals ?? []+ const evidenceCount = reportSignals !== null ? signals.length : report.signal_count++ return (+ <div className="@container w-full max-w-[calc(160ch+5rem)] mx-auto px-6 py-5 text-sm">+ <div className="flex items-center gap-2 flex-wrap mb-4">+ <ReportDetailBadges+ report={report}+ priorityExplanation={priorityExplanation}+ actionabilityExplanation={actionabilityExplanation}+ />+ {isReResearch && (+ <Tooltip title="A prior research run on this report already completed – this is a re-attempt.">+ <LemonTag size="small" type="warning" className="cursor-help select-none">+ Re-research+ </LemonTag>+ </Tooltip>+ )}+ </div>++ <div className="grid grid-cols-1 @4xl:grid-cols-[minmax(0,80ch)_minmax(0,1fr)] gap-5">+ <div className="flex flex-col min-w-0 gap-5">+ <RunStateStrip report={report} />+ <RunOutputWidget report={report} />+ <ReportTasksSection report={report} />+ </div>++ <div className="flex flex-col min-w-0 gap-5">+ {evidenceCount > 0 && (+ <RightColumnSection+ icon={<IconSearch />}+ title="Evidence so far"+ rightSlot={+ <span className="text-[0.6875rem] text-tertiary tabular-nums">+ {evidenceCount} finding{evidenceCount === 1 ? '' : 's'}+ </span>+ }+ >+ {reportSignalsLoading && reportSignals === null ? (+ <div className="flex items-center gap-2 text-xs text-tertiary py-1">+ <Spinner className="size-3" />+ Loading findings…+ </div>+ ) : (+ <div className="flex flex-col gap-3">+ {signals.map((signal: SignalNode) => (+ <SignalCard key={signal.signal_id} signal={signal} />+ ))}+ </div>+ )}+ </RightColumnSection>+ )}+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/DetailSection.tsx b/frontend/src/scenes/inbox/components/detail/DetailSection.tsxnew file mode 100644index 000000000000..91f84eedfb24--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/DetailSection.tsx@@ -0,0 +1,51 @@+import { ReactNode } from 'react'++interface DetailSectionProps {+ icon: ReactNode+ title: string+ rightSlot?: ReactNode+ children: ReactNode+}++/** Prominent content section with a spanning divider, used for the main column (Summary, Evidence). */+export function DetailSection({ icon, title, rightSlot, children }: DetailSectionProps): JSX.Element {+ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-3 min-w-0 cursor-default select-none">+ <div className="flex items-center gap-2 min-w-0">+ <span className="flex shrink-0 items-center text-secondary [&_svg]:size-[0.9375rem]">{icon}</span>+ <span className="truncate font-semibold text-sm text-primary tracking-tight">{title}</span>+ </div>+ <div className="h-px min-w-4 flex-1 bg-border-light" />+ {rightSlot && <div className="shrink-0">{rightSlot}</div>}+ </div>+ <div>{children}</div>+ </div>+ )+}++interface RightColumnSectionProps {+ icon: ReactNode+ title: string+ rightSlot?: ReactNode+ children: ReactNode+}++/**+ * Slim caption header used by sections in the detail-view right column (Runs, Reviewers).+ * Lighter than `DetailSection` so the side column reads as supporting detail.+ */+export function RightColumnSection({ icon, title, rightSlot, children }: RightColumnSectionProps): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2 cursor-default select-none text-tertiary">+ <div className="flex items-center gap-2">+ <span className="flex shrink-0 items-center [&_svg]:size-3">{icon}</span>+ <span className="font-medium text-[0.6875rem] uppercase tracking-wider">{title}</span>+ </div>+ {rightSlot && <div className="shrink-0">{rightSlot}</div>}+ </div>+ <div>{children}</div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsxnew file mode 100644index 000000000000..9ea1a8154f2c--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx@@ -0,0 +1,111 @@+import type { Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import {+ makeReport,+ mockArtefacts,+ mockReportTasks,+ mockReviewers,+ mockSignals,+ mockTask,+ pullRequestReports,+ reportTabReports,+ runReportsMany,+} from '../../__mocks__/inboxMocks'+import { SignalReportStatus } from '../../types'+import { AgentRunDetail } from './AgentRunDetail'+import { PullRequestDetail } from './PullRequestDetail'+import { ReportDetail } from './ReportDetail'++// Detail-body stories. Each detail component mounts the keyed `inboxReportDetailLogic`,+// which fetches artefacts / signals / tasks – mocked here. Polish the two-column detail+// layout (summary, evidence, runs, reviewers) against the desktop detail views.++const detailMocks = mswDecorator({+ get: {+ '/api/projects/:id/signals/reports/:reportId/artefacts': (req) => [+ 200,+ mockArtefacts(req.params.reportId as string),+ ],+ '/api/projects/:id/signals/reports/:reportId/signals': (req) => [+ 200,+ { report: null, signals: mockSignals(req.params.reportId as string, 4) },+ ],+ '/api/projects/:id/signals/reports/:reportId/tasks': (req) => [+ 200,+ mockReportTasks(req.params.reportId as string),+ ],+ '/api/projects/:id/signals/reports/available_reviewers': () => [200, mockReviewers],+ '/api/projects/:id/tasks/:taskId': (req) => [200, mockTask(req.params.taskId as string)],+ },+})++const meta: Meta = {+ title: 'Scenes-App/Inbox/Detail',+ parameters: { layout: 'fullscreen', viewMode: 'story', mockDate: '2026-06-11' },+ decorators: [detailMocks],+}+export default meta++type Story = StoryObj++function Frame({ children }: { children: React.ReactNode }): JSX.Element {+ return <div className="bg-primary min-h-screen py-4">{children}</div>+}++export const Report: Story = {+ render: () => (+ <Frame>+ <ReportDetail report={reportTabReports[0]} tab="reports" />+ </Frame>+ ),+}++export const ReportMinimal: Story = {+ render: () => (+ <Frame>+ <ReportDetail+ report={makeReport({+ title: 'No summary yet',+ summary: null,+ status: SignalReportStatus.CANDIDATE,+ signal_count: 1,+ })}+ tab="reports"+ />+ </Frame>+ ),+}++export const PullRequest: Story = {+ render: () => (+ <Frame>+ <PullRequestDetail report={pullRequestReports[0]} />+ </Frame>+ ),+}++export const RunInProgress: Story = {+ render: () => (+ <Frame>+ <AgentRunDetail report={runReportsMany.find((r) => r.status === SignalReportStatus.IN_PROGRESS)!} />+ </Frame>+ ),+}++export const RunFailed: Story = {+ render: () => (+ <Frame>+ <AgentRunDetail report={runReportsMany.find((r) => r.status === SignalReportStatus.FAILED)!} />+ </Frame>+ ),+}++export const RunReady: Story = {+ render: () => (+ <Frame>+ <AgentRunDetail report={pullRequestReports[0]} />+ </Frame>+ ),+}diff --git a/frontend/src/scenes/inbox/components/detail/InboxDetailHeader.tsx b/frontend/src/scenes/inbox/components/detail/InboxDetailHeader.tsxnew file mode 100644index 000000000000..3663b66fe12b--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/InboxDetailHeader.tsx@@ -0,0 +1,59 @@+import { IconArrowLeft } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { IconLink } from 'lib/lemon-ui/icons'+import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { addProjectIdIfMissing } from 'lib/utils/kea-router'+import { urls } from 'scenes/urls'++import { InboxTabKey, INBOX_TAB_LABEL, SignalReport } from '../../types'+import { displayConventionalCommitTitle, parseConventionalCommitTitle } from '../../utils/reportPresentation'+import { ConventionalCommitScopeTag } from '../cards/ReportCard'++/**+ * Header for the Runs detail view: a labeled back button, the conventional-commit title, and a+ * copy-link button that copies an absolute deep-link to the run. Report / PR / Not actionable+ * details render their own merged header inside `InboxDetailFrame`.+ */+export function InboxDetailHeader({ report, tab }: { report: SignalReport; tab: InboxTabKey }): JSX.Element {+ const conventionalTitle = parseConventionalCommitTitle(report.title)+ const displayTitle = displayConventionalCommitTitle(report.title, 'Untitled report')+ const reportPath = urls.inboxReport(tab, report.id)++ return (+ <div className="shrink-0 border-b border-primary px-6 pt-5 pb-4 flex flex-col gap-3">+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconArrowLeft />}+ to={urls.inbox(tab)}+ className="-ml-2 w-fit"+ >+ {INBOX_TAB_LABEL[tab]}+ </LemonButton>+ <div className="flex items-start justify-between gap-3 min-w-0">+ <h1 className="min-w-0 flex-1 m-0 break-words text-2xl font-bold leading-tight tracking-tight">+ {conventionalTitle && (+ <ConventionalCommitScopeTag type={conventionalTitle.type} scope={conventionalTitle.scope} />+ )}+ {displayTitle}+ </h1>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconLink />}+ tooltip="Copy a link to this report"+ className="shrink-0"+ onClick={() =>+ void copyToClipboard(+ `${window.location.origin}${addProjectIdIfMissing(reportPath)}`,+ 'report link'+ )+ }+ >+ Copy link+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/PullRequestDetail.tsx b/frontend/src/scenes/inbox/components/detail/PullRequestDetail.tsxnew file mode 100644index 000000000000..8fd7bb044d1b--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/PullRequestDetail.tsx@@ -0,0 +1,11 @@+import { SignalReport } from '../../types'+import { ReportDetail } from './ReportDetail'++/**+ * Pull request detail is now the unified `ReportDetail`, which renders the PR banner ++ * "Open in GitHub" action whenever the report has a shipped implementation PR. Kept as a+ * thin alias for back-compat (e.g. stories / any external imports).+ */+export function PullRequestDetail({ report }: { report: SignalReport }): JSX.Element {+ return <ReportDetail report={report} tab="pulls" />+}diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsxnew file mode 100644index 000000000000..48c2fc692e9f--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx@@ -0,0 +1,428 @@+import { useValues } from 'kea'+import { ReactNode } from 'react'++import { IconArrowLeft, IconCode, IconDocument, IconExternal, IconPullRequest, IconSearch } from '@posthog/icons'+import { LemonButton, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { IconLink } from 'lib/lemon-ui/icons'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { addProjectIdIfMissing } from 'lib/utils/kea-router'+import { SignalNode } from 'scenes/debug/signals/types'+import { urls } from 'scenes/urls'++import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'+import { SignalCard } from '../../SignalCard'+import { InboxTabKey, INBOX_TAB_LABEL, SignalReport, SignalReportStatus } from '../../types'+import {+ displayConventionalCommitTitle,+ ParsedPrUrlParts,+ parseConventionalCommitTitle,+ parsePrUrlParts,+ safeHttpUrl,+} from '../../utils/reportPresentation'+import { ForYouBadge } from '../badges/ForYouBadge'+import { SignalReportActionabilityBadge } from '../badges/SignalReportActionabilityBadge'+import { SignalReportPriorityBadge } from '../badges/SignalReportPriorityBadge'+import { SignalReportStatusBadge } from '../badges/SignalReportStatusBadge'+import { hasKnownSourceProduct, knownSourceProductEntries, SourceProductIconRow } from '../badges/sourceProductIcons'+import { ConventionalCommitScopeTag } from '../cards/ReportCard'+import { RightColumnSection } from './DetailSection'+import { ReportDetailActions } from './ReportDetailActions'+import { ReportTasksSection } from './ReportTasksSection'+import { SuggestedReviewersSection } from './SuggestedReviewersSection'++/**+ * Status / priority / actionability badges for a report's detail header. Mirrors desktop `InboxDetailFrame`.+ * The judgment rationale (when present) is sourced from the detail logic's loaded artefacts and surfaced by+ * a circled help icon overlaying the chip's top-right corner; the chip is then hoverable for the rationale.+ */+export function ReportDetailBadges({+ report,+ priorityExplanation,+ actionabilityExplanation,+}: {+ report: SignalReport+ priorityExplanation?: string | null+ actionabilityExplanation?: string | null+}): JSX.Element {+ return (+ <>+ <SignalReportPriorityBadge priority={report.priority} explanation={priorityExplanation} />+ {/* "Ready" is the default terminal state; once actionability is known, surface that instead. */}+ {(report.status !== 'ready' || !report.actionability) && <SignalReportStatusBadge status={report.status} />}+ <SignalReportActionabilityBadge+ actionability={report.actionability}+ explanation={actionabilityExplanation}+ />+ {report.is_suggested_reviewer && <ForYouBadge />}+ </>+ )+}++/**+ * Single meta line under the title: status/actionability/for-you chips, then dot-separated stats+ * (finding count · created [· updated] · source stack). The updated time is only shown when+ * it meaningfully differs from created. `evidenceCount` switches to the live signal count once+ * findings load, so the row reads the same before and after the query resolves.+ */+function ReportDetailMeta({+ report,+ evidenceCount,+ actionabilityExplanation,+}: {+ report: SignalReport+ evidenceCount: number+ actionabilityExplanation?: string | null+}): JSX.Element {+ const hasSource = hasKnownSourceProduct(report.source_products)+ // "Ready" is the default terminal state; surface the status chip only until actionability is known.+ const showStatus = report.status !== 'ready' || !report.actionability++ const stats: ReactNode[] = []+ if (evidenceCount > 0) {+ stats.push(+ <span className="tabular-nums">+ {evidenceCount} finding{evidenceCount === 1 ? '' : 's'}+ </span>+ )+ }+ // Updated is shown alongside Created only when they differ beyond same-moment noise (≥ 1 min apart).+ const updatedDiffers =+ !!report.updated_at && Math.abs(dayjs(report.updated_at).diff(dayjs(report.created_at), 'minute')) >= 1+ stats.push(+ <span className="flex items-center gap-1">+ <span>Created</span>+ <TZLabel time={report.created_at} />+ </span>+ )+ if (updatedDiffers) {+ stats.push(+ <span className="flex items-center gap-1">+ <span>Updated</span>+ <TZLabel time={report.updated_at} />+ </span>+ )+ }+ if (hasSource) {+ stats.push(<MetaSourceStack sourceProducts={report.source_products} />)+ }++ return (+ <div className="flex items-center gap-x-2 gap-y-1.5 flex-wrap text-xs text-tertiary leading-none select-none">+ {showStatus && <SignalReportStatusBadge status={report.status} />}+ <SignalReportActionabilityBadge+ actionability={report.actionability}+ explanation={actionabilityExplanation}+ />+ {report.is_suggested_reviewer && <ForYouBadge />}+ <span className="flex items-center gap-2 flex-wrap min-w-0">+ {stats.map((node, i) => (+ <span key={i} className="flex items-center gap-2 min-w-0">+ {i > 0 && <span aria-hidden>·</span>}+ {node}+ </span>+ ))}+ </span>+ </div>+ )+}++/** Source-product icon stack reused inside the detail meta row. */+function MetaSourceStack({ sourceProducts }: { sourceProducts?: string[] | null }): JSX.Element | null {+ const [primary, ...overflow] = knownSourceProductEntries(sourceProducts)+ if (!primary) {+ return null+ }+ return (+ <span className="inline-flex items-center gap-1.5 min-w-0">+ <SourceProductIconRow+ entries={[primary, ...overflow]}+ className="inline-flex items-center gap-1 shrink-0"+ />+ <span>+ {primary.meta.label}+ {overflow.length > 0 ? ` + ${overflow.length}` : null}+ </span>+ </span>+ )+}++/** Placeholder finding rows shown while the signals query is in flight, sized to the known count. */+function EvidenceSkeleton({ count }: { count: number }): JSX.Element {+ const rows = Math.max(1, Math.min(count, 4))+ return (+ <div className="flex flex-col gap-3" aria-hidden>+ {Array.from({ length: rows }).map((_, i) => (+ <div+ key={i}+ className="flex flex-col gap-2 rounded border border-primary bg-surface-primary px-3 py-2.5"+ >+ <div className="h-3 w-1/3 rounded bg-fill-highlight-100 animate-pulse" />+ <div className="h-2.5 w-4/5 rounded bg-fill-highlight-50 animate-pulse" />+ </div>+ ))}+ </div>+ )+}++/**+ * Layout-faithful placeholder shown while a report's base record loads on a cold open (deep link+ * with no list row to seed from). Mirrors `InboxDetailFrame`'s header + two-column shape so the+ * page doesn't jump when the real content lands — and so loading reads as "this view, populating"+ * rather than a bare centered spinner.+ */+export function ReportDetailSkeleton(): JSX.Element {+ return (+ <div className="@container w-full max-w-[calc(160ch+5rem)] mx-auto px-6 py-5 text-sm" aria-hidden>+ <div className="flex flex-col gap-3.5 mb-6 pb-5 border-b border-primary">+ <div className="h-3.5 w-24 rounded bg-fill-highlight-50 animate-pulse" />+ <div className="flex items-start justify-between gap-4 flex-wrap">+ <div className="flex items-start gap-3 min-w-0 flex-1">+ <div className="size-7 shrink-0 mt-0.5 rounded bg-fill-highlight-100 animate-pulse" />+ <div className="flex flex-col gap-2 min-w-0 flex-1">+ <div className="h-6 w-2/3 rounded bg-fill-highlight-100 animate-pulse" />+ <div className="h-3 w-1/2 rounded bg-fill-highlight-50 animate-pulse" />+ </div>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <div className="h-8 w-24 rounded bg-fill-highlight-50 animate-pulse" />+ <div className="h-8 w-20 rounded bg-fill-highlight-50 animate-pulse" />+ </div>+ </div>+ </div>++ <div className="grid grid-cols-1 @4xl:grid-cols-[minmax(0,80ch)_minmax(0,1fr)] gap-5">+ <div className="min-w-0 flex flex-col gap-2.5">+ <div className="h-4 w-28 rounded bg-fill-highlight-100 animate-pulse" />+ <div className="h-3 w-full rounded bg-fill-highlight-50 animate-pulse" />+ <div className="h-3 w-11/12 rounded bg-fill-highlight-50 animate-pulse" />+ <div className="h-3 w-3/4 rounded bg-fill-highlight-50 animate-pulse" />+ </div>+ <div className="flex flex-col min-w-0 gap-5">+ {Array.from({ length: 2 }).map((_, i) => (+ <div key={i} className="flex flex-col gap-2.5">+ <div className="h-4 w-24 rounded bg-fill-highlight-100 animate-pulse" />+ <div className="h-16 w-full rounded border border-primary bg-surface-primary animate-pulse" />+ </div>+ ))}+ </div>+ </div>+ </div>+ )+}++interface InboxDetailFrameProps {+ report: SignalReport+ /** Active inbox tab — drives the copy-link target in the merged header. */+ tab: InboxTabKey+ /** Summary section heading icon + title. */+ summary: { icon: ReactNode; title: string }+ /** Extra primary action(s) rendered after the shared report actions. */+ primaryAction?: ReactNode+ /** Extra sections (Tasks, Reviewers) – defaults applied by callers. */+ children?: ReactNode+}++/**+ * Shared chrome for the Report and Pull request detail bodies. Owns the full page header+ * (title, copy link) merged with the badges/meta/actions, then summary on the left+ * and supporting sections (Evidence, Runs, Reviewers) on the right. Mirrors desktop+ * `InboxDetailFrame`. AgentRunDetail keeps its own layout + shell header.+ */+export function InboxDetailFrame({+ report,+ tab,+ summary,+ primaryAction,+ children,+}: InboxDetailFrameProps): JSX.Element {+ const { reportSignals, reportSignalsLoading, priorityExplanation, actionabilityExplanation } = useValues(+ inboxReportDetailLogic({ reportId: report.id, report })+ )+ const signals = reportSignals ?? []+ const evidenceCount = reportSignals !== null ? signals.length : report.signal_count+ const hasEvidence = evidenceCount > 0++ const summaryPending =+ report.status === SignalReportStatus.IN_PROGRESS || report.status === SignalReportStatus.CANDIDATE++ const conventionalTitle = parseConventionalCommitTitle(report.title)+ const displayTitle = displayConventionalCommitTitle(report.title, 'Untitled report')+ const reportPath = urls.inboxReport(tab, report.id)++ return (+ <div className="@container w-full max-w-[calc(160ch+5rem)] mx-auto px-6 py-5 text-sm">+ <div className="flex flex-col gap-3.5 mb-6 pb-5 border-b border-primary">+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconArrowLeft />}+ to={urls.inbox(tab)}+ className="-ml-2 w-fit"+ >+ {INBOX_TAB_LABEL[tab]}+ </LemonButton>+ <div className="flex items-start justify-between gap-4 flex-wrap">+ {/* Priority square anchors the title; everything else collapses into the meta line. */}+ <div className="flex items-start gap-3 min-w-0 flex-1">+ {report.priority && (+ <div className="shrink-0 mt-0.5">+ <SignalReportPriorityBadge+ priority={report.priority}+ explanation={priorityExplanation}+ />+ </div>+ )}+ <div className="flex flex-col gap-2 min-w-0">+ <h1 className="min-w-0 m-0 break-words text-xl font-bold leading-tight tracking-tight">+ {conventionalTitle && (+ <ConventionalCommitScopeTag+ type={conventionalTitle.type}+ scope={conventionalTitle.scope}+ />+ )}+ {displayTitle}+ </h1>+ <ReportDetailMeta+ report={report}+ evidenceCount={evidenceCount}+ actionabilityExplanation={actionabilityExplanation}+ />+ </div>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconLink />}+ tooltip="Copy a link to this report"+ onClick={() =>+ void copyToClipboard(+ `${window.location.origin}${addProjectIdIfMissing(reportPath)}`,+ 'report link'+ )+ }+ >+ Copy link+ </LemonButton>+ <ReportDetailActions report={report} />+ {primaryAction}+ </div>+ </div>+ </div>++ <div className="grid grid-cols-1 @4xl:grid-cols-[minmax(0,80ch)_minmax(0,1fr)] gap-5">+ <div className="min-w-0">+ <RightColumnSection icon={summary.icon} title={summary.title}>+ {report.summary ? (+ <LemonMarkdown className="text-sm text-secondary leading-normal break-words" disableImages>+ {report.summary}+ </LemonMarkdown>+ ) : (+ <p className={`text-sm text-tertiary m-0${summaryPending ? ' italic' : ''}`}>+ No summary yet – an agent is still investigating.+ </p>+ )}+ </RightColumnSection>+ </div>++ <div className="flex flex-col min-w-0 gap-5">+ {/* Pull request (when present) first, then reviewers, evidence, and runs. */}+ {children}+ <SuggestedReviewersSection report={report} />+ {hasEvidence && (+ <RightColumnSection+ icon={<IconSearch />}+ title="Evidence"+ rightSlot={+ <span className="text-[0.6875rem] text-tertiary tabular-nums">+ {evidenceCount} finding{evidenceCount === 1 ? '' : 's'}+ </span>+ }+ >+ {reportSignalsLoading && reportSignals === null ? (+ <EvidenceSkeleton count={evidenceCount} />+ ) : (+ <div className="flex flex-col gap-3">+ {signals.map((signal: SignalNode) => (+ <SignalCard key={signal.signal_id} signal={signal} />+ ))}+ </div>+ )}+ </RightColumnSection>+ )}+ <ReportTasksSection report={report} />+ </div>+ </div>+ </div>+ )+}++/**+ * PR identity banner: the `repoSlug#number` ref, mono, with a PR glyph, linking out to GitHub.+ * Surfaced as the first right-column section when the report has a shipped implementation PR.+ */+function PullRequestBanner({ prUrl, prRef }: { prUrl: string; prRef: ParsedPrUrlParts }): JSX.Element {+ return (+ <Link+ to={prUrl}+ target="_blank"+ disableClientSideRouting+ className="group flex items-center gap-3 rounded border border-primary bg-surface-primary px-4 py-3 no-underline text-inherit transition-colors duration-150 hover:border-primary hover:bg-surface-secondary"+ >+ <span className="flex items-center justify-center size-7 shrink-0 rounded-full bg-success-highlight text-success">+ <IconPullRequest className="text-base" />+ </span>+ <span className="font-mono text-[13px] text-primary truncate">+ {prRef.repoSlug}#{prRef.number}+ </span>+ <Tooltip title="Open in GitHub">+ <span className="shrink-0 text-tertiary transition-colors group-hover:text-default">+ <IconExternal className="text-base" />+ </span>+ </Tooltip>+ </Link>+ )+}++/**+ * Unified report detail for Pull requests / Reports / Not actionable. The PR banner ++ * "Open in GitHub" action surface only when the report has a shipped implementation PR;+ * otherwise it reads as a plain report. Runs keep their own `AgentRunDetail`.+ */+export function ReportDetail({ report, tab }: { report: SignalReport; tab: InboxTabKey }): JSX.Element {+ const prUrl = safeHttpUrl(report.implementation_pr_url)+ const prRef = prUrl ? parsePrUrlParts(prUrl) : null+ const hasPr = !!(prRef && prUrl)++ return (+ <InboxDetailFrame+ report={report}+ tab={tab}+ summary={{ icon: hasPr ? <IconPullRequest /> : <IconDocument />, title: 'Summary' }}+ primaryAction={+ hasPr ? (+ <LemonButton+ type="primary"+ size="small"+ sideIcon={<IconExternal />}+ to={prUrl}+ targetBlank+ tooltip={`${prRef.repoSlug}#${prRef.number}`}+ >+ Open in GitHub+ </LemonButton>+ ) : undefined+ }+ >+ {hasPr ? (+ <RightColumnSection icon={<IconCode />} title="Diff">+ <PullRequestBanner prUrl={prUrl} prRef={prRef} />+ </RightColumnSection>+ ) : null}+ </InboxDetailFrame>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsxnew file mode 100644index 000000000000..b66993ac854b--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx@@ -0,0 +1,97 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { IconArchive, IconPullRequest } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { inboxSceneLogic } from '../../inboxSceneLogic'+import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { ACTIONABLE_ACTIONABILITY_VALUES, SignalReport } from '../../types'+import { useReportArchive } from '../cards/useReportArchive'++/** Mirror desktop's `Inbox report action` analytics for detail-pane actions. */+function fireReportAction(report: SignalReport, action: 'create_pr', extras: Record<string, unknown> = {}): void {+ posthog.capture('Inbox report action', {+ report_id: report.id,+ report_title: report.title ?? null,+ priority: report.priority ?? null,+ actionability: report.actionability ?? null,+ action_type: action,+ surface: 'detail_pane',+ ...extras,+ })+}++/**+ * Should the Create PR action be offered? Mirrors desktop `canCreateImplementationPr` /+ * the server-side autostart rules: only when ready & actionable, or blocked on user input.+ */+function canCreateImplementationPr(report: SignalReport): boolean {+ if (report.implementation_pr_url) {+ return false+ }+ if (report.already_addressed === true) {+ return false+ }+ if (report.status === 'pending_input') {+ return true+ }+ if (report.status === 'ready') {+ return report.actionability != null && ACTIONABLE_ACTIONABILITY_VALUES.includes(report.actionability)+ }+ return false+}++/**+ * Detail-pane actions: Archive (suppress the report out of the inbox, then return to the list)+ * and Create PR (opens an implementation task and navigates to it). Task creation/navigation is+ * owned by `inboxTaskKickoffLogic`; archiving reuses the shared `useReportArchive` dialog flow.+ */+export function ReportDetailActions({ report }: { report: SignalReport }): JSX.Element {+ const { isCreatingPr } = useValues(inboxTaskKickoffLogic)+ const { createPrFromReport } = useActions(inboxTaskKickoffLogic)+ const { activeTab } = useValues(inboxSceneLogic)++ const showCreatePr = canCreateImplementationPr(report)++ const { isArchiving, onArchiveClick } = useReportArchive({+ reportId: report.id,+ cardTitle: report.title ?? 'Untitled report',+ // Back to the list once archived – the suppressed report drops out on the list's refetch.+ onArchived: () => router.actions.push(urls.inbox(activeTab)),+ })++ return (+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconArchive />}+ loading={isArchiving}+ tooltip="Archive this report out of your inbox"+ onClick={onArchiveClick}+ >+ Archive+ </LemonButton>++ {showCreatePr && (+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPullRequest />}+ loading={isCreatingPr}+ tooltip="Have Self-driving open a pull request for this report"+ onClick={() => {+ fireReportAction(report, 'create_pr')+ createPrFromReport(report)+ }}+ >+ Create PR+ </LemonButton>+ )}+ </>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsxnew file mode 100644index 000000000000..2c5b6802fa22--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx@@ -0,0 +1,96 @@+import clsx from 'clsx'+import { useValues } from 'kea'+import { combineUrl } from 'kea-router'++import { IconChevronRight, IconTerminal } from '@posthog/icons'+import { Link, Spinner } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { Task, TaskRunStatus } from 'products/tasks/frontend/types'++import { inboxReportDetailLogic, ReportTaskEntry } from '../../logics/inboxReportDetailLogic'+import { SignalReport, SignalReportTaskRelationship } from '../../types'+import { RightColumnSection } from './DetailSection'++const RELATIONSHIP_LABEL: Record<SignalReportTaskRelationship, string> = {+ research: 'Research',+ implementation: 'Implementation',+ repo_selection: 'Repo selection',+}++const TERMINAL_STATUSES: TaskRunStatus[] = [TaskRunStatus.COMPLETED, TaskRunStatus.FAILED, TaskRunStatus.CANCELLED]++function TaskRunStatusDot({ status }: { status: TaskRunStatus }): JSX.Element {+ const terminal = TERMINAL_STATUSES.includes(status)+ const color =+ status === TaskRunStatus.FAILED || status === TaskRunStatus.CANCELLED+ ? 'bg-danger'+ : terminal+ ? 'bg-success'+ : 'bg-primary'+ return (+ <span+ className={clsx('inline-block size-1.5 shrink-0 rounded-full', color, !terminal && 'animate-pulse')}+ aria-hidden+ />+ )+}++/**+ * Renders the report's linked tasks inline (latest status + relationship) and links out to+ * cloud's existing task detail page. The run-log/session viewer lives there; this is the doorway.+ * Only `implementation` and `research` relationships are shown, implementation-first.+ */+export function ReportTasksSection({ report }: { report: SignalReport }): JSX.Element | null {+ const { reportTasks, reportTasksLoading } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))++ if (reportTasksLoading && !reportTasks) {+ return (+ <RightColumnSection icon={<IconTerminal />} title="Runs">+ <div className="flex items-center gap-2 text-xs text-tertiary py-1">+ <Spinner className="size-3" />+ Loading runs…+ </div>+ </RightColumnSection>+ )+ }++ if (!reportTasks || reportTasks.length === 0) {+ return null+ }++ return (+ <RightColumnSection icon={<IconTerminal />} title="Runs">+ <div className="flex flex-col gap-0.5">+ {reportTasks.map((entry: ReportTaskEntry) => (+ <TaskRow key={entry.task.id} entry={entry} />+ ))}+ </div>+ </RightColumnSection>+ )+}++function TaskRow({ entry }: { entry: ReportTaskEntry }): JSX.Element {+ const { task, relationship } = entry+ const status = task.latest_run?.status ?? TaskRunStatus.NOT_STARTED+ const runId = task.latest_run?.id+ // Deep-link straight to the task's run logs in cloud's Tasks UI (selecting the latest run),+ // rather than the in-inbox Runs route.+ const taskLogUrl = runId ? combineUrl(urls.taskDetail(task.id), { runId }).url : urls.taskDetail(task.id)+ return (+ <Link+ to={taskLogUrl}+ className="group flex items-center gap-2 rounded px-1.5 py-1 text-left text-xs no-underline transition-colors hover:bg-fill-highlight-50"+ >+ <TaskRunStatusDot status={status} />+ <span className="shrink-0 text-secondary">{RELATIONSHIP_LABEL[relationship]}</span>+ <span className="ml-auto truncate text-tertiary">{getTaskTitle(task)}</span>+ <IconChevronRight className="shrink-0 text-tertiary opacity-0 transition-opacity group-hover:opacity-100" />+ </Link>+ )+}++function getTaskTitle(task: Task): string {+ return task.title || 'Untitled'+}diff --git a/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsx b/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsxnew file mode 100644index 000000000000..fa0b41513bfd--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsx@@ -0,0 +1,297 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import { useMemo, useState } from 'react'++import { IconCheck, IconPeople, IconPlus, IconX } from '@posthog/icons'+import { LemonButton, LemonInput, Link, Spinner, Tooltip } from '@posthog/lemon-ui'++import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'++import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'+import { EnrichedReviewer, SignalReport } from '../../types'+import { RightColumnSection } from './DetailSection'+import {+ AvailableReviewerOption,+ getReviewerOptionDisplayName,+ reviewerMatchesOption,+ reviewersToWriteContent,+} from './reviewerDisplay'++/**+ * Suggested reviewers for the report, read from the `suggested_reviewers` artefact, with add/remove+ * editing. Mirrors desktop's `SuggestedReviewersSection`: a search popover to add org members (current+ * user pinned "Me"), per-row remove, and an optimistic update that converges on the reloaded artefact.+ */+export function SuggestedReviewersSection({ report }: { report: SignalReport }): JSX.Element | null {+ const logic = inboxReportDetailLogic({ reportId: report.id, report })+ const {+ reportReviewers,+ displayReviewers,+ addReviewerOptions,+ availableReviewersLoading,+ isUpdatingReviewers,+ reportArtefacts,+ } = useValues(logic)+ const { updateReviewers, searchAvailableReviewers } = useActions(logic)++ // The writable artefact id; without it there's nothing to PUT against, so the section can't render.+ const artefactId = useMemo(+ () => reportArtefacts?.find((a) => a.type === 'suggested_reviewers')?.id ?? null,+ [reportArtefacts]+ )++ const [addOpen, setAddOpen] = useState(false)+ const [query, setQuery] = useState('')++ const reviewers = displayReviewers+ const baseReviewers = reviewers ?? []+ // Assigned set keyed by user uuid (how `reviewerMatchesOption` matches), so the add-list+ // membership check is O(1) per option instead of scanning every reviewer per keystroke.+ const assignedUuids = useMemo(+ () => new Set(baseReviewers.map((r) => r.user?.uuid).filter(Boolean)),+ [baseReviewers]+ )+ const meUuid = addReviewerOptions[0]?.user_uuid++ // Render nothing only when there is no artefact at all (no reviewers ever computed). An empty list with+ // an artefact still renders so the user can add reviewers.+ if (!artefactId || reportReviewers === null) {+ return null+ }++ const fireAction = (+ action: 'add_suggested_reviewer' | 'remove_suggested_reviewer',+ login?: string | null+ ): void => {+ posthog.capture('Inbox report action', {+ report_id: report.id,+ report_title: report.title ?? null,+ priority: report.priority ?? null,+ actionability: report.actionability ?? null,+ action_type: action,+ surface: 'detail_pane',+ suggested_reviewer_login: login || undefined,+ })+ }++ const removeReviewer = (target: EnrichedReviewer): void => {+ const next = baseReviewers.filter((r) => r !== target)+ fireAction('remove_suggested_reviewer', target.github_login)+ updateReviewers(artefactId, reviewersToWriteContent(next), next)+ }++ const toggleOption = (option: AvailableReviewerOption): void => {+ const existing = baseReviewers.find((r) => reviewerMatchesOption(r, option))+ if (existing) {+ removeReviewer(existing)+ return+ }+ const optimisticEntry: EnrichedReviewer = {+ github_login: '',+ github_name: option.name || null,+ relevant_commits: [],+ user: {+ id: 0,+ uuid: option.user_uuid,+ email: option.email,+ first_name: option.name,+ last_name: '',+ },+ }+ const next = [...baseReviewers, optimisticEntry]+ fireAction('add_suggested_reviewer', option.user_uuid)+ updateReviewers(artefactId, [...reviewersToWriteContent(baseReviewers), { user_uuid: option.user_uuid }], next)+ }++ return (+ <RightColumnSection+ icon={<IconPeople />}+ title="Reviewers"+ rightSlot={+ <div className="flex items-center gap-2">+ {isUpdatingReviewers && <Spinner className="size-3" />}+ <LemonDropdown+ visible={addOpen}+ onClickOutside={() => {+ setAddOpen(false)+ setQuery('')+ }}+ closeOnClickInside={false}+ placement="bottom-end"+ overlay={+ <div className="flex flex-col gap-2 w-72 p-1">+ <LemonInput+ type="search"+ size="small"+ autoFocus+ placeholder="Search users…"+ value={query}+ onChange={(value) => {+ setQuery(value)+ searchAvailableReviewers(value)+ }}+ />+ <div className="max-h-72 overflow-y-auto flex flex-col">+ {availableReviewersLoading ? (+ <span className="flex items-center gap-2 px-1 py-2 text-xs text-tertiary">+ <Spinner className="size-3" />+ Searching…+ </span>+ ) : addReviewerOptions.length === 0 ? (+ <span className="px-1 py-2 text-xs text-tertiary">No users found.</span>+ ) : (+ addReviewerOptions.map((option) => {+ const assigned = assignedUuids.has(option.user_uuid)+ const isMe = meUuid === option.user_uuid+ return (+ <button+ key={option.user_uuid}+ type="button"+ disabled={isUpdatingReviewers}+ className="flex w-full items-start justify-between gap-2 rounded px-1.5 py-1 text-left transition-colors hover:bg-fill-highlight-50 disabled:opacity-60"+ onClick={() => toggleOption(option)}+ >+ <div className="flex items-center gap-2 min-w-0">+ <PersonDisplay+ person={{+ properties: {+ email: option.email,+ name: option.name,+ },+ }}+ displayName={getReviewerOptionDisplayName(option, isMe)}+ withIcon="xs"+ noLink+ noPopover+ />+ </div>+ <span className="flex size-4 shrink-0 items-center justify-center text-primary">+ {assigned && <IconCheck className="text-sm" />}+ </span>+ </button>+ )+ })+ )}+ </div>+ </div>+ }+ >+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconPlus />}+ onClick={() => setAddOpen((open) => !open)}+ >+ Add+ </LemonButton>+ </LemonDropdown>+ </div>+ }+ >+ {baseReviewers.length === 0 ? (+ <span className="text-xs text-tertiary">No reviewers assigned. Use "Add" to suggest one.</span>+ ) : (+ <div className="flex flex-col gap-1.5">+ {baseReviewers.map((reviewer: EnrichedReviewer) => (+ <ReviewerRow+ key={reviewer.user?.uuid ?? reviewer.github_login}+ reviewer={reviewer}+ disabled={isUpdatingReviewers}+ onRemove={() => removeReviewer(reviewer)}+ />+ ))}+ </div>+ )}+ </RightColumnSection>+ )+}++function ReviewerRow({+ reviewer,+ disabled,+ onRemove,+}: {+ reviewer: EnrichedReviewer+ disabled: boolean+ onRemove: () => void+}): JSX.Element {+ const displayName = reviewer.github_name ?? reviewer.user?.first_name ?? reviewer.github_login+ const reason = reviewer.relevant_commits[0]?.reason ?? null+ const githubUrl = reviewer.github_login ? `https://github.com/${reviewer.github_login}` : null++ const person = (+ <PersonDisplay+ person={{+ properties: {+ email: reviewer.user?.email,+ name: displayName,+ },+ }}+ displayName={displayName}+ withIcon="xs"+ noLink+ noPopover+ />+ )++ return (+ <div className="group flex items-start gap-2 rounded px-1.5 py-1.5 transition-colors hover:bg-fill-highlight-50">+ <Tooltip+ title={+ reviewer.user+ ? githubUrl+ ? `@${reviewer.github_login} on GitHub`+ : undefined+ : `${displayName} hasn't connected their GitHub account to PostHog. Ask them to do so in Settings!`+ }+ >+ <span className={!reviewer.user ? 'opacity-75' : undefined}>+ {/* The GitHub handle's link is merged into the name: clicking it opens the+ reviewer's GitHub profile, flagged by the external-link icon. */}+ {githubUrl ? (+ <Link+ to={githubUrl}+ target="_blank"+ className="inline-flex items-center gap-1 text-default hover:text-primary"+ >+ {person}+ </Link>+ ) : (+ person+ )}+ </span>+ </Tooltip>+ <div className="flex flex-col min-w-0 flex-1 gap-0.5">+ {reviewer.relevant_commits.length > 0 && (+ <span className="text-[0.6875rem] text-tertiary">+ {reviewer.relevant_commits.map((commit, i) => (+ <span key={commit.sha}>+ {i > 0 && ', '}+ <Tooltip title={commit.reason || undefined}>+ <Link+ to={commit.url}+ target="_blank"+ className="font-mono text-tertiary hover:text-primary"+ >+ {commit.sha.slice(0, 7)}+ </Link>+ </Tooltip>+ </span>+ ))}+ </span>+ )}+ {reason && <span className="text-[0.6875rem] text-tertiary leading-snug">{reason}</span>}+ </div>+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconX />}+ disabledReason={disabled ? 'Updating…' : undefined}+ onClick={onRemove}+ tooltip={`Remove ${reviewer.github_login || reviewer.user?.first_name || 'reviewer'}`}+ className="opacity-0 transition-opacity group-hover:opacity-100"+ />+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/reviewerDisplay.ts b/frontend/src/scenes/inbox/components/detail/reviewerDisplay.tsnew file mode 100644index 000000000000..9fc15822913d--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/reviewerDisplay.ts@@ -0,0 +1,97 @@+import { EnrichedReviewer } from '../../types'++/** A reviewer that can be added to a report, resolved from org members with a GitHub identity. */+export interface AvailableReviewerOption {+ user_uuid: string+ name: string+ email: string+}++/** Current user fields needed to pin / label the "Me" entry. Mirrors desktop `CurrentSuggestedReviewerUser`. */+export interface CurrentReviewerUser {+ uuid: string+ first_name?: string | null+ last_name?: string | null+ email?: string | null+}++function normalizeString(value: string | null | undefined): string {+ return typeof value === 'string' ? value.trim() : ''+}++function buildCurrentUserName(currentUser?: CurrentReviewerUser | null): string {+ const firstName = normalizeString(currentUser?.first_name)+ const lastName = normalizeString(currentUser?.last_name)+ return [firstName, lastName].filter(Boolean).join(' ')+}++/**+ * Build the add-reviewer option list: pin the current user ("Me") first, then the rest sorted by name.+ * Mirrors desktop `buildSuggestedReviewerFilterOptions`.+ */+export function buildAddReviewerOptions(+ available: AvailableReviewerOption[],+ currentUser?: CurrentReviewerUser | null+): AvailableReviewerOption[] {+ const byUuid = new Map<string, AvailableReviewerOption>()+ for (const reviewer of available) {+ const uuid = normalizeString(reviewer.user_uuid)+ if (!uuid || byUuid.has(uuid)) {+ continue+ }+ byUuid.set(uuid, {+ user_uuid: uuid,+ name: normalizeString(reviewer.name),+ email: normalizeString(reviewer.email),+ })+ }++ const currentUserUuid = normalizeString(currentUser?.uuid)+ let meOption: AvailableReviewerOption | null = null+ if (currentUserUuid) {+ const existing = byUuid.get(currentUserUuid)+ meOption = {+ user_uuid: currentUserUuid,+ name: buildCurrentUserName(currentUser) || existing?.name || '',+ email: normalizeString(currentUser?.email) || existing?.email || '',+ }+ byUuid.set(currentUserUuid, meOption)+ }++ const others = Array.from(byUuid.values())+ .filter((option) => option.user_uuid !== currentUserUuid)+ .sort(+ (a, b) =>+ a.name.toLowerCase().localeCompare(b.name.toLowerCase()) ||+ a.email.toLowerCase().localeCompare(b.email.toLowerCase()) ||+ a.user_uuid.localeCompare(b.user_uuid)+ )++ return meOption ? [meOption, ...others] : others+}++/** Display name for an add-reviewer option, with a "(Me)" suffix when it's the current user. */+export function getReviewerOptionDisplayName(option: AvailableReviewerOption, isMe: boolean): string {+ const base = normalizeString(option.name) || normalizeString(option.email) || 'Unknown user'+ return isMe ? `${base} (Me)` : base+}++/** Does an existing reviewer match an available option? Match by user uuid. */+export function reviewerMatchesOption(reviewer: EnrichedReviewer, option: AvailableReviewerOption): boolean {+ return !!reviewer.user?.uuid && reviewer.user.uuid === option.user_uuid+}++/** Convert reviewers to the write-content entries the backend expects (`{ user_uuid }` / `{ github_login }`). */+export function reviewersToWriteContent(reviewers: EnrichedReviewer[]): Record<string, string>[] {+ return reviewers+ .map((reviewer): Record<string, string> | null => {+ if (reviewer.user?.uuid) {+ return { user_uuid: reviewer.user.uuid }+ }+ if (reviewer.github_login) {+ return { github_login: reviewer.github_login }+ }+ return null+ })+ .filter((entry): entry is Record<string, string> => entry !== null)+}diff --git a/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsxnew file mode 100644index 000000000000..eaa9c5b71104--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx@@ -0,0 +1,374 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import {+ IconBolt,+ IconCheckCircle,+ IconChevronRight,+ IconCompass,+ IconGithub,+ IconPullRequest,+ IconServer,+} from '@posthog/icons'+import { LemonModal, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'+import { mcpStoreLogic } from '@posthog/products-mcp-store/frontend/mcpStoreLogic'+import { ServerIcon } from '@posthog/products-mcp-store/frontend/scene/icons'++import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { slackChannelDisplayName } from 'lib/integrations/slackChannel'+import { IconSlack } from 'lib/lemon-ui/icons'+import { cn } from 'lib/utils/css-classes'+import { urls } from 'scenes/urls'++import { scoutFleetLogic } from '../../logics/scoutFleetLogic'+import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'+import { userAutonomyLogic } from '../../logics/userAutonomyLogic'+import { signalSourcesLogic } from '../../signalSourcesLogic'+import { AutoStartThresholdSection } from '../config/AutoStartThresholdSection'+import { ScoutsFleetSection } from '../config/scouts/ScoutsFleetSection'+import { SignalSourcesPanel } from '../config/SignalSourcesPanel'+import { SlackNotificationsSection } from '../config/SlackNotificationsSection'+import { AgentSetupModalKey, agentSetupModalLogic } from './agentSetupModalLogic'++type WidgetTone = 'todo' | 'done' | 'neutral'+/** Visual weight reflecting how important / frequently edited a part of the setup is. */+type WidgetSize = 'lg' | 'md' | 'sm'++interface SetupWidgetCardProps {+ icon: JSX.Element+ title: string+ /** Short status line; falls back to a skeleton while `loading`. */+ status: React.ReactNode+ tone: WidgetTone+ size: WidgetSize+ loading?: boolean+ /** One-line context, shown on `lg` cards only. */+ description?: string+ /** Modal-backed widgets pass `onClick`; link-out widgets (Code access, MCP) pass `to`. */+ onClick?: () => void+ to?: string+ /** Extra content under the status (e.g. MCP brand icons). */+ children?: React.ReactNode+}++function TrailingAffordance({ tone, to }: { tone: WidgetTone; to?: string }): JSX.Element | null {+ if (tone === 'todo') {+ return (+ <LemonTag type="warning" size="small">+ Set up+ </LemonTag>+ )+ }+ if (tone === 'done') {+ return <IconCheckCircle className="size-4 shrink-0 text-success" />+ }+ if (to) {+ return <IconChevronRight className="size-4 shrink-0 text-muted transition-colors group-hover:text-default" />+ }+ return null+}++const ICON_BOX_CLASS: Record<WidgetSize, string> = {+ sm: 'size-5 [&_svg]:size-3',+ md: 'size-6 [&_svg]:size-3.5',+ lg: 'size-7 [&_svg]:size-4',+}+const TITLE_CLASS: Record<WidgetSize, string> = {+ sm: 'text-[13px] font-medium',+ md: 'text-[13px] font-medium',+ lg: 'text-[13px] font-semibold',+}+const CARD_PADDING_CLASS: Record<WidgetSize, string> = {+ sm: 'px-2.5 py-1.5',+ md: 'px-2.5 py-2',+ lg: 'px-2.5 py-2 gap-0.5',+}++function SetupWidgetCard(props: SetupWidgetCardProps): JSX.Element {+ const { icon, title, status, tone, size, loading, description, onClick, to, children } = props++ const cardClassName = cn(+ 'group flex rounded border border-primary bg-surface-primary text-left no-underline cursor-pointer transition-colors hover:border-secondary',+ size === 'sm' ? 'items-center justify-between gap-2' : 'flex-col',+ CARD_PADDING_CLASS[size]+ )++ // Compact single-row layout for the lowest-importance widgets.+ const content =+ size === 'sm' ? (+ <>+ <div className="flex items-center gap-2 min-w-0">+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center rounded bg-surface-secondary text-default',+ ICON_BOX_CLASS[size]+ )}+ >+ {icon}+ </span>+ <span className={cn('text-default truncate', TITLE_CLASS[size])}>{title}</span>+ </div>+ <div className="flex items-center gap-1.5 shrink-0">+ {loading ? (+ <LemonSkeleton className="h-3 w-16" />+ ) : (+ <span className="text-xs text-secondary">{status}</span>+ )}+ <TrailingAffordance tone={tone} to={to} />+ </div>+ </>+ ) : (+ <div className="flex items-start gap-2 min-w-0">+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center rounded bg-surface-secondary text-default',+ ICON_BOX_CLASS[size]+ )}+ >+ {icon}+ </span>+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">+ <div className="flex items-center justify-between gap-1.5">+ <span className={cn('text-default truncate', TITLE_CLASS[size])}>{title}</span>+ <TrailingAffordance tone={tone} to={to} />+ </div>+ {loading ? (+ <LemonSkeleton className="h-3 w-20" />+ ) : (+ <span className="text-xs text-secondary truncate">{status}</span>+ )}+ {size === 'lg' && description && (+ <p className="text-xs text-tertiary leading-snug mb-0">{description}</p>+ )}+ {children}+ </div>+ </div>+ )++ if (to) {+ return (+ <Link to={to} className={cardClassName}>+ {content}+ </Link>+ )+ }+ return (+ <button type="button" onClick={onClick} className={cardClassName}>+ {content}+ </button>+ )+}++function SignalSourcesWidget(): JSX.Element {+ const { sourceConfigs, enabledSourcesCount } = useValues(signalSourcesLogic)+ const { openSetupModal } = useActions(agentSetupModalLogic)+ const hasAny = enabledSourcesCount > 0+ return (+ <SetupWidgetCard+ icon={<IconBolt />}+ title="Signal sources"+ size="lg"+ tone={hasAny ? 'done' : 'todo'}+ loading={sourceConfigs === null}+ status={hasAny ? `${enabledSourcesCount} watching` : 'None active yet'}+ description="Each source watches a product and spins up work when something matters."+ onClick={() => openSetupModal('signal-sources')}+ />+ )+}++function ScoutTroopWidget(): JSX.Element {+ useMountedLogic(scoutFleetLogic)+ const { scoutConfigs, enabledCount } = useValues(scoutFleetLogic)+ const { openSetupModal } = useActions(agentSetupModalLogic)+ const hasAny = enabledCount > 0+ return (+ <SetupWidgetCard+ icon={<IconCompass />}+ title="Scout troop"+ size="lg"+ tone={hasAny ? 'done' : 'todo'}+ loading={scoutConfigs === null}+ status={hasAny ? `${enabledCount} on patrol` : 'No scouts running'}+ description="Scheduled agents that sweep this project on a cadence and report findings."+ onClick={() => openSetupModal('scout-troop')}+ />+ )+}++function CodeAccessWidget(): JSX.Element {+ const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)+ const hasGithub = getIntegrationsByKind(['github']).length > 0+ return (+ <SetupWidgetCard+ icon={<IconGithub />}+ title="Code access"+ size="md"+ tone={hasGithub ? 'done' : 'todo'}+ loading={integrationsLoading && !hasGithub}+ status={hasGithub ? 'GitHub connected' : 'Foundational – connect to start'}+ to={urls.settings('environment-integrations', 'integration-github')}+ />+ )+}++function McpServersWidget(): JSX.Element {+ useMountedLogic(mcpStoreLogic)+ const { installations, installationsLoading } = useValues(mcpStoreLogic)+ const count = installations.length+ return (+ <SetupWidgetCard+ icon={<IconServer />}+ title="MCP servers"+ size="md"+ tone={count > 0 ? 'done' : 'neutral'}+ loading={installationsLoading && count === 0}+ status={count > 0 ? `${count} connected` : 'Connect external tools'}+ to={urls.settings('mcp-servers')}+ >+ {count > 0 && (+ <div className="flex items-center gap-1 pt-1">+ {installations.slice(0, 6).map((installation) => (+ <ServerIcon key={installation.id} iconKey={installation.icon_key} size={16} />+ ))}+ {count > 6 && <span className="text-[11px] text-muted">+{count - 6}</span>}+ </div>+ )}+ </SetupWidgetCard>+ )+}++function NotificationsWidget(): JSX.Element {+ useMountedLogic(userAutonomyLogic)+ const { slackIntegrations, integrationsLoading } = useValues(integrationsLogic)+ const { autonomyConfig } = useValues(userAutonomyLogic)+ const { openSetupModal } = useActions(agentSetupModalLogic)++ const channel = autonomyConfig?.slack_notification_channel ?? null+ const notifying = (slackIntegrations?.length ?? 0) > 0 && !!channel+ return (+ <SetupWidgetCard+ icon={<IconSlack className="grayscale" />}+ title="Notifications"+ size="md"+ tone={notifying ? 'done' : 'todo'}+ loading={integrationsLoading && slackIntegrations === undefined}+ status={notifying && channel ? `Slack ${slackChannelDisplayName(channel)}` : 'Not connected'}+ onClick={() => openSetupModal('slack')}+ />+ )+}++function AutoStartWidget(): JSX.Element {+ useMountedLogic(signalTeamConfigLogic)+ const { autonomyConfig, autonomyConfigLoading } = useValues(userAutonomyLogic)+ const { openSetupModal } = useActions(agentSetupModalLogic)++ const userPriority = autonomyConfig?.autostart_priority ?? null+ return (+ <SetupWidgetCard+ icon={<IconPullRequest />}+ title="Auto-create PR"+ size="sm"+ tone="neutral"+ loading={autonomyConfigLoading && autonomyConfig === null}+ status={userPriority ? `${userPriority}+` : 'Off for you'}+ onClick={() => openSetupModal('auto-start')}+ />+ )+}++/** Section heading styled like a LemonTabs label (same 14px scale, tertiary color) so the+ * rail reads as a sibling of the tab bar rather than a louder header. */+function SetupSection({ title, children }: { title: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex flex-col">+ <h4 className="text-sm font-medium text-tertiary mt-0 mb-3.5">{title}</h4>+ <div className="flex flex-col gap-1.5">{children}</div>+ </div>+ )+}++const SETUP_MODALS: Record<+ AgentSetupModalKey,+ { title: string; description: string; width: number; body: JSX.Element }+> = {+ 'signal-sources': {+ title: 'Signal sources',+ description: 'Each source watches for signals and spins up work when something matters.',+ width: 760,+ body: <SignalSourcesPanel />,+ },+ 'scout-troop': {+ title: 'Scout troop',+ description: 'Scheduled agents that sweep this project on a cadence and emit findings to your inbox.',+ width: 760,+ body: <ScoutsFleetSection />,+ },+ slack: {+ title: 'Notifications',+ description: 'Get pinged in Slack when you’re a suggested reviewer on a new inbox item.',+ width: 560,+ body: <SlackNotificationsSection />,+ },+ 'auto-start': {+ title: 'Auto-create PR',+ description:+ 'Automatically open a pull request for an actionable report at or above a priority threshold – set the team default and your personal override.',+ width: 560,+ body: <AutoStartThresholdSection />,+ },+}++function SetupModal(): JSX.Element {+ const { openModal } = useValues(agentSetupModalLogic)+ const { closeSetupModal } = useActions(agentSetupModalLogic)+ const config = openModal ? SETUP_MODALS[openModal] : null+ return (+ <LemonModal+ isOpen={config !== null}+ onClose={closeSetupModal}+ title={config?.title ?? ''}+ description={config?.description}+ width={config?.width}+ >+ {config?.body}+ </LemonModal>+ )+}++/**+ * The agent-setup widgets, grouped into Agents / Connections / Preferences. Each widget shows+ * status and nudges the user to finish that part of the setup. Signal sources and Scout troop+ * (most edited) are largest; connections medium; Auto-create PR compact. Code access and MCP link+ * out to settings; the rest open a management modal.+ *+ * Rendered two ways: `rail` (a column to the right of the tabs on wide viewports) and+ * `stacked` (the Configuration tab body on narrow viewports).+ */+export function AgentSetupColumn({ layout }: { layout: 'rail' | 'stacked' }): JSX.Element {+ useMountedLogic(integrationsLogic)+ useMountedLogic(signalSourcesLogic)++ return (+ <div+ className={cn(+ 'flex flex-col gap-5',+ layout === 'stacked' ? 'mx-auto w-full max-w-2xl px-6 py-6' : 'px-4 py-3'+ )}+ >+ <SetupSection title="Agents">+ <SignalSourcesWidget />+ <ScoutTroopWidget />+ </SetupSection>+ <SetupSection title="Connections">+ <CodeAccessWidget />+ <NotificationsWidget />+ <McpServersWidget />+ </SetupSection>+ <SetupSection title="Preferences">+ <AutoStartWidget />+ </SetupSection>+ <SetupModal />+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/shell/DismissReportDialog.tsx b/frontend/src/scenes/inbox/components/shell/DismissReportDialog.tsxnew file mode 100644index 000000000000..ad93b3bd7a02--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/DismissReportDialog.tsx@@ -0,0 +1,99 @@+import { IconHide, IconPause } from '@posthog/icons'++import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import { DISMISSAL_REASON_OPTIONS, DismissalReasonValue, isDismissalReasonSnooze } from '../../utils/dismissalReasons'++export interface DismissReportDialogResult {+ reason: DismissalReasonValue+ note: string+}++interface OpenDismissReportDialogParams {+ /** Report title for single-report copy. Ignored when `selectedCount > 1`. */+ reportTitle?: string | null+ /** When greater than 1, copy reflects a bulk dismiss of the current selection. */+ selectedCount?: number+ /** Called with the chosen reason + note once the user confirms. */+ onConfirm: (result: DismissReportDialogResult) => void | Promise<void>+}++const PAUSE_OPTION_TOOLTIP =+ 'Snoozes this report: it briefly leaves your inbox while more context is gathered, and it can come back if new findings match.'+const SUPPRESS_OPTION_TOOLTIP =+ 'Dismisses permanently: the report leaves your inbox and matching findings will not surface it again. Your reason is saved with the report.'++// Vertical radio list mirroring desktop `DismissReportDialog`: each reason carries an icon ++// tooltip explaining whether it snoozes (pause) or dismisses permanently (eye-slash).+const REASON_RADIO_OPTIONS: LemonRadioOption<DismissalReasonValue>[] = DISMISSAL_REASON_OPTIONS.map((option) => {+ const snoozes = isDismissalReasonSnooze(option.value)+ return {+ value: option.value,+ label: (+ <Tooltip title={snoozes ? PAUSE_OPTION_TOOLTIP : SUPPRESS_OPTION_TOOLTIP} placement="right">+ <span className="inline-flex flex-wrap items-center gap-1.5">+ {option.label}+ {snoozes ? (+ <IconPause className="shrink-0 text-secondary" />+ ) : (+ <IconHide className="shrink-0 text-secondary" />+ )}+ </span>+ </Tooltip>+ ),+ }+})++/**+ * Opens the dismiss dialog. Mirrors desktop `DismissReportDialog`: pick a reason+ * (canonical {@link DISMISSAL_REASON_OPTIONS}) plus an optional note, then suppress.+ * The caller wires `onConfirm` to the bulk-dismiss action or a direct+ * `api.signalReports.setState(id, { state: 'suppressed', dismissal_reason, dismissal_note })`.+ */+export function openDismissReportDialog({+ reportTitle,+ selectedCount = 1,+ onConfirm,+}: OpenDismissReportDialogParams): void {+ const isBulk = selectedCount > 1+ const title = isBulk+ ? `Archive ${selectedCount} reports?`+ : `Archive report "${reportTitle?.trim() ? reportTitle : 'Untitled report'}"?`+ const description = isBulk+ ? 'These reports will be archived out of your inbox. Your feedback is saved on each report and helps the agent.'+ : 'This report will be archived out of your inbox. Your feedback is saved on the report and helps the agent.'++ LemonDialog.openForm({+ title,+ description,+ maxWidth: '30rem',+ initialValues: { reason: null as DismissalReasonValue | null, note: '' },+ content: (+ <div className="flex flex-col gap-3">+ <LemonField name="reason" label="Reason">+ {({ value, onChange }) => (+ <LemonRadio value={value} onChange={onChange} options={REASON_RADIO_OPTIONS} />+ )}+ </LemonField>+ <LemonField name="note" label="Note" info="Optional – helps the agent learn">+ <LemonTextArea placeholder="Optional: add detail" maxLength={4000} rows={3} />+ </LemonField>+ </div>+ ),+ errors: {+ reason: (reason) => (!reason ? "You haven't picked a reason" : undefined),+ },+ primaryButtonProps: { children: 'Archive & teach the agent' },+ shouldAwaitSubmit: true,+ onSubmit: async ({ reason, note }) => {+ if (!reason) {+ return+ }+ await onConfirm({ reason, note: (note ?? '').trim() })+ },+ })+}diff --git a/frontend/src/scenes/inbox/components/shell/InboxBulkSelectionBar.tsx b/frontend/src/scenes/inbox/components/shell/InboxBulkSelectionBar.tsxnew file mode 100644index 000000000000..ce715918bf73--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InboxBulkSelectionBar.tsx@@ -0,0 +1,57 @@+import { useActions, useValues } from 'kea'++import { IconArchive, IconX } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'+import { openDismissReportDialog } from './DismissReportDialog'++/**+ * Bulk action toolbar shown when one or more reports are multi-selected.+ * Mirrors desktop `InboxBulkSelectionBar` (the dismiss + clear slice). Selection+ * and the bulk-dismiss call live in `inboxBulkActionsLogic`; delete / reingest+ * remain on `inboxSceneLogic` per-report.+ */+export function InboxBulkSelectionBar(): JSX.Element | null {+ const { selectedCount, isDismissing } = useValues(inboxBulkActionsLogic)+ const { clearSelection, bulkDismiss } = useActions(inboxBulkActionsLogic)++ if (selectedCount === 0) {+ return null+ }++ return (+ <div className="flex items-center justify-between gap-3 flex-wrap rounded border border-accent bg-accent-highlight-secondary px-3 py-2">+ <div className="flex items-center gap-2 min-w-0">+ <span className="font-medium text-sm shrink-0">{selectedCount} selected</span>+ <span className="text-xs text-muted">Shift-click range · ⌘-click toggle · Esc to clear</span>+ </div>++ <div className="flex items-center gap-2 flex-wrap">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconArchive />}+ loading={isDismissing}+ disabledReason={isDismissing ? 'Archiving…' : undefined}+ onClick={() =>+ openDismissReportDialog({+ selectedCount,+ onConfirm: ({ reason, note }) => bulkDismiss(reason, note),+ })+ }+ >+ Archive+ </LemonButton>+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconX />}+ tooltip="Clear selection"+ aria-label="Clear selection"+ onClick={clearSelection}+ />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/shell/InboxScopeSelect.tsx b/frontend/src/scenes/inbox/components/shell/InboxScopeSelect.tsxnew file mode 100644index 000000000000..c5cde76c08be--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InboxScopeSelect.tsx@@ -0,0 +1,182 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { IconAsterisk, IconCheck, IconChevronDown } from '@posthog/icons'+import { LemonInput, LemonSegmentedButton, Spinner } from '@posthog/lemon-ui'++import { Popover } from 'lib/lemon-ui/Popover'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture/ProfilePicture'++import { isTeammateInboxScope, parseTeammateInboxScope, teammateInboxScope } from '../../inboxMembership'+import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import { INBOX_SCOPE_ENTIRE_PROJECT, INBOX_SCOPE_FOR_YOU, InboxScope } from '../../types'++/**+ * Two-segment scope toggle built on `LemonSegmentedButton`. Left segment is+ * "For you"; the right segment shows "Entire project" or the selected teammate's+ * name and opens a searchable people picker ("Entire project" + each teammate,+ * with avatars). One-to-one port of desktop `InboxScopeSelect` (segmented control+ * + combobox), in LemonUI. Scope is persisted via `inboxFiltersLogic`; teammates+ * come from its shared `availableReviewers` loader.+ */+export function InboxScopeSelect(): JSX.Element {+ const { scope, availableReviewers: reviewers, availableReviewersLoading } = useValues(inboxFiltersLogic)+ const { setScope, searchAvailableReviewers } = useActions(inboxFiltersLogic)+ const [open, setOpen] = useState(false)+ const [search, setSearch] = useState('')+ // External reference (callback ref → state so the Popover re-anchors once mounted).+ // Anchoring via `referenceElement` keeps the segment buttons OUT of the popover-reference+ // context, so LemonButton doesn't auto-add its own dropdown chevron to each segment.+ const [referenceEl, setReferenceEl] = useState<HTMLDivElement | null>(null)+ // Remember the selected teammate's label so the trigger stays correct even while a search+ // query has filtered them out of the server-returned `reviewers` list.+ const [knownTeammateLabel, setKnownTeammateLabel] = useState<string | null>(null)++ const isForYou = scope === INBOX_SCOPE_FOR_YOU+ const selectedTeammateUuid = isTeammateInboxScope(scope) ? parseTeammateInboxScope(scope) : null+ const selectedTeammate = reviewers.find((r) => r.user_uuid === selectedTeammateUuid)+ const selectedTeammateLabel = selectedTeammate ? selectedTeammate.name || selectedTeammate.email : null++ useEffect(() => {+ if (selectedTeammateUuid && selectedTeammateLabel) {+ setKnownTeammateLabel(selectedTeammateLabel)+ }+ }, [selectedTeammateUuid, selectedTeammateLabel])++ const rightLabel = selectedTeammateUuid+ ? (selectedTeammateLabel ?? knownTeammateLabel ?? 'Teammate')+ : 'Entire project'++ const pick = (next: InboxScope, label?: string): void => {+ if (label) {+ setKnownTeammateLabel(label)+ }+ setScope(next)+ setOpen(false)+ setSearch('')+ searchAvailableReviewers('')+ }++ return (+ <>+ <div ref={setReferenceEl} className="inline-flex">+ <LemonSegmentedButton+ size="small"+ value={isForYou ? 'for-you' : 'other'}+ onChange={(value) => {+ if (value === 'for-you') {+ // Left segment selects the For-you scope and closes the picker.+ setScope(INBOX_SCOPE_FOR_YOU)+ setOpen(false)+ } else {+ // Right segment opens the people picker; the scope only changes+ // once a row (Entire project / teammate) is picked.+ setOpen((v) => !v)+ }+ }}+ options={[+ { value: 'for-you', label: 'For you' },+ {+ value: 'other',+ label: (+ <span className="inline-flex items-center gap-1">+ <span className="max-w-[160px] truncate">{rightLabel}</span>+ <IconChevronDown className="text-tertiary" />+ </span>+ ),+ },+ ]}+ />+ </div>+ <Popover+ visible={open}+ onClickOutside={() => setOpen(false)}+ referenceElement={referenceEl}+ placement="bottom-end"+ overlay={+ <div className="w-[240px] p-1">+ <LemonInput+ type="search"+ size="small"+ placeholder="Search people…"+ value={search}+ onChange={(value) => {+ setSearch(value)+ searchAvailableReviewers(value)+ }}+ autoFocus+ className="mb-1"+ />+ <div className="max-h-[16rem] overflow-y-auto space-y-px">+ <ScopeRow+ active={scope === INBOX_SCOPE_ENTIRE_PROJECT}+ onClick={() => pick(INBOX_SCOPE_ENTIRE_PROJECT)}+ avatar={+ <span+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-dashed border-secondary text-tertiary"+ aria-hidden+ >+ <IconAsterisk className="text-xs" />+ </span>+ }+ label="Entire project"+ />+ {reviewers.map((reviewer) => (+ <ScopeRow+ key={reviewer.user_uuid}+ active={selectedTeammateUuid === reviewer.user_uuid}+ onClick={() =>+ pick(teammateInboxScope(reviewer.user_uuid), reviewer.name || reviewer.email)+ }+ avatar={+ <ProfilePicture+ user={{ first_name: reviewer.name, email: reviewer.email }}+ size="sm"+ />+ }+ label={reviewer.name || reviewer.email}+ />+ ))}+ {availableReviewersLoading ? (+ <div className="flex items-center gap-2 px-2 py-1.5 text-xs text-tertiary">+ <Spinner className="size-3" />+ Searching…+ </div>+ ) : reviewers.length === 0 ? (+ <div className="px-2 py-1.5 text-xs text-tertiary">No matching people.</div>+ ) : null}+ </div>+ </div>+ }+ />+ </>+ )+}++function ScopeRow({+ active,+ onClick,+ avatar,+ label,+}: {+ active: boolean+ onClick: () => void+ avatar: JSX.Element+ label: string+}): JSX.Element {+ return (+ <button+ type="button"+ onClick={onClick}+ className={clsx(+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm transition-colors',+ active ? 'bg-surface-secondary font-medium' : 'hover:bg-surface-secondary'+ )}+ >+ {avatar}+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {active && <IconCheck className="shrink-0 text-sm text-default" />}+ </button>+ )+}diff --git a/frontend/src/scenes/inbox/components/shell/InboxSearchFilterBar.tsx b/frontend/src/scenes/inbox/components/shell/InboxSearchFilterBar.tsxnew file mode 100644index 000000000000..3186dd3b3257--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InboxSearchFilterBar.tsx@@ -0,0 +1,191 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconCheck, IconChevronDown, IconFlag, IconRefresh, IconSearch, IconSort, IconTarget } from '@posthog/icons'+import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'++import {+ INBOX_PRIORITY_OPTIONS,+ INBOX_SORT_OPTIONS,+ INBOX_SOURCE_OPTIONS,+ inboxPriorityFilterLabel,+ inboxSortOptionKey,+ inboxSourceFilterLabel,+} from '../../filterOptions'+import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import { SignalReportPriority } from '../../types'++/** A single filter trigger + dropdown overlay, matching desktop's `InboxFilterPopover`. */+function FilterPopover({+ label,+ value,+ icon,+ active,+ children,+}: {+ label: string+ value: string+ icon: JSX.Element+ active: boolean+ children: React.ReactNode+}): JSX.Element {+ const [visible, setVisible] = useState(false)+ return (+ <LemonDropdown+ closeOnClickInside={false}+ visible={visible}+ onVisibilityChange={setVisible}+ matchWidth={false}+ actionable+ placement="bottom-start"+ overlay={<div className="min-w-[200px] max-w-[260px] p-1 deprecated-space-y-px">{children}</div>}+ >+ <button+ type="button"+ aria-label={`${label}: ${value}`}+ className="flex h-8 shrink-0 items-center gap-1.5 rounded border border-primary bg-surface-primary px-2.5 text-sm text-default transition-colors hover:border-secondary hover:bg-surface-secondary"+ >+ <span className="flex shrink-0 items-center text-tertiary [&>svg]:size-3.5">{icon}</span>+ <span className="max-w-[150px] truncate">{value}</span>+ {active && <span className="size-1.5 shrink-0 rounded-full bg-accent" />}+ <IconChevronDown className="shrink-0 text-sm text-tertiary" />+ </button>+ </LemonDropdown>+ )+}++/** A single multi-select row inside a filter popover: icon/glyph + label, with a check when active. */+function FilterItem({+ icon,+ label,+ active,+ onClick,+}: {+ icon?: JSX.Element+ label: React.ReactNode+ active: boolean+ onClick: () => void+}): JSX.Element {+ return (+ <button+ type="button"+ onClick={onClick}+ className="flex w-full items-center justify-between gap-2 rounded px-1.5 py-1 text-left text-sm text-default transition-colors hover:bg-surface-secondary"+ >+ <span className="flex min-w-0 items-center gap-1.5">+ {icon && <span className="flex shrink-0 items-center text-tertiary [&>svg]:size-3.5">{icon}</span>}+ <span className="truncate">{label}</span>+ </span>+ {active && <IconCheck className="shrink-0 text-sm text-default" />}+ </button>+ )+}++interface InboxSearchFilterBarProps {+ searchPlaceholder?: string+ /** Triggers a reload of the report list (lives on `inboxSceneLogic`). */+ onRefresh?: () => void+ refreshing?: boolean+}++/**+ * Search input + Source / Sort / Priority filter popovers + refresh. One-to-one+ * port of desktop `InboxSearchFilterBar`. There is no status filter (desktop+ * dropped it; status is a fixed request constant). Filter state is persisted via+ * `inboxFiltersLogic`; the central scene reloads on change.+ */+export function InboxSearchFilterBar({+ searchPlaceholder = 'Search by title or description…',+ onRefresh,+ refreshing,+}: InboxSearchFilterBarProps): JSX.Element {+ const { searchQuery, sortField, sortDirection, sourceProductFilter, priorityFilter } = useValues(inboxFiltersLogic)+ const { setSearchQuery, setSort, toggleSourceProduct, togglePriority } = useActions(inboxFiltersLogic)++ const activeSort = INBOX_SORT_OPTIONS.find((o) => o.field === sortField && o.direction === sortDirection)+ const activeSortKey = inboxSortOptionKey(sortField, sortDirection)++ return (+ <div className="flex items-center gap-2 flex-wrap w-full">+ <LemonInput+ className="flex-1 min-w-[220px]"+ type="search"+ value={searchQuery}+ onChange={setSearchQuery}+ placeholder={searchPlaceholder}+ prefix={<IconSearch />}+ size="small"+ />++ <FilterPopover+ label="Source"+ value={inboxSourceFilterLabel(sourceProductFilter)}+ icon={<IconTarget />}+ active={sourceProductFilter.length > 0}+ >+ {INBOX_SOURCE_OPTIONS.map((option) => (+ <FilterItem+ key={option.value}+ icon={option.icon}+ label={option.label}+ active={sourceProductFilter.includes(option.value)}+ onClick={() => toggleSourceProduct(option.value)}+ />+ ))}+ </FilterPopover>++ <FilterPopover+ label="Sort"+ value={activeSort?.label ?? 'Priority first'}+ icon={<IconSort />}+ active={activeSortKey !== 'priority:asc'}+ >+ {INBOX_SORT_OPTIONS.map((option) => (+ <FilterItem+ key={inboxSortOptionKey(option.field, option.direction)}+ icon={option.icon}+ label={option.label}+ active={sortField === option.field && sortDirection === option.direction}+ onClick={() => setSort(option.field, option.direction)}+ />+ ))}+ </FilterPopover>++ <FilterPopover+ label="Priority"+ value={inboxPriorityFilterLabel(priorityFilter)}+ icon={<IconFlag />}+ active={priorityFilter.length > 0}+ >+ {INBOX_PRIORITY_OPTIONS.map((option) => (+ <FilterItem+ key={option.value}+ icon={+ <span+ className="inline-block size-2 shrink-0 rounded-full"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ backgroundColor: option.accent }}+ />+ }+ label={option.value}+ active={priorityFilter.includes(option.value)}+ onClick={() => togglePriority(option.value as SignalReportPriority)}+ />+ ))}+ </FilterPopover>++ {onRefresh && (+ <LemonButton+ type="secondary"+ size="xsmall"+ icon={<IconRefresh />}+ loading={refreshing}+ tooltip="Refresh"+ aria-label="Refresh"+ onClick={onRefresh}+ className="bg-surface-primary ml-auto"+ />+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/shell/InboxTabBar.tsx b/frontend/src/scenes/inbox/components/shell/InboxTabBar.tsxnew file mode 100644index 000000000000..8c5aa5de30d4--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InboxTabBar.tsx@@ -0,0 +1,77 @@+import { useMountedLogic, useValues } from 'kea'+import { router } from 'kea-router'++import { LemonTabs, LemonTag } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { inboxSceneLogic } from '../../inboxSceneLogic'+import { INBOX_FLAT_TAB_LIST_PARAMS, reportListLogic } from '../../logics/reportListLogic'+import {+ INBOX_FLAT_LIST_TAB_KEYS,+ INBOX_STAFF_ONLY_TAB_KEYS,+ INBOX_TAB_KEYS,+ INBOX_TAB_LABEL,+ InboxFlatListTabKey,+ InboxTabKey,+} from '../../types'++function isFlatListTabKey(tab: InboxTabKey): tab is InboxFlatListTabKey {+ return (INBOX_FLAT_LIST_TAB_KEYS as readonly string[]).includes(tab)+}++function isStaffOnlyTabKey(tab: InboxTabKey): boolean {+ return (INBOX_STAFF_ONLY_TAB_KEYS as string[]).includes(tab)+}++/**+ * Count chip for a flat report tab. Mounts that tab's `reportListLogic` so its `count`+ * (a cheap `limit=1` request) is available for the badge before the tab is ever opened.+ * The active tab shares the same keyed instance, so no double-fetch.+ */+function FlatTabCount({ tabKey }: { tabKey: InboxFlatListTabKey }): JSX.Element {+ const logic = reportListLogic({ tabKey, listParams: INBOX_FLAT_TAB_LIST_PARAMS[tabKey] })+ useMountedLogic(logic)+ const { count } = useValues(logic)+ return <span className="text-xs text-muted tabular-nums">{count ?? 0}</span>+}++/**+ * Tab bar: Pull requests / Reports (everyone) + Not actionable / Runs (staff-only, with a+ * "Staff" tag). Each report tab shows its own server-computed count. The Configuration tab+ * is only shown when `showConfigTab` is set – i.e. when the scene is too narrow for the+ * setup rail; on wide viewports the rail replaces it.+ */+export function InboxTabBar({ showConfigTab }: { showConfigTab?: boolean }): JSX.Element {+ const { activeTab, isStaff, runsCount } = useValues(inboxSceneLogic)++ const visibleTabKeys = INBOX_TAB_KEYS.filter(+ (key) => (key !== 'config' || showConfigTab) && (!isStaffOnlyTabKey(key) || isStaff)+ )++ return (+ <LemonTabs+ activeKey={activeTab}+ // Hide LemonTabs' own bottom border + margin so the single full-width border lives on the+ // scene header row; the active-tab slider then sits directly on that one border.+ barClassName="before:hidden mb-0"+ onChange={(key) => router.actions.push(urls.inbox(key))}+ tabs={visibleTabKeys.map((key) => ({+ key,+ label: (+ <span className="flex items-center gap-1.5">+ <span>{INBOX_TAB_LABEL[key]}</span>+ {isFlatListTabKey(key) && <FlatTabCount tabKey={key} />}+ {key === 'runs' && <span className="text-xs text-muted tabular-nums">{runsCount}</span>}+ {isStaffOnlyTabKey(key) && (+ <LemonTag type="completion" size="small">+ Staff+ </LemonTag>+ )}+ </span>+ ),+ content: <></>,+ }))}+ />+ )+}diff --git a/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.ts b/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.tsnew file mode 100644index 000000000000..6787835afb0f--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.ts@@ -0,0 +1,26 @@+import { actions, kea, path, reducers } from 'kea'++import type { agentSetupModalLogicType } from './agentSetupModalLogicType'++/** Setup widgets whose management UI opens in a modal. GitHub and MCP servers link out instead. */+export type AgentSetupModalKey = 'signal-sources' | 'scout-troop' | 'slack' | 'auto-start'++/** Tracks which agent-setup widget's modal is open (one at a time), driven from the widget strip. */+export const agentSetupModalLogic = kea<agentSetupModalLogicType>([+ path(['scenes', 'inbox', 'components', 'shell', 'agentSetupModalLogic']),++ actions({+ openSetupModal: (key: AgentSetupModalKey) => ({ key }),+ closeSetupModal: true,+ }),++ reducers({+ openModal: [+ null as AgentSetupModalKey | null,+ {+ openSetupModal: (_, { key }) => key,+ closeSetupModal: () => null,+ },+ ],+ }),+])diff --git a/frontend/src/scenes/inbox/components/signalCards/ConversationsTicketSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/ConversationsTicketSignalCard.tsxnew file mode 100644index 000000000000..bd44f9c0e524--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/ConversationsTicketSignalCard.tsx@@ -0,0 +1,129 @@+import { IconChevronRight, IconComment, IconGithub, IconLetter } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { IconMicrosoftTeams, IconSlack } from 'lib/lemon-ui/icons'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonTag, type LemonTagType } from 'lib/lemon-ui/LemonTag'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { urls } from 'scenes/urls'++import type { ConversationsTicketSignalExtra } from '~/queries/schema/schema-signals'++import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/** Guard for Conversations ticket extras. Keys on the ticket number + channel source unique to this source. */+export function isConversationsTicketExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & ConversationsTicketSignalExtra {+ return 'ticket_number' in extra && 'channel_source' in extra+}++/** Sentence-case a lower-case token, treating underscores as spaces (e.g. `on_hold` → "On hold"). */+function humanizeToken(value: string): string {+ const spaced = value.replace(/_/g, ' ')+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)+}++/** Map a Conversations ticket status to a tag colour. */+export function conversationsStatusTagType(s: string): LemonTagType {+ switch (s) {+ case 'resolved':+ return 'success'+ case 'new':+ return 'primary'+ case 'open':+ case 'pending':+ case 'on_hold':+ default:+ return 'default'+ }+}++/** Human label for a Conversations ticket status (Sentence-cased, underscores humanized). */+export function conversationsStatusLabel(s: string): string {+ return humanizeToken(s)+}++/** Map a Conversations ticket priority to a tag colour. */+export function conversationsPriorityTagType(p: string): LemonTagType {+ switch (p) {+ case 'high':+ return 'danger'+ case 'medium':+ return 'warning'+ case 'low':+ default:+ return 'default'+ }+}++/** Map a channel source to its brand icon, or null when unrecognized. */+export function conversationsChannelIcon(source: string): JSX.Element | null {+ switch (source) {+ case 'widget':+ return <IconComment />+ case 'email':+ return <IconLetter />+ case 'github':+ return <IconGithub />+ case 'slack':+ return <IconSlack />+ case 'teams':+ return <IconMicrosoftTeams />+ default:+ return null+ }+}++export function ConversationsTicketSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as Record<string, unknown> & ConversationsTicketSignalExtra+ const channelIcon = conversationsChannelIcon(extra.channel_source)++ return (+ <SignalCardShell signal={signal} label={extra.email_subject ?? undefined}>+ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}+ <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary">+ <span className="font-mono font-medium">#{extra.ticket_number}</span>+ <LemonTag size="small" type={conversationsStatusTagType(extra.status)}>+ {conversationsStatusLabel(extra.status)}+ </LemonTag>+ {extra.priority && (+ <LemonTag size="small" type={conversationsPriorityTagType(extra.priority)}>+ {humanizeToken(extra.priority)}+ </LemonTag>+ )}+ <LemonTag size="small" type="muted">+ <span className="flex items-center gap-1">+ {channelIcon}+ <span>+ {extra.channel_source}+ {extra.channel_detail && ` · ${humanizeToken(extra.channel_detail)}`}+ </span>+ </span>+ </LemonTag>+ <span>{humanFriendlyDetailedTime(extra.created_at)}</span>+ </div>+ <div className="flex items-center mt-2">+ <span className="flex-1" />+ <Link+ to={urls.supportTicketDetail(extra.ticket_number)}+ className="flex items-center gap-1 text-xs font-medium"+ >+ Open ticket+ <IconChevronRight />+ </Link>+ </div>+ </SignalCardShell>+ )+}++export const conversationsTicketSignalCardEntry: SignalCardEntry = {+ key: 'conversations',+ matches: (signal) => signal.source_product === 'conversations' && isConversationsTicketExtra(signal.extra),+ Component: ConversationsTicketSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/EndpointExecutionFailedSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/EndpointExecutionFailedSignalCard.tsxnew file mode 100644index 000000000000..73eee3b3c433--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/EndpointExecutionFailedSignalCard.tsx@@ -0,0 +1,89 @@+import { combineUrl } from 'kea-router'++import { IconWarning } from '@posthog/icons'+import { LemonTag, Link } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import type { SignalNode } from 'scenes/debug/signals/types'+import { urls } from 'scenes/urls'++import type { EndpointExecutionFailedSignalExtra } from '~/queries/schema/schema-signals'++import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/** Narrows a signal's `extra` to the endpoint execution failure shape. */+export function isEndpointExecutionFailedExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & EndpointExecutionFailedSignalExtra {+ return typeof extra.endpoint_name === 'string' && typeof extra.error_class === 'string'+}++/** Inbox signal card for a failed endpoint execution: endpoint identity, error class, and the error message. */+export function EndpointExecutionFailedSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra: EndpointExecutionFailedSignalExtra | null = isEndpointExecutionFailedExtra(signal.extra)+ ? signal.extra+ : null++ if (!extra) {+ return <SignalCardShell signal={signal}>{null}</SignalCardShell>+ }++ const { endpoint_name, endpoint_version, materialized, error_class, error_message } = extra+ const endpointUrl = urls.endpoint(endpoint_name, endpoint_version ?? undefined)+ const logsUrl = combineUrl(endpointUrl, { tab: 'logs' }).url++ return (+ <SignalCardShell signal={signal}>+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium">{endpoint_name}</span>+ {endpoint_version != null && <LemonTag size="small">v{endpoint_version}</LemonTag>}+ {materialized && <LemonTag size="small">Materialized</LemonTag>}+ </div>++ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mt-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ <div className="mt-2">+ <LemonTag type="danger" size="small" icon={<IconWarning />}>+ {error_class}+ </LemonTag>+ </div>++ {error_message && (+ <div className="mt-2">+ <CodeSnippet+ language={Language.Text}+ wrap+ compact+ maxLinesWithoutExpansion={6}+ thing="error message"+ >+ {error_message}+ </CodeSnippet>+ </div>+ )}++ <div className="flex items-center gap-3 text-xs mt-2">+ <span className="flex-1" />+ <Link to={endpointUrl} className="font-medium">+ View endpoint+ </Link>+ <Link to={logsUrl} className="font-medium">+ View execution logs+ </Link>+ </div>+ </SignalCardShell>+ )+}++export const endpointExecutionFailedSignalCardEntry: SignalCardEntry = {+ key: 'endpoints',+ matches: (signal: SignalNode) =>+ signal.source_product === 'endpoints' && isEndpointExecutionFailedExtra(signal.extra),+ Component: EndpointExecutionFailedSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/ErrorTrackingSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/ErrorTrackingSignalCard.tsxnew file mode 100644index 000000000000..d292b809c27e--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/ErrorTrackingSignalCard.tsx@@ -0,0 +1,136 @@+import { BindLogic, useValues } from 'kea'++import { IconExternal, IconTrending } from '@posthog/icons'+import { LemonSkeleton, LemonTag, LemonTagType, Link } from '@posthog/lemon-ui'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import type { SignalNode } from 'scenes/debug/signals/types'+import { urls } from 'scenes/urls'++import type { ErrorTrackingSignalExtra } from '~/queries/schema/schema-signals'++import { ErrorTrackingIssueListRow } from 'products/error_tracking/frontend/components/ErrorTrackingIssueList/ErrorTrackingIssueList'++import {+ inboxErrorTrackingIssueLogic,+ InboxErrorTrackingIssueLogicProps,+ InboxErrorTrackingIssueSourceType,+} from './inboxErrorTrackingIssueLogic'+import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/** Narrows a signal's `extra` to the error tracking shape (a string `fingerprint`). */+export function isErrorTrackingExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & ErrorTrackingSignalExtra {+ return typeof extra.fingerprint === 'string'+}++interface SourceTypeBadge {+ label: string+ type: LemonTagType+ icon?: JSX.Element+}++const SOURCE_TYPE_BADGES: Record<InboxErrorTrackingIssueSourceType, SourceTypeBadge> = {+ issue_created: { label: 'New issue', type: 'primary' },+ issue_reopened: { label: 'Reopened', type: 'warning' },+ issue_spiking: { label: 'Spiking', type: 'danger', icon: <IconTrending /> },+}++function asSourceType(sourceType: string): InboxErrorTrackingIssueSourceType {+ return sourceType === 'issue_reopened' || sourceType === 'issue_spiking' ? sourceType : 'issue_created'+}++/** Footer link out to the full error tracking issue scene. */+function ViewIssueLink({ issueId, fingerprint }: { issueId: string; fingerprint: string }): JSX.Element {+ return (+ <Link+ to={urls.errorTrackingIssue(issueId, { fingerprint })}+ target="_blank"+ className="flex items-center gap-1 text-xs font-medium shrink-0"+ >+ View issue <IconExternal className="size-3" />+ </Link>+ )+}++/** Inner body: reads the loaded issue from the bound logic and renders the live row, skeleton, or fallback. */+function ErrorTrackingSignalCardBody({+ signal,+ fingerprint,+}: {+ signal: SignalNode+ fingerprint: string+}): JSX.Element {+ const { mergedIssue, issueLoading, summaryLoading, mergedFailed, mergedToIssueId } =+ useValues(inboxErrorTrackingIssueLogic)++ const linkIssueId = mergedToIssueId ?? signal.source_id++ if (mergedFailed) {+ // Issue not found or merged away – degrade to a thin fallback with just the fingerprint and a link.+ return (+ <div className="flex items-center gap-2 text-xs text-tertiary">+ <span className="font-mono truncate">{fingerprint}</span>+ <span className="flex-1" />+ <ViewIssueLink issueId={linkIssueId} fingerprint={fingerprint} />+ </div>+ )+ }++ if (!mergedIssue || (issueLoading && summaryLoading)) {+ return <LemonSkeleton className="h-16 w-full" />+ }++ return (+ <div className="rounded border bg-surface-primary">+ <ErrorTrackingIssueListRow issue={mergedIssue} canMutateIssues={false} />+ </div>+ )+}++/** Inbox signal card for error tracking issues: embeds the live issue row read-only. */+export function ErrorTrackingSignalCard({ signal }: SignalCardProps): JSX.Element {+ const fingerprint = isErrorTrackingExtra(signal.extra) ? signal.extra.fingerprint : ''+ const sourceType = asSourceType(signal.source_type)+ const badge = SOURCE_TYPE_BADGES[sourceType]++ const logicProps: InboxErrorTrackingIssueLogicProps = {+ issueId: signal.source_id,+ fingerprint,+ sourceType,+ }++ return (+ <SignalCardShell+ signal={signal}+ rightSlot={+ <LemonTag type={badge.type} size="small" icon={badge.icon}>+ {badge.label}+ </LemonTag>+ }+ >+ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ <BindLogic logic={inboxErrorTrackingIssueLogic} props={logicProps}>+ <ErrorTrackingSignalCardBody signal={signal} fingerprint={fingerprint} />+ </BindLogic>++ <div className="flex items-center gap-2 text-xs text-tertiary mt-2">+ <span className="flex-1" />+ <ViewIssueLink issueId={signal.source_id} fingerprint={fingerprint} />+ </div>+ </SignalCardShell>+ )+}++export const errorTrackingSignalCardEntry: SignalCardEntry = {+ key: 'error_tracking',+ matches: (signal) => signal.source_product === 'error_tracking' && isErrorTrackingExtra(signal.extra),+ Component: ErrorTrackingSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/ExternalSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/ExternalSignalCard.tsxnew file mode 100644index 000000000000..af9edcd7c44e--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/ExternalSignalCard.tsx@@ -0,0 +1,103 @@+import clsx from 'clsx'++import { IconExternal } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import type { SignalNode } from 'scenes/debug/signals/types'++import { SignalCardShell } from './SignalCardShell'++export type StatePillTone = 'success' | 'danger' | 'warning' | 'muted' | 'default'++const STATE_PILL_TONE_CLASSES: Record<StatePillTone, string> = {+ success: 'bg-success-highlight text-success',+ danger: 'bg-danger-highlight text-danger',+ warning: 'bg-warning-highlight text-warning',+ muted: 'bg-fill-highlight-50 text-muted',+ default: 'bg-fill-highlight-50 text-secondary',+}++export interface StatePill {+ label: string+ tone: StatePillTone+}++/** Small pill with a leading status dot, e.g. an issue's open/closed state. */+export function StatePillBadge({ pill }: { pill: StatePill }): JSX.Element {+ return (+ <span+ className={clsx(+ 'inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs font-medium',+ STATE_PILL_TONE_CLASSES[pill.tone]+ )}+ >+ <span className="size-1.5 rounded-full bg-current" />+ {pill.label}+ </span>+ )+}++/**+ * Presentational shell for external-source signal cards (GitHub, Linear, Zendesk, pganalyze).+ * Captures the common anatomy — brand-icon header, optional state pill + title, markdown body,+ * a chip meta row, and a footer with timestamps on the left and a prominent external link on the+ * right. Product-specific colourings (label chips, priority indicators) are passed in via `metaChips`.+ */+export function ExternalSignalCard({+ signal,+ title,+ statePill,+ children,+ metaChips,+ footerLeft,+ link,+}: {+ signal: SignalNode+ /** Optional title shown in the header (e.g. issue number or identifier). */+ title?: React.ReactNode+ /** Optional state pill rendered in the header right slot. */+ statePill?: StatePill+ /** Body content — typically the signal description. If a string, rendered as markdown. */+ children?: React.ReactNode+ /** Chip row (labels, tags, priority, status). Caller-rendered for product-specific colours. */+ metaChips?: React.ReactNode+ /** Footer left content, typically timestamps. */+ footerLeft?: React.ReactNode+ /** Primary external link-out. Always opens in a new tab. */+ link?: { to: string; label: string }+}): JSX.Element {+ return (+ <SignalCardShell+ signal={signal}+ label={title}+ rightSlot={statePill ? <StatePillBadge pill={statePill} /> : undefined}+ >+ {typeof children === 'string' ? (+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {children}+ </LemonMarkdown>+ ) : (+ children+ )}++ {metaChips && <div className="flex items-center gap-1.5 flex-wrap">{metaChips}</div>}++ {(footerLeft || link) && (+ <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary mt-2">+ {footerLeft}+ <span className="flex-1" />+ {link && (+ <Link+ to={link.to}+ target="_blank"+ className="flex items-center gap-1 text-xs font-medium shrink-0"+ >+ {link.label} <IconExternal className="size-3" />+ </Link>+ )}+ </div>+ )}+ </SignalCardShell>+ )+}diff --git a/frontend/src/scenes/inbox/components/signalCards/GenericSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/GenericSignalCard.tsxnew file mode 100644index 000000000000..817e5bbe70f7--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/GenericSignalCard.tsx@@ -0,0 +1,50 @@+import clsx from 'clsx'+import { useState } from 'react'++import { IconChevronRight } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++import { SignalCardShell } from './SignalCardShell'+import type { SignalCardProps } from './types'++/** Fallback card for signals without a dedicated renderer. Shows content, timestamp, and raw metadata. */+export function GenericSignalCard({ signal }: SignalCardProps): JSX.Element {+ const [showRaw, setShowRaw] = useState(false)++ return (+ <SignalCardShell signal={signal}>+ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ <div className="text-xs text-tertiary">+ <TZLabel time={signal.timestamp} />+ </div>++ {Object.keys(signal.extra).length > 0 && (+ <div className="mt-2">+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => setShowRaw(!showRaw)}+ icon={+ <IconChevronRight className={clsx('size-3 transition-transform', showRaw && 'rotate-90')} />+ }+ >+ Raw metadata+ </LemonButton>+ {showRaw && (+ <pre className="text-xs mt-1 p-2 bg-surface-secondary rounded overflow-x-auto max-h-60">+ {JSON.stringify(signal.extra, null, 2)}+ </pre>+ )}+ </div>+ )}+ </SignalCardShell>+ )+}diff --git a/frontend/src/scenes/inbox/components/signalCards/GithubIssueSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/GithubIssueSignalCard.tsxnew file mode 100644index 000000000000..08c5f4de8cff--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/GithubIssueSignalCard.tsx@@ -0,0 +1,79 @@+import { IconLock } from '@posthog/icons'++import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'++import type { GithubIssueSignalExtra } from '~/queries/schema/schema-signals'++import { ExternalSignalCard, type StatePill } from './ExternalSignalCard'+import type { SignalCardEntry, SignalCardProps } from './types'++/** Narrows a signal's `extra` to a GitHub issue payload. */+export function isGithubIssueExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & GithubIssueSignalExtra {+ return 'html_url' in extra && 'number' in extra+}++function titleCase(value: string): string {+ return value.length > 0 ? value[0].toUpperCase() + value.slice(1).toLowerCase() : value+}++function statePillFromState(state: string): StatePill {+ switch (state.toLowerCase()) {+ case 'open':+ return { label: 'Open', tone: 'success' }+ case 'closed':+ // Owner preference: closed reads as muted/gray rather than alarming.+ return { label: 'Closed', tone: 'muted' }+ default:+ return { label: titleCase(state), tone: 'default' }+ }+}++export function GithubIssueSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as Record<string, unknown> & GithubIssueSignalExtra++ const labels = Array.isArray(extra.labels) ? extra.labels : []++ const metaChips = (+ <>+ {labels.map((label) => (+ <LemonTag key={label} size="small" className="rounded-full">+ {label}+ </LemonTag>+ ))}+ {extra.locked && (+ <LemonTag size="small" type="muted" icon={<IconLock />}>+ Locked+ </LemonTag>+ )}+ </>+ )++ const footerLeft = (+ <span>+ Opened {humanFriendlyDetailedTime(extra.created_at)}+ {extra.updated_at !== extra.created_at && ` · Updated ${humanFriendlyDetailedTime(extra.updated_at)}`}+ </span>+ )++ return (+ <ExternalSignalCard+ signal={signal}+ title={<span className="font-medium">#{extra.number}</span>}+ statePill={statePillFromState(extra.state)}+ metaChips={metaChips}+ footerLeft={footerLeft}+ link={{ to: extra.html_url, label: 'View on GitHub' }}+ >+ {signal.content}+ </ExternalSignalCard>+ )+}++export const githubIssueSignalCardEntry: SignalCardEntry = {+ key: 'github',+ matches: (signal) => signal.source_product === 'github' && isGithubIssueExtra(signal.extra),+ Component: GithubIssueSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/HealthCheckSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/HealthCheckSignalCard.tsxnew file mode 100644index 000000000000..a8c7fde7e360--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/HealthCheckSignalCard.tsx@@ -0,0 +1,209 @@+import { Fragment } from 'react'++import { LemonTag, Link } from '@posthog/lemon-ui'+import type { LemonTagType } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++import type { HealthCheckSeverity, HealthCheckSignalExtra } from '~/queries/schema/schema-signals'++import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/**+ * Health-check signals are PostHog-native instrumentation issues. They always carry a `kind`,+ * a `severity`, and an `issue_id`, which together distinguish them from other native sources.+ */+export function isHealthCheckExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & HealthCheckSignalExtra {+ return 'kind' in extra && 'severity' in extra && 'issue_id' in extra+}++/** Severity → LemonTag tone for the header right slot. */+const SEVERITY_TAG_TYPE: Record<HealthCheckSeverity, LemonTagType> = {+ critical: 'danger',+ warning: 'warning',+ info: 'muted',+}++/** Human labels for known health-check kinds. Unknown kinds fall back to a humanized form. */+const KIND_LABELS: Record<string, string> = {+ authorized_urls: 'Authorized URLs not set',+ no_live_events: 'No live events',+ no_pageleave_events: 'Missing pageleave events',+ partial_proxy: 'Partial reverse-proxy coverage',+ reverse_proxy: 'Reverse proxy recommended',+ scroll_depth: 'Missing scroll-depth data',+ web_vitals: 'Missing web vitals',+ sdk_outdated: 'Outdated SDK',+ materialized_view_failure: 'Materialized view failing',+ ingestion_warning: 'Ingestion warning',+}++function capitalize(value: string): string {+ return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value+}++function kindLabel(kind: string): string {+ return KIND_LABELS[kind] ?? capitalize(kind.replace(/_/g, ' '))+}++/** Turn a snake_case payload key into a readable label, e.g. `current_version` → `Current version`. */+function humanizeKey(key: string): string {+ return capitalize(key.replace(/_/g, ' '))+}++function isPrimitive(value: unknown): value is string | number | boolean {+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'+}++/** Format a single primitive value for display (booleans become Yes/No). */+function formatPrimitive(value: string | number | boolean): string {+ if (typeof value === 'boolean') {+ return value ? 'Yes' : 'No'+ }+ return String(value)+}++/**+ * Format a payload value into a display string, or return null to omit it.+ * Nested objects and arrays of objects are omitted to avoid rendering "[object Object]".+ */+function formatPayloadValue(value: unknown): string | null {+ if (isPrimitive(value)) {+ return formatPrimitive(value)+ }+ if (Array.isArray(value)) {+ const primitives = value.filter(isPrimitive)+ if (primitives.length !== value.length || primitives.length === 0) {+ return null+ }+ const formatted = primitives.map(formatPrimitive)+ if (formatted.length > 5) {+ return `${formatted.slice(0, 5).join(', ')} +${formatted.length - 5} more`+ }+ return formatted.join(', ')+ }+ return null+}++/** Generic readable key-value list over an `extra.payload`. Skips `reason` (shown as the summary). */+function PayloadKeyValueList({ payload }: { payload: Record<string, unknown> }): JSX.Element | null {+ const rows = Object.entries(payload)+ .filter(([key]) => key !== 'reason')+ .map(([key, value]) => [key, formatPayloadValue(value)] as const)+ .filter((row): row is readonly [string, string] => row[1] !== null)++ if (rows.length === 0) {+ return null+ }++ return (+ <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs">+ {rows.map(([key, value]) => (+ <Fragment key={key}>+ <span className="text-tertiary">{humanizeKey(key)}</span>+ <span className="text-secondary">{value}</span>+ </Fragment>+ ))}+ </div>+ )+}++/** `sdk_outdated`: render the version upgrade as a single `current → latest` line. */+function SdkOutdatedPayload({ payload }: { payload: Record<string, unknown> }): JSX.Element | null {+ const current = payload.current_version+ const latest = payload.latest_version+ if (!isPrimitive(current) || !isPrimitive(latest)) {+ return <PayloadKeyValueList payload={payload} />+ }+ return (+ <div className="text-xs text-secondary">+ <span className="font-mono">{formatPrimitive(current)}</span>+ <span className="text-tertiary"> → </span>+ <span className="font-mono">{formatPrimitive(latest)}</span>+ </div>+ )+}++/** `partial_proxy`: render unproxied hosts as monospace host chips. */+function PartialProxyPayload({ payload }: { payload: Record<string, unknown> }): JSX.Element | null {+ const hosts = Array.isArray(payload.unproxied_hosts) ? payload.unproxied_hosts.filter(isPrimitive) : []+ if (hosts.length === 0) {+ return <PayloadKeyValueList payload={payload} />+ }+ return (+ <div className="flex flex-wrap gap-1">+ {hosts.map((host) => (+ <code key={String(host)} className="text-xs px-1 py-0.5 rounded bg-surface-secondary font-mono">+ {formatPrimitive(host)}+ </code>+ ))}+ </div>+ )+}++/** Pick the kind-specific payload renderer, defaulting to the generic key-value list. */+function PayloadRenderer({ kind, payload }: { kind: string; payload: Record<string, unknown> }): JSX.Element | null {+ if (kind === 'sdk_outdated') {+ return <SdkOutdatedPayload payload={payload} />+ }+ if (kind === 'partial_proxy') {+ return <PartialProxyPayload payload={payload} />+ }+ return <PayloadKeyValueList payload={payload} />+}++export function HealthCheckSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as Record<string, unknown> & HealthCheckSignalExtra++ const severityTag = (+ <LemonTag size="small" type={SEVERITY_TAG_TYPE[extra.severity]}>+ {capitalize(extra.severity)}+ </LemonTag>+ )++ const body = signal.content || ''+ const summary = extra.summary || ''+ // Avoid printing the summary twice when content already equals it.+ const showSummaryFallback = !body && !!summary+ const markdownText = body || (showSummaryFallback ? summary : '')++ return (+ <SignalCardShell signal={signal} label={extra.title} rightSlot={severityTag}>+ <div className="flex flex-col gap-2">+ <div>+ <LemonTag size="small" type="muted">+ {kindLabel(extra.kind)}+ </LemonTag>+ </div>++ {markdownText && (+ <LemonMarkdown className="text-sm text-secondary" disableImages>+ {markdownText}+ </LemonMarkdown>+ )}++ <PayloadRenderer kind={extra.kind} payload={extra.payload} />++ <div className="flex items-center gap-2 pt-1">+ <span className="flex-1" />+ <Link to={extra.link} className="text-xs font-medium">+ Open in PostHog+ </Link>+ <span className="text-xs text-tertiary">+ <TZLabel time={signal.timestamp} />+ </span>+ </div>+ </div>+ </SignalCardShell>+ )+}++export const healthCheckSignalCardEntry: SignalCardEntry = {+ key: 'health_checks',+ matches: (signal) => signal.source_product === 'health_checks' && isHealthCheckExtra(signal.extra),+ Component: HealthCheckSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/LinearIssueSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/LinearIssueSignalCard.tsxnew file mode 100644index 000000000000..f94892b24dff--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/LinearIssueSignalCard.tsx@@ -0,0 +1,104 @@+import clsx from 'clsx'++import { LemonTag } from '@posthog/lemon-ui'++import { humanFriendlyDetailedTime } from 'lib/utils/datetime'++import type { LinearIssueSignalExtra } from '~/queries/schema/schema-signals'++import { ExternalSignalCard, type StatePill } from './ExternalSignalCard'+import type { SignalCardEntry, SignalCardProps } from './types'++/**+ * Linear has `url` + `priority` + `number`, but unlike GitHub it carries no `html_url`.+ * Requiring `identifier` and `priority_label` keeps this narrow enough not to match other issue sources.+ */+export function isLinearIssueExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & LinearIssueSignalExtra {+ return 'identifier' in extra && 'priority_label' in extra && typeof extra.url === 'string'+}++/** Linear workflow state types → state pill tone. */+function statePillForState(extra: LinearIssueSignalExtra): StatePill | undefined {+ if (!extra.state_name) {+ return undefined+ }+ const tone: StatePill['tone'] =+ extra.state_type === 'started'+ ? 'warning'+ : extra.state_type === 'completed'+ ? 'success'+ : extra.state_type === 'canceled' || extra.state_type === 'backlog'+ ? 'muted'+ : 'default'+ return { label: extra.state_name, tone }+}++/** Tailwind text colour for a Linear priority dot. `0` (No priority) stays muted. */+const PRIORITY_DOT_CLASS: Record<number, string> = {+ 1: 'text-danger',+ 2: 'text-warning',+ 3: 'text-primary',+ 4: 'text-muted',+}++function PriorityIndicator({ extra }: { extra: LinearIssueSignalExtra }): JSX.Element {+ const dotClass = PRIORITY_DOT_CLASS[extra.priority] ?? 'text-muted'+ const label = extra.priority === 0 ? extra.priority_label || 'No priority' : extra.priority_label+ return (+ <span className={clsx('inline-flex items-center gap-1 text-xs', extra.priority === 0 && 'text-muted')}>+ <span className={clsx('size-1.5 rounded-full bg-current', dotClass)} />+ {label}+ </span>+ )+}++export function LinearIssueSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as Record<string, unknown> & LinearIssueSignalExtra++ const title = extra.identifier || `#${extra.number}`+ const labels = Array.isArray(extra.labels) ? extra.labels : []++ const metaChips = (+ <>+ <PriorityIndicator extra={extra} />+ {extra.team_name && (+ <LemonTag size="small" type="muted">+ {extra.team_name}+ </LemonTag>+ )}+ {labels.map((label) => (+ <LemonTag key={label} size="small">+ {label}+ </LemonTag>+ ))}+ </>+ )++ const footerLeft = (+ <span>+ Opened {humanFriendlyDetailedTime(extra.created_at)}+ {extra.updated_at !== extra.created_at && <> · Updated {humanFriendlyDetailedTime(extra.updated_at)}</>}+ </span>+ )++ return (+ <ExternalSignalCard+ signal={signal}+ title={<span className="font-mono">{title}</span>}+ statePill={statePillForState(extra)}+ metaChips={metaChips}+ footerLeft={footerLeft}+ link={{ to: extra.url, label: 'View in Linear' }}+ >+ {signal.content}+ </ExternalSignalCard>+ )+}++export const linearIssueSignalCardEntry: SignalCardEntry = {+ key: 'linear',+ matches: (signal) => signal.source_product === 'linear' && isLinearIssueExtra(signal.extra),+ Component: LinearIssueSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/LlmAnalyticsSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/LlmAnalyticsSignalCard.tsxnew file mode 100644index 000000000000..1fe2d882f389--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/LlmAnalyticsSignalCard.tsx@@ -0,0 +1,219 @@+import { BindLogic, useValues } from 'kea'++import { IconExternal } from '@posthog/icons'+import { LemonSkeleton, Link } from '@posthog/lemon-ui'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import type { SignalNode } from 'scenes/debug/signals/types'+import { urls } from 'scenes/urls'++import type { LlmEvalReportSignalExtra, LlmEvalSignalExtra } from '~/queries/schema/schema-signals'++import { LLMProviderIcon } from 'products/ai_observability/frontend/LLMProviderIcon'+import { normalizeLLMProvider } from 'products/ai_observability/frontend/settings/llmProviderKeysLogic'+import { formatLLMCost, formatLLMLatency, formatTokens } from 'products/ai_observability/frontend/utils'++import { inboxLlmTraceLogic } from './inboxLlmTraceLogic'+import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++// ── Type guards ──────────────────────────────────────────────────────────────────++export function isLlmEvalTraceExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & LlmEvalSignalExtra {+ return 'evaluation_id' in extra && 'trace_id' in extra+}++export function isLlmEvalReportExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & LlmEvalReportSignalExtra {+ return 'evaluation_id' in extra && 'report_run_id' in extra+}++// ── Shared link-out ────────────────────────────────────────────────────────────────++function ExternalSignalLink({ to, label }: { to: string; label: string }): JSX.Element {+ return (+ <Link to={to} target="_blank" className="flex items-center gap-1 text-xs font-medium shrink-0">+ {label} <IconExternal className="size-3" />+ </Link>+ )+}++// Plain "model · provider" fallback line shown while the trace loads or when it failed to load.+function ModelProviderLine({ model, provider }: { model?: string; provider?: string }): JSX.Element | null {+ const parts = [model, provider].filter(Boolean)+ if (parts.length === 0) {+ return null+ }+ return <div className="text-xs text-tertiary">{parts.join(' · ')}</div>+}++// ── Trace card (source_type: evaluation) ──────────────────────────────────────────++/** Metric strip rendered once the trace loads. Each metric is guarded — missing fields are skipped. */+function TraceMetricStrip({ extra }: { extra: LlmEvalSignalExtra }): JSX.Element | null {+ const { trace, traceLoading } = useValues(inboxLlmTraceLogic)++ if (traceLoading) {+ return <LemonSkeleton className="h-4 w-48" />+ }++ if (!trace) {+ return <ModelProviderLine model={extra.model} provider={extra.provider} />+ }++ const provider = normalizeLLMProvider(extra.provider)+ const metrics: React.ReactNode[] = []++ if (typeof trace.totalLatency === 'number') {+ metrics.push(<span key="latency">{formatLLMLatency(trace.totalLatency)}</span>)+ }+ if (typeof trace.totalCost === 'number') {+ metrics.push(<span key="cost">{formatLLMCost(trace.totalCost)}</span>)+ }+ if (typeof trace.inputTokens === 'number' || typeof trace.outputTokens === 'number') {+ metrics.push(+ <span key="tokens">+ {formatTokens(trace.inputTokens ?? 0)} → {formatTokens(trace.outputTokens ?? 0)}+ </span>+ )+ }++ if (metrics.length === 0 && !extra.model && !provider) {+ return <></>+ }++ return (+ <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary">+ {provider && (+ <span className="inline-flex items-center shrink-0">+ <LLMProviderIcon provider={provider} className="size-3.5" />+ </span>+ )}+ {extra.model && <span className="font-medium text-secondary">{extra.model}</span>}+ {metrics.length > 0 && (+ <span className="flex items-center gap-2">+ {metrics.map((metric, index) => (+ <span key={index} className="flex items-center gap-2">+ {index > 0 && <span className="text-border">·</span>}+ {metric}+ </span>+ ))}+ </span>+ )}+ </div>+ )+}++// 2-line preview derived from the trace's input/output state (or null while loading / on failure).+function TracePreview(): JSX.Element | null {+ const { trace } = useValues(inboxLlmTraceLogic)++ if (!trace) {+ return null+ }++ const previewText = [stringifyState(trace.inputState), stringifyState(trace.outputState)]+ .filter(Boolean)+ .join('\n')+ .trim()++ if (!previewText) {+ return null+ }++ return <div className="text-xs text-tertiary line-clamp-2 mt-1 whitespace-pre-wrap break-words">{previewText}</div>+}++// Reduce an arbitrary input/output state payload to a short displayable string.+function stringifyState(state: unknown): string {+ if (state == null) {+ return ''+ }+ if (typeof state === 'string') {+ return state+ }+ try {+ return JSON.stringify(state)+ } catch {+ return ''+ }+}++function LlmEvalTraceSignalCardBody({ signal, extra }: { signal: SignalNode; extra: LlmEvalSignalExtra }): JSX.Element {+ return (+ <SignalCardShell signal={signal}>+ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ <TraceMetricStrip extra={extra} />+ <TracePreview />++ <div className="flex items-center gap-3 mt-2">+ <ExternalSignalLink+ to={urls.aiObservabilityTrace(extra.trace_id, { event: extra.target_event_id })}+ label="View trace"+ />+ <ExternalSignalLink to={urls.aiObservabilityEvaluation(extra.evaluation_id)} label="View evaluation" />+ </div>+ </SignalCardShell>+ )+}++export function LlmEvalTraceSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as unknown as LlmEvalSignalExtra+ return (+ <BindLogic logic={inboxLlmTraceLogic} props={{ traceId: extra.trace_id }}>+ <LlmEvalTraceSignalCardBody signal={signal} extra={extra} />+ </BindLogic>+ )+}++// ── Report card (source_type: evaluation_report) ──────────────────────────────────++export function LlmEvalReportSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as unknown as LlmEvalReportSignalExtra++ return (+ <SignalCardShell signal={signal}>+ <div className="text-sm font-semibold text-primary">{extra.evaluation_name}</div>+ {extra.evaluation_description && (+ <div className="text-xs text-secondary line-clamp-2 mt-0.5">{extra.evaluation_description}</div>+ )}++ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mt-2 mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ <div className="text-xs text-tertiary mt-1">+ Run · {humanFriendlyDetailedTime(extra.period_start)} – {humanFriendlyDetailedTime(extra.period_end)}+ </div>++ <div className="mt-2">+ <ExternalSignalLink to={urls.aiObservabilityEvaluation(extra.evaluation_id)} label="View evaluation" />+ </div>+ </SignalCardShell>+ )+}++// ── Registry entries ──────────────────────────────────────────────────────────────++export const llmEvalTraceSignalCardEntry: SignalCardEntry = {+ key: 'llm_analytics:evaluation',+ matches: (signal) => signal.source_product === 'llm_analytics' && isLlmEvalTraceExtra(signal.extra),+ Component: LlmEvalTraceSignalCard,+}++export const llmEvalReportSignalCardEntry: SignalCardEntry = {+ key: 'llm_analytics:evaluation_report',+ matches: (signal) => signal.source_product === 'llm_analytics' && isLlmEvalReportExtra(signal.extra),+ Component: LlmEvalReportSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/LogsAlertSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/LogsAlertSignalCard.tsxnew file mode 100644index 000000000000..31e2d2b5816b--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/LogsAlertSignalCard.tsx@@ -0,0 +1,166 @@+import { IconWarning } from '@posthog/icons'+import { LemonTag, Link } from '@posthog/lemon-ui'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { urls } from 'scenes/urls'++import type { LogsAlertStateChangeSignalExtra } from '~/queries/schema/schema-signals'++import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/** Narrows a signal's `extra` to the logs alert state-change shape. */+export function isLogsAlertStateChangeExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & LogsAlertStateChangeSignalExtra {+ return (+ typeof extra.alert_id === 'string' &&+ (extra.action === 'firing' || extra.action === 'broken') &&+ 'threshold_count' in extra+ )+}++/** Reads a string array off the loosely-typed filters bag, returning [] when absent or malformed. */+function readStringArray(filters: Record<string, unknown>, key: string): string[] {+ const value = filters[key]+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []+}++/** Compact rendering of the alert's log filters: services, severities, and a count of remaining conditions. */+function FiltersBlock({ filters }: { filters: Record<string, unknown> }): JSX.Element {+ const serviceNames = readStringArray(filters, 'serviceNames')+ const severityLevels = readStringArray(filters, 'severityLevels')+ const filterGroup = filters.filterGroup++ // Best-effort count of extra UniversalFilters conditions without fully expanding them.+ let filterGroupCount = 0+ if (filterGroup && typeof filterGroup === 'object') {+ const values = (filterGroup as { values?: unknown }).values+ if (Array.isArray(values)) {+ filterGroupCount = values.length+ }+ }++ const hasAny = serviceNames.length > 0 || severityLevels.length > 0 || filterGroupCount > 0+ if (!hasAny) {+ return <span className="text-xs text-tertiary">All logs</span>+ }++ return (+ <div className="flex flex-col gap-1">+ {serviceNames.length > 0 && (+ <div className="flex items-center gap-1 flex-wrap">+ <span className="text-xs text-tertiary">Services</span>+ {serviceNames.map((name) => (+ <LemonTag key={name} size="small">+ {name}+ </LemonTag>+ ))}+ </div>+ )}+ {severityLevels.length > 0 && (+ <div className="flex items-center gap-1 flex-wrap">+ <span className="text-xs text-tertiary">Severities</span>+ {severityLevels.map((level) => (+ <LemonTag key={level} size="small">+ {level}+ </LemonTag>+ ))}+ </div>+ )}+ {filterGroupCount > 0 && (+ <LemonTag size="small" type="muted">+ + {filterGroupCount} filter {filterGroupCount === 1 ? 'condition' : 'conditions'}+ </LemonTag>+ )}+ </div>+ )+}++/** Firing body: threshold sentence plus a compact observed / threshold pair. */+function FiringBody({ extra }: { extra: LogsAlertStateChangeSignalExtra }): JSX.Element {+ const observed = extra.result_count === null ? 'No result' : extra.result_count++ return (+ <div className="flex flex-col gap-2">+ <p className="text-sm m-0">+ Result count {observed} is {extra.threshold_operator} threshold {extra.threshold_count} over the last{' '}+ {extra.window_minutes} minutes+ </p>+ <div className="flex items-baseline gap-2">+ <span className="text-lg font-semibold">+ <span className="text-danger">{extra.result_count === null ? '–' : extra.result_count}</span>+ {' / '}+ {extra.threshold_count}+ </span>+ <span className="text-xs text-tertiary">observed / threshold</span>+ </div>+ </div>+ )+}++/** Broken body: auto-disable sentence plus a muted line describing what was being checked. */+function BrokenBody({ extra }: { extra: LogsAlertStateChangeSignalExtra }): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <p className="text-sm m-0">+ Alert auto-disabled after{' '}+ <span className="text-warning font-semibold">{extra.consecutive_failures}</span> consecutive failed+ checks+ </p>+ <p className="text-xs text-tertiary m-0">+ Was checking result count {extra.threshold_operator} {extra.threshold_count} over {extra.window_minutes}+ m+ </p>+ </div>+ )+}++/** Inbox signal card for logs alert state changes (firing / broken). */+export function LogsAlertSignalCard({ signal }: SignalCardProps): JSX.Element {+ if (!isLogsAlertStateChangeExtra(signal.extra)) {+ return <SignalCardShell signal={signal}>{null}</SignalCardShell>+ }+ const extra = signal.extra+ const alertUrl = urls.logsAlertDetail(extra.alert_id)++ const stateBadge =+ extra.action === 'firing' ? (+ <LemonTag type="danger" size="small">+ Firing+ </LemonTag>+ ) : (+ <LemonTag type="warning" size="small" icon={<IconWarning />}>+ Broken+ </LemonTag>+ )++ return (+ <SignalCardShell signal={signal} label={extra.alert_name} rightSlot={stateBadge}>+ <div className="flex flex-col gap-3">+ {extra.action === 'firing' ? <FiringBody extra={extra} /> : <BrokenBody extra={extra} />}++ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ <FiltersBlock filters={extra.filters} />++ <div className="flex items-center gap-2 text-xs">+ <span className="flex-1" />+ <Link to={alertUrl} className="font-medium shrink-0">+ View alert+ </Link>+ </div>+ </div>+ </SignalCardShell>+ )+}++export const logsAlertSignalCardEntry: SignalCardEntry = {+ key: 'logs',+ matches: (signal) => signal.source_product === 'logs' && isLogsAlertStateChangeExtra(signal.extra),+ Component: LogsAlertSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/PgAnalyzeSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/PgAnalyzeSignalCard.tsxnew file mode 100644index 000000000000..8d7a811dcad1--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/PgAnalyzeSignalCard.tsx@@ -0,0 +1,129 @@+import { IconExternal } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonTag, type LemonTagType } from 'lib/lemon-ui/LemonTag'+import { safeHttpUrl } from 'scenes/inbox/utils/reportPresentation'++import type { PgAnalyzeIssueReference, PgAnalyzeIssueSignalExtra } from '~/queries/schema/schema-signals'++import { ExternalSignalCard } from './ExternalSignalCard'+import type { SignalCardEntry, SignalCardProps } from './types'++/** Narrows a signal's `extra` to a pganalyze issue payload. */+export function isPgAnalyzeExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & PgAnalyzeIssueSignalExtra {+ return 'references' in extra && Array.isArray(extra.references) && 'synced_at' in extra+}++/** Maps a pganalyze severity to a LemonTag tone. Case-insensitive; unknown values fall back to `default`. */+function severityTone(severity: string): LemonTagType {+ switch (severity.toLowerCase()) {+ case 'critical':+ return 'danger'+ case 'high':+ return 'caution'+ case 'medium':+ return 'warning'+ case 'low':+ return 'muted'+ case 'info':+ return 'completion'+ default:+ return 'default'+ }+}++/** Sentence-cases a label (first letter upper, rest lower). */+function sentenceCase(value: string): string {+ return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()+}++function ReferenceRow({ reference }: { reference: PgAnalyzeIssueReference }): JSX.Element | null {+ if (reference.name === null && reference.url === null && reference.queryText === null) {+ return null+ }++ if (reference.name !== null) {+ const href = reference.url !== null ? safeHttpUrl(reference.url) : null+ return (+ <div className="flex items-center gap-1.5 text-xs flex-wrap">+ {reference.kind !== null && <span className="text-tertiary">{reference.kind}</span>}+ {href !== null ? (+ <Link to={href} target="_blank" className="flex items-center gap-1 font-mono">+ {reference.name} <IconExternal className="size-3" />+ </Link>+ ) : (+ <span className="font-mono">{reference.name}</span>+ )}+ </div>+ )+ }++ if (reference.queryText !== null) {+ return (+ <CodeSnippet language={Language.SQL} wrap compact maxLinesWithoutExpansion={6}>+ {reference.queryText}+ </CodeSnippet>+ )+ }++ return null+}++export function PgAnalyzeSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as Record<string, unknown> & PgAnalyzeIssueSignalExtra++ const serverLabel = extra.server_name ?? extra.server_human_id+ const metaChips = (+ <>+ {extra.severity !== null && (+ <LemonTag type={severityTone(extra.severity)}>{sentenceCase(extra.severity)}</LemonTag>+ )}+ {serverLabel && <LemonTag type="muted">{serverLabel}</LemonTag>}+ </>+ )++ const visibleReferences = extra.references.filter(+ (reference) => reference.name !== null || reference.url !== null || reference.queryText !== null+ )++ const externalUrl = extra.references+ .map((reference) => (reference.url !== null ? safeHttpUrl(reference.url) : null))+ .find((url): url is string => url !== null)++ return (+ <ExternalSignalCard+ signal={signal}+ metaChips={metaChips}+ footerLeft={+ <span className="flex items-center gap-1">+ Synced <TZLabel time={extra.synced_at} />+ </span>+ }+ link={externalUrl ? { to: externalUrl, label: 'View in pganalyze' } : undefined}+ >+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>++ {visibleReferences.length > 0 && (+ <div className="border-t pt-2 mt-2 flex flex-col gap-2">+ <div className="text-xs font-medium text-tertiary">References</div>+ {visibleReferences.map((reference, index) => (+ <ReferenceRow key={index} reference={reference} />+ ))}+ </div>+ )}+ </ExternalSignalCard>+ )+}++export const pgAnalyzeSignalCardEntry: SignalCardEntry = {+ key: 'pganalyze',+ matches: (signal) => signal.source_product === 'pganalyze' && isPgAnalyzeExtra(signal.extra),+ Component: PgAnalyzeSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/SessionReplaySignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/SessionReplaySignalCard.tsxnew file mode 100644index 000000000000..4a3029f76c78--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/SessionReplaySignalCard.tsx@@ -0,0 +1,223 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { IconBug, IconCursorClick, IconExternal, IconGlobe, IconKeyboard, IconPlay } from '@posthog/icons'+import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'+import type { LemonTagType } from '@posthog/lemon-ui'++import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { dayjs } from 'lib/dayjs'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { getExportsContentRetrieveUrl } from '~/generated/core/api'+import type { SessionProblemEventEntry, SessionProblemSignalExtra } from '~/queries/schema/schema-signals'++import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/** How many timeline events to show before collapsing the rest behind a toggle. */+const TIMELINE_PREVIEW_COUNT = 4++const PROBLEM_TYPE_TAG: Record<SessionProblemSignalExtra['problem_type'], { label: string; type: LemonTagType }> = {+ blocking_exception: { label: 'Blocking exception', type: 'danger' },+ failure: { label: 'Failure', type: 'danger' },+ non_blocking_exception: { label: 'Exception', type: 'warning' },+ abandonment: { label: 'Abandonment', type: 'warning' },+ confusion: { label: 'Confusion', type: 'caution' },+}++/** Narrows a raw `extra` payload to the live session-problem shape. */+export function isSessionProblemExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & SessionProblemSignalExtra {+ return typeof extra.session_id === 'string' && 'problem_type' in extra+}++/** Picks a glyph for a timeline event based on its interaction type. */+function EventGlyph({ entry }: { entry: SessionProblemEventEntry }): JSX.Element {+ const className = 'size-3.5 shrink-0 text-tertiary'+ switch (entry.event_type) {+ case 'click':+ return <IconCursorClick className={className} aria-hidden />+ case 'keypress':+ case 'input':+ return <IconKeyboard className={className} aria-hidden />+ case 'exception':+ return <IconBug className={className} aria-hidden />+ case 'pageview':+ case '$pageview':+ return <IconGlobe className={className} aria-hidden />+ default:+ return <IconGlobe className={className} aria-hidden />+ }+}++/** A single row in the problem-event timeline; its time opens the recording at that moment. */+function TimelineRow({ entry, sessionId }: { entry: SessionProblemEventEntry; sessionId: string }): JSX.Element {+ const primaryText = entry.interaction_text?.trim() || entry.event+ return (+ <li className="flex items-start gap-2 py-0.5">+ <EventGlyph entry={entry} />+ <div className="flex-1 min-w-0">+ <div className="text-xs text-primary truncate">{primaryText}</div>+ {entry.current_url && (+ <div className="text-xs text-tertiary font-mono truncate">{entry.current_url}</div>+ )}+ </div>+ <ViewRecordingButton+ sessionId={sessionId}+ timestamp={entry.timestamp}+ openPlayerIn={RecordingPlayerType.Modal}+ size="xsmall"+ type="tertiary"+ label={humanFriendlyDetailedTime(entry.timestamp)}+ />+ </li>+ )+}++/** Live card for a session-replay problem segment: thumbnail preview, replay link-out, and an event timeline. */+export function SessionReplaySignalCard({ signal }: SignalCardProps): JSX.Element {+ const { currentTeamId } = useValues(teamLogic)+ const [showAllEvents, setShowAllEvents] = useState(false)+ const [thumbnailFailed, setThumbnailFailed] = useState(false)++ const extra = signal.extra as Record<string, unknown> & SessionProblemSignalExtra+ const problemTag = PROBLEM_TYPE_TAG[extra.problem_type]++ const hasThumbnail = extra.exported_asset_id !== undefined && currentTeamId !== null && !thumbnailFailed+ const thumbnailSrc = hasThumbnail+ ? getExportsContentRetrieveUrl(String(currentTeamId), extra.exported_asset_id as number)+ : undefined++ const replayUrl = urls.replaySingle(extra.session_id, {+ unixTimestampMillis: dayjs(extra.start_time).valueOf(),+ })++ const events = extra.event_history ?? []+ const visibleEvents = showAllEvents ? events : events.slice(0, TIMELINE_PREVIEW_COUNT)++ const activeDuration =+ extra.session_active_seconds !== undefined ? humanFriendlyDuration(extra.session_active_seconds) : undefined+ const totalDuration =+ extra.session_duration !== undefined ? humanFriendlyDuration(extra.session_duration) : undefined++ return (+ <SignalCardShell+ signal={signal}+ label={extra.segment_title}+ rightSlot={+ problemTag ? (+ <LemonTag type={problemTag.type} size="small" className="shrink-0">+ {problemTag.label}+ </LemonTag>+ ) : undefined+ }+ >+ {signal.content && (+ <LemonMarkdown className="text-sm text-secondary mb-2" disableImages>+ {signal.content}+ </LemonMarkdown>+ )}++ {/* 16:9 framed preview: eager thumbnail when an export exists, otherwise a play affordance. */}+ <div className="relative w-full aspect-video rounded overflow-hidden border bg-surface-secondary mb-2">+ {thumbnailSrc ? (+ <>+ <img+ src={thumbnailSrc}+ alt={`Recording preview for ${extra.segment_title}`}+ className="absolute inset-0 size-full object-cover"+ onError={() => setThumbnailFailed(true)}+ />+ <div className="absolute inset-0 flex items-center justify-center bg-black/20">+ <ViewRecordingButton+ sessionId={extra.session_id}+ timestamp={extra.start_time}+ openPlayerIn={RecordingPlayerType.Modal}+ checkRecordingExists+ size="small"+ type="primary"+ label="Play"+ />+ </div>+ </>+ ) : (+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 text-tertiary">+ <IconPlay className="size-6" aria-hidden />+ <ViewRecordingButton+ sessionId={extra.session_id}+ timestamp={extra.start_time}+ openPlayerIn={RecordingPlayerType.Modal}+ checkRecordingExists+ size="small"+ type="secondary"+ label="Play recording"+ />+ </div>+ )}+ </div>++ {/* Dot-separated meta line: affected user, segment window, active/total duration. */}+ <div className="flex items-center gap-1.5 flex-wrap text-xs text-tertiary mb-2">+ <span className="font-mono">{extra.distinct_id.slice(0, 10)}…</span>+ <span>·</span>+ <span>+ {humanFriendlyDetailedTime(extra.start_time)} – {humanFriendlyDetailedTime(extra.end_time)}+ </span>+ {(activeDuration || totalDuration) && (+ <>+ <span>·</span>+ <span>+ {activeDuration ? `${activeDuration} active` : null}+ {activeDuration && totalDuration ? ' / ' : null}+ {totalDuration ? `${totalDuration} total` : null}+ </span>+ </>+ )}+ </div>++ {/* Compact problem-event timeline, collapsed past the preview count. */}+ {events.length > 0 && (+ <div className="border-t pt-2">+ <ul className="flex flex-col">+ {visibleEvents.map((entry, index) => (+ <TimelineRow+ key={`${entry.timestamp}-${index}`}+ entry={entry}+ sessionId={extra.session_id}+ />+ ))}+ </ul>+ {events.length > TIMELINE_PREVIEW_COUNT && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => setShowAllEvents(!showAllEvents)}+ className="mt-1"+ >+ {showAllEvents ? 'Show fewer events' : `Show all ${events.length} events`}+ </LemonButton>+ )}+ </div>+ )}++ <div className="flex items-center mt-2">+ <span className="flex-1" />+ <Link to={replayUrl} className="flex items-center gap-1 text-xs font-medium shrink-0">+ Open replay <IconExternal className="size-3" />+ </Link>+ </div>+ </SignalCardShell>+ )+}++export const sessionReplaySignalCardEntry: SignalCardEntry = {+ key: 'session_replay',+ matches: (signal) => signal.source_product === 'session_replay' && isSessionProblemExtra(signal.extra),+ Component: SessionReplaySignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/SignalCardShell.tsx b/frontend/src/scenes/inbox/components/signalCards/SignalCardShell.tsxnew file mode 100644index 000000000000..e7d44edbb9b2--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/SignalCardShell.tsx@@ -0,0 +1,69 @@+import { LemonTag } from '@posthog/lemon-ui'++import { signalCardSourceLine } from 'lib/signals/signalCardSourceLine'+import type { SignalNode } from 'scenes/debug/signals/types'++import { getSourceProductMeta } from '../badges/sourceProductIcons'++/**+ * Header shared by every signal card: the source product's brand icon, the human+ * "Product · Signal type" line, an optional label/right slot, and the weight tag.+ */+export function SignalCardHeader({+ signal,+ label,+ rightSlot,+}: {+ signal: SignalNode+ /** Optional bold title shown after the source line (e.g. an entity name). */+ label?: React.ReactNode+ /** Optional content rendered before the weight tag (e.g. a severity badge). */+ rightSlot?: React.ReactNode+}): JSX.Element {+ const meta = getSourceProductMeta(signal.source_product)+ const Icon = meta?.Icon++ return (+ <div className="flex items-center gap-2 mb-2">+ {Icon ? (+ <span+ className="inline-flex shrink-0 items-center"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ color: meta?.color }}+ aria-hidden+ >+ <Icon className="text-base" />+ </span>+ ) : (+ <span className="size-2.5 rounded-full shrink-0 bg-border" />+ )}+ <span className="text-xs font-medium text-tertiary">{signalCardSourceLine(signal)}</span>+ {label && <span className="text-xs font-medium text-primary flex-1 truncate">{label}</span>}+ <span className="flex-1" />+ {rightSlot}+ <LemonTag size="small" className="shrink-0">+ Weight: {signal.weight.toFixed(1)}+ </LemonTag>+ </div>+ )+}++/** Bordered card container + shared header. Per-source cards render their body as `children`. */+export function SignalCardShell({+ signal,+ label,+ rightSlot,+ children,+}: {+ signal: SignalNode+ label?: React.ReactNode+ rightSlot?: React.ReactNode+ children: React.ReactNode+}): JSX.Element {+ return (+ <div className="border rounded p-3 bg-surface-primary">+ <SignalCardHeader signal={signal} label={label} rightSlot={rightSlot} />+ {children}+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/components/signalCards/SignalsScoutSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/SignalsScoutSignalCard.tsxnew file mode 100644index 000000000000..b0606cf68d94--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/SignalsScoutSignalCard.tsx@@ -0,0 +1,209 @@+import { useState } from 'react'++import { IconExternal, IconList } from '@posthog/icons'+import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress/LemonProgress'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { urls } from 'scenes/urls'++import type { SignalsScoutEvidenceEntry, SignalsScoutSignalExtra } from '~/queries/schema/schema-signals'++import { INBOX_SOURCE_OPTIONS } from '../../filterOptions'+import { SignalReportPriorityBadge } from '../badges/SignalReportPriorityBadge'+import { SignalCardShell } from './SignalCardShell'+import type { SignalCardEntry, SignalCardProps } from './types'++/** How many evidence rows to show before collapsing the rest behind a toggle. */+const EVIDENCE_PREVIEW_COUNT = 3++/** O(1) source-product → {label, icon} lookup, built once from the shared filter options. */+const SOURCE_BY_VALUE: Record<string, { label: string; icon: JSX.Element }> = Object.fromEntries(+ INBOX_SOURCE_OPTIONS.map((o) => [o.value, { label: o.label, icon: o.icon }])+)++/** Narrows a raw `extra` payload to the live Signals scout shape. */+export function isSignalsScoutExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & SignalsScoutSignalExtra {+ return Array.isArray(extra.evidence) && typeof extra.skill_name === 'string' && typeof extra.confidence === 'number'+}++/**+ * Humanizes a scout skill slug into a label: strips the `signals-scout-` prefix, turns dashes into+ * spaces, Sentence-cases the result, and appends " scout" (e.g. `signals-scout-error-tracking` →+ * "Error tracking scout"). A bare `signals-scout` becomes "Scout".+ */+export function humanizeScoutSkillName(skillName: string): string {+ const rest = skillName+ .replace(/^signals-scout-?/, '')+ .replace(/-/g, ' ')+ .trim()+ if (!rest) {+ return 'Scout'+ }+ const sentenceCased = rest.charAt(0).toUpperCase() + rest.slice(1)+ return `${sentenceCased} scout`+}++/**+ * Builds a deep link into the product an evidence entry came from, or null when no link applies.+ * Entity-keyed products need an `entityId`; `logs` is entity-less; unknown products get no link.+ */+export function scoutEvidenceUrl(sourceProduct: string, entityId?: string): string | null {+ switch (sourceProduct) {+ case 'error_tracking':+ return entityId ? urls.errorTrackingIssue(entityId) : null+ case 'session_replay':+ return entityId ? urls.replaySingle(entityId) : null+ case 'llm_analytics':+ return entityId ? urls.aiObservabilityTrace(entityId) : null+ case 'logs':+ return urls.logs()+ default:+ return null+ }+}++/** A single evidence row: source icon + eyebrow, the summary, and an optional deep link. */+function EvidenceRow({ entry }: { entry: SignalsScoutEvidenceEntry }): JSX.Element {+ const meta = SOURCE_BY_VALUE[entry.source_product]+ const url = scoutEvidenceUrl(entry.source_product, entry.entity_id)+ return (+ <li className="flex items-start gap-2 py-0.5">+ <span className="inline-flex shrink-0 items-center text-tertiary mt-0.5" aria-hidden>+ {meta ? meta.icon : <IconList />}+ </span>+ <div className="flex-1 min-w-0">+ <div className="text-xs font-medium text-tertiary">{meta?.label ?? entry.source_product}</div>+ <div className="text-sm text-primary">{entry.summary}</div>+ </div>+ {url && (+ <Link to={url} className="flex items-center gap-1 text-xs font-medium shrink-0">+ View <IconExternal className="size-3" />+ </Link>+ )}+ </li>+ )+}++/** Truncated mono identifier rendering for footer run/finding ids. */+function MonoId({ label, value }: { label: string; value: string }): JSX.Element {+ return (+ <span className="inline-flex items-center gap-1">+ <span>{label}</span>+ <span className="font-mono">{value.length > 12 ? `${value.slice(0, 12)}…` : value}</span>+ </span>+ )+}++/** Richest inbox card: a cross-source scout finding with confidence, hypothesis, evidence, and run metadata. */+export function SignalsScoutSignalCard({ signal }: SignalCardProps): JSX.Element {+ const [showAllEvidence, setShowAllEvidence] = useState(false)++ const extra = signal.extra as Record<string, unknown> & SignalsScoutSignalExtra++ const skillLabel = humanizeScoutSkillName(extra.skill_name)+ const confidencePercent = Math.round(extra.confidence * 100)+ const hypothesis = extra.hypothesis?.trim() || signal.content++ const evidence = extra.evidence ?? []+ const visibleEvidence = showAllEvidence ? evidence : evidence.slice(0, EVIDENCE_PREVIEW_COUNT)++ const tags = extra.tags ?? []+ const timeRange = extra.time_range++ return (+ <SignalCardShell+ signal={signal}+ label={+ <span>+ {skillLabel}+ <span className="text-tertiary font-normal"> · v{extra.skill_version}</span>+ </span>+ }+ rightSlot={<SignalReportPriorityBadge priority={extra.severity} />}+ >+ {/* Confidence meter. */}+ <div className="mb-2">+ <div className="flex items-center justify-between text-xs text-tertiary mb-0.5">+ <span>Confidence</span>+ <span className="tabular-nums">{confidencePercent}%</span>+ </div>+ <LemonProgress percent={confidencePercent} />+ </div>++ {/* Hypothesis — the prominent narrative of the finding. */}+ {hypothesis && (+ <LemonMarkdown className="text-sm text-primary mb-2" disableImages>+ {hypothesis}+ </LemonMarkdown>+ )}++ {/* Tags as raw kebab slugs. */}+ {tags.length > 0 && (+ <div className="flex flex-wrap gap-1 mb-2">+ {tags.map((tag) => (+ <LemonTag key={tag} size="small" type="muted">+ {tag}+ </LemonTag>+ ))}+ </div>+ )}++ {/* Time window the finding refers to. */}+ {timeRange && (+ <div className="text-xs text-tertiary mb-2">+ {humanFriendlyDetailedTime(timeRange.date_from)} – {humanFriendlyDetailedTime(timeRange.date_to)}+ </div>+ )}++ {/* Evidence — the centerpiece, one row per source observation. */}+ {evidence.length > 0 && (+ <div className="border-t pt-2">+ <div className="text-xs font-medium text-tertiary mb-1">Evidence</div>+ <ul className="flex flex-col">+ {visibleEvidence.map((entry, index) => (+ <EvidenceRow key={`${entry.source_product}-${entry.entity_id ?? index}`} entry={entry} />+ ))}+ </ul>+ {evidence.length > EVIDENCE_PREVIEW_COUNT && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => setShowAllEvidence(!showAllEvidence)}+ className="mt-1"+ >+ {showAllEvidence ? 'Show fewer' : `Show all ${evidence.length}`}+ </LemonButton>+ )}+ </div>+ )}++ {/* Footer — run/finding identifiers and an optional trace link-out. */}+ <div className="flex items-center flex-wrap gap-x-3 gap-y-1 border-t pt-2 mt-2 text-xs text-tertiary">+ <MonoId label="Finding" value={extra.finding_id} />+ <MonoId label="Scout run" value={extra.scout_run_id} />+ <MonoId label="Task run" value={extra.task_run_id} />+ {extra.mcp_trace_id && (+ <>+ <span className="flex-1" />+ <Link+ to={urls.aiObservabilityTrace(extra.mcp_trace_id)}+ className="flex items-center gap-1 font-medium shrink-0"+ >+ View LLM trace <IconExternal className="size-3" />+ </Link>+ </>+ )}+ </div>+ </SignalCardShell>+ )+}++export const signalsScoutSignalCardEntry: SignalCardEntry = {+ key: 'signals_scout',+ matches: (signal) => signal.source_product === 'signals_scout' && isSignalsScoutExtra(signal.extra),+ Component: SignalsScoutSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/ZendeskTicketSignalCard.tsx b/frontend/src/scenes/inbox/components/signalCards/ZendeskTicketSignalCard.tsxnew file mode 100644index 000000000000..11d73457e7e5--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/ZendeskTicketSignalCard.tsx@@ -0,0 +1,114 @@+import { LemonTag, type LemonTagType } from 'lib/lemon-ui/LemonTag'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'++import type { ZendeskTicketSignalExtra } from '~/queries/schema/schema-signals'++import { ExternalSignalCard, type StatePill } from './ExternalSignalCard'+import type { SignalCardEntry, SignalCardProps } from './types'++const MAX_VISIBLE_TAGS = 6++/** Guard for Zendesk ticket extras. Keys on `status` + `tags` so it doesn't collide with Linear, which also carries `url` + `priority`. */+export function isZendeskTicketExtra(+ extra: Record<string, unknown>+): extra is Record<string, unknown> & ZendeskTicketSignalExtra {+ return typeof extra.url === 'string' && 'status' in extra && 'tags' in extra+}++/** Map a Zendesk priority to a tag colour. */+function zendeskPriorityTagType(p: string | null): LemonTagType {+ switch (p) {+ case 'urgent':+ return 'danger'+ case 'high':+ return 'warning'+ case 'low':+ return 'muted'+ case 'normal':+ default:+ return 'default'+ }+}++/** Map a Zendesk status to a state-pill tone (constrained to the shell's 5 tones). */+function zendeskStatusTone(s: string): StatePill['tone'] {+ switch (s) {+ case 'solved':+ return 'success'+ case 'open':+ case 'pending':+ return 'warning'+ case 'closed':+ return 'muted'+ case 'new':+ case 'hold':+ default:+ return 'default'+ }+}++/** Sentence-case a lower-case token (e.g. a status or priority). */+function sentenceCase(value: string): string {+ return value.charAt(0).toUpperCase() + value.slice(1)+}++/** Strip Zendesk API artifacts so a raw API URL resolves to the user-facing ticket URL. */+function cleanZendeskUrl(url: string): string {+ return url.replace('/api/v2', '').replace('.json', '')+}++export function ZendeskTicketSignalCard({ signal }: SignalCardProps): JSX.Element {+ const extra = signal.extra as Record<string, unknown> & ZendeskTicketSignalExtra++ const statePill: StatePill = {+ label: sentenceCase(extra.status),+ tone: zendeskStatusTone(extra.status),+ }++ const tags = Array.isArray(extra.tags) ? extra.tags : []+ const visibleTags = tags.slice(0, MAX_VISIBLE_TAGS)+ const overflowCount = tags.length - visibleTags.length++ const metaChips = (+ <>+ {extra.priority !== null && (+ <LemonTag size="small" type={zendeskPriorityTagType(extra.priority)}>+ Priority: {sentenceCase(extra.priority)}+ </LemonTag>+ )}+ {extra.type !== null && (+ <LemonTag size="small" type="default">+ {sentenceCase(extra.type)}+ </LemonTag>+ )}+ {visibleTags.map((tag) => (+ <LemonTag key={tag} size="small" type="muted">+ {tag}+ </LemonTag>+ ))}+ {overflowCount > 0 && (+ <LemonTag size="small" type="muted">+ +{overflowCount} more+ </LemonTag>+ )}+ </>+ )++ return (+ <ExternalSignalCard+ signal={signal}+ statePill={statePill}+ metaChips={metaChips}+ footerLeft={<span>Created {humanFriendlyDetailedTime(extra.created_at)}</span>}+ link={{ to: cleanZendeskUrl(extra.url), label: 'Open in Zendesk' }}+ >+ {signal.content}+ </ExternalSignalCard>+ )+}++export const zendeskTicketSignalCardEntry: SignalCardEntry = {+ key: 'zendesk',+ matches: (signal) => signal.source_product === 'zendesk' && isZendeskTicketExtra(signal.extra),+ Component: ZendeskTicketSignalCard,+}diff --git a/frontend/src/scenes/inbox/components/signalCards/inboxErrorTrackingIssueLogic.ts b/frontend/src/scenes/inbox/components/signalCards/inboxErrorTrackingIssueLogic.tsnew file mode 100644index 000000000000..b1794dd5f30c--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/inboxErrorTrackingIssueLogic.ts@@ -0,0 +1,170 @@+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { ErrorTrackingSpikeEvent } from 'lib/components/Errors/types'+import { dayjs } from 'lib/dayjs'++import { DateRange, ErrorTrackingIssue, ErrorTrackingRelationalIssue } from '~/queries/schema/schema-general'++import { errorTrackingIssueQuery } from 'products/error_tracking/frontend/queries'+import { ERROR_TRACKING_LISTING_RESOLUTION } from 'products/error_tracking/frontend/utils'++import type { inboxErrorTrackingIssueLogicType } from './inboxErrorTrackingIssueLogicType'++export type InboxErrorTrackingIssueSourceType = 'issue_created' | 'issue_reopened' | 'issue_spiking'++export interface InboxErrorTrackingIssueLogicProps {+ issueId: string+ fingerprint: string+ sourceType: InboxErrorTrackingIssueSourceType+}++/** Aggregations + volume + last_seen for the issue, mirroring the error tracking scene's `loadSummary`. */+export interface InboxErrorTrackingIssueSummary {+ last_seen?: string+ first_seen?: string+ aggregations: ErrorTrackingIssue['aggregations']+}++/** Window anchored on the signal: the last 30 days, which comfortably covers a freshly emitted issue. */+function defaultDateRange(): DateRange {+ return {+ date_from: dayjs().subtract(30, 'day').toISOString(),+ date_to: dayjs().toISOString(),+ }+}++/**+ * Loads the live error tracking issue (relational row + summary aggregations, plus spike events for+ * spiking signals) so the inbox signal card can embed the real issue row read-only. Keyed by+ * issue id + fingerprint so distinct signals don't share state.+ */+export const inboxErrorTrackingIssueLogic = kea<inboxErrorTrackingIssueLogicType>([+ path((key) => ['scenes', 'inbox', 'components', 'signalCards', 'inboxErrorTrackingIssueLogic', key]),+ props({} as InboxErrorTrackingIssueLogicProps),+ key((props) => `${props.issueId}:${props.fingerprint}`),++ actions({+ setMergedToIssueId: (issueId: string | null) => ({ issueId }),+ }),++ reducers({+ // When `getIssue` 308-redirects (the issue was merged away), capture the surviving issue id+ // so the card can fall back to a link rather than render a stale row.+ mergedToIssueId: [+ null as string | null,+ {+ setMergedToIssueId: (_, { issueId }) => issueId,+ },+ ],+ }),++ loaders(({ props, actions }) => ({+ issue: [+ null as ErrorTrackingRelationalIssue | null,+ {+ loadIssue: async () => {+ try {+ return await api.errorTracking.getIssue(props.issueId, props.fingerprint)+ } catch (error: any) {+ // 308 means the issue was merged into another; surface the target for the fallback.+ if (error?.status === 308 && error?.data && 'issue_id' in error.data) {+ actions.setMergedToIssueId(error.data.issue_id)+ }+ throw error+ }+ },+ },+ ],+ summary: [+ null as InboxErrorTrackingIssueSummary | null,+ {+ loadSummary: async () => {+ const response = await api.query(+ errorTrackingIssueQuery({+ issueId: props.issueId,+ dateRange: defaultDateRange(),+ filterTestAccounts: false,+ withAggregations: true,+ }),+ { refresh: 'blocking' }+ )+ if (!response.results.length) {+ return null+ }+ const summary = response.results[0]+ if (!summary.aggregations) {+ return null+ }+ return {+ first_seen: summary.first_seen,+ last_seen: summary.last_seen,+ aggregations: summary.aggregations,+ }+ },+ },+ ],+ spikeEvents: [+ [] as ErrorTrackingSpikeEvent[],+ {+ loadSpikeEvents: async () => {+ const { date_from, date_to } = defaultDateRange()+ const response = await api.errorTracking.getSpikeEvents({+ issueIds: [props.issueId],+ dateFrom: date_from ?? undefined,+ dateTo: date_to ?? undefined,+ })+ return response.results+ },+ },+ ],+ })),++ selectors({+ /** True once the issue load failed (not found, merged away, or otherwise unavailable). */+ mergedFailed: [(s) => [s.issueLoading, s.issue], (issueLoading, issue) => !issueLoading && !issue],++ /** Assembled `ErrorTrackingIssue` for the read-only row: relational issue merged with summary. */+ mergedIssue: [+ (s) => [s.issue, s.summary],+ (+ issue: ErrorTrackingRelationalIssue | null,+ summary: InboxErrorTrackingIssueSummary | null+ ): ErrorTrackingIssue | null => {+ if (!issue) {+ return null+ }+ return {+ ...issue,+ last_seen: summary?.last_seen ?? issue.first_seen,+ aggregations: summary?.aggregations,+ // The relational issue carries no library; the runtime icon falls back to unknown.+ library: null,+ }+ },+ ],++ /** Spike-highlight resolution shared with the listing sparkline. */+ sparklineResolution: [() => [], () => ERROR_TRACKING_LISTING_RESOLUTION],+ }),++ listeners(({ props, actions }) => ({+ loadIssueSuccess: () => {+ actions.setMergedToIssueId(null)+ },+ loadIssueFailure: () => {+ // No-op beyond the 308 capture in the loader; `mergedFailed` drives the fallback UI.+ },+ loadSummarySuccess: () => {+ if (props.sourceType === 'issue_spiking') {+ actions.loadSpikeEvents()+ }+ },+ })),++ afterMount(({ actions }) => {+ actions.loadIssue()+ actions.loadSummary()+ }),+])diff --git a/frontend/src/scenes/inbox/components/signalCards/inboxLlmTraceLogic.ts b/frontend/src/scenes/inbox/components/signalCards/inboxLlmTraceLogic.tsnew file mode 100644index 000000000000..2f4499b5b956--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/inboxLlmTraceLogic.ts@@ -0,0 +1,58 @@+import { afterMount, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { dayjs } from 'lib/dayjs'++import { LLMTrace, NodeKind, TraceQuery, TraceQueryResponse } from '~/queries/schema/schema-general'++import type { inboxLlmTraceLogicType } from './inboxLlmTraceLogicType'++export interface InboxLlmTraceLogicProps {+ traceId: string+}++// Earliest timestamp we look back to when fetching a trace by id without a known date — mirrors the+// wide default used by the AI observability trace scene logic. Signals reference older traces, so a+// narrow window would miss them.+const TRACE_LOOKBACK_FLOOR = dayjs.utc(new Date(2025, 0, 10)).toISOString()++/**+ * Keyed loader that eagerly fetches a single `LLMTrace` by id for an inbox signal card. Intentionally+ * standalone — it does not mount the AI observability trace scene logic (which owns URL routing). On+ * failure it returns `null` so the card degrades to text-only rather than blocking.+ */+export const inboxLlmTraceLogic = kea<inboxLlmTraceLogicType>([+ path((key) => ['scenes', 'inbox', 'components', 'signalCards', 'inboxLlmTraceLogic', key]),+ props({} as InboxLlmTraceLogicProps),+ key((props) => props.traceId),++ loaders(({ props }) => ({+ trace: [+ null as LLMTrace | null,+ {+ loadTrace: async () => {+ if (!props.traceId) {+ return null+ }+ const query: TraceQuery = {+ kind: NodeKind.TraceQuery,+ traceId: props.traceId,+ dateRange: { date_from: TRACE_LOOKBACK_FLOOR },+ }+ try {+ const response = (await api.query(query)) as TraceQueryResponse+ return response.results[0] ?? null+ } catch {+ // Degrade to text-only — never block the card on a fetch failure.+ return null+ }+ },+ },+ ],+ })),++ afterMount(({ actions }) => {+ actions.loadTrace()+ }),+])diff --git a/frontend/src/scenes/inbox/components/signalCards/registry.ts b/frontend/src/scenes/inbox/components/signalCards/registry.tsnew file mode 100644index 000000000000..d09e70fb6bb5--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/registry.ts@@ -0,0 +1,63 @@+import { ConversationsTicketSignalCard, conversationsTicketSignalCardEntry } from './ConversationsTicketSignalCard'+import {+ EndpointExecutionFailedSignalCard,+ endpointExecutionFailedSignalCardEntry,+} from './EndpointExecutionFailedSignalCard'+import { ErrorTrackingSignalCard, errorTrackingSignalCardEntry } from './ErrorTrackingSignalCard'+import { GithubIssueSignalCard, githubIssueSignalCardEntry } from './GithubIssueSignalCard'+import { HealthCheckSignalCard, healthCheckSignalCardEntry } from './HealthCheckSignalCard'+import { LinearIssueSignalCard, linearIssueSignalCardEntry } from './LinearIssueSignalCard'+import {+ LlmEvalReportSignalCard,+ LlmEvalTraceSignalCard,+ llmEvalReportSignalCardEntry,+ llmEvalTraceSignalCardEntry,+} from './LlmAnalyticsSignalCard'+import { LogsAlertSignalCard, logsAlertSignalCardEntry } from './LogsAlertSignalCard'+import { PgAnalyzeSignalCard, pgAnalyzeSignalCardEntry } from './PgAnalyzeSignalCard'+import { SessionReplaySignalCard, sessionReplaySignalCardEntry } from './SessionReplaySignalCard'+import { SignalsScoutSignalCard, signalsScoutSignalCardEntry } from './SignalsScoutSignalCard'+import type { SignalCardEntry } from './types'+import { ZendeskTicketSignalCard, zendeskTicketSignalCardEntry } from './ZendeskTicketSignalCard'++// Re-export every per-source card so consumers (stories, tests) can reach them by name.+export {+ ConversationsTicketSignalCard,+ EndpointExecutionFailedSignalCard,+ ErrorTrackingSignalCard,+ GithubIssueSignalCard,+ HealthCheckSignalCard,+ LinearIssueSignalCard,+ LlmEvalReportSignalCard,+ LlmEvalTraceSignalCard,+ LogsAlertSignalCard,+ PgAnalyzeSignalCard,+ SessionReplaySignalCard,+ SignalsScoutSignalCard,+ ZendeskTicketSignalCard,+}++/**+ * Ordered list of signal-card renderers. `SignalCard` picks the first entry whose `matches`+ * returns true. Every entry gates on `source_product`, so entries are mutually exclusive and+ * order is not load-bearing — but keep richer/more-specific variants first as a safety net.+ */+export const SIGNAL_CARD_REGISTRY: SignalCardEntry[] = [+ // PostHog products with live embeds+ errorTrackingSignalCardEntry,+ sessionReplaySignalCardEntry,+ // LLM analytics: report variant first (mutually exclusive guards, but explicit)+ llmEvalReportSignalCardEntry,+ llmEvalTraceSignalCardEntry,+ // Other PostHog-native products+ healthCheckSignalCardEntry,+ conversationsTicketSignalCardEntry,+ endpointExecutionFailedSignalCardEntry,+ logsAlertSignalCardEntry,+ signalsScoutSignalCardEntry,+ // External sources+ githubIssueSignalCardEntry,+ linearIssueSignalCardEntry,+ zendeskTicketSignalCardEntry,+ pgAnalyzeSignalCardEntry,+]diff --git a/frontend/src/scenes/inbox/components/signalCards/types.ts b/frontend/src/scenes/inbox/components/signalCards/types.tsnew file mode 100644index 000000000000..dc74fdc486d7--- /dev/null+++ b/frontend/src/scenes/inbox/components/signalCards/types.ts@@ -0,0 +1,19 @@+import type { SignalNode } from 'scenes/debug/signals/types'++/** Props every per-source signal card receives. The card narrows `signal.extra` itself via its type guard. */+export interface SignalCardProps {+ signal: SignalNode+}++/**+ * One entry in the signal-card registry. `matches` is evaluated in registry order, so more specific+ * entries must come before more general ones. The first matching entry renders the signal; if none+ * match, the generic fallback card is used.+ */+export interface SignalCardEntry {+ /** Stable identifier for the source/variant this entry renders. */+ key: string+ /** True when this entry should render `signal`. Registry order is priority. */+ matches: (signal: SignalNode) => boolean+ Component: (props: SignalCardProps) => JSX.Element+}diff --git a/frontend/src/scenes/inbox/components/tabs/InboxTabs.stories.tsx b/frontend/src/scenes/inbox/components/tabs/InboxTabs.stories.tsxnew file mode 100644index 000000000000..c894810b513d--- /dev/null+++ b/frontend/src/scenes/inbox/components/tabs/InboxTabs.stories.tsx@@ -0,0 +1,99 @@+import type { Decorator, Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import { pullRequestReports, reportTabReports, runReportsFew, runReportsMany } from '../../__mocks__/inboxMocks'+import { SignalReport } from '../../types'+import { PullRequestsTab } from './PullRequestsTab'+import { ReportsTab } from './ReportsTab'+import { RunsTab } from './RunsTab'++// Stories for the inbox tab bodies. The flat report tabs (Reports / Pull requests) load via+// `reportListLogic`, so they get an mswDecorator that mocks the reports list endpoint; the+// Runs tab is prop-driven and receives mock reports directly. Use these to polish list+// density, card design, and the Runs-tab queued / live / finished sections.++// Mocks the shared reports list endpoint so the logic-driven flat tabs render the given set.+function reportsListDecorator(reports: SignalReport[]): Decorator {+ return mswDecorator({+ get: {+ '/api/projects/:id/signals/reports': () => [+ 200,+ { results: reports, count: reports.length, next: null, previous: null },+ ],+ },+ })+}++const meta: Meta = {+ title: 'Scenes-App/Inbox/Tabs',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-06-11',+ testOptions: { waitForLoadersToDisappear: false },+ },+}+export default meta++type Story = StoryObj++export const Reports: Story = {+ decorators: [reportsListDecorator(reportTabReports)],+ render: () => (+ <div className="bg-primary min-h-screen">+ <ReportsTab />+ </div>+ ),+}++export const ReportsEmpty: Story = {+ decorators: [reportsListDecorator([])],+ render: () => (+ <div className="bg-primary min-h-screen">+ <ReportsTab />+ </div>+ ),+}++export const PullRequests: Story = {+ decorators: [reportsListDecorator(pullRequestReports)],+ render: () => (+ <div className="bg-primary min-h-screen">+ <PullRequestsTab />+ </div>+ ),+}++export const PullRequestsEmpty: Story = {+ decorators: [reportsListDecorator([])],+ render: () => (+ <div className="bg-primary min-h-screen">+ <PullRequestsTab />+ </div>+ ),+}++export const RunsManyAgents: Story = {+ render: () => (+ <div className="bg-primary min-h-screen">+ <RunsTab reports={runReportsMany} />+ </div>+ ),+}++export const RunsFewAgents: Story = {+ render: () => (+ <div className="bg-primary min-h-screen">+ <RunsTab reports={runReportsFew} />+ </div>+ ),+}++export const RunsEmpty: Story = {+ render: () => (+ <div className="bg-primary min-h-screen">+ <RunsTab reports={[]} />+ </div>+ ),+}diff --git a/frontend/src/scenes/inbox/components/tabs/NotActionableTab.tsx b/frontend/src/scenes/inbox/components/tabs/NotActionableTab.tsxnew file mode 100644index 000000000000..dba93f3f8988--- /dev/null+++ b/frontend/src/scenes/inbox/components/tabs/NotActionableTab.tsx@@ -0,0 +1,26 @@+import { IconInfo } from '@posthog/icons'++import { INBOX_FLAT_TAB_LIST_PARAMS } from '../../logics/reportListLogic'+import { ReportCard } from '../cards/ReportCard'+import { InboxReportList } from '../InboxReportList'++/**+ * Staff-only (internal) tab listing reports the agent judged `not_actionable`.+ * Same primitive as Pull requests / Reports – only the filter differs. Useful for+ * debugging signal quality.+ */+export function NotActionableTab(): JSX.Element {+ return (+ <InboxReportList+ tabKey="not-actionable"+ listParams={INBOX_FLAT_TAB_LIST_PARAMS['not-actionable']}+ Card={ReportCard}+ emptyState={{+ icon: <IconInfo className="text-2xl" />,+ title: 'Nothing judged not-actionable',+ description:+ 'Reports the agent decided are not actionable land here, so the team can audit signal quality.',+ }}+ />+ )+}diff --git a/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsx b/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsxnew file mode 100644index 000000000000..2bc9e09ea923--- /dev/null+++ b/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsx@@ -0,0 +1,21 @@+import { IconPullRequest } from '@posthog/icons'++import { INBOX_FLAT_TAB_LIST_PARAMS } from '../../logics/reportListLogic'+import { ReportCard } from '../cards/ReportCard'+import { InboxReportList } from '../InboxReportList'++export function PullRequestsTab(): JSX.Element {+ return (+ <InboxReportList+ tabKey="pulls"+ listParams={INBOX_FLAT_TAB_LIST_PARAMS.pulls}+ Card={ReportCard}+ emptyState={{+ icon: <IconPullRequest className="text-2xl" />,+ title: 'No pull requests right now',+ description:+ 'When an agent ships a code change, the PR draft lands here for you to review and publish.',+ }}+ />+ )+}diff --git a/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsx b/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsxnew file mode 100644index 000000000000..f2719a50f4ef--- /dev/null+++ b/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsx@@ -0,0 +1,21 @@+import { IconNotebook } from '@posthog/icons'++import { INBOX_FLAT_TAB_LIST_PARAMS } from '../../logics/reportListLogic'+import { ReportCard } from '../cards/ReportCard'+import { InboxReportList } from '../InboxReportList'++export function ReportsTab(): JSX.Element {+ return (+ <InboxReportList+ tabKey="reports"+ listParams={INBOX_FLAT_TAB_LIST_PARAMS.reports}+ Card={ReportCard}+ emptyState={{+ icon: <IconNotebook className="text-2xl" />,+ title: 'No reports yet',+ description:+ "Reports are what agents surface when there's something worth your judgment but no clean code change to draft.",+ }}+ />+ )+}diff --git a/frontend/src/scenes/inbox/components/tabs/RunsTab.tsx b/frontend/src/scenes/inbox/components/tabs/RunsTab.tsxnew file mode 100644index 000000000000..309bb4a7fd54--- /dev/null+++ b/frontend/src/scenes/inbox/components/tabs/RunsTab.tsx@@ -0,0 +1,188 @@+import { useMemo, useState } from 'react'++import { IconBrain } from '@posthog/icons'++import { isFinishedRunReport, isLiveRunReport, isQueuedRunReport } from '../../inboxMembership'+import { SignalReport } from '../../types'+import { AgentRunCard } from '../cards/AgentRunCard'++const RECENTLY_FINISHED_LIMIT = 10+const QUEUED_LIMIT = 10++function timestampMs(value: string | null | undefined): number {+ if (!value) {+ return 0+ }+ const ms = new Date(value).getTime()+ return Number.isFinite(ms) ? ms : 0+}++export function RunsTab({ reports }: { reports: SignalReport[] }): JSX.Element {+ const [showAllFinished, setShowAllFinished] = useState(false)+ const [showAllQueued, setShowAllQueued] = useState(false)++ const { queuedRuns, liveRuns, finishedRuns } = useMemo(() => {+ const queued: SignalReport[] = []+ const live: SignalReport[] = []+ const finished: SignalReport[] = []+ for (const report of reports) {+ if (isQueuedRunReport(report)) {+ queued.push(report)+ } else if (isLiveRunReport(report)) {+ live.push(report)+ } else if (isFinishedRunReport(report)) {+ finished.push(report)+ }+ }+ const newestFirst = (a: SignalReport, b: SignalReport): number =>+ timestampMs(b.updated_at ?? b.created_at) - timestampMs(a.updated_at ?? a.created_at)+ queued.sort(newestFirst)+ live.sort(newestFirst)+ finished.sort(newestFirst)+ return { queuedRuns: queued, liveRuns: live, finishedRuns: finished }+ }, [reports])++ const visibleFinishedRuns = showAllFinished ? finishedRuns : finishedRuns.slice(0, RECENTLY_FINISHED_LIMIT)+ const hiddenFinishedCount = Math.max(0, finishedRuns.length - visibleFinishedRuns.length)+ const finishedShowAll = resolveShowAllControl(+ finishedRuns.length,+ RECENTLY_FINISHED_LIMIT,+ hiddenFinishedCount,+ showAllFinished,+ () => setShowAllFinished(true),+ () => setShowAllFinished(false)+ )++ const visibleQueuedRuns = showAllQueued ? queuedRuns : queuedRuns.slice(0, QUEUED_LIMIT)+ const hiddenQueuedCount = Math.max(0, queuedRuns.length - visibleQueuedRuns.length)+ const queuedShowAll = resolveShowAllControl(+ queuedRuns.length,+ QUEUED_LIMIT,+ hiddenQueuedCount,+ showAllQueued,+ () => setShowAllQueued(true),+ () => setShowAllQueued(false)+ )++ const hasAnyRuns = queuedRuns.length > 0 || liveRuns.length > 0 || finishedRuns.length > 0++ return (+ <div className="mx-auto max-w-3xl flex flex-col gap-4 px-6 py-4">+ {!hasAnyRuns ? (+ <div className="mx-auto max-w-md flex flex-col items-center text-center py-16 gap-2">+ <div className="flex items-center justify-center h-12 w-12 rounded-full bg-fill-primary text-secondary mb-1">+ <IconBrain className="text-2xl" />+ </div>+ <h3 className="text-base font-semibold m-0">No agents are working on anything right now</h3>+ <p className="text-sm text-tertiary m-0">+ When Self-driving kicks one off, you'll see the live run land here until it finishes as a Pull+ request or a Report.+ </p>+ </div>+ ) : (+ <div className="flex flex-col gap-5">+ {queuedRuns.length > 0 && (+ <RunsSection+ title="Queued"+ count={queuedRuns.length}+ runs={visibleQueuedRuns}+ showAll={queuedShowAll}+ />+ )}+ <RunsSection+ title="Live"+ count={liveRuns.length}+ isLive+ runs={liveRuns}+ empty={{+ title: 'Nothing in motion right now',+ description: 'Self-driving will queue something up here when it kicks off a run.',+ }}+ />+ {finishedRuns.length > 0 && (+ <RunsSection+ title="Recently finished"+ count={finishedRuns.length}+ runs={visibleFinishedRuns}+ showAll={finishedShowAll}+ />+ )}+ </div>+ )}+ </div>+ )+}++type ShowAllControl =+ | { kind: 'expand'; hiddenCount: number; onClick: () => void }+ | { kind: 'collapse'; onClick: () => void }++function resolveShowAllControl(+ totalCount: number,+ limit: number,+ hiddenCount: number,+ expanded: boolean,+ onExpand: () => void,+ onCollapse: () => void+): ShowAllControl | undefined {+ if (hiddenCount > 0) {+ return { kind: 'expand', hiddenCount, onClick: onExpand }+ }+ if (expanded && totalCount > limit) {+ return { kind: 'collapse', onClick: onCollapse }+ }+ return undefined+}++interface RunsSectionProps {+ title: string+ count: number+ description?: string+ isLive?: boolean+ runs: SignalReport[]+ empty?: { title: string; description: string }+ showAll?: ShowAllControl+}++function RunsSection({ title, count, description, isLive, runs, empty, showAll }: RunsSectionProps): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-col gap-0.5 cursor-default select-none">+ <div className="flex items-center gap-2">+ <span className="font-semibold text-[13px] text-default">{title}</span>+ <span className="text-xs text-tertiary tabular-nums">{count}</span>+ {isLive && count > 0 && (+ <span className="inline-flex h-1.5 w-1.5 animate-pulse rounded-full bg-accent" aria-hidden />+ )}+ </div>+ {description && <span className="text-xs text-secondary leading-snug">{description}</span>}+ </div>+ {runs.length === 0 && empty ? (+ <div className="flex items-center gap-3 cursor-default select-none rounded border border-dashed border-primary bg-surface-secondary px-4 py-3.5">+ <div className="flex items-center justify-center h-8 w-8 shrink-0 rounded-full bg-fill-primary ring-1 ring-inset ring-primary">+ <IconBrain className="text-tertiary" />+ </div>+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">+ <span className="font-medium text-[13px] text-default">{empty.title}</span>+ <span className="text-xs text-tertiary leading-snug">{empty.description}</span>+ </div>+ </div>+ ) : (+ <div className="flex flex-col gap-3">+ {runs.map((report) => (+ <AgentRunCard key={report.id} report={report} />+ ))}+ </div>+ )}+ {showAll && (+ <button+ type="button"+ onClick={showAll.onClick}+ className="self-start rounded px-1.5 py-1 font-medium text-xs text-accent hover:bg-accent-highlight"+ >+ {showAll.kind === 'collapse' ? 'Show less' : `Show all ${showAll.hiddenCount} more`}+ </button>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/inbox/filterOptions.tsx b/frontend/src/scenes/inbox/filterOptions.tsxnew file mode 100644index 000000000000..6bfad265afd8--- /dev/null+++ b/frontend/src/scenes/inbox/filterOptions.tsx@@ -0,0 +1,101 @@+import { JSX } from 'react'++import {+ IconBrain,+ IconBug,+ IconCalendar,+ IconClock,+ IconCompass,+ IconDatabase,+ IconGithub,+ IconList,+ IconReceipt,+ IconRefresh,+ IconRewindPlay,+ IconStack,+ IconSupport,+} from '@posthog/icons'+import { LemonTagType } from '@posthog/lemon-ui'++import { InboxSortDirection, InboxSortField } from './logics/inboxFiltersLogic'+import { SignalReportPriority } from './types'++/**+ * Single source of truth for per-priority color. P0–P4 each get a DISTINCT hue so+ * users can tell them apart at a glance (red → orange → amber → blue → gray).+ * Consumed by the priority badge, the priority monogram, and the filter dots.+ */+export const PRIORITY_TAG_TYPE: Record<SignalReportPriority, LemonTagType> = {+ P0: 'danger', // red+ P1: 'warning', // orange+ P2: 'caution', // amber+ P3: 'highlight', // blue+ P4: 'muted', // gray+}++/** Matching CSS accent per priority, for non-LemonTag surfaces (filter dots, monograms). */+export const PRIORITY_ACCENT: Record<SignalReportPriority, string> = {+ P0: 'var(--red-9, #e5484d)',+ P1: 'var(--orange-9, #f76b15)',+ P2: 'var(--amber-9, #ffc53d)',+ P3: 'var(--blue-9, #3b9eff)',+ P4: 'var(--muted, #8f8f8f)',+}++// Port of desktop `@posthog/ui/features/inbox/filterOptions`. Drives the Source /+// Sort / Priority filter popovers. Source-product values match the backend+// `source_product` values; priority values are P0–P4.++export interface InboxSortOption {+ label: string+ field: InboxSortField+ direction: InboxSortDirection+ icon: JSX.Element+}++export const INBOX_SORT_OPTIONS: InboxSortOption[] = [+ { label: 'Priority first', field: 'priority', direction: 'asc', icon: <IconList /> },+ { label: 'Last updated first', field: 'updated_at', direction: 'desc', icon: <IconRefresh /> },+ { label: 'Newest first', field: 'created_at', direction: 'desc', icon: <IconCalendar /> },+ { label: 'Oldest first', field: 'created_at', direction: 'asc', icon: <IconClock /> },+]++export const INBOX_PRIORITY_OPTIONS: { value: SignalReportPriority; accent: string }[] = (+ ['P0', 'P1', 'P2', 'P3', 'P4'] as SignalReportPriority[]+).map((value) => ({ value, accent: PRIORITY_ACCENT[value] }))++export const INBOX_SOURCE_OPTIONS: { value: string; label: string; icon: JSX.Element }[] = [+ { value: 'session_replay', label: 'Session replay', icon: <IconRewindPlay /> },+ { value: 'error_tracking', label: 'Error tracking', icon: <IconBug /> },+ { value: 'llm_analytics', label: 'AI observability', icon: <IconBrain /> },+ { value: 'github', label: 'GitHub', icon: <IconGithub /> },+ { value: 'linear', label: 'Linear', icon: <IconStack /> },+ { value: 'zendesk', label: 'Zendesk', icon: <IconReceipt /> },+ { value: 'conversations', label: 'Conversations', icon: <IconSupport /> },+ { value: 'pganalyze', label: 'pganalyze', icon: <IconDatabase /> },+ { value: 'signals_scout', label: 'Scout', icon: <IconCompass /> },+]++export function inboxSortOptionKey(field: InboxSortField, direction: InboxSortDirection): string {+ return `${field}:${direction}`+}++export function inboxSourceFilterLabel(selected: string[]): string {+ if (selected.length === 0) {+ return 'All sources'+ }+ if (selected.length === 1) {+ return INBOX_SOURCE_OPTIONS.find((o) => o.value === selected[0])?.label ?? selected[0]+ }+ return `${selected.length} sources`+}++export function inboxPriorityFilterLabel(selected: SignalReportPriority[]): string {+ if (selected.length === 0) {+ return 'All priorities'+ }+ if (selected.length <= 2) {+ return selected.join(', ')+ }+ return `${selected.length} priorities`+}diff --git a/frontend/src/scenes/inbox/inboxMembership.ts b/frontend/src/scenes/inbox/inboxMembership.tsnew file mode 100644index 000000000000..fdad0bb351f5--- /dev/null+++ b/frontend/src/scenes/inbox/inboxMembership.ts@@ -0,0 +1,55 @@+// Port of desktop `@posthog/core/inbox/reportMembership`. Pure functions that+// decide which tab a report belongs to and how the scope filter applies.+// Keep behaviour identical to desktop – this is the source of truth for tab IA.++import { InboxScope, SignalReport, SignalReportStatus } from './types'++/**+ * Statuses out of the inbox entirely (user-suppressed or removed). `failed` is+ * NOT here: failed runs surface in the Runs tab's recently-finished section.+ */+const INBOX_EXCLUDED_STATUSES = new Set<SignalReportStatus>([SignalReportStatus.SUPPRESSED, SignalReportStatus.DELETED])++export function isExcludedFromInbox(report: SignalReport): boolean {+ return INBOX_EXCLUDED_STATUSES.has(report.status)+}++export function teammateInboxScope(uuid: string): InboxScope {+ return `teammate:${uuid}`+}++export function parseTeammateInboxScope(scope: InboxScope): string | null {+ if (!scope.startsWith('teammate:')) {+ return null+ }+ const uuid = scope.slice('teammate:'.length).trim()+ return uuid || null+}++export function isTeammateInboxScope(scope: InboxScope): scope is `teammate:${string}` {+ return parseTeammateInboxScope(scope) != null+}++const QUEUED_RUN_STATUSES = new Set<SignalReportStatus>([SignalReportStatus.POTENTIAL, SignalReportStatus.CANDIDATE])+const LIVE_RUN_STATUSES = new Set<SignalReportStatus>([+ SignalReportStatus.IN_PROGRESS,+ SignalReportStatus.PENDING_INPUT,+])+const FINISHED_RUN_STATUSES = new Set<SignalReportStatus>([SignalReportStatus.READY, SignalReportStatus.FAILED])++export function isQueuedRunReport(report: SignalReport): boolean {+ return QUEUED_RUN_STATUSES.has(report.status)+}++export function isLiveRunReport(report: SignalReport): boolean {+ return LIVE_RUN_STATUSES.has(report.status)+}++export function isFinishedRunReport(report: SignalReport): boolean {+ return FINISHED_RUN_STATUSES.has(report.status)+}++/** Runs-tab count chip + cross-tab exclusion: only "in motion" runs (queued or live). */+export function isAgentRunReport(report: SignalReport): boolean {+ return isQueuedRunReport(report) || isLiveRunReport(report)+}diff --git a/frontend/src/scenes/inbox/inboxSceneLogic.ts b/frontend/src/scenes/inbox/inboxSceneLogic.tsindex f22fdf53e58e..b9aaf6e1b77b 100644--- a/frontend/src/scenes/inbox/inboxSceneLogic.ts+++ b/frontend/src/scenes/inbox/inboxSceneLogic.ts@@ -5,104 +5,110 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api, { CountedPaginatedResponse } from 'lib/api'-import { SignalNode } from 'scenes/debug/signals/types'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { Breadcrumb } from '~/types'+import { isAgentRunReport, isFinishedRunReport } from './inboxMembership'import type { inboxSceneLogicType } from './inboxSceneLogicType'+import { INBOX_PIPELINE_STATUS_FILTERS } from './logics/inboxFiltersLogic'+import { INBOX_FLAT_TAB_LIST_PARAMS, reportListLogic } from './logics/reportListLogic'import { signalSourcesLogic } from './signalSourcesLogic'-import {- EnrichedReviewer,- SignalReport,- SignalReportArtefact,- SignalReportArtefactResponse,- SignalReportStatus,-} from './types'+import { InboxFlatListTabKey, INBOX_STAFF_ONLY_TAB_KEYS, INBOX_TAB_KEYS, InboxTabKey, SignalReport } from './types'-const REPORTS_PAGE_SIZE = 200--export type DetailTab = 'overview' | 'signals'+const RUNS_PAGE_SIZE = 200const SESSION_ANALYSIS_POLL_INTERVAL_MS = 5000+function isInboxTabKey(value: string | undefined): value is InboxTabKey {+ return value !== undefined && (INBOX_TAB_KEYS as string[]).includes(value)+}++function isStaffOnlyTab(tab: string | undefined): boolean {+ return tab !== undefined && (INBOX_STAFF_ONLY_TAB_KEYS as string[]).includes(tab)+}++/**+ * Find a report already loaded in one of the mounted per-tab lists (or the staff Runs list),+ * so opening it can render the detail instantly from the list row instead of waiting on a fresh+ * `GET`. The background fetch still runs to converge on the authoritative record.+ */+function findLoadedReport(id: string, runsReports: SignalReport[]): SignalReport | null {+ const fromRuns = runsReports.find((r) => r.id === id)+ if (fromRuns) {+ return fromRuns+ }+ for (const tabKey of Object.keys(INBOX_FLAT_TAB_LIST_PARAMS) as InboxFlatListTabKey[]) {+ const mounted = reportListLogic.findMounted({ tabKey, listParams: INBOX_FLAT_TAB_LIST_PARAMS[tabKey] })+ const found = mounted?.values.reports.find((r) => r.id === id)+ if (found) {+ return found+ }+ }+ return null+}++/**+ * Inbox scene orchestrator. Owns the active tab, the selected report (loaded by id),+ * the staff-only project-wide Runs list, and session-analysis. The per-tab report+ * lists + their counts live in the keyed `reportListLogic` (one instance per flat tab),+ * so this logic no longer holds a shared report list.+ */export const inboxSceneLogic = kea<inboxSceneLogicType>([path(['scenes', 'inbox', 'inboxSceneLogic']),- connect({- values: [signalSourcesLogic, ['hasNoSources', 'isSessionAnalysisRunning']],+ connect(() => ({+ values: [signalSourcesLogic, ['isSessionAnalysisRunning'], userLogic, ['user']],actions: [signalSourcesLogic, ['loadSourceConfigs']],- }),+ })),actions({setSelectedReportId: (id: string | null) => ({ id }),- setSearchQuery: (query: string) => ({ query }),- setStatusFilters: (statuses: SignalReportStatus[]) => ({ statuses }),- setActiveDetailTab: (tab: DetailTab) => ({ tab }),- deleteReport: (reportId: string) => ({ reportId }),- reingestReport: (reportId: string) => ({ reportId }),+ // Seed (or clear) the selected report synchronously from an already-loaded list row, so the+ // detail renders without a spinner while the authoritative fetch runs in the background.+ seedSelectedReport: (report: SignalReport | null) => ({ report }),+ setActiveTab: (tab: InboxTabKey) => ({ tab }),runSessionAnalysis: true,runSessionAnalysisSuccess: true,runSessionAnalysisFailure: (error: string) => ({ error }),}),- loaders(({ values }) => ({- reportsResponse: [+ loaders(() => ({+ // Staff-only Runs tab: project-wide, UNFILTERED (no reviewer scope / source / priority / search) –+ // every report whose run is in progress or has concluded.+ runsResponse: [null as CountedPaginatedResponse<SignalReport> | null,{- loadReports: async () => {+ loadRuns: async () => {return await api.signalReports.list({- limit: REPORTS_PAGE_SIZE,- offset: 0,- status: values.statusFilters.length > 0 ? values.statusFilters.join(',') : undefined,- search: values.searchQuery.trim() || undefined,- ordering: '-is_suggested_reviewer,-signal_count',+ status: INBOX_PIPELINE_STATUS_FILTERS.join(','),+ ordering: 'status,-updated_at',+ limit: RUNS_PAGE_SIZE,})},- loadMoreReports: async () => {- const currentResults = values.reportsResponse?.results ?? []- const response = await api.signalReports.list({- limit: REPORTS_PAGE_SIZE,- offset: currentResults.length,- status: values.statusFilters.length > 0 ? values.statusFilters.join(',') : undefined,- search: values.searchQuery.trim() || undefined,- ordering: '-is_suggested_reviewer,-signal_count',- })- return {- ...response,- results: [...currentResults, ...response.results],- }- },- },- ],- artefacts: [- {} as Record<string, SignalReportArtefact[]>,- {- loadArtefacts: async ({ reportId }: { reportId: string }) => {- const response: SignalReportArtefactResponse = await api.signalReports.artefacts(reportId)- return { ...values.artefacts, [reportId]: response.results }- },},],- reportSignals: [- {} as Record<string, SignalNode[]>,+ // The selected report's base record, loaded by id so detail works regardless of which+ // tab/list it came from (and on direct deep-link).+ selectedReportResponse: [+ null as SignalReport | null,{- loadReportSignals: async ({ reportId }: { reportId: string }) => {- const response = await api.signalReports.getReportSignals(reportId)- return { ...values.reportSignals, [reportId]: response.signals }+ loadSelectedReport: async ({ id }: { id: string }) => {+ return await api.signalReports.get(id)},},],})),reducers({- reportsResponse: {- deleteReport: (state: CountedPaginatedResponse<SignalReport> | null, { reportId }: { reportId: string }) =>- state- ? { ...state, results: state.results.filter((r) => r.id !== reportId), count: state.count - 1 }- : state,+ selectedReportResponse: {+ // Navigation seeds this directly: the listener resolves the list row (or null) and+ // dispatches `seedSelectedReport` in the same tick, so we never flash through a stale+ // report or a spinner when the row is already loaded. The loader repopulates it on fetch.+ seedSelectedReport: (_, { report }) => report,},selectedReportId: [null as string | null,@@ -110,23 +116,10 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([setSelectedReportId: (_, { id }) => id,},],- searchQuery: [- '',- {- setSearchQuery: (_, { query }) => query,- },- ],- statusFilters: [- [SignalReportStatus.READY] as SignalReportStatus[],+ activeTab: [+ 'pulls' as InboxTabKey,{- setStatusFilters: (_, { statuses }) => statuses,- },- ],- activeDetailTab: [- 'overview' as DetailTab,- {- setActiveDetailTab: (_, { tab }) => tab,- setSelectedReportId: () => 'overview' as DetailTab,+ setActiveTab: (_, { tab }) => tab,},],isRunningSessionAnalysis: [@@ -150,119 +143,44 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([},],],- reports: [- (s) => [s.reportsResponse],- (reportsResponse: CountedPaginatedResponse<SignalReport> | null): SignalReport[] =>- reportsResponse?.results ?? [],- ],- reportsLoading: [- (s) => [s.reportsResponseLoading],- (reportsResponseLoading: boolean): boolean => reportsResponseLoading,- ],- reportsTotal: [- (s) => [s.reportsResponse],- (reportsResponse: CountedPaginatedResponse<SignalReport> | null): number => reportsResponse?.count ?? 0,+ isStaff: [() => [userLogic.selectors.user], (user): boolean => user?.is_staff ?? false],+ runsTabReports: [+ (s) => [s.runsResponse],+ (runsResponse: CountedPaginatedResponse<SignalReport> | null): SignalReport[] =>+ (runsResponse?.results ?? []).filter((r) => isAgentRunReport(r) || isFinishedRunReport(r)),],- reportsHasMore: [- (s) => [s.reportsResponse],- (reportsResponse: CountedPaginatedResponse<SignalReport> | null): boolean =>- reportsResponse?.next !== null && reportsResponse?.next !== undefined,- ],- filteredReports: [(s) => [s.reports], (reports: SignalReport[]): SignalReport[] => reports],+ runsCount: [(s) => [s.runsTabReports], (runsTabReports: SignalReport[]): number => runsTabReports.length],selectedReport: [- (s) => [s.reports, s.selectedReportId],- (reports: SignalReport[], selectedReportId: string | null): SignalReport | null =>- reports.find((r) => r.id === selectedReportId) ?? null,- ],- shouldShowEnablingCtaOnMobile: [- (s) => [s.hasNoSources, s.filteredReports, s.reportsLoading],- (hasNoSources: boolean, filteredReports: SignalReport[], reportsLoading: boolean): boolean =>- hasNoSources && !reportsLoading && filteredReports.length === 0,- ],- selectedReportSignals: [- (s) => [s.reportSignals, s.selectedReportId],- (reportSignals: Record<string, SignalNode[]>, selectedReportId: string | null): SignalNode[] | null =>- selectedReportId ? (reportSignals[selectedReportId] ?? null) : null,+ (s) => [s.selectedReportResponse],+ (selectedReportResponse: SignalReport | null): SignalReport | null => selectedReportResponse,],- selectedReportReviewers: [- (s) => [s.artefacts, s.selectedReportId],- (- artefacts: Record<string, SignalReportArtefact[]>,- selectedReportId: string | null- ): EnrichedReviewer[] | null => {- if (!selectedReportId) {- return null- }- const reportArtefacts = artefacts[selectedReportId]- if (!reportArtefacts) {- return null- }- const reviewersArtefact = reportArtefacts.find((a) => a.type === 'suggested_reviewers')- if (!reviewersArtefact) {- return null- }- // content is already JSON-decoded by the serializer- return reviewersArtefact.content as EnrichedReviewer[]- },+ selectedReportLoading: [+ (s) => [s.selectedReportResponseLoading],+ (selectedReportResponseLoading: boolean): boolean => selectedReportResponseLoading,],}),listeners(({ actions, values, cache }) => ({- setSearchQuery: async (_, breakpoint) => {- await breakpoint(300)- actions.loadReports()- },- setStatusFilters: () => {- actions.loadReports()- },- setSelectedReportId: ({ id }) => {- if (id) {- if (!values.artefacts[id]) {- actions.loadArtefacts({ reportId: id })- }- if (!values.reportSignals[id]) {- actions.loadReportSignals({ reportId: id })- }- }- },- setActiveDetailTab: ({ tab }) => {- if (tab === 'signals' && values.selectedReportId && !values.reportSignals[values.selectedReportId]) {- actions.loadReportSignals({ reportId: values.selectedReportId })+ setActiveTab: ({ tab }) => {+ // Refresh the project-wide runs list each time the (staff-only) Runs tab opens.+ if (tab === 'runs' && values.isStaff) {+ actions.loadRuns()}},- deleteReport: async ({ reportId }) => {- // Reducer handles optimistic removal from list- if (values.selectedReportId === reportId) {- actions.setSelectedReportId(null)- }- try {- await api.signalReports.delete(reportId)- lemonToast.success('Report deleted')- } catch (error: any) {- const errorMessage = error?.detail || error?.message || 'Failed to delete report'- lemonToast.error(errorMessage)- actions.loadReports()- }- },- reingestReport: async ({ reportId }) => {- try {- await api.signalReports.reingest(reportId)- lemonToast.success('Reingestion started — signals will be re-grouped')- if (values.selectedReportId === reportId) {- actions.setSelectedReportId(null)- }- actions.loadReports()- } catch (error: any) {- const errorMessage = error?.detail || error?.message || 'Failed to start reingestion'- lemonToast.error(errorMessage)+ setSelectedReportId: ({ id }) => {+ if (!id) {+ actions.seedSelectedReport(null)+ return}+ // Reuse the list row if we already have it (instant render), then refresh from the server.+ actions.seedSelectedReport(findLoadedReport(id, values.runsTabReports))+ actions.loadSelectedReport({ id })},loadSourceConfigsSuccess: () => {clearInterval(cache.sessionAnalysisPollInterval)if (values.isSessionAnalysisRunning) {cache.sessionAnalysisPollInterval = setInterval(() => {actions.loadSourceConfigs()- actions.loadReports()}, SESSION_ANALYSIS_POLL_INTERVAL_MS)}},@@ -272,19 +190,18 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([lemonToast.success('Session analysis completed')actions.runSessionAnalysisSuccess()} catch (error: any) {- const errorMessage = error?.detail || error?.message || 'Failed to run session analysis'- lemonToast.error(errorMessage)- actions.runSessionAnalysisFailure(errorMessage)+ lemonToast.error(error?.detail || error?.message || 'Failed to run session analysis')+ actions.runSessionAnalysisFailure(error?.detail || error?.message || 'Failed to run session analysis')}},- runSessionAnalysisSuccess: () => {- actions.loadReports()- },})),- events(({ actions, cache }) => ({+ events(({ actions, values, cache }) => ({afterMount: () => {- actions.loadReports()+ // Runs is a staff-only (internal) tab; only fetch its list for staff users.+ if (values.isStaff) {+ actions.loadRuns()+ }},beforeUnmount: () => {clearInterval(cache.sessionAnalysisPollInterval)@@ -292,8 +209,18 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([})),actionToUrl(({ values }) => ({+ setActiveTab: () => [+ values.selectedReportId+ ? urls.inboxReport(values.activeTab, values.selectedReportId)+ : urls.inbox(values.activeTab),+ router.values.searchParams,+ router.values.hashParams,+ { replace: false },+ ],setSelectedReportId: () => [- values.selectedReportId ? urls.inbox(values.selectedReportId) : urls.inbox(),+ values.selectedReportId+ ? urls.inboxReport(values.activeTab, values.selectedReportId)+ : urls.inbox(values.activeTab),router.values.searchParams,router.values.hashParams,{ replace: false },@@ -306,7 +233,27 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([actions.setSelectedReportId(null)}},- [urls.inbox(':reportId')]: ({ reportId }: { reportId?: string }) => {+ [urls.inbox(':tab')]: ({ tab }: { tab?: string }) => {+ // Staff-only tabs (Runs, Not actionable): bounce non-staff to the default tab.+ if (isStaffOnlyTab(tab) && userLogic.values.user != null && !values.isStaff) {+ actions.setActiveTab('pulls')+ return+ }+ if (isInboxTabKey(tab) && values.activeTab !== tab) {+ actions.setActiveTab(tab)+ }+ if (values.selectedReportId !== null) {+ actions.setSelectedReportId(null)+ }+ },+ [urls.inboxReport(':tab', ':reportId')]: ({ tab, reportId }: { tab?: string; reportId?: string }) => {+ if (isStaffOnlyTab(tab) && userLogic.values.user != null && !values.isStaff) {+ actions.setActiveTab('pulls')+ return+ }+ if (isInboxTabKey(tab) && values.activeTab !== tab) {+ actions.setActiveTab(tab)+ }const id = reportId ?? nullif (values.selectedReportId !== id) {actions.setSelectedReportId(id)diff --git a/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts b/frontend/src/scenes/inbox/inboxTaskKickoffLogic.tsnew file mode 100644index 000000000000..adffd5009cc7--- /dev/null+++ b/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts@@ -0,0 +1,125 @@+import { actions, kea, listeners, path, reducers } from 'kea'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { urls } from 'scenes/urls'++import { OriginProduct } from 'products/tasks/frontend/types'++import type { inboxTaskKickoffLogicType } from './inboxTaskKickoffLogicType'+import { SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP, SignalReport, SignalReportTaskRelationship } from './types'++// Cloud-adapted port of desktop `useDiscussReport` / `useCreatePrReport`. These are+// task-kickoff actions (create a cloud Task linked to the report, then navigate to it) –+// NOT a live chat surface. The created task carries the SignalReport linkage so the+// backend's agent pipeline can pick it up.++function buildCreatePrReportPrompt(report: SignalReport, feedback?: string): string {+ const base = `Act on PostHog Inbox report "${report.title ?? report.id}" (id ${report.id}). Investigate the root cause using the report's contributing findings, implement the fix, and open a PR.${+ report.summary ? `\n\nReport summary:\n${report.summary}` : ''+ }`+ const trimmed = feedback?.trim()+ if (!trimmed) {+ return base+ }+ return `${base}\n\nAdditional feedback from the user (take this into account):\n${trimmed}`+}++function buildDiscussReportPrompt(report: SignalReport, question?: string): string {+ const base = `Discuss PostHog Inbox report "${report.title ?? report.id}" (id ${report.id}). Investigate the contributing findings and help the user understand and decide what to do.${+ report.summary ? `\n\nReport summary:\n${report.summary}` : ''+ }`+ const trimmed = question?.trim()+ if (!trimmed) {+ return base+ }+ return `${base}\n\nThe user asks:\n${trimmed}`+}++async function createReportTask(+ report: SignalReport,+ relationship: SignalReportTaskRelationship,+ prompt: string,+ fallbackTitle: string+): Promise<void> {+ // Pick a default repository (mirrors desktop resolving lastUsedCloudRepository → first repo).+ let repository: string | undefined+ try {+ const { repositories } = await api.tasks.repositories()+ repository = repositories[0]+ } catch {+ repository = undefined+ }++ const task = await api.tasks.create({+ title: report.title?.trim() || fallbackTitle,+ description: prompt,+ origin_product: OriginProduct.SIGNAL_REPORT,+ repository,+ // Linkage fields accepted by the tasks backend for the signal_report origin.+ signal_report: report.id,+ signal_report_task_relationship: relationship,+ } as Parameters<typeof api.tasks.create>[0])++ router.actions.push(urls.taskDetail(task.id))+}++export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([+ path(['scenes', 'inbox', 'inboxTaskKickoffLogic']),++ actions({+ discussReport: (report: SignalReport, question?: string) => ({ report, question }),+ createPrFromReport: (report: SignalReport) => ({ report }),+ discussReportSuccess: true,+ discussReportFailure: true,+ createPrSuccess: true,+ createPrFailure: true,+ }),++ reducers({+ isDiscussing: [+ false,+ {+ discussReport: () => true,+ discussReportSuccess: () => false,+ discussReportFailure: () => false,+ },+ ],+ isCreatingPr: [+ false,+ {+ createPrFromReport: () => true,+ createPrSuccess: () => false,+ createPrFailure: () => false,+ },+ ],+ }),++ listeners(({ actions }) => ({+ discussReport: async ({ report, question }) => {+ try {+ await createReportTask(report, 'research', buildDiscussReportPrompt(report, question), 'Discuss report')+ actions.discussReportSuccess()+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || 'Failed to start discussion')+ actions.discussReportFailure()+ }+ },+ createPrFromReport: async ({ report }) => {+ try {+ await createReportTask(+ report,+ SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP,+ buildCreatePrReportPrompt(report),+ 'Implement report fix'+ )+ actions.createPrSuccess()+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || 'Failed to start PR task')+ actions.createPrFailure()+ }+ },+ })),+])diff --git a/frontend/src/scenes/inbox/logics/inboxBulkActionsLogic.ts b/frontend/src/scenes/inbox/logics/inboxBulkActionsLogic.tsnew file mode 100644index 000000000000..420ebdfbe619--- /dev/null+++ b/frontend/src/scenes/inbox/logics/inboxBulkActionsLogic.ts@@ -0,0 +1,119 @@+import { actions, kea, listeners, path, reducers, selectors } from 'kea'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'++import type { DismissalReasonValue } from '../utils/dismissalReasons'+import type { inboxBulkActionsLogicType } from './inboxBulkActionsLogicType'++/** Tally of a bulk operation that ran one request per selected report. */+interface BulkActionResult {+ successCount: number+ failureCount: number+}++function formatDismissSummary(result: BulkActionResult): string {+ const { successCount, failureCount } = result+ const pluralized = successCount === 1 ? 'report' : 'reports'+ if (failureCount === 0) {+ return `${successCount} ${pluralized} dismissed`+ }+ return `${successCount} ${pluralized} dismissed, ${failureCount} failed`+}++/**+ * Multi-select + bulk dismiss for the inbox report list. Mirrors desktop+ * `inboxReportSelectionStore` (selection state) and `useInboxBulkActions`+ * (bulk suppress via `updateSignalReportState`). Kept deliberately thin: shift /+ * range selection lives in the list component; this logic owns the id set and+ * the dismiss call.+ */+export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([+ path(['scenes', 'inbox', 'logics', 'inboxBulkActionsLogic']),++ actions({+ toggleReportSelection: (reportId: string) => ({ reportId }),+ setSelectedReportIds: (reportIds: string[]) => ({ reportIds }),+ selectAll: (reportIds: string[]) => ({ reportIds }),+ clearSelection: true,+ /** Suppress every selected report with the chosen reason/note, then clear. */+ bulkDismiss: (reason: DismissalReasonValue, note: string) => ({ reason, note }),+ bulkDismissSuccess: true,+ bulkDismissFailure: true,+ }),++ reducers({+ selectedReportIds: [+ [] as string[],+ {+ toggleReportSelection: (state, { reportId }) =>+ state.includes(reportId) ? state.filter((id) => id !== reportId) : [...state, reportId],+ setSelectedReportIds: (_, { reportIds }) => Array.from(new Set(reportIds)),+ selectAll: (_, { reportIds }) => Array.from(new Set(reportIds)),+ clearSelection: () => [],+ },+ ],+ isDismissing: [+ false,+ {+ bulkDismiss: () => true,+ bulkDismissSuccess: () => false,+ bulkDismissFailure: () => false,+ },+ ],+ }),++ selectors({+ selectedCount: [+ (s) => [s.selectedReportIds],+ (selectedReportIds: string[]): number => selectedReportIds.length,+ ],+ hasSelection: [+ (s) => [s.selectedReportIds],+ (selectedReportIds: string[]): boolean => selectedReportIds.length > 0,+ ],+ }),++ listeners(({ actions, values }) => ({+ bulkDismiss: async ({ reason, note }) => {+ const reportIds = values.selectedReportIds+ if (reportIds.length === 0) {+ actions.bulkDismissFailure()+ return+ }+ const trimmedNote = note.trim().slice(0, 4000)+ const results = await Promise.allSettled(+ reportIds.map((id) =>+ api.signalReports.setState(id, {+ state: 'suppressed',+ dismissal_reason: reason,+ ...(trimmedNote ? { dismissal_note: trimmedNote } : {}),+ })+ )+ )+ const successCount = results.filter((r) => r.status === 'fulfilled').length+ const result: BulkActionResult = {+ successCount,+ failureCount: results.length - successCount,+ }++ actions.clearSelection()++ // Total failure: nothing was suppressed, so there's nothing for the list to drop.+ if (result.successCount === 0) {+ lemonToast.error(formatDismissSummary(result))+ actions.bulkDismissFailure()+ return+ }+ // Any success (partial or full) must reload so the suppressed reports leave the list.+ // A partial failure still surfaces as an error toast ("N dismissed, M failed").+ if (result.failureCount > 0) {+ lemonToast.error(formatDismissSummary(result))+ } else {+ lemonToast.success(formatDismissSummary(result))+ }+ actions.bulkDismissSuccess()+ },+ })),+])diff --git a/frontend/src/scenes/inbox/logics/inboxFiltersLogic.ts b/frontend/src/scenes/inbox/logics/inboxFiltersLogic.tsnew file mode 100644index 000000000000..ac84d18655f1--- /dev/null+++ b/frontend/src/scenes/inbox/logics/inboxFiltersLogic.ts@@ -0,0 +1,151 @@+import { actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import { INBOX_SCOPE_FOR_YOU, InboxScope, SignalReportPriority, SignalReportStatus } from '../types'+import type { inboxFiltersLogicType } from './inboxFiltersLogicType'++/** A teammate who can be scoped to / suggested as a reviewer. Matches the `available_reviewers` API row. */+export interface InboxReviewerOption {+ user_uuid: string+ name: string+ email: string+}++/**+ * Status set always sent to the list API: every in-flight pipeline status.+ * Mirrors desktop `INBOX_PIPELINE_STATUS_FILTER`. There is no user-facing status+ * filter (desktop dropped it in filter-store v2); status is a fixed request+ * constant, and tab membership does the rest of the partitioning client-side.+ */+export const INBOX_PIPELINE_STATUS_FILTERS: SignalReportStatus[] = [+ SignalReportStatus.POTENTIAL,+ SignalReportStatus.CANDIDATE,+ SignalReportStatus.IN_PROGRESS,+ SignalReportStatus.READY,+ SignalReportStatus.PENDING_INPUT,+ SignalReportStatus.FAILED,+]++export type InboxSortField = 'priority' | 'created_at' | 'updated_at'+export type InboxSortDirection = 'asc' | 'desc'++/**+ * Build the `ordering` query param. Mirrors desktop `buildSignalReportListOrdering`:+ * 1. Status rank (semantic server-side rank, always applied)+ * 2. Toolbar-selected field (priority, updated_at, created_at)+ * 3. `-updated_at` as a recency tiebreak, so reports tied on status + field+ * surface most-recently-updated first instead of in arbitrary order.+ * (Skipped when the selected field is already `updated_at`.)+ *+ * Reviewer scope is NOT an ordering tiebreak. A `-is_suggested_reviewer` sort+ * floats the current user's own reports to the top of the single loaded page,+ * which starves the "Entire project" scope of genuinely project-wide reports+ * once the list exceeds one page. Scope is applied separately (client-side here),+ * matching desktop fix #2699.+ */+export function buildSignalReportListOrdering(field: InboxSortField, direction: InboxSortDirection): string {+ const fieldKey = direction === 'desc' ? `-${field}` : field+ return field === 'updated_at' ? `status,${fieldKey}` : `status,${fieldKey},-updated_at`+}++/**+ * Persisted inbox filter state. Mirrors desktop's zustand stores:+ * - `inboxReviewerScopeStore` → `scope` (persisted, default "for-you")+ * - `inboxSignalsFilterStore` v2 → `sortField`/`sortDirection` (default priority/asc),+ * `sourceProductFilter`, `priorityFilter` (all persisted). `searchQuery` is NOT+ * persisted on desktop, so it isn't here either.+ *+ * The central `inboxSceneLogic` connects these values, maps them to list-API+ * params (`source_product`, `priority`, `ordering`), and reloads on change.+ */+export const inboxFiltersLogic = kea<inboxFiltersLogicType>([+ path(['scenes', 'inbox', 'logics', 'inboxFiltersLogic']),++ actions({+ setScope: (scope: InboxScope) => ({ scope }),+ setSearchQuery: (searchQuery: string) => ({ searchQuery }),+ setSort: (field: InboxSortField, direction: InboxSortDirection) => ({ field, direction }),+ toggleSourceProduct: (source: string) => ({ source }),+ togglePriority: (priority: SignalReportPriority) => ({ priority }),+ clearFilters: true,+ // Debounced server-side org-member search for the scope (teammate) picker.+ searchAvailableReviewers: (query: string) => ({ query }),+ }),++ loaders({+ // Shared, project-wide reviewer roster used by the scope picker. Filtered server-side via+ // `query` (backend ranks + caps at 100) so the picker isn't limited to the alphabetical first page.+ availableReviewers: [+ [] as InboxReviewerOption[],+ {+ loadAvailableReviewers: async ({ query }: { query?: string } = {}) => {+ // The api wrapper already returns the typed `{ user_uuid, name, email }[]` array.+ return await api.signalReports.availableReviewers(query)+ },+ },+ ],+ }),++ listeners(({ actions }) => ({+ searchAvailableReviewers: async ({ query }, breakpoint) => {+ await breakpoint(300)+ actions.loadAvailableReviewers({ query: query.trim() || undefined })+ },+ })),++ reducers({+ scope: [+ INBOX_SCOPE_FOR_YOU as InboxScope,+ { persist: true },+ {+ setScope: (_, { scope }) => scope,+ },+ ],+ // Not persisted – matches desktop (searchQuery is excluded from `partialize`).+ searchQuery: [+ '',+ {+ setSearchQuery: (_, { searchQuery }) => searchQuery,+ clearFilters: () => '',+ },+ ],+ sortField: [+ 'priority' as InboxSortField,+ { persist: true },+ {+ setSort: (_, { field }) => field,+ },+ ],+ sortDirection: [+ 'asc' as InboxSortDirection,+ { persist: true },+ {+ setSort: (_, { direction }) => direction,+ },+ ],+ sourceProductFilter: [+ [] as string[],+ { persist: true },+ {+ toggleSourceProduct: (state, { source }) =>+ state.includes(source) ? state.filter((s) => s !== source) : [...state, source],+ clearFilters: () => [],+ },+ ],+ priorityFilter: [+ [] as SignalReportPriority[],+ { persist: true },+ {+ togglePriority: (state, { priority }) =>+ state.includes(priority) ? state.filter((p) => p !== priority) : [...state, priority],+ clearFilters: () => [],+ },+ ],+ }),++ afterMount(({ actions }) => {+ actions.loadAvailableReviewers()+ }),+])diff --git a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.tsnew file mode 100644index 000000000000..13e36be28adf--- /dev/null+++ b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts@@ -0,0 +1,321 @@+import { actions, afterMount, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api, { PaginatedResponse } from 'lib/api'+import { SignalNode } from 'scenes/debug/signals/types'+import { userLogic } from 'scenes/userLogic'++import { Task, TaskRunStatus } from 'products/tasks/frontend/types'++import {+ AvailableReviewerOption,+ buildAddReviewerOptions,+ CurrentReviewerUser,+} from '../components/detail/reviewerDisplay'+import {+ EnrichedReviewer,+ SignalReport,+ SignalReportArtefact,+ SignalReportArtefactResponse,+ SignalReportStatus,+ SignalReportTask,+ SignalReportTaskRelationship,+} from '../types'+import type { inboxReportDetailLogicType } from './inboxReportDetailLogicType'++/** Run statuses that count as terminal. Mirrors desktop `isTerminalStatus` / `ReportTasksSection`. */+const TERMINAL_RUN_STATUSES: TaskRunStatus[] = [TaskRunStatus.COMPLETED, TaskRunStatus.FAILED, TaskRunStatus.CANCELLED]++export interface InboxReportDetailLogicProps {+ reportId: string+ /** The selected report, fed in by the shell so task polling can stop once it reaches a terminal status. */+ report?: SignalReport | null+}++/** A linked task plus the relationship and when the link was created. Mirrors desktop `ReportTaskData`. */+export interface ReportTaskEntry {+ task: Task+ relationship: SignalReportTaskRelationship+ startedAt: string+}++// Only these relationships are rendered, implementation-first. Mirrors desktop `useReportTasks`.+const DISPLAYED_RELATIONSHIPS: SignalReportTaskRelationship[] = ['implementation', 'research']++// While the report is still being worked, poll linked tasks every 5s. Mirrors desktop.+const ACTIVE_STATUSES: SignalReportStatus[] = [+ SignalReportStatus.CANDIDATE,+ SignalReportStatus.IN_PROGRESS,+ SignalReportStatus.PENDING_INPUT,+]++const REPORT_TASKS_POLL_INTERVAL_MS = 5000++/** Extract the PR url from a task's latest run output, if present. Mirrors desktop `getTaskPrUrl`. */+export function getTaskPrUrl(task: Task): string | null {+ const prUrl = task.latest_run?.output?.pr_url+ return typeof prUrl === 'string' && prUrl.length > 0 ? prUrl : null+}++/**+ * `explanation` text from the latest judgment artefact of `type`, or null. The priority/actionability+ * judgment artefacts already carry the agent's rationale — surfaced in the detail view without any extra fetch.+ */+function latestJudgmentExplanation(+ artefacts: SignalReportArtefact[] | null,+ type: 'priority_judgment' | 'actionability_judgment'+): string | null {+ const matching = (artefacts ?? []).filter((a) => a.type === type)+ if (matching.length === 0) {+ return null+ }+ const latest = matching.reduce((a, b) => (b.created_at > a.created_at ? b : a))+ const explanation = latest.content?.explanation+ return typeof explanation === 'string' && explanation.trim() ? explanation : null+}++/**+ * Per-selected-report detail logic: artefacts, contributing signals, suggested reviewers, and linked tasks.+ * Keyed by `reportId` so each open report gets its own mounted instance. Does NOT import `inboxSceneLogic`+ * (the report id is passed in as a prop) to avoid a logic cycle.+ */+export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([+ path(['scenes', 'inbox', 'logics', 'inboxReportDetailLogic']),+ props({} as InboxReportDetailLogicProps),+ key((props) => props.reportId),++ actions({+ setReport: (report: SignalReport | null) => ({ report }),+ // Optimistically replace the reviewer list while the PUT is in flight, then reload from the server.+ // Mirrors desktop `useUpdateSuggestedReviewers` optimistic behavior.+ updateReviewers: (artefactId: string, content: Record<string, string>[], optimistic: EnrichedReviewer[]) => ({+ artefactId,+ content,+ optimistic,+ }),+ setOptimisticReviewers: (reviewers: EnrichedReviewer[] | null) => ({ reviewers }),+ // Debounced server-side org-member search for the add-reviewer picker.+ searchAvailableReviewers: (query: string) => ({ query }),+ }),++ loaders(({ props }) => ({+ reportArtefacts: [+ null as SignalReportArtefact[] | null,+ {+ loadReportArtefacts: async () => {+ const response: SignalReportArtefactResponse = await api.signalReports.artefacts(props.reportId)+ return response.results+ },+ },+ ],+ reportSignals: [+ null as SignalNode[] | null,+ {+ loadReportSignals: async () => {+ const response = await api.signalReports.getReportSignals(props.reportId)+ return response.signals+ },+ },+ ],+ reportTasks: [+ null as ReportTaskEntry[] | null,+ {+ loadReportTasks: async () => {+ const response: PaginatedResponse<SignalReportTask> = await api.signalReports.tasks(props.reportId)+ const relevant = response.results.filter((rt) => DISPLAYED_RELATIONSHIPS.includes(rt.relationship))+ const entries = await Promise.all(+ relevant.map(async (rt): Promise<ReportTaskEntry> => {+ const task = await api.tasks.get(rt.task_id)+ return { task, relationship: rt.relationship, startedAt: rt.created_at }+ })+ )+ return entries.sort(+ (a, b) =>+ DISPLAYED_RELATIONSHIPS.indexOf(a.relationship) -+ DISPLAYED_RELATIONSHIPS.indexOf(b.relationship)+ )+ },+ },+ ],+ availableReviewers: [+ null as AvailableReviewerOption[] | null,+ {+ // Org members with a linked GitHub identity who can be added as reviewers.+ // Filtered server-side via `query` (the backend ranks + caps at 100) so the picker+ // isn't limited to the alphabetical first page. Empty query loads the default page.+ loadAvailableReviewers: async ({ query }: { query?: string } = {}) => {+ return await api.signalReports.availableReviewers(query)+ },+ },+ ],+ })),++ reducers({+ report: [+ null as SignalReport | null,+ {+ setReport: (_, { report }) => report,+ },+ ],+ // While a reviewer update is in flight, this overrides the artefact-derived list so the UI+ // reflects the change immediately. Cleared once the reload lands (or the update fails).+ optimisticReviewers: [+ null as EnrichedReviewer[] | null,+ {+ updateReviewers: (_, { optimistic }) => optimistic,+ setOptimisticReviewers: (_, { reviewers }) => reviewers,+ },+ ],+ }),++ selectors({+ // Mirrors the optimistic override lifecycle: an update is in flight exactly while the+ // optimistic list is set (cleared once the reload lands or the update fails).+ isUpdatingReviewers: [(s) => [s.optimisticReviewers], (optimisticReviewers) => optimisticReviewers !== null],+ reportReviewers: [+ (s) => [s.reportArtefacts],+ (reportArtefacts: SignalReportArtefact[] | null): EnrichedReviewer[] | null => {+ if (!reportArtefacts) {+ return null+ }+ const reviewersArtefact = reportArtefacts.find((a) => a.type === 'suggested_reviewers')+ if (!reviewersArtefact) {+ return null+ }+ return reviewersArtefact.content as unknown as EnrichedReviewer[]+ },+ ],+ isReportActive: [+ (s) => [s.report],+ (report: SignalReport | null): boolean => (report ? ACTIVE_STATUSES.includes(report.status) : false),+ ],+ // Rationale behind the priority / actionability judgments, pulled from the already-loaded artefacts.+ priorityExplanation: [+ (s) => [s.reportArtefacts],+ (reportArtefacts: SignalReportArtefact[] | null): string | null =>+ latestJudgmentExplanation(reportArtefacts, 'priority_judgment'),+ ],+ actionabilityExplanation: [+ (s) => [s.reportArtefacts],+ (reportArtefacts: SignalReportArtefact[] | null): string | null =>+ latestJudgmentExplanation(reportArtefacts, 'actionability_judgment'),+ ],+ // The reviewer list to render: optimistic override (if any) wins over the artefact-derived list,+ // then the current user is pinned to the top. Mirrors desktop `displayReviewers`.+ displayReviewers: [+ (s) => [s.reportReviewers, s.optimisticReviewers, userLogic.selectors.user],+ (+ reportReviewers: EnrichedReviewer[] | null,+ optimisticReviewers: EnrichedReviewer[] | null,+ user: { uuid: string } | null+ ): EnrichedReviewer[] | null => {+ const reviewers = optimisticReviewers ?? reportReviewers+ if (!reviewers) {+ return null+ }+ const meUuid = user?.uuid+ if (!meUuid) {+ return reviewers+ }+ const meIndex = reviewers.findIndex((r) => r.user?.uuid === meUuid)+ if (meIndex <= 0) {+ return reviewers+ }+ return [reviewers[meIndex], ...reviewers.filter((_, i) => i !== meIndex)]+ },+ ],+ // Add-reviewer options: org members with GitHub, current user pinned first ("Me"). Mirrors desktop.+ addReviewerOptions: [+ (s) => [s.availableReviewers, userLogic.selectors.user],+ (+ availableReviewers: AvailableReviewerOption[] | null,+ currentUser: { uuid: string; first_name?: string; last_name?: string; email?: string } | null+ ): AvailableReviewerOption[] => {+ const me: CurrentReviewerUser | null = currentUser+ ? {+ uuid: currentUser.uuid,+ first_name: currentUser.first_name,+ last_name: currentUser.last_name,+ email: currentUser.email,+ }+ : null+ return buildAddReviewerOptions(availableReviewers ?? [], me)+ },+ ],+ // True when a re-research is under way: ≥2 research tasks, one currently in-flight while a prior+ // attempt already reached a terminal state. Mirrors desktop `AgentRunDetail`'s `isReResearch`.+ isReResearch: [+ (s) => [s.reportTasks],+ (reportTasks: ReportTaskEntry[] | null): boolean => {+ if (!reportTasks) {+ return false+ }+ const researchTasks = reportTasks.filter((rt) => rt.relationship === 'research')+ if (researchTasks.length < 2) {+ return false+ }+ const hasInFlight = researchTasks.some((rt) => {+ const status = rt.task.latest_run?.status+ return !!status && !TERMINAL_RUN_STATUSES.includes(status)+ })+ const hasPriorTerminal = researchTasks.some((rt) => {+ const status = rt.task.latest_run?.status+ return !!status && TERMINAL_RUN_STATUSES.includes(status)+ })+ return hasInFlight && hasPriorTerminal+ },+ ],+ }),++ listeners(({ actions, values, cache, props }) => ({+ searchAvailableReviewers: async ({ query }, breakpoint) => {+ await breakpoint(300)+ actions.loadAvailableReviewers({ query: query.trim() || undefined })+ },+ // Persist a reviewer add/remove. The optimistic list is already in place (set by the action's+ // reducer); on success reload the artefact so we converge on the server's enriched data, and on+ // failure clear the optimistic override so the UI snaps back. Mirrors desktop `useUpdateSuggestedReviewers`.+ updateReviewers: async ({ artefactId, content }) => {+ try {+ await api.signalReports.updateArtefact(props.reportId, artefactId, content)+ await actions.loadReportArtefacts()+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || 'Failed to update reviewers')+ } finally {+ // Clear the optimistic override; the freshly-loaded artefact is now the source of truth.+ actions.setOptimisticReviewers(null)+ }+ },+ // Poll linked tasks only while the report is active; stop once it reaches a terminal status+ // (or is unloaded). Mirrors desktop `useReportTasks` gating. The keyed disposable replaces+ // any running interval on re-add and is torn down automatically on unmount / tab hide.+ setReport: () => {+ if (values.isReportActive) {+ cache.disposables.add(() => {+ const interval = setInterval(() => actions.loadReportTasks(), REPORT_TASKS_POLL_INTERVAL_MS)+ return () => clearInterval(interval)+ }, 'reportTasksPoll')+ } else {+ cache.disposables.dispose('reportTasksPoll')+ }+ },+ })),++ propsChanged(({ actions, props }, oldProps) => {+ // The shell re-renders the detail with a refreshed `selectedReport`; re-gate polling on the new status.+ if (props.report !== oldProps.report) {+ actions.setReport(props.report ?? null)+ }+ }),++ afterMount(({ actions, props }) => {+ actions.loadReportArtefacts()+ actions.loadReportSignals()+ actions.loadReportTasks()+ actions.loadAvailableReviewers()+ // Seed the report from props so polling is gated on its status from the first tick.+ actions.setReport(props.report ?? null)+ }),+])diff --git a/frontend/src/scenes/inbox/logics/reportListLogic.ts b/frontend/src/scenes/inbox/logics/reportListLogic.tsnew file mode 100644index 000000000000..48a1b42c2eca--- /dev/null+++ b/frontend/src/scenes/inbox/logics/reportListLogic.ts@@ -0,0 +1,220 @@+import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api, { CountedPaginatedResponse } from 'lib/api'+import { userLogic } from 'scenes/userLogic'++import { ACTIONABLE_ACTIONABILITY_VALUES, INBOX_SCOPE_FOR_YOU, InboxFlatListTabKey, SignalReport } from '../types'+import { DismissalReasonValue } from '../utils/dismissalReasons'+import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'+import { buildSignalReportListOrdering, inboxFiltersLogic } from './inboxFiltersLogic'+import type { reportListLogicType } from './reportListLogicType'++const PAGE_SIZE = 50++/** Fixed, tab-defining server filter (e.g. `{ has_implementation_pr: 'true' }`). */+export type ReportListParams = Record<string, string>++export interface ReportListLogicProps {+ tabKey: InboxFlatListTabKey+ /** The tab's fixed server filter. User-driven chrome (search/sort/source/priority/scope) is layered on top. */+ listParams: ReportListParams+}++/**+ * The fixed server filter per flat tab – the single source of truth shared by the tab+ * bodies, the count chips, and the scene. Mirrors the backend filters confirmed in the plan.+ */+export const INBOX_FLAT_TAB_LIST_PARAMS: Record<InboxFlatListTabKey, ReportListParams> = {+ pulls: { has_implementation_pr: 'true' },+ reports: {+ has_implementation_pr: 'false',+ status: 'ready,pending_input',+ actionability: ACTIONABLE_ACTIONABILITY_VALUES.join(','),+ },+ 'not-actionable': { actionability: 'not_actionable' },+}++function teammateUuidFromScope(scope: string): string | undefined {+ return scope.startsWith('teammate:') ? scope.slice('teammate:'.length).trim() || undefined : undefined+}++/**+ * Keyed per-tab report list. Mounted once per flat tab (pulls / reports / not-actionable),+ * each with its own fixed `listParams`, so every tab is its own filtered request with its+ * own accurate `count` and its own pagination. The shared user chrome (search, sort, source,+ * priority, reviewer scope) is connected from `inboxFiltersLogic` and applied on top.+ *+ * `count` loads on mount (cheap `limit=1`) so the tab badge is correct before the contents+ * are fetched. The list itself loads lazily (`ensureLoaded`) only when the tab is rendered.+ */+export const reportListLogic = kea<reportListLogicType>([+ path((tabKey) => ['scenes', 'inbox', 'logics', 'reportListLogic', tabKey]),+ props({} as ReportListLogicProps),+ key((props) => props.tabKey),++ connect(() => ({+ values: [+ inboxFiltersLogic,+ ['scope', 'searchQuery', 'sortField', 'sortDirection', 'sourceProductFilter', 'priorityFilter'],+ userLogic,+ ['user'],+ ],+ actions: [+ inboxFiltersLogic,+ ['setSearchQuery', 'setSort', 'toggleSourceProduct', 'togglePriority', 'setScope', 'clearFilters'],+ ],+ })),++ actions({+ ensureLoaded: true,+ loadMore: true,+ archiveReport: (reportId: string, reason: DismissalReasonValue, note: string) => ({ reportId, reason, note }),+ removeReport: (reportId: string) => ({ reportId }),+ refresh: true,+ }),++ loaders(({ values }) => ({+ // Cheap count-only request (limit=1) – populates the tab badge before contents load.+ count: [+ null as number | null,+ {+ loadCount: async () => {+ const response = await api.signalReports.list({ ...values.listApiParams, limit: 1 })+ return response.count+ },+ },+ ],+ reportsResponse: [+ null as CountedPaginatedResponse<SignalReport> | null,+ {+ loadReports: async () => {+ return await api.signalReports.list({ ...values.listApiParams, offset: 0, limit: PAGE_SIZE })+ },+ loadMoreReports: async () => {+ const current = values.reportsResponse?.results ?? []+ const response = await api.signalReports.list({+ ...values.listApiParams,+ offset: current.length,+ limit: PAGE_SIZE,+ })+ return { ...response, results: [...current, ...response.results] }+ },+ },+ ],+ })),++ reducers({+ reportsResponse: {+ // Optimistic removal on archive – keeps the list snappy; count refreshes in the background.+ removeReport: (state, { reportId }) =>+ state+ ? {+ ...state,+ results: state.results.filter((r) => r.id !== reportId),+ count: Math.max(0, state.count - 1),+ }+ : state,+ },+ count: {+ removeReport: (state) => (state != null ? Math.max(0, state - 1) : state),+ },+ }),++ selectors({+ // The tab's fixed filter merged with the user-driven chrome + reviewer scope (server-side).+ listApiParams: [+ (s) => [+ s.searchQuery,+ s.sortField,+ s.sortDirection,+ s.sourceProductFilter,+ s.priorityFilter,+ s.scope,+ s.user,+ (_, p) => p.listParams,+ ],+ (searchQuery, sortField, sortDirection, sourceProductFilter, priorityFilter, scope, user, listParams) => {+ const suggestedReviewer =+ scope === INBOX_SCOPE_FOR_YOU ? (user?.uuid ?? undefined) : teammateUuidFromScope(scope)+ return {+ ...listParams,+ search: searchQuery.trim() || undefined,+ ordering: buildSignalReportListOrdering(sortField, sortDirection),+ source_product: sourceProductFilter.length > 0 ? sourceProductFilter.join(',') : undefined,+ priority: priorityFilter.length > 0 ? priorityFilter.join(',') : undefined,+ suggested_reviewers: suggestedReviewer,+ }+ },+ ],+ reports: [+ (s) => [s.reportsResponse],+ (reportsResponse: CountedPaginatedResponse<SignalReport> | null): SignalReport[] =>+ reportsResponse?.results ?? [],+ ],+ hasMore: [+ (s) => [s.reportsResponse],+ (reportsResponse: CountedPaginatedResponse<SignalReport> | null): boolean =>+ reportsResponse?.next !== null && reportsResponse?.next !== undefined,+ ],+ isLoaded: [(s) => [s.reportsResponse], (reportsResponse): boolean => reportsResponse !== null],+ }),++ listeners(({ actions, values }) => ({+ ensureLoaded: () => {+ if (values.reportsResponse === null && !values.reportsResponseLoading) {+ actions.loadReports()+ }+ },+ loadMore: () => {+ if (values.hasMore && !values.reportsResponseLoading) {+ actions.loadMoreReports()+ }+ },+ refresh: () => {+ actions.loadCount()+ if (values.isLoaded) {+ actions.loadReports()+ }+ },+ // User-driven filter/scope changes re-fetch the count always, and the contents if this tab is loaded.+ setSearchQuery: async (_, breakpoint) => {+ await breakpoint(300)+ actions.refresh()+ },+ setSort: () => actions.refresh(),+ toggleSourceProduct: () => actions.refresh(),+ togglePriority: () => actions.refresh(),+ setScope: () => actions.refresh(),+ clearFilters: () => actions.refresh(),+ // For-you scope needs the current user's uuid; reload once it resolves.+ [userLogic.actionTypes.loadUserSuccess]: () => {+ if (values.scope === INBOX_SCOPE_FOR_YOU) {+ actions.refresh()+ }+ },+ archiveReport: async ({ reportId, reason, note }) => {+ actions.removeReport(reportId)+ try {+ await api.signalReports.setState(reportId, {+ state: 'suppressed',+ dismissal_reason: reason,+ ...(note ? { dismissal_note: note } : {}),+ })+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || 'Failed to archive report')+ actions.refresh()+ }+ },+ // Bulk archive happens in the singleton; refresh this tab once it lands.+ [inboxBulkActionsLogic.actionTypes.bulkDismissSuccess]: () => actions.refresh(),+ })),++ events(({ actions }) => ({+ afterMount: () => {+ actions.loadCount()+ },+ })),+])diff --git a/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts b/frontend/src/scenes/inbox/logics/scoutFleetLogic.tsnew file mode 100644index 000000000000..c911d5bc0df3--- /dev/null+++ b/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts@@ -0,0 +1,207 @@+import { actions, events, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { urls } from 'scenes/urls'++import { OriginProduct } from 'products/tasks/frontend/types'++import { SignalScoutConfig, SignalScoutConfigUpdate, SignalScoutRunSummary } from '../types'+import {+ computeFleetSummary,+ computeScoutRollups,+ FleetSummary,+ getScoutOrigin,+ ScoutRollup,+ sortConfigsForDisplay,+} from '../utils/scoutRunsWindow'+import type { scoutFleetLogicType } from './scoutFleetLogicType'++// Fleet runs are refetched on a slow cadence so "running now" / recent emissions+// stay live without hammering the capped runs endpoint (desktop: 60s).+const RUNS_REFETCH_INTERVAL_MS = 60_000+const RUNS_PAGE_LIMIT = 100++/**+ * Cloud port of desktop's scouts fleet hooks (`useScoutConfigs`, `useScoutRuns`,+ * `useScoutConfigMutations`, `useScoutChatTask`). Owns:+ * - loaders for scout configs + the recent runs window+ * - optimistic config mutations (enable/disable, live/dry-run, cadence)+ * - the runs-window rollups + fleet summary selectors+ * - "Make a scout" / fleet-overview / recent-signals chat task-kickoffs+ */+export const scoutFleetLogic = kea<scoutFleetLogicType>([+ path(['scenes', 'inbox', 'logics', 'scoutFleetLogic']),++ actions({+ updateScoutConfig: (configId: string, updates: SignalScoutConfigUpdate) => ({ configId, updates }),+ patchScoutConfigLocally: (configId: string, updates: SignalScoutConfigUpdate) => ({ configId, updates }),+ setHideDisabled: (hideDisabled: boolean) => ({ hideDisabled }),+ setExpanded: (expanded: boolean) => ({ expanded }),+ startScoutChatTask: (prompt: string, taskLabel: string, fallbackTitle: string) => ({+ prompt,+ taskLabel,+ fallbackTitle,+ }),+ startScoutChatTaskSuccess: true,+ startScoutChatTaskFailure: true,+ }),++ loaders(() => ({+ scoutConfigs: [+ null as SignalScoutConfig[] | null,+ {+ loadScoutConfigs: async () => {+ return await api.signalScout.configs.list()+ },+ },+ ],+ runsWindow: [+ { runs: [] as SignalScoutRunSummary[], complete: true } as {+ runs: SignalScoutRunSummary[]+ complete: boolean+ },+ {+ loadRunsWindow: async () => {+ const runs = await api.signalScout.runs.list({ limit: RUNS_PAGE_LIMIT })+ // The endpoint caps at 100 rows; if it returned a full page there may be+ // older runs in the window we can't see, so flag the window as truncated.+ return { runs, complete: runs.length < RUNS_PAGE_LIMIT }+ },+ },+ ],+ })),++ reducers({+ // Tracks whether any chat-task kickoff is mid-flight (CTA disabled state).+ chatTaskRunning: [+ false,+ {+ startScoutChatTask: () => true,+ startScoutChatTaskSuccess: () => false,+ startScoutChatTaskFailure: () => false,+ },+ ],+ expanded: [+ // Defaults open: the only consumer is the Scout troop setup modal, which should+ // show the troop list immediately rather than a collapsed one-line pulse.+ true,+ {+ setExpanded: (_, { expanded }) => expanded,+ },+ ],+ hideDisabled: [+ false,+ {+ setHideDisabled: (_, { hideDisabled }) => hideDisabled,+ },+ ],+ scoutConfigs: [+ null as SignalScoutConfig[] | null,+ {+ // Optimistic patch; the listener reconciles against the server response.+ patchScoutConfigLocally: (state, { configId, updates }) =>+ state?.map((config) => (config.id === configId ? { ...config, ...updates } : config)) ?? state,+ },+ ],+ }),++ selectors({+ rollups: [+ (s) => [s.runsWindow],+ (runsWindow): Map<string, ScoutRollup> => computeScoutRollups(runsWindow.runs),+ ],+ fleetSummary: [+ (s) => [s.scoutConfigs, s.rollups],+ (scoutConfigs, rollups): FleetSummary | null =>+ scoutConfigs ? computeFleetSummary(scoutConfigs, rollups) : null,+ ],+ enabledCount: [+ (s) => [s.scoutConfigs],+ (scoutConfigs): number => scoutConfigs?.filter((config) => config.enabled).length ?? 0,+ ],+ lastRunAt: [+ (s) => [s.scoutConfigs],+ (scoutConfigs): string | null => {+ let latest: string | null = null+ for (const config of scoutConfigs ?? []) {+ if (config.last_run_at && (!latest || config.last_run_at > latest)) {+ latest = config.last_run_at+ }+ }+ return latest+ },+ ],+ visibleConfigs: [+ (s) => [s.scoutConfigs, s.hideDisabled],+ (scoutConfigs, hideDisabled): SignalScoutConfig[] => {+ const sorted = sortConfigsForDisplay(scoutConfigs ?? [])+ return hideDisabled ? sorted.filter((config) => config.enabled) : sorted+ },+ ],+ runsWindowComplete: [(s) => [s.runsWindow], (runsWindow): boolean => runsWindow.complete],+ customScoutCount: [+ (s) => [s.scoutConfigs],+ (scoutConfigs): number =>+ scoutConfigs?.filter((config) => getScoutOrigin(config.skill_name) === 'custom').length ?? 0,+ ],+ }),++ listeners(({ actions, values }) => ({+ updateScoutConfig: async ({ configId, updates }) => {+ const previousConfig = values.scoutConfigs?.find((config) => config.id === configId)+ // Optimistic update so the toggle/select feels instant.+ actions.patchScoutConfigLocally(configId, updates)+ try {+ const updated = await api.signalScout.configs.update(configId, updates)+ // Reconcile this one row against the server (preserves concurrent edits to others).+ actions.patchScoutConfigLocally(configId, updated)+ } catch (error: any) {+ if (previousConfig) {+ actions.patchScoutConfigLocally(configId, previousConfig)+ }+ lemonToast.error(error?.detail || error?.message || 'Failed to update scout config')+ }+ },+ startScoutChatTask: async ({ prompt, fallbackTitle, taskLabel }) => {+ // Task-kickoff, mirroring inboxTaskKickoffLogic: create an auto-mode cloud+ // task from a templated prompt, then navigate to it. Not a live chat.+ try {+ let repository: string | undefined+ try {+ const { repositories } = await api.tasks.repositories()+ repository = repositories[0]+ } catch {+ repository = undefined+ }+ const task = await api.tasks.create({+ title: fallbackTitle,+ description: prompt,+ origin_product: OriginProduct.SIGNAL_REPORT,+ repository,+ })+ actions.startScoutChatTaskSuccess()+ router.actions.push(urls.taskDetail(task.id))+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || `Failed to start ${taskLabel}`)+ actions.startScoutChatTaskFailure()+ }+ },+ })),++ events(({ actions, cache }) => ({+ afterMount: () => {+ actions.loadScoutConfigs()+ actions.loadRunsWindow()+ // Slow poll keeps "running now" + recent emissions fresh. The keyed disposable+ // is torn down automatically on unmount / tab hide.+ cache.disposables.add(() => {+ const interval = setInterval(() => actions.loadRunsWindow(), RUNS_REFETCH_INTERVAL_MS)+ return () => clearInterval(interval)+ }, 'runsPoll')+ },+ })),+])diff --git a/frontend/src/scenes/inbox/logics/signalTeamConfigLogic.ts b/frontend/src/scenes/inbox/logics/signalTeamConfigLogic.tsnew file mode 100644index 000000000000..ba4af14d5d0e--- /dev/null+++ b/frontend/src/scenes/inbox/logics/signalTeamConfigLogic.ts@@ -0,0 +1,57 @@+import { actions, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'++import type { SignalReportPriority, SignalTeamConfig } from '../types'+import type { signalTeamConfigLogicType } from './signalTeamConfigLogicType'++/**+ * Team-level Self-driving config (singleton per team). Wraps the+ * `signals/team_config` endpoint via `api.signalTeamConfig`. The field surfaced+ * here is the team-wide default PR auto-start threshold, which seeds every+ * user's effective threshold until they set a personal override+ * (`userAutonomyLogic`). The backend field is non-nullable (P0–P4), so unlike+ * the per-user override there is no "Never" option here.+ */+export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([+ path(['scenes', 'inbox', 'logics', 'signalTeamConfigLogic']),+ actions({+ setDefaultAutostartPriority: (priority: SignalReportPriority) => ({ priority }),+ }),+ loaders({+ teamConfig: [+ null as SignalTeamConfig | null,+ {+ loadTeamConfig: async () => {+ return await api.signalTeamConfig.get()+ },+ },+ ],+ }),+ reducers({+ // Optimistically reflect the chosen priority so the select doesn't flicker+ // back to the stale value while the request is in flight.+ teamConfig: {+ setDefaultAutostartPriority: (state, { priority }) => ({+ ...(state ?? { default_autostart_priority: null }),+ default_autostart_priority: priority,+ }),+ },+ }),+ listeners(({ actions }) => ({+ setDefaultAutostartPriority: async ({ priority }) => {+ try {+ await api.signalTeamConfig.update({ default_autostart_priority: priority })+ } catch (error: any) {+ lemonToast.error(+ error?.detail ?? error?.message ?? 'Failed to update team default auto-start threshold'+ )+ } finally {+ actions.loadTeamConfig()+ }+ },+ })),+])diff --git a/frontend/src/scenes/inbox/logics/userAutonomyLogic.ts b/frontend/src/scenes/inbox/logics/userAutonomyLogic.tsnew file mode 100644index 000000000000..d3b0bcfaee0a--- /dev/null+++ b/frontend/src/scenes/inbox/logics/userAutonomyLogic.ts@@ -0,0 +1,90 @@+import { actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'++import type { SignalReportPriority, SignalUserAutonomyConfig } from '../types'+import type { userAutonomyLogicType } from './userAutonomyLogicType'++/**+ * Per-user Self-driving autonomy override. Wraps the `users/@me/signal_autonomy`+ * endpoint via `api.signalUserAutonomy`. The only field surfaced here is the PR+ * auto-start priority threshold; `null` means "never auto-start" (review first).+ */+export const userAutonomyLogic = kea<userAutonomyLogicType>([+ path(['scenes', 'inbox', 'logics', 'userAutonomyLogic']),+ actions({+ setAutostartPriority: (priority: SignalReportPriority | null) => ({ priority }),+ // Slack notification preferences (suggested-reviewer pings for new inbox items).+ // integration + channel together enable notifications; either null disables them.+ updateSlackNotifications: (updates: {+ integrationId?: number | null+ channel?: string | null+ minPriority?: SignalReportPriority | null+ }) => ({ updates }),+ }),+ loaders({+ autonomyConfig: [+ null as SignalUserAutonomyConfig | null,+ {+ loadAutonomyConfig: async () => {+ return await api.signalUserAutonomy.get()+ },+ },+ ],+ }),+ reducers({+ // Optimistically reflect the chosen priority so the select doesn't flicker+ // back to the stale value while the request is in flight.+ autonomyConfig: {+ setAutostartPriority: (state, { priority }) => ({+ ...(state ?? { autostart_priority: null }),+ autostart_priority: priority,+ }),+ updateSlackNotifications: (state, { updates }) => ({+ ...(state ?? { autostart_priority: null }),+ ...('integrationId' in updates+ ? { slack_notification_integration_id: updates.integrationId ?? null }+ : {}),+ ...('channel' in updates ? { slack_notification_channel: updates.channel ?? null } : {}),+ ...('minPriority' in updates ? { slack_notification_min_priority: updates.minPriority ?? null } : {}),+ }),+ },+ }),+ listeners(({ actions }) => ({+ setAutostartPriority: async ({ priority }) => {+ try {+ await api.signalUserAutonomy.update({ autostart_priority: priority })+ } catch (error: any) {+ lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update auto-start threshold')+ } finally {+ actions.loadAutonomyConfig()+ }+ },+ updateSlackNotifications: async ({ updates }) => {+ // Send only the keys the caller passed so unrelated fields (e.g. autostart_priority) aren't wiped.+ const body: Partial<SignalUserAutonomyConfig> = {}+ if ('integrationId' in updates) {+ body.slack_notification_integration_id = updates.integrationId ?? null+ }+ if ('channel' in updates) {+ body.slack_notification_channel = updates.channel ?? null+ }+ if ('minPriority' in updates) {+ body.slack_notification_min_priority = updates.minPriority ?? null+ }+ try {+ await api.signalUserAutonomy.update(body)+ } catch (error: any) {+ lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update Slack notification setting')+ } finally {+ actions.loadAutonomyConfig()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadAutonomyConfig()+ }),+])diff --git a/frontend/src/scenes/inbox/signalSourcesLogic.ts b/frontend/src/scenes/inbox/signalSourcesLogic.tsindex f796bb7643c5..2f70af7245fc 100644--- a/frontend/src/scenes/inbox/signalSourcesLogic.ts+++ b/frontend/src/scenes/inbox/signalSourcesLogic.ts@@ -138,6 +138,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([toggleErrorTracking: true,toggleErrorTrackingComplete: true,toggleHealthChecks: true,+ toggleConversations: true,saveSessionAnalysisFilters: (filters: RecordingUniversalFilters) => ({ filters }),clearSessionAnalysisFilters: true,}),@@ -191,6 +192,8 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([},toggleHealthChecks: (state: SignalSourceConfig[] | null) =>toggleSourceConfigState(state, SignalSourceProduct.HEALTH_CHECKS, SignalSourceType.HEALTH_ISSUE),+ toggleConversations: (state: SignalSourceConfig[] | null) =>+ toggleSourceConfigState(state, SignalSourceProduct.CONVERSATIONS, SignalSourceType.TICKET),},togglingSourceKeys: [new Set<string>(),@@ -263,11 +266,24 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([c.source_product === SignalSourceProduct.PGANALYZE && c.source_type === SignalSourceType.ISSUE) ?? null,],+ conversationsConfig: [+ (s) => [s.sourceConfigs],+ (sourceConfigs: SignalSourceConfig[] | null): SignalSourceConfig | null =>+ sourceConfigs?.find(+ (c) =>+ c.source_product === SignalSourceProduct.CONVERSATIONS &&+ c.source_type === SignalSourceType.TICKET+ ) ?? null,+ ],isSessionAnalysisToggling: [(s) => [s.togglingSourceKeys],(keys: Set<string>): boolean =>keys.has(`${SignalSourceProduct.SESSION_REPLAY}_${SignalSourceType.SESSION_ANALYSIS_CLUSTER}`),],+ isConversationsToggling: [+ (s) => [s.togglingSourceKeys],+ (keys: Set<string>): boolean => keys.has(`${SignalSourceProduct.CONVERSATIONS}_${SignalSourceType.TICKET}`),+ ],isGithubIssuesToggling: [(s) => [s.togglingSourceKeys],(keys: Set<string>): boolean => keys.has(`${SignalSourceProduct.GITHUB}_${SignalSourceType.ISSUE}`),@@ -474,6 +490,16 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([enabled: desiredEnabled,})},+ toggleConversations: () => {+ const config = values.conversationsConfig+ // Send the flipped target state. A missing config row means "off", so first toggle enables.+ const desiredEnabled = !(config?.enabled ?? false)+ actions.toggleSignalSource({+ sourceProduct: SignalSourceProduct.CONVERSATIONS,+ sourceType: SignalSourceType.TICKET,+ enabled: desiredEnabled,+ })+ },toggleDataWarehouseSource: ({ dwSource }) => {const { sourceProduct, sourceType } = DATA_WAREHOUSE_SOURCE_CONFIG[dwSource]const config = getDataWarehouseSourceConfig(values, dwSource)diff --git a/frontend/src/scenes/inbox/types.ts b/frontend/src/scenes/inbox/types.tsindex dd89ad42f5eb..bf0f699f0731 100644--- a/frontend/src/scenes/inbox/types.ts+++ b/frontend/src/scenes/inbox/types.ts@@ -10,6 +10,18 @@ import {export type { EnrichedReviewer, RelevantCommit }export { SignalSourceProduct, SignalSourceType }+/** P0 (highest) – P4 (lowest). Mirrors desktop `SignalReportPriority`. */+export type SignalReportPriority = 'P0' | 'P1' | 'P2' | 'P3' | 'P4'++/** Actionability judgment outcome. Mirrors desktop `SignalReportActionability`. */+export type SignalReportActionability = 'immediately_actionable' | 'requires_human_input' | 'not_actionable'++/** Actionability values that represent a report worth acting on — drives the Reports tab filter and the Create PR gate. */+export const ACTIONABLE_ACTIONABILITY_VALUES: SignalReportActionability[] = [+ 'immediately_actionable',+ 'requires_human_input',+]+export interface SignalReport {id: stringtitle: string | null@@ -22,6 +34,18 @@ export interface SignalReport {updated_at: stringartefact_count: numberis_suggested_reviewer: boolean+ /** Count of signals at the time the latest research run kicked off. */+ signals_at_run?: number+ /** P0–P4 from the priority judgment when the report is researched. */+ priority?: SignalReportPriority | null+ /** Actionability choice from the actionability judgment artefact. */+ actionability?: SignalReportActionability | null+ /** Whether the issue appears already fixed, from the actionability judgment artefact. */+ already_addressed?: boolean | null+ /** Distinct source products contributing signals to this report. */+ source_products?: string[]+ /** PR URL from the latest implementation task run, if available. */+ implementation_pr_url?: string | null}export enum SignalReportStatus {@@ -32,6 +56,9 @@ export enum SignalReportStatus {READY = 'ready',RESOLVED = 'resolved',FAILED = 'failed',+ // Out-of-inbox terminal states (backend: SignalReport.Status). Excluded from every tab.+ DELETED = 'deleted',+ SUPPRESSED = 'suppressed',}export interface SignalReportArtefact {@@ -69,3 +96,161 @@ export enum SignalSourceConfigStatus {COMPLETED = 'completed',FAILED = 'failed',}++// ── Inbox 2.0 IA: tabs + scope ──────────────────────────────────────────────++export type InboxTabKey = 'pulls' | 'reports' | 'not-actionable' | 'runs' | 'config'++export const INBOX_TAB_KEYS: InboxTabKey[] = ['pulls', 'reports', 'not-actionable', 'runs', 'config']++export const INBOX_TAB_LABEL: Record<InboxTabKey, string> = {+ pulls: 'Pull requests',+ reports: 'Reports',+ 'not-actionable': 'Not actionable',+ runs: 'Runs',+ config: 'Configuration',+}++/**+ * The Configuration tab holds the agent-setup widgets. It only appears when the scene is too+ * narrow for the right-hand setup rail (see `AgentSetupColumn`); on wide viewports the rail+ * replaces it. Kept a real routing key so deep links and narrow-mode navigation work.+ */+export const INBOX_CONFIG_TAB_KEY: InboxTabKey = 'config'++/** Tabs that show a report-count chip. */+export const INBOX_REPORT_TAB_KEYS: InboxTabKey[] = ['pulls', 'reports', 'not-actionable', 'runs']++/**+ * Tabs only visible to staff users (internal). Non-staff see Pull requests + Reports.+ * Not-actionable reports and the project-wide Runs debug view are internal.+ */+export const INBOX_STAFF_ONLY_TAB_KEYS: InboxTabKey[] = ['not-actionable', 'runs']++/** The three flat report-list tabs that share the keyed reportListLogic + InboxReportList primitive. */+export const INBOX_FLAT_LIST_TAB_KEYS = ['pulls', 'reports', 'not-actionable'] as const+export type InboxFlatListTabKey = (typeof INBOX_FLAT_LIST_TAB_KEYS)[number]++export interface InboxTabCounts {+ pulls: number+ reports: number+ 'not-actionable': number+ runs: number+}++export const EMPTY_TAB_COUNTS: InboxTabCounts = { pulls: 0, reports: 0, 'not-actionable': 0, runs: 0 }++/** `for-you` (suggested-reviewer reports), `entire-project` (all), or `teammate:<uuid>`. */+export type InboxScope = 'for-you' | 'entire-project' | `teammate:${string}`++export const INBOX_SCOPE_FOR_YOU: InboxScope = 'for-you'+export const INBOX_SCOPE_ENTIRE_PROJECT: InboxScope = 'entire-project'++// ── SignalReport ↔ Task linkage ─────────────────────────────────────────────++export const SIGNAL_REPORT_TASK_RELATIONSHIPS = ['repo_selection', 'research', 'implementation'] as const++export type SignalReportTaskRelationship = (typeof SIGNAL_REPORT_TASK_RELATIONSHIPS)[number]++export const SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP: SignalReportTaskRelationship = 'implementation'++export interface SignalReportTask {+ id: string+ relationship: SignalReportTaskRelationship+ task_id: string+ created_at: string+}++// ── 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+ created_at?: string+ updated_at?: string+}++// ── Team-level autonomy config (backend SignalTeamConfigViewSet; singleton per team) ─++export interface SignalTeamConfig {+ id?: string+ /** Team-wide default PR auto-start threshold. null = never auto-start by default. */+ default_autostart_priority: SignalReportPriority | null+ /** Default Slack channel for this team's inbox notifications. */+ default_slack_notification_channel?: string | null+ /** Per-repo base-branch overrides for auto-started PRs, keyed by 'org/repo'. */+ autostart_base_branches?: Record<string, string>+ created_at?: string+ updated_at?: string+}++// ── Scouts (backend SignalScoutConfigViewSet / SignalScoutRunViewSet) ─────────++/** Per-(team, skill) scout config. One row per `signals-scout-*` skill. */+export interface SignalScoutConfig {+ id: string+ /** The `signals-scout-*` skill this config controls. Fixed at creation. */+ skill_name: string+ /** Whether this scout runs on its schedule. */+ enabled: boolean+ /** Whether the scout writes findings to the inbox. false = dry-run. */+ emit: boolean+ /** Minutes between runs (10–43200). */+ run_interval_minutes: number+ /** When the coordinator last dispatched this scout; null if never. */+ last_run_at: string | null+ created_at: string+}++/** Editable subset of a scout config (PATCH `signals/scout/configs/{id}`). */+export interface SignalScoutConfigUpdate {+ enabled?: boolean+ emit?: boolean+ run_interval_minutes?: number+}++/** Status from the linked TaskRun behind a scout run. */+export type SignalScoutRunStatus = 'not_started' | 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'++/** Lightweight projection of a scout run row (newest-first list response). */+export interface SignalScoutRunSummary {+ run_id: string+ skill_name: string+ skill_version: number+ status: SignalScoutRunStatus+ started_at: string+ completed_at: string | null+ task_id?: string | null+ task_run_id?: string | null+ /** Relative deep-link to cloud's Tasks UI, e.g. `/project/{id}/tasks/{task}?runId={run}`. */+ task_url?: string | null+ summary: string+ emitted_count: number+ emitted_finding_ids: string[]+}++/** One finding a scout run emitted to the inbox. */+export interface SignalScoutEmission {+ id: string+ run_id: string+ finding_id: string+ description: string+ weight: number+ confidence: number+ severity: SignalReportPriority | null+ source_id: string+ emitted_at: string+}++// ── Report state transitions (backend `state` action: dismiss / snooze) ──────++export interface SignalReportStateRequest {+ state: 'suppressed' | 'potential'+ dismissal_reason?: string+ dismissal_note?: string+ /** Only honored for state === 'potential' (snooze): re-promote after N more signals. */+ snooze_for?: number+}diff --git a/frontend/src/scenes/inbox/utils/dismissalReasons.ts b/frontend/src/scenes/inbox/utils/dismissalReasons.tsnew file mode 100644index 000000000000..81bfabaf1d6f--- /dev/null+++ b/frontend/src/scenes/inbox/utils/dismissalReasons.ts@@ -0,0 +1,38 @@+// Port of desktop `packages/shared/src/dismissal-reasons.ts`. Canonical dismiss /+// suppress reasons shown in the inbox. Values are persisted on dismissal artefacts+// by the backend `state` action – add or reorder options here only, and keep the+// values in sync with desktop.++export const DISMISSAL_REASON_OPTIONS = [+ {+ value: 'already_fixed',+ label: 'Already fixed',+ snoozesInsteadOfDismiss: true,+ },+ {+ value: 'report_unclear',+ label: 'Report is unclear to me',+ },+ {+ value: 'analysis_wrong',+ label: "Agent's analysis is wrong",+ },+ {+ value: 'wontfix_intentional',+ label: "Won't fix - intentional behavior",+ },+ {+ value: 'wontfix_irrelevant',+ label: "Won't fix - issue is real but insignificant",+ },+ { value: 'other', label: 'Something else…' },+] as const++/** Persisted dismissal / suppress reason (values match {@link DISMISSAL_REASON_OPTIONS}). */+export type DismissalReasonValue = (typeof DISMISSAL_REASON_OPTIONS)[number]['value']++/** Whether the given reason snoozes the report (temporarily) instead of permanently dismissing it. */+export function isDismissalReasonSnooze(value: DismissalReasonValue): boolean {+ const option = DISMISSAL_REASON_OPTIONS.find((o) => o.value === value)+ return option != null && 'snoozesInsteadOfDismiss' in option && option.snoozesInsteadOfDismiss === true+}diff --git a/frontend/src/scenes/inbox/utils/reportPresentation.ts b/frontend/src/scenes/inbox/utils/reportPresentation.tsnew file mode 100644index 000000000000..7bd6f9591fd8--- /dev/null+++ b/frontend/src/scenes/inbox/utils/reportPresentation.ts@@ -0,0 +1,113 @@+// Pure presentation helpers ported from desktop `@posthog/core/inbox/reportPresentation`.+// Shared across the Inbox cards/detail so the conventional-commit + headline parsing+// lives in exactly one place.++const MAX_HEADLINE_LENGTH = 140+const SENTENCE_END = /([.!?])[*_`]*(?=\s|$)/+const EDGE_EMPHASIS = /^[*_`\s]+|[*_`\s]+$/g+const CONVENTIONAL_COMMIT_TITLE = /^(\w+)(?:\(([^)]*)\))?!?:\s*(.+)$/++/** Compact single-sentence headline derived from a report summary, for list rendering. */+export function deriveHeadline(summary: string | null | undefined): string | null {+ if (typeof summary !== 'string') {+ return null+ }+ const trimmed = summary.trim()+ if (!trimmed) {+ return null+ }+ const firstLine = trimmed.split(/\r?\n/, 1)[0] ?? ''+ let headline = firstLine+ const sentenceMatch = SENTENCE_END.exec(firstLine)+ if (sentenceMatch) {+ headline = firstLine.slice(0, sentenceMatch.index + sentenceMatch[1].length)+ }+ headline = headline.replace(EDGE_EMPHASIS, '').trim()+ if (!headline) {+ return null+ }+ if (headline.length > MAX_HEADLINE_LENGTH) {+ headline = `${headline.slice(0, MAX_HEADLINE_LENGTH).trimEnd()}…`+ }+ return headline+}++export interface ParsedConventionalCommitTitle {+ type: string+ scope: string | null+ description: string+}++export function parseConventionalCommitTitle(title: string | null | undefined): ParsedConventionalCommitTitle | null {+ if (typeof title !== 'string') {+ return null+ }+ const trimmed = title.trim()+ if (!trimmed) {+ return null+ }+ const match = CONVENTIONAL_COMMIT_TITLE.exec(trimmed)+ if (!match) {+ return null+ }+ const description = match[3].trim()+ if (!description) {+ return null+ }+ return { type: match[1].toLowerCase(), scope: match[2]?.trim() || null, description }+}++export function displayConventionalCommitTitle(title: string | null | undefined, fallback: string): string {+ const parsed = parseConventionalCommitTitle(title)+ if (parsed) {+ return parsed.description+ }+ const trimmed = title?.trim()+ return trimmed ? trimmed : fallback+}++/**+ * Return the URL only if it's a safe `http(s)` link, otherwise `null`. Guards external `href`s+ * against `javascript:` / `data:` and other script-bearing schemes – `implementation_pr_url`+ * originates from an agent's raw task-run output and is not scheme-validated server-side.+ */+export function safeHttpUrl(url: string | null | undefined): string | null {+ if (!url) {+ return null+ }+ try {+ const { protocol } = new URL(url)+ return protocol === 'http:' || protocol === 'https:' ? url : null+ } catch {+ return null+ }+}++/** Canonical GitHub PR URL path matcher: `/<owner>/<repo>/pull/<number>`. */+const PR_URL_PATH = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:$|[/?#])/++export interface ParsedPrUrlParts {+ owner: string+ repo: string+ number: string+ repoSlug: string+}++/** Parse a canonical GitHub PR URL into its owner / repo / number / repoSlug parts. */+export function parsePrUrlParts(prUrl: string): ParsedPrUrlParts | null {+ try {+ const match = new URL(prUrl).pathname.match(PR_URL_PATH)+ if (!match) {+ return null+ }+ const [, owner, repo, number] = match+ return { owner, repo, number, repoSlug: `${owner}/${repo}` }+ } catch {+ return null+ }+}++/** Parse a GitHub PR URL into its repo slug, e.g. `posthog/posthog`. */+export function parsePrRepoSlug(prUrl: string): string | null {+ return parsePrUrlParts(prUrl)?.repoSlug ?? null+}diff --git a/frontend/src/scenes/inbox/utils/scoutRunsWindow.ts b/frontend/src/scenes/inbox/utils/scoutRunsWindow.tsnew file mode 100644index 000000000000..11394e9c6cad--- /dev/null+++ b/frontend/src/scenes/inbox/utils/scoutRunsWindow.ts@@ -0,0 +1,409 @@+// Ported from PostHog Code desktop `packages/core/src/scouts/scoutRunsWindow.ts`+// and `scoutPresentation.ts`. Pure metrics + display helpers over scout runs and+// configs; no I/O. The runs the cloud API returns are already the newest-first,+// 100-row-capped window the desktop assembled by hand, so the cursor-pagination+// loop is dropped here – but the same window framing and labels are preserved.++import { humanFriendlyDuration } from 'lib/utils/durations'+import { pluralize } from 'lib/utils/strings'++import { SignalScoutConfig, SignalScoutRunStatus, SignalScoutRunSummary } from '../types'++/**+ * The window every scout stat describes. The cloud runs endpoint caps each list+ * response at 100 rows newest-first; we frame all numbers as "the recent window+ * we can see", matching desktop's fixed-window framing.+ */+export const SCOUT_RUNS_WINDOW_HOURS = 72++/** Human-friendly span the window covers, e.g. "3 days". */+export const SCOUT_RUNS_WINDOW_SPAN = ((): string => {+ if (SCOUT_RUNS_WINDOW_HOURS % 24 !== 0) {+ return `${SCOUT_RUNS_WINDOW_HOURS}h`+ }+ const days = SCOUT_RUNS_WINDOW_HOURS / 24+ return `${days} day${days === 1 ? '' : 's'}`+})()++/** Label for stats derived from a window, e.g. "last 3 days". */+export function scoutRunsWindowLabel(complete: boolean): string {+ const base = `last ${SCOUT_RUNS_WINDOW_SPAN}`+ return complete ? base : `${base} · truncated`+}++// ── Origin classification ────────────────────────────────────────────────────++/**+ * Canonical scouts shipped in the PostHog repo (products/signals/skills). The+ * configs endpoint does not yet distinguish canonical from hand-authored skills,+ * so classify by this known-name list (matches desktop `CANONICAL_SCOUT_SKILLS`).+ */+export const CANONICAL_SCOUT_SKILLS = new Set<string>([+ 'signals-scout-general',+ 'signals-scout-anomaly-detection',+ 'signals-scout-ai-observability',+ 'signals-scout-csp-violations',+ 'signals-scout-data-pipelines',+ 'signals-scout-error-tracking',+ 'signals-scout-experiments',+ 'signals-scout-feature-flags',+ 'signals-scout-health-checks',+ 'signals-scout-logs',+ 'signals-scout-observability-gaps',+ 'signals-scout-revenue-analytics',+ 'signals-scout-session-replay',+ 'signals-scout-surveys',+ 'signals-scout-web-analytics',+])++export type ScoutOrigin = 'canonical' | 'custom'++export function getScoutOrigin(skillName: string): ScoutOrigin {+ return CANONICAL_SCOUT_SKILLS.has(skillName) ? 'canonical' : 'custom'+}++/** "signals-scout-error-tracking" → "Error tracking" */+export function prettifyScoutSkillName(skillName: string): string {+ const cleaned = skillName+ .replace(/^signals-scout-/, '')+ .replace(/[-_]/g, ' ')+ .trim()+ if (!cleaned) {+ return skillName+ }+ return cleaned.charAt(0).toUpperCase() + cleaned.slice(1)+}++// ── Run status / outcome ─────────────────────────────────────────────────────++export type ScoutRunStatus = 'completed' | 'failed' | 'running' | 'queued' | 'unknown'++export function normalizeRunStatus(status: SignalScoutRunStatus): ScoutRunStatus {+ if (status === 'completed') {+ return 'completed'+ }+ if (status === 'failed' || status === 'cancelled') {+ return 'failed'+ }+ if (status === 'in_progress') {+ return 'running'+ }+ if (status === 'queued' || status === 'not_started') {+ return 'queued'+ }+ return 'unknown'+}++export function runDurationSeconds(run: SignalScoutRunSummary, now: Date): number | null {+ if (!run.started_at) {+ return null+ }+ const started = new Date(run.started_at).getTime()+ if (Number.isNaN(started)) {+ return null+ }+ const ended = run.completed_at ? new Date(run.completed_at).getTime() : now.getTime()+ if (Number.isNaN(ended) || ended < started) {+ return null+ }+ return (ended - started) / 1000+}++/** Format a run's duration for display, e.g. "1m 30s". Empty string when unknown. */+export function formatRunDuration(seconds: number | null): string {+ return humanFriendlyDuration(seconds, { maxUnits: 2 })+}++/**+ * Scout runs are hard-killed at the ~31-minute Temporal activity deadline and+ * surface as bare "failed" with no error field. Until the serializer carries a+ * failure kind, infer a timeout from the run length.+ */+const TIMEOUT_THRESHOLD_SECONDS = 29 * 60++export type ScoutRunFailureKind = 'timed_out' | 'error'++export function deriveRunFailureKind(run: SignalScoutRunSummary, now: Date): ScoutRunFailureKind | null {+ if (normalizeRunStatus(run.status) !== 'failed') {+ return null+ }+ const duration = runDurationSeconds(run, now)+ if (duration !== null && duration >= TIMEOUT_THRESHOLD_SECONDS) {+ return 'timed_out'+ }+ return 'error'+}++/**+ * A SIGKILL mid-run can strand a TaskRun in IN_PROGRESS with no self-heal. Past+ * the run deadline we can be sure the run is not actually still working.+ */+const STUCK_THRESHOLD_SECONDS = 35 * 60++export function isRunStuck(run: SignalScoutRunSummary, now: Date): boolean {+ if (normalizeRunStatus(run.status) !== 'running') {+ return false+ }+ const duration = runDurationSeconds(run, now)+ return duration !== null && duration >= STUCK_THRESHOLD_SECONDS+}++export type ScoutRunOutcome = 'emitted' | 'quiet' | 'error' | 'timed_out' | 'running' | 'stuck' | 'queued' | 'unknown'++export function deriveRunOutcome(run: SignalScoutRunSummary, now: Date): ScoutRunOutcome {+ const status = normalizeRunStatus(run.status)+ if (status === 'completed') {+ return (run.emitted_count ?? 0) > 0 ? 'emitted' : 'quiet'+ }+ if (status === 'failed') {+ return deriveRunFailureKind(run, now) === 'timed_out' ? 'timed_out' : 'error'+ }+ if (status === 'running') {+ return isRunStuck(run, now) ? 'stuck' : 'running'+ }+ if (status === 'queued') {+ return 'queued'+ }+ return 'unknown'+}++export function scoutRunOutcomeLabel(run: SignalScoutRunSummary, now: Date): string {+ switch (deriveRunOutcome(run, now)) {+ case 'emitted': {+ const count = run.emitted_count ?? 0+ return `${pluralize(count, 'signal')} emitted`+ }+ case 'quiet':+ return '0 signals emitted'+ case 'error':+ return 'failed'+ case 'timed_out':+ return 'timed out'+ case 'running':+ return 'running now'+ case 'stuck':+ return 'running past the deadline – may be stuck'+ case 'queued':+ return 'queued'+ case 'unknown':+ return run.status+ }+}++// ── Per-scout rollups ────────────────────────────────────────────────────────++export interface ScoutRollup {+ runCount: number+ completedCount: number+ failedCount: number+ emittedCount: number+ latestRun: SignalScoutRunSummary | null+ runningRun: SignalScoutRunSummary | null+ /** This scout's runs in the window, oldest first (timeline order). */+ runs: SignalScoutRunSummary[]+}++function emptyRollup(): ScoutRollup {+ return {+ runCount: 0,+ completedCount: 0,+ failedCount: 0,+ emittedCount: 0,+ latestRun: null,+ runningRun: null,+ runs: [],+ }+}++/**+ * Client-side rollup over the recent fleet runs, keyed by skill_name. The runs+ * endpoint has no per-scout filter or aggregate stats yet and caps at 100 rows,+ * so these numbers describe "the recent window we can see", not all time.+ */+export function computeScoutRollups(runs: SignalScoutRunSummary[]): Map<string, ScoutRollup> {+ const rollups = new Map<string, ScoutRollup>()+ for (const run of runs) {+ let rollup = rollups.get(run.skill_name)+ if (!rollup) {+ rollup = emptyRollup()+ rollups.set(run.skill_name, rollup)+ }+ rollup.runCount += 1+ const status = normalizeRunStatus(run.status)+ if (status === 'completed') {+ rollup.completedCount += 1+ }+ if (status === 'failed') {+ rollup.failedCount += 1+ }+ rollup.emittedCount += run.emitted_count ?? 0+ rollup.runs.push(run)+ const startedAt = run.started_at ? new Date(run.started_at).getTime() : 0+ const latestStartedAt = rollup.latestRun?.started_at ? new Date(rollup.latestRun.started_at).getTime() : -1+ if (startedAt > latestStartedAt) {+ rollup.latestRun = run+ }+ if (status === 'running' && !rollup.runningRun) {+ rollup.runningRun = run+ }+ }+ for (const rollup of rollups.values()) {+ rollup.runs.sort((a, b) => {+ const aStarted = a.started_at ? new Date(a.started_at).getTime() : 0+ const bStarted = b.started_at ? new Date(b.started_at).getTime() : 0+ return aStarted - bStarted+ })+ }+ return rollups+}++// ── Fleet summary ────────────────────────────────────────────────────────────++export interface FleetSummary {+ totalCount: number+ enabledCount: number+ runningCount: number+ emittedCount: number+ /** Completed / (completed + failed) over the window, or null when no finished runs. */+ successRate: number | null+ /** Share of runs in the window that emitted at least one signal, or null when no runs. */+ emitRate: number | null+}++export function computeFleetSummary(configs: SignalScoutConfig[], rollups: Map<string, ScoutRollup>): FleetSummary {+ let runningCount = 0+ let emittedCount = 0+ let completedCount = 0+ let failedCount = 0+ let runCount = 0+ let emittedRunCount = 0+ for (const rollup of rollups.values()) {+ if (rollup.runningRun) {+ runningCount += 1+ }+ emittedCount += rollup.emittedCount+ completedCount += rollup.completedCount+ failedCount += rollup.failedCount+ runCount += rollup.runCount+ for (const run of rollup.runs) {+ if ((run.emitted_count ?? 0) > 0) {+ emittedRunCount += 1+ }+ }+ }+ const finished = completedCount + failedCount+ return {+ totalCount: configs.length,+ enabledCount: configs.filter((config) => config.enabled).length,+ runningCount,+ emittedCount,+ successRate: finished > 0 ? completedCount / finished : null,+ emitRate: runCount > 0 ? emittedRunCount / runCount : null,+ }+}++// ── Run interval formatting ──────────────────────────────────────────────────++export interface RunIntervalOption {+ minutes: number+ label: string+}++export const RUN_INTERVAL_OPTIONS: RunIntervalOption[] = [+ { minutes: 30, label: 'Every 30 minutes' },+ { minutes: 60, label: 'Hourly' },+ { minutes: 120, label: 'Every 2 hours' },+ { minutes: 180, label: 'Every 3 hours' },+ { minutes: 360, label: 'Every 6 hours' },+ { minutes: 720, label: 'Every 12 hours' },+ { minutes: 1440, label: 'Daily' },+]++export function formatRunInterval(minutes: number): string {+ const preset = RUN_INTERVAL_OPTIONS.find((option) => option.minutes === minutes)+ if (preset) {+ return preset.label+ }+ if (minutes % 1440 === 0) {+ return `Every ${minutes / 1440} days`+ }+ if (minutes % 60 === 0) {+ return `Every ${minutes / 60} hours`+ }+ return `Every ${minutes} minutes`+}++/** Short form for row badges: "hourly", "every 3h". */+export function formatRunIntervalShort(minutes: number): string {+ if (minutes === 60) {+ return 'hourly'+ }+ if (minutes === 1440) {+ return 'daily'+ }+ if (minutes % 1440 === 0) {+ return `every ${minutes / 1440}d`+ }+ if (minutes % 60 === 0) {+ return `every ${minutes / 60}h`+ }+ return `every ${minutes}m`+}++export function sortConfigsForDisplay(configs: SignalScoutConfig[]): SignalScoutConfig[] {+ return [...configs].sort((a, b) => {+ if (a.enabled !== b.enabled) {+ return a.enabled ? -1 : 1+ }+ return prettifyScoutSkillName(a.skill_name).localeCompare(prettifyScoutSkillName(b.skill_name))+ })+}++// ── Templated chat-task prompts (ported from desktop scoutPrompts.ts) ─────────++export const SCOUT_AUTHOR_PROMPT = `I'd like to make a new scout for this PostHog project.++Use the authoring-signals-scouts skill from the PostHog MCP to guide creating a new signals scout.++First, take a quick scan of this PostHog project to ground your suggestions: skim its events, insights, dashboards, recently emitted signals, and the existing scout fleet so you understand what this product is and where automated monitoring would add value.++Then ask me what sort of scout I'd like to make, and offer a few concrete suggestions tailored to what you found (for example specific funnels, error or latency spikes, churn or activation signals, or revenue metrics worth watching) – and call out gaps the current fleet doesn't already cover. Once I pick a direction, walk me through authoring the scout end to end.++If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list to see the existing fleet) plus the read-data and insight tools to scan the project.`++export const SCOUT_FLEET_OVERVIEW_PROMPT = `How is my scout fleet performing?++Use the exploring-signals-scouts skill from the PostHog MCP to survey the signals scout fleet on this project and give me a high-level overview:++- The fleet: which scouts exist, enabled vs disabled, and their cadences+- Recent run health: success rate, failures and timeouts, anything stuck+- Output: which scouts emitted signals recently, emit rate, signal-to-noise+- Memory: notable scratchpad entries the fleet has learned+- Recommendations: anything misconfigured, noisy, or worth tuning++Lead with a short overall verdict, then per-scout notes only where something is notable. If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list, runs list, scratchpad search).`++export const SCOUT_RECENT_SIGNALS_PROMPT = `What signals have my scouts emitted recently?++Use the exploring-signals-scouts skill from the PostHog MCP to pull the most recent scout runs that emitted findings and walk me through the signals:++- What each signal says, in plain language+- Which scout emitted it, when, and its severity/confidence where available+- Whether it looks genuinely actionable or like noise++Group by scout, newest first. Close with a short note on overall signal quality and any scouts that look noisy or suspiciously silent. If the skill is unavailable, fall back to the signals-scout MCP tools directly (runs list with emitted filter, run emissions).`++/** Per-scout variant of the templated questions, scoped to one skill. */+export function buildScoutCheckinPrompt(skillName: string, displayName: string): string {+ return `How is my ${displayName} scout performing?++Use the exploring-signals-scouts skill from the PostHog MCP to dig into the \`${skillName}\` scout on this project:++- Its config: enabled, cadence, dry-run posture+- Recent run history: successes, failures, timeouts, durations+- Signals it emitted recently and whether they look genuinely actionable+- Scratchpad memory the fleet holds that relates to this scout+- Whether its scope, thresholds, and schedule look right – suggest tuning if not++Lead with a short verdict. If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list, runs list, run emissions, scratchpad search).`+}diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex c55108b8a4bd..2a059d88f711 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -929,7 +929,8 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.coupons(':campaign')]: [Scene.Coupons, 'coupons'],[urls.health()]: [Scene.Health, 'health'],[urls.inbox()]: [Scene.Inbox, 'inbox'],- [urls.inbox(':reportId')]: [Scene.Inbox, 'inbox'],+ [urls.inbox(':tab')]: [Scene.Inbox, 'inbox'],+ [urls.inboxReport(':tab', ':reportId')]: [Scene.Inbox, 'inbox'],[urls.pipelineStatus()]: [Scene.PipelineStatus, 'pipelineStatus'],[urls.sdkHealth()]: [Scene.SdkHealth, 'sdkHealth'],[urls.healthAlerts()]: [Scene.HealthAlerts, 'healthAlerts'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 34264c0a3bff..d2ff134494c6 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -10,6 +10,7 @@ import type { BillingSectionId } from './billing/types'import { DataPipelinesNewSceneKind } from './data-pipelines/DataPipelinesNewScene'import { OutputTab } from './data-warehouse/editor/outputPaneLogic'import type { HogFunctionSceneTab } from './hog-functions/HogFunctionScene'+import type { InboxTabKey } from './inbox/types'import type { ModelsSceneTab } from './models/modelsSceneLogic'import type { SettingId, SettingLevelId, SettingSectionId } from './settings/types'@@ -295,7 +296,9 @@ export const urls = {presetKinds && presetKinds.length > 0? `/health/alerts?preset_kinds=${encodeURIComponent(presetKinds.join(','))}`: '/health/alerts',- inbox: (reportId?: string): string => `/inbox${reportId ? `/${reportId}` : ''}`,+ // Inbox 2.0 tab-first routing: /inbox, /inbox/<tab>, /inbox/<tab>/<reportId>.+ inbox: (tab?: InboxTabKey | ':tab'): string => `/inbox${tab ? `/${tab}` : ''}`,+ inboxReport: (tab: InboxTabKey | ':tab', reportId: string | ':reportId'): string => `/inbox/${tab}/${reportId}`,webAnalyticsBotAnalytics: (): string => '/web/bots',webAnalyticsHealth: (): string => '/web/health',pipelineStatus: (): string => '/health/pipeline-status',diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 406ce7762979..002561674b79 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -672,6 +672,74 @@ class TestSignalReportListAPI(APIBaseTest):assert body["attr"] == "has_implementation_pr"assert body["code"] == "invalid_input"+ # --- actionability filter ---++ def test_filter_actionability_single_value(self):+ actionable = self._create_report(title="Actionable")+ self._actionability_artefact(actionable, actionability="immediately_actionable")+ not_actionable = self._create_report(title="Not actionable")+ self._actionability_artefact(not_actionable, actionability="not_actionable")++ response = self.client.get(self._list_url(actionability="not_actionable"))+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert {r["id"] for r in body["results"]} == {str(not_actionable.id)}+ assert body["count"] == 1++ def test_filter_actionability_multiple_values(self):+ immediate = self._create_report(title="Immediate")+ self._actionability_artefact(immediate, actionability="immediately_actionable")+ needs_input = self._create_report(title="Needs input")+ self._actionability_artefact(needs_input, actionability="requires_human_input")+ not_actionable = self._create_report(title="Not actionable")+ self._actionability_artefact(not_actionable, actionability="not_actionable")++ response = self.client.get(self._list_url(actionability="immediately_actionable,requires_human_input"))+ assert response.status_code == status.HTTP_200_OK+ ids = {r["id"] for r in response.json()["results"]}+ assert ids == {str(immediate.id), str(needs_input.id)}++ def test_filter_actionability_excludes_reports_without_judgment(self):+ # A report with no actionability_judgment artefact (annotation is NULL) is excluded.+ unjudged = self._create_report(title="Unjudged")+ not_actionable = self._create_report(title="Not actionable")+ self._actionability_artefact(not_actionable, actionability="not_actionable")++ response = self.client.get(self._list_url(actionability="not_actionable"))+ ids = {r["id"] for r in response.json()["results"]}+ assert str(unjudged.id) not in ids+ assert str(not_actionable.id) in ids++ def test_filter_actionability_count_via_limit_one(self):+ for i in range(3):+ report = self._create_report(title=f"NA report {i}")+ self._actionability_artefact(report, actionability="not_actionable")+ actionable = self._create_report(title="Actionable")+ self._actionability_artefact(actionable, actionability="immediately_actionable")++ response = self.client.get(self._list_url(actionability="not_actionable", limit=1))+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["count"] == 3+ assert len(body["results"]) == 1++ def test_filter_actionability_absent_returns_all(self):+ a = self._create_report(title="A")+ self._actionability_artefact(a, actionability="immediately_actionable")+ b = self._create_report(title="B")+ self._actionability_artefact(b, actionability="not_actionable")++ response = self.client.get(self._list_url())+ ids = {r["id"] for r in response.json()["results"]}+ assert {str(a.id), str(b.id)} <= ids++ def test_filter_actionability_invalid_value_returns_400(self):+ response = self.client.get(self._list_url(actionability="maybe_later"))+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ body = response.json()+ assert body["attr"] == "actionability"+ assert body["code"] == "invalid_input"+# --- source_products ---def test_source_products_defaults_to_empty_list(self):diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 6e842c90104c..6c9c36e306f5 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -63,6 +63,7 @@ from products.signals.backend.models import (SignalTeamConfig,SignalUserAutonomyConfig,)+from products.signals.backend.report_generation.research import ActionabilityChoicefrom products.signals.backend.report_generation.resolve_reviewers import (get_org_member_github_login_to_user_map,get_org_member_github_logins_by_user_uuid,@@ -398,6 +399,7 @@ class SignalReportViewSet(qs = self._apply_signal_report_implementation_pr_filter(qs)qs = self._apply_signal_report_suggested_reviewer_filter(qs)qs = self._annotate_latest_actionability_value(qs)+ qs = self._apply_signal_report_actionability_filter(qs)qs = self._annotate_signal_report_status_rank(qs)qs = self._annotate_signal_report_priority(qs)qs = self._apply_signal_report_priority_filter(qs)@@ -567,6 +569,34 @@ class SignalReportViewSet(return queryset.filter(priority_rank__in=values)+ def _apply_signal_report_actionability_filter(self, queryset):+ # Filters on the `latest_actionability_value` annotation (the actionability+ # choice from the latest actionability_judgment artefact), which must be+ # annotated first. Powers the inbox's actionability-keyed tabs: the Reports+ # tab passes the two actionable values, the staff-only Not-actionable tab+ # passes `not_actionable`. Reports without an actionability judgment+ # (annotation is NULL) are excluded when this filter is set. Absent or empty+ # param leaves the list unchanged; an unrecognized value is a 400.+ actionability_filter = self.request.query_params.get("actionability")+ if not actionability_filter:+ return queryset++ values = [a.strip() for a in actionability_filter.split(",") if a.strip()]+ if not values:+ return queryset++ allowed = {choice.value for choice in ActionabilityChoice}+ invalid = [v for v in values if v not in allowed]+ if invalid:+ raise serializers.ValidationError(+ {+ "actionability": f"Invalid actionability value(s): {', '.join(sorted(set(invalid)))}. "+ f"Allowed: {', '.join(sorted(allowed))}."+ }+ )++ return queryset.filter(latest_actionability_value__in=values)+def _annotate_signal_report_status_rank(self, queryset):# `ordering=status` uses semantic stage rank (annotation), not lexicographic `status` column order.# `status=ready` splits into two virtual stages (requires `latest_actionability_value`):diff --git a/products/tasks/frontend/types.ts b/products/tasks/frontend/types.tsindex 2dc702c5d8ab..50becbac7465 100644--- a/products/tasks/frontend/types.ts+++ b/products/tasks/frontend/types.ts@@ -6,6 +6,9 @@ export enum OriginProduct {USER_CREATED = 'user_created',SUPPORT_QUEUE = 'support_queue',SESSION_SUMMARIES = 'session_summaries',+ // Tasks kicked off from an Inbox SignalReport (Discuss / Create PR). Backend already+ // accepts `signal_report` + `signal_report_task_relationship` for this origin.+ SIGNAL_REPORT = 'signal_report',}export enum TaskRunStatus {